code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
* proto/v1beta1/grafeas.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* API version: version not set
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package grafeas
import (
"time"
)
// An instance of an analysis type that has been found on a resource.
type V1beta1Occurrence struct {
// Output only. The name of the occurrence in the form of `projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]`.
Name string `json:"name,omitempty"`
// Required. Immutable. The resource for which the occurrence applies.
Resource *V1beta1Resource `json:"resource,omitempty"`
// Required. Immutable. The analysis note associated with this occurrence, in the form of `projects/[PROVIDER_ID]/notes/[NOTE_ID]`. This field can be used as a filter in list requests.
NoteName string `json:"note_name,omitempty"`
// Output only. This explicitly denotes which of the occurrence details are specified. This field can be used as a filter in list requests.
Kind *V1beta1NoteKind `json:"kind,omitempty"`
// A description of actions that can be taken to remedy the note.
Remediation string `json:"remediation,omitempty"`
// Output only. The time this occurrence was created.
CreateTime time.Time `json:"create_time,omitempty"`
// Output only. The time this occurrence was last updated.
UpdateTime time.Time `json:"update_time,omitempty"`
// Describes a security vulnerability.
Vulnerability *V1beta1vulnerabilityDetails `json:"vulnerability,omitempty"`
// Describes a verifiable build.
Build *V1beta1buildDetails `json:"build,omitempty"`
// Describes how this resource derives from the basis in the associated note.
DerivedImage *V1beta1imageDetails `json:"derived_image,omitempty"`
// Describes the installation of a package on the linked resource.
Installation *V1beta1packageDetails `json:"installation,omitempty"`
// Describes the deployment of an artifact on a runtime.
Deployment *V1beta1deploymentDetails `json:"deployment,omitempty"`
// Describes when a resource was discovered.
Discovered *V1beta1discoveryDetails `json:"discovered,omitempty"`
// Describes an attestation of an artifact.
Attestation *V1beta1attestationDetails `json:"attestation,omitempty"`
}
| grafeas/client-go | 0.1.0/model_v1beta1_occurrence.go | GO | apache-2.0 | 2,287 |
---
date: 2016-09-13T09:00:00+00:00
title: Community support
type: page
layout: overview
aliases:
- /community/
---
Vamp Community Edition is open source and Apache 2.0 licensed. For details of the **Vamp Enterprise Edition** please check the [Vamp feature matrix](/product/enterprise-edition/), [start a free trial] (/ee-trial-signup/), or [contact us](mailto:[email protected]) to discuss your requirements, pricing and features.
## Community support
If you have a question about Vamp, please check the [Vamp documentation](/documentation/using-vamp/artifacts) first - we're always adding new resources, tutorials and examples.
* **Bug reports:** If you found a bug, please report it! [Create an issue on GitHub](https://github.com/magneticio/vamp/issues) and provide as much info as you can, specifically the version of Vamp you are running and the container driver you are using.
* **Gitter:** You can post questions directly to us on our [public Gitter channel](https://gitter.im/magneticio/vamp)
* **Twitter:** You can also follow us on Twitter: [@vamp_io](https://twitter.com/vamp_io)
| magneticio/vamp.io | content/community-support.md | Markdown | apache-2.0 | 1,094 |
#include "stdafx.h"
#include "InputReader.h"
#include "graph.h"
#include <iostream>
#include <string>
using namespace std;
InputReader::InputReader(const char* fileName, const char* stFileName)
{
in.open(fileName);
if(!in.is_open())
{
cout<<"Input file "<<fileName<<" doesn't exist!"<<endl;
exit(1);
}
stIn.open(stFileName);
if(!stIn.is_open())
{
cout<<"Input file "<<stFileName<<" doesn't exist!"<<endl;
in.close();
exit(1);
}
}
InputReader::~InputReader()
{
in.close();
stIn.close();
}
void InputReader::ReadFirstLine()
{
in>>strLine;
assert(strLine[0] == 'g');
in>>strLine;
assert(strLine[0] == '#');
in>> gId;
}
bool InputReader::ReadGraph(Graph &g)
{
ReadFirstLine();
if(gId == 0)
{
return false; /*ÒѾûÓÐͼ*/
}
g.nId = gId;
in>>strLine;
assert(strLine[0] == 's'); /*¶ÁÈ¡¶¥µãÊýºÍ±ßÊý*/
in>>g.nV>>g.nE;
assert(g.nV < MAX); /*·ÀÖ¹ÁÚ½Ó¾ØÕó´óС²»¹»ÓÃ*/
/*ÏÂÃæ¶ÁÈ¡±ßµÄÐÅÏ¢*/
int u,v; /*u,vÊÇÒ»Ìõ±ßµÄÁ½¸ö¶¥µã*/
for(int i = 1; i <= g.nE; i++)
{
in>>strLine;
assert(strLine[0] == 'e');
in>>u>>v; /*×¢ÒâÕâ¸ö²»ÄÜÓëÏÂÃæµÄдµ½Ò»Æð*/
in>>g.matrix[u][v].iC>>g.matrix[u][v].dP>>g.matrix[u][v].iLabel;
}
return true;
}
void InputReader::ReadSourceSink(int &s, int &t)
{
stIn>>s>>t;
} | yuanmouren1hao/KeyEdge_Mining_On_UncertainGraph | myFlow_caiwei/myFlow/InputReader.cpp | C++ | apache-2.0 | 1,474 |
<?php
namespace Illuminate\Database\Eloquent;
use Closure;
use BadMethodCallException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Pagination\Paginator;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Concerns\BuildsQueries;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
/**
* @mixin \Illuminate\Database\Query\Builder
*/
class Builder
{
use BuildsQueries, Concerns\QueriesRelationships;
/**
* The base query builder instance.
*
* @var \Illuminate\Database\Query\Builder
*/
protected $query;
/**
* The model being queried.
*
* @var \Illuminate\Database\Eloquent\Model
*/
protected $model;
/**
* The relationships that should be eager loaded.
*
* @var array
*/
protected $eagerLoad = [];
/**
* All of the globally registered builder macros.
*
* @var array
*/
protected static $macros = [];
/**
* All of the locally registered builder macros.
*
* @var array
*/
protected $localMacros = [];
/**
* A replacement for the typical delete function.
*
* @var \Closure
*/
protected $onDelete;
/**
* The methods that should be returned from query builder.
*
* @var array
*/
protected $passthru = [
'insert', 'insertGetId', 'getBindings', 'toSql',
'exists', 'doesntExist', 'count', 'min', 'max', 'avg', 'sum', 'getConnection',
];
/**
* Applied global scopes.
*
* @var array
*/
protected $scopes = [];
/**
* Removed global scopes.
*
* @var array
*/
protected $removedScopes = [];
/**
* Create a new Eloquent query builder instance.
*
* @param \Illuminate\Database\Query\Builder $query
* @return void
*/
public function __construct(QueryBuilder $query)
{
$this->query = $query;
}
/**
* Create and return an un-saved model instance.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public function make(array $attributes = [])
{
return $this->newModelInstance($attributes);
}
/**
* Register a new global scope.
*
* @param string $identifier
* @param \Illuminate\Database\Eloquent\Scope|\Closure $scope
* @return $this
*/
public function withGlobalScope($identifier, $scope)
{
$this->scopes[$identifier] = $scope;
if (method_exists($scope, 'extend')) {
$scope->extend($this);
}
return $this;
}
/**
* Remove a registered global scope.
*
* @param \Illuminate\Database\Eloquent\Scope|string $scope
* @return $this
*/
public function withoutGlobalScope($scope)
{
if (! is_string($scope)) {
$scope = get_class($scope);
}
unset($this->scopes[$scope]);
$this->removedScopes[] = $scope;
return $this;
}
/**
* Remove all or passed registered global scopes.
*
* @param array|null $scopes
* @return $this
*/
public function withoutGlobalScopes(array $scopes = null)
{
if (is_array($scopes)) {
foreach ($scopes as $scope) {
$this->withoutGlobalScope($scope);
}
} else {
$this->scopes = [];
}
return $this;
}
/**
* Get an array of global scopes that were removed from the query.
*
* @return array
*/
public function removedScopes()
{
return $this->removedScopes;
}
/**
* Add a where clause on the primary key to the query.
*
* @param mixed $id
* @return $this
*/
public function whereKey($id)
{
if (is_array($id) || $id instanceof Arrayable) {
$this->query->whereIn($this->model->getQualifiedKeyName(), $id);
return $this;
}
return $this->where($this->model->getQualifiedKeyName(), '=', $id);
}
/**
* Add a where clause on the primary key to the query.
*
* @param mixed $id
* @return $this
*/
public function whereKeyNot($id)
{
if (is_array($id) || $id instanceof Arrayable) {
$this->query->whereNotIn($this->model->getQualifiedKeyName(), $id);
return $this;
}
return $this->where($this->model->getQualifiedKeyName(), '!=', $id);
}
/**
* Add a basic where clause to the query.
*
* @param string|array|\Closure $column
* @param string $operator
* @param mixed $value
* @param string $boolean
* @return $this
*/
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
if ($column instanceof Closure) {
$column($query = $this->model->newModelQuery());
$this->query->addNestedWhereQuery($query->getQuery(), $boolean);
} else {
$this->query->where(...func_get_args());
}
return $this;
}
/**
* Add an "or where" clause to the query.
*
* @param \Closure|array|string $column
* @param string $operator
* @param mixed $value
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function orWhere($column, $operator = null, $value = null)
{
list($value, $operator) = $this->query->prepareValueAndOperator(
$value, $operator, func_num_args() == 2
);
return $this->where($column, $operator, $value, 'or');
}
/**
* Create a collection of models from plain arrays.
*
* @param array $items
* @return \Illuminate\Database\Eloquent\Collection
*/
public function hydrate(array $items)
{
$instance = $this->newModelInstance();
return $instance->newCollection(array_map(function ($item) use ($instance) {
return $instance->newFromBuilder($item);
}, $items));
}
/**
* Create a collection of models from a raw query.
*
* @param string $query
* @param array $bindings
* @return \Illuminate\Database\Eloquent\Collection
*/
public function fromQuery($query, $bindings = [])
{
return $this->hydrate(
$this->query->getConnection()->select($query, $bindings)
);
}
/**
* Find a model by its primary key.
*
* @param mixed $id
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null
*/
public function find($id, $columns = ['*'])
{
if (is_array($id) || $id instanceof Arrayable) {
return $this->findMany($id, $columns);
}
return $this->whereKey($id)->first($columns);
}
/**
* Find multiple models by their primary keys.
*
* @param \Illuminate\Contracts\Support\Arrayable|array $ids
* @param array $columns
* @return \Illuminate\Database\Eloquent\Collection
*/
public function findMany($ids, $columns = ['*'])
{
if (empty($ids)) {
return $this->model->newCollection();
}
return $this->whereKey($ids)->get($columns);
}
/**
* Find a model by its primary key or throw an exception.
*
* @param mixed $id
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function findOrFail($id, $columns = ['*'])
{
$result = $this->find($id, $columns);
if (is_array($id)) {
if (count($result) == count(array_unique($id))) {
return $result;
}
} elseif (! is_null($result)) {
return $result;
}
throw (new ModelNotFoundException)->setModel(
get_class($this->model), $id
);
}
/**
* Find a model by its primary key or return fresh model instance.
*
* @param mixed $id
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model
*/
public function findOrNew($id, $columns = ['*'])
{
if (! is_null($model = $this->find($id, $columns))) {
return $model;
}
return $this->newModelInstance();
}
/**
* Get the first record matching the attributes or instantiate it.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function firstOrNew(array $attributes, array $values = [])
{
if (! is_null($instance = $this->where($attributes)->first())) {
return $instance;
}
return $this->newModelInstance($attributes + $values);
}
/**
* Get the first record matching the attributes or create it.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function firstOrCreate(array $attributes, array $values = [])
{
if (! is_null($instance = $this->where($attributes)->first())) {
return $instance;
}
return tap($this->newModelInstance($attributes + $values), function ($instance) {
$instance->save();
});
}
/**
* Create or update a record matching the attributes, and fill it with values.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function updateOrCreate(array $attributes, array $values = [])
{
return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
$instance->fill($values)->save();
});
}
/**
* Execute the query and get the first result or throw an exception.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|static
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function firstOrFail($columns = ['*'])
{
if (! is_null($model = $this->first($columns))) {
return $model;
}
throw (new ModelNotFoundException)->setModel(get_class($this->model));
}
/**
* Execute the query and get the first result or call a callback.
*
* @param \Closure|array $columns
* @param \Closure|null $callback
* @return \Illuminate\Database\Eloquent\Model|static|mixed
*/
public function firstOr($columns = ['*'], Closure $callback = null)
{
if ($columns instanceof Closure) {
$callback = $columns;
$columns = ['*'];
}
if (! is_null($model = $this->first($columns))) {
return $model;
}
return call_user_func($callback);
}
/**
* Get a single column's value from the first result of a query.
*
* @param string $column
* @return mixed
*/
public function value($column)
{
if ($result = $this->first([$column])) {
return $result->{$column};
}
}
/**
* Execute the query as a "select" statement.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Collection|static[]
*/
public function get($columns = ['*'])
{
$builder = $this->applyScopes();
// If we actually found models we will also eager load any relationships that
// have been specified as needing to be eager loaded, which will solve the
// n+1 query issue for the developers to avoid running a lot of queries.
if (count($models = $builder->getModels($columns)) > 0) {
$models = $builder->eagerLoadRelations($models);
}
return $builder->getModel()->newCollection($models);
}
/**
* Get the hydrated models without eager loading.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model[]
*/
public function getModels($columns = ['*'])
{
return $this->model->hydrate(
$this->query->get($columns)->all()
)->all();
}
/**
* Eager load the relationships for the models.
*
* @param array $models
* @return array
*/
public function eagerLoadRelations(array $models)
{
foreach ($this->eagerLoad as $name => $constraints) {
// For nested eager loads we'll skip loading them here and they will be set as an
// eager load on the query to retrieve the relation so that they will be eager
// loaded on that query, because that is where they get hydrated as models.
if (strpos($name, '.') === false) {
$models = $this->eagerLoadRelation($models, $name, $constraints);
}
}
return $models;
}
/**
* Eagerly load the relationship on a set of models.
*
* @param array $models
* @param string $name
* @param \Closure $constraints
* @return array
*/
protected function eagerLoadRelation(array $models, $name, Closure $constraints)
{
// First we will "back up" the existing where conditions on the query so we can
// add our eager constraints. Then we will merge the wheres that were on the
// query back to it in order that any where conditions might be specified.
$relation = $this->getRelation($name);
$relation->addEagerConstraints($models);
$constraints($relation);
// Once we have the results, we just match those back up to their parent models
// using the relationship instance. Then we just return the finished arrays
// of models which have been eagerly hydrated and are readied for return.
return $relation->match(
$relation->initRelation($models, $name),
$relation->getEager(), $name
);
}
/**
* Get the relation instance for the given relation name.
*
* @param string $name
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function getRelation($name)
{
// We want to run a relationship query without any constrains so that we will
// not have to remove these where clauses manually which gets really hacky
// and error prone. We don't want constraints because we add eager ones.
$relation = Relation::noConstraints(function () use ($name) {
try {
return $this->getModel()->newInstance()->$name();
} catch (BadMethodCallException $e) {
throw RelationNotFoundException::make($this->getModel(), $name);
}
});
$nested = $this->relationsNestedUnder($name);
// If there are nested relationships set on the query, we will put those onto
// the query instances so that they can be handled after this relationship
// is loaded. In this way they will all trickle down as they are loaded.
if (count($nested) > 0) {
$relation->getQuery()->with($nested);
}
return $relation;
}
/**
* Get the deeply nested relations for a given top-level relation.
*
* @param string $relation
* @return array
*/
protected function relationsNestedUnder($relation)
{
$nested = [];
// We are basically looking for any relationships that are nested deeper than
// the given top-level relationship. We will just check for any relations
// that start with the given top relations and adds them to our arrays.
foreach ($this->eagerLoad as $name => $constraints) {
if ($this->isNestedUnder($relation, $name)) {
$nested[substr($name, strlen($relation.'.'))] = $constraints;
}
}
return $nested;
}
/**
* Determine if the relationship is nested.
*
* @param string $relation
* @param string $name
* @return bool
*/
protected function isNestedUnder($relation, $name)
{
return Str::contains($name, '.') && Str::startsWith($name, $relation.'.');
}
/**
* Get a generator for the given query.
*
* @return \Generator
*/
public function cursor()
{
foreach ($this->applyScopes()->query->cursor() as $record) {
yield $this->model->newFromBuilder($record);
}
}
/**
* Chunk the results of a query by comparing numeric IDs.
*
* @param int $count
* @param callable $callback
* @param string $column
* @param string|null $alias
* @return bool
*/
public function chunkById($count, callable $callback, $column = null, $alias = null)
{
$column = is_null($column) ? $this->getModel()->getKeyName() : $column;
$alias = is_null($alias) ? $column : $alias;
$lastId = 0;
do {
$clone = clone $this;
// We'll execute the query for the given page and get the results. If there are
// no results we can just break and return from here. When there are results
// we will call the callback with the current chunk of these results here.
$results = $clone->forPageAfterId($count, $lastId, $column)->get();
$countResults = $results->count();
if ($countResults == 0) {
break;
}
// On each chunk result set, we will pass them to the callback and then let the
// developer take care of everything within the callback, which allows us to
// keep the memory low for spinning through large result sets for working.
if ($callback($results) === false) {
return false;
}
$lastId = $results->last()->{$alias};
unset($results);
} while ($countResults == $count);
return true;
}
/**
* Add a generic "order by" clause if the query doesn't already have one.
*
* @return void
*/
protected function enforceOrderBy()
{
if (empty($this->query->orders) && empty($this->query->unionOrders)) {
$this->orderBy($this->model->getQualifiedKeyName(), 'asc');
}
}
/**
* Get an array with the values of a given column.
*
* @param string $column
* @param string|null $key
* @return \Illuminate\Support\Collection
*/
public function pluck($column, $key = null)
{
$results = $this->toBase()->pluck($column, $key);
// If the model has a mutator for the requested column, we will spin through
// the results and mutate the values so that the mutated version of these
// columns are returned as you would expect from these Eloquent models.
if (! $this->model->hasGetMutator($column) &&
! $this->model->hasCast($column) &&
! in_array($column, $this->model->getDates())) {
return $results;
}
return $results->map(function ($value) use ($column) {
return $this->model->newFromBuilder([$column => $value])->{$column};
});
}
/**
* Paginate the given query.
*
* @param int $perPage
* @param array $columns
* @param string $pageName
* @param int|null $page
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
*
* @throws \InvalidArgumentException
*/
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$perPage = $perPage ?: $this->model->getPerPage();
$results = ($total = $this->toBase()->getCountForPagination())
? $this->forPage($page, $perPage)->get($columns)
: $this->model->newCollection();
return $this->paginator($results, $total, $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
/**
* Paginate the given query into a simple paginator.
*
* @param int $perPage
* @param array $columns
* @param string $pageName
* @param int|null $page
* @return \Illuminate\Contracts\Pagination\Paginator
*/
public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$perPage = $perPage ?: $this->model->getPerPage();
// Next we will set the limit and offset for this query so that when we get the
// results we get the proper section of results. Then, we'll create the full
// paginator instances for these results with the given page and per page.
$this->skip(($page - 1) * $perPage)->take($perPage + 1);
return $this->simplePaginator($this->get($columns), $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
/**
* Save a new model and return the instance.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|$this
*/
public function create(array $attributes = [])
{
return tap($this->newModelInstance($attributes), function ($instance) {
$instance->save();
});
}
/**
* Save a new model and return the instance. Allow mass-assignment.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|$this
*/
public function forceCreate(array $attributes)
{
return $this->model->unguarded(function () use ($attributes) {
return $this->newModelInstance()->create($attributes);
});
}
/**
* Update a record in the database.
*
* @param array $values
* @return int
*/
public function update(array $values)
{
return $this->toBase()->update($this->addUpdatedAtColumn($values));
}
/**
* Increment a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
public function increment($column, $amount = 1, array $extra = [])
{
return $this->toBase()->increment(
$column, $amount, $this->addUpdatedAtColumn($extra)
);
}
/**
* Decrement a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
public function decrement($column, $amount = 1, array $extra = [])
{
return $this->toBase()->decrement(
$column, $amount, $this->addUpdatedAtColumn($extra)
);
}
/**
* Add the "updated at" column to an array of values.
*
* @param array $values
* @return array
*/
protected function addUpdatedAtColumn(array $values)
{
if (! $this->model->usesTimestamps()) {
return $values;
}
return Arr::add(
$values, $this->model->getUpdatedAtColumn(),
$this->model->freshTimestampString()
);
}
/**
* Delete a record from the database.
*
* @return mixed
*/
public function delete()
{
if (isset($this->onDelete)) {
return call_user_func($this->onDelete, $this);
}
return $this->toBase()->delete();
}
/**
* Run the default delete function on the builder.
*
* Since we do not apply scopes here, the row will actually be deleted.
*
* @return mixed
*/
public function forceDelete()
{
return $this->query->delete();
}
/**
* Register a replacement for the default delete function.
*
* @param \Closure $callback
* @return void
*/
public function onDelete(Closure $callback)
{
$this->onDelete = $callback;
}
/**
* Call the given local model scopes.
*
* @param array $scopes
* @return mixed
*/
public function scopes(array $scopes)
{
$builder = $this;
foreach ($scopes as $scope => $parameters) {
// If the scope key is an integer, then the scope was passed as the value and
// the parameter list is empty, so we will format the scope name and these
// parameters here. Then, we'll be ready to call the scope on the model.
if (is_int($scope)) {
list($scope, $parameters) = [$parameters, []];
}
// Next we'll pass the scope callback to the callScope method which will take
// care of grouping the "wheres" properly so the logical order doesn't get
// messed up when adding scopes. Then we'll return back out the builder.
$builder = $builder->callScope(
[$this->model, 'scope'.ucfirst($scope)],
(array) $parameters
);
}
return $builder;
}
/**
* Apply the scopes to the Eloquent builder instance and return it.
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function applyScopes()
{
if (! $this->scopes) {
return $this;
}
$builder = clone $this;
foreach ($this->scopes as $identifier => $scope) {
if (! isset($builder->scopes[$identifier])) {
continue;
}
$builder->callScope(function (Builder $builder) use ($scope) {
// If the scope is a Closure we will just go ahead and call the scope with the
// builder instance. The "callScope" method will properly group the clauses
// that are added to this query so "where" clauses maintain proper logic.
if ($scope instanceof Closure) {
$scope($builder);
}
// If the scope is a scope object, we will call the apply method on this scope
// passing in the builder and the model instance. After we run all of these
// scopes we will return back the builder instance to the outside caller.
if ($scope instanceof Scope) {
$scope->apply($builder, $this->getModel());
}
});
}
return $builder;
}
/**
* Apply the given scope on the current builder instance.
*
* @param callable $scope
* @param array $parameters
* @return mixed
*/
protected function callScope(callable $scope, $parameters = [])
{
array_unshift($parameters, $this);
$query = $this->getQuery();
// We will keep track of how many wheres are on the query before running the
// scope so that we can properly group the added scope constraints in the
// query as their own isolated nested where statement and avoid issues.
$originalWhereCount = is_null($query->wheres)
? 0 : count($query->wheres);
$result = $scope(...array_values($parameters)) ?? $this;
if (count((array) $query->wheres) > $originalWhereCount) {
$this->addNewWheresWithinGroup($query, $originalWhereCount);
}
return $result;
}
/**
* Nest where conditions by slicing them at the given where count.
*
* @param \Illuminate\Database\Query\Builder $query
* @param int $originalWhereCount
* @return void
*/
protected function addNewWheresWithinGroup(QueryBuilder $query, $originalWhereCount)
{
// Here, we totally remove all of the where clauses since we are going to
// rebuild them as nested queries by slicing the groups of wheres into
// their own sections. This is to prevent any confusing logic order.
$allWheres = $query->wheres;
$query->wheres = [];
$this->groupWhereSliceForScope(
$query, array_slice($allWheres, 0, $originalWhereCount)
);
$this->groupWhereSliceForScope(
$query, array_slice($allWheres, $originalWhereCount)
);
}
/**
* Slice where conditions at the given offset and add them to the query as a nested condition.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $whereSlice
* @return void
*/
protected function groupWhereSliceForScope(QueryBuilder $query, $whereSlice)
{
$whereBooleans = collect($whereSlice)->pluck('boolean');
// Here we'll check if the given subset of where clauses contains any "or"
// booleans and in this case create a nested where expression. That way
// we don't add any unnecessary nesting thus keeping the query clean.
if ($whereBooleans->contains('or')) {
$query->wheres[] = $this->createNestedWhere(
$whereSlice, $whereBooleans->first()
);
} else {
$query->wheres = array_merge($query->wheres, $whereSlice);
}
}
/**
* Create a where array with nested where conditions.
*
* @param array $whereSlice
* @param string $boolean
* @return array
*/
protected function createNestedWhere($whereSlice, $boolean = 'and')
{
$whereGroup = $this->getQuery()->forNestedWhere();
$whereGroup->wheres = $whereSlice;
return ['type' => 'Nested', 'query' => $whereGroup, 'boolean' => $boolean];
}
/**
* Set the relationships that should be eager loaded.
*
* @param mixed $relations
* @return $this
*/
public function with($relations)
{
$eagerLoad = $this->parseWithRelations(is_string($relations) ? func_get_args() : $relations);
$this->eagerLoad = array_merge($this->eagerLoad, $eagerLoad);
return $this;
}
/**
* Prevent the specified relations from being eager loaded.
*
* @param mixed $relations
* @return $this
*/
public function without($relations)
{
$this->eagerLoad = array_diff_key($this->eagerLoad, array_flip(
is_string($relations) ? func_get_args() : $relations
));
return $this;
}
/**
* Create a new instance of the model being queried.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public function newModelInstance($attributes = [])
{
return $this->model->newInstance($attributes)->setConnection(
$this->query->getConnection()->getName()
);
}
/**
* Parse a list of relations into individuals.
*
* @param array $relations
* @return array
*/
protected function parseWithRelations(array $relations)
{
$results = [];
foreach ($relations as $name => $constraints) {
// If the "relation" value is actually a numeric key, we can assume that no
// constraints have been specified for the eager load and we'll just put
// an empty Closure with the loader so that we can treat all the same.
if (is_numeric($name)) {
$name = $constraints;
list($name, $constraints) = Str::contains($name, ':')
? $this->createSelectWithConstraint($name)
: [$name, function () {
//
}];
}
// We need to separate out any nested includes. Which allows the developers
// to load deep relationships using "dots" without stating each level of
// the relationship with its own key in the array of eager load names.
$results = $this->addNestedWiths($name, $results);
$results[$name] = $constraints;
}
return $results;
}
/**
* Create a constraint to select the given columns for the relation.
*
* @param string $name
* @return array
*/
protected function createSelectWithConstraint($name)
{
return [explode(':', $name)[0], function ($query) use ($name) {
$query->select(explode(',', explode(':', $name)[1]));
}];
}
/**
* Parse the nested relationships in a relation.
*
* @param string $name
* @param array $results
* @return array
*/
protected function addNestedWiths($name, $results)
{
$progress = [];
// If the relation has already been set on the result array, we will not set it
// again, since that would override any constraints that were already placed
// on the relationships. We will only set the ones that are not specified.
foreach (explode('.', $name) as $segment) {
$progress[] = $segment;
if (! isset($results[$last = implode('.', $progress)])) {
$results[$last] = function () {
//
};
}
}
return $results;
}
/**
* Get the underlying query builder instance.
*
* @return \Illuminate\Database\Query\Builder
*/
public function getQuery()
{
return $this->query;
}
/**
* Set the underlying query builder instance.
*
* @param \Illuminate\Database\Query\Builder $query
* @return $this
*/
public function setQuery($query)
{
$this->query = $query;
return $this;
}
/**
* Get a base query builder instance.
*
* @return \Illuminate\Database\Query\Builder
*/
public function toBase()
{
return $this->applyScopes()->getQuery();
}
/**
* Get the relationships being eagerly loaded.
*
* @return array
*/
public function getEagerLoads()
{
return $this->eagerLoad;
}
/**
* Set the relationships being eagerly loaded.
*
* @param array $eagerLoad
* @return $this
*/
public function setEagerLoads(array $eagerLoad)
{
$this->eagerLoad = $eagerLoad;
return $this;
}
/**
* Get the model instance being queried.
*
* @return \Illuminate\Database\Eloquent\Model
*/
public function getModel()
{
return $this->model;
}
/**
* Set a model instance for the model being queried.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return $this
*/
public function setModel(Model $model)
{
$this->model = $model;
$this->query->from($model->getTable());
return $this;
}
/**
* Qualify the given column name by the model's table.
*
* @param string $column
* @return string
*/
public function qualifyColumn($column)
{
return $this->model->qualifyColumn($column);
}
/**
* Get the given macro by name.
*
* @param string $name
* @return \Closure
*/
public function getMacro($name)
{
return Arr::get($this->localMacros, $name);
}
/**
* Dynamically handle calls into the query instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if ($method === 'macro') {
$this->localMacros[$parameters[0]] = $parameters[1];
return;
}
if (isset($this->localMacros[$method])) {
array_unshift($parameters, $this);
return $this->localMacros[$method](...$parameters);
}
if (isset(static::$macros[$method])) {
if (static::$macros[$method] instanceof Closure) {
return call_user_func_array(static::$macros[$method]->bindTo($this, static::class), $parameters);
}
return call_user_func_array(static::$macros[$method], $parameters);
}
if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
return $this->callScope([$this->model, $scope], $parameters);
}
if (in_array($method, $this->passthru)) {
return $this->toBase()->{$method}(...$parameters);
}
$this->query->{$method}(...$parameters);
return $this;
}
/**
* Dynamically handle calls into the query instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public static function __callStatic($method, $parameters)
{
if ($method === 'macro') {
static::$macros[$parameters[0]] = $parameters[1];
return;
}
if (! isset(static::$macros[$method])) {
throw new BadMethodCallException("Method {$method} does not exist.");
}
if (static::$macros[$method] instanceof Closure) {
return call_user_func_array(Closure::bind(static::$macros[$method], null, static::class), $parameters);
}
return call_user_func_array(static::$macros[$method], $parameters);
}
/**
* Force a clone of the underlying query builder when cloning.
*
* @return void
*/
public function __clone()
{
$this->query = clone $this->query;
}
}
| drthomas21/WordPress_Tutorial | community_htdocs/vendor/illuminate/database/Eloquent/Builder.php | PHP | apache-2.0 | 37,905 |
package operationExtensibility.tests;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import operationExtensibility.*;
public class TestEvaluator {
private static Visitor<Integer> v;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
v = new Evaluator();
}
@Test
public void testLit() {
Lit x = new Lit();
x.setInfo(42);
assertEquals("evaluate a literal", 42, x.accept(v));
}
@Test
public void testAdd() {
Add x = new Add();
Lit y = new Lit();
y.setInfo(1);
x.setLeft(y);
y = new Lit();
y.setInfo(2);
x.setRight(y);
assertEquals("evaluate addition", 3, x.accept(v));
}
}
| egaburov/funstuff | Haskell/tytag/xproblem_src/samples/expressions/Java/operationExtensibility/tests/TestEvaluator.java | Java | apache-2.0 | 719 |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AspNetCoreTodo.Models;
namespace AspNetCoreTodo.Services
{
public interface ITodoItemService
{
Task<IEnumerable<TodoItem>> GetIncompleteItemsAsync(ApplicationUser user);
Task<bool> AddItemAsync(NewTodoItem newItem, ApplicationUser user);
Task<bool> MarkDoneAsync(Guid id, ApplicationUser user);
}
} | nqdien/littleaspnetcorebook | Services/ITodoItemService.cs | C# | apache-2.0 | 420 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">
<HTML>
<HEAD>
<meta name="generator" content="JDiff v1.0.9">
<!-- Generated by the JDiff Javadoc doclet -->
<!-- (http://www.jdiff.org) -->
<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator
</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="../stylesheet-jdiff.css" TITLE="Style">
</HEAD>
<BODY>
<!-- Start of nav bar -->
<TABLE summary="Navigation bar" BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<TABLE summary="Navigation bar" BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigSecondaryKeyComparator.html" target="_top"><FONT CLASS="NavBarFont1"><B><tt>pig 0.8.0-CDH3B4-SNAPSHOT</tt></B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="changes-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="pkg_org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_statistics.html"><FONT CLASS="NavBarFont1"><B>Statistics</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_help.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM><b>Generated by<br><a href="http://www.jdiff.org" class="staysblack" target="_top">JDiff</a></b></EM></TD>
</TR>
<TR>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigRecordReader.html"><B>PREV CLASS</B></A>
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit.html"><B>NEXT CLASS</B></A>
<A HREF="../changes.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:
<a href="#constructors">CONSTRUCTORS</a> |
<a href="#methods">METHODS</a> |
FIELDS
</FONT></TD>
</TR>
</TABLE>
<HR>
<!-- End of nav bar -->
<H2>
Class org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.<A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigSecondaryKeyComparator.html" target="_top"><tt>PigSecondaryKeyComparator</tt></A>
</H2>
<a NAME="constructors"></a>
<p>
<a NAME="Changed"></a>
<TABLE summary="Changed Constructors" BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD VALIGN="TOP" COLSPAN=3><FONT SIZE="+1"><B>Changed Constructors</B></FONT></TD>
</TR>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator.ctor_changed()"></A>
<nobr><A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigSecondaryKeyComparator.html#PigSecondaryKeyComparator()" target="_top"><tt>PigSecondaryKeyComparator</tt></A>(<code>void</code>) </nobr>
</TD>
<TD VALIGN="TOP" WIDTH="30%">
Change of visibility from public to protected.<br>
</TD>
<TD> </TD>
</TR>
</TABLE>
<a NAME="methods"></a>
<p>
<a NAME="Removed"></a>
<TABLE summary="Removed Methods" BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD VALIGN="TOP" COLSPAN=2><FONT SIZE="+1"><B>Removed Methods</B></FONT></TD>
</TR>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator.compare_removed(java.lang.Object, java.lang.Object, int, int, boolean[], boolean)"></A>
<nobr><code>int</code> <A HREF="http://hadoop.apache.org/pig/docs/r0.7.0/api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigSecondaryKeyComparator.html#compare(java.lang.Object, java.lang.Object, int, int, boolean[], boolean)" target="_top"><tt>compare</tt></A>(<code>Object,</nobr> Object<nobr>,</nobr> int<nobr>,</nobr> int<nobr>,</nobr> boolean[]<nobr>,</nobr> boolean<nobr><nobr></code>)</nobr>
</TD>
<TD> </TD>
</TR>
</TABLE>
<a NAME="fields"></a>
<HR>
<!-- Start of nav bar -->
<TABLE summary="Navigation bar" BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<TABLE summary="Navigation bar" BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigSecondaryKeyComparator.html" target="_top"><FONT CLASS="NavBarFont1"><B><tt>pig 0.8.0-CDH3B4-SNAPSHOT</tt></B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="changes-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="pkg_org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_statistics.html"><FONT CLASS="NavBarFont1"><B>Statistics</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_help.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3></TD>
</TR>
<TR>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigRecordReader.html"><B>PREV CLASS</B></A>
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit.html"><B>NEXT CLASS</B></A>
<A HREF="../changes.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
<TD BGCOLOR="0xFFFFFF" CLASS="NavBarCell3"></TD>
</TR>
</TABLE>
<HR>
<!-- End of nav bar -->
</BODY>
</HTML>
| simplegeo/hadoop-pig | docs/jdiff/changes/org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator.html | HTML | apache-2.0 | 7,373 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.ivy.core.pack;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ivy.util.FileUtil;
/**
* Packaging which handle OSGi bundles with inner packed jar
*/
public class OsgiBundlePacking extends ZipPacking {
private static final String[] NAMES = {"bundle"};
@Override
public String[] getNames() {
return NAMES;
}
@Override
protected void writeFile(InputStream zip, File f) throws IOException {
// XXX maybe we should only unpack file listed by the 'Bundle-ClassPath' MANIFEST header ?
if (f.getName().endsWith(".jar.pack.gz")) {
zip = FileUtil.unwrapPack200(zip);
f = new File(f.getParentFile(), f.getName().substring(0, f.getName().length() - 8));
}
super.writeFile(zip, f);
}
}
| jaikiran/ant-ivy | src/java/org/apache/ivy/core/pack/OsgiBundlePacking.java | Java | apache-2.0 | 1,656 |
package fr.openwide.core.wicket.more.markup.html.feedback;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
public abstract class AbstractFeedbackPanel extends Panel {
private static final long serialVersionUID = 8440891357292721078L;
private static final int[] ERROR_MESSAGE_LEVELS = {
FeedbackMessage.FATAL,
FeedbackMessage.ERROR,
FeedbackMessage.WARNING,
FeedbackMessage.SUCCESS,
FeedbackMessage.INFO,
FeedbackMessage.DEBUG,
FeedbackMessage.UNDEFINED
};
private static final String[] ERROR_MESSAGE_LEVEL_NAMES = {
"FATAL",
"ERROR",
"WARNING",
"SUCCESS",
"INFO",
"DEBUG",
"UNDEFINED"
};
private List<FeedbackPanel> feedbackPanels = new ArrayList<FeedbackPanel>();
public AbstractFeedbackPanel(String id, MarkupContainer container) {
super(id);
int i = 0;
for(int level: ERROR_MESSAGE_LEVELS) {
FeedbackPanel f = getFeedbackPanel(ERROR_MESSAGE_LEVEL_NAMES[i] + "feedbackPanel", level, container);
feedbackPanels.add(f);
add(f);
i++;
}
}
public abstract FeedbackPanel getFeedbackPanel(String id, int level, MarkupContainer container);
}
| openwide-java/owsi-core-parent | owsi-core/owsi-core-components/owsi-core-component-wicket-more/src/main/java/fr/openwide/core/wicket/more/markup/html/feedback/AbstractFeedbackPanel.java | Java | apache-2.0 | 1,314 |
<h3 class="page-header">Розв'язок</h3>
<div class="task-solution-top"></div>
<div class="task-solution-bg">
<p>
В першу чергу, обчислимо ОДЗ:
</p>
<div class="formula-block">
\begin{equation*}
\begin{aligned}
\mbox{ОДЗ}:\;&x-3\geq 0;\\
&x\geq 3;
\end{aligned}
\end{equation*}
</div>
<p>
Перший доданок є завжди додатним, бо це квадратний корінь. Другий доданок,
також завжди додатний, бо це модуль. Очевидно, що сума двох додатних чисел
рівна нулю лише тоді, коли ці числа рівні нулю. Тобто, ми маємо таку систему:
</p>
<div class="formula-block">
\begin{equation*}
\begin{aligned}
&\left\{
\begin{aligned}
&x-3=0,\\
&x^2-9=0;
\end{aligned}
\right.\\
&\left\{
\begin{aligned}
&x=3,\\
&x=\pm 3;
\end{aligned}
\right.
\end{aligned}
\end{equation*}
</div>
<p>
Значення $x=-3$ не задовольняє ОДЗ, тому відповідь буде:
</p>
<div class="formula-block">
$$x=3.$$
</div>
</div>
| SMHFandA/Tex.TasksSolutions | site/uk/chapter_5/group_1/solutions/solution_5_1_8.html | HTML | apache-2.0 | 1,399 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There area two reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router what URI segments to use if those provided
| in the URL cannot be matched to a valid route.
|
*/
$route['default_controller'] = "reader";
$route['sitemap.xml'] = "reader/sitemap";
$route['rss.xml'] = "reader/feeds";
$route['atom.xml'] = "reader/feeds/atom";
$route['admin'] = "admin/series";
$route['admin/series/series/(:any)'] = "admin/series/serie/$1";
$route['account'] = "account/index/profile";
$route['account/profile'] = "account/index/profile";
$route['account/teams'] = "account/index/teams";
$route['account/leave_team/(:any)'] = "account/index/leave_team/$1";
$route['account/request/(:any)'] = "account/index/request/$1";
$route['account/leave_leadership/(:any)'] = "account/index/leave_leadership/$1";
$route['reader/list'] = 'reader/lista';
$route['reader/list/(:num)'] = 'reader/lista/$1';
$route['admin/members/members'] = 'admin/members/membersa';
// added for compatibility on upgrade 0.8.1 -> 0.8.2 on 30/09/2011
$route['admin/upgrade'] = 'admin/system/upgrade';
$route['404_override'] = '';
/* End of file routes.php */
/* Location: ./application/config/routes.php */ | woxxy/FoOlSlide | application/config/routes.php | PHP | apache-2.0 | 2,388 |
/*
* EditorMouseMenu.java
*
* Created on March 21, 2007, 10:34 AM; Updated May 29, 2007
*
* Copyright 2007 Grotto Networking
*/
package Samples.MouseMenu;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.layout.StaticLayout;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPopupMenu;
/**
* Illustrates the use of custom edge and vertex classes in a graph editing application.
* Demonstrates a new graph mouse plugin for bringing up popup menus for vertices and
* edges.
* @author Dr. Greg M. Bernstein
*/
public class EditorMouseMenu {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Editing and Mouse Menu Demo");
SparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> g =
new SparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge>();
// Layout<V, E>, VisualizationViewer<V,E>
// Map<GraphElements.MyVertex,Point2D> vertexLocations = new HashMap<GraphElements.MyVertex, Point2D>();
Layout<GraphElements.MyVertex, GraphElements.MyEdge> layout = new StaticLayout(g);
layout.setSize(new Dimension(300,300));
VisualizationViewer<GraphElements.MyVertex,GraphElements.MyEdge> vv =
new VisualizationViewer<GraphElements.MyVertex,GraphElements.MyEdge>(layout);
vv.setPreferredSize(new Dimension(350,350));
// Show vertex and edge labels
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
// Create a graph mouse and add it to the visualization viewer
EditingModalGraphMouse gm = new EditingModalGraphMouse(vv.getRenderContext(),
GraphElements.MyVertexFactory.getInstance(),
GraphElements.MyEdgeFactory.getInstance());
// Set some defaults for the Edges...
GraphElements.MyEdgeFactory.setDefaultCapacity(192.0);
GraphElements.MyEdgeFactory.setDefaultWeight(5.0);
// Trying out our new popup menu mouse plugin...
PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin();
// Add some popup menus for the edges and vertices to our mouse plugin.
JPopupMenu edgeMenu = new MyMouseMenus.EdgeMenu(frame);
JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu();
myPlugin.setEdgePopup(edgeMenu);
myPlugin.setVertexPopup(vertexMenu);
gm.remove(gm.getPopupEditingPlugin()); // Removes the existing popup editing plugin
gm.add(myPlugin); // Add our new plugin to the mouse
vv.setGraphMouse(gm);
//JFrame frame = new JFrame("Editing and Mouse Menu Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
// Let's add a menu for changing mouse modes
JMenuBar menuBar = new JMenuBar();
JMenu modeMenu = gm.getModeMenu();
modeMenu.setText("Mouse Mode");
modeMenu.setIcon(null); // I'm using this in a main menu
modeMenu.setPreferredSize(new Dimension(80,20)); // Change the size so I can see the text
menuBar.add(modeMenu);
frame.setJMenuBar(menuBar);
gm.setMode(ModalGraphMouse.Mode.EDITING); // Start off in editing mode
frame.pack();
frame.setVisible(true);
}
}
| ksotala/BayesGame | BayesGame/src/Samples/MouseMenu/EditorMouseMenu.java | Java | apache-2.0 | 3,984 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2016 Eugene Frolov <[email protected]>
#
# All Rights Reserved.
#
# 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.
import random
import uuid as pyuuid
import mock
import requests
from six.moves.urllib import parse
from restalchemy.common import utils
from restalchemy.storage import exceptions
from restalchemy.storage.sql import engines
from restalchemy.tests.functional.restapi.ra_based.microservice import (
storable_models as models)
from restalchemy.tests.functional.restapi.ra_based.microservice import consts
from restalchemy.tests.functional.restapi.ra_based.microservice import service
from restalchemy.tests.unit import base
TEMPL_SERVICE_ENDPOINT = utils.lastslash("http://127.0.0.1:%s/")
TEMPL_ROOT_COLLECTION_ENDPOINT = TEMPL_SERVICE_ENDPOINT
TEMPL_V1_COLLECTION_ENDPOINT = utils.lastslash(parse.urljoin(
TEMPL_SERVICE_ENDPOINT, 'v1'))
TEMPL_VMS_COLLECTION_ENDPOINT = utils.lastslash(parse.urljoin(
TEMPL_V1_COLLECTION_ENDPOINT, 'vms'))
TEMPL_VM_RESOURCE_ENDPOINT = parse.urljoin(TEMPL_VMS_COLLECTION_ENDPOINT, '%s')
TEMPL_POWERON_ACTION_ENDPOINT = parse.urljoin(
utils.lastslash(TEMPL_VM_RESOURCE_ENDPOINT),
'actions/poweron/invoke')
TEMPL_PORTS_COLLECTION_ENDPOINT = utils.lastslash(parse.urljoin(
utils.lastslash(TEMPL_VM_RESOURCE_ENDPOINT), 'ports'))
TEMPL_PORT_RESOURCE_ENDPOINT = parse.urljoin(TEMPL_PORTS_COLLECTION_ENDPOINT,
'%s')
class BaseResourceTestCase(base.BaseTestCase):
def get_endpoint(self, template, *args):
return template % ((self.service_port,) + tuple(args))
def setUp(self):
super(BaseResourceTestCase, self).setUp()
engines.engine_factory.configure_factory(consts.DATABASE_URI)
engine = engines.engine_factory.get_engine()
self.session = engine.get_session()
self.session.execute("""CREATE TABLE IF NOT EXISTS vms (
uuid CHAR(36) NOT NULL,
state VARCHAR(10) NOT NULL,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (uuid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;""", None)
self.service_port = random.choice(range(2100, 2200))
url = parse.urlparse(self.get_endpoint(TEMPL_SERVICE_ENDPOINT))
self._service = service.RESTService(bind_host=url.hostname,
bind_port=url.port)
self._service.start()
def tearDown(self):
super(BaseResourceTestCase, self).tearDown()
self._service.stop()
self.session.execute("DROP TABLE IF EXISTS vms;", None)
class TestRootResourceTestCase(BaseResourceTestCase):
def test_get_versions_list(self):
response = requests.get(self.get_endpoint(
TEMPL_ROOT_COLLECTION_ENDPOINT))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), ["v1"])
class TestVersionsResourceTestCase(BaseResourceTestCase):
def test_get_resources_list(self):
response = requests.get(
self.get_endpoint(TEMPL_V1_COLLECTION_ENDPOINT))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), ["vms"])
class TestVMResourceTestCase(BaseResourceTestCase):
def _insert_vm_to_db(self, uuid, name, state):
vm = models.VM(uuid=uuid, name=name, state=state)
vm.save()
def _vm_exists_in_db(self, uuid):
try:
models.VM.objects.get_one(filters={'uuid': uuid})
return True
except exceptions.RecordNotFound:
return False
@mock.patch('uuid.uuid4')
def test_create_vm_resource_successful(self, uuid4_mock):
RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
uuid4_mock.return_value = RESOURCE_ID
vm_request_body = {
"name": "test"
}
vm_response_body = {
"uuid": str(RESOURCE_ID),
"name": "test",
"state": "off"
}
LOCATION = self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT, RESOURCE_ID)
response = requests.post(self.get_endpoint(
TEMPL_VMS_COLLECTION_ENDPOINT), json=vm_request_body)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.headers['location'], LOCATION)
self.assertEqual(response.json(), vm_response_body)
def test_get_vm_resource_by_uuid_successful(self):
RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
self._insert_vm_to_db(uuid=RESOURCE_ID, name="test", state="off")
vm_response_body = {
"uuid": str(RESOURCE_ID),
"name": "test",
"state": "off"
}
VM_RES_ENDPOINT = self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
RESOURCE_ID)
response = requests.get(VM_RES_ENDPOINT)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), vm_response_body)
def test_update_vm_resource_successful(self):
RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
self._insert_vm_to_db(uuid=RESOURCE_ID, name="old", state="off")
vm_request_body = {
"name": "new"
}
vm_response_body = {
"uuid": str(RESOURCE_ID),
"name": "new",
"state": "off"
}
VM_RES_ENDPOINT = self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
RESOURCE_ID)
response = requests.put(VM_RES_ENDPOINT, json=vm_request_body)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), vm_response_body)
def test_delete_vm_resource_successful(self):
RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
self._insert_vm_to_db(uuid=RESOURCE_ID, name="test", state="off")
VM_RES_ENDPOINT = self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
RESOURCE_ID)
response = requests.delete(VM_RES_ENDPOINT)
self.assertEqual(response.status_code, 204)
self.assertFalse(self._vm_exists_in_db(RESOURCE_ID))
def test_process_vm_action_successful(self):
RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
self._insert_vm_to_db(uuid=RESOURCE_ID, name="test", state="off")
vm_response_body = {
"uuid": str(RESOURCE_ID),
"name": "test",
"state": "on"
}
POWERON_ACT_ENDPOINT = self.get_endpoint(TEMPL_POWERON_ACTION_ENDPOINT,
RESOURCE_ID)
response = requests.post(POWERON_ACT_ENDPOINT)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), vm_response_body)
def test_get_collection_vms_successful(self):
RESOURCE_ID1 = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
RESOURCE_ID2 = pyuuid.UUID("00000000-0000-0000-0000-000000000002")
self._insert_vm_to_db(uuid=RESOURCE_ID1, name="test1", state="off")
self._insert_vm_to_db(uuid=RESOURCE_ID2, name="test2", state="on")
vm_response_body = [{
"uuid": str(RESOURCE_ID1),
"name": "test1",
"state": "off"
}, {
"uuid": str(RESOURCE_ID2),
"name": "test2",
"state": "on"
}]
response = requests.get(self.get_endpoint(
TEMPL_VMS_COLLECTION_ENDPOINT))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), vm_response_body)
class TestNestedResourceTestCase(BaseResourceTestCase):
def setUp(self):
super(TestNestedResourceTestCase, self).setUp()
self.session.execute("""CREATE TABLE IF NOT EXISTS ports (
uuid CHAR(36) NOT NULL,
mac CHAR(17) NOT NULL,
vm CHAR(36) NOT NULL,
PRIMARY KEY (uuid),
CONSTRAINT FOREIGN KEY ix_vms_uuid (vm) REFERENCES vms (uuid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;""", None)
self.vm1 = models.VM(
uuid=pyuuid.UUID("00000000-0000-0000-0000-000000000001"),
name="vm1",
state="on")
self.vm1.save(session=self.session)
self.vm2 = models.VM(
uuid=pyuuid.UUID("00000000-0000-0000-0000-000000000002"),
name="vm2",
state="off")
self.vm2.save(session=self.session)
self.session.commit()
def tearDown(self):
self.session.execute("DROP TABLE IF EXISTS ports;", None)
super(TestNestedResourceTestCase, self).tearDown()
@mock.patch('uuid.uuid4')
def test_create_nested_resource_successful(self, uuid4_mock):
VM_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
PORT_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000003")
uuid4_mock.return_value = PORT_RESOURCE_ID
port_request_body = {
"mac": "00:00:00:00:00:03"
}
port_response_body = {
"uuid": str(PORT_RESOURCE_ID),
"mac": "00:00:00:00:00:03",
"vm": parse.urlparse(
self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
VM_RESOURCE_ID)).path
}
LOCATION = self.get_endpoint(TEMPL_PORT_RESOURCE_ENDPOINT,
VM_RESOURCE_ID,
PORT_RESOURCE_ID)
response = requests.post(
self.get_endpoint(TEMPL_PORTS_COLLECTION_ENDPOINT, VM_RESOURCE_ID),
json=port_request_body)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.headers['location'], LOCATION)
self.assertEqual(response.json(), port_response_body)
def test_get_nested_resource_successful(self):
VM_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
PORT_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000003")
port = models.Port(uuid=PORT_RESOURCE_ID,
mac="00:00:00:00:00:03",
vm=self.vm1)
port.save(session=self.session)
self.session.commit()
port_response_body = {
"uuid": str(PORT_RESOURCE_ID),
"mac": "00:00:00:00:00:03",
"vm": parse.urlparse(
self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
VM_RESOURCE_ID)).path
}
response = requests.get(
self.get_endpoint(TEMPL_PORT_RESOURCE_ENDPOINT,
VM_RESOURCE_ID,
PORT_RESOURCE_ID))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), port_response_body)
def test_get_ports_collection_successful(self):
VM_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
PORT1_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000003")
PORT2_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000004")
PORT3_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000005")
port1 = models.Port(uuid=PORT1_RESOURCE_ID,
mac="00:00:00:00:00:03",
vm=self.vm1)
port1.save(session=self.session)
port2 = models.Port(uuid=PORT2_RESOURCE_ID,
mac="00:00:00:00:00:04",
vm=self.vm1)
port2.save(session=self.session)
port3 = models.Port(uuid=PORT3_RESOURCE_ID,
mac="00:00:00:00:00:05",
vm=self.vm2)
port3.save(session=self.session)
ports_response_body = [{
"uuid": str(PORT1_RESOURCE_ID),
"mac": "00:00:00:00:00:03",
"vm": parse.urlparse(
self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
VM_RESOURCE_ID)).path
}, {
"uuid": str(PORT2_RESOURCE_ID),
"mac": "00:00:00:00:00:04",
"vm": parse.urlparse(
self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
VM_RESOURCE_ID)).path
}]
self.session.commit()
response = requests.get(
self.get_endpoint(TEMPL_PORTS_COLLECTION_ENDPOINT, VM_RESOURCE_ID))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), ports_response_body)
def test_delete_nested_resource_successful(self):
VM_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
PORT_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000003")
port = models.Port(uuid=PORT_RESOURCE_ID,
mac="00:00:00:00:00:03",
vm=self.vm1)
port.save(session=self.session)
self.session.commit()
response = requests.delete(
self.get_endpoint(TEMPL_PORT_RESOURCE_ENDPOINT,
VM_RESOURCE_ID,
PORT_RESOURCE_ID))
self.assertEqual(response.status_code, 204)
self.assertRaises(exceptions.RecordNotFound,
models.Port.objects.get_one,
filters={'uuid': PORT_RESOURCE_ID})
| phantomii/restalchemy | restalchemy/tests/functional/restapi/ra_based/test_resources.py | Python | apache-2.0 | 13,940 |
package ru.job4j.max;
/**
*Класс помогает узнать, какое из двух чисел больше.
*@author ifedorenko
*@since 14.08.2017
*@version 1
*/
public class Max {
/**
*Возвращает большее число из двух.
*@param first содержит первое число
*@param second содержит второе число
*@return Большее из двух
*/
public int max(int first, int second) {
return first > second ? first : second;
}
/**
*Возвращает большее число из трех.
*@param first содержит первое число
*@param second содержит второе число
*@param third содержит третье число
*@return Большее из трех
*/
public int max(int first, int second, int third) {
return max(first, max(second, third));
}
} | fr3anthe/ifedorenko | 1.1-Base/src/main/java/ru/job4j/max/Max.java | Java | apache-2.0 | 887 |
/**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*/
package com.cloudera.flume.reporter.server;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.thrift.*;
import org.apache.thrift.meta_data.*;
import org.apache.thrift.protocol.*;
public class FlumeReport implements TBase<FlumeReport._Fields>, java.io.Serializable, Cloneable {
private static final TStruct STRUCT_DESC = new TStruct("FlumeReport");
private static final TField STRING_METRICS_FIELD_DESC = new TField("stringMetrics", TType.MAP, (short)3);
private static final TField LONG_METRICS_FIELD_DESC = new TField("longMetrics", TType.MAP, (short)4);
private static final TField DOUBLE_METRICS_FIELD_DESC = new TField("doubleMetrics", TType.MAP, (short)5);
public Map<String,String> stringMetrics;
public Map<String,Long> longMetrics;
public Map<String,Double> doubleMetrics;
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements TFieldIdEnum {
STRING_METRICS((short)3, "stringMetrics"),
LONG_METRICS((short)4, "longMetrics"),
DOUBLE_METRICS((short)5, "doubleMetrics");
private static final Map<Integer, _Fields> byId = new HashMap<Integer, _Fields>();
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byId.put((int)field._thriftId, field);
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
return byId.get(fieldId);
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, FieldMetaData> metaDataMap = Collections.unmodifiableMap(new EnumMap<_Fields, FieldMetaData>(_Fields.class) {{
put(_Fields.STRING_METRICS, new FieldMetaData("stringMetrics", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.STRING),
new FieldValueMetaData(TType.STRING))));
put(_Fields.LONG_METRICS, new FieldMetaData("longMetrics", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.STRING),
new FieldValueMetaData(TType.I64))));
put(_Fields.DOUBLE_METRICS, new FieldMetaData("doubleMetrics", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.STRING),
new FieldValueMetaData(TType.DOUBLE))));
}});
static {
FieldMetaData.addStructMetaDataMap(FlumeReport.class, metaDataMap);
}
public FlumeReport() {
}
public FlumeReport(
Map<String,String> stringMetrics,
Map<String,Long> longMetrics,
Map<String,Double> doubleMetrics)
{
this();
this.stringMetrics = stringMetrics;
this.longMetrics = longMetrics;
this.doubleMetrics = doubleMetrics;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public FlumeReport(FlumeReport other) {
if (other.isSetStringMetrics()) {
Map<String,String> __this__stringMetrics = new HashMap<String,String>();
for (Map.Entry<String, String> other_element : other.stringMetrics.entrySet()) {
String other_element_key = other_element.getKey();
String other_element_value = other_element.getValue();
String __this__stringMetrics_copy_key = other_element_key;
String __this__stringMetrics_copy_value = other_element_value;
__this__stringMetrics.put(__this__stringMetrics_copy_key, __this__stringMetrics_copy_value);
}
this.stringMetrics = __this__stringMetrics;
}
if (other.isSetLongMetrics()) {
Map<String,Long> __this__longMetrics = new HashMap<String,Long>();
for (Map.Entry<String, Long> other_element : other.longMetrics.entrySet()) {
String other_element_key = other_element.getKey();
Long other_element_value = other_element.getValue();
String __this__longMetrics_copy_key = other_element_key;
Long __this__longMetrics_copy_value = other_element_value;
__this__longMetrics.put(__this__longMetrics_copy_key, __this__longMetrics_copy_value);
}
this.longMetrics = __this__longMetrics;
}
if (other.isSetDoubleMetrics()) {
Map<String,Double> __this__doubleMetrics = new HashMap<String,Double>();
for (Map.Entry<String, Double> other_element : other.doubleMetrics.entrySet()) {
String other_element_key = other_element.getKey();
Double other_element_value = other_element.getValue();
String __this__doubleMetrics_copy_key = other_element_key;
Double __this__doubleMetrics_copy_value = other_element_value;
__this__doubleMetrics.put(__this__doubleMetrics_copy_key, __this__doubleMetrics_copy_value);
}
this.doubleMetrics = __this__doubleMetrics;
}
}
public FlumeReport deepCopy() {
return new FlumeReport(this);
}
@Deprecated
public FlumeReport clone() {
return new FlumeReport(this);
}
public int getStringMetricsSize() {
return (this.stringMetrics == null) ? 0 : this.stringMetrics.size();
}
public void putToStringMetrics(String key, String val) {
if (this.stringMetrics == null) {
this.stringMetrics = new HashMap<String,String>();
}
this.stringMetrics.put(key, val);
}
public Map<String,String> getStringMetrics() {
return this.stringMetrics;
}
public FlumeReport setStringMetrics(Map<String,String> stringMetrics) {
this.stringMetrics = stringMetrics;
return this;
}
public void unsetStringMetrics() {
this.stringMetrics = null;
}
/** Returns true if field stringMetrics is set (has been asigned a value) and false otherwise */
public boolean isSetStringMetrics() {
return this.stringMetrics != null;
}
public void setStringMetricsIsSet(boolean value) {
if (!value) {
this.stringMetrics = null;
}
}
public int getLongMetricsSize() {
return (this.longMetrics == null) ? 0 : this.longMetrics.size();
}
public void putToLongMetrics(String key, long val) {
if (this.longMetrics == null) {
this.longMetrics = new HashMap<String,Long>();
}
this.longMetrics.put(key, val);
}
public Map<String,Long> getLongMetrics() {
return this.longMetrics;
}
public FlumeReport setLongMetrics(Map<String,Long> longMetrics) {
this.longMetrics = longMetrics;
return this;
}
public void unsetLongMetrics() {
this.longMetrics = null;
}
/** Returns true if field longMetrics is set (has been asigned a value) and false otherwise */
public boolean isSetLongMetrics() {
return this.longMetrics != null;
}
public void setLongMetricsIsSet(boolean value) {
if (!value) {
this.longMetrics = null;
}
}
public int getDoubleMetricsSize() {
return (this.doubleMetrics == null) ? 0 : this.doubleMetrics.size();
}
public void putToDoubleMetrics(String key, double val) {
if (this.doubleMetrics == null) {
this.doubleMetrics = new HashMap<String,Double>();
}
this.doubleMetrics.put(key, val);
}
public Map<String,Double> getDoubleMetrics() {
return this.doubleMetrics;
}
public FlumeReport setDoubleMetrics(Map<String,Double> doubleMetrics) {
this.doubleMetrics = doubleMetrics;
return this;
}
public void unsetDoubleMetrics() {
this.doubleMetrics = null;
}
/** Returns true if field doubleMetrics is set (has been asigned a value) and false otherwise */
public boolean isSetDoubleMetrics() {
return this.doubleMetrics != null;
}
public void setDoubleMetricsIsSet(boolean value) {
if (!value) {
this.doubleMetrics = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case STRING_METRICS:
if (value == null) {
unsetStringMetrics();
} else {
setStringMetrics((Map<String,String>)value);
}
break;
case LONG_METRICS:
if (value == null) {
unsetLongMetrics();
} else {
setLongMetrics((Map<String,Long>)value);
}
break;
case DOUBLE_METRICS:
if (value == null) {
unsetDoubleMetrics();
} else {
setDoubleMetrics((Map<String,Double>)value);
}
break;
}
}
public void setFieldValue(int fieldID, Object value) {
setFieldValue(_Fields.findByThriftIdOrThrow(fieldID), value);
}
public Object getFieldValue(_Fields field) {
switch (field) {
case STRING_METRICS:
return getStringMetrics();
case LONG_METRICS:
return getLongMetrics();
case DOUBLE_METRICS:
return getDoubleMetrics();
}
throw new IllegalStateException();
}
public Object getFieldValue(int fieldId) {
return getFieldValue(_Fields.findByThriftIdOrThrow(fieldId));
}
/** Returns true if field corresponding to fieldID is set (has been asigned a value) and false otherwise */
public boolean isSet(_Fields field) {
switch (field) {
case STRING_METRICS:
return isSetStringMetrics();
case LONG_METRICS:
return isSetLongMetrics();
case DOUBLE_METRICS:
return isSetDoubleMetrics();
}
throw new IllegalStateException();
}
public boolean isSet(int fieldID) {
return isSet(_Fields.findByThriftIdOrThrow(fieldID));
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof FlumeReport)
return this.equals((FlumeReport)that);
return false;
}
public boolean equals(FlumeReport that) {
if (that == null)
return false;
boolean this_present_stringMetrics = true && this.isSetStringMetrics();
boolean that_present_stringMetrics = true && that.isSetStringMetrics();
if (this_present_stringMetrics || that_present_stringMetrics) {
if (!(this_present_stringMetrics && that_present_stringMetrics))
return false;
if (!this.stringMetrics.equals(that.stringMetrics))
return false;
}
boolean this_present_longMetrics = true && this.isSetLongMetrics();
boolean that_present_longMetrics = true && that.isSetLongMetrics();
if (this_present_longMetrics || that_present_longMetrics) {
if (!(this_present_longMetrics && that_present_longMetrics))
return false;
if (!this.longMetrics.equals(that.longMetrics))
return false;
}
boolean this_present_doubleMetrics = true && this.isSetDoubleMetrics();
boolean that_present_doubleMetrics = true && that.isSetDoubleMetrics();
if (this_present_doubleMetrics || that_present_doubleMetrics) {
if (!(this_present_doubleMetrics && that_present_doubleMetrics))
return false;
if (!this.doubleMetrics.equals(that.doubleMetrics))
return false;
}
return true;
}
@Override
public int hashCode() {
return 0;
}
public void read(TProtocol iprot) throws TException {
TField field;
iprot.readStructBegin();
while (true)
{
field = iprot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
_Fields fieldId = _Fields.findByThriftId(field.id);
if (fieldId == null) {
TProtocolUtil.skip(iprot, field.type);
} else {
switch (fieldId) {
case STRING_METRICS:
if (field.type == TType.MAP) {
{
TMap _map0 = iprot.readMapBegin();
this.stringMetrics = new HashMap<String,String>(2*_map0.size);
for (int _i1 = 0; _i1 < _map0.size; ++_i1)
{
String _key2;
String _val3;
_key2 = iprot.readString();
_val3 = iprot.readString();
this.stringMetrics.put(_key2, _val3);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, field.type);
}
break;
case LONG_METRICS:
if (field.type == TType.MAP) {
{
TMap _map4 = iprot.readMapBegin();
this.longMetrics = new HashMap<String,Long>(2*_map4.size);
for (int _i5 = 0; _i5 < _map4.size; ++_i5)
{
String _key6;
long _val7;
_key6 = iprot.readString();
_val7 = iprot.readI64();
this.longMetrics.put(_key6, _val7);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, field.type);
}
break;
case DOUBLE_METRICS:
if (field.type == TType.MAP) {
{
TMap _map8 = iprot.readMapBegin();
this.doubleMetrics = new HashMap<String,Double>(2*_map8.size);
for (int _i9 = 0; _i9 < _map8.size; ++_i9)
{
String _key10;
double _val11;
_key10 = iprot.readString();
_val11 = iprot.readDouble();
this.doubleMetrics.put(_key10, _val11);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, field.type);
}
break;
}
iprot.readFieldEnd();
}
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
validate();
}
public void write(TProtocol oprot) throws TException {
validate();
oprot.writeStructBegin(STRUCT_DESC);
if (this.stringMetrics != null) {
oprot.writeFieldBegin(STRING_METRICS_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.STRING, TType.STRING, this.stringMetrics.size()));
for (Map.Entry<String, String> _iter12 : this.stringMetrics.entrySet())
{
oprot.writeString(_iter12.getKey());
oprot.writeString(_iter12.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.longMetrics != null) {
oprot.writeFieldBegin(LONG_METRICS_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.STRING, TType.I64, this.longMetrics.size()));
for (Map.Entry<String, Long> _iter13 : this.longMetrics.entrySet())
{
oprot.writeString(_iter13.getKey());
oprot.writeI64(_iter13.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.doubleMetrics != null) {
oprot.writeFieldBegin(DOUBLE_METRICS_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.STRING, TType.DOUBLE, this.doubleMetrics.size()));
for (Map.Entry<String, Double> _iter14 : this.doubleMetrics.entrySet())
{
oprot.writeString(_iter14.getKey());
oprot.writeDouble(_iter14.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("FlumeReport(");
boolean first = true;
sb.append("stringMetrics:");
if (this.stringMetrics == null) {
sb.append("null");
} else {
sb.append(this.stringMetrics);
}
first = false;
if (!first) sb.append(", ");
sb.append("longMetrics:");
if (this.longMetrics == null) {
sb.append("null");
} else {
sb.append(this.longMetrics);
}
first = false;
if (!first) sb.append(", ");
sb.append("doubleMetrics:");
if (this.doubleMetrics == null) {
sb.append("null");
} else {
sb.append(this.doubleMetrics);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws TException {
// check for required fields
}
}
| hammer/flume | src/gen-java/com/cloudera/flume/reporter/server/FlumeReport.java | Java | apache-2.0 | 17,245 |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.
*/
package org.kuali.rice.kew.docsearch.dao.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.uif.RemotableAttributeField;
import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.document.search.DocumentSearchCriteria;
import org.kuali.rice.kew.api.document.search.DocumentSearchResults;
import org.kuali.rice.kew.docsearch.dao.DocumentSearchDAO;
import org.kuali.rice.kew.impl.document.search.DocumentSearchGenerator;
import org.kuali.rice.kew.util.PerformanceLogger;
import org.kuali.rice.krad.util.KRADConstants;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
/**
* Spring JdbcTemplate implementation of DocumentSearchDAO
*
* @author Kuali Rice Team ([email protected])
*
*/
public class DocumentSearchDAOJdbcImpl implements DocumentSearchDAO {
public static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DocumentSearchDAOJdbcImpl.class);
private static final int DEFAULT_FETCH_MORE_ITERATION_LIMIT = 10;
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = new TransactionAwareDataSourceProxy(dataSource);
}
@Override
public DocumentSearchResults.Builder findDocuments(final DocumentSearchGenerator documentSearchGenerator, final DocumentSearchCriteria criteria, final boolean criteriaModified, final List<RemotableAttributeField> searchFields) {
final int maxResultCap = getMaxResultCap(criteria);
try {
final JdbcTemplate template = new JdbcTemplate(dataSource);
return template.execute(new ConnectionCallback<DocumentSearchResults.Builder>() {
@Override
public DocumentSearchResults.Builder doInConnection(final Connection con) throws SQLException {
final Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
try {
final int fetchIterationLimit = getFetchMoreIterationLimit();
final int fetchLimit = fetchIterationLimit * maxResultCap;
statement.setFetchSize(maxResultCap + 1);
statement.setMaxRows(fetchLimit + 1);
PerformanceLogger perfLog = new PerformanceLogger();
String sql = documentSearchGenerator.generateSearchSql(criteria, searchFields);
perfLog.log("Time to generate search sql from documentSearchGenerator class: " + documentSearchGenerator
.getClass().getName(), true);
LOG.info("Executing document search with statement max rows: " + statement.getMaxRows());
LOG.info("Executing document search with statement fetch size: " + statement.getFetchSize());
perfLog = new PerformanceLogger();
final ResultSet rs = statement.executeQuery(sql);
try {
perfLog.log("Time to execute doc search database query.", true);
final Statement searchAttributeStatement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
try {
return documentSearchGenerator.processResultSet(criteria, criteriaModified, searchAttributeStatement, rs, maxResultCap, fetchLimit);
} finally {
try {
searchAttributeStatement.close();
} catch (SQLException e) {
LOG.warn("Could not close search attribute statement.");
}
}
} finally {
try {
rs.close();
} catch (SQLException e) {
LOG.warn("Could not close result set.");
}
}
} finally {
try {
statement.close();
} catch (SQLException e) {
LOG.warn("Could not close statement.");
}
}
}
});
} catch (DataAccessException dae) {
String errorMsg = "DataAccessException: " + dae.getMessage();
LOG.error("getList() " + errorMsg, dae);
throw new RuntimeException(errorMsg, dae);
} catch (Exception e) {
String errorMsg = "LookupException: " + e.getMessage();
LOG.error("getList() " + errorMsg, e);
throw new RuntimeException(errorMsg, e);
}
}
/**
* Returns the maximum number of results that should be returned from the document search.
*
* @param criteria the criteria in which to check for a max results value
* @return the maximum number of results that should be returned from a document search
*/
public int getMaxResultCap(DocumentSearchCriteria criteria) {
int systemLimit = KewApiConstants.DOCUMENT_LOOKUP_DEFAULT_RESULT_CAP;
String resultCapValue = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.DOCUMENT_SEARCH_DETAIL_TYPE, KewApiConstants.DOC_SEARCH_RESULT_CAP);
if (StringUtils.isNotBlank(resultCapValue)) {
try {
int configuredLimit = Integer.parseInt(resultCapValue);
if (configuredLimit <= 0) {
LOG.warn(KewApiConstants.DOC_SEARCH_RESULT_CAP + " was less than or equal to zero. Please use a positive integer.");
} else {
systemLimit = configuredLimit;
}
} catch (NumberFormatException e) {
LOG.warn(KewApiConstants.DOC_SEARCH_RESULT_CAP + " is not a valid number. Value was " + resultCapValue + ". Using default: " + KewApiConstants.DOCUMENT_LOOKUP_DEFAULT_RESULT_CAP);
}
}
int maxResults = systemLimit;
if (criteria.getMaxResults() != null) {
int criteriaLimit = criteria.getMaxResults().intValue();
if (criteriaLimit > systemLimit) {
LOG.warn("Result set cap of " + criteriaLimit + " is greater than system value of " + systemLimit);
} else {
if (criteriaLimit < 0) {
LOG.warn("Criteria results limit was less than zero.");
criteriaLimit = 0;
}
maxResults = criteriaLimit;
}
}
return maxResults;
}
public int getFetchMoreIterationLimit() {
int fetchMoreLimit = DEFAULT_FETCH_MORE_ITERATION_LIMIT;
String fetchMoreLimitValue = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.DOCUMENT_SEARCH_DETAIL_TYPE, KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT);
if (!StringUtils.isBlank(fetchMoreLimitValue)) {
try {
fetchMoreLimit = Integer.parseInt(fetchMoreLimitValue);
if (fetchMoreLimit < 0) {
LOG.warn(KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT + " was less than zero. Please use a value greater than or equal to zero.");
fetchMoreLimit = DEFAULT_FETCH_MORE_ITERATION_LIMIT;
}
} catch (NumberFormatException e) {
LOG.warn(KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT + " is not a valid number. Value was " + fetchMoreLimitValue);
}
}
return fetchMoreLimit;
}
}
| ua-eas/ua-rice-2.1.9 | impl/src/main/java/org/kuali/rice/kew/docsearch/dao/impl/DocumentSearchDAOJdbcImpl.java | Java | apache-2.0 | 8,999 |
/*
* Copyright 2016 Alexander Severgin
*
* 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.
*/
package eu.alpinweiss.filegen.util.generator.impl;
import eu.alpinweiss.filegen.model.FieldDefinition;
import eu.alpinweiss.filegen.model.FieldType;
import eu.alpinweiss.filegen.util.wrapper.AbstractDataWrapper;
import eu.alpinweiss.filegen.util.generator.FieldGenerator;
import eu.alpinweiss.filegen.util.vault.ParameterVault;
import eu.alpinweiss.filegen.util.vault.ValueVault;
import org.apache.commons.lang.StringUtils;
import java.util.concurrent.ThreadLocalRandom;
/**
* {@link AutoNumberGenerator}.
*
* @author Aleksandrs.Severgins | <a href="http://alpinweiss.eu">SIA Alpinweiss</a>
*/
public class AutoNumberGenerator implements FieldGenerator {
private final FieldDefinition fieldDefinition;
private int startNum;
public AutoNumberGenerator(FieldDefinition fieldDefinition) {
this.fieldDefinition = fieldDefinition;
final String pattern = this.fieldDefinition.getPattern();
if (!pattern.isEmpty()) {
startNum = Integer.parseInt(pattern);
}
}
@Override
public void generate(final ParameterVault parameterVault, ThreadLocalRandom randomGenerator, ValueVault valueVault) {
valueVault.storeValue(new IntegerDataWrapper() {
@Override
public Double getNumberValue() {
int value = startNum + (parameterVault.rowCount() * parameterVault.dataPartNumber()) + parameterVault.iterationNumber();
return new Double(value);
}
});
}
private class IntegerDataWrapper extends AbstractDataWrapper {
@Override
public FieldType getFieldType() {
return FieldType.INTEGER;
}
}
}
| alpinweiss/filegen | src/main/java/eu/alpinweiss/filegen/util/generator/impl/AutoNumberGenerator.java | Java | apache-2.0 | 2,280 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.analytics.mapper;
import org.elasticsearch.index.mapper.FieldTypeTestCase;
import org.elasticsearch.index.mapper.MappedFieldType;
public class HistogramFieldTypeTests extends FieldTypeTestCase<MappedFieldType> {
@Override
protected MappedFieldType createDefaultFieldType() {
return new HistogramFieldMapper.HistogramFieldType();
}
}
| uschindler/elasticsearch | x-pack/plugin/analytics/src/test/java/org/elasticsearch/xpack/analytics/mapper/HistogramFieldTypeTests.java | Java | apache-2.0 | 632 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.gml.provider;
import java.util.Collection;
import java.util.List;
import net.opengis.gml.FeatureStyleType;
import net.opengis.gml.GmlFactory;
import net.opengis.gml.GmlPackage;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.FeatureMapUtil;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link net.opengis.gml.FeatureStyleType} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class FeatureStyleTypeItemProvider
extends AbstractGMLTypeItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FeatureStyleTypeItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addFeatureConstraintPropertyDescriptor(object);
addBaseTypePropertyDescriptor(object);
addFeatureTypePropertyDescriptor(object);
addQueryGrammarPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Feature Constraint feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFeatureConstraintPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_featureConstraint_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_featureConstraint_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_FeatureConstraint(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Base Type feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addBaseTypePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_baseType_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_baseType_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_BaseType(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Feature Type feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFeatureTypePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_featureType_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_featureType_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_FeatureType(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Query Grammar feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addQueryGrammarPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_queryGrammar_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_queryGrammar_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_QueryGrammar(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_GeometryStyle());
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_TopologyStyle());
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_LabelStyle());
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns FeatureStyleType.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/FeatureStyleType"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((FeatureStyleType)object).getId();
return label == null || label.length() == 0 ?
getString("_UI_FeatureStyleType_type") :
getString("_UI_FeatureStyleType_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(FeatureStyleType.class)) {
case GmlPackage.FEATURE_STYLE_TYPE__FEATURE_CONSTRAINT:
case GmlPackage.FEATURE_STYLE_TYPE__BASE_TYPE:
case GmlPackage.FEATURE_STYLE_TYPE__FEATURE_TYPE:
case GmlPackage.FEATURE_STYLE_TYPE__QUERY_GRAMMAR:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
case GmlPackage.FEATURE_STYLE_TYPE__GEOMETRY_STYLE:
case GmlPackage.FEATURE_STYLE_TYPE__TOPOLOGY_STYLE:
case GmlPackage.FEATURE_STYLE_TYPE__LABEL_STYLE:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_GeometryStyle(),
GmlFactory.eINSTANCE.createGeometryStylePropertyType()));
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_TopologyStyle(),
GmlFactory.eINSTANCE.createTopologyStylePropertyType()));
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_LabelStyle(),
GmlFactory.eINSTANCE.createLabelStylePropertyType()));
}
/**
* This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getCreateChildText(Object owner, Object feature, Object child, Collection<?> selection) {
Object childFeature = feature;
Object childObject = child;
if (childFeature instanceof EStructuralFeature && FeatureMapUtil.isFeatureMap((EStructuralFeature)childFeature)) {
FeatureMap.Entry entry = (FeatureMap.Entry)childObject;
childFeature = entry.getEStructuralFeature();
childObject = entry.getValue();
}
boolean qualify =
childFeature == GmlPackage.eINSTANCE.getAbstractGMLType_Name() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_CoordinateOperationName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_CsName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_DatumName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_EllipsoidName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_GroupName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_MeridianName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_MethodName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_ParameterName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_SrsName();
if (qualify) {
return getString
("_UI_CreateChild_text2",
new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) });
}
return super.getCreateChildText(owner, feature, child, selection);
}
}
| markus1978/citygml4emf | de.hub.citygml.emf.ecore.edit/src/net/opengis/gml/provider/FeatureStyleTypeItemProvider.java | Java | apache-2.0 | 10,661 |
\section{ESRI}
\index{ESRI}
\index{Environmental Systems Research Institute}
Environmental Systems Research Institute (ESRI) offers geospatial related data
services and process online through its proprietary API. Features of the ESRI
platform include access to basemaps, geocoding, demographic data, a dynamic
world atlas, and multiple data sets in a open-data resource~\cite{hid-sp18-505-ESRI2018}.
| cloudmesh/book | cloud-technologies/incomming/tex/abstract-esri-data-services.tex | TeX | apache-2.0 | 402 |
# Copyright 2021 Google LLC
#
# 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.
"""GKE nodes service account permissions for logging.
The service account used by GKE nodes should have the logging.logWriter
role, otherwise ingestion of logs won't work.
"""
from gcpdiag import lint, models
from gcpdiag.queries import gke, iam
ROLE = 'roles/logging.logWriter'
def prefetch_rule(context: models.Context):
# Make sure that we have the IAM policy in cache.
project_ids = {c.project_id for c in gke.get_clusters(context).values()}
for pid in project_ids:
iam.get_project_policy(pid)
def run_rule(context: models.Context, report: lint.LintReportRuleInterface):
# Find all clusters with logging enabled.
clusters = gke.get_clusters(context)
iam_policy = iam.get_project_policy(context.project_id)
if not clusters:
report.add_skipped(None, 'no clusters found')
for _, c in sorted(clusters.items()):
if not c.has_logging_enabled():
report.add_skipped(c, 'logging disabled')
else:
# Verify service-account permissions for every nodepool.
for np in c.nodepools:
sa = np.service_account
if not iam.is_service_account_enabled(sa, context.project_id):
report.add_failed(np, f'service account disabled or deleted: {sa}')
elif not iam_policy.has_role_permissions(f'serviceAccount:{sa}', ROLE):
report.add_failed(np, f'service account: {sa}\nmissing role: {ROLE}')
else:
report.add_ok(np)
| GoogleCloudPlatform/gcpdiag | gcpdiag/lint/gke/err_2021_001_logging_perm.py | Python | apache-2.0 | 1,986 |
package sarama
// ApiVersionsRequest ...
type ApiVersionsRequest struct{}
func (a *ApiVersionsRequest) encode(pe packetEncoder) error {
return nil
}
func (a *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) {
return nil
}
func (a *ApiVersionsRequest) key() int16 {
return 18
}
func (a *ApiVersionsRequest) version() int16 {
return 0
}
func (a *ApiVersionsRequest) headerVersion() int16 {
return 1
}
func (a *ApiVersionsRequest) requiredVersion() KafkaVersion {
return V0_10_0_0
}
| trivago/gollum | vendor/github.com/Shopify/sarama/api_versions_request.go | GO | apache-2.0 | 516 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
package com.amazonaws.services.neptune.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/neptune-2014-10-31/RemoveRoleFromDBCluster" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RemoveRoleFromDBClusterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof RemoveRoleFromDBClusterResult == false)
return false;
RemoveRoleFromDBClusterResult other = (RemoveRoleFromDBClusterResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public RemoveRoleFromDBClusterResult clone() {
try {
return (RemoveRoleFromDBClusterResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-neptune/src/main/java/com/amazonaws/services/neptune/model/RemoveRoleFromDBClusterResult.java | Java | apache-2.0 | 2,392 |
<!DOCTYPE html>
<html>
<head>
<title>Startup Cookie Manager</title>
</head>
<body>
<h3 title="example.com will preserve example.com, and *.example.com cookies.">Cookie whitelist (include subdomains)</h3>
<p title="example.com will preserve example.com, and *.example.com cookies.">
<textarea id="subdomain-whitelist" rows="4" cols="50"></textarea>
</p>
<h3 title="example.com will preserve example.com, .example.com, and www.example.com cookies.">Cookie whitelist (root domains only)</h3>
<p title="example.com will preserve example.com, .example.com, and www.example.com cookies.">
<textarea id="domain-only-whitelist" rows="4" cols="50"></textarea>
</p>
<h3 title="Additional tasks to perform whenever cookies and site data are cleared.">Additional settings</h3>
<p>
<input type="checkbox" id="cache_option">
<label for="cache_option">Clear cache.</label>
</p>
<p>
<input type="checkbox" id="history_option">
<label for="history_option">Clear history.</label>
</p>
<p align="center" style="color:grey;">
Developed by <a href="https://aaronhorler.com">Aaron Horler</a> (aghorler) | <a href="https://github.com/aghorler/Startup-Cookie-Destroyer">GitHub source</a>
</p>
<script src="/js/options.js"></script>
</body>
</html>
| aghorler/Startup-Cookie-Destroyer | html/options.html | HTML | apache-2.0 | 1,380 |
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>minus</title>
<link href="../../../images/logo-icon.svg" rel="icon" type="image/svg">
<script>var pathToRoot = "../../../";</script>
<script type="text/javascript" src="../../../scripts/sourceset_dependencies.js" async="async"></script>
<link href="../../../styles/style.css" rel="Stylesheet">
<link href="../../../styles/logo-styles.css" rel="Stylesheet">
<link href="../../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../../styles/main.css" rel="Stylesheet">
<script type="text/javascript" src="../../../scripts/clipboard.js" async="async"></script>
<script type="text/javascript" src="../../../scripts/navigation-loader.js" async="async"></script>
<script type="text/javascript" src="../../../scripts/platform-content-handler.js" async="async"></script>
<script type="text/javascript" src="../../../scripts/main.js" async="async"></script>
</head>
<body>
<div id="container">
<div id="leftColumn">
<div id="logo"></div>
<div id="paneSearch"></div>
<div id="sideMenu"></div>
</div>
<div id="main">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<script type="text/javascript" src="../../../scripts/pages.js"></script>
<script type="text/javascript" src="../../../scripts/main.js"></script>
<div class="main-content" id="content" pageIds="org.hexworks.zircon.api.data/Rect/minus/#org.hexworks.zircon.api.data.Rect/PointingToDeclaration//-828656838">
<div class="navigation-wrapper" id="navigation-wrapper">
<div class="breadcrumbs"><a href="../../index.html">zircon.core</a>/<a href="../index.html">org.hexworks.zircon.api.data</a>/<a href="index.html">Rect</a>/<a href="minus.html">minus</a></div>
<div class="pull-right d-flex">
<div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div>
<div id="searchBar"></div>
</div>
</div>
<div class="cover ">
<h1 class="cover"><span>minus</span></h1>
</div>
<div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">abstract operator fun <a href="minus.html">minus</a>(rect: <a href="index.html">Rect</a>): <a href="index.html">Rect</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
</div>
<h2 class="">Sources</h2>
<div class="table" data-togglable="Sources"><a data-name="%5Borg.hexworks.zircon.api.data%2FRect%2Fminus%2F%23org.hexworks.zircon.api.data.Rect%2FPointingToDeclaration%2F%5D%2FSource%2F-828656838" anchor-label="https://github.com/Hexworks/zircon/tree/master/zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/data/Rect.kt#L50" id="%5Borg.hexworks.zircon.api.data%2FRect%2Fminus%2F%23org.hexworks.zircon.api.data.Rect%2FPointingToDeclaration%2F%5D%2FSource%2F-828656838" data-filterable-set=":zircon.core:dokkaHtml/commonMain"></a>
<div class="table-row" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain">
<div class="main-subrow keyValue ">
<div class=""><span class="inline-flex"><a href="https://github.com/Hexworks/zircon/tree/master/zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/data/Rect.kt#L50">(source)</a><span class="anchor-wrapper"><span class="anchor-icon" pointing-to="%5Borg.hexworks.zircon.api.data%2FRect%2Fminus%2F%23org.hexworks.zircon.api.data.Rect%2FPointingToDeclaration%2F%5D%2FSource%2F-828656838"></span>
<div class="copy-popup-wrapper "><span class="copy-popup-icon"></span><span>Link copied to clipboard</span></div>
</span></span></div>
<div></div>
</div>
</div>
</div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body>
</html>
| Hexworks/zircon | docs/2020.2.0-RELEASE-KOTLIN/zircon.core/zircon.core/org.hexworks.zircon.api.data/-rect/minus.html | HTML | apache-2.0 | 4,930 |
using System.Collections.Generic;
namespace Microsoft.Xna.Framework.Graphics
{
internal partial class DXConstantBufferData
{
public string Name { get; private set; }
public int Size { get; private set; }
public List<int> ParameterIndex { get; private set; }
public List<int> ParameterOffset { get; private set; }
public List<DXEffectObject.d3dx_parameter> Parameters { get; private set; }
public bool SameAs(DXConstantBufferData other)
{
// If the names of the constant buffers don't
// match then consider them different right off
// the bat... even if their parameters are the same.
if (Name != other.Name)
return false;
// Do we have the same count of parameters and size?
if ( Size != other.Size ||
Parameters.Count != other.Parameters.Count)
return false;
// Compare the parameters themselves.
for (var i = 0; i < Parameters.Count; i++)
{
var p1 = Parameters[i];
var p2 = other.Parameters[i];
// Check the importaint bits.
if ( p1.name != p2.name ||
p1.rows != p2.rows ||
p1.columns != p2.columns ||
p1.class_ != p2.class_ ||
p1.type != p2.type ||
p1.bufferOffset != p2.bufferOffset)
return false;
}
// These are equal.
return true;
}
}
}
| jonathanpeppers/MonoGameOrientation | MonoGame/Tools/2MGFX/DXConstantBufferData.cs | C# | apache-2.0 | 1,654 |
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="{{ site.description }}">
<title>{% if page.title %}{{ page.title }} - {{ site.title }}{% else %}{{ site.title }}{% endif %}</title>
<link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
<!-- Bootstrap Core CSS -->
<link rel="stylesheet" href="{{ "/css/bootstrap.min.css" | prepend: site.baseurl }}">
<!-- Custom CSS -->
<link rel="stylesheet" href="{{ "/css/clean-blog.css" | prepend: site.baseurl }}">
<link rel="stylesheet" href="{{ "/css/style.css" | prepend: site.baseurl }}">
<!-- Pygments Github CSS -->
<link rel="stylesheet" href="{{ "/css/syntax.css" | prepend: site.baseurl }}">
<!-- Custom Fonts -->
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
| lucasmarcelli/marcellisite | _includes/head.html | HTML | apache-2.0 | 1,737 |
PUSH
====
An open framework that allows data to be pushed from a server to a client
| nickersan/PUSH | README.md | Markdown | apache-2.0 | 85 |
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- **************************************************************** -->
<!-- * PLEASE KEEP COMPLICATED EXPRESSIONS OUT OF THESE TEMPLATES, * -->
<!-- * i.e. only iterate & print data where possible. Thanks, Jez. * -->
<!-- **************************************************************** -->
<html>
<head>
<!-- Generated by groovydoc -->
<title>VersionStrategies (Gradle Wooga Release plugin API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<body class="center">
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="VersionStrategies (Gradle Wooga Release plugin API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<div>
<ul class="navList">
<li><a href="../../../../../index.html?wooga/gradle/release/version/semver/VersionStrategies" target="_top">Frames</a></li>
<li><a href="VersionStrategies.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field <li><a href="#property_summary">Property</a></li> Constructor Method
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field <li><a href="#prop_detail">Property</a></li> Constructor Method
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">Package: <strong>wooga.gradle.release.version.semver</strong></div>
<h2 title="[Groovy] Class VersionStrategies" class="title">[Groovy] Class VersionStrategies</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><ul class="inheritance"></ul></li><li>wooga.gradle.release.version.semver.VersionStrategies
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== NESTED CLASS SUMMARY =========== -->
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<!-- =========== FIELD SUMMARY =========== -->
<!-- =========== PROPERTY SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="property_summary"><!-- --></a>
<h3>Properties Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Properties Summary table, listing nested classes, and an explanation">
<caption><span>Properties</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Type</th>
<th class="colLast" scope="col">Name and description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><strong>static org.ajoberstar.gradle.git.release.semver.PartialSemVerStrategy</strong></code> </td>
<td class="colLast"><code><a href="#COUNT_INCREMENTED">COUNT_INCREMENTED</a></code><br></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><strong>static org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code> </td>
<td class="colLast"><code><a href="#DEVELOPMENT">DEVELOPMENT</a></code><br>Returns a version strategy to be used for <CODE>development</CODE> builds.</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><strong>static org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code> </td>
<td class="colLast"><code><a href="#FINAL">FINAL</a></code><br>Returns a version strategy to be used for <CODE>final</CODE> builds.</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><strong>static org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code> </td>
<td class="colLast"><code><a href="#PRE_RELEASE">PRE_RELEASE</a></code><br>Returns a version strategy to be used for <CODE>pre-release</CODE>/<CODE>candidate</CODE> builds.</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><strong>static org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code> </td>
<td class="colLast"><code><a href="#SNAPSHOT">SNAPSHOT</a></code><br>Returns a version strategy to be used for <CODE>snapshot</CODE> builds.</td>
</tr>
</table>
</ul>
</li>
</ul>
<!-- =========== ELEMENT SUMMARY =========== -->
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary"><!-- --></a>
<h3>Inherited Methods Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Inherited Methods Summary table">
<caption><span>Inherited Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Methods inherited from class</th>
<th class="colLast" scope="col">Name</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class java.lang.Object</code></td>
<td class="colLast"><code>java.lang.Object#wait(long, int), java.lang.Object#wait(long), java.lang.Object#wait(), java.lang.Object#equals(java.lang.Object), java.lang.Object#toString(), java.lang.Object#hashCode(), java.lang.Object#getClass(), java.lang.Object#notify(), java.lang.Object#notifyAll()</code></td>
</tr>
</table>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- =========== PROPERTY DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="prop_detail">
<!-- -->
</a>
<h3>Property Detail</h3>
<a name="COUNT_INCREMENTED"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>static final org.ajoberstar.gradle.git.release.semver.PartialSemVerStrategy <strong>COUNT_INCREMENTED</strong></h4>
<p></p>
</li>
</ul>
<a name="DEVELOPMENT"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>static final org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>DEVELOPMENT</strong></h4>
<p> Returns a version strategy to be used for <CODE>development</CODE> builds.
<p>
This strategy creates a unique version string based on last commit hash and the
distance of commits to nearest normal version.
This version string is not compatible with <a href="https://fsprojects.github.io/Paket/">Paket</a> or
<a href="https://www.nuget.org/">Nuget</a>
<p>
Example:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.3.0"
commitHash = "90c90b9"
distance = 22
inferred = "1.3.0-dev.22+90c90b9"
</CODE>
</pre>
</p>
</li>
</ul>
<a name="FINAL"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>static final org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>FINAL</strong></h4>
<p> Returns a version strategy to be used for <CODE>final</CODE> builds.
<p>
This strategy infers the release version by checking the nearest release.
<p>
Example:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.3.0"
inferred = "1.4.0"
</CODE>
</pre>
</p>
</li>
</ul>
<a name="PRE_RELEASE"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>static final org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>PRE_RELEASE</strong></h4>
<p> Returns a version strategy to be used for <CODE>pre-release</CODE>/<CODE>candidate</CODE> builds.
<p>
This strategy infers the release version by checking the nearest any release.
If a <CODE>pre-release</CODE> with the same <CODE>major</CODE>.<CODE>minor</CODE>.<CODE>patch</CODE> version exists, bumps the count part.
<p>
Example <i>new pre release</i>:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.2.0"
nearestAnyVersion = ""
inferred = "1.3.0-rc00001"
</CODE>
</pre>
<p>
Example <i>pre release version exists</i>:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.2.0"
nearestAnyVersion = "1.3.0-rc00001"
inferred = "1.3.0-rc00002"
</CODE>
</pre>
<p>
Example <i>last final release higher than pre-release</i>:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.3.0"
nearestAnyVersion = "1.3.0-rc00001"
inferred = "1.4.0-rc00001"
</CODE>
</pre>
</p>
</li>
</ul>
<a name="SNAPSHOT"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>static final org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>SNAPSHOT</strong></h4>
<p> Returns a version strategy to be used for <CODE>snapshot</CODE> builds.
<p>
This strategy creates a snapshot version suitable for <a href="https://fsprojects.github.io/Paket/">Paket</a> and
<a href="https://www.nuget.org/">Nuget</a>. <CODE>Nuget</CODE> and <CODE>Paket</CODE> don't support
<CODE>SNAPSHOT</CODE> versions or any numerical values after the <CODE>patch</CODE> component. We trick these package managers
by creating a unique version based on <CODE>branch</CODE> and the distance of commits to nearest normal version.
If the branch name contains numerical values, they will be converted into alphanumerical counterparts.
The <CODE>master</CODE> branch is a special case so it will end up being higher than any other branch build (m>b)
<p>
Example <i>from master branch</i>:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.3.0"
branch = "master"
distance = 22
inferred = "1.4.0-master00022"
</CODE>
</pre>
<p>
Example <i>from topic branch</i>:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.3.0"
branch = "feature/fix_22"
distance = 34
inferred = "1.4.0-branchFeatureFixTwoTow00034"
</CODE>
</pre>
</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<div>
<ul class="navList">
<li><a href="../../../../../index.html?wooga/gradle/release/version/semver/VersionStrategies" target="_top">Frames</a></li>
<li><a href="VersionStrategies.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field <li><a href="#property_summary">Property</a></li> Constructor Method
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field <li><a href="#prop_detail">Property</a></li> Constructor Method
</ul>
</div>
<p>Gradle Wooga Release plugin API</p>
<a name="skip-navbar_bottom">
<!-- -->
</a>
</div>
</div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| wooga/atlas-release | docs/api/wooga/gradle/release/version/semver/VersionStrategies.html | HTML | apache-2.0 | 16,288 |
/**
* @file XMLConstructorException.h
* @brief XMLConstructorException an exception thrown by XML classes
* @author Ben Bornstein
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2013-2015 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
* 3. University of Heidelberg, Heidelberg, Germany
*
* Copyright (C) 2009-2013 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ------------------------------------------------------------------------ -->
*
* @class XMLConstructorException
* @sbmlbrief{core} Exceptions thrown by some libSBML constructors.
*
* @htmlinclude not-sbml-warning.html
*
* In some situations, constructors for SBML objects may need to indicate
* to callers that the creation of the object failed. The failure may be
* for different reasons, such as an attempt to use invalid parameters or a
* system condition such as a memory error. To communicate this to
* callers, those classes will throw an XMLConstructorException. @if cpp
* Callers can use the standard C++ <code>std::exception</code> method
* <code>what()</code> to extract the diagnostic message stored with the
* exception.@endif@~
* <p>
* In languages that don't have an exception mechanism (e.g., C), the
* constructors generally try to return an error code instead of throwing
* an exception.
*
* @see SBMLConstructorException
*/
#ifndef XMLConstructorException_h
#define XMLConstructorException_h
#include <sbml/common/sbmlfwd.h>
#ifdef __cplusplus
#include <string>
#include <stdexcept>
LIBSBML_CPP_NAMESPACE_BEGIN
class LIBSBML_EXTERN XMLConstructorException : public std::invalid_argument
{
public:
/** @cond doxygenLibsbmlInternal */
/* constructor */
XMLConstructorException (std::string
message="NULL reference in XML constructor");
/** @endcond */
};
LIBSBML_CPP_NAMESPACE_END
#endif /* __cplusplus */
#ifndef SWIG
LIBSBML_CPP_NAMESPACE_BEGIN
BEGIN_C_DECLS
END_C_DECLS
LIBSBML_CPP_NAMESPACE_END
#endif /* !SWIG */
#endif /* XMLConstructorException_h */
| Fairly/opencor | src/plugins/api/SBMLAPI/include/sbml/xml/XMLConstructorException.h | C | apache-2.0 | 3,150 |
package ru.istolbov;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
* @author istolbov
* @version $Id$
*/
public class TurnTest {
/**
* Test turn back array.
*/
@Test
public void whenWeTurnBackArray() {
final int[] targetArray = new int[] {5, 4, 3, 2, 1};
final int[] testArray = new int[] {1, 2, 3, 4, 5};
final Turn turn = new Turn();
final int[] resultArray = turn.back(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test sort.
*/
@Test
public void whenWeSortArray() {
final int[] targetArray = new int[] {1, 2, 3, 4, 5};
final int[] testArray = new int[] {5, 3, 4, 1, 2};
final Turn turn = new Turn();
final int[] resultArray = turn.sort(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test rotate.
*/
@Test
public void whenWeRotateArray() {
final int[][] targetArray = new int[][] {{13, 9, 5, 1}, {14, 10, 6, 2}, {15, 11, 7, 3}, {16, 12, 8, 4}};
final int[][] testArray = new int[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
final Turn turn = new Turn();
final int[][] resultArray = turn.rotate(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test duplicateDelete.
*/
@Test
public void whenWeDuplicateDeleteInArray() {
final String[] targetArray = new String[] {"Привет", "Мир", "Май"};
final String[] testArray = new String[] {"Привет", "Привет", "Мир", "Привет", "Май", "Май", "Мир"};
final Turn turn = new Turn();
final String[] resultArray = turn.duplicateDelete(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test join.
*/
@Test
public void whenWeJoinArrays() {
final int[] firstTestArray = new int[] {1, 3, 5, 7, 9};
final int[] secondTestArray = new int[] {2, 4, 6, 8, 10};
final int[] targetArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
final Turn turn = new Turn();
final int[] resultArray = turn.join(firstTestArray, secondTestArray);
assertThat(resultArray, is(targetArray));
}
} | istolbov/i_stolbov | chapter_001/src/test/java/ru/istolbov/TurnTest.java | Java | apache-2.0 | 2,196 |
""" Launcher functionality for the Google Compute Engine (GCE)
"""
import json
import logging
import os
from dcos_launch import onprem, util
from dcos_launch.platforms import gcp
from dcos_test_utils.helpers import Host
from googleapiclient.errors import HttpError
log = logging.getLogger(__name__)
def get_credentials(env=None) -> tuple:
path = None
if env is None:
env = os.environ.copy()
if 'GCE_CREDENTIALS' in env:
json_credentials = env['GCE_CREDENTIALS']
elif 'GOOGLE_APPLICATION_CREDENTIALS' in env:
path = env['GOOGLE_APPLICATION_CREDENTIALS']
json_credentials = util.read_file(path)
else:
raise util.LauncherError(
'MissingParameter', 'Either GCE_CREDENTIALS or GOOGLE_APPLICATION_CREDENTIALS must be set in env')
return json_credentials, path
class OnPremLauncher(onprem.AbstractOnpremLauncher):
# Launches a homogeneous cluster of plain GMIs intended for onprem DC/OS
def __init__(self, config: dict, env=None):
creds_string, _ = get_credentials(env)
self.gcp_wrapper = gcp.GcpWrapper(json.loads(creds_string))
self.config = config
@property
def deployment(self):
""" Builds a BareClusterDeployment instance with self.config, but only returns it successfully if the
corresponding real deployment (active machines) exists and doesn't contain any errors.
"""
try:
deployment = gcp.BareClusterDeployment(self.gcp_wrapper, self.config['deployment_name'],
self.config['gce_zone'])
info = deployment.get_info()
errors = info['operation'].get('error')
if errors:
raise util.LauncherError('DeploymentContainsErrors', str(errors))
return deployment
except HttpError as e:
if e.resp.status == 404:
raise util.LauncherError('DeploymentNotFound',
"The deployment you are trying to access doesn't exist") from e
raise e
def create(self) -> dict:
self.key_helper()
node_count = 1 + (self.config['num_masters'] + self.config['num_public_agents']
+ self.config['num_private_agents'])
gcp.BareClusterDeployment.create(
self.gcp_wrapper,
self.config['deployment_name'],
self.config['gce_zone'],
node_count,
self.config['disk_size'],
self.config['disk_type'],
self.config['source_image'],
self.config['machine_type'],
self.config['image_project'],
self.config['ssh_user'],
self.config['ssh_public_key'],
self.config['disable_updates'],
self.config['use_preemptible_vms'],
tags=self.config.get('tags'))
return self.config
def key_helper(self):
""" Generates a public key and a private key and stores them in the config. The public key will be applied to
all the instances in the deployment later on when wait() is called.
"""
if self.config['key_helper']:
private_key, public_key = util.generate_rsa_keypair()
self.config['ssh_private_key'] = private_key.decode()
self.config['ssh_public_key'] = public_key.decode()
def get_cluster_hosts(self) -> [Host]:
return list(self.deployment.hosts)[1:]
def get_bootstrap_host(self) -> Host:
return list(self.deployment.hosts)[0]
def wait(self):
""" Waits for the deployment to complete: first, the network that will contain the cluster is deployed. Once
the network is deployed, a firewall for the network and an instance template are deployed. Finally,
once the instance template is deployed, an instance group manager and all its instances are deployed.
"""
self.deployment.wait_for_completion()
def delete(self):
""" Deletes all the resources associated with the deployment (instance template, network, firewall, instance
group manager and all its instances.
"""
self.deployment.delete()
| dcos/dcos-launch | dcos_launch/gcp.py | Python | apache-2.0 | 4,208 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConsoleApplication2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("jd")]
[assembly: AssemblyProduct("ConsoleApplication2")]
[assembly: AssemblyCopyright("Copyright © jd 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("54da768a-cc04-48a7-892b-57549b90159e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| singhjaideep/ado-net-segfault | ConsoleApplication2/Properties/AssemblyInfo.cs | C# | apache-2.0 | 1,454 |
package javay.test.security;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* DES安全编码组件
*
* <pre>
* 支持 DES、DESede(TripleDES,就是3DES)、AES、Blowfish、RC2、RC4(ARCFOUR)
* DES key size must be equal to 56
* DESede(TripleDES) key size must be equal to 112 or 168
* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
* RC2 key size must be between 40 and 1024 bits
* RC4(ARCFOUR) key size must be between 40 and 1024 bits
* 具体内容 需要关注 JDK Document http://.../docs/technotes/guides/security/SunProviders.html
* </pre>
*
*/
public abstract class DESCoder extends Coder {
/**
* ALGORITHM 算法 <br>
* 可替换为以下任意一种算法,同时key值的size相应改变。
*
* <pre>
* DES key size must be equal to 56
* DESede(TripleDES) key size must be equal to 112 or 168
* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
* RC2 key size must be between 40 and 1024 bits
* RC4(ARCFOUR) key size must be between 40 and 1024 bits
* </pre>
*
* 在Key toKey(byte[] key)方法中使用下述代码
* <code>SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);</code> 替换
* <code>
* DESKeySpec dks = new DESKeySpec(key);
* SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
* SecretKey secretKey = keyFactory.generateSecret(dks);
* </code>
*/
public static final String ALGORITHM = "DES";
/**
* 转换密钥<br>
*
* @param key
* @return
* @throws Exception
*/
private static Key toKey(byte[] key) throws Exception {
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey secretKey = keyFactory.generateSecret(dks);
// 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码
// SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
return secretKey;
}
/**
* 解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, String key) throws Exception {
Key k = toKey(decryptBASE64(key));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, k);
return cipher.doFinal(data);
}
/**
* 加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String key) throws Exception {
Key k = toKey(decryptBASE64(key));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, k);
return cipher.doFinal(data);
}
/**
* 生成密钥
*
* @return
* @throws Exception
*/
public static String initKey() throws Exception {
return initKey(null);
}
/**
* 生成密钥
*
* @param seed
* @return
* @throws Exception
*/
public static String initKey(String seed) throws Exception {
SecureRandom secureRandom = null;
if (seed != null) {
secureRandom = new SecureRandom(decryptBASE64(seed));
} else {
secureRandom = new SecureRandom();
}
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
kg.init(secureRandom);
SecretKey secretKey = kg.generateKey();
return encryptBASE64(secretKey.getEncoded());
}
}
| dubenju/javay | src/java/javay/test/security/DESCoder.java | Java | apache-2.0 | 4,047 |
---
title: TiDB 简介
aliases: ['/docs-cn/dev/overview/','/docs-cn/dev/key-features/']
---
# TiDB 简介
[TiDB](https://github.com/pingcap/tidb) 是 [PingCAP](https://pingcap.com/about-cn/) 公司自主设计、研发的开源分布式关系型数据库,是一款同时支持在线事务处理与在线分析处理 (Hybrid Transactional and Analytical Processing, HTAP) 的融合型分布式数据库产品,具备水平扩容或者缩容、金融级高可用、实时 HTAP、云原生的分布式数据库、兼容 MySQL 5.7 协议和 MySQL 生态等重要特性。目标是为用户提供一站式 OLTP (Online Transactional Processing)、OLAP (Online Analytical Processing)、HTAP 解决方案。TiDB 适合高可用、强一致要求较高、数据规模较大等各种应用场景。
关于 TiDB 的关键技术创新,请观看以下视频。
<video src="https://tidb-docs.s3.us-east-2.amazonaws.com/compressed+-+Lesson+01.mp4" width="600px" height="450px" controls="controls" poster="https://tidb-docs.s3.us-east-2.amazonaws.com/thumbnail+-+lesson+1.png"></video>
## 五大核心特性
- 一键水平扩容或者缩容
得益于 TiDB 存储计算分离的架构的设计,可按需对计算、存储分别进行在线扩容或者缩容,扩容或者缩容过程中对应用运维人员透明。
- 金融级高可用
数据采用多副本存储,数据副本通过 Multi-Raft 协议同步事务日志,多数派写入成功事务才能提交,确保数据强一致性且少数副本发生故障时不影响数据的可用性。可按需配置副本地理位置、副本数量等策略满足不同容灾级别的要求。
- 实时 HTAP
提供行存储引擎 [TiKV](/tikv-overview.md)、列存储引擎 [TiFlash](/tiflash/tiflash-overview.md) 两款存储引擎,TiFlash 通过 Multi-Raft Learner 协议实时从 TiKV 复制数据,确保行存储引擎 TiKV 和列存储引擎 TiFlash 之间的数据强一致。TiKV、TiFlash 可按需部署在不同的机器,解决 HTAP 资源隔离的问题。
- 云原生的分布式数据库
专为云而设计的分布式数据库,通过 [TiDB Operator](https://docs.pingcap.com/zh/tidb-in-kubernetes/stable/tidb-operator-overview) 可在公有云、私有云、混合云中实现部署工具化、自动化。
- 兼容 MySQL 5.7 协议和 MySQL 生态
兼容 MySQL 5.7 协议、MySQL 常用的功能、MySQL 生态,应用无需或者修改少量代码即可从 MySQL 迁移到 TiDB。提供丰富的[数据迁移工具](/ecosystem-tool-user-guide.md)帮助应用便捷完成数据迁移。
## 四大核心应用场景
- 对数据一致性及高可靠、系统高可用、可扩展性、容灾要求较高的金融行业属性的场景
众所周知,金融行业对数据一致性及高可靠、系统高可用、可扩展性、容灾要求较高。传统的解决方案是同城两个机房提供服务、异地一个机房提供数据容灾能力但不提供服务,此解决方案存在以下缺点:资源利用率低、维护成本高、RTO (Recovery Time Objective) 及 RPO (Recovery Point Objective) 无法真实达到企业所期望的值。TiDB 采用多副本 + Multi-Raft 协议的方式将数据调度到不同的机房、机架、机器,当部分机器出现故障时系统可自动进行切换,确保系统的 RTO <= 30s 及 RPO = 0。
- 对存储容量、可扩展性、并发要求较高的海量数据及高并发的 OLTP 场景
随着业务的高速发展,数据呈现爆炸性的增长,传统的单机数据库无法满足因数据爆炸性的增长对数据库的容量要求,可行方案是采用分库分表的中间件产品或者 NewSQL 数据库替代、采用高端的存储设备等,其中性价比最大的是 NewSQL 数据库,例如:TiDB。TiDB 采用计算、存储分离的架构,可对计算、存储分别进行扩容和缩容,计算最大支持 512 节点,每个节点最大支持 1000 并发,集群容量最大支持 PB 级别。
- Real-time HTAP 场景
随着 5G、物联网、人工智能的高速发展,企业所生产的数据会越来越多,其规模可能达到数百 TB 甚至 PB 级别,传统的解决方案是通过 OLTP 型数据库处理在线联机交易业务,通过 ETL 工具将数据同步到 OLAP 型数据库进行数据分析,这种处理方案存在存储成本高、实时性差等多方面的问题。TiDB 在 4.0 版本中引入列存储引擎 TiFlash 结合行存储引擎 TiKV 构建真正的 HTAP 数据库,在增加少量存储成本的情况下,可以同一个系统中做联机交易处理、实时数据分析,极大地节省企业的成本。
- 数据汇聚、二次加工处理的场景
当前绝大部分企业的业务数据都分散在不同的系统中,没有一个统一的汇总,随着业务的发展,企业的决策层需要了解整个公司的业务状况以便及时做出决策,故需要将分散在各个系统的数据汇聚在同一个系统并进行二次加工处理生成 T+0 或 T+1 的报表。传统常见的解决方案是采用 ETL + Hadoop 来完成,但 Hadoop 体系太复杂,运维、存储成本太高无法满足用户的需求。与 Hadoop 相比,TiDB 就简单得多,业务通过 ETL 工具或者 TiDB 的同步工具将数据同步到 TiDB,在 TiDB 中可通过 SQL 直接生成报表。
关于 TiDB 典型应用场景和用户案例的介绍,请观看以下视频。
<video src="https://tidb-docs.s3.us-east-2.amazonaws.com/compressed+-+Lesson+06.mp4" width="600px" height="450px" controls="controls" poster="https://tidb-docs.s3.us-east-2.amazonaws.com/thumbnail+-+lesson+6.png"></video>
## 另请参阅
- [TiDB 整体架构](/tidb-architecture.md)
- [TiDB 数据库的存储](/tidb-storage.md)
- [TiDB 数据库的计算](/tidb-computing.md)
- [TiDB 数据库的调度](/tidb-scheduling.md)
| pingcap/docs-cn | overview.md | Markdown | apache-2.0 | 5,881 |
/*
* Copyright 2016 Yu Sheng. All Rights Reserved.
*
* 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.
*/
package com.ysheng.auth.model.api;
/**
* Defines the grant types.
*/
public enum GrantType {
AUTHORIZATION_CODE,
IMPLICIT,
PASSWORD,
CLIENT_CREDENTIALS
}
| zeelichsheng/auth | auth-model/src/main/java/com/ysheng/auth/model/api/GrantType.java | Java | apache-2.0 | 769 |
# Stachybotrys renispora P.C. Misra SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycotaxon 4(1): 161 (1976)
#### Original name
Stachybotrys renispora P.C. Misra
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Sordariomycetes/Hypocreales/Stachybotrys/Stachybotrys renispora/README.md | Markdown | apache-2.0 | 217 |
# Asteroma senecionis Ellis & Everh. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Asteroma senecionis Ellis & Everh.
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Sordariomycetes/Diaporthales/Gnomoniaceae/Asteroma/Asteroma senecionis/README.md | Markdown | apache-2.0 | 197 |
# Bulbophyllum ambongense Schltr. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Bulbophyllum/Bulbophyllum rubrum/ Syn. Bulbophyllum ambongense/README.md | Markdown | apache-2.0 | 188 |
# Statice formosa Hort. ex Vilm. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Plumbaginaceae/Statice/Statice formosa/README.md | Markdown | apache-2.0 | 180 |
# Pyrethrum seticuspe Maxim. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/incertae sedis/Dendranthema lavandulifolium lavandulifolium/ Syn. Pyrethrum seticuspe/README.md | Markdown | apache-2.0 | 183 |
# Cortinarius turmalis (Fr.) Fr., 1838 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Epicr. syst. mycol. (Upsaliae) 257 (1838)
#### Original name
Cortinarius turmalis (Fr.) Fr., 1838
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Cortinarius/Cortinarius turmalis/README.md | Markdown | apache-2.0 | 263 |
# Ramularia knautiae (C. Massal.) Bubák, 1903 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Öst. bot. Z. 53: 50 (1903)
#### Original name
Ramularia succisae var. knautiae C. Massal., 1889
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Ramularia/Ramularia succisae/ Syn. Ramularia knautiae/README.md | Markdown | apache-2.0 | 269 |
/* jshint sub: true */
/* global exports: true */
'use strict';
// //////////////////////////////////////////////////////////////////////////////
// / @brief node-request-style HTTP requests
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2015 triAGENS GmbH, Cologne, Germany
// /
// / 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.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Alan Plum
// / @author Copyright 2015, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////
const internal = require('internal');
const Buffer = require('buffer').Buffer;
const extend = require('lodash').extend;
const httperr = require('http-errors');
const is = require('@arangodb/is');
const querystring = require('querystring');
const qs = require('qs');
const url = require('url');
class Response {
throw (msg) {
if (this.status >= 400) {
throw Object.assign(
httperr(this.status, msg || this.message),
{details: this}
);
}
}
constructor (res, encoding, json) {
this.status = this.statusCode = res.code;
this.message = res.message;
this.headers = res.headers ? res.headers : {};
this.body = this.rawBody = res.body;
if (this.body && encoding !== null) {
this.body = this.body.toString(encoding || 'utf-8');
if (json) {
try {
this.json = JSON.parse(this.body);
} catch (e) {
this.json = undefined;
}
}
}
}
}
function querystringify (query, useQuerystring) {
if (!query) {
return '';
}
if (typeof query === 'string') {
return query.charAt(0) === '?' ? query.slice(1) : query;
}
return (useQuerystring ? querystring : qs).stringify(query)
.replace(/[!'()*]/g, function (c) {
// Stricter RFC 3986 compliance
return '%' + c.charCodeAt(0).toString(16);
});
}
function request (req) {
if (typeof req === 'string') {
req = {url: req, method: 'GET'};
}
let path = req.url || req.uri;
if (!path) {
throw new Error('Request URL must not be empty.');
}
let pathObj = typeof path === 'string' ? url.parse(path) : path;
if (pathObj.auth) {
let auth = pathObj.auth.split(':');
req = extend({
auth: {
username: decodeURIComponent(auth[0]),
password: decodeURIComponent(auth[1])
}
}, req);
delete pathObj.auth;
}
let query = typeof req.qs === 'string' ? req.qs : querystringify(req.qs, req.useQuerystring);
if (query) {
pathObj.search = query;
}
path = url.format(pathObj);
let contentType;
let body = req.body;
if (req.json) {
body = JSON.stringify(body);
contentType = 'application/json';
} else if (typeof body === 'string') {
contentType = 'text/plain; charset=utf-8';
} else if (typeof body === 'object' && body instanceof Buffer) {
contentType = 'application/octet-stream';
} else if (!body) {
if (req.form) {
contentType = 'application/x-www-form-urlencoded';
body = typeof req.form === 'string' ? req.form : querystringify(req.form, req.useQuerystring);
} else if (req.formData) {
// contentType = 'multipart/form-data'
// body = formData(req.formData)
throw new Error('Multipart form encoding is currently not supported.');
} else if (req.multipart) {
// contentType = 'multipart/related'
// body = multipart(req.multipart)
throw new Error('Multipart encoding is currently not supported.');
}
}
const headers = {};
if (contentType) {
headers['content-type'] = contentType;
}
if (req.headers) {
Object.keys(req.headers).forEach(function (name) {
headers[name.toLowerCase()] = req.headers[name];
});
}
if (req.auth) {
headers['authorization'] = ( // eslint-disable-line dot-notation
req.auth.bearer ?
'Bearer ' + req.auth.bearer :
'Basic ' + new Buffer(
req.auth.username + ':' +
req.auth.password
).toString('base64')
);
}
let options = {
method: (req.method || 'get').toUpperCase(),
headers: headers,
returnBodyAsBuffer: true,
returnBodyOnError: req.returnBodyOnError !== false
};
if (is.existy(req.timeout)) {
options.timeout = req.timeout;
}
if (is.existy(req.followRedirect)) {
options.followRedirects = req.followRedirect; // [sic] node-request compatibility
}
if (is.existy(req.maxRedirects)) {
options.maxRedirects = req.maxRedirects;
} else {
options.maxRedirects = 10;
}
if (req.sslProtocol) {
options.sslProtocol = req.sslProtocol;
}
let result = internal.download(path, body, options);
return new Response(result, req.encoding, req.json);
}
exports = request;
exports.request = request;
exports.Response = Response;
['delete', 'get', 'head', 'patch', 'post', 'put']
.forEach(function (method) {
exports[method.toLowerCase()] = function (url, options) {
if (typeof url === 'object') {
options = url;
url = undefined;
} else if (typeof url === 'string') {
options = extend({}, options, {url: url});
}
return request(extend({method: method.toUpperCase()}, options));
};
});
module.exports = exports;
| baslr/ArangoDB | js/common/modules/@arangodb/request.js | JavaScript | apache-2.0 | 5,781 |
Android Kod Yazım Kılavuzu
---------------------------
Bu dokümanın amacı Android uygulama geliştirirken bize yardımcı olacak kod yazım prensiplerini belirlemektir. Uygulama geliştirirken bu dokümana göre hareket etmek temiz ve istikrarlı kod yazımında bize yardımcı olacaktır.
Not: Bazı yerlerde İngilizce-Türkçe kullanımında karışıklık olmaktadır. Bunlar kullanılan kelimelerin tam karşılığının olmamasından kaynaklanmaktadır. Örneğin; handle etmek , class dosyaları..
##1. Uygulama Prensipleri
###1.1 Proje Yapısı
Uygulama geliştirirken, proje yapısı ağağıdaki gibi olmadır. :
src/AndroidTest
src/Test
src/CommonTest
src/main
**AndroidTest** - Fonksiyonel testleri içeren klasör.
**Test** - Unit testleri içeren klasör.
**CommonTest** - Paylaşılan AndroidTest & Test kodlarının bulunduğu klasör.
**main** - Uygulamanın kodlarını içeren klasör.
Uygulamanın genel yapısı herhangi bir değişiklikte ya da yeni bir özellik eklendiğinde yukarıda belirlenmiş şekilde kalmalıdır. Bu yapıyı kullanmanın avantajı test ile ilişkili olan kodların ayrı olmasıdır.
###1.2 Dosya İsimlendirme
####1.2.1 Class dosyaları
Her class dosyası BüyükKüçük şeklinde tanımlanmaldır. Örnek olarak;
AndroidActivity, NetworkHelper, UserFragment, PerActivity
Android kütüphanesinden kalıtılmış bileşen **her zaman** hangi sınıftan kalıtılıyorsa o bileşenin ismi ile bitmelidir. Örnek olarak;
UserFragment, SignUpActivity, RateAppDialog, PushNotificationServer, NumberView
BüyükKüçük harf şeklinde kullanılan class isimleri okunabilirlik açısından kolaylık sağlamaktadır. Ayrıca class'ları bileşenlerin isimlerine göre isimlendirme de hangi class'ın ne için kullanıldığı hakkında bize bilgi vermektedir. Örnek olarak RegistrationDialog bize kayıt ile ilgili işlemin bu dialog'da yapıldığını göstermektedir.
####1.2.2 Resource Dosyaları
Resource dosyalarını isimlendirirken küçük-harf kullanmalıyız ve boşluk yerine alt çizgi (_) kullanmalıyız. Örnek olarak;
activity_main, fragment_user, item_post
Bu şekilde kullanım, herhangi bir amaca yönelik oluşturulmuş layout dosyasını bulmamızda bize kolaylık sağlar. Android Studio'da layout kısmı alfabetik olarak sıralanmış durumdadır. Böylece activity_main şeklinde isim verildiğinde tüm aynı amaca hizmet eden layout'lar gruplanmış olacaktır.
####1.2.2.1 Drawable Dosyaları
Drawable resource dosyaları **ic_name_00dp** şeklinde adlandırılmalıdır..
ic_entrance_24dp , ic_accept_32dp
Bu şekilde bir isimlendirme, drawable klasörlerinde bulunan ikonların boyutlarının açılmadan öğrenilmesine yardımcı olacaktır.
Diğer drawable bileşenlerinin kullanımı aşağıdaki şekilde olmalıdır.
| Tipi | Ön Eki | Örnek |
|------------|-----------|------------------------|
| Selector | selector_ | selector_button_cancel |
| Background | bg_ | bg_rounded_button |
| Circle | circle_ | circle_white |
| Progress | progress_ | progress_circle_purple |
| Divider | divider_ | divider_grey |
Bu şekilde isimlendirme benzer bileşenlerin Android Studio ile gruplandırılmasına yardımcı olmaktadır. Aynı zamanda hangi bileşenin nerede kullanıldığına dair bilgi vermektedir. Doğru isimlendirme uygulama geliştirirken meydana gelecek ikilikleri engellemektedir.
Selector state resource dosyası oluşurken de duruma göre son ek vermemiz gerekmektedir.
| Durum | Son Ek | Örnek |
|----------|-----------|---------------------|
| Normal | _normal | btn_accept_normal |
| Pressed | _pressed | btn_accept_pressed |
| Focused | _focused | btn_accept_focused |
| Disabled | _disabled | btn_accept_disabled |
| Selected | _selected | btn_accept_selected |
####1.2.2.2 Layout Dosyaları
Layout dosyaları aşağıdaki şekilde Java class'ına göre oluşturulmalıdır.
**class_java_name**
| Bileşen | Class İsmi | Layout İsmi |
|------------------|-----------------|-------------------|
| Activity | MainActivity | activity_main |
| Fragment | MainFragment | fragment_main |
| Dialog | RateDialog | dialog_rate |
| Widget | UserProfileView | view_user_profile |
| AdapterView Item | N/A | item_follower |
####1.2.2.3 Menu Dosyaları
Menu dosyalarının menu_ ön eki ile isimlendirilmesine gerek yoktur. Zaten bu dosyalar menu klasörü içinde bulunmaktadır.
####1.2.2.4 Values Dosyaları
Values kısmında bulunan dosyalar çoğul olmalıdır.
attrs.xml, strings.xml, styles.xml, colors.xml, dimens.xml
##2. Kod Rehberi
###2.1 Java Dili Kuralları
####2.1.1 Exceptionları görmezden gelmeyin :)
Exceptionları handle etmeden bırakmayınız.
public void setUserId(String id) {
try {
mUserId = Integer.parseInt(id);
} catch (NumberFormatException e) { }
}
Yukarıdaki yazım tarzı hem kullanıcıya, hem de uygulama geliştiriciye meydana gelen hata ile ilgili bilgi vermemektedir. Bunun yerine ilgili hata ile ilgili bilgi verdiren log yazdırılmalıdır.
public void setCount(String count) {
try {
count = Integer.parseInt(id);
} catch (NumberFormatException e) {
count = 0;
Log.e(TAG, "There was an error parsing the count " + e);
DialogFactory.showErrorMessage(R.string.error_message_parsing_count);
}
}
Hataları şu şekilde handle etmeliyiz.
- Kullanıcıya hata meydana geldiğine dair uyarı vermeliyiz.
- Hata oluşması durumunda değişkene sabit bir değer vermeliyiz.
- Uygun olan exception'ı göstermeliyiz.
####2.1.2 Türü belli olmayan exception'lar
Exception yakalarken aşağıdaki şekilde en genel halini göstermemeliyiz.
public void openCustomTab(Context context, Uri uri) {
Intent intent = buildIntent(context, uri);
try {
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "There was an error opening the custom tab " + e);
}
}
Neden?
Bu şekilde genel haliyle yakalanan exception'lar bize aldığımız hatalar hakkında bilgi vermemektedir.
Bunun yerine duruma göre exceptionlar yakalanmaladır.
public void openCustomTab(Context context, Uri uri) {
Intent intent = buildIntent(context, uri);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "There was an error opening the custom tab " + e);
}
}
####2.1.3 Exception'ların gruplanması.
Exceptionlar aynı koddan meydana geliyorsa gruplandırılması gerekmektedir.
public void openCustomTab(Context context, @Nullable Uri uri) {
Intent intent = buildIntent(context, uri);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "There was an error opening the custom tab " + e);
} catch (NullPointerException e) {
Log.e(TAG, "There was an error opening the custom tab " + e);
} catch (SomeOtherException e) {
// Show some dialog
}
}
Gruplanmış exception' lar aşağıdaki gibidir:
public void openCustomTab(Context context, @Nullable Uri uri) {
Intent intent = buildIntent(context, uri);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e | NullPointerException e) {
Log.e(TAG, "There was an error opening the custom tab " + e);
} catch (SomeOtherException e) {
// Show some dialog
}
}
####2.1.4 Try-catch kulllanımı
Try-catch kullanımı kod okunabilirliğini arttırır. Meydana gelen hata da kolayca handle edilmiş olur. Aynı zamanda debug aşamasını da epey kolaylaştırmış olur.
####2.1.5 Never use Finalizers
*There are no guarantees as to when a finalizer will be called, or even that it will be called at all. In most cases, you can do what you need from a finalizer with good exception handling. If you absolutely need it, define a close() method (or the like) and document exactly when that method needs to be called. See InputStreamfor an example. In this case it is appropriate but not required to print a short log message from the finalizer, as long as it is not expected to flood the logs.* - taken from the Android code style guidelines
####2.1.6 Bileşenlerin import edilmesi.
Bileşenler import edilirken tüm ismi ile import edilmeli.
Bunun yerine:
import android.support.v7.widget.*;
Bunu yapın :) 😃
import android.support.v7.widget.RecyclerView;
####2.1.7 Kullanılmayan importları tutmayın.
###2.2 Java Kod Stili Kuralları
####2.2.1 Field tanımlama ve isimlendirme
Tüm field'lar sayfanın en üstünde ve aşağıdaki kurallara göre tanımlanmalıdır.
- Private, non-static olmayan fieldların isimleri *m* ile başlamamalıdır:
userSignedIn, userNameText, acceptButton
Aşağıdaki kullanım kod okunabilirliğini azaltmaktadır:
mUserSignedIn, mUserNameText, mAcceptButton
- Private, static field isimleri *s* ile başlamamalıdır.:
someStaticField, userNameText
Aşağıdaki kullanım da okunabilirliği azaltmaktadır:
sSomeStaticField, sUserNameText
- Diğer tüm fieldlar küçük harfle başlamalıdır.
int numOfChildren;
String username;
- Static final değişkenler BUYUK_HARFLE_VE_ALTYAZI ile yazılmalıdır. .
private static final int PAGE_COUNT = 0;
Değişken isimleri kullanıma göre isimlendirilmelidir.
int e; //listedeki eleman sayısı
Yukarıdaki kullanım yerine, değişkenin ismini kullanım amacına göre vermemiz gerekmekdir.
int elemanSayisi;
####2.2.1.2 View Alanlarının İsimlendirmesi
View bileşenleri isimlendirilirken, bileşenlerinin isimlerine göre adlandırılır.
| View | Name |
|----------------|--------------------|
| TextView | usernameText |
| Button | acceptLoginButton |
| ImageView | profileAvatarImage |
| RelativeLayout | profileLayout |
Yukarıdaki kullanım ile birlikte hangi değişkenimizin hangi bileşenden meydana geldiğini anlayabiliriz.
####2.2.2 Container tiplerini isimlendirmede kullanmamalıyız
Bunu yapın:
List<String> userIds = new ArrayList<>();
Bunu yapmayın:
List<String> userIdList = new ArrayList<>();
####2.2.3 Aynı isimlendirme yapmaktan kaçının
Bir değişkeni, metodu isimlendirirken aynı isimleri kullanmayınız.
hasUserSelectedSingleProfilePreviously
hasUserSelectedSignedProfilePreviously
####2.2.4 Number series naming
Method oluştururken kullandığımız parametreleri amaçlarına göre isimlendirmeliyiz.
public void doSomething(String s1, String s2, String s3)
Yukarıdaki kullanımda s1, s2 ve s3'ün ne olduğu belli değil. Bunun yerine:
public void doSomething(String userName, String userEmail, String userId)
Parametreleri değişkenlere göre isimlendirmeliyiz.
####2.2.5 Pronouncable names
Field' lar metotlar ve sınıflar adlandırılırken:
- Okunabilir olmalı: Etkin bir isim okunduğunda direk anlaşılabilmelidir.
- Kolay telaffuz edilebilmeli
- Kolay arama yapılabilmeli : Örneğin bir methot' u bir sınıf içerisinde ararken kolayca sonuca ulaştırabilecek isimler tercih edilmelidir.
- Maceristan notasyonu (Hungarian notation- mLocation vb.) yukarıda bahsedilen üç maddeye uymadığı için kullanmayınız.
####2.2.6 Kısaltmaları (Baş harflerden oluşan) kelime olarak kullanma
Sınıf isimlerinin,değişken isimlerinin kısaltmaları kelime olarak kullanıken sadece baş harfi büyük harfle yazılarak kullanılmalıdır.
Örneğin:
| Doğru | Yanlış |
|--------------------|------------------|
| setUserId | setUserID |
| String Uri | String URI |
| int id | int ID |
| parseHtml | parseHTML |
| generateXmlFile | generateXMLFile |
####2.2.7 Satırların uzunluğuna göre ayarlama
Değişken tanımlarker satıların dizilimi için herhangi bir özel form kullanmayınız, örneğin:
private int userId = 8;
private int count = 0;
private String username = "hitherejoe";
Bu şekilde yapmaktan kaçının:
private String username = "hitherejoe";
private int userId = 8;
private int count = 0;
####2.2.8 Girintiler için boşluk kullanma
Bloklar için 4 boşluk bırakılmalı:
if (userSignedIn) {
count = 1;
}
String tanımlamalar için baştan 8 satır boşluk bırakılmalı.
String userAboutText =
"This is some text about the user and it is pretty long, can you see!"
###2.2.9 If-Statements
####2.2.9.1 Standart süslü parantez stili
Süslü parantez ile koşul daima aynı satırda olmalıdır.
Aşağıdaki gibi yazmaktan kaçının.
class SomeClass {
private void someFunction()
{
if (isSomething)
{
}
else if (!isSomethingElse)
{
}
else
{
}
}
}
yerine bunu kullanın :
class SomeClass {
private void someFunction() {
if (isSomething) {
} else if (!isSomethingElse) {
} else {
}
}
}
####2.2.9.2 Satır-içi if-clauses
bazı durumlarlar if bloklar tek satırda yazmak daha mantıklıdır. Örneğin:
if (user == null) return false;
Fakat, bu sadece basit işlemler için geçerlidir. Aşağıdaki şekilde olan kod parçacıkları için süslü parantezlerle yazmak daha doğrudur.
if (user == null) throw new IllegalArgumentExeption("Oops, user object is required.");
####2.2.9.3 İç içe if koşulu
Mümkün oldukça iç içe if lokları yazmaktan kaçının. Örneğin:
Bunun yerine:
if (userSignedIn) {
if (userId != null) {
}
}
Bu şekilde yazmayı tercih ediniz:
if (userSignedIn && userId != null) {
}
Bu şekilde yazımlar kod okunabilirliğini artırttırır ve gereksiz satır kullanımını engellenmiş olur.
####2.2.9.4 üçlü operatör
Uygun olduğu durumlarda işlemleri kolaylaştımak için üçlü operatörler kullanılabilir.
Örneğin bu kod satırını okumak kolaydır:
userStatusImage = signedIn ? R.drawable.ic_tick : R.drawable.ic_cross;
ve aşağıdaki gibi fazla satır :
if (signedIn) {
userStatusImage = R.drawable.ic_tick;
} else {
userStatusImage = R.drawable.ic_cross;
}
**Note:** Üçlü operatörlerin kullanıldığı bazı zamnlar vardır. Eğer if-koşul mantığı karmaşık ya da karakter sayısı fazla ise standart süslü parantez stili kullanılmalıdır.
###2.2.10 Annotations
####2.2.10.1 Annotation practices
Android kod stil rehberinden alınmıştır:
**@Override:** The @Override annotation must be used whenever a method overrides the declaration or implementation from a super-class. For example, if you use the @inheritdocs Javadoc tag, and derive from a class (not an interface), you must also annotate that the method @Overrides the parent class's method.
@Override annotation bir metot üst bir sınıftan kalıtıldığında kullanılmalıdır.
**@SuppressWarnings:** The @SuppressWarnings annotation should only be used under circumstances where it is impossible to eliminate a warning. If a warning passes this "impossible to eliminate" test, the @SuppressWarnings annotation must be used, so as to ensure that all warnings reflect actual problems in the code.
--Daha fazla bilgi almak için rehbere bakabilirsiniz.
----------
Annotations mümkün oldukça her zaman kullanılmalıdır. Örneğin bir field'ın null olması umulduğu durumlarda @Nullable annotation'ı kullanılmalıdır.
@Nullable TextView userNameText;
private void getName(@Nullable String name) { }
####2.2.10.2 Annotation stili
Metotlar yada class lar için kullanılan annotation'lar satır başına sadece biri için yazılmalıdır:
@Annotation
@AnotherAnnotation
public class SomeClass {
@SomeAnotation
public String getMeAString() {
}
}
####2.2.11 Kullanılmayan elementler
Bütün kullanılmayan elementler **fields**, **imports**, **methods** and **classes** kaldırılmalıdır.(Eğer özel bir sebebi yoksa).
####2.2.12 Arguments in fragments and activities
intent ve bundle ile veri gönderirken, key - value aşağıdaki tanımlamalar kullanılmalıdır.
**Activity**
Bir activity' e veri gönderirken bir KEY aracılığı ile gönderilir.
private static final String KEY_NAME = "com.your.package.name.to.activity.KEY_NAME";
**Fragment**
Bir fragment' e veri gönderirken bir EXTRA aracılığı ile gönderilir.
private static final String EXTRA_NAME = "EXTRA_NAME";
**Activity**
public static Intent getStartIntent(Context context, Post post) {
Intent intent = new Intent(context, CurrentActivity.class);
intent.putParcelableExtra(EXTRA_POST, post);
return intent;
}
**Fragment**
public static PostFragment newInstance(Post post) {
PostFragment fragment = new PostFragment();
Bundle args = new Bundle();
args.putParcelable(ARGUMENT_POST, post);
fragment.setArguments(args)
return fragment;
}
###2.2.13 Yorum satırları
####2.2.13.1 Satır içi yorumlar
Kodların kompleks olduğu durumlarda okuyucunun anlaması için kolay anlaşılabilir cümlelerle açıklamalar yazılmalıdır. Fakat aslolan kodların yorum satırı olmadan anlaşılabilecek şekilde yazılmasıdır.
**Not:** Yorum satırı olmak zorunda değildir max 100 karakteri de geçmemesine özen gösterilmeli.
### 2.3 Resource dosyalarının isimlendirilmesi
Tüm resource dosyaları isimlendirilirken küçük harf ve alt çizgi kullanılmalıdır.
text_username, activity_main, fragment_user, error_message_network_connection
Bu şekilde kullanımın bize kazandırdığı en büyük avantaj, proje dosyalarında bir tutarlılığın oluşmasıdır.
#### 2.3.1 ID İsimlendirmesi
Tüm ID'ler isimlendirilirken ait olduğu element'e göre isimlendirilir.
Örneğin;
| Element | Ön Ek |
|----------------|-----------|
| ImageView | image_ |
| Fragment | fragment_ |
| RelativeLayout | layout_ |
| Button | button_ |
| TextView | text_ |
| View | view_ |
Kullanım:
<TextView
android:id="@+id/text_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
#### 2.3.2 Strings
String isimlendirmeleri kullanıldığı ekrana ve kullanım amacına göre isimlendirilmelidir.
| Ekran | String ifade | Strings.xml karşılığı |
|-----------------------|----------------|---------------------------|
| Registration Fragment | “Register now” | registration_register_now |
| Sign Up Activity | “Cancel” | sign_up_cancel |
| Rate App Dialog | “No thanks” | rate_app_no_thanks |
Eğer yukarıdaki gibi isimlendirme mümkün değilse aşağıdaki gibi kullanım tipine göre isimlendirme opsiyonu kullanılabilir.
| Ön Ek | Açıklama |
|---------|----------------------------------------------|
| error_ | Error mesajalrı için kullanılır. |
| title_ | Dialog başlıklarında kullanılır. |
| action_ | Menü ile ilgili string ifadelerde kullanılır.|
| msg_ | Used for generic message such as in a dialog |
| label_ | Used for activity labels |
Two important things to note for String resources:
- String resources should never be reused across screens. This can cause issues when it comes to changing a string for a specific screen. It saves future complications by having a single string for each screens usage.
- String resources should **always** be defined in the strings file and never hardcoded in layout or class files.
#### 2.3.3 Stiller ve temalar
Stil ve tema isimlendirmeleri BuyukKucuk isimlendirme şeklinde yapılmalıdır.
AppTheme.DarkBackground.NoActionBar
AppTheme.LightBackground.TransparentStatusBar
ProfileButtonStyle
TitleTextStyle
### 2.3.4 XML Attribute sıralanması
Attribute sıralaması için Android Studio içerisinde bir fonksiyon bulunmalıdır. XML ile ilgili yaptığımız değişikliklikler sonrası bu fonksiyonu çalıştırmalıyız.
Windows bilgisayarlar için çalıştırma yöntemi;
`Ctrl + shift + L`
Mac için çalıştırma yöntemi;
`cmd + shift + L`
# 3. Gradle Stili
## 3.1 Kütüphaneler
### 3.1.1 Versiyonlama
Uygulanabilirse, aynı versiyonu paylaşan kütüphanelerin versiyon numarası tek bir değişkenle tutulup, diğer kütüphanelerle paylaşılabilir.
Örneğin;
final SUPPORT_LIBRARY_VERSION = '23.4.0'
compile "com.android.support:support-v4:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:support-annotations:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:design:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:percent:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:customtabs:$SUPPORT_LIBRARY_VERSION"
Bu şekilde kullandığımızda ileride kütüphanelerde güncelleme yapacağımız zaman tek seferde versiyon numarasını değiştirerek tüm kütüphaneleri tek seferde güncellemiş oluruz.
### 3.1.2 Gruplama
Aynı package adını kullanan kütüphaneler gruplanabilir.
compile "com.android.support:percent:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:customtabs:$SUPPORT_LIBRARY_VERSION"
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.5'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.jakewharton.timber:timber:4.1.2'
compile 'com.github.bumptech.glide:glide:3.7.0'
`compile` , `testCompile` and `androidTestCompile` kütüphaneleri de kendi içerisinde gruplanabilir.
// Uygulama Kütüphaneleri
compile "com.android.support:support-v4:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION"
// Cihaz testi kütüphanesi
androidTestCompile "com.android.support:support-annotations:$SUPPORT_LIBRARY_VERSION"
// Unit test kütüphanesi
testCompile 'org.robolectric:robolectric:3.0'
Bu şekilde kullanım,geliştiriciye kütüphanelerin kullanımında bir düzen ve kolaylık sağlamaktadır.
### 3.1.3 Amaca uygun kütüphaneler
Uygulamaya eklenen kütüphaneler belirli amaca uygun olarak kullanılacaksa `compile` , `testCompile` veya `androidTestCompile` yazım tarzı kullanılan amacına uygun olmalı. Örneğin; roboelectric kütüphanesi sadece unit test amacı ile gereklidir. Bu yüzden de `testCompile` şeklinde eklenmektedir.
testCompile 'org.robolectric:robolectric:3.0'
| salihyalcin/android-guidelines | android_java_style.md | Markdown | apache-2.0 | 23,308 |
/// <reference path="../apimanPlugin.ts"/>
/// <reference path="../services.ts"/>
module Apiman {
export var UserRedirectController = _module.controller("Apiman.UserRedirectController",
['$q', '$scope', '$location', 'PageLifecycle', '$routeParams',
($q, $scope, $location, PageLifecycle, $routeParams) => {
PageLifecycle.loadPage('UserRedirect', undefined, undefined, $scope, function() {
PageLifecycle.forwardTo('/users/{0}/orgs', $routeParams.user);
});
}])
}
| kunallimaye/apiman | manager/ui/hawtio/plugins/api-manager/ts/user/user.ts | TypeScript | apache-2.0 | 528 |
#ifndef _TCUX11_HPP
#define _TCUX11_HPP
/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief X11 utilities.
*//*--------------------------------------------------------------------*/
#include "tcuDefs.hpp"
#include "gluRenderConfig.hpp"
#include "gluPlatform.hpp"
#include "deMutex.hpp"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/Xatom.h>
namespace tcu
{
namespace x11
{
enum
{
DEFAULT_WINDOW_WIDTH = 400,
DEFAULT_WINDOW_HEIGHT = 300
};
class EventState
{
public:
EventState (void);
virtual ~EventState (void);
void setQuitFlag (bool quit);
bool getQuitFlag (void);
protected:
de::Mutex m_mutex;
bool m_quit;
private:
EventState (const EventState&);
EventState& operator= (const EventState&);
};
class DisplayBase
{
public:
DisplayBase (EventState& platform);
virtual ~DisplayBase (void);
virtual void processEvents (void) = 0;
protected:
EventState& m_eventState;
private:
DisplayBase (const DisplayBase&);
DisplayBase& operator= (const DisplayBase&);
};
class WindowBase
{
public:
WindowBase (void);
virtual ~WindowBase (void);
virtual void setVisibility (bool visible) = 0;
virtual void processEvents (void) = 0;
virtual DisplayBase& getDisplay (void) = 0;
virtual void getDimensions (int* width, int* height) const = 0;
virtual void setDimensions (int width, int height) = 0;
protected:
bool m_visible;
private:
WindowBase (const WindowBase&);
WindowBase& operator= (const WindowBase&);
};
class XlibDisplay : public DisplayBase
{
public:
XlibDisplay (EventState& platform, const char* name);
virtual ~XlibDisplay (void);
::Display* getXDisplay (void) { return m_display; }
Atom getDeleteAtom (void) { return m_deleteAtom; }
::Visual* getVisual (VisualID visualID);
bool getVisualInfo (VisualID visualID, XVisualInfo& dst);
void processEvents (void);
void processEvent (XEvent& event);
protected:
::Display* m_display;
Atom m_deleteAtom;
private:
XlibDisplay (const XlibDisplay&);
XlibDisplay& operator= (const XlibDisplay&);
};
class XlibWindow : public WindowBase
{
public:
XlibWindow (XlibDisplay& display, int width, int height,
::Visual* visual);
~XlibWindow (void);
void setVisibility (bool visible);
void processEvents (void);
DisplayBase& getDisplay (void) { return (DisplayBase&)m_display; }
::Window& getXID (void) { return m_window; }
void getDimensions (int* width, int* height) const;
void setDimensions (int width, int height);
protected:
XlibDisplay& m_display;
::Colormap m_colormap;
::Window m_window;
private:
XlibWindow (const XlibWindow&);
XlibWindow& operator= (const XlibWindow&);
};
} // x11
} // tcu
#endif // _TCUX11_HPP
| chadversary/deqp | framework/platform/X11/tcuX11.hpp | C++ | apache-2.0 | 3,554 |
/**
@author Admino Technologies Oy
Copyright 2013 Admino Technologies Oy. All rights reserved.
See LICENCE for conditions of distribution and use.
@file
@brief */
#pragma once
#include "CloudRenderingPluginApi.h"
#include "CloudRenderingPluginFwd.h"
#include "IModule.h"
class CLOUDRENDERING_API CloudRenderingPlugin : public IModule
{
Q_OBJECT
public:
CloudRenderingPlugin();
~CloudRenderingPlugin();
/// IModule override.
void Initialize();
/// IModule override.
void Uninitialize();
public slots:
WebRTCRendererPtr Renderer() const;
WebRTCClientPtr Client() const;
bool IsRenderer() const;
bool IsClient() const;
private:
QString LC;
WebRTCRendererPtr renderer_;
WebRTCClientPtr client_;
};
| Adminotech/fiware-cloud-rendering-renderer | CloudRenderingPlugin/CloudRenderingPlugin.h | C | apache-2.0 | 800 |
/*
* 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.
*/
#include "data/constructs/column.h"
#include <string>
#include "data/constructs/inputvalidation.h"
namespace cclient {
namespace data {
void Column::setColFamily(const char *r, uint32_t size) {
columnFamily = std::string(r, size);
}
void Column::setColQualifier(const char *r, uint32_t size) {
columnQualifier = std::string(r, size);
}
void Column::setColVisibility(const char *r, uint32_t size) {
columnVisibility = std::string(r, size);
}
Column::~Column() {}
bool Column::operator<(const Column &rhs) const {
int compare =
compareBytes(columnFamily.data(), 0, columnFamily.size(),
rhs.columnFamily.data(), 0, rhs.columnFamily.size());
if (compare < 0)
return true;
else if (compare > 0)
return false;
;
compare =
compareBytes(columnQualifier.data(), 0, columnQualifier.size(),
rhs.columnQualifier.data(), 0, rhs.columnQualifier.size());
if (compare < 0)
return true;
else if (compare > 0)
return false;
compare =
compareBytes(columnVisibility.data(), 0, columnVisibility.size(),
rhs.columnVisibility.data(), 0, rhs.columnVisibility.size());
if (compare < 0) return true;
return false;
}
bool Column::operator==(const Column &rhs) const {
int compare =
compareBytes(columnFamily.data(), 0, columnFamily.size(),
rhs.columnFamily.data(), 0, rhs.columnFamily.size());
if (compare != 0) return false;
compare =
compareBytes(columnQualifier.data(), 0, columnQualifier.size(),
rhs.columnQualifier.data(), 0, rhs.columnQualifier.size());
if (compare != 0) return false;
compare =
compareBytes(columnVisibility.data(), 0, columnVisibility.size(),
rhs.columnVisibility.data(), 0, rhs.columnVisibility.size());
if (compare != 0)
return false;
else
return true;
}
uint64_t Column::write(cclient::data::streams::OutputStream *outStream) {
if (columnFamily.empty()) {
outStream->writeBoolean(false);
} else {
outStream->writeBoolean(true);
outStream->writeBytes(columnFamily.data(), columnFamily.size());
}
if (columnQualifier.empty()) {
outStream->writeBoolean(false);
} else {
outStream->writeBoolean(true);
outStream->writeBytes(columnQualifier.data(), columnQualifier.size());
}
if (columnVisibility.empty()) {
return outStream->writeBoolean(false);
} else {
outStream->writeBoolean(true);
return outStream->writeBytes(columnVisibility.data(),
columnVisibility.size());
}
}
} // namespace data
} // namespace cclient
| phrocker/sharkbite | src/data/constructs/column.cpp | C++ | apache-2.0 | 3,199 |
package me.knox.zmz.mvp.model;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import java.util.List;
import javax.inject.Inject;
import me.knox.zmz.App;
import me.knox.zmz.entity.News;
import me.knox.zmz.mvp.contract.NewsListContract;
import me.knox.zmz.network.JsonResponse;
/**
* Created by KNOX.
*/
public class NewsListModel implements NewsListContract.Model {
@Inject public NewsListModel() {
// empty constructor for injection
}
@Override public Flowable<JsonResponse<List<News>>> getNewsList() {
return App.getInstance().getApi().getNews().observeOn(AndroidSchedulers.mainThread(), true);
}
}
| chowaikong/ZMZ | app/src/main/java/me/knox/zmz/mvp/model/NewsListModel.java | Java | apache-2.0 | 664 |
/*
* Copyright 2022 Imply Data, Inc.
*
* 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.
*/
import { ESLintUtils } from '@typescript-eslint/utils';
import { readonlyImplicitFields } from './readonly-implicit-fields';
const ruleTester = new ESLintUtils.RuleTester({
parser: '@typescript-eslint/parser',
});
ruleTester.run('readonly-implicit-fields', readonlyImplicitFields, {
valid: [
// Various valid cases inside of Immutable Classes
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare readonly foo: string;
private readonly baz: number;
public readonly qux: () => void;
public getBaz = () => this.baz;
public changeBaz = (baz: number) => this;
public doStuff(): string { return 'stuff'; }
}`,
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly foo: string;
public declare readonly foo: string;
private declare readonly foo: string;
}`,
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly getFoo: () => string;
public declare readonly getFoo: () => string;
private declare readonly getFoo: () => string;
}`,
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly changeFoo: (foo: string) => MyClass;
public declare readonly changeFoo: (foo: string) => MyClass;
private declare readonly changeFoo: (foo: string) => MyClass;
}`,
// Invalid cases but not inside of BaseImmutable inheritors
`class MyClass extends NotImmutable {
declare foo: string;
}`,
`class MyClass extends NotImmutable {
public declare foo: string;
}`,
`class MyClass extends NotImmutable {
private declare foo: string;
}`,
],
invalid: [
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare foo: string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare readonly foo: string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare foo: string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly foo: string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare foo: string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare readonly foo: string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare getFoo: () => string;
}`,
errors: [{ messageId: 'useReadonlyForAccessor', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare readonly getFoo: () => string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare getFoo: () => string;
}`,
errors: [{ messageId: 'useReadonlyForAccessor', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly getFoo: () => string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare getFoo: () => string;
}`,
errors: [{ messageId: 'useReadonlyForAccessor', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare readonly getFoo: () => string;
}`,
},
// Weird spacing
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public
declare foo : string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 4, column: 13 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public
declare readonly foo : string;
}`,
},
],
});
| implydata/immutable-class | packages/eslint-plugin-immutable-class/src/rules/readonly-implicit-fields.spec.ts | TypeScript | apache-2.0 | 5,020 |
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// 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.
package google.registry.model.tld;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Maps.toMap;
import static google.registry.config.RegistryConfig.getSingletonCacheRefreshDuration;
import static google.registry.model.common.EntityGroupRoot.getCrossTldKey;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static org.joda.money.CurrencyUnit.USD;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.net.InternetDomainName;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Mapify;
import com.googlecode.objectify.annotation.OnSave;
import com.googlecode.objectify.annotation.Parent;
import google.registry.model.Buildable;
import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject;
import google.registry.model.UnsafeSerializable;
import google.registry.model.annotations.InCrossTld;
import google.registry.model.annotations.ReportedOn;
import google.registry.model.common.EntityGroupRoot;
import google.registry.model.common.TimedTransitionProperty;
import google.registry.model.common.TimedTransitionProperty.TimedTransition;
import google.registry.model.domain.fee.BaseFee.FeeType;
import google.registry.model.domain.fee.Fee;
import google.registry.model.replay.DatastoreAndSqlEntity;
import google.registry.model.tld.label.PremiumList;
import google.registry.model.tld.label.ReservedList;
import google.registry.persistence.VKey;
import google.registry.persistence.converter.JodaMoneyType;
import google.registry.util.Idn;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.PostLoad;
import javax.persistence.Transient;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Type;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.joda.time.Duration;
/** Persisted per-TLD configuration data. */
@ReportedOn
@Entity
@javax.persistence.Entity(name = "Tld")
@InCrossTld
public class Registry extends ImmutableObject
implements Buildable, DatastoreAndSqlEntity, UnsafeSerializable {
@Parent @Transient Key<EntityGroupRoot> parent = getCrossTldKey();
/**
* The canonical string representation of the TLD associated with this {@link Registry}, which is
* the standard ASCII for regular TLDs and punycoded ASCII for IDN TLDs.
*/
@Id
@javax.persistence.Id
@Column(name = "tld_name", nullable = false)
String tldStrId;
/**
* A duplicate of {@link #tldStrId}, to simplify BigQuery reporting since the id field becomes
* {@code __key__.name} rather than being exported as a named field.
*/
@Transient String tldStr;
/** Sets the Datastore specific field, tldStr, when the entity is loaded from Cloud SQL */
@PostLoad
void postLoad() {
tldStr = tldStrId;
}
/** The suffix that identifies roids as belonging to this specific tld, e.g. -HOW for .how. */
String roidSuffix;
/** Default values for all the relevant TLD parameters. */
public static final TldState DEFAULT_TLD_STATE = TldState.PREDELEGATION;
public static final boolean DEFAULT_ESCROW_ENABLED = false;
public static final boolean DEFAULT_DNS_PAUSED = false;
public static final Duration DEFAULT_ADD_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_AUTO_RENEW_GRACE_PERIOD = Duration.standardDays(45);
public static final Duration DEFAULT_REDEMPTION_GRACE_PERIOD = Duration.standardDays(30);
public static final Duration DEFAULT_RENEW_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_TRANSFER_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_AUTOMATIC_TRANSFER_LENGTH = Duration.standardDays(5);
public static final Duration DEFAULT_PENDING_DELETE_LENGTH = Duration.standardDays(5);
public static final Duration DEFAULT_ANCHOR_TENANT_ADD_GRACE_PERIOD = Duration.standardDays(30);
public static final CurrencyUnit DEFAULT_CURRENCY = USD;
public static final Money DEFAULT_CREATE_BILLING_COST = Money.of(USD, 8);
public static final Money DEFAULT_EAP_BILLING_COST = Money.of(USD, 0);
public static final Money DEFAULT_RENEW_BILLING_COST = Money.of(USD, 8);
public static final Money DEFAULT_RESTORE_BILLING_COST = Money.of(USD, 100);
public static final Money DEFAULT_SERVER_STATUS_CHANGE_BILLING_COST = Money.of(USD, 20);
public static final Money DEFAULT_REGISTRY_LOCK_OR_UNLOCK_BILLING_COST = Money.of(USD, 0);
/** The type of TLD, which determines things like backups and escrow policy. */
public enum TldType {
/** A real, official TLD. */
REAL,
/** A test TLD, for the prober. */
TEST
}
/**
* The states a TLD can be in at any given point in time. The ordering below is the required
* sequence of states (ignoring {@link #PDT} which is a pseudo-state).
*/
public enum TldState {
/** The state of not yet being delegated to this registry in the root zone by IANA. */
PREDELEGATION,
/**
* The state in which only trademark holders can submit a "create" request. It is identical to
* {@link #GENERAL_AVAILABILITY} in all other respects.
*/
START_DATE_SUNRISE,
/**
* A state in which no domain operations are permitted. Generally used between sunrise and
* general availability. This state is special in that it has no ordering constraints and can
* appear after any phase.
*/
QUIET_PERIOD,
/**
* The steady state of a TLD in which all domain names are available via first-come,
* first-serve.
*/
GENERAL_AVAILABILITY,
/** A "fake" state for use in predelegation testing. Acts like {@link #GENERAL_AVAILABILITY}. */
PDT
}
/**
* A transition to a TLD state at a specific time, for use in a TimedTransitionProperty. Public
* because App Engine's security manager requires this for instantiation via reflection.
*/
@Embed
public static class TldStateTransition extends TimedTransition<TldState> {
/** The TLD state. */
private TldState tldState;
@Override
public TldState getValue() {
return tldState;
}
@Override
protected void setValue(TldState tldState) {
this.tldState = tldState;
}
}
/**
* A transition to a given billing cost at a specific time, for use in a TimedTransitionProperty.
*
* <p>Public because App Engine's security manager requires this for instantiation via reflection.
*/
@Embed
public static class BillingCostTransition extends TimedTransition<Money> {
/** The billing cost value. */
private Money billingCost;
@Override
public Money getValue() {
return billingCost;
}
@Override
protected void setValue(Money billingCost) {
this.billingCost = billingCost;
}
}
/** Returns the registry for a given TLD, throwing if none exists. */
public static Registry get(String tld) {
Registry registry = CACHE.getUnchecked(tld).orElse(null);
if (registry == null) {
throw new RegistryNotFoundException(tld);
}
return registry;
}
/** Returns the registry entities for the given TLD strings, throwing if any don't exist. */
static ImmutableSet<Registry> getAll(Set<String> tlds) {
try {
ImmutableMap<String, Optional<Registry>> registries = CACHE.getAll(tlds);
ImmutableSet<String> missingRegistries =
registries.entrySet().stream()
.filter(e -> !e.getValue().isPresent())
.map(Map.Entry::getKey)
.collect(toImmutableSet());
if (missingRegistries.isEmpty()) {
return registries.values().stream().map(Optional::get).collect(toImmutableSet());
} else {
throw new RegistryNotFoundException(missingRegistries);
}
} catch (ExecutionException e) {
throw new RuntimeException("Unexpected error retrieving TLDs " + tlds, e);
}
}
/**
* Invalidates the cache entry.
*
* <p>This is called automatically when the registry is saved. One should also call it when a
* registry is deleted.
*/
@OnSave
public void invalidateInCache() {
CACHE.invalidate(tldStr);
}
/** A cache that loads the {@link Registry} for a given tld. */
private static final LoadingCache<String, Optional<Registry>> CACHE =
CacheBuilder.newBuilder()
.expireAfterWrite(
java.time.Duration.ofMillis(getSingletonCacheRefreshDuration().getMillis()))
.build(
new CacheLoader<String, Optional<Registry>>() {
@Override
public Optional<Registry> load(final String tld) {
// Enter a transaction-less context briefly; we don't want to enroll every TLD in
// a transaction that might be wrapping this call.
return tm().doTransactionless(() -> tm().loadByKeyIfPresent(createVKey(tld)));
}
@Override
public Map<String, Optional<Registry>> loadAll(Iterable<? extends String> tlds) {
ImmutableMap<String, VKey<Registry>> keysMap =
toMap(ImmutableSet.copyOf(tlds), Registry::createVKey);
Map<VKey<? extends Registry>, Registry> entities =
tm().doTransactionless(() -> tm().loadByKeys(keysMap.values()));
return Maps.transformEntries(
keysMap, (k, v) -> Optional.ofNullable(entities.getOrDefault(v, null)));
}
});
public static VKey<Registry> createVKey(String tld) {
return VKey.create(Registry.class, tld, Key.create(getCrossTldKey(), Registry.class, tld));
}
public static VKey<Registry> createVKey(Key<Registry> key) {
return createVKey(key.getName());
}
/**
* The name of the pricing engine that this TLD uses.
*
* <p>This must be a valid key for the map of pricing engines injected by {@code @Inject
* Map<String, PricingEngine>}.
*
* <p>Note that it used to be the canonical class name, hence the name of this field, but this
* restriction has since been relaxed and it may now be any unique string.
*/
String pricingEngineClassName;
/**
* The set of name(s) of the {@code DnsWriter} implementations that this TLD uses.
*
* <p>There must be at least one entry in this set.
*
* <p>All entries of this list must be valid keys for the map of {@code DnsWriter}s injected by
* {@code @Inject Map<String, DnsWriter>}
*/
@Column(nullable = false)
Set<String> dnsWriters;
/**
* The number of locks we allow at once for {@link google.registry.dns.PublishDnsUpdatesAction}.
*
* <p>This should always be a positive integer- use 1 for TLD-wide locks. All {@link Registry}
* objects have this value default to 1.
*
* <p>WARNING: changing this parameter changes the lock name for subsequent DNS updates, and thus
* invalidates the locking scheme for enqueued DNS publish updates. If the {@link
* google.registry.dns.writer.DnsWriter} you use is not parallel-write tolerant, you must follow
* this procedure to change this value:
*
* <ol>
* <li>Pause the DNS queue via {@link google.registry.tools.UpdateTldCommand}
* <li>Change this number
* <li>Let the Registry caches expire (currently 5 minutes) and drain the DNS publish queue
* <li>Unpause the DNS queue
* </ol>
*
* <p>Failure to do so can result in parallel writes to the {@link
* google.registry.dns.writer.DnsWriter}, which may be dangerous depending on your implementation.
*/
@Column(nullable = false)
int numDnsPublishLocks;
/** Updates an unset numDnsPublishLocks (0) to the standard default of 1. */
void setDefaultNumDnsPublishLocks() {
if (numDnsPublishLocks == 0) {
numDnsPublishLocks = 1;
}
}
/**
* The unicode-aware representation of the TLD associated with this {@link Registry}.
*
* <p>This will be equal to {@link #tldStr} for ASCII TLDs, but will be non-ASCII for IDN TLDs. We
* store this in a field so that it will be retained upon import into BigQuery.
*/
@Column(nullable = false)
String tldUnicode;
/**
* Id of the folder in drive used to public (export) information for this TLD.
*
* <p>This is optional; if not configured, then information won't be exported for this TLD.
*/
@Nullable String driveFolderId;
/** The type of the TLD, whether it's real or for testing. */
@Column(nullable = false)
@Enumerated(EnumType.STRING)
TldType tldType = TldType.REAL;
/**
* Whether to enable invoicing for this TLD.
*
* <p>Note that this boolean is the sole determiner on whether invoices should be generated for a
* TLD. This applies to {@link TldType#TEST} TLDs as well.
*/
@Column(nullable = false)
boolean invoicingEnabled = false;
/**
* A property that transitions to different TldStates at different times. Stored as a list of
* TldStateTransition embedded objects using the @Mapify annotation.
*/
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<TldState, TldStateTransition> tldStateTransitions =
TimedTransitionProperty.forMapify(DEFAULT_TLD_STATE, TldStateTransition.class);
/** An automatically managed creation timestamp. */
@Column(nullable = false)
CreateAutoTimestamp creationTime = CreateAutoTimestamp.create(null);
/** The set of reserved list names that are applicable to this registry. */
@Column(name = "reserved_list_names")
Set<String> reservedListNames;
/**
* Retrieves an ImmutableSet of all ReservedLists associated with this TLD.
*
* <p>This set contains only the names of the list and not a reference to the lists. Updates to a
* reserved list in Cloud SQL are saved as a new ReservedList entity. When using the ReservedList
* for a registry, the database should be queried for the entity with this name that has the
* largest revision ID.
*/
public ImmutableSet<String> getReservedListNames() {
return nullToEmptyImmutableCopy(reservedListNames);
}
/**
* The name of the {@link PremiumList} for this TLD, if there is one.
*
* <p>This is only the name of the list and not a reference to the list. Updates to the premium
* list in Cloud SQL are saved as a new PremiumList entity. When using the PremiumList for a
* registry, the database should be queried for the entity with this name that has the largest
* revision ID.
*/
@Column(name = "premium_list_name", nullable = true)
String premiumListName;
/** Should RDE upload a nightly escrow deposit for this TLD? */
@Column(nullable = false)
boolean escrowEnabled = DEFAULT_ESCROW_ENABLED;
/** Whether the pull queue that writes to authoritative DNS is paused for this TLD. */
@Column(nullable = false)
boolean dnsPaused = DEFAULT_DNS_PAUSED;
/**
* The length of the add grace period for this TLD.
*
* <p>Domain deletes are free and effective immediately so long as they take place within this
* amount of time following creation.
*/
@Column(nullable = false)
Duration addGracePeriodLength = DEFAULT_ADD_GRACE_PERIOD;
/** The length of the anchor tenant add grace period for this TLD. */
@Column(nullable = false)
Duration anchorTenantAddGracePeriodLength = DEFAULT_ANCHOR_TENANT_ADD_GRACE_PERIOD;
/** The length of the auto renew grace period for this TLD. */
@Column(nullable = false)
Duration autoRenewGracePeriodLength = DEFAULT_AUTO_RENEW_GRACE_PERIOD;
/** The length of the redemption grace period for this TLD. */
@Column(nullable = false)
Duration redemptionGracePeriodLength = DEFAULT_REDEMPTION_GRACE_PERIOD;
/** The length of the renew grace period for this TLD. */
@Column(nullable = false)
Duration renewGracePeriodLength = DEFAULT_RENEW_GRACE_PERIOD;
/** The length of the transfer grace period for this TLD. */
@Column(nullable = false)
Duration transferGracePeriodLength = DEFAULT_TRANSFER_GRACE_PERIOD;
/** The length of time before a transfer is automatically approved for this TLD. */
@Column(nullable = false)
Duration automaticTransferLength = DEFAULT_AUTOMATIC_TRANSFER_LENGTH;
/** The length of time a domain spends in the non-redeemable pending delete phase for this TLD. */
@Column(nullable = false)
Duration pendingDeleteLength = DEFAULT_PENDING_DELETE_LENGTH;
/** The currency unit for all costs associated with this TLD. */
@Column(nullable = false)
CurrencyUnit currency = DEFAULT_CURRENCY;
/** The per-year billing cost for registering a new domain name. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "create_billing_cost_amount"),
@Column(name = "create_billing_cost_currency")
})
Money createBillingCost = DEFAULT_CREATE_BILLING_COST;
/** The one-time billing cost for restoring a domain name from the redemption grace period. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "restore_billing_cost_amount"),
@Column(name = "restore_billing_cost_currency")
})
Money restoreBillingCost = DEFAULT_RESTORE_BILLING_COST;
/** The one-time billing cost for changing the server status (i.e. lock). */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "server_status_change_billing_cost_amount"),
@Column(name = "server_status_change_billing_cost_currency")
})
Money serverStatusChangeBillingCost = DEFAULT_SERVER_STATUS_CHANGE_BILLING_COST;
/** The one-time billing cost for a registry lock/unlock action initiated by a registrar. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "registry_lock_or_unlock_cost_amount"),
@Column(name = "registry_lock_or_unlock_cost_currency")
})
Money registryLockOrUnlockBillingCost = DEFAULT_REGISTRY_LOCK_OR_UNLOCK_BILLING_COST;
/**
* A property that transitions to different renew billing costs at different times. Stored as a
* list of BillingCostTransition embedded objects using the @Mapify annotation.
*
* <p>A given value of this property represents the per-year billing cost for renewing a domain
* name. This cost is also used to compute costs for transfers, since each transfer includes a
* renewal to ensure transfers have a cost.
*/
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<Money, BillingCostTransition> renewBillingCostTransitions =
TimedTransitionProperty.forMapify(DEFAULT_RENEW_BILLING_COST, BillingCostTransition.class);
/** A property that tracks the EAP fee schedule (if any) for the TLD. */
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<Money, BillingCostTransition> eapFeeSchedule =
TimedTransitionProperty.forMapify(DEFAULT_EAP_BILLING_COST, BillingCostTransition.class);
/** Marksdb LORDN service username (password is stored in Keyring) */
String lordnUsername;
/** The end of the claims period (at or after this time, claims no longer applies). */
@Column(nullable = false)
DateTime claimsPeriodEnd = END_OF_TIME;
/** An allow list of clients allowed to be used on domains on this TLD (ignored if empty). */
@Nullable Set<String> allowedRegistrantContactIds;
/** An allow list of hosts allowed to be used on domains on this TLD (ignored if empty). */
@Nullable Set<String> allowedFullyQualifiedHostNames;
public String getTldStr() {
return tldStr;
}
public String getRoidSuffix() {
return roidSuffix;
}
/** Retrieve the actual domain name representing the TLD for which this registry operates. */
public InternetDomainName getTld() {
return InternetDomainName.from(tldStr);
}
/** Retrieve the TLD type (real or test). */
public TldType getTldType() {
return tldType;
}
/**
* Retrieve the TLD state at the given time. Defaults to {@link TldState#PREDELEGATION}.
*
* <p>Note that {@link TldState#PDT} TLDs pretend to be in {@link TldState#GENERAL_AVAILABILITY}.
*/
public TldState getTldState(DateTime now) {
TldState state = tldStateTransitions.getValueAtTime(now);
return TldState.PDT.equals(state) ? TldState.GENERAL_AVAILABILITY : state;
}
/** Retrieve whether this TLD is in predelegation testing. */
public boolean isPdt(DateTime now) {
return TldState.PDT.equals(tldStateTransitions.getValueAtTime(now));
}
public DateTime getCreationTime() {
return creationTime.getTimestamp();
}
public boolean getEscrowEnabled() {
return escrowEnabled;
}
public boolean getDnsPaused() {
return dnsPaused;
}
public String getDriveFolderId() {
return driveFolderId;
}
public Duration getAddGracePeriodLength() {
return addGracePeriodLength;
}
public Duration getAutoRenewGracePeriodLength() {
return autoRenewGracePeriodLength;
}
public Duration getRedemptionGracePeriodLength() {
return redemptionGracePeriodLength;
}
public Duration getRenewGracePeriodLength() {
return renewGracePeriodLength;
}
public Duration getTransferGracePeriodLength() {
return transferGracePeriodLength;
}
public Duration getAutomaticTransferLength() {
return automaticTransferLength;
}
public Duration getPendingDeleteLength() {
return pendingDeleteLength;
}
public Duration getAnchorTenantAddGracePeriodLength() {
return anchorTenantAddGracePeriodLength;
}
public Optional<String> getPremiumListName() {
return Optional.ofNullable(premiumListName);
}
public CurrencyUnit getCurrency() {
return currency;
}
/**
* Use <code>PricingEngineProxy.getDomainCreateCost</code> instead of this to find the cost for a
* domain create.
*/
@VisibleForTesting
public Money getStandardCreateCost() {
return createBillingCost;
}
/**
* Returns the add-on cost of a domain restore (the flat registry-wide fee charged in addition to
* one year of renewal for that name).
*/
public Money getStandardRestoreCost() {
return restoreBillingCost;
}
/**
* Use <code>PricingEngineProxy.getDomainRenewCost</code> instead of this to find the cost for a
* domain renewal, and all derived costs (i.e. autorenews, transfers, and the per-domain part of a
* restore cost).
*/
public Money getStandardRenewCost(DateTime now) {
return renewBillingCostTransitions.getValueAtTime(now);
}
/** Returns the cost of a server status change (i.e. lock). */
public Money getServerStatusChangeCost() {
return serverStatusChangeBillingCost;
}
/** Returns the cost of a registry lock/unlock. */
public Money getRegistryLockOrUnlockBillingCost() {
return registryLockOrUnlockBillingCost;
}
public ImmutableSortedMap<DateTime, TldState> getTldStateTransitions() {
return tldStateTransitions.toValueMap();
}
public ImmutableSortedMap<DateTime, Money> getRenewBillingCostTransitions() {
return renewBillingCostTransitions.toValueMap();
}
/** Returns the EAP fee for the registry at the given time. */
public Fee getEapFeeFor(DateTime now) {
ImmutableSortedMap<DateTime, Money> valueMap = getEapFeeScheduleAsMap();
DateTime periodStart = valueMap.floorKey(now);
DateTime periodEnd = valueMap.ceilingKey(now);
// NOTE: assuming END_OF_TIME would never be reached...
Range<DateTime> validPeriod =
Range.closedOpen(
periodStart != null ? periodStart : START_OF_TIME,
periodEnd != null ? periodEnd : END_OF_TIME);
return Fee.create(
eapFeeSchedule.getValueAtTime(now).getAmount(),
FeeType.EAP,
// An EAP fee does not count as premium -- it's a separate one-time fee, independent of
// which the domain is separately considered standard vs premium depending on renewal price.
false,
validPeriod,
validPeriod.upperEndpoint());
}
@VisibleForTesting
public ImmutableSortedMap<DateTime, Money> getEapFeeScheduleAsMap() {
return eapFeeSchedule.toValueMap();
}
public String getLordnUsername() {
return lordnUsername;
}
public DateTime getClaimsPeriodEnd() {
return claimsPeriodEnd;
}
public String getPremiumPricingEngineClassName() {
return pricingEngineClassName;
}
public ImmutableSet<String> getDnsWriters() {
return ImmutableSet.copyOf(dnsWriters);
}
/** Returns the number of simultaneous DNS publish operations we allow at once. */
public int getNumDnsPublishLocks() {
return numDnsPublishLocks;
}
public ImmutableSet<String> getAllowedRegistrantContactIds() {
return nullToEmptyImmutableCopy(allowedRegistrantContactIds);
}
public ImmutableSet<String> getAllowedFullyQualifiedHostNames() {
return nullToEmptyImmutableCopy(allowedFullyQualifiedHostNames);
}
@Override
public Builder asBuilder() {
return new Builder(clone(this));
}
/** A builder for constructing {@link Registry} objects, since they are immutable. */
public static class Builder extends Buildable.Builder<Registry> {
public Builder() {}
private Builder(Registry instance) {
super(instance);
}
public Builder setTldType(TldType tldType) {
getInstance().tldType = tldType;
return this;
}
public Builder setInvoicingEnabled(boolean invoicingEnabled) {
getInstance().invoicingEnabled = invoicingEnabled;
return this;
}
/** Sets the TLD state to transition to the specified states at the specified times. */
public Builder setTldStateTransitions(ImmutableSortedMap<DateTime, TldState> tldStatesMap) {
checkNotNull(tldStatesMap, "TLD states map cannot be null");
// Filter out any entries with QUIET_PERIOD as the value before checking for ordering, since
// that phase is allowed to appear anywhere.
checkArgument(
Ordering.natural()
.isStrictlyOrdered(
Iterables.filter(tldStatesMap.values(), not(equalTo(TldState.QUIET_PERIOD)))),
"The TLD states are chronologically out of order");
getInstance().tldStateTransitions =
TimedTransitionProperty.fromValueMap(tldStatesMap, TldStateTransition.class);
return this;
}
public Builder setTldStr(String tldStr) {
checkArgument(tldStr != null, "TLD must not be null");
getInstance().tldStr = tldStr;
return this;
}
public Builder setEscrowEnabled(boolean enabled) {
getInstance().escrowEnabled = enabled;
return this;
}
public Builder setDnsPaused(boolean paused) {
getInstance().dnsPaused = paused;
return this;
}
public Builder setDriveFolderId(String driveFolderId) {
getInstance().driveFolderId = driveFolderId;
return this;
}
public Builder setPremiumPricingEngine(String pricingEngineClass) {
getInstance().pricingEngineClassName = checkArgumentNotNull(pricingEngineClass);
return this;
}
public Builder setDnsWriters(ImmutableSet<String> dnsWriters) {
getInstance().dnsWriters = dnsWriters;
return this;
}
public Builder setNumDnsPublishLocks(int numDnsPublishLocks) {
checkArgument(
numDnsPublishLocks > 0,
"numDnsPublishLocks must be positive when set explicitly (use 1 for TLD-wide locks)");
getInstance().numDnsPublishLocks = numDnsPublishLocks;
return this;
}
public Builder setAddGracePeriodLength(Duration addGracePeriodLength) {
checkArgument(
addGracePeriodLength.isLongerThan(Duration.ZERO),
"addGracePeriodLength must be non-zero");
getInstance().addGracePeriodLength = addGracePeriodLength;
return this;
}
/** Warning! Changing this will affect the billing time of autorenew events in the past. */
public Builder setAutoRenewGracePeriodLength(Duration autoRenewGracePeriodLength) {
checkArgument(
autoRenewGracePeriodLength.isLongerThan(Duration.ZERO),
"autoRenewGracePeriodLength must be non-zero");
getInstance().autoRenewGracePeriodLength = autoRenewGracePeriodLength;
return this;
}
public Builder setRedemptionGracePeriodLength(Duration redemptionGracePeriodLength) {
checkArgument(
redemptionGracePeriodLength.isLongerThan(Duration.ZERO),
"redemptionGracePeriodLength must be non-zero");
getInstance().redemptionGracePeriodLength = redemptionGracePeriodLength;
return this;
}
public Builder setRenewGracePeriodLength(Duration renewGracePeriodLength) {
checkArgument(
renewGracePeriodLength.isLongerThan(Duration.ZERO),
"renewGracePeriodLength must be non-zero");
getInstance().renewGracePeriodLength = renewGracePeriodLength;
return this;
}
public Builder setTransferGracePeriodLength(Duration transferGracePeriodLength) {
checkArgument(
transferGracePeriodLength.isLongerThan(Duration.ZERO),
"transferGracePeriodLength must be non-zero");
getInstance().transferGracePeriodLength = transferGracePeriodLength;
return this;
}
public Builder setAutomaticTransferLength(Duration automaticTransferLength) {
checkArgument(
automaticTransferLength.isLongerThan(Duration.ZERO),
"automaticTransferLength must be non-zero");
getInstance().automaticTransferLength = automaticTransferLength;
return this;
}
public Builder setPendingDeleteLength(Duration pendingDeleteLength) {
checkArgument(
pendingDeleteLength.isLongerThan(Duration.ZERO), "pendingDeleteLength must be non-zero");
getInstance().pendingDeleteLength = pendingDeleteLength;
return this;
}
public Builder setCurrency(CurrencyUnit currency) {
checkArgument(currency != null, "currency must be non-null");
getInstance().currency = currency;
return this;
}
public Builder setCreateBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "createBillingCost cannot be negative");
getInstance().createBillingCost = amount;
return this;
}
public Builder setReservedListsByName(Set<String> reservedListNames) {
checkArgument(reservedListNames != null, "reservedListNames must not be null");
ImmutableSet.Builder<ReservedList> builder = new ImmutableSet.Builder<>();
for (String reservedListName : reservedListNames) {
// Check for existence of the reserved list and throw an exception if it doesn't exist.
Optional<ReservedList> reservedList = ReservedList.get(reservedListName);
checkArgument(
reservedList.isPresent(),
"Could not find reserved list %s to add to the tld",
reservedListName);
builder.add(reservedList.get());
}
return setReservedLists(builder.build());
}
public Builder setReservedLists(ReservedList... reservedLists) {
return setReservedLists(ImmutableSet.copyOf(reservedLists));
}
public Builder setReservedLists(Set<ReservedList> reservedLists) {
checkArgumentNotNull(reservedLists, "reservedLists must not be null");
ImmutableSet.Builder<String> nameBuilder = new ImmutableSet.Builder<>();
for (ReservedList reservedList : reservedLists) {
nameBuilder.add(reservedList.getName());
}
getInstance().reservedListNames = nameBuilder.build();
return this;
}
public Builder setPremiumList(@Nullable PremiumList premiumList) {
getInstance().premiumListName = (premiumList == null) ? null : premiumList.getName();
return this;
}
public Builder setRestoreBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "restoreBillingCost cannot be negative");
getInstance().restoreBillingCost = amount;
return this;
}
/**
* Sets the renew billing cost to transition to the specified values at the specified times.
*
* <p>Renew billing costs transitions should only be added at least 5 days (the length of an
* automatic transfer) in advance, to avoid discrepancies between the cost stored with the
* billing event (created when the transfer is requested) and the cost at the time when the
* transfer actually occurs (5 days later).
*/
public Builder setRenewBillingCostTransitions(
ImmutableSortedMap<DateTime, Money> renewCostsMap) {
checkArgumentNotNull(renewCostsMap, "Renew billing costs map cannot be null");
checkArgument(
renewCostsMap.values().stream().allMatch(Money::isPositiveOrZero),
"Renew billing cost cannot be negative");
getInstance().renewBillingCostTransitions =
TimedTransitionProperty.fromValueMap(renewCostsMap, BillingCostTransition.class);
return this;
}
/** Sets the EAP fee schedule for the TLD. */
public Builder setEapFeeSchedule(ImmutableSortedMap<DateTime, Money> eapFeeSchedule) {
checkArgumentNotNull(eapFeeSchedule, "EAP schedule map cannot be null");
checkArgument(
eapFeeSchedule.values().stream().allMatch(Money::isPositiveOrZero),
"EAP fee cannot be negative");
getInstance().eapFeeSchedule =
TimedTransitionProperty.fromValueMap(eapFeeSchedule, BillingCostTransition.class);
return this;
}
private static final Pattern ROID_SUFFIX_PATTERN = Pattern.compile("^[A-Z0-9_]{1,8}$");
public Builder setRoidSuffix(String roidSuffix) {
checkArgument(
ROID_SUFFIX_PATTERN.matcher(roidSuffix).matches(),
"ROID suffix must be in format %s",
ROID_SUFFIX_PATTERN.pattern());
getInstance().roidSuffix = roidSuffix;
return this;
}
public Builder setServerStatusChangeBillingCost(Money amount) {
checkArgument(
amount.isPositiveOrZero(), "Server status change billing cost cannot be negative");
getInstance().serverStatusChangeBillingCost = amount;
return this;
}
public Builder setRegistryLockOrUnlockBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "Registry lock/unlock cost cannot be negative");
getInstance().registryLockOrUnlockBillingCost = amount;
return this;
}
public Builder setLordnUsername(String username) {
getInstance().lordnUsername = username;
return this;
}
public Builder setClaimsPeriodEnd(DateTime claimsPeriodEnd) {
getInstance().claimsPeriodEnd = checkArgumentNotNull(claimsPeriodEnd);
return this;
}
public Builder setAllowedRegistrantContactIds(
ImmutableSet<String> allowedRegistrantContactIds) {
getInstance().allowedRegistrantContactIds = allowedRegistrantContactIds;
return this;
}
public Builder setAllowedFullyQualifiedHostNames(
ImmutableSet<String> allowedFullyQualifiedHostNames) {
getInstance().allowedFullyQualifiedHostNames = allowedFullyQualifiedHostNames;
return this;
}
@Override
public Registry build() {
final Registry instance = getInstance();
// Pick up the name of the associated TLD from the instance object.
String tldName = instance.tldStr;
checkArgument(tldName != null, "No registry TLD specified");
// Check for canonical form by converting to an InternetDomainName and then back.
checkArgument(
InternetDomainName.isValid(tldName)
&& tldName.equals(InternetDomainName.from(tldName).toString()),
"Cannot create registry for TLD that is not a valid, canonical domain name");
// Check the validity of all TimedTransitionProperties to ensure that they have values for
// START_OF_TIME. The setters above have already checked this for new values, but also check
// here to catch cases where we loaded an invalid TimedTransitionProperty from Datastore and
// cloned it into a new builder, to block re-building a Registry in an invalid state.
instance.tldStateTransitions.checkValidity();
instance.renewBillingCostTransitions.checkValidity();
instance.eapFeeSchedule.checkValidity();
// All costs must be in the expected currency.
// TODO(b/21854155): When we move PremiumList into Datastore, verify its currency too.
checkArgument(
instance.getStandardCreateCost().getCurrencyUnit().equals(instance.currency),
"Create cost must be in the registry's currency");
checkArgument(
instance.getStandardRestoreCost().getCurrencyUnit().equals(instance.currency),
"Restore cost must be in the registry's currency");
checkArgument(
instance.getServerStatusChangeCost().getCurrencyUnit().equals(instance.currency),
"Server status change cost must be in the registry's currency");
checkArgument(
instance.getRegistryLockOrUnlockBillingCost().getCurrencyUnit().equals(instance.currency),
"Registry lock/unlock cost must be in the registry's currency");
Predicate<Money> currencyCheck =
(Money money) -> money.getCurrencyUnit().equals(instance.currency);
checkArgument(
instance.getRenewBillingCostTransitions().values().stream().allMatch(currencyCheck),
"Renew cost must be in the registry's currency");
checkArgument(
instance.eapFeeSchedule.toValueMap().values().stream().allMatch(currencyCheck),
"All EAP fees must be in the registry's currency");
checkArgumentNotNull(
instance.pricingEngineClassName, "All registries must have a configured pricing engine");
checkArgument(
instance.dnsWriters != null && !instance.dnsWriters.isEmpty(),
"At least one DNS writer must be specified."
+ " VoidDnsWriter can be used if DNS writing isn't desired");
// If not set explicitly, numDnsPublishLocks defaults to 1.
instance.setDefaultNumDnsPublishLocks();
checkArgument(
instance.numDnsPublishLocks > 0,
"Number of DNS publish locks must be positive. Use 1 for TLD-wide locks.");
instance.tldStrId = tldName;
instance.tldUnicode = Idn.toUnicode(tldName);
return super.build();
}
}
/** Exception to throw when no Registry entity is found for given TLD string(s). */
public static class RegistryNotFoundException extends RuntimeException {
RegistryNotFoundException(ImmutableSet<String> tlds) {
super("No registry object(s) found for " + Joiner.on(", ").join(tlds));
}
RegistryNotFoundException(String tld) {
this(ImmutableSet.of(tld));
}
}
}
| google/nomulus | core/src/main/java/google/registry/model/tld/Registry.java | Java | apache-2.0 | 40,835 |
import java.util.Scanner;
/**
* @author Oleg Cherednik
* @since 27.10.2017
*/
public class Solution {
static int[] leftRotation(int[] a, int d) {
for (int i = 0, j = a.length - 1; i < j; i++, j--)
swap(a, i, j);
d %= a.length;
if (d > 0) {
d = a.length - d;
for (int i = 0, j = d - 1; i < j; i++, j--)
swap(a, i, j);
for (int i = d, j = a.length - 1; i < j; i++, j--)
swap(a, i, j);
}
return a;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d = in.nextInt();
int[] a = new int[n];
for (int a_i = 0; a_i < n; a_i++) {
a[a_i] = in.nextInt();
}
int[] result = leftRotation(a, d);
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + (i != result.length - 1 ? " " : ""));
}
System.out.println("");
in.close();
}
}
| oleg-cherednik/hackerrank | Data Structures/Arrays/Left Rotation/Solution.java | Java | apache-2.0 | 1,184 |
package com.pmis.manage.dao;
import org.springframework.stereotype.Component;
import com.pmis.common.dao.CommonDao;
@Component
public class UserInfoDao extends CommonDao{
}
| twosunnus/zhcy | src/com/pmis/manage/dao/UserInfoDao.java | Java | apache-2.0 | 193 |
/**
* Licensed to Odiago, Inc. under one or more contributor license
* agreements. See the NOTICE.txt file distributed with this work for
* additional information regarding copyright ownership. Odiago, Inc.
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.odiago.flumebase.lang;
import java.util.Collections;
import java.util.List;
/**
* Abstract base class that defines a callable function. Subclasses
* of this exist for scalar, aggregate, and table functions.
*/
public abstract class Function {
/**
* @return the Type of the object returned by the function.
*/
public abstract Type getReturnType();
/**
* @return an ordered list containing the types expected for all mandatory arguments.
*/
public abstract List<Type> getArgumentTypes();
/**
* @return an ordered list containing types expected for variable argument lists.
* If a function takes a variable-length argument list, the varargs must be arranged
* in groups matching the size of the list returned by this method. e.g., to accept
* an arbitrary number of strings, this should return a singleton list of type STRING.
* If pairs of strings and ints are required, this should return a list [STRING, INT].
*/
public List<Type> getVarArgTypes() {
return Collections.emptyList();
}
/**
* Determines whether arguments are promoted to their specified types by
* the runtime. If this returns true, actual arguments are promoted to
* new values that match the types specified in getArgumentTypes().
* If false, the expressions are simply type-checked to ensure that there
* is a valid promotion, but are passed in as-is. The default value of
* this method is true.
*/
public boolean autoPromoteArguments() {
return true;
}
}
| flumebase/flumebase | src/main/java/com/odiago/flumebase/lang/Function.java | Java | apache-2.0 | 2,315 |
/**
* Copyright 2016 Netflix, Inc.
*
* 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.
*/
package io.reactivex.internal.operators.maybe;
import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableHelper;
/**
* Turns an onSuccess into an onComplete, onError and onComplete is relayed as is.
*
* @param <T> the value type
*/
public final class MaybeIgnoreElement<T> extends AbstractMaybeWithUpstream<T, T> {
public MaybeIgnoreElement(MaybeSource<T> source) {
super(source);
}
@Override
protected void subscribeActual(MaybeObserver<? super T> observer) {
source.subscribe(new IgnoreMaybeObserver<T>(observer));
}
static final class IgnoreMaybeObserver<T> implements MaybeObserver<T>, Disposable {
final MaybeObserver<? super T> actual;
Disposable d;
IgnoreMaybeObserver(MaybeObserver<? super T> actual) {
this.actual = actual;
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.d, d)) {
this.d = d;
actual.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
d = DisposableHelper.DISPOSED;
actual.onComplete();
}
@Override
public void onError(Throwable e) {
d = DisposableHelper.DISPOSED;
actual.onError(e);
}
@Override
public void onComplete() {
d = DisposableHelper.DISPOSED;
actual.onComplete();
}
@Override
public boolean isDisposed() {
return d.isDisposed();
}
@Override
public void dispose() {
d.dispose();
d = DisposableHelper.DISPOSED;
}
}
}
| benjchristensen/RxJava | src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElement.java | Java | apache-2.0 | 2,368 |
// Copyright 2020 The Knative Authors
//
// 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.
package service
import (
"testing"
"gotest.tools/v3/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sfake "k8s.io/client-go/kubernetes/fake"
"knative.dev/kperf/pkg"
"knative.dev/kperf/pkg/testutil"
servingv1client "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1"
servingv1fake "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/fake"
)
func TestCleanServicesFunc(t *testing.T) {
tests := []struct {
name string
cleanArgs pkg.CleanArgs
}{
{
name: "should clean services in namespace",
cleanArgs: pkg.CleanArgs{
Namespace: "test-kperf-1",
},
},
{
name: "should clean services in namespace range",
cleanArgs: pkg.CleanArgs{
NamespacePrefix: "test-kperf",
NamespaceRange: "1,2",
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-kperf-1",
},
}
client := k8sfake.NewSimpleClientset(ns)
fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake}
servingClient := func() (servingv1client.ServingV1Interface, error) {
return fakeServing, nil
}
p := &pkg.PerfParams{
ClientSet: client,
NewServingClient: servingClient,
}
err := CleanServices(p, tc.cleanArgs)
assert.NilError(t, err)
})
}
}
func TestNewServiceCleanCommand(t *testing.T) {
t.Run("incompleted or wrong args for service clean", func(t *testing.T) {
client := k8sfake.NewSimpleClientset()
fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake}
servingClient := func() (servingv1client.ServingV1Interface, error) {
return fakeServing, nil
}
p := &pkg.PerfParams{
ClientSet: client,
NewServingClient: servingClient,
}
cmd := NewServiceCleanCommand(p)
_, err := testutil.ExecuteCommand(cmd)
assert.ErrorContains(t, err, "both namespace and namespace-prefix are empty")
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf-1", "--namespace-range", "2,1")
assert.ErrorContains(t, err, "failed to parse namespace range 2,1")
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "x,y")
assert.ErrorContains(t, err, "strconv.Atoi: parsing \"x\": invalid syntax")
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "1,y")
assert.ErrorContains(t, err, "strconv.Atoi: parsing \"y\": invalid syntax")
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "1")
assert.ErrorContains(t, err, "expected range like 1,500, given 1")
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf-1", "--namespace-range", "1,2")
assert.ErrorContains(t, err, "no namespace found with prefix test-kperf-1")
})
t.Run("clean service as expected", func(t *testing.T) {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-kperf-1",
},
}
client := k8sfake.NewSimpleClientset(ns)
fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake}
servingClient := func() (servingv1client.ServingV1Interface, error) {
return fakeServing, nil
}
p := &pkg.PerfParams{
ClientSet: client,
NewServingClient: servingClient,
}
cmd := NewServiceCleanCommand(p)
_, err := testutil.ExecuteCommand(cmd, "--namespace", "test-kperf-1")
assert.NilError(t, err)
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "1,2")
assert.NilError(t, err)
})
t.Run("failed to clean services", func(t *testing.T) {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-kperf-2",
},
}
client := k8sfake.NewSimpleClientset(ns)
fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake}
servingClient := func() (servingv1client.ServingV1Interface, error) {
return fakeServing, nil
}
p := &pkg.PerfParams{
ClientSet: client,
NewServingClient: servingClient,
}
cmd := NewServiceCleanCommand(p)
_, err := testutil.ExecuteCommand(cmd, "--namespace", "test-kperf-1")
assert.ErrorContains(t, err, "namespaces \"test-kperf-1\" not found")
cmd = NewServiceCleanCommand(p)
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf-1", "--namespace-range", "1,2")
assert.ErrorContains(t, err, "no namespace found with prefix test-kperf-1")
})
t.Run("clean generated ksvc with namespace flag", func(t *testing.T) {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-kperf-prefix-1",
},
}
client := k8sfake.NewSimpleClientset(ns)
fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake}
servingClient := func() (servingv1client.ServingV1Interface, error) {
return fakeServing, nil
}
p := &pkg.PerfParams{
ClientSet: client,
NewServingClient: servingClient,
}
cmd := NewServiceCleanCommand(p)
_, err := testutil.ExecuteCommand(cmd, "--namespace", "test-kperf-prefix-1", "--svc-prefix", "test-ksvc")
assert.NilError(t, err)
})
}
| knative-sandbox/kperf | pkg/command/service/clean_test.go | GO | apache-2.0 | 5,720 |
/*
* Copyright 2014–2018 SlamData Inc.
*
* 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.
*/
package quasar.frontend.logicalplan
import slamdata.Predef._
import quasar.{Data, Func}
import quasar.DataGenerators._
import quasar.fp._
import quasar.std
import matryoshka._
import matryoshka.data.Fix
import org.scalacheck._
import org.specs2.scalaz.{ScalazMatchers, Spec}
import scalaz._, Scalaz._
import scalaz.scalacheck.ScalazProperties.{equal => _, _}
import pathy.Path._
class LogicalPlanSpecs extends Spec with ScalazMatchers {
val lpf = new LogicalPlanR[Fix[LogicalPlan]]
implicit val arbLogicalPlan: Delay[Arbitrary, LogicalPlan] =
new Delay[Arbitrary, LogicalPlan] {
def apply[A](arb: Arbitrary[A]) =
Arbitrary {
Gen.oneOf(readGen[A], addGen(arb), constGen[A], letGen(arb), freeGen[A](Nil))
}
}
// Switch this to parameterize over Funcs as well
def addGen[A: Arbitrary]: Gen[LogicalPlan[A]] = for {
l <- Arbitrary.arbitrary[A]
r <- Arbitrary.arbitrary[A]
} yield Invoke(std.MathLib.Add, Func.Input2(l, r))
def letGen[A: Arbitrary]: Gen[LogicalPlan[A]] = for {
n <- Gen.choose(0, 1000)
(form, body) <- Arbitrary.arbitrary[(A, A)]
} yield let(Symbol("tmp" + n), form, body)
def readGen[A]: Gen[LogicalPlan[A]] = Gen.const(read(rootDir </> file("foo")))
def constGen[A]: Gen[LogicalPlan[A]] = for {
data <- Arbitrary.arbitrary[Data]
} yield constant(data)
def freeGen[A](vars: List[Symbol]): Gen[LogicalPlan[A]] = for {
n <- Gen.choose(0, 1000)
} yield free(Symbol("tmp" + n))
implicit val arbIntLP = arbLogicalPlan(Arbitrary.arbInt)
checkAll(traverse.laws[LogicalPlan])
import quasar.std.StdLib._, relations._, quasar.std.StdLib.set._, structural._, math._
"normalizeTempNames" should {
"rename simple nested lets" in {
lpf.normalizeTempNames(
lpf.let('foo, lpf.read(file("foo")),
lpf.let('bar, lpf.read(file("bar")),
Fix(MakeMapN(
lpf.constant(Data.Str("x")) -> Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("x")))),
lpf.constant(Data.Str("y")) -> Fix(MapProject(lpf.free('bar), lpf.constant(Data.Str("y"))))))))) must equal(
lpf.let('__tmp0, lpf.read(file("foo")),
lpf.let('__tmp1, lpf.read(file("bar")),
Fix(MakeMapN(
lpf.constant(Data.Str("x")) -> Fix(MapProject(lpf.free('__tmp0), lpf.constant(Data.Str("x")))),
lpf.constant(Data.Str("y")) -> Fix(MapProject(lpf.free('__tmp1), lpf.constant(Data.Str("y")))))))))
}
"rename shadowed name" in {
lpf.normalizeTempNames(
lpf.let('x, lpf.read(file("foo")),
lpf.let('x, Fix(MakeMapN(
lpf.constant(Data.Str("x")) -> Fix(MapProject(lpf.free('x), lpf.constant(Data.Str("x")))))),
lpf.free('x)))) must equal(
lpf.let('__tmp0, lpf.read(file("foo")),
lpf.let('__tmp1, Fix(MakeMapN(
lpf.constant(Data.Str("x")) -> Fix(MapProject(lpf.free('__tmp0), lpf.constant(Data.Str("x")))))),
lpf.free('__tmp1))))
}
}
"normalizeLets" should {
"re-nest" in {
lpf.normalizeLets(
lpf.let('bar,
lpf.let('foo,
lpf.read(file("foo")),
Fix(Filter(lpf.free('foo), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("x")))), lpf.constant(Data.Str("z"))))))),
Fix(MakeMapN(
lpf.constant(Data.Str("y")) -> Fix(MapProject(lpf.free('bar), lpf.constant(Data.Str("y")))))))) must equal(
lpf.let('foo,
lpf.read(file("foo")),
lpf.let('bar,
Fix(Filter(lpf.free('foo), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("x")))), lpf.constant(Data.Str("z")))))),
Fix(MakeMapN(
lpf.constant(Data.Str("y")) -> Fix(MapProject(lpf.free('bar), lpf.constant(Data.Str("y")))))))))
}
"re-nest deep" in {
lpf.normalizeLets(
lpf.let('baz,
lpf.let('bar,
lpf.let('foo,
lpf.read(file("foo")),
Fix(Filter(lpf.free('foo), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("x")))), lpf.constant(Data.Int(0))))))),
Fix(Filter(lpf.free('bar), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("y")))), lpf.constant(Data.Int(1))))))),
Fix(MakeMapN(
lpf.constant(Data.Str("z")) -> Fix(MapProject(lpf.free('bar), lpf.constant(Data.Str("z")))))))) must equal(
lpf.let('foo,
lpf.read(file("foo")),
lpf.let('bar,
Fix(Filter(lpf.free('foo), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("x")))), lpf.constant(Data.Int(0)))))),
lpf.let('baz,
Fix(Filter(lpf.free('bar), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("y")))), lpf.constant(Data.Int(1)))))),
Fix(MakeMapN(
lpf.constant(Data.Str("z")) -> Fix(MapProject(lpf.free('bar), lpf.constant(Data.Str("z"))))))))))
}
"hoist multiple Lets" in {
lpf.normalizeLets(
Fix(Add(
lpf.let('x, lpf.constant(Data.Int(0)), Fix(Add(lpf.free('x), lpf.constant(Data.Int(1))))),
lpf.let('y, lpf.constant(Data.Int(2)), Fix(Add(lpf.free('y), lpf.constant(Data.Int(3)))))))) must equal(
lpf.let('x, lpf.constant(Data.Int(0)),
lpf.let('y, lpf.constant(Data.Int(2)),
Fix(Add(
Fix(Add(lpf.free('x), lpf.constant(Data.Int(1)))),
Fix(Add(lpf.free('y), lpf.constant(Data.Int(3)))))))))
}
"hoist deep Let by one level" in {
lpf.normalizeLets(
Fix(Add(
lpf.constant(Data.Int(0)),
Fix(Add(
lpf.let('x, lpf.constant(Data.Int(1)), Fix(Add(lpf.free('x), lpf.constant(Data.Int(2))))),
lpf.constant(Data.Int(3))))))) must equal(
Fix(Add(
lpf.constant(Data.Int(0)),
lpf.let('x, lpf.constant(Data.Int(1)),
Fix(Add(
Fix(Add(lpf.free('x), lpf.constant(Data.Int(2)))),
lpf.constant(Data.Int(3))))))))
}
}
}
| jedesah/Quasar | frontend/src/test/scala/quasar/frontend/logicalplan/LogicalPlanSpecs.scala | Scala | apache-2.0 | 6,634 |
package com.intellij.util.xml.impl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.NullableFactory;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.DomNameStrategy;
import com.intellij.util.xml.EvaluatedXmlName;
import com.intellij.util.xml.stubs.ElementStub;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
/**
* @author peter
*/
public class DomRootInvocationHandler extends DomInvocationHandler<AbstractDomChildDescriptionImpl, ElementStub> {
private static final Logger LOG = Logger.getInstance("#com.intellij.util.xml.impl.DomRootInvocationHandler");
private final DomFileElementImpl<?> myParent;
public DomRootInvocationHandler(final Class aClass,
final RootDomParentStrategy strategy,
@Nonnull final DomFileElementImpl fileElement,
@Nonnull final EvaluatedXmlName tagName,
@Nullable ElementStub stub
) {
super(aClass, strategy, tagName, new AbstractDomChildDescriptionImpl(aClass) {
@Nonnull
public List<? extends DomElement> getValues(@Nonnull final DomElement parent) {
throw new UnsupportedOperationException();
}
public int compareTo(final AbstractDomChildDescriptionImpl o) {
throw new UnsupportedOperationException();
}
}, fileElement.getManager(), true, stub);
myParent = fileElement;
}
public void undefineInternal() {
try {
final XmlTag tag = getXmlTag();
if (tag != null) {
deleteTag(tag);
detach();
fireUndefinedEvent();
}
}
catch (Exception e) {
LOG.error(e);
}
}
public boolean equals(final Object obj) {
if (!(obj instanceof DomRootInvocationHandler)) return false;
final DomRootInvocationHandler handler = (DomRootInvocationHandler)obj;
return myParent.equals(handler.myParent);
}
public int hashCode() {
return myParent.hashCode();
}
@Nonnull
public String getXmlElementNamespace() {
return getXmlName().getNamespace(getFile(), getFile());
}
@Override
protected String checkValidity() {
final XmlTag tag = (XmlTag)getXmlElement();
if (tag != null && !tag.isValid()) {
return "invalid root tag";
}
final String s = myParent.checkValidity();
if (s != null) {
return "root: " + s;
}
return null;
}
@Nonnull
public DomFileElementImpl getParent() {
return myParent;
}
public DomElement createPathStableCopy() {
final DomFileElement stableCopy = myParent.createStableCopy();
return getManager().createStableValue(new NullableFactory<DomElement>() {
public DomElement create() {
return stableCopy.isValid() ? stableCopy.getRootElement() : null;
}
});
}
protected XmlTag setEmptyXmlTag() {
final XmlTag[] result = new XmlTag[]{null};
getManager().runChange(new Runnable() {
public void run() {
try {
final String namespace = getXmlElementNamespace();
@NonNls final String nsDecl = StringUtil.isEmpty(namespace) ? "" : " xmlns=\"" + namespace + "\"";
final XmlFile xmlFile = getFile();
final XmlTag tag = XmlElementFactory.getInstance(xmlFile.getProject()).createTagFromText("<" + getXmlElementName() + nsDecl + "/>");
result[0] = ((XmlDocument)xmlFile.getDocument().replace(((XmlFile)tag.getContainingFile()).getDocument())).getRootTag();
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
});
return result[0];
}
@Nonnull
public final DomNameStrategy getNameStrategy() {
final Class<?> rawType = getRawType();
final DomNameStrategy strategy = DomImplUtil.getDomNameStrategy(rawType, isAttribute());
if (strategy != null) {
return strategy;
}
return DomNameStrategy.HYPHEN_STRATEGY;
}
}
| consulo/consulo-xml | xml-dom-impl/src/main/java/com/intellij/util/xml/impl/DomRootInvocationHandler.java | Java | apache-2.0 | 4,330 |
package org.consumersunion.stories.common.client.util;
public class CachedObjectKeys {
public static final String OPENED_CONTENT = "openedContent";
public static final String OPENED_STORY = "openedStory";
public static final String OPENED_COLLECTION = "openedCollection";
}
| stori-es/stori_es | dashboard/src/main/java/org/consumersunion/stories/common/client/util/CachedObjectKeys.java | Java | apache-2.0 | 287 |
#ifndef LOG_H
#define LOG_H
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <proton/import_export.h>
#include <proton/type_compat.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @cond INTERNAL
*/
/**
* @file
*
* Control log messages that are not associated with a transport.
* See pn_transport_trace for transport-related logging.
*/
/**
* Callback for customized logging.
*/
typedef void (*pn_logger_t)(const char *message);
/**
* Enable/disable global logging.
*
* By default, logging is enabled by environment variable PN_TRACE_LOG.
* Calling this function overrides the environment setting.
*/
PN_EXTERN void pn_log_enable(bool enabled);
/**
* Set the logger.
*
* By default a logger that prints to stderr is installed.
*
* @param logger is called with each log message if logging is enabled.
* Passing 0 disables logging regardless of pn_log_enable() or environment settings.
*/
PN_EXTERN void pn_log_logger(pn_logger_t logger);
/**
* @endcond
*/
#ifdef __cplusplus
}
#endif
#endif
| alanconway/qpid-proton | c/include/proton/log.h | C | apache-2.0 | 1,795 |
package dkalymbaev.triangle;
class Triangle {
/**
* This class defines points a b and c as peacks of triangle.
*/
public Point a;
public Point b;
public Point c;
/**
* Creating of a new objects.
* @param a is the length of the first side.
* @param b is the length of the second side.
* @param c is the length of the third side.
*/
public Triangle(Point a, Point b, Point c) {
this.a = a;
this.b = b;
this.c = c;
}
public double area() {
double ab = a.distanceTo(b);
double bc = b.distanceTo(c);
double ac = a.distanceTo(c);
double halfperim = ((ab + bc + ac) / 2);
double area = Math.sqrt(halfperim * (halfperim - ab) * (halfperim - bc) * (halfperim - ac));
if (ab > 0 && bc > 0 && ac > 0) {
return area;
} else {
return 0;
}
}
} | Damir2805/java-a-to-z | Chapter_001/src/main/java/dkalymbaev/triangle/Triangle.java | Java | apache-2.0 | 783 |
/*
* Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
* Copyright [2016-2019] EMBL-European Bioinformatics Institute
*
* 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.
*/
package org.ensembl.healthcheck.util;
import java.util.HashMap;
import java.util.Map;
/**
* A default implementation of the {@link MapRowMapper} intended as an
* extension point to help when creating these call back objects. This version
* will return a HashMap of the given generic types.
*
* @author ayates
* @author dstaines
*/
public abstract class AbstractMapRowMapper<K, T> implements MapRowMapper<K, T>{
public Map<K, T> getMap() {
return new HashMap<K,T>();
}
}
| Ensembl/ensj-healthcheck | src/org/ensembl/healthcheck/util/AbstractMapRowMapper.java | Java | apache-2.0 | 1,222 |
/**
* Created by plter on 6/13/16.
*/
(function () {
var files = ["hello.js", "app.js"];
files.forEach(function (file) {
var scriptTag = document.createElement("script");
scriptTag.async = false;
scriptTag.src = file;
document.body.appendChild(scriptTag);
});
}()); | plter/HTML5Course20160612 | 20160613/LoadScript/loader.js | JavaScript | apache-2.0 | 315 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>文件</title>
<meta name="generator" content="Org mode" />
<meta name="author" content="Wu, Shanliang" />
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
.title { text-align: center;
margin-bottom: .2em; }
.subtitle { text-align: center;
font-size: medium;
font-weight: bold;
margin-top:0; }
.todo { font-family: monospace; color: red; }
.done { font-family: monospace; color: green; }
.priority { font-family: monospace; color: orange; }
.tag { background-color: #eee; font-family: monospace;
padding: 2px; font-size: 80%; font-weight: normal; }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.org-right { margin-left: auto; margin-right: 0px; text-align: right; }
.org-left { margin-left: 0px; margin-right: auto; text-align: left; }
.org-center { margin-left: auto; margin-right: auto; text-align: center; }
.underline { text-decoration: underline; }
#postamble p, #preamble p { font-size: 90%; margin: .2em; }
p.verse { margin-left: 3%; }
pre {
border: 1px solid #ccc;
box-shadow: 3px 3px 3px #eee;
padding: 8pt;
font-family: monospace;
overflow: auto;
margin: 1.2em;
}
pre.src {
position: relative;
overflow: visible;
padding-top: 1.2em;
}
pre.src:before {
display: none;
position: absolute;
background-color: white;
top: -10px;
right: 10px;
padding: 3px;
border: 1px solid black;
}
pre.src:hover:before { display: inline;}
/* Languages per Org manual */
pre.src-asymptote:before { content: 'Asymptote'; }
pre.src-awk:before { content: 'Awk'; }
pre.src-C:before { content: 'C'; }
/* pre.src-C++ doesn't work in CSS */
pre.src-clojure:before { content: 'Clojure'; }
pre.src-css:before { content: 'CSS'; }
pre.src-D:before { content: 'D'; }
pre.src-ditaa:before { content: 'ditaa'; }
pre.src-dot:before { content: 'Graphviz'; }
pre.src-calc:before { content: 'Emacs Calc'; }
pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
pre.src-fortran:before { content: 'Fortran'; }
pre.src-gnuplot:before { content: 'gnuplot'; }
pre.src-haskell:before { content: 'Haskell'; }
pre.src-hledger:before { content: 'hledger'; }
pre.src-java:before { content: 'Java'; }
pre.src-js:before { content: 'Javascript'; }
pre.src-latex:before { content: 'LaTeX'; }
pre.src-ledger:before { content: 'Ledger'; }
pre.src-lisp:before { content: 'Lisp'; }
pre.src-lilypond:before { content: 'Lilypond'; }
pre.src-lua:before { content: 'Lua'; }
pre.src-matlab:before { content: 'MATLAB'; }
pre.src-mscgen:before { content: 'Mscgen'; }
pre.src-ocaml:before { content: 'Objective Caml'; }
pre.src-octave:before { content: 'Octave'; }
pre.src-org:before { content: 'Org mode'; }
pre.src-oz:before { content: 'OZ'; }
pre.src-plantuml:before { content: 'Plantuml'; }
pre.src-processing:before { content: 'Processing.js'; }
pre.src-python:before { content: 'Python'; }
pre.src-R:before { content: 'R'; }
pre.src-ruby:before { content: 'Ruby'; }
pre.src-sass:before { content: 'Sass'; }
pre.src-scheme:before { content: 'Scheme'; }
pre.src-screen:before { content: 'Gnu Screen'; }
pre.src-sed:before { content: 'Sed'; }
pre.src-sh:before { content: 'shell'; }
pre.src-sql:before { content: 'SQL'; }
pre.src-sqlite:before { content: 'SQLite'; }
/* additional languages in org.el's org-babel-load-languages alist */
pre.src-forth:before { content: 'Forth'; }
pre.src-io:before { content: 'IO'; }
pre.src-J:before { content: 'J'; }
pre.src-makefile:before { content: 'Makefile'; }
pre.src-maxima:before { content: 'Maxima'; }
pre.src-perl:before { content: 'Perl'; }
pre.src-picolisp:before { content: 'Pico Lisp'; }
pre.src-scala:before { content: 'Scala'; }
pre.src-shell:before { content: 'Shell Script'; }
pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
/* additional language identifiers per "defun org-babel-execute"
in ob-*.el */
pre.src-cpp:before { content: 'C++'; }
pre.src-abc:before { content: 'ABC'; }
pre.src-coq:before { content: 'Coq'; }
pre.src-groovy:before { content: 'Groovy'; }
/* additional language identifiers from org-babel-shell-names in
ob-shell.el: ob-shell is the only babel language using a lambda to put
the execution function name together. */
pre.src-bash:before { content: 'bash'; }
pre.src-csh:before { content: 'csh'; }
pre.src-ash:before { content: 'ash'; }
pre.src-dash:before { content: 'dash'; }
pre.src-ksh:before { content: 'ksh'; }
pre.src-mksh:before { content: 'mksh'; }
pre.src-posh:before { content: 'posh'; }
/* Additional Emacs modes also supported by the LaTeX listings package */
pre.src-ada:before { content: 'Ada'; }
pre.src-asm:before { content: 'Assembler'; }
pre.src-caml:before { content: 'Caml'; }
pre.src-delphi:before { content: 'Delphi'; }
pre.src-html:before { content: 'HTML'; }
pre.src-idl:before { content: 'IDL'; }
pre.src-mercury:before { content: 'Mercury'; }
pre.src-metapost:before { content: 'MetaPost'; }
pre.src-modula-2:before { content: 'Modula-2'; }
pre.src-pascal:before { content: 'Pascal'; }
pre.src-ps:before { content: 'PostScript'; }
pre.src-prolog:before { content: 'Prolog'; }
pre.src-simula:before { content: 'Simula'; }
pre.src-tcl:before { content: 'tcl'; }
pre.src-tex:before { content: 'TeX'; }
pre.src-plain-tex:before { content: 'Plain TeX'; }
pre.src-verilog:before { content: 'Verilog'; }
pre.src-vhdl:before { content: 'VHDL'; }
pre.src-xml:before { content: 'XML'; }
pre.src-nxml:before { content: 'XML'; }
/* add a generic configuration mode; LaTeX export needs an additional
(add-to-list 'org-latex-listings-langs '(conf " ")) in .emacs */
pre.src-conf:before { content: 'Configuration File'; }
table { border-collapse:collapse; }
caption.t-above { caption-side: top; }
caption.t-bottom { caption-side: bottom; }
td, th { vertical-align:top; }
th.org-right { text-align: center; }
th.org-left { text-align: center; }
th.org-center { text-align: center; }
td.org-right { text-align: right; }
td.org-left { text-align: left; }
td.org-center { text-align: center; }
dt { font-weight: bold; }
.footpara { display: inline; }
.footdef { margin-bottom: 1em; }
.figure { padding: 1em; }
.figure p { text-align: center; }
.inlinetask {
padding: 10px;
border: 2px solid gray;
margin: 10px;
background: #ffffcc;
}
#org-div-home-and-up
{ text-align: right; font-size: 70%; white-space: nowrap; }
textarea { overflow-x: auto; }
.linenr { font-size: smaller }
.code-highlighted { background-color: #ffff00; }
.org-info-js_info-navigation { border-style: none; }
#org-info-js_console-label
{ font-size: 10px; font-weight: bold; white-space: nowrap; }
.org-info-js_search-highlight
{ background-color: #ffff00; color: #000000; font-weight: bold; }
.org-svg { width: 90%; }
/*]]>*/-->
</style>
<link rel="stylesheet" type="text/css" href="../css/main.css" />
<script type="text/javascript">
/*
@licstart The following is the entire license notice for the
JavaScript code in this tag.
Copyright (C) 2012-2019 Free Software Foundation, Inc.
The JavaScript code in this tag is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License (GNU GPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version. The code is distributed WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
As additional permission under GNU GPL version 3 section 7, you
may distribute non-source (e.g., minimized or compacted) forms of
that code without the copy of the GNU GPL normally required by
section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.
@licend The above is the entire license notice
for the JavaScript code in this tag.
*/
<!--/*--><![CDATA[/*><!--*/
function CodeHighlightOn(elem, id)
{
var target = document.getElementById(id);
if(null != target) {
elem.cacheClassElem = elem.className;
elem.cacheClassTarget = target.className;
target.className = "code-highlighted";
elem.className = "code-highlighted";
}
}
function CodeHighlightOff(elem, id)
{
var target = document.getElementById(id);
if(elem.cacheClassElem)
elem.className = elem.cacheClassElem;
if(elem.cacheClassTarget)
target.className = elem.cacheClassTarget;
}
/*]]>*///-->
</script>
</head>
<body>
<div id="org-div-home-and-up">
<a accesskey="h" href="operation-objects.html"> UP </a>
|
<a accesskey="H" href="../elisp.html"> HOME </a>
</div><div id="content">
<h1 class="title">文件</h1>
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#org760b7c8">打开文件</a></li>
<li><a href="#org53d8f23">文件读写</a></li>
<li><a href="#org90be9ba">文件信息</a></li>
<li><a href="#orgf9e4cd2">修改文件信息</a></li>
<li><a href="#orgfb973bd">文件名操作</a></li>
<li><a href="#org649f07e">临时文件</a></li>
<li><a href="#org14afedb">读取目录内容</a></li>
<li><a href="#orgfbd11db">文件Handle</a></li>
</ul>
</div>
</div>
<pre class="example">
作为一个编辑器,自然文件是最重要的操作对象之一
这一节要介绍有关文件的一系列命令,比如查找文件,读写文件,文件信息、读取目录、文件名操作等
</pre>
<div id="outline-container-org760b7c8" class="outline-2">
<h2 id="org760b7c8">打开文件</h2>
<div class="outline-text-2" id="text-org760b7c8">
<p>
当打开一个文件时,实际上 emacs 做了很多事情:
</p>
<ul class="org-ul">
<li>把文件名展开成为完整的文件名</li>
<li>判断文件是否存在</li>
<li>判断文件是否可读或者文件大小是否太大</li>
<li>查看文件是否已经打开,是否被锁定</li>
<li>向缓冲区插入文件内容</li>
<li>设置缓冲区的模式</li>
</ul>
<pre class="example">
这还只是简单的一个步骤,实际情况比这要复杂的多,许多异常需要考虑
而且为了所有函数的可扩展性,许多变量、handler 和 hook 被加入到文件操作的函数中,使得每一个环节都可以让用户或者 elisp 开发者可以定制,甚至完全接管所有的文件操作
</pre>
<p>
这里需要区分两个概念:文件和缓冲区。它们是两个不同的对象:
</p>
<ul class="org-ul">
<li>文件:是在计算机上可持久保存的信息</li>
<li>缓冲区: Emacs 中包含文件内容信息的对象,在 emacs 退出后就会消失,只有当保存缓冲区之后缓冲区里的内容才写到文件中去</li>
</ul>
</div>
</div>
<div id="outline-container-org53d8f23" class="outline-2">
<h2 id="org53d8f23">文件读写</h2>
<div class="outline-text-2" id="text-org53d8f23">
<p>
打开一个文件的命令是 <span class="underline">find-file</span> : 这命令使一个缓冲区访问某个文件,并让这个缓冲区成为当前缓冲区
</p>
<ul class="org-ul">
<li><span class="underline">find-file-noselect</span> :所有访问文件的核心函数,它只返回访问文件的缓冲区</li>
<li>find-file 在打开文件过程中会调用 <span class="underline">find-file-hook</span></li>
</ul>
<p>
这两个函数都有一个特点,如果 emacs 里已经有一个缓冲区访问这个文件的话,emacs 不会创建另一个缓冲区来访问文件,而只是简单返回或者转到这个缓冲区
</p>
<pre class="example">
怎样检查有没有缓冲区是否访问某个文件呢?
所有和文件关联的缓冲区里都有一个 buffer-local 变量buffer-file-name。但是不要直接设置这个变量来改变缓冲区关联的文件,而是使用 set-visited-file-name 来修改
同样不要直接从 buffer-list 里搜索buffer-file-name 来查找和某个文件关联的缓冲区,应该使用get-file-buffer 或者 find-buffer-visiting
</pre>
<div class="org-src-container">
<pre class="src src-lisp">(find-file <span style="color: #deb887;">"~/tmp/test.txt"</span>)
(<span style="color: #00bfff; font-weight: bold;">with-current-buffer</span>
(find-file-noselect <span style="color: #deb887;">"~/tmp/test.txt"</span>)
buffer-file-name) <span style="color: #5f9ea0; font-style: italic;">; => "/home/klose/tmp/test.txt"</span>
(find-buffer-visiting <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => #<buffer test.txt></span>
(get-file-buffer <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => #<buffer test.txt></span>
</pre>
</div>
<p>
保存一个文件的过程相对简单一些:
</p>
<ol class="org-ol">
<li>首先创建备份文件</li>
<li>处理文件的位模式</li>
<li>将缓冲区写入文件</li>
</ol>
<p>
保存文件的命令是 <span class="underline">save-buffer</span>
</p>
<ul class="org-ul">
<li>相当于其它编辑器里 <b>另存为</b> 的命令是 <span class="underline">write-file</span> ,在这个过程中会调用一些函数或者 hook:
<ul class="org-ul">
<li>write-file-functions 和 write-contents-functions 几乎功能完全相同,都是在写入文件之前运行的函数,如果这些函数中有一个返回了 non-nil 的值, 则会认为文件已经写入了,后面的函数都不会运行,而且也不会使用再调用其它 写入文件的函数
<ul class="org-ul">
<li>这两个变量有一个重要的区别是write-contents-functions 在改变主模式之后会被修改,因为它没有permanent-local 属性,而 write-file-functions 则会仍然保留</li>
</ul></li>
<li>before-save-hook 和 write-file-functions 功能也比较类似,但是这个变量里的函数会逐个执行,不论返回什么值也不会影响后面文件的写入</li>
<li>after-save-hook 是在文件已经写入之后才调用的 hook,它是 save-buffer 最后一个动作</li>
</ul></li>
</ul>
<pre class="example">
但是实际上在 elisp 编程过程中经常遇到的一个问题是读取一个文件中的内容, 读取完之后并不希望这个缓冲区还留下来
如果直接用 kill-buffer 可能会把用户打开的文件关闭。而且 find-file-noselect 做的事情实在超出我们的需要
</pre>
<p>
这时可能需要的是更底层的文件读写函数,它们是 <span class="underline">insert-file-contents</span> 和 <span class="underline">write-region</span> ,调用形式分别是:
</p>
<div class="org-src-container">
<pre class="src src-lisp">(insert-file-contents filename <span style="color: #98f5ff;">&optional</span> visit beg end replace)
(write-region start end filename <span style="color: #98f5ff;">&optional</span> append visit lockname mustbenew)
</pre>
</div>
<p>
<span class="underline">insert-file-contents</span> 可以插入文件中指定部分到当前缓冲区中:
</p>
<ul class="org-ul">
<li>如果指定 visit 则会标记缓冲区的修改状态并关联缓冲区到文件,一般是不用的</li>
<li>replace 是指是否要删除缓冲区里其它内容,这比先删除缓冲区其它内容后插入文件内容要快一些,但是一般也用不上</li>
</ul>
<pre class="example">
insert-file-contents 会处理文件的编码,如果不需要解码文件的话,可以用 insert-file-contents-literally
</pre>
<p>
<span class="underline">write-region</span> 可以把缓冲区中的一部分写入到指定文件中:
</p>
<ul class="org-ul">
<li>如果指定 append 则是添加到文件末尾</li>
<li>visit 参数也会把缓冲区和文件关联</li>
<li>lockname 则是文件锁定的名字</li>
<li>mustbenew 确保文件存在时会要求用户确认操作</li>
</ul>
</div>
</div>
<div id="outline-container-org90be9ba" class="outline-2">
<h2 id="org90be9ba">文件信息</h2>
<div class="outline-text-2" id="text-org90be9ba">
<ul class="org-ul">
<li>文件是否存在可以使用 <span class="underline">file-exists-p</span> 来判断:对于目录和一般文件都可以用这个函数进行判断
<ul class="org-ul">
<li>符号链接只有当 <span class="underline">目标文件</span> 存在时才返回 t</li>
</ul></li>
<li><span class="underline">file-readable-p</span> 、 <span class="underline">file-writable-p</span> , <span class="underline">file-executable-p</span> 分用来测试用户对文件的权限
<ul class="org-ul">
<li>文件的位模式还可以用 <span class="underline">file-modes</span> 函数得到</li>
</ul></li>
</ul>
<div class="org-src-container">
<pre class="src src-lisp">(file-exists-p <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(file-readable-p <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(file-writable-p <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(file-executable-p <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => nil</span>
(format <span style="color: #deb887;">"%o"</span> (file-modes <span style="color: #deb887;">"~/tmp/test.txt"</span>)) <span style="color: #5f9ea0; font-style: italic;">; => "644"</span>
</pre>
</div>
<p>
文件类型判断:
</p>
<ul class="org-ul">
<li><span class="underline">file-regular-p</span> : 判断一个文件名是否是一个普通文件(不是目录,命名管道、终端或者其它 IO 设备)</li>
<li><span class="underline">file-directory-p</span>: 判断一个文件名是否一个存在的目录</li>
<li><span class="underline">file-symlink-p</span> : 判断一个文件名是否是一个符号链接
<ul class="org-ul">
<li>当文件名是一个符号链接时会返回 <span class="underline">目标文件名</span></li>
<li>文件的真实名字也就是除去相对链接和符号链接后得到的文件名可以用 <span class="underline">file-truename</span> 得到</li>
</ul></li>
</ul>
<pre class="example">
事实上每个和文件关联的 buffer 里也有一个缓冲区局部变量 buffer-file-truename 来记录这个文件名
</pre>
<div class="org-src-container">
<pre class="src src-sh">$ ls -l t.txt
lrwxrwxrwx 1 klose klose 8 2007-07-15 15:51 t.txt -> test.txt
</pre>
</div>
<div class="org-src-container">
<pre class="src src-lisp">(file-regular-p <span style="color: #deb887;">"~/tmp/t.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(file-directory-p <span style="color: #deb887;">"~/tmp/t.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => nil</span>
(file-symlink-p <span style="color: #deb887;">"~/tmp/t.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "test.txt"</span>
(file-truename <span style="color: #deb887;">"~/tmp/t.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "/home/klose/tmp/test.txt"</span>
</pre>
</div>
<p>
文件更详细的信息可以用 <span class="underline">file-attributes</span> 函数得到。这个函数类似系统的 stat 命令,返回文件几乎所有的信息,包括 <span class="underline">文件类型</span> , <span class="underline">用户</span> 和 <span class="underline">组用户</span> , <span class="underline">访问日期</span> 、 <span class="underline">修改日期</span> 、 <span class="underline">status change 日期</span> 、 <span class="underline">文件大小</span> 、 <span class="underline">文件位模式</span> 、 <span class="underline">inode number</span> 、 <span class="underline">system number</span> …..
</p>
<div class="org-src-container">
<pre class="src src-lisp">(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-type</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(car (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-name-number</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(cadr (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-uid</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 2 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-gid</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 3 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-atime</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 4 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-mtime</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 5 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-ctime</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 6 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-size</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 7 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-modes</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 8 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-guid-changep</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 9 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-inode-number</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 10 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-system-number</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 11 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-type</span> (attr)
(car attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-name-number</span> (attr)
(cadr attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-uid</span> (attr)
(nth 2 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-gid</span> (attr)
(nth 3 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-atime</span> (attr)
(nth 4 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-mtime</span> (attr)
(nth 5 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-ctime</span> (attr)
(nth 6 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-size</span> (attr)
(nth 7 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-modes</span> (attr)
(nth 8 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-guid-changep</span> (attr)
(nth 9 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-inode-number</span> (attr)
(nth 10 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-system-number</span> (attr)
(nth 11 attr))
</pre>
</div>
<pre class="example">
前一组函数是直接由文件名访问文件信息,而后一组函数是由 file-attributes 的返回值来得到文件信息
</pre>
</div>
</div>
<div id="outline-container-orgf9e4cd2" class="outline-2">
<h2 id="orgf9e4cd2">修改文件信息</h2>
<div class="outline-text-2" id="text-orgf9e4cd2">
<ul class="org-ul">
<li>重命名和复制文件可以用 <span class="underline">rename-file</span> 和 <span class="underline">copy-file</span></li>
<li>删除文件使用 <span class="underline">delete-file</span></li>
<li>创建目录使用 <span class="underline">make-directory</span> 函数</li>
<li>不能用 delete-file 删除 目录,只能用 <span class="underline">delete-directory</span> 删除目录,当目录不为空时会产生一个错误</li>
<li>设置文件修改时间使用 <span class="underline">set-file-times</span></li>
<li>设置文件位模式可以用 <span class="underline">set-file-modes</span> 函数:参数必须是一个整数
<ul class="org-ul">
<li>可以用位函数 logand、logior 和 logxor 函数来进行位操作</li>
</ul></li>
</ul>
</div>
</div>
<div id="outline-container-orgfb973bd" class="outline-2">
<h2 id="orgfb973bd">文件名操作</h2>
<div class="outline-text-2" id="text-orgfb973bd">
<p>
路径一般由 <span class="underline">目录</span> 和 <span class="underline">文件名</span> ,而文件名一般由 <span class="underline">主文件名</span> (basename)、 <span class="underline">文件名后缀</span> 和 <span class="underline">版本号</span> 构成。 Emacs 有一系列函数来得到路径中的不同部分:
</p>
<div class="org-src-container">
<pre class="src src-lisp">(file-name-directory <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~/tmp/"</span>
(file-name-nondirectory <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "test.txt"</span>
(file-name-sans-extension <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~/tmp/test"</span>
(file-name-extension <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "txt"</span>
(file-name-sans-versions <span style="color: #deb887;">"~/tmp/test.txt~"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~/tmp/test.txt"</span>
(file-name-sans-versions <span style="color: #deb887;">"~/tmp/test.txt.~1~"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~/tmp/test.txt"</span>
</pre>
</div>
<pre class="example">
虽然 MSWin 的文件名使用的路径分隔符不同,但是这里介绍的函数都能用于 MSWin 形式的文件名,只是返回的文件名都是 Unix 形式了
</pre>
<p>
路径如果是从根目录开始的称为是绝对路径:
</p>
<ul class="org-ul">
<li>测试一个路径是否是绝对路径使用 <span class="underline">file-name-absolute-p</span>
<ul class="org-ul">
<li>如果在 Unix 或 GNU/Linux 系统,以 ~ 开头的路径也是绝对路径</li>
<li>在 MSWin 上,以 "/" 、 "\"、"X:" 开头的路径都是绝对路径</li>
</ul></li>
<li>如果不是绝对路径,可以使用 <span class="underline">expand-file-name</span> 来得到绝对路径</li>
<li>把一个绝对路径转换成相对某个路径的相对路径的可以用 <span class="underline">file-relative-name</span> 函数</li>
</ul>
<div class="org-src-container">
<pre class="src src-lisp">(file-name-absolute-p <span style="color: #deb887;">"~rms/foo"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(file-name-absolute-p <span style="color: #deb887;">"/user/rms/foo"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(expand-file-name <span style="color: #deb887;">"foo"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "/home/klose/foo"</span>
(expand-file-name <span style="color: #deb887;">"foo"</span> <span style="color: #deb887;">"/usr/spool/"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "/usr/spool/foo"</span>
(file-relative-name <span style="color: #deb887;">"/foo/bar"</span> <span style="color: #deb887;">"/foo/"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "bar"</span>
(file-relative-name <span style="color: #deb887;">"/foo/bar"</span> <span style="color: #deb887;">"/hack/"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "../foo/bar"</span>
</pre>
</div>
<p>
对于目录,如果要将其作为目录,也就是确保它是以路径分隔符结束,可以用 <span class="underline">file-name-as-directory</span>
</p>
<pre class="example">
不要用 (concat dir "/") 来转换,这会有移植问题
</pre>
<p>
和它相对应的函数是 <span class="underline">directory-file-name</span>
</p>
<div class="org-src-container">
<pre class="src src-lisp">(file-name-as-directory <span style="color: #deb887;">"~rms/lewis"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~rms/lewis/"</span>
(directory-file-name <span style="color: #deb887;">"~lewis/"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~lewis"</span>
</pre>
</div>
<p>
如果要得到所在系统使用的文件名,可以用 <span class="underline">convert-standard-filename</span>
</p>
<div class="org-src-container">
<pre class="src src-lisp">(convert-standard-filename <span style="color: #deb887;">"c:/windows"</span>) <span style="color: #5f9ea0; font-style: italic;">;=> "c:\\windows"</span>
</pre>
</div>
<pre class="example">
比如 在 MSWin 系统上,可以用这个函数返回用 "\" 分隔的文件名
</pre>
</div>
</div>
<div id="outline-container-org649f07e" class="outline-2">
<h2 id="org649f07e">临时文件</h2>
<div class="outline-text-2" id="text-org649f07e">
<ul class="org-ul">
<li>如果需要产生一个临时文件,可以使用 <span class="underline">make-temp-file</span>
<ul class="org-ul">
<li>这个函数按给定前缀产生一个不和现有文件冲突的文件,并返回它的文件名</li>
<li>如果给定的名字是一个相对文件名,则产生的文件名会用 <span class="underline">temporary-file-directory</span> 进行扩展
<ul class="org-ul">
<li>也可以用这个函数产生一个临时文件夹</li>
</ul></li>
</ul></li>
<li>如果只想产生一个不存在的文件名,可以用 <span class="underline">make-temp-name</span> 函数</li>
</ul>
<div class="org-src-container">
<pre class="src src-lisp">(make-temp-file <span style="color: #deb887;">"foo"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "/tmp/foo5611dxf"</span>
(make-temp-name <span style="color: #deb887;">"foo"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "foo5611q7l"</span>
</pre>
</div>
</div>
</div>
<div id="outline-container-org14afedb" class="outline-2">
<h2 id="org14afedb">读取目录内容</h2>
<div class="outline-text-2" id="text-org14afedb">
<p>
可以用 <span class="underline">directory-files</span> 来得到某个目录中的全部或者符合某个正则表达式的文件名:
</p>
<div class="org-src-container">
<pre class="src src-lisp">(directory-files <span style="color: #deb887;">"~/tmp/dir/"</span>)
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">=></span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">("#foo.el#" "." ".#foo.el" ".." "foo.el" "t.pl" "t2.pl")</span>
(directory-files <span style="color: #deb887;">"~/tmp/dir/"</span> t)
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">=></span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">("/home/ywb/tmp/dir/#foo.el#"</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/."</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/.#foo.el"</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/.."</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/foo.el"</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/t.pl"</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/t2.pl")</span>
(directory-files <span style="color: #deb887;">"~/tmp/dir/"</span> nil <span style="color: #deb887;">"\\.pl$"</span>) <span style="color: #5f9ea0; font-style: italic;">; => ("t.pl" "t2.pl")</span>
</pre>
</div>
<ul class="org-ul">
<li><span class="underline">directory-files-and-attributes</span> 和 directory-files 相似,但是返回的列表 中包含了 file-attributes 得到的信息</li>
<li><span class="underline">file-name-all-versions</span> 用于得到某个文件在目录中的所有版本</li>
<li><span class="underline">file-expand-wildcards</span> 可以用通配符来得到目录中的文件列表</li>
</ul>
</div>
</div>
<div id="outline-container-orgfbd11db" class="outline-2">
<h2 id="orgfbd11db">文件Handle</h2>
<div class="outline-text-2" id="text-orgfbd11db">
<pre class="example">
如果不把文件局限在存储在本地机器上的信息,而且有一套基本的文件操作,比如判断文件是否存在、打开文件、保存文件、得到目录内容之类,那远程的文件和本地文件的差别也仅在于文件名表示方法不同而已
在 Emacs 里,底层的文件操作函数都可以托管给 elisp 中的函数,这样只要用 elisp 实现了某种类型文件的基本操作,就能像编辑本地文件一样编辑其它类型文件了
</pre>
<p>
决定何种类型的文件名使用什么方式来操作是在 <span class="underline">file-name-handler-alist</span> 变量定义的。它是由形如 <span class="underline">(REGEXP . HANDLER)</span> 的列表。如果文件名匹配这个 REGEXP 则使用 HANDLER 来进行相应的文件操作。这里所说的文件操作,具体的来说有这些函数:
</p>
<div class="org-src-container">
<pre class="src src-lisp">`<span style="color: #ffd700;">access-file</span>', `<span style="color: #ffd700;">add-name-to-file</span>', `<span style="color: #ffd700;">byte-compiler-base-file-name</span>',
`<span style="color: #ffd700;">copy-file</span>', `<span style="color: #ffd700;">delete-directory</span>', `<span style="color: #ffd700;">delete-file</span>',
`<span style="color: #ffd700;">diff-latest-backup-file</span>', `<span style="color: #ffd700;">directory-file-name</span>', `<span style="color: #ffd700;">directory-files</span>',
`<span style="color: #ffd700;">directory-files-and-attributes</span>', `<span style="color: #ffd700;">dired-call-process</span>',
`<span style="color: #ffd700;">dired-compress-file</span>', `<span style="color: #ffd700;">dired-uncache</span>',
`<span style="color: #ffd700;">expand-file-name</span>', `<span style="color: #ffd700;">file-accessible-directory-p</span>', `<span style="color: #ffd700;">file-attributes</span>',
`<span style="color: #ffd700;">file-directory-p</span>', `<span style="color: #ffd700;">file-executable-p</span>', `<span style="color: #ffd700;">file-exists-p</span>',
`<span style="color: #ffd700;">file-local-copy</span>', `<span style="color: #ffd700;">file-remote-p</span>', `<span style="color: #ffd700;">file-modes</span>',
`<span style="color: #ffd700;">file-name-all-completions</span>', `<span style="color: #ffd700;">file-name-as-directory</span>',
`<span style="color: #ffd700;">file-name-completion</span>', `<span style="color: #ffd700;">file-name-directory</span>', `<span style="color: #ffd700;">file-name-nondirectory</span>',
`<span style="color: #ffd700;">file-name-sans-versions</span>', `<span style="color: #ffd700;">file-newer-than-file-p</span>',
`<span style="color: #ffd700;">file-ownership-preserved-p</span>', `<span style="color: #ffd700;">file-readable-p</span>', `<span style="color: #ffd700;">file-regular-p</span>',
`<span style="color: #ffd700;">file-symlink-p</span>', `<span style="color: #ffd700;">file-truename</span>', `<span style="color: #ffd700;">file-writable-p</span>',
`<span style="color: #ffd700;">find-backup-file-name</span>', `<span style="color: #ffd700;">find-file-noselect</span>',
`<span style="color: #ffd700;">get-file-buffer</span>', `<span style="color: #ffd700;">insert-directory</span>', `<span style="color: #ffd700;">insert-file-contents</span>',
`<span style="color: #ffd700;">load</span>', `<span style="color: #ffd700;">make-auto-save-file-name</span>', `<span style="color: #ffd700;">make-directory</span>',
`<span style="color: #ffd700;">make-directory-internal</span>', `<span style="color: #ffd700;">make-symbolic-link</span>',
`<span style="color: #ffd700;">rename-file</span>', `<span style="color: #ffd700;">set-file-modes</span>', `<span style="color: #ffd700;">set-file-times</span>',
`<span style="color: #ffd700;">set-visited-file-modtime</span>', `<span style="color: #ffd700;">shell-command</span>', `<span style="color: #ffd700;">substitute-in-file-name</span>',
`<span style="color: #ffd700;">unhandled-file-name-directory</span>', `<span style="color: #ffd700;">vc-registered</span>',
`<span style="color: #ffd700;">verify-visited-file-modtime</span>',
`<span style="color: #ffd700;">write-region</span>'
</pre>
</div>
<p>
在 HANDLE 里,可以只接管部分的文件操作,其它仍交给 emacs 原来的函数来完成
</p>
<pre class="example">
举一个简单的例子。比如最新版本的 emacs 把 *scratch* 的 auto-save-mode 打开了
如果你不想这个缓冲区的自动保存的文件名散布得到处都是,可以想办法让这个缓冲区的自动保存文件放到指定的目录中
刚好 make-auto-save-file-name 是在上面这个列表里的,但是不幸的是在函数定义里 make-auto-save-file-name 里不对不关联文件的缓冲区使用 handler
继续往下看,发现生成保存文件名是使用了 expand-file-name 函数
</pre>
<p>
一个解决方法就是:
</p>
<div class="org-src-container">
<pre class="src src-lisp">(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">my-scratch-auto-save-file-name</span> (operation <span style="color: #98f5ff;">&rest</span> args)
(<span style="color: #00bfff; font-weight: bold;">if</span> (and (eq operation 'expand-file-name)
(string= (car args) <span style="color: #deb887;">"#*scratch*#"</span>))
(expand-file-name (concat <span style="color: #deb887;">"~/.emacs.d/backup/"</span> (car args)))
(<span style="color: #00bfff; font-weight: bold;">let</span> ((inhibit-file-name-handlers
(cons 'my-scratch-auto-save-file-name
(and (eq inhibit-file-name-operation operation)
inhibit-file-name-handlers)))
(inhibit-file-name-operation operation))
(apply operation args))))
</pre>
</div>
<p>
<a href="text.html">Next:文本</a>
</p>
<p>
<a href="window.html">Previous:窗口</a>
</p>
<p>
<a href="operation-objects.html">TOP:操作对象</a>
</p>
</div>
</div>
</div>
<div id="postamble" class="status">
<br/>
<div class='ds-thread'></div>
<script>
var duoshuoQuery = {short_name:'klose911'};
(function() {
var dsThread = document.getElementsByClassName('ds-thread')[0];
dsThread.setAttribute('data-thread-key', document.title);
dsThread.setAttribute('data-title', document.title);
dsThread.setAttribute('data-url', window.location.href);
var ds = document.createElement('script');
ds.type = 'text/javascript';ds.async = true;
ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
ds.charset = 'UTF-8';
(document.getElementsByTagName('head')[0]
|| document.getElementsByTagName('body')[0]).appendChild(ds);
})();
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-90850421-1', 'auto');
ga('send', 'pageview');
</script>
</div>
</body>
</html>
| klose911/klose911.github.io | html/elisp/operation-objects/file.html | HTML | apache-2.0 | 42,496 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="shortcut icon" type="image/x-icon" href="../../../../../../../favicon.ico" />
<title>com.google.android.gms.games.multiplayer | Android Developers</title>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto+Condensed">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold"
title="roboto">
<link href="../../../../../../../assets/css/default.css?v=2" rel="stylesheet" type="text/css">
<!-- FULLSCREEN STYLESHEET -->
<link href="../../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">
<!-- JAVASCRIPT -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="../../../../../../../assets/js/android_3p-bundle.js" type="text/javascript"></script>
<script type="text/javascript">
var toRoot = "../../../../../../../";
var metaTags = [];
var devsite = false;
</script>
<script src="../../../../../../../assets/js/docs.js?v=2" type="text/javascript"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-5831155-1', 'android.com');
ga('create', 'UA-49880327-2', 'android.com', {'name': 'universal'}); // New tracker);
ga('send', 'pageview');
ga('universal.send', 'pageview'); // Send page view for new tracker.
</script>
</head>
<body class="gc-documentation
develop">
<div id="doc-api-level" class="" style="display:none"></div>
<a name="top"></a>
<a name="top"></a>
<!-- Header -->
<div id="header-wrapper">
<div id="header">
<div class="wrap" id="header-wrap">
<div class="col-3 logo">
<a href="../../../../../../../index.html">
<img src="../../../../../../../assets/images/dac_logo.png"
srcset="../../../../../../../assets/images/[email protected] 2x"
width="123" height="25" alt="Android Developers" />
</a>
<div class="btn-quicknav" id="btn-quicknav">
<a href="#" class="arrow-inactive">Quicknav</a>
<a href="#" class="arrow-active">Quicknav</a>
</div>
</div>
<ul class="nav-x col-9">
<li class="design">
<a href="../../../../../../../design/index.html"
zh-tw-lang="設計"
zh-cn-lang="设计"
ru-lang="Проектирование"
ko-lang="디자인"
ja-lang="設計"
es-lang="Diseñar"
>Design</a></li>
<li class="develop"><a href="../../../../../../../develop/index.html"
zh-tw-lang="開發"
zh-cn-lang="开发"
ru-lang="Разработка"
ko-lang="개발"
ja-lang="開発"
es-lang="Desarrollar"
>Develop</a></li>
<li class="distribute last"><a href="../../../../../../../distribute/googleplay/index.html"
zh-tw-lang="發佈"
zh-cn-lang="分发"
ru-lang="Распространение"
ko-lang="배포"
ja-lang="配布"
es-lang="Distribuir"
>Distribute</a></li>
</ul>
<div class="menu-container">
<div class="moremenu">
<div id="more-btn"></div>
</div>
<div class="morehover" id="moremenu">
<div class="top"></div>
<div class="mid">
<div class="header">Links</div>
<ul>
<li><a href="https://play.google.com/apps/publish/" target="_googleplay">Google Play Developer Console</a></li>
<li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
<li><a href="../../../../../../../about/index.html">About Android</a></li>
</ul>
<div class="header">Android Sites</div>
<ul>
<li><a href="http://www.android.com">Android.com</a></li>
<li class="active"><a>Android Developers</a></li>
<li><a href="http://source.android.com">Android Open Source Project</a></li>
</ul>
<br class="clearfix" />
</div><!-- end 'mid' -->
<div class="bottom"></div>
</div><!-- end 'moremenu' -->
<div class="search" id="search-container">
<div class="search-inner">
<div id="search-btn"></div>
<div class="left"></div>
<form onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../../../')" />
</form>
<div class="right"></div>
<a class="close hide">close</a>
<div class="left"></div>
<div class="right"></div>
</div><!-- end search-inner -->
</div><!-- end search-container -->
<div class="search_filtered_wrapper reference">
<div class="suggest-card reference no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
<div class="search_filtered_wrapper docs">
<div class="suggest-card dummy no-display"> </div>
<div class="suggest-card develop no-display">
<ul class="search_filtered">
</ul>
<div class="child-card guides no-display">
</div>
<div class="child-card training no-display">
</div>
<div class="child-card samples no-display">
</div>
</div>
<div class="suggest-card design no-display">
<ul class="search_filtered">
</ul>
</div>
<div class="suggest-card distribute no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
</div><!-- end menu-container (search and menu widget) -->
<!-- Expanded quicknav -->
<div id="quicknav" class="col-13">
<ul>
<li class="about">
<ul>
<li><a href="../../../../../../../about/index.html">About</a></li>
<li><a href="../../../../../../../wear/index.html">Wear</a></li>
<li><a href="../../../../../../../tv/index.html">TV</a></li>
<li><a href="../../../../../../../auto/index.html">Auto</a></li>
</ul>
</li>
<li class="design">
<ul>
<li><a href="../../../../../../../design/index.html">Get Started</a></li>
<li><a href="../../../../../../../design/devices.html">Devices</a></li>
<li><a href="../../../../../../../design/style/index.html">Style</a></li>
<li><a href="../../../../../../../design/patterns/index.html">Patterns</a></li>
<li><a href="../../../../../../../design/building-blocks/index.html">Building Blocks</a></li>
<li><a href="../../../../../../../design/downloads/index.html">Downloads</a></li>
<li><a href="../../../../../../../design/videos/index.html">Videos</a></li>
</ul>
</li>
<li class="develop">
<ul>
<li><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../../../../../sdk/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a>
</li>
<li><a href="../../../../../../../google/index.html">Google Services</a>
</li>
</ul>
</li>
<li class="distribute last">
<ul>
<li><a href="../../../../../../../distribute/googleplay/index.html">Google Play</a></li>
<li><a href="../../../../../../../distribute/essentials/index.html">Essentials</a></li>
<li><a href="../../../../../../../distribute/users/index.html">Get Users</a></li>
<li><a href="../../../../../../../distribute/engage/index.html">Engage & Retain</a></li>
<li><a href="../../../../../../../distribute/monetize/index.html">Monetize</a></li>
<li><a href="../../../../../../../distribute/tools/index.html">Tools & Reference</a></li>
<li><a href="../../../../../../../distribute/stories/index.html">Developer Stories</a></li>
</ul>
</li>
</ul>
</div><!-- /Expanded quicknav -->
</div><!-- end header-wrap.wrap -->
</div><!-- end header -->
<!-- Secondary x-nav -->
<div id="nav-x">
<div class="wrap">
<ul class="nav-x col-9 develop" style="width:100%">
<li class="training"><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li class="guide"><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li class="reference"><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li class="tools"><a href="../../../../../../../sdk/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a></li>
<li class="google"><a href="../../../../../../../google/index.html"
>Google Services</a>
</li>
</ul>
</div>
</div>
<!-- /Sendondary x-nav DEVELOP -->
<div id="searchResults" class="wrap" style="display:none;">
<h2 id="searchTitle">Results</h2>
<div id="leftSearchControl" class="search-control">Loading...</div>
</div>
</div> <!--end header-wrapper -->
<div id="sticky-header">
<div>
<a class="logo" href="#top"></a>
<a class="top" href="#top"></a>
<ul class="breadcrumb">
<li class="current">com.google.android.gms.games.multiplayer</li>
</ul>
</div>
</div>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled"
title="Select your target API level to dim unavailable APIs">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/package-summary.html">com.google.android.gms</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/actions/package-summary.html">com.google.android.gms.actions</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/package-summary.html">com.google.android.gms.ads</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/doubleclick/package-summary.html">com.google.android.gms.ads.doubleclick</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/identifier/package-summary.html">com.google.android.gms.ads.identifier</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/package-summary.html">com.google.android.gms.ads.mediation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/admob/package-summary.html">com.google.android.gms.ads.mediation.admob</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/customevent/package-summary.html">com.google.android.gms.ads.mediation.customevent</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/purchase/package-summary.html">com.google.android.gms.ads.purchase</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/search/package-summary.html">com.google.android.gms.ads.search</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/analytics/package-summary.html">com.google.android.gms.analytics</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/analytics/ecommerce/package-summary.html">com.google.android.gms.analytics.ecommerce</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/appindexing/package-summary.html">com.google.android.gms.appindexing</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/appstate/package-summary.html">com.google.android.gms.appstate</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/auth/package-summary.html">com.google.android.gms.auth</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/auth/api/package-summary.html">com.google.android.gms.auth.api</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/cast/package-summary.html">com.google.android.gms.cast</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/package-summary.html">com.google.android.gms.common</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/annotation/package-summary.html">com.google.android.gms.common.annotation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/api/package-summary.html">com.google.android.gms.common.api</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/data/package-summary.html">com.google.android.gms.common.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/images/package-summary.html">com.google.android.gms.common.images</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/package-summary.html">com.google.android.gms.drive</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/events/package-summary.html">com.google.android.gms.drive.events</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/metadata/package-summary.html">com.google.android.gms.drive.metadata</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/query/package-summary.html">com.google.android.gms.drive.query</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/widget/package-summary.html">com.google.android.gms.drive.widget</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/package-summary.html">com.google.android.gms.fitness</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/data/package-summary.html">com.google.android.gms.fitness.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/request/package-summary.html">com.google.android.gms.fitness.request</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/result/package-summary.html">com.google.android.gms.fitness.result</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/service/package-summary.html">com.google.android.gms.fitness.service</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/package-summary.html">com.google.android.gms.games</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/achievement/package-summary.html">com.google.android.gms.games.achievement</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/event/package-summary.html">com.google.android.gms.games.event</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/leaderboard/package-summary.html">com.google.android.gms.games.leaderboard</a></li>
<li class="selected api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/package-summary.html">com.google.android.gms.games.multiplayer</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/realtime/package-summary.html">com.google.android.gms.games.multiplayer.realtime</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/turnbased/package-summary.html">com.google.android.gms.games.multiplayer.turnbased</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/quest/package-summary.html">com.google.android.gms.games.quest</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/request/package-summary.html">com.google.android.gms.games.request</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/snapshot/package-summary.html">com.google.android.gms.games.snapshot</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/gcm/package-summary.html">com.google.android.gms.gcm</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/package-summary.html">com.google.android.gms.identity.intents</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/model/package-summary.html">com.google.android.gms.identity.intents.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/location/package-summary.html">com.google.android.gms.location</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/package-summary.html">com.google.android.gms.maps</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/model/package-summary.html">com.google.android.gms.maps.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/panorama/package-summary.html">com.google.android.gms.panorama</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/package-summary.html">com.google.android.gms.plus</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/moments/package-summary.html">com.google.android.gms.plus.model.moments</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/people/package-summary.html">com.google.android.gms.plus.model.people</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/security/package-summary.html">com.google.android.gms.security</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/tagmanager/package-summary.html">com.google.android.gms.tagmanager</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wallet/package-summary.html">com.google.android.gms.wallet</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wallet/fragment/package-summary.html">com.google.android.gms.wallet.fragment</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wearable/package-summary.html">com.google.android.gms.wearable</a></li>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitation.html">Invitation</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitations.html">Invitations</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitations.LoadInvitationsResult.html">Invitations.LoadInvitationsResult</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Multiplayer.html">Multiplayer</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/OnInvitationReceivedListener.html">OnInvitationReceivedListener</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Participant.html">Participant</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Participatable.html">Participatable</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/InvitationBuffer.html">InvitationBuffer</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/InvitationEntity.html">InvitationEntity</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantBuffer.html">ParticipantBuffer</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantEntity.html">ParticipantEntity</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantResult.html">ParticipantResult</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantUtils.html">ParticipantUtils</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../../../../");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<div class="col-12" id="doc-col">
<div id="api-info-block">
<div class="api-level">
</div>
</div>
<div id="jd-header">
package
<h1>com.google.android.gms.games.multiplayer</h1>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<div class="jd-descr">
Contains data classes for multiplayer functionality.
</div>
<h2>Interfaces</h2>
<div class="jd-sumtable">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitation.html">Invitation</a></td>
<td class="jd-descrcol" width="100%">Data interface for an invitation object. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitations.html">Invitations</a></td>
<td class="jd-descrcol" width="100%">Entry point for invitations functionality. </td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitations.LoadInvitationsResult.html">Invitations.LoadInvitationsResult</a></td>
<td class="jd-descrcol" width="100%">Result delivered when invitations have been loaded. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Multiplayer.html">Multiplayer</a></td>
<td class="jd-descrcol" width="100%">Common constants/methods for multiplayer functionality. </td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/OnInvitationReceivedListener.html">OnInvitationReceivedListener</a></td>
<td class="jd-descrcol" width="100%">Listener to invoke when a new invitation is received. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Participant.html">Participant</a></td>
<td class="jd-descrcol" width="100%">Data interface for multiplayer participants. </td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Participatable.html">Participatable</a></td>
<td class="jd-descrcol" width="100%">Interface defining methods for an object which can have participants. </td>
</tr>
</table>
</div>
<h2>Classes</h2>
<div class="jd-sumtable">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/InvitationBuffer.html">InvitationBuffer</a></td>
<td class="jd-descrcol" width="100%"><code><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html">DataBuffer</a></code> implementation containing Invitation data. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/InvitationEntity.html">InvitationEntity</a></td>
<td class="jd-descrcol" width="100%">Data object representing the data for a multiplayer invitation. </td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantBuffer.html">ParticipantBuffer</a></td>
<td class="jd-descrcol" width="100%"><code><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html">DataBuffer</a></code> implementation containing match participant data. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantEntity.html">ParticipantEntity</a></td>
<td class="jd-descrcol" width="100%">Data object representing a Participant in a match. </td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantResult.html">ParticipantResult</a></td>
<td class="jd-descrcol" width="100%">Data class used to report a participant's result in a match. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantUtils.html">ParticipantUtils</a></td>
<td class="jd-descrcol" width="100%">Utilities for working with multiplayer participants. </td>
</tr>
</table>
</div>
<div id="footer" class="wrap" >
<div id="copyright">
Except as noted, this content is licensed under <a
href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="../../../../../../../license.html">
Content License</a>.
</div>
<div id="build_info">
Android GmsCore 1501030 r —
<script src="../../../../../../../timestamp.js" type="text/javascript"></script>
<script>document.write(BUILD_TIMESTAMP)</script>
</div>
<div id="footerlinks">
<p>
<a href="../../../../../../../about/index.html">About Android</a> |
<a href="../../../../../../../legal.html">Legal</a> |
<a href="../../../../../../../support.html">Support</a>
</p>
</div>
</div> <!-- end footer -->
</div><!-- end jd-content -->
</div><!-- doc-content -->
</div> <!-- end body-content -->
</body>
</html>
| gudnam/bringluck | google_play_services/docs/reference/com/google/android/gms/games/multiplayer/package-summary.html | HTML | apache-2.0 | 33,928 |
#!/bin/bash
#
./srmgor_2conn 2>&1 | tee runlog${1}.txt
| gmallard/stompngo_examples | srmgor_2conn/run.sh | Shell | apache-2.0 | 56 |
package mesosphere.marathon.integration
import mesosphere.marathon.api.v2.json.GroupUpdate
import mesosphere.marathon.integration.setup.{ IntegrationFunSuite, IntegrationHealthCheck, SingleMarathonIntegrationTest, WaitTestSupport }
import mesosphere.marathon.state.{ AppDefinition, PathId, UpgradeStrategy }
import org.apache.http.HttpStatus
import org.scalatest._
import spray.http.DateTime
import scala.concurrent.duration._
class GroupDeployIntegrationTest
extends IntegrationFunSuite
with SingleMarathonIntegrationTest
with Matchers
with BeforeAndAfter
with GivenWhenThen {
//clean up state before running the test case
before(cleanUp())
test("create empty group successfully") {
Given("A group which does not exist in marathon")
val group = GroupUpdate.empty("test".toRootTestPath)
When("The group gets created")
val result = marathon.createGroup(group)
Then("The group is created. A success event for this group is send.")
result.code should be(201) //created
val event = waitForChange(result)
}
test("update empty group successfully") {
Given("An existing group")
val name = "test2".toRootTestPath
val group = GroupUpdate.empty(name)
val dependencies = Set("/test".toTestPath)
waitForChange(marathon.createGroup(group))
When("The group gets updated")
waitForChange(marathon.updateGroup(name, group.copy(dependencies = Some(dependencies))))
Then("The group is updated")
val result = marathon.group("test2".toRootTestPath)
result.code should be(200)
result.value.dependencies should be(dependencies)
}
test("deleting an existing group gives a 200 http response") {
Given("An existing group")
val group = GroupUpdate.empty("test3".toRootTestPath)
waitForChange(marathon.createGroup(group))
When("The group gets deleted")
val result = marathon.deleteGroup(group.id.get)
waitForChange(result)
Then("The group is deleted")
result.code should be(200)
// only expect the test base group itself
marathon.listGroupsInBaseGroup.value.filter { group => group.id != testBasePath } should be('empty)
}
test("delete a non existing group should give a 404 http response") {
When("A non existing group is deleted")
val result = marathon.deleteGroup("does_not_exist".toRootTestPath)
Then("We get a 404 http response code")
result.code should be(404)
}
test("create a group with applications to start") {
Given("A group with one application")
val app = appProxy("/test/app".toRootTestPath, "v1", 2, withHealth = false)
val group = GroupUpdate("/test".toRootTestPath, Set(app))
When("The group is created")
waitForChange(marathon.createGroup(group))
Then("A success event is send and the application has been started")
val tasks = waitForTasks(app.id, app.instances)
tasks should have size 2
}
test("update a group with applications to restart") {
Given("A group with one application started")
val id = "test".toRootTestPath
val appId = id / "app"
val app1V1 = appProxy(appId, "v1", 2, withHealth = false)
waitForChange(marathon.createGroup(GroupUpdate(id, Set(app1V1))))
waitForTasks(app1V1.id, app1V1.instances)
When("The group is updated, with a changed application")
val app1V2 = appProxy(appId, "v2", 2, withHealth = false)
waitForChange(marathon.updateGroup(id, GroupUpdate(id, Set(app1V2))))
Then("A success event is send and the application has been started")
waitForTasks(app1V2.id, app1V2.instances)
}
test("update a group with the same application so no restart is triggered") {
Given("A group with one application started")
val id = "test".toRootTestPath
val appId = id / "app"
val app1V1 = appProxy(appId, "v1", 2, withHealth = false)
waitForChange(marathon.createGroup(GroupUpdate(id, Set(app1V1))))
waitForTasks(app1V1.id, app1V1.instances)
val tasks = marathon.tasks(appId)
When("The group is updated, with the same application")
waitForChange(marathon.updateGroup(id, GroupUpdate(id, Set(app1V1))))
Then("There is no deployment and all tasks still live")
marathon.listDeploymentsForBaseGroup().value should be ('empty)
marathon.tasks(appId).value.toSet should be(tasks.value.toSet)
}
test("create a group with application with health checks") {
Given("A group with one application")
val id = "proxy".toRootTestPath
val appId = id / "app"
val proxy = appProxy(appId, "v1", 1)
val group = GroupUpdate(id, Set(proxy))
When("The group is created")
val create = marathon.createGroup(group)
Then("A success event is send and the application has been started")
waitForChange(create)
}
test("upgrade a group with application with health checks") {
Given("A group with one application")
val id = "test".toRootTestPath
val appId = id / "app"
val proxy = appProxy(appId, "v1", 1)
val group = GroupUpdate(id, Set(proxy))
waitForChange(marathon.createGroup(group))
val check = appProxyCheck(proxy.id, "v1", state = true)
When("The group is updated")
check.afterDelay(1.second, state = false)
check.afterDelay(3.seconds, state = true)
val update = marathon.updateGroup(id, group.copy(apps = Some(Set(appProxy(appId, "v2", 1)))))
Then("A success event is send and the application has been started")
waitForChange(update)
}
test("rollback from an upgrade of group") {
Given("A group with one application")
val gid = "proxy".toRootTestPath
val appId = gid / "app"
val proxy = appProxy(appId, "v1", 2)
val group = GroupUpdate(gid, Set(proxy))
val create = marathon.createGroup(group)
waitForChange(create)
waitForTasks(proxy.id, proxy.instances)
val v1Checks = appProxyCheck(appId, "v1", state = true)
When("The group is updated")
waitForChange(marathon.updateGroup(gid, group.copy(apps = Some(Set(appProxy(appId, "v2", 2))))))
Then("The new version is deployed")
val v2Checks = appProxyCheck(appId, "v2", state = true)
WaitTestSupport.validFor("all v2 apps are available", 10.seconds) { v2Checks.pingSince(2.seconds) }
When("A rollback to the first version is initiated")
waitForChange(marathon.rollbackGroup(gid, create.value.version), 120.seconds)
Then("The rollback will be performed and the old version is available")
v1Checks.healthy
WaitTestSupport.validFor("all v1 apps are available", 10.seconds) { v1Checks.pingSince(2.seconds) }
}
test("during Deployment the defined minimum health capacity is never undershot") {
Given("A group with one application")
val id = "test".toRootTestPath
val appId = id / "app"
val proxy = appProxy(appId, "v1", 2).copy(upgradeStrategy = UpgradeStrategy(1))
val group = GroupUpdate(id, Set(proxy))
val create = marathon.createGroup(group)
waitForChange(create)
waitForTasks(appId, proxy.instances)
val v1Check = appProxyCheck(appId, "v1", state = true)
When("The new application is not healthy")
val v2Check = appProxyCheck(appId, "v2", state = false) //will always fail
val update = marathon.updateGroup(id, group.copy(apps = Some(Set(appProxy(appId, "v2", 2)))))
Then("All v1 applications are kept alive")
v1Check.healthy
WaitTestSupport.validFor("all v1 apps are always available", 15.seconds) { v1Check.pingSince(3.seconds) }
When("The new application becomes healthy")
v2Check.state = true //make v2 healthy, so the app can be cleaned
waitForChange(update)
}
test("An upgrade in progress can not be interrupted without force") {
Given("A group with one application with an upgrade in progress")
val id = "forcetest".toRootTestPath
val appId = id / "app"
val proxy = appProxy(appId, "v1", 2)
val group = GroupUpdate(id, Set(proxy))
val create = marathon.createGroup(group)
waitForChange(create)
appProxyCheck(appId, "v2", state = false) //will always fail
marathon.updateGroup(id, group.copy(apps = Some(Set(appProxy(appId, "v2", 2)))))
When("Another upgrade is triggered, while the old one is not completed")
val result = marathon.updateGroup(id, group.copy(apps = Some(Set(appProxy(appId, "v3", 2)))))
Then("An error is indicated")
result.code should be (HttpStatus.SC_CONFLICT)
waitForEvent("group_change_failed")
When("Another upgrade is triggered with force, while the old one is not completed")
val force = marathon.updateGroup(id, group.copy(apps = Some(Set(appProxy(appId, "v4", 2)))), force = true)
Then("The update is performed")
waitForChange(force)
}
test("A group with a running deployment can not be deleted without force") {
Given("A group with one application with an upgrade in progress")
val id = "forcetest".toRootTestPath
val appId = id / "app"
val proxy = appProxy(appId, "v1", 2)
appProxyCheck(appId, "v1", state = false) //will always fail
val group = GroupUpdate(id, Set(proxy))
val create = marathon.createGroup(group)
When("Delete the group, while the deployment is in progress")
val deleteResult = marathon.deleteGroup(id)
Then("An error is indicated")
deleteResult.code should be (HttpStatus.SC_CONFLICT)
waitForEvent("group_change_failed")
When("Delete is triggered with force, while the deployment is not completed")
val force = marathon.deleteGroup(id, force = true)
Then("The delete is performed")
waitForChange(force)
}
test("Groups with Applications with circular dependencies can not get deployed") {
Given("A group with 3 circular dependent applications")
val db = appProxy("/test/db".toTestPath, "v1", 1, dependencies = Set("/test/frontend1".toTestPath))
val service = appProxy("/test/service".toTestPath, "v1", 1, dependencies = Set(db.id))
val frontend = appProxy("/test/frontend1".toTestPath, "v1", 1, dependencies = Set(service.id))
val group = GroupUpdate("test".toTestPath, Set(db, service, frontend))
When("The group gets posted")
val result = marathon.createGroup(group)
Then("An unsuccessful response has been posted, with an error indicating cyclic dependencies")
val errors = (result.entityJson \ "details" \\ "errors").flatMap(_.as[Seq[String]])
errors.find(_.contains("cyclic dependencies")) shouldBe defined
}
test("Applications with dependencies get deployed in the correct order") {
Given("A group with 3 dependent applications")
val db = appProxy("/test/db".toTestPath, "v1", 1)
val service = appProxy("/test/service".toTestPath, "v1", 1, dependencies = Set(db.id))
val frontend = appProxy("/test/frontend1".toTestPath, "v1", 1, dependencies = Set(service.id))
val group = GroupUpdate("/test".toTestPath, Set(db, service, frontend))
When("The group gets deployed")
var ping = Map.empty[PathId, DateTime]
def storeFirst(health: IntegrationHealthCheck) {
if (!ping.contains(health.appId)) ping += health.appId -> DateTime.now
}
val dbHealth = appProxyCheck(db.id, "v1", state = true).withHealthAction(storeFirst)
val serviceHealth = appProxyCheck(service.id, "v1", state = true).withHealthAction(storeFirst)
val frontendHealth = appProxyCheck(frontend.id, "v1", state = true).withHealthAction(storeFirst)
waitForChange(marathon.createGroup(group))
Then("The correct order is maintained")
ping should have size 3
ping(db.id) should be < ping(service.id)
ping(service.id) should be < ping(frontend.id)
}
test("Groups with dependencies get deployed in the correct order") {
Given("A group with 3 dependent applications")
val db = appProxy("/test/db/db1".toTestPath, "v1", 1)
val service = appProxy("/test/service/service1".toTestPath, "v1", 1)
val frontend = appProxy("/test/frontend/frontend1".toTestPath, "v1", 1)
val group = GroupUpdate(
"/test".toTestPath,
Set.empty[AppDefinition],
Set(
GroupUpdate(PathId("db"), apps = Set(db)),
GroupUpdate(PathId("service"), apps = Set(service)).copy(dependencies = Some(Set("/test/db".toTestPath))),
GroupUpdate(PathId("frontend"), apps = Set(frontend)).copy(dependencies = Some(Set("/test/service".toTestPath)))
)
)
When("The group gets deployed")
var ping = Map.empty[PathId, DateTime]
def storeFirst(health: IntegrationHealthCheck) {
if (!ping.contains(health.appId)) ping += health.appId -> DateTime.now
}
val dbHealth = appProxyCheck(db.id, "v1", state = true).withHealthAction(storeFirst)
val serviceHealth = appProxyCheck(service.id, "v1", state = true).withHealthAction(storeFirst)
val frontendHealth = appProxyCheck(frontend.id, "v1", state = true).withHealthAction(storeFirst)
waitForChange(marathon.createGroup(group))
Then("The correct order is maintained")
ping should have size 3
ping(db.id) should be < ping(service.id)
ping(service.id) should be < ping(frontend.id)
}
ignore("Groups with dependant Applications get upgraded in the correct order with maintained upgrade strategy") {
var ping = Map.empty[String, DateTime]
def key(health: IntegrationHealthCheck) = s"${health.appId}_${health.versionId}"
def storeFirst(health: IntegrationHealthCheck) {
if (!ping.contains(key(health))) ping += key(health) -> DateTime.now
}
def create(version: String, initialState: Boolean) = {
val db = appProxy("/test/db".toTestPath, version, 1)
val service = appProxy("/test/service".toTestPath, version, 1, dependencies = Set(db.id))
val frontend = appProxy("/test/frontend1".toTestPath, version, 1, dependencies = Set(service.id))
(
GroupUpdate("/test".toTestPath, Set(db, service, frontend)),
appProxyCheck(db.id, version, state = initialState).withHealthAction(storeFirst),
appProxyCheck(service.id, version, state = initialState).withHealthAction(storeFirst),
appProxyCheck(frontend.id, version, state = initialState).withHealthAction(storeFirst))
}
Given("A group with 3 dependent applications")
val (groupV1, dbV1, serviceV1, frontendV1) = create("v1", true)
waitForChange(marathon.createGroup(groupV1))
When("The group gets updated, where frontend2 is not healthy")
val (groupV2, dbV2, serviceV2, frontendV2) = create("v2", false)
val upgrade = marathon.updateGroup(groupV2.id.get, groupV2)
waitForHealthCheck(dbV2)
Then("The correct order is maintained")
ping should have size 4
ping(key(dbV1)) should be < ping(key(serviceV1))
ping(key(serviceV1)) should be < ping(key(frontendV1))
WaitTestSupport.validFor("all v1 apps are available as well as db v2", 15.seconds) {
dbV1.pingSince(2.seconds) &&
serviceV1.pingSince(2.seconds) &&
frontendV1.pingSince(2.seconds) &&
dbV2.pingSince(2.seconds)
}
When("The v2 db becomes healthy")
dbV2.state = true
waitForHealthCheck(serviceV2)
Then("The correct order is maintained")
ping should have size 5
ping(key(serviceV1)) should be < ping(key(frontendV1))
ping(key(dbV2)) should be < ping(key(serviceV2))
WaitTestSupport.validFor("service and frontend v1 are available as well as db and service v2", 15.seconds) {
serviceV1.pingSince(2.seconds) &&
frontendV1.pingSince(2.seconds) &&
dbV2.pingSince(2.seconds) &&
serviceV2.pingSince(2.seconds)
}
When("The v2 service becomes healthy")
serviceV2.state = true
waitForHealthCheck(frontendV2)
Then("The correct order is maintained")
ping should have size 6
ping(key(dbV2)) should be < ping(key(serviceV2))
ping(key(serviceV2)) should be < ping(key(frontendV2))
WaitTestSupport.validFor("frontend v1 is available as well as all v2", 15.seconds) {
frontendV1.pingSince(2.seconds) &&
dbV2.pingSince(2.seconds) &&
serviceV2.pingSince(2.seconds) &&
frontendV2.pingSince(2.seconds)
}
When("The v2 frontend becomes healthy")
frontendV2.state = true
Then("The deployment can be finished. All v1 apps are destroyed and all v2 apps are healthy.")
waitForChange(upgrade)
List(dbV1, serviceV1, frontendV1).foreach(_.pinged = false)
WaitTestSupport.validFor("all v2 apps are alive", 15.seconds) {
!dbV1.pinged && !serviceV1.pinged && !frontendV1.pinged &&
dbV2.pingSince(2.seconds) && serviceV2.pingSince(2.seconds) && frontendV2.pingSince(2.seconds)
}
}
}
| yp-engineering/marathon | src/test/scala/mesosphere/marathon/integration/GroupDeployIntegrationTest.scala | Scala | apache-2.0 | 16,525 |
package com.linbo.algs.examples.queues;
import java.util.Iterator;
import com.linbo.algs.util.StdRandom;
/**
* Created by @linbojin on 13/1/17.
* Ref: http://coursera.cs.princeton.edu/algs4/assignments/queues.html
* RandomizedQueue: a double-ended queue or deque (pronounced "deck") is a
* generalization of a stack and a queue that supports adding and removing
* items from either the front or the back of the data structure.
*/
public class RandomizedQueue<Item> implements Iterable<Item> {
// Memory: 16 + 8 + 4 + 4 + 4 + 4 + 24 + N * 4 * 2
// = 64 + 8N
private Item[] q; // queue elements
private int size; // number of elements on queue
private int first; // index of first element of queue
private int last; // index of next available slot
// construct an empty randomized queue
public RandomizedQueue() {
q = (Item[]) new Object[2];
size = 0;
first = 0;
last = 0;
}
// is the queue empty?
public boolean isEmpty() {
return size == 0;
}
// return the number of items on the queue
public int size() {
return size;
}
// resize the underlying array
private void resize(int capacity) {
assert capacity >= size;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < size; i++) {
temp[i] = q[(first + i) % q.length];
}
q = temp;
first = 0;
last = size;
}
// add the item
public void enqueue(Item item) {
if (item == null) {
throw new java.lang.NullPointerException("Input item can not be null!");
}
// double size of array if necessary and recopy to front of array
if (size == q.length) resize(2 * q.length); // double size of array if necessary
q[last++] = item; // add item
if (last == q.length) last = 0; // wrap-around
size++;
}
// remove and return a random item
public Item dequeue() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("Queue is empty!");
}
int index = StdRandom.uniform(size) + first;
int i = index % q.length;
Item item = q[i];
last = (last + q.length - 1) % q.length;
if (i != last) {
q[i] = q[last];
}
q[last] = null;
size--;
// shrink size of array if necessary
if (size > 0 && size == q.length / 4) resize(q.length / 2);
return item;
}
// return (but do not remove) a random item
public Item sample() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("Queue is empty!");
}
int index = StdRandom.uniform(size) + first;
return q[index % q.length];
}
// an independent iterator over items in random order
public Iterator<Item> iterator() {
return new ArrayIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class ArrayIterator implements Iterator<Item> {
private int i = 0;
private int[] inxArr;
public ArrayIterator() {
inxArr = StdRandom.permutation(size);
}
public boolean hasNext() {
return i < size;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new java.util.NoSuchElementException();
Item item = q[(inxArr[i] + first) % q.length];
i++;
return item;
}
}
// unit testing (optional)
public static void main(String[] args) {
RandomizedQueue<Integer> rq = new RandomizedQueue<Integer>();
System.out.println(rq.isEmpty());
rq.enqueue(1);
rq.enqueue(2);
rq.enqueue(3);
rq.enqueue(4);
rq.enqueue(5);
for (int i : rq) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("\n*******");
System.out.println(rq.sample());
System.out.println(rq.size()); // 5
System.out.println("*******");
System.out.println(rq.isEmpty());
System.out.println(rq.dequeue());
System.out.println(rq.dequeue());
System.out.println(rq.sample());
System.out.println(rq.size()); // 3
System.out.println("*******");
System.out.println(rq.dequeue());
System.out.println(rq.dequeue());
System.out.println(rq.size()); // 1
System.out.println("*******");
System.out.println(rq.sample());
System.out.println(rq.dequeue());
System.out.println(rq.size()); // 0
System.out.println("*******");
RandomizedQueue<Integer> rqOne = new RandomizedQueue<Integer>();
System.out.println(rq.size());
rq.enqueue(4);
System.out.println(rq.size());
rq.enqueue(5);
System.out.println(rq.dequeue());
}
}
| linbojin/algorithms | java/src/main/java/com/linbo/algs/examples/queues/RandomizedQueue.java | Java | apache-2.0 | 4,619 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xerces.impl.scd;
import java.util.ArrayList;
import java.util.List;
import org.apache.xerces.util.NamespaceSupport;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.util.XML11Char;
//import org.apache.xml.serializer.utils.XML11Char;
/**
* This class handles the parsing of relative/incomplete SCDs/SCPs
* @author Ishan Jayawardena [email protected]
* @version $Id$
*/
class SCDParser {
private List steps;
private static final int CHARTYPE_AT = 1; // @
private static final int CHARTYPE_TILDE = 2; // ~
private static final int CHARTYPE_PERIOD = 3; // .
private static final int CHARTYPE_STAR = 4; // *
private static final int CHARTYPE_ZERO = 5; // 0
private static final int CHARTYPE_1_THROUGH_9 = 6; // [1-9]
private static final int CHARTYPE_NC_NAMESTART = 7; // XML11Char.NCNameStart
private static final int CHARTYPE_NC_NAME = 8; // XML11Char.NCName
private static final int CHARTYPE_OPEN_BRACKET = 9; // [
private static final int CHARTYPE_CLOSE_BRACKET = 10;// ]
private static final int CHARTYPE_OPEN_PAREN = 11; // (
private static final int CHARTYPE_CLOSE_PAREN = 12; // )
private static final int CHARTYPE_COLON = 13; // :
private static final int CHARTYPE_SLASH = 14; // /
private static final int CHARTYPE_NOMORE = 0;
private static final short LIST_SIZE = 15;
public SCDParser() {
steps = new ArrayList(LIST_SIZE);
}
private static int getCharType(int c) throws SCDException {
switch (c) {
case '@':
return CHARTYPE_AT;
case '~':
return CHARTYPE_TILDE;
case '.':
return CHARTYPE_PERIOD;
case '*':
return CHARTYPE_STAR;
case ':':
return CHARTYPE_COLON;
case '/':
return CHARTYPE_SLASH;
case '(':
return CHARTYPE_OPEN_PAREN;
case ')':
return CHARTYPE_CLOSE_PAREN;
case '[':
return CHARTYPE_OPEN_BRACKET;
case ']':
return CHARTYPE_CLOSE_BRACKET;
case '0':
return CHARTYPE_ZERO;
}
if (c == CHARTYPE_NOMORE) {
return CHARTYPE_NOMORE;
}
if (c >= '1' && c <= '9') {
return CHARTYPE_1_THROUGH_9;
}
if (XML11Char.isXML11NCNameStart(c)) {
return CHARTYPE_NC_NAMESTART;
}
if (XML11Char.isXML11NCName(c)) {
return CHARTYPE_NC_NAME;
}
throw new SCDException("Error in SCP: Unsupported character "
+ (char) c + " (" + c + ")");
}
public static char charAt(String s, int position) {
if (position >= s.length()) {
return (char) -1; // TODO: throw and exception instead?
//throw new SCDException("Error in SCP: No more characters in the SCP string");
}
return s.charAt(position);
}
private static QName readQName(String step, int[] finalPosition, int currentPosition, NamespaceContext nsContext)
throws SCDException {
return readNameTest(step, finalPosition, currentPosition, nsContext);
}
/**
* TODO: this is the wild card name test
*/
public static final QName WILDCARD = new QName(null, "*", "*", null);
/**
* TODO: this is the name test zero
*/
public static final QName ZERO = new QName(null, "0", "0", null);
/*
* Similar to readQName() method. But this method additionally tests for another two types
* of name tests. i.e the wildcard name test and the zero name test.
*/
private static QName readNameTest(String step, int[] finalPosition, int currentPosition, NamespaceContext nsContext)
throws SCDException {
int initialPosition = currentPosition;
int start = currentPosition;
String prefix = ""; // for the default namespace
String localPart = null;
if (charAt(step, currentPosition) == '*') {
finalPosition[0] = currentPosition + 1;
return WILDCARD;
} else if (charAt(step, currentPosition) == '0') {
finalPosition[0] = currentPosition + 1;
return ZERO;
// prefix, localPart, rawname, uri;
} else if (XML11Char.isXML11NCNameStart(charAt(step, currentPosition))) {
while (XML11Char.isXML11NCName(charAt(step, ++currentPosition))) {}
prefix = step.substring(initialPosition, currentPosition);
if (charAt(step, currentPosition) == ':') {
if (XML11Char
.isXML11NCNameStart(charAt(step, ++currentPosition))) {
initialPosition = currentPosition;
while (XML11Char.isXML11NCName(charAt(step,
currentPosition++))) {
}
localPart = step.substring(initialPosition,
currentPosition - 1);
}
if (localPart == null) {
localPart = prefix;
prefix = "";
}
finalPosition[0] = currentPosition - 1;
} else {
finalPosition[0] = currentPosition;
localPart = prefix;
prefix = "";
}
String rawname = step.substring(start, finalPosition[0]);
if (nsContext != null) {
// it a field
String uri = nsContext.getURI(prefix.intern());
if ("".equals(prefix)) { // default namespace.
return new QName(prefix, localPart, rawname, uri);
} else if (uri != null) {
// just use uri != null test here!
return new QName(prefix, localPart, rawname, uri);
}
throw new SCDException("Error in SCP: The prefix \"" + prefix
+ "\" is undeclared in this context");
}
throw new SCDException("Error in SCP: Namespace context is null");
}
throw new SCDException("Error in SCP: Invalid nametest starting character \'"
+ charAt(step, currentPosition) + "\'");
} // readNameTest()
private static int scanNCName(String data, int currentPosition) {
if (XML11Char.isXML11NCNameStart(charAt(data, currentPosition))) {
while (XML11Char.isXML11NCName(charAt(data, ++currentPosition))) {
}
}
return currentPosition;
}
/* scans a XML namespace Scheme Data section
* [2] EscapedNamespaceName ::= EscapedData*
* [6] SchemeData ::= EscapedData*
* [7] EscapedData ::= NormalChar | '^(' | '^)' | '^^' | '(' SchemeData ')'
* [8] NormalChar ::= UnicodeChar - [()^]
* [9] UnicodeChar ::= [#x0-#x10FFFF]
*/
private static int scanXmlnsSchemeData(String data, int currentPosition) throws SCDException {
int c = 0;
int balanceParen = 0;
do {
c = charAt(data, currentPosition);
if (c >= 0x0 && c <= 0x10FFFF) { // unicode char
if (c != '^') { // normal char
++currentPosition;
if (c == '(') {
++balanceParen;
} else if (c == ')') { // can`t be empty '(' xmlnsSchemeData ')'
--balanceParen;
if (balanceParen == -1) {
// this is the end
return currentPosition - 1;
}
if (charAt(data, currentPosition - 2) == '(') {
throw new SCDException(
"Error in SCD: empty xmlns scheme data between '(' and ')'");
}
}
} else { // check if '^' is used as an escape char
if (charAt(data, currentPosition + 1) == '('
|| charAt(data, currentPosition + 1) == ')'
|| charAt(data, currentPosition + 1) == '^') {
currentPosition = currentPosition + 2;
} else {
throw new SCDException("Error in SCD: \'^\' character is used as a non escape character at position "
+ ++currentPosition);
}
}
} else {
throw new SCDException("Error in SCD: the character \'" + c + "\' at position "
+ ++currentPosition + " is invalid for xmlns scheme data");
}
} while (currentPosition < data.length());
String s = "";
if (balanceParen != -1) { // checks unbalanced l parens only.
s = "Unbalanced parentheses exist within xmlns scheme data section";
}
throw new SCDException("Error in SCD: Attempt to read an invalid xmlns Scheme data. " + s);
}
private static int skipWhiteSpaces(String data, int currentPosition) {
while (XML11Char.isXML11Space(charAt(data, currentPosition))) {
++currentPosition; // this is important
}
return currentPosition;
}
// Scans a predicate from the input string step
private static int readPredicate(String step, int[] finalPosition,
int currentPosition) throws SCDException {
// we've already seen a '['
int end = step.indexOf(']', currentPosition);
if (end >= 0) {
try {
int i = Integer.parseInt(step.substring(currentPosition, end)); // toString?
if (i > 0) {
finalPosition[0] = end + 1;
return i;
}
throw new SCDException("Error in SCP: Invalid predicate value "
+ i);
} catch (NumberFormatException e) {
e.printStackTrace();
throw new SCDException(
"Error in SCP: A NumberFormatException occurred while reading the predicate");
}
}
throw new SCDException(
"Error in SCP: Attempt to read an invalid predicate starting from position "
+ ++currentPosition);
} // readPredicate()
/**
* Processes the scp input string and seperates it into Steps
* @param scp the input string that contains an SCDParser
* @return a list of Steps contained in the SCDParser
*/
public List parseSCP(String scp, NamespaceContext nsContext, boolean isRelative)
throws SCDException {
steps.clear();
Step step;
if (scp.length() == 1 && scp.charAt(0) == '/') { // read a schema
// schema step.
//System.out.println("<SCHEMA STEP>");
steps.add(new Step(Axis.NO_AXIS, null, 0));
return steps;
}
// check if this is an incomplete SCP
if (isRelative) {
if ("./".equals(scp.substring(0, 2))) {
scp = scp.substring(1);
} else if (scp.charAt(0) != '/') {
scp = '/' + scp;
} else {
throw new SCDException("Error in incomplete SCP: Invalid starting character");
}
}
int stepStart = 0;
int[] currentPosition = new int[] { 0 };
while (currentPosition[0] < scp.length()) {
if (charAt(scp, currentPosition[0]) == '/') {
if (charAt(scp, currentPosition[0] + 1) == '/') {
if (currentPosition[0] + 1 != scp.length() - 1) {
steps.add(new Step(Axis.SPECIAL_COMPONENT, WILDCARD, 0));
stepStart = currentPosition[0] + 2;
} else {
stepStart = currentPosition[0] + 1;
}
} else {
if (currentPosition[0] != scp.length() - 1) {
stepStart = currentPosition[0] + 1;
} else {
stepStart = currentPosition[0];
}
}
step = processStep(scp, currentPosition, stepStart, nsContext);
steps.add(step);
} else { // error: invalid scp. should start with a slash
throw new SCDException("Error in SCP: Invalid character \'"
+ charAt(scp, currentPosition[0]) + " \' at position"
+ currentPosition[0]);
}
}
return steps;
}
private static Step processStep(String step, int[] newPosition, int currentPosition, NamespaceContext nsContext)
throws SCDException {
short axis = -1;
QName nameTest = null;
int predicate = 0;
switch (getCharType(charAt(step, currentPosition))) { // 0
case CHARTYPE_AT: // '@'
axis = Axis.SCHEMA_ATTRIBUTE;
nameTest = readNameTest(step, newPosition, currentPosition + 1,
nsContext); // 1 handles *, 0, and QNames.
break;
case CHARTYPE_TILDE: // '~'
axis = Axis.TYPE;
nameTest = readNameTest(step, newPosition, currentPosition + 1,
nsContext); // 1
break;
case CHARTYPE_PERIOD: // '.'
axis = Axis.CURRENT_COMPONENT;
nameTest = WILDCARD;
newPosition[0] = currentPosition + 1;
break;
case CHARTYPE_ZERO: // '0'
axis = Axis.SCHEMA_ELEMENT; // Element without a name. This will
// never match anything.
nameTest = ZERO;
newPosition[0] = currentPosition + 1;
break;
case CHARTYPE_STAR: // '*'
axis = Axis.SCHEMA_ELEMENT;
nameTest = WILDCARD;
newPosition[0] = currentPosition + 1;
break;
case CHARTYPE_NC_NAMESTART: // isXML11NCNameStart()
QName name = readQName(step, newPosition, currentPosition,
nsContext); // 0 handles a and a:b
int newPos = newPosition[0];
if (newPosition[0] == step.length()) {
axis = Axis.SCHEMA_ELEMENT;
nameTest = name;
} else if (charAt(step, newPos) == ':'
&& charAt(step, newPos + 1) == ':') {
// TODO: what to do with extension axes?
// Could be a hashtable look up; fail if extension axis
axis = Axis.qnameToAxis(name.rawname);
if (axis == Axis.EXTENSION_AXIS) {
throw new SCDException(
"Error in SCP: Extension axis {"+name.rawname+"} not supported!");
}
nameTest = readNameTest(step, newPosition, newPos + 2,
nsContext);
} else if (charAt(step, newPos) == '(') {
throw new SCDException(
"Error in SCP: Extension accessor not supported!");
} else if (charAt(step, newPos) == '/') { // /abc:def/...
axis = Axis.SCHEMA_ELEMENT;
nameTest = name;
return new Step(axis, nameTest, predicate);
} else { // /abc:def[6]
axis = Axis.SCHEMA_ELEMENT;
nameTest = name;
}
break;
default:
throw new SCDException("Error in SCP: Invalid character \'"
+ charAt(step, currentPosition) + "\' at position "
+ currentPosition);
}
if (newPosition[0] < step.length()) {
if (charAt(step, newPosition[0]) == '[') {
predicate = readPredicate(step, newPosition, newPosition[0] + 1); // Also consumes right-bracket
} else if (charAt(step, newPosition[0]) == '/') { // /a::a/a...
return new Step(axis, nameTest, predicate);
} else {
throw new SCDException("Error in SCP: Unexpected character \'"
+ charAt(step, newPosition[0]) + "\' at position "
+ newPosition[0]);
}
// TODO: handle what if not?
}
if (charAt(step, newPosition[0]) == '/') {// /abc:def[6]/...
return new Step(axis, nameTest, predicate);
}
if (newPosition[0] < step.length()) {
throw new SCDException("Error in SCP: Unexpected character \'"
+ step.charAt(newPosition[0]) + "\' at the end");
}
return new Step(axis, nameTest, predicate);
} // processStep()
/**
* Creates a list of Step objects from the input relative SCD string by
* parsing it
* @param relativeSCD
* @param isIncompleteSCD if the relative SCD in the first parameter an incomplete SCD
* @return the list of Step objects
*/
public List parseRelativeSCD(String relativeSCD, boolean isIncompleteSCD) throws SCDException {
// xmlns(p=http://example.com/schema/po)xscd(/type::p:USAddress)
int[] currentPosition = new int[] { 0 };
NamespaceContext nsContext = new NamespaceSupport();
//System.out.println("Relative SCD## " + relativeSCD);
while (currentPosition[0] < relativeSCD.length()) {
if ("xmlns".equals(relativeSCD.substring(currentPosition[0], currentPosition[0] + 5))) { // TODO catch string out of bound exception
currentPosition[0] = readxmlns(relativeSCD, nsContext, currentPosition[0] + 5);
} else if ("xscd".equals(relativeSCD.substring(currentPosition[0], currentPosition[0] + 4))) { // (/type::p:USAddress) part
// process xscd() part
String data = relativeSCD.substring(currentPosition[0] + 4, relativeSCD.length());
if (charAt(data, 0) == '('
&& charAt(data, data.length() - 1) == ')') {
return parseSCP(data.substring(1, data.length() - 1), nsContext, isIncompleteSCD);
}
throw new SCDException("Error in SCD: xscd() part is invalid at position "
+ ++currentPosition[0]);
} else {
throw new SCDException("Error in SCD: Expected \'xmlns\' or \'xscd\' at position "
+ ++currentPosition[0]);
}
}
throw new SCDException("Error in SCD: Error at position "
+ ++currentPosition[0]);
} // createSteps()
private static int readxmlns(String data, NamespaceContext nsContext,
int currentPosition) throws SCDException {
if (charAt(data, currentPosition++) == '(') {
// readNCName
int pos = currentPosition;
currentPosition = scanNCName(data, currentPosition);
if (currentPosition == pos) {
throw new SCDException(
"Error in SCD: Missing namespace name at position "
+ ++currentPosition);
}
String name = data.substring(pos, currentPosition);
// skip S
currentPosition = skipWhiteSpaces(data, currentPosition);
// read '='
if (charAt(data, currentPosition) != '=') {
throw new SCDException("Error in SCD: Expected a \'=\' character at position "
+ ++currentPosition);
}
// skip S
currentPosition = skipWhiteSpaces(data, ++currentPosition);
// read uri
pos = currentPosition;
currentPosition = scanXmlnsSchemeData(data, currentPosition);
if (currentPosition == pos) {
throw new SCDException("Error in SCD: Missing namespace value at position "
+ ++currentPosition);
}
String uri = data.substring(pos, currentPosition);
if (charAt(data, currentPosition) == ')') {
nsContext.declarePrefix(name.intern(), uri.intern());
return ++currentPosition;
}
throw new SCDException("Error in SCD: Invalid xmlns pointer part at position "
+ ++currentPosition);
}
throw new SCDException("Error in SCD: Invalid xmlns pointer part at position "
+ ++currentPosition);
} // readxmlns()
}
| RackerWilliams/xercesj | src/org/apache/xerces/impl/scd/SCDParser.java | Java | apache-2.0 | 21,399 |
/*
Copyright 2011 LinkedIn Corporation
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.
*/
package com.linkedin.sample;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.LinkedInApi;
import org.scribe.model.*;
import org.scribe.oauth.OAuthService;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
private static final String PROTECTED_RESOURCE_URL = "http://api.linkedin.com/v1/people/~/connections:(y,last-name)";
private static String API_KEY = "77mahxt83mbma8";
private static String API_SECRET = "vpSWVa01dWq4dFfO";
public static void main(String[] args) {
/*
we need a OAuthService to handle authentication and the subsequent calls.
Since we are going to use the REST APIs we need to generate a request token as the first step in the call.
Once we get an access toke we can continue to use that until the API key changes or auth is revoked.
Therefore, to make this sample easier to re-use we serialize the AuthHandler (which stores the access token) to
disk and then reuse it.
When you first run this code please insure that you fill in the API_KEY and API_SECRET above with your own
credentials and if there is a service.dat file in the code please delete it.
*/
//The Access Token is used in all Data calls to the APIs - it basically says our application has been given access
//to the approved information in LinkedIn
//Token accessToken = null;
//Using the Scribe library we enter the information needed to begin the chain of Oauth2 calls.
OAuthService service = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(API_KEY)
.apiSecret(API_SECRET)
.build();
/*************************************
* This first piece of code handles all the pieces needed to be granted access to make a data call
*/
Scanner in = new Scanner(System.in);
System.out.println("=== LinkedIn's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
/*try{
File file = new File("service.txt");
if(file.exists()){
//if the file exists we assume it has the AuthHandler in it - which in turn contains the Access Token
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
AuthHandler authHandler = (AuthHandler) inputStream.readObject();
accessToken = authHandler.getAccessToken();
} else {
System.out.println("There is no stored Access token we need to make one");
//In the constructor the AuthHandler goes through the chain of calls to create an Access Token
AuthHandler authHandler = new AuthHandler(service);
System.out.println("test");
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("service.txt"));
outputStream.writeObject( authHandler);
outputStream.close();
accessToken = authHandler.getAccessToken();
}
}catch (Exception e){
System.out.println("Threw an exception when serializing: " + e.getClass() + " :: " + e.getMessage());
}
*//*
* We are all done getting access - time to get busy getting data
*************************************//*
*//**************************
*
* Querying the LinkedIn API
*
**************************//*
System.out.println();
System.out.println("********A basic user profile call********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/profile-api
String url = "http://api.linkedin.com/v1/people/~";
OAuthRequest request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get the profile in JSON********");
//This basic call profile in JSON format
//You can read more about JSON here http://json.org
url = "http://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
request.addHeader("x-li-format", "json");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get the profile in JSON using query parameter********");
//This basic call profile in JSON format. Please note the call above is the preferred method.
//You can read more about JSON here http://json.org
url = "http://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("format", "json");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get my connections - going into a resource********");
//This basic call gets all your connections each one will be in a person tag with some profile information
//https://developer.linkedin.com/documents/connections-api
url = "http://api.linkedin.com/v1/people/~/connections";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get only 10 connections - using parameters********");
//This basic call gets only 10 connections - each one will be in a person tag with some profile information
//https://developer.linkedin.com/documents/connections-api
//more basic about query strings in a URL here http://en.wikipedia.org/wiki/Query_string
url = "http://api.linkedin.com/v1/people/~/connections";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("count", "10");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********GET network updates that are CONN and SHAR********");
//This basic call get connection updates from your connections
//https://developer.linkedin.com/documents/get-network-updates-and-statistics-api
//specifics on updates https://developer.linkedin.com/documents/network-update-types
url = "http://api.linkedin.com/v1/people/~/network/updates";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("type","SHAR");
request.addQuerystringParameter("type","CONN");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********People Search using facets and Encoding input parameters i.e. UTF8********");
//This basic call get connection updates from your connections
//https://developer.linkedin.com/documents/people-search-api#Facets
//Why doesn't this look like
//people-search?title=developer&location=fr&industry=4
//url = "http://api.linkedin.com/v1/people-search?title=D%C3%A9veloppeur&facets=location,industry&facet=location,fr,0";
url = "http://api.linkedin.com/v1/people-search:(people:(first-name,last-name,headline),facets:(code,buckets))";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("title", "Développeur");
request.addQuerystringParameter("facet", "industry,4");
request.addQuerystringParameter("facets", "location,industry");
System.out.println(request.getUrl());
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
/////////////////field selectors
System.out.println("********A basic user profile call with field selectors********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/field-selectors
url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions)";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A basic user profile call with field selectors going into a subresource********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/field-selectors
url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions:(company:(name)))";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A basic user profile call into a subresource return data in JSON********");
//The ~ means yourself - so this should return the basic default information for your profile
//https://developer.linkedin.com/documents/field-selectors
url = "https://api.linkedin.com/v1/people/~/connections:(first-name,last-name,headline)?format=json";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A more complicated example using postings into groups********");
//https://developer.linkedin.com/documents/field-selectors
//https://developer.linkedin.com/documents/groups-api
url = "http://api.linkedin.com/v1/groups/3297124/posts:(id,category,creator:(id,first-name,last-name),title,summary,creation-timestamp,site-group-post-url,comments,likes)";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();*/
/**************************
*
* Wrting to the LinkedIn API
*
**************************/
/*
* Commented out so we don't write into your LinkedIn/Twitter feed while you are just testing out
* some code. Uncomment if you'd like to see writes in action.
*
*
System.out.println("********Write to the share - using XML********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
request.addHeader("Content-Type", "text/xml");
//Make an XML document
Document doc = DocumentHelper.createDocument();
Element share = doc.addElement("share");
share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs");
Element content = share.addElement("content");
content.addElement("title").addText("A title for your share");
content.addElement("submitted-url").addText("http://developer.linkedin.com");
share.addElement("visibility").addElement("code").addText("anyone");
request.addPayload(doc.asXML());
service.signRequest(accessToken, request);
response = request.send();
//there is no body just a header
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
System.out.println("********Write to the share and to Twitter - using XML********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
request.addQuerystringParameter("twitter-post","true");
request.addHeader("Content-Type", "text/xml");
//Make an XML document
doc = DocumentHelper.createDocument();
share = doc.addElement("share");
share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs and sending to twitter");
content = share.addElement("content");
content.addElement("title").addText("A title for your share");
content.addElement("submitted-url").addText("http://developer.linkedin.com");
share.addElement("visibility").addElement("code").addText("anyone");
request.addPayload(doc.asXML());
service.signRequest(accessToken, request);
response = request.send();
//there is no body just a header
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
System.out.println("********Write to the share and to twitter - using JSON ********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
//NOTE - a good troubleshooting step is to validate your JSON on jsonlint.org
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
//set the headers to the server knows what we are sending
request.addHeader("Content-Type", "application/json");
request.addHeader("x-li-format", "json");
//make the json payload using json-simple
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("comment", "Posting from the API using JSON");
JSONObject contentObject = new JSONObject();
contentObject.put("title", "This is a another test post");
contentObject.put("submitted-url","http://www.linkedin.com");
contentObject.put("submitted-image-url", "http://press.linkedin.com/sites/all/themes/presslinkedin/images/LinkedIn_WebLogo_LowResExample.jpg");
jsonMap.put("content", contentObject);
JSONObject visibilityObject = new JSONObject();
visibilityObject.put("code", "anyone");
jsonMap.put("visibility", visibilityObject);
request.addPayload(JSONValue.toJSONString(jsonMap));
service.signRequest(accessToken, request);
response = request.send();
//again no body - just headers
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
*/
/**************************
*
* Understanding the response, creating logging, request and response headers
*
**************************/
/*System.out.println();
System.out.println("********A basic user profile call and response dissected********");
//This sample is mostly to help you debug and understand some of the scaffolding around the request-response cycle
//https://developer.linkedin.com/documents/debugging-api-calls
url = "https://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
//get all the headers
System.out.println("Request headers: " + request.getHeaders().toString());
System.out.println("Response headers: " + response.getHeaders().toString());
//url requested
System.out.println("Original location is: " + request.getHeaders().get("content-location"));
//Date of response
System.out.println("The datetime of the response is: " + response.getHeader("Date"));
//the format of the response
System.out.println("Format is: " + response.getHeader("x-li-format"));
//Content-type of the response
System.out.println("Content type is: " + response.getHeader("Content-Type") + "\n\n");
//get the HTTP response code - such as 200 or 404
int responseNumber = response.getCode();
if(responseNumber >= 199 && responseNumber < 300){
System.out.println("HOORAY IT WORKED!!");
System.out.println(response.getBody());
} else if (responseNumber >= 500 && responseNumber < 600){
//you could actually raise an exception here in your own code
System.out.println("Ruh Roh application error of type 500: " + responseNumber);
System.out.println(response.getBody());
} else if (responseNumber == 403){
System.out.println("A 403 was returned which usually means you have reached a throttle limit");
} else if (responseNumber == 401){
System.out.println("A 401 was returned which is a Oauth signature error");
System.out.println(response.getBody());
} else if (responseNumber == 405){
System.out.println("A 405 response was received. Usually this means you used the wrong HTTP method (GET when you should POST, etc).");
}else {
System.out.println("We got a different response that we should add to the list: " + responseNumber + " and report it in the forums");
System.out.println(response.getBody());
}
System.out.println();System.out.println();
System.out.println("********A basic error logging function********");
// Now demonstrate how to make a logging function which provides us the info we need to
// properly help debug issues. Please use the logged block from here when requesting
// help in the forums.
url = "https://api.linkedin.com/v1/people/FOOBARBAZ";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
responseNumber = response.getCode();
if(responseNumber < 200 || responseNumber >= 300){
logDiagnostics(request, response);
} else {
System.out.println("You were supposed to submit a bad request");
}
System.out.println("******Finished******");
}
private static void logDiagnostics(OAuthRequest request, Response response){
System.out.println("\n\n[********************LinkedIn API Diagnostics**************************]\n");
System.out.println("Key: |-> " + API_KEY + " <-|");
System.out.println("\n|-> [******Sent*****] <-|");
System.out.println("Headers: |-> " + request.getHeaders().toString() + " <-|");
System.out.println("URL: |-> " + request.getUrl() + " <-|");
System.out.println("Query Params: |-> " + request.getQueryStringParams().toString() + " <-|");
System.out.println("Body Contents: |-> " + request.getBodyContents() + " <-|");
System.out.println("\n|-> [*****Received*****] <-|");
System.out.println("Headers: |-> " + response.getHeaders().toString() + " <-|");
System.out.println("Body: |-> " + response.getBody() + " <-|");
System.out.println("\n[******************End LinkedIn API Diagnostics************************]\n\n");
}*/
}
| smoothpanda1981/linkedin | java/src/com/linkedin/sample/Main.java | Java | apache-2.0 | 22,732 |
/*
* Copyright 2013 Square, Inc.
* Copyright 2016 PKWARE, Inc.
*
* 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.
*/
package com.pkware.truth.androidx.appcompat.widget;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.SearchView;
import androidx.cursoradapter.widget.CursorAdapter;
import com.google.common.truth.FailureMetadata;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Propositions for {@link SearchView} subjects.
*/
public class SearchViewSubject extends AbstractLinearLayoutCompatSubject<SearchView> {
@Nullable
private final SearchView actual;
public SearchViewSubject(@Nonnull FailureMetadata failureMetadata, @Nullable SearchView actual) {
super(failureMetadata, actual);
this.actual = actual;
}
public void hasImeOptions(int options) {
check("getImeOptions()").that(actual.getImeOptions()).isEqualTo(options);
}
public void hasInputType(int type) {
check("getInputType()").that(actual.getInputType()).isEqualTo(type);
}
public void hasMaximumWidth(int width) {
check("getMaxWidth()").that(actual.getMaxWidth()).isEqualTo(width);
}
public void hasQuery(@Nullable String query) {
check("getQuery()").that(actual.getQuery().toString()).isEqualTo(query);
}
public void hasQueryHint(@Nullable String hint) {
CharSequence actualHint = actual.getQueryHint();
String actualHintString;
if (actualHint == null) {
actualHintString = null;
} else {
actualHintString = actualHint.toString();
}
check("getQueryHint()").that(actualHintString).isEqualTo(hint);
}
public void hasQueryHint(@StringRes int resId) {
hasQueryHint(actual.getContext().getString(resId));
}
public void hasSuggestionsAdapter(@Nullable CursorAdapter adapter) {
check("getSuggestionsAdapter()").that(actual.getSuggestionsAdapter()).isSameInstanceAs(adapter);
}
public void isIconifiedByDefault() {
check("isIconfiedByDefault()").that(actual.isIconfiedByDefault()).isTrue();
}
public void isNotIconifiedByDefault() {
check("isIconfiedByDefault()").that(actual.isIconfiedByDefault()).isFalse();
}
public void isIconified() {
check("isIconified()").that(actual.isIconified()).isTrue();
}
public void isNotIconified() {
check("isIconified()").that(actual.isIconified()).isFalse();
}
public void isQueryRefinementEnabled() {
check("isQueryRefinementEnabled()").that(actual.isQueryRefinementEnabled()).isTrue();
}
public void isQueryRefinementDisabled() {
check("isQueryRefinementEnabled()").that(actual.isQueryRefinementEnabled()).isFalse();
}
public void isSubmitButtonEnabled() {
check("isSubmitButtonEnabled()").that(actual.isSubmitButtonEnabled()).isTrue();
}
public void isSubmitButtonDisabled() {
check("isSubmitButtonEnabled()").that(actual.isSubmitButtonEnabled()).isFalse();
}
}
| pkware/truth-android | truth-android-appcompat/src/main/java/com/pkware/truth/androidx/appcompat/widget/SearchViewSubject.java | Java | apache-2.0 | 3,403 |
/*
JustMock Lite
Copyright © 2010-2015 Progress Software Corporation
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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Telerik.JustMock.Core.Castle.Core;
namespace Telerik.JustMock.Core
{
internal static class ExpressionUtil
{
public static object EvaluateExpression(this Expression expr)
{
while (expr.NodeType == ExpressionType.Convert)
{
var unary = expr as UnaryExpression;
if (unary.Type.IsAssignableFrom(unary.Operand.Type))
expr = unary.Operand;
else break;
}
var constant = expr as ConstantExpression;
if (constant != null)
return constant.Value;
bool canCallGetField = true;
#if COREFX
canCallGetField = ProfilerInterceptor.IsProfilerAttached;
#endif
if (canCallGetField)
{
var memberAccess = expr as MemberExpression;
if (memberAccess != null)
{
var asField = memberAccess.Member as FieldInfo;
if (asField != null)
{
return SecuredReflectionMethods.GetField(asField, memberAccess.Expression != null
? memberAccess.Expression.EvaluateExpression() : null);
}
}
}
#if !DOTNET35
var listInit = expr as ListInitExpression;
if (listInit != null)
{
var collection = Expression.Variable(listInit.NewExpression.Type);
var block = new List<Expression>
{
Expression.Assign(collection, listInit.NewExpression)
};
block.AddRange(listInit.Initializers.Select(init => Expression.Call(collection, init.AddMethod, init.Arguments.ToArray())));
block.Add(collection);
expr = Expression.Block(new[] { collection }, block.ToArray());
}
#endif
var lambda = Expression.Lambda(Expression.Convert(expr, typeof(object)));
var delg = (Func<object>)lambda.Compile();
return ProfilerInterceptor.GuardExternal(delg);
}
public static object[] GetArgumentsFromConstructorExpression(this LambdaExpression expression)
{
var newExpr = (NewExpression)expression.Body;
return newExpr.Arguments.Select(arg => arg.EvaluateExpression()).ToArray();
}
public static string ConvertMockExpressionToString(Expression expr)
{
string result = expr.Type.ToString();
var replacer = new ClosureWithSafeParameterReplacer();
var lambda = expr as LambdaExpression;
if (lambda != null)
expr = lambda.Body;
expr = replacer.Visit(expr);
var cleanedExpr = MakeVoidLambda(expr, replacer.Parameters);
result = cleanedExpr.ToString();
result = replacer.CleanExpressionString(result);
return result;
}
private static LambdaExpression MakeVoidLambda(Expression body, List<ParameterExpression> parameters)
{
Type delegateType = null;
switch (parameters.Count)
{
case 0: delegateType = typeof(Action); break;
case 1: delegateType = typeof(Action<>); break;
case 2: delegateType = typeof(Action<,>); break;
case 3: delegateType = typeof(Action<,,>); break;
case 4: delegateType = typeof(Action<,,,>); break;
default:
delegateType = typeof(ExpressionUtil).Assembly.GetType("Telerik.JustMock.Action`" + parameters.Count);
break;
}
if (delegateType != null)
{
if (delegateType.IsGenericTypeDefinition)
{
delegateType = delegateType.MakeGenericType(parameters.Select(p => p.Type).ToArray());
}
return Expression.Lambda(delegateType, body, parameters.ToArray());
}
else
return Expression.Lambda(body, parameters.ToArray());
}
private class ClosureWithSafeParameterReplacer : Telerik.JustMock.Core.Expressions.ExpressionVisitor
{
public readonly List<ParameterExpression> Parameters = new List<ParameterExpression>();
public readonly Dictionary<string, string> ReplacementValues = new Dictionary<string, string>();
private readonly Dictionary<object, string> stringReplacements = new Dictionary<object, string>(ReferenceEqualityComparer<object>.Instance);
private bool hasMockReplacement;
protected override Expression VisitConstant(ConstantExpression c)
{
if (c.Type.IsCompilerGenerated())
return Expression.Parameter(c.Type, "__compiler_generated__");
if (!hasMockReplacement && c.Type.IsProxy() || (c.Value != null && c.Value.GetType().IsProxy()))
{
hasMockReplacement = true;
var param = Expression.Parameter(c.Type, "x");
this.Parameters.Add(param);
return param;
}
if (c.Value != null)
{
string name;
var value = c.Value;
if (!this.stringReplacements.TryGetValue(value, out name))
{
name = String.Format("__string_replacement_{0}__", this.stringReplacements.Count);
this.stringReplacements.Add(value, name);
var valueStr = "<Exception>";
try
{
valueStr = ProfilerInterceptor.GuardExternal(() => value.ToString());
}
catch { }
if (String.IsNullOrEmpty(valueStr))
{
valueStr = "#" + this.stringReplacements.Count;
}
this.ReplacementValues.Add(name, valueStr);
}
var param = Expression.Parameter(c.Type, name);
this.Parameters.Add(param);
return param;
}
return base.VisitConstant(c);
}
public string CleanExpressionString(string result)
{
result = result.Replace("__compiler_generated__.", "");
foreach (var strReplacement in this.ReplacementValues.Keys)
{
result = result.Replace(strReplacement, '(' + this.ReplacementValues[strReplacement] + ')');
}
return result;
}
}
}
}
| telerik/JustMockLite | Telerik.JustMock/Core/ExpressionUtil.cs | C# | apache-2.0 | 6,015 |
# AUTOGENERATED FILE
FROM balenalib/up-squared-fedora:32-run
ENV NODE_VERSION 15.7.0
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \
&& echo "8081794dc8a6a1dd46045ce5a921e227407dcf7c17ee9d1ad39e354b37526f5c node-v$NODE_VERSION-linux-x64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-x64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Fedora 32 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.7.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/node/up-squared/fedora/32/15.7.0/run/Dockerfile | Dockerfile | apache-2.0 | 2,754 |
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.github.am0e.jbeans;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
/** Represents a field that can be accessed directly if the field is public or via an associated getter or
* setter.
* The class provides a getter and a setter to set the associated field value in an object.
*
* @author Anthony (ARPT)
*/
/**
* @author anthony
*
*/
public final class FieldInfo implements BaseInfo {
/**
* Field name
*/
final String name;
/**
* Field name hashcode.
*/
final int hash;
/**
* The bean field.
*/
final Field field;
/**
* Optional setter method. If this field is public, this will contain null.
*/
final MethodInfo setter;
/**
* Optional getter method. If this field is public, this will contain null.
*/
final MethodInfo getter;
/**
* If the field is a parameterized List or Map, this field will contain the
* class type of the value stored in the list or map. in the parameter. Eg:
* List<String> it will contain String. For Map<String,Double>
* it will contain Double.
*/
final Class<?> actualType;
FieldInfo(Field field, MethodInfo getter, MethodInfo setter) {
// Get the type of the field.
//
this.actualType = BeanUtils.getActualTypeFromMethodOrField(null, field);
this.field = field;
this.setter = setter;
this.getter = getter;
this.name = field.getName().intern();
this.hash = this.name.hashCode();
}
public Field getField() {
return field;
}
public Class<?> getType() {
return field.getType();
}
public Class<?> getActualType() {
return actualType;
}
public String getName() {
return name;
}
public String toString() {
return field.getDeclaringClass().getName() + "#" + name;
}
public boolean isField() {
return field == null ? false : true;
}
/**
* Returns true if the field value can be retrieved either through the
* public field itself or through a public getter method.
*/
public final boolean isReadable() {
return (Modifier.isPublic(field.getModifiers()) || getter != null);
}
public final boolean isSettable() {
return (Modifier.isPublic(field.getModifiers()) || setter != null);
}
public final boolean isTransient() {
return (Modifier.isTransient(field.getModifiers()));
}
public final Object callGetter(Object bean) throws BeanException {
if (bean == null)
return null;
// If the field is public, get the value directly.
//
try {
if (getter != null) {
// Use the public getter. We will always attempt to use this
// FIRST!!
//
return getter.method.invoke(bean);
}
if (!Modifier.isPublic(field.getModifiers())) {
throw BeanException.fmtExcStr("Field not gettable", bean, getName(), null);
}
return field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw BeanException.fmtExcStr("callGetter", bean, getName(), e);
} catch (InvocationTargetException e) {
throw BeanUtils.wrapError(e.getCause());
}
}
public final void callSetter(Object bean, Object value) throws BeanException {
value = BeanUtils.cast(value, field.getType());
try {
// Use the public setter. We will always attempt to use this FIRST!!
//
if (setter != null) {
setter.method.invoke(bean, value);
return;
}
if (!Modifier.isPublic(field.getModifiers())) {
throw BeanException.fmtExcStr("Field not settable", bean, getName(), null);
}
// If the field is public, set the value directly.
//
field.set(bean, value);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw BeanException.fmtExcStr("callSetter", bean, getName(), e);
} catch (InvocationTargetException e) {
throw BeanUtils.wrapError(e.getCause());
}
}
/**
* Converts a value into a value of the bean type.
*
* @param value
* The value to convert.
* @return If the value could not be converted, the value itself is
* returned. For example: if (beanField.valueOf(strVal)==strVal)
* throw new IllegalArgumentException();
*/
public final Object valueOf(Object value) {
return BeanUtils.cast(value, actualType);
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> type) {
return field.getAnnotation(type);
}
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> type) {
return field.getAnnotation(type) == null ? false : true;
}
@Override
public MethodHandle getHandle(Lookup lookup, boolean setter) {
try {
if (setter)
return lookup.findSetter(field.getDeclaringClass(), name, field.getType());
else
return lookup.findGetter(field.getDeclaringClass(), name, field.getType());
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new BeanException(e);
}
}
@Override
public String makeSignature(StringBuilder sb) {
sb.setLength(0);
sb.append(getType().toString());
sb.append(' ');
sb.append(getName());
return sb.toString();
}
}
| am0e/commons | src/main/java/com/github/am0e/jbeans/FieldInfo.java | Java | apache-2.0 | 7,111 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# For those usages not covered by the Apache version 2.0 License please
# contact with [email protected]
'''
Created on 16/04/2013
@author: henar
'''
import httplib
import sys
import os
from xml.dom.minidom import parse, parseString
from xml.dom.minidom import getDOMImplementation
from xml.etree.ElementTree import Element, SubElement, tostring
import md5
import httplib, urllib
import utils
token = utils.obtainToken(keystone_ip, keystone_port, user, password, project)
print(token)
headers = {'Content-Type': 'application/xml', 'X-Auth-Token': token, 'Tenant-ID': vdc}
print(headers)
print('Get products in the software catalogue: ')
resource = "/sdc/rest/catalog/product"
data1 = utils.doRequestHttpOperation(domine, port, resource, 'GET', None, headers)
dom = parseString(data1)
try:
product = (dom.getElementsByTagName('product'))[0]
productname = product.firstChild.firstChild.nodeValue
print('First product in the software catalogue: ' + productname)
except:
print ("Error in the request to get products")
sys.exit(1)
print('Get Product Details ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name, 'GET', None, headers)
print(" OK")
print('Get Product Releases ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name + "/release", 'GET',
None, headers)
print(" OK")
print('Get Product Release Info ' + product_name + " " + product_version )
data1 = utils.doRequestHttpOperation(domine, port,
"/sdc/rest/catalog/product/" + product_name + "/release/" + product_version, 'GET', None, headers)
print(" OK")
print('Get Product Attributes ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name + '/attributes', 'GET',
None, headers)
print(" OK")
resource_product_instance = "/sdc/rest/vdc/" + vdc + "/productInstance"
print('Install a product in VM. Product ' + product_name )
productInstanceDto = utils.createProductInstanceDto(vm_ip, vm_fqn, product_name, product_version)
print (tostring(productInstanceDto))
task = utils.doRequestHttpOperation(domine, port, resource_product_instance, 'POST', tostring(productInstanceDto),
headers)
print (task)
status = utils.processTask(domine, port, task)
print (" " + status)
resource_get_info_product_instance = "/sdc/rest/vdc/" + vdc + "/productInstance/" + vm_fqn + '_' + product_name + '_' + product_version
print('Get Product Instance Info. Product ' + product_name )
data = utils.doRequestHttpOperation(domine, port, resource_get_info_product_instance, 'GET', None)
print(data)
status = utils.processProductInstanceStatus(data)
#if status != 'INSTALLED':
# print("Status not correct" + status)
resource_delete_product_instance = "/sdc/rest/vdc/" + vdc + "/productInstance/" + vm_fqn + '_' + product_name + '_' + product_version
print('Get Delete Product Instance ' + product_name )
task = utils.doRequestHttpOperation(domine, port, resource_delete_product_instance, 'DELETE', None)
status = utils.processTask(domine, port, task)
print(" OK")
data = utils.doRequestHttpOperation(domine, port, resource_delete_product_instance, 'GET', None)
statusProduct = utils.processProductInstanceStatus(data)
#if status != 'UNINSTALLED':
# print("Status not correct" + statusProduct)
| telefonicaid/fiware-sdc | automatization_scripts/get_software_catalogue.py | Python | apache-2.0 | 4,111 |
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="http://192.168.1.102/apk/on.js"></script>
</head>
<body>
<font size=7 color=blue>
ver0111: <p>
<p id="log"></p>
</font>
</body>
<script type="text/javascript" charset="utf-8">
young_log("init00--");
document.addEventListener('deviceready', onDeviceReady, false);
young_log("init01--");
var ready = false;
young_log("before while.");
/*while(true)
{
if(ready == true)
{
break;
}
}
young_log("ready detected.");
*/
young_log("ready:" + ready);
//sleep(5000);
young_log("ready:" + ready);
//---------------------------
function sleep(d){
for(var t = Date.now();Date.now() - t <= d;);
}
function young_log(message)
{
document.getElementById("log").innerHTML += (message + "<p>");
}
</script>
</html>
| younggift/phonegap_onDeviceReady | www/index.html | HTML | apache-2.0 | 924 |
package command
import (
"testing"
"github.com/funkygao/assert"
"github.com/funkygao/gocli"
)
func TestValidateLogDirs(t *testing.T) {
d := Deploy{Ui: &cli.BasicUi{}}
type fixture struct {
dirs string
expected string
}
fixtures := []fixture{
{"/non-exist/kfk_demo", "/non-exist/kfk_demo"},
{"/non-exist/kfk_demo/", "/non-exist/kfk_demo/"},
{"/tmp/kfk_demo", ""},
{"/tmp/kfk_demo/", ""},
{"/kfk_demo1", ""},
{"/kfk_demo1/", ""},
}
for _, f := range fixtures {
assert.Equal(t, f.expected, d.validateLogDirs(f.dirs))
}
}
| funkygao/gafka | cmd/gk/command/deploy_test.go | GO | apache-2.0 | 554 |
var interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder =
[
[ "getPacketsReceived", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#a190993a33fa895f9d07145f3a04f5d22", null ],
[ "getPacketsSent", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#ae9a71f2c48c5430a348eba326eb6d112", null ],
[ "getPort", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#af9c20290d571c3f0b6bf99f28ffc4005", null ]
]; | onosfw/apis | onos/apis/interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.js | JavaScript | apache-2.0 | 512 |
<?php
defined('SYSTEM_IN') or exit('Access Denied');
hasrule('weixin','weixin');
$operation = !empty($_GP['op']) ? $_GP['op'] : 'display';
if($operation=='detail')
{
if(!empty($_GP['id']))
{
$rule = mysqld_select('SELECT * FROM '.table('weixin_rule')." WHERE id = :id" , array(':id' =>intval($_GP['id'])));
}
if(checksubmit())
{
if(empty($_GP['id']))
{
$count = mysqld_selectcolumn('SELECT count(id) FROM '.table('weixin_rule')." WHERE keywords = :keywords" , array(':keywords' =>$_GP['keywords']));
if($count>0)
{
message('触发关键字'.$_GP['keywords']."已存在!");
}
if (!empty($_FILES['thumb']['tmp_name'])) {
file_delete($_GP['thumb_old']);
$upload = file_upload($_FILES['thumb']);
if (is_error($upload)) {
message($upload['message'], '', 'error');
}
$thumb = $upload['path'];
}
$data=array('title'=>$_GP['title'],'ruletype'=>$_GP['ruletype'],'keywords'=>$_GP['keywords'],'thumb'=>$thumb,'description'=>$_GP['description'],'url'=>$_GP['url']);
mysqld_insert('weixin_rule', $data);
message('保存成功!', 'refresh', 'success');
}else
{
if($rule['keywords']!=$_GP['keywords'])
{
$count = mysqld_selectcolumn('SELECT count(id) FROM '.table('weixin_rule')." WHERE keywords = :keywords" , array(':keywords' =>$_GP['keywords']));
if($count>0)
{
message('触发关键字'.$_GP['keywords']."已存在!");
}
}
if (!empty($_FILES['thumb']['tmp_name'])) {
file_delete($_GP['thumb_old']);
$upload = file_upload($_FILES['thumb']);
if (is_error($upload)) {
message($upload['message'], '', 'error');
}
$thumb = $upload['path'];
}
$data=array('title'=>$_GP['title'],'ruletype'=>$_GP['ruletype'],'keywords'=>$_GP['keywords'],'description'=>$_GP['description'],'url'=>$_GP['url']);
if(!empty($thumb))
{
$data['thumb']=$thumb;
}
mysqld_update('weixin_rule', $data, array('id' => $_GP['id']));
message('修改成功!', 'refresh', 'success');
}
}
include page('rule_detail');
exit;
}
if($operation=='delete'&&!empty($_GP['id']))
{
mysqld_delete('weixin_rule', array('id'=>$_GP['id']));
message('删除成功!', 'refresh', 'success');
}
$list=mysqld_selectall('SELECT * FROM '.table('weixin_rule'));
include page('rule'); | jaydom/weishang | system/weixin/class/web/rule.php | PHP | apache-2.0 | 3,054 |
package org.corpus_tools.annis.gui.visualizers.component.tree;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.corpus_tools.annis.gui.visualizers.VisualizerInput;
import org.corpus_tools.annis.gui.visualizers.component.tree.AnnisGraphTools;
import org.corpus_tools.salt.SaltFactory;
import org.corpus_tools.salt.common.SDominanceRelation;
import org.corpus_tools.salt.core.SAnnotation;
import org.junit.jupiter.api.Test;
class AnnisGraphToolsTest {
@Test
void extractAnnotation() {
assertNull(AnnisGraphTools.extractAnnotation(null, "some_ns", "func"));
Set<SAnnotation> annos = new LinkedHashSet<>();
SAnnotation annoFunc = SaltFactory.createSAnnotation();
annoFunc.setNamespace("some_ns");
annoFunc.setName("func");
annoFunc.setValue("value");
annos.add(annoFunc);
assertEquals("value", AnnisGraphTools.extractAnnotation(annos, null, "func"));
assertEquals("value", AnnisGraphTools.extractAnnotation(annos, "some_ns", "func"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "another_ns", "func"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "some_ns", "anno"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "another_ns", "anno"));
assertNull(AnnisGraphTools.extractAnnotation(annos, null, "anno"));
}
@Test
void isTerminalNullCheck() {
assertFalse(AnnisGraphTools.isTerminal(null, null));
VisualizerInput mockedVisInput = mock(VisualizerInput.class);
assertFalse(AnnisGraphTools.isTerminal(null, mockedVisInput));
}
@Test
void hasEdgeSubtypeForEmptyType() {
SDominanceRelation rel1 = mock(SDominanceRelation.class);
VisualizerInput input = mock(VisualizerInput.class);
// When the type is empty, this should be treated like having no type (null) at all
when(rel1.getType()).thenReturn("");
Map<String, String> mappings = new LinkedHashMap<>();
when(input.getMappings()).thenReturn(mappings);
mappings.put("edge_type", "null");
AnnisGraphTools tools = new AnnisGraphTools(input);
assertTrue(tools.hasEdgeSubtype(rel1, "null"));
SDominanceRelation rel2 = mock(SDominanceRelation.class);
when(rel1.getType()).thenReturn(null);
assertTrue(tools.hasEdgeSubtype(rel2, "null"));
}
}
| korpling/ANNIS | src/test/java/org/corpus_tools/annis/gui/visualizers/component/tree/AnnisGraphToolsTest.java | Java | apache-2.0 | 2,637 |
// ----------------------------------------------------------------------------
// Copyright 2007-2011, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// 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.
//
// ----------------------------------------------------------------------------
// Change History:
// 2006/08/21 Martin D. Flynn
// Initial release
// ----------------------------------------------------------------------------
package org.opengts.dbtypes;
import java.lang.*;
import java.util.*;
import java.math.*;
import java.io.*;
import java.sql.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
public class DTIPAddress
extends DBFieldType
{
// ------------------------------------------------------------------------
private IPTools.IPAddress ipAddr = null;
public DTIPAddress(IPTools.IPAddress ipAddr)
{
this.ipAddr = ipAddr;
}
public DTIPAddress(String ipAddr)
{
super(ipAddr);
this.ipAddr = new IPTools.IPAddress(ipAddr);
}
public DTIPAddress(ResultSet rs, String fldName)
throws SQLException
{
super(rs, fldName);
// set to default value if 'rs' is null
this.ipAddr = (rs != null)? new IPTools.IPAddress(rs.getString(fldName)) : null;
}
// ------------------------------------------------------------------------
public boolean isMatch(String ipAddr)
{
if (this.ipAddr != null) {
return this.ipAddr.isMatch(ipAddr);
} else {
return true;
}
}
// ------------------------------------------------------------------------
public Object getObject()
{
return this.toString();
}
public String toString()
{
return (this.ipAddr != null)? this.ipAddr.toString() : "";
}
// ------------------------------------------------------------------------
public boolean equals(Object other)
{
if (this == other) {
// same object
return true;
} else
if (other instanceof DTIPAddress) {
DTIPAddress otherList = (DTIPAddress)other;
if (otherList.ipAddr == this.ipAddr) {
// will also match if both are null
return true;
} else
if ((this.ipAddr == null) || (otherList.ipAddr == null)) {
// one is null, the other isn't
return false;
} else {
// IPAddressList match
return this.ipAddr.equals(otherList.ipAddr);
}
} else {
return false;
}
}
// ------------------------------------------------------------------------
}
| CASPED/OpenGTS | src/org/opengts/dbtypes/DTIPAddress.java | Java | apache-2.0 | 3,318 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_72) on Wed May 13 11:47:42 EDT 2015 -->
<title>Cassandra.describe_partitioner_result._Fields (apache-cassandra API)</title>
<meta name="date" content="2015-05-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Cassandra.describe_partitioner_result._Fields (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Cassandra.describe_partitioner_result._Fields.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result.html" title="class in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_ring_args.html" title="class in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" target="_top">Frames</a></li>
<li><a href="Cassandra.describe_partitioner_result._Fields.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.thrift</div>
<h2 title="Enum Cassandra.describe_partitioner_result._Fields" class="title">Enum Cassandra.describe_partitioner_result._Fields</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum<<a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a>></li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.thrift.Cassandra.describe_partitioner_result._Fields</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Comparable<<a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a>>, org.apache.thrift.TFieldIdEnum</dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result.html" title="class in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result</a></dd>
</dl>
<hr>
<br>
<pre>public static enum <span class="strong">Cassandra.describe_partitioner_result._Fields</span>
extends java.lang.Enum<<a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a>>
implements org.apache.thrift.TFieldIdEnum</pre>
<div class="block">The set of fields this struct contains, along with convenience methods for finding and manipulating them.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_summary">
<!-- -->
</a>
<h3>Enum Constant Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#SUCCESS">SUCCESS</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#findByName(java.lang.String)">findByName</a></strong>(java.lang.String name)</code>
<div class="block">Find the _Fields constant that matches name, or null if its not found.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#findByThriftId(int)">findByThriftId</a></strong>(int fieldId)</code>
<div class="block">Find the _Fields constant that matches fieldId, or null if its not found.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#findByThriftIdOrThrow(int)">findByThriftIdOrThrow</a></strong>(int fieldId)</code>
<div class="block">Find the _Fields constant that matches fieldId, throwing an exception
if it is not found.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#getFieldName()">getFieldName</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>short</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#getThriftFieldId()">getThriftFieldId</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a>[]</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#values()">values</a></strong>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Enum">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Enum</h3>
<code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_detail">
<!-- -->
</a>
<h3>Enum Constant Detail</h3>
<a name="SUCCESS">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>SUCCESS</h4>
<pre>public static final <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a> SUCCESS</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="values()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a>[] values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
<pre>
for (Cassandra.describe_partitioner_result._Fields c : Cassandra.describe_partitioner_result._Fields.values())
System.out.println(c);
</pre></div>
<dl><dt><span class="strong">Returns:</span></dt><dd>an array containing the constants of this enum type, in the order they are declared</dd></dl>
</li>
</ul>
<a name="valueOf(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a> valueOf(java.lang.String name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the enum constant with the specified name</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd></dl>
</li>
</ul>
<a name="findByThriftId(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findByThriftId</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a> findByThriftId(int fieldId)</pre>
<div class="block">Find the _Fields constant that matches fieldId, or null if its not found.</div>
</li>
</ul>
<a name="findByThriftIdOrThrow(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findByThriftIdOrThrow</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a> findByThriftIdOrThrow(int fieldId)</pre>
<div class="block">Find the _Fields constant that matches fieldId, throwing an exception
if it is not found.</div>
</li>
</ul>
<a name="findByName(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findByName</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a> findByName(java.lang.String name)</pre>
<div class="block">Find the _Fields constant that matches name, or null if its not found.</div>
</li>
</ul>
<a name="getThriftFieldId()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getThriftFieldId</h4>
<pre>public short getThriftFieldId()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getThriftFieldId</code> in interface <code>org.apache.thrift.TFieldIdEnum</code></dd>
</dl>
</li>
</ul>
<a name="getFieldName()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getFieldName</h4>
<pre>public java.lang.String getFieldName()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getFieldName</code> in interface <code>org.apache.thrift.TFieldIdEnum</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Cassandra.describe_partitioner_result._Fields.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result.html" title="class in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_ring_args.html" title="class in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" target="_top">Frames</a></li>
<li><a href="Cassandra.describe_partitioner_result._Fields.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
| anuragkapur/cassandra-2.1.2-ak-skynet | apache-cassandra-2.0.15/javadoc/org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html | HTML | apache-2.0 | 17,844 |
package ru.stqa.pft.mantis.appmanager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import ru.stqa.pft.mantis.model.User;
import java.util.List;
/**
* Created by Даниил on 11.06.2017.
*/
public class DbHelper {
private final SessionFactory sessionFactory;
public DbHelper() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
}
public User getUser() {
Session session = sessionFactory.openSession();
session.beginTransaction();
List<User> result = session.createQuery("from User").list();
session.getTransaction().commit();
session.close();
return result.stream().filter((s)->(!s.getUsername().equals("administrator"))).iterator().next();
}
}
| SweetyDonut/java_pft | Mantis_tests/src/test/java/ru/stqa/pft/mantis/appmanager/DbHelper.java | Java | apache-2.0 | 1,105 |
<!-- top navbar-->
<header data-ng-include="'app/views/partials/top-navbar.html'" data-ng-class="app.theme.topbar"></header>
<!-- Sidebar-->
<aside data-ng-include="'app/views/partials/sidebar.html'" data-ng-class="app.theme.sidebar"></aside>
<!-- Main-->
<section>
<!-- Content-->
<div ui-view="" autoscroll="false" data-ng-class="app.viewAnimation" class="app"></div>
</section>
<!-- Page footer-->
<footer data-ng-include="'app/views/partials/footer.html'"></footer> | mkhairul/fighto_admin | public/app/views/app.html | HTML | apache-2.0 | 475 |
package com.mricefox.androidhorizontalcalendar.library.calendar;
import android.database.Observable;
/**
* Author:zengzifeng email:[email protected]
* Description:
* Date:2015/12/25
*/
public class DataSetObservable extends Observable<DataSetObserver> {
public boolean hasObservers() {
synchronized (mObservers) {
return !mObservers.isEmpty();
}
}
public void notifyChanged() {
synchronized (mObservers) {//mObservers register and notify maybe in different thread
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
}
public void notifyItemRangeChanged(long from, long to) {
synchronized (mObservers) {
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeChanged(from, to);
}
}
}
}
| MrIceFox/AndroidHorizontalCalendar | library/src/main/java/com/mricefox/androidhorizontalcalendar/library/calendar/DataSetObservable.java | Java | apache-2.0 | 918 |
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaotypesURI(t *testing.T) {
convey.Convey("typesURI", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := testDao.typesURI()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTypeMapping(t *testing.T) {
convey.Convey("TypeMapping", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
rmap, err := testDao.TypeMapping(c)
ctx.Convey("Then err should be nil.rmap should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rmap, convey.ShouldNotBeNil)
})
})
})
}
| LQJJ/demo | 126-go-common-master/app/interface/main/dm2/dao/archive_test.go | GO | apache-2.0 | 814 |
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.eclipse.ceylon.langtools.classfile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.ceylon.langtools.classfile.TypeAnnotation.Position.TypePathEntry;
/**
* See JSR 308 specification, Section 3.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class TypeAnnotation {
TypeAnnotation(ClassReader cr) throws IOException, Annotation.InvalidAnnotation {
constant_pool = cr.getConstantPool();
position = read_position(cr);
annotation = new Annotation(cr);
}
public TypeAnnotation(ConstantPool constant_pool,
Annotation annotation, Position position) {
this.constant_pool = constant_pool;
this.position = position;
this.annotation = annotation;
}
public int length() {
int n = annotation.length();
n += position_length(position);
return n;
}
@Override
public String toString() {
try {
return "@" + constant_pool.getUTF8Value(annotation.type_index).toString().substring(1) +
" pos: " + position.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
public final ConstantPool constant_pool;
public final Position position;
public final Annotation annotation;
private static Position read_position(ClassReader cr) throws IOException, Annotation.InvalidAnnotation {
// Copied from ClassReader
int tag = cr.readUnsignedByte(); // TargetType tag is a byte
if (!TargetType.isValidTargetTypeValue(tag))
throw new Annotation.InvalidAnnotation("TypeAnnotation: Invalid type annotation target type value: " + String.format("0x%02X", tag));
TargetType type = TargetType.fromTargetTypeValue(tag);
Position position = new Position();
position.type = type;
switch (type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
position.offset = cr.readUnsignedShort();
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
int table_length = cr.readUnsignedShort();
position.lvarOffset = new int[table_length];
position.lvarLength = new int[table_length];
position.lvarIndex = new int[table_length];
for (int i = 0; i < table_length; ++i) {
position.lvarOffset[i] = cr.readUnsignedShort();
position.lvarLength[i] = cr.readUnsignedShort();
position.lvarIndex[i] = cr.readUnsignedShort();
}
break;
// exception parameter
case EXCEPTION_PARAMETER:
position.exception_index = cr.readUnsignedShort();
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
position.parameter_index = cr.readUnsignedByte();
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
position.parameter_index = cr.readUnsignedByte();
position.bound_index = cr.readUnsignedByte();
break;
// class extends or implements clause
case CLASS_EXTENDS:
int in = cr.readUnsignedShort();
if (in == 0xFFFF)
in = -1;
position.type_index = in;
break;
// throws
case THROWS:
position.type_index = cr.readUnsignedShort();
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
position.parameter_index = cr.readUnsignedByte();
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
position.offset = cr.readUnsignedShort();
position.type_index = cr.readUnsignedByte();
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("TypeAnnotation: UNKNOWN target type should never occur!");
default:
throw new AssertionError("TypeAnnotation: Unknown target type: " + type);
}
{ // Write type path
int len = cr.readUnsignedByte();
List<Integer> loc = new ArrayList<Integer>(len);
for (int i = 0; i < len * TypePathEntry.bytesPerEntry; ++i)
loc.add(cr.readUnsignedByte());
position.location = Position.getTypePathFromBinary(loc);
}
return position;
}
private static int position_length(Position pos) {
int n = 0;
n += 1; // TargetType tag is a byte
switch (pos.type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
n += 2; // offset
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
n += 2; // table_length;
int table_length = pos.lvarOffset.length;
n += 2 * table_length; // offset
n += 2 * table_length; // length
n += 2 * table_length; // index
break;
// exception parameter
case EXCEPTION_PARAMETER:
n += 2; // exception_index
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
n += 1; // parameter_index
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
n += 1; // parameter_index
n += 1; // bound_index
break;
// class extends or implements clause
case CLASS_EXTENDS:
n += 2; // type_index
break;
// throws
case THROWS:
n += 2; // type_index
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
n += 1; // parameter_index
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
n += 2; // offset
n += 1; // type index
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("TypeAnnotation: UNKNOWN target type should never occur!");
default:
throw new AssertionError("TypeAnnotation: Unknown target type: " + pos.type);
}
{
n += 1; // length
n += TypePathEntry.bytesPerEntry * pos.location.size(); // bytes for actual array
}
return n;
}
// Code duplicated from org.eclipse.ceylon.langtools.tools.javac.code.TypeAnnotationPosition
public static class Position {
public enum TypePathEntryKind {
ARRAY(0),
INNER_TYPE(1),
WILDCARD(2),
TYPE_ARGUMENT(3);
public final int tag;
private TypePathEntryKind(int tag) {
this.tag = tag;
}
}
public static class TypePathEntry {
/** The fixed number of bytes per TypePathEntry. */
public static final int bytesPerEntry = 2;
public final TypePathEntryKind tag;
public final int arg;
public static final TypePathEntry ARRAY = new TypePathEntry(TypePathEntryKind.ARRAY);
public static final TypePathEntry INNER_TYPE = new TypePathEntry(TypePathEntryKind.INNER_TYPE);
public static final TypePathEntry WILDCARD = new TypePathEntry(TypePathEntryKind.WILDCARD);
private TypePathEntry(TypePathEntryKind tag) {
if (!(tag == TypePathEntryKind.ARRAY ||
tag == TypePathEntryKind.INNER_TYPE ||
tag == TypePathEntryKind.WILDCARD)) {
throw new AssertionError("Invalid TypePathEntryKind: " + tag);
}
this.tag = tag;
this.arg = 0;
}
public TypePathEntry(TypePathEntryKind tag, int arg) {
if (tag != TypePathEntryKind.TYPE_ARGUMENT) {
throw new AssertionError("Invalid TypePathEntryKind: " + tag);
}
this.tag = tag;
this.arg = arg;
}
public static TypePathEntry fromBinary(int tag, int arg) {
if (arg != 0 && tag != TypePathEntryKind.TYPE_ARGUMENT.tag) {
throw new AssertionError("Invalid TypePathEntry tag/arg: " + tag + "/" + arg);
}
switch (tag) {
case 0:
return ARRAY;
case 1:
return INNER_TYPE;
case 2:
return WILDCARD;
case 3:
return new TypePathEntry(TypePathEntryKind.TYPE_ARGUMENT, arg);
default:
throw new AssertionError("Invalid TypePathEntryKind tag: " + tag);
}
}
@Override
public String toString() {
return tag.toString() +
(tag == TypePathEntryKind.TYPE_ARGUMENT ? ("(" + arg + ")") : "");
}
@Override
public boolean equals(Object other) {
if (! (other instanceof TypePathEntry)) {
return false;
}
TypePathEntry tpe = (TypePathEntry) other;
return this.tag == tpe.tag && this.arg == tpe.arg;
}
@Override
public int hashCode() {
return this.tag.hashCode() * 17 + this.arg;
}
}
public TargetType type = TargetType.UNKNOWN;
// For generic/array types.
// TODO: or should we use null? Noone will use this object.
public List<TypePathEntry> location = new ArrayList<TypePathEntry>(0);
// Tree position.
public int pos = -1;
// For typecasts, type tests, new (and locals, as start_pc).
public boolean isValidOffset = false;
public int offset = -1;
// For locals. arrays same length
public int[] lvarOffset = null;
public int[] lvarLength = null;
public int[] lvarIndex = null;
// For type parameter bound
public int bound_index = Integer.MIN_VALUE;
// For type parameter and method parameter
public int parameter_index = Integer.MIN_VALUE;
// For class extends, implements, and throws clauses
public int type_index = Integer.MIN_VALUE;
// For exception parameters, index into exception table
public int exception_index = Integer.MIN_VALUE;
public Position() {}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
sb.append(type);
switch (type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
sb.append(", offset = ");
sb.append(offset);
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
if (lvarOffset == null) {
sb.append(", lvarOffset is null!");
break;
}
sb.append(", {");
for (int i = 0; i < lvarOffset.length; ++i) {
if (i != 0) sb.append("; ");
sb.append("start_pc = ");
sb.append(lvarOffset[i]);
sb.append(", length = ");
sb.append(lvarLength[i]);
sb.append(", index = ");
sb.append(lvarIndex[i]);
}
sb.append("}");
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
sb.append(", param_index = ");
sb.append(parameter_index);
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
sb.append(", param_index = ");
sb.append(parameter_index);
sb.append(", bound_index = ");
sb.append(bound_index);
break;
// class extends or implements clause
case CLASS_EXTENDS:
sb.append(", type_index = ");
sb.append(type_index);
break;
// throws
case THROWS:
sb.append(", type_index = ");
sb.append(type_index);
break;
// exception parameter
case EXCEPTION_PARAMETER:
sb.append(", exception_index = ");
sb.append(exception_index);
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
sb.append(", param_index = ");
sb.append(parameter_index);
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
sb.append(", offset = ");
sb.append(offset);
sb.append(", type_index = ");
sb.append(type_index);
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
sb.append(", position UNKNOWN!");
break;
default:
throw new AssertionError("Unknown target type: " + type);
}
// Append location data for generics/arrays.
if (!location.isEmpty()) {
sb.append(", location = (");
sb.append(location);
sb.append(")");
}
sb.append(", pos = ");
sb.append(pos);
sb.append(']');
return sb.toString();
}
/**
* Indicates whether the target tree of the annotation has been optimized
* away from classfile or not.
* @return true if the target has not been optimized away
*/
public boolean emitToClassfile() {
return !type.isLocal() || isValidOffset;
}
/**
* Decode the binary representation for a type path and set
* the {@code location} field.
*
* @param list The bytecode representation of the type path.
*/
public static List<TypePathEntry> getTypePathFromBinary(List<Integer> list) {
List<TypePathEntry> loc = new ArrayList<TypePathEntry>(list.size() / TypePathEntry.bytesPerEntry);
int idx = 0;
while (idx < list.size()) {
if (idx + 1 == list.size()) {
throw new AssertionError("Could not decode type path: " + list);
}
loc.add(TypePathEntry.fromBinary(list.get(idx), list.get(idx + 1)));
idx += 2;
}
return loc;
}
public static List<Integer> getBinaryFromTypePath(List<TypePathEntry> locs) {
List<Integer> loc = new ArrayList<Integer>(locs.size() * TypePathEntry.bytesPerEntry);
for (TypePathEntry tpe : locs) {
loc.add(tpe.tag.tag);
loc.add(tpe.arg);
}
return loc;
}
}
// Code duplicated from org.eclipse.ceylon.langtools.tools.javac.code.TargetType
// The IsLocal flag could be removed here.
public enum TargetType {
/** For annotations on a class type parameter declaration. */
CLASS_TYPE_PARAMETER(0x00),
/** For annotations on a method type parameter declaration. */
METHOD_TYPE_PARAMETER(0x01),
/** For annotations on the type of an "extends" or "implements" clause. */
CLASS_EXTENDS(0x10),
/** For annotations on a bound of a type parameter of a class. */
CLASS_TYPE_PARAMETER_BOUND(0x11),
/** For annotations on a bound of a type parameter of a method. */
METHOD_TYPE_PARAMETER_BOUND(0x12),
/** For annotations on a field. */
FIELD(0x13),
/** For annotations on a method return type. */
METHOD_RETURN(0x14),
/** For annotations on the method receiver. */
METHOD_RECEIVER(0x15),
/** For annotations on a method parameter. */
METHOD_FORMAL_PARAMETER(0x16),
/** For annotations on a throws clause in a method declaration. */
THROWS(0x17),
/** For annotations on a local variable. */
LOCAL_VARIABLE(0x40, true),
/** For annotations on a resource variable. */
RESOURCE_VARIABLE(0x41, true),
/** For annotations on an exception parameter. */
EXCEPTION_PARAMETER(0x42, true),
/** For annotations on a type test. */
INSTANCEOF(0x43, true),
/** For annotations on an object creation expression. */
NEW(0x44, true),
/** For annotations on a constructor reference receiver. */
CONSTRUCTOR_REFERENCE(0x45, true),
/** For annotations on a method reference receiver. */
METHOD_REFERENCE(0x46, true),
/** For annotations on a typecast. */
CAST(0x47, true),
/** For annotations on a type argument of an object creation expression. */
CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT(0x48, true),
/** For annotations on a type argument of a method call. */
METHOD_INVOCATION_TYPE_ARGUMENT(0x49, true),
/** For annotations on a type argument of a constructor reference. */
CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT(0x4A, true),
/** For annotations on a type argument of a method reference. */
METHOD_REFERENCE_TYPE_ARGUMENT(0x4B, true),
/** For annotations with an unknown target. */
UNKNOWN(0xFF);
private static final int MAXIMUM_TARGET_TYPE_VALUE = 0x4B;
private final int targetTypeValue;
private final boolean isLocal;
private TargetType(int targetTypeValue) {
this(targetTypeValue, false);
}
private TargetType(int targetTypeValue, boolean isLocal) {
if (targetTypeValue < 0
|| targetTypeValue > 255)
throw new AssertionError("Attribute type value needs to be an unsigned byte: " + String.format("0x%02X", targetTypeValue));
this.targetTypeValue = targetTypeValue;
this.isLocal = isLocal;
}
/**
* Returns whether or not this TargetType represents an annotation whose
* target is exclusively a tree in a method body
*
* Note: wildcard bound targets could target a local tree and a class
* member declaration signature tree
*/
public boolean isLocal() {
return isLocal;
}
public int targetTypeValue() {
return this.targetTypeValue;
}
private static final TargetType[] targets;
static {
targets = new TargetType[MAXIMUM_TARGET_TYPE_VALUE + 1];
TargetType[] alltargets = values();
for (TargetType target : alltargets) {
if (target.targetTypeValue != UNKNOWN.targetTypeValue)
targets[target.targetTypeValue] = target;
}
for (int i = 0; i <= MAXIMUM_TARGET_TYPE_VALUE; ++i) {
if (targets[i] == null)
targets[i] = UNKNOWN;
}
}
public static boolean isValidTargetTypeValue(int tag) {
if (tag == UNKNOWN.targetTypeValue)
return true;
return (tag >= 0 && tag < targets.length);
}
public static TargetType fromTargetTypeValue(int tag) {
if (tag == UNKNOWN.targetTypeValue)
return UNKNOWN;
if (tag < 0 || tag >= targets.length)
throw new AssertionError("Unknown TargetType: " + tag);
return targets[tag];
}
}
}
| ceylon/ceylon | langtools-classfile/src/org/eclipse/ceylon/langtools/classfile/TypeAnnotation.java | Java | apache-2.0 | 23,331 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_112) on Tue Sep 12 14:31:27 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.netflix.ribbon.RibbonArchive (BOM: * : All 2017.9.5 API)</title>
<meta name="date" content="2017-09-12">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.wildfly.swarm.netflix.ribbon.RibbonArchive (BOM: * : All 2017.9.5 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.9.5</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/netflix/ribbon/class-use/RibbonArchive.html" target="_top">Frames</a></li>
<li><a href="RibbonArchive.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.netflix.ribbon.RibbonArchive" class="title">Uses of Interface<br>org.wildfly.swarm.netflix.ribbon.RibbonArchive</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">RibbonArchive</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.netflix.ribbon">org.wildfly.swarm.netflix.ribbon</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.netflix.ribbon">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">RibbonArchive</a> in <a href="../../../../../../org/wildfly/swarm/netflix/ribbon/package-summary.html">org.wildfly.swarm.netflix.ribbon</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/netflix/ribbon/package-summary.html">org.wildfly.swarm.netflix.ribbon</a> that return <a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">RibbonArchive</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">RibbonArchive</a></code></td>
<td class="colLast"><span class="typeNameLabel">RibbonArchive.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html#advertise--">advertise</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">RibbonArchive</a></code></td>
<td class="colLast"><span class="typeNameLabel">RibbonArchive.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html#advertise-java.lang.String-">advertise</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> serviceNames)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.9.5</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/netflix/ribbon/class-use/RibbonArchive.html" target="_top">Frames</a></li>
<li><a href="RibbonArchive.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2017.9.5/apidocs/org/wildfly/swarm/netflix/ribbon/class-use/RibbonArchive.html | HTML | apache-2.0 | 7,782 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_60-ea) on Thu Dec 15 09:48:34 EST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.cdi (Public javadocs 2016.12.1 API)</title>
<meta name="date" content="2016-12-15">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../org/wildfly/swarm/cdi/package-summary.html" target="classFrame">org.wildfly.swarm.cdi</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="CDIFraction.html" title="class in org.wildfly.swarm.cdi" target="classFrame">CDIFraction</a></li>
</ul>
</div>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2016.12.1/apidocs/org/wildfly/swarm/cdi/package-frame.html | HTML | apache-2.0 | 924 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_60-ea) on Tue Sep 06 12:41:42 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.config.logging (Public javadocs 2016.9 API)</title>
<meta name="date" content="2016-09-06">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.wildfly.swarm.config.logging (Public javadocs 2016.9 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.9</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/wildfly/swarm/config/jmx/configuration/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../org/wildfly/swarm/config/mail/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/logging/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package org.wildfly.swarm.config.logging</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">AsyncHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandler.html" title="class in org.wildfly.swarm.config.logging">AsyncHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">AsyncHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandler.html" title="class in org.wildfly.swarm.config.logging">AsyncHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">ConsoleHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandler.html" title="class in org.wildfly.swarm.config.logging">ConsoleHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">ConsoleHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandler.html" title="class in org.wildfly.swarm.config.logging">ConsoleHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatterConsumer.html" title="interface in org.wildfly.swarm.config.logging">CustomFormatterConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatter.html" title="class in org.wildfly.swarm.config.logging">CustomFormatter</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatterSupplier.html" title="interface in org.wildfly.swarm.config.logging">CustomFormatterSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatter.html" title="class in org.wildfly.swarm.config.logging">CustomFormatter</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">CustomHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomHandler.html" title="class in org.wildfly.swarm.config.logging">CustomHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">CustomHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomHandler.html" title="class in org.wildfly.swarm.config.logging">CustomHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/FileHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">FileHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/FileHandler.html" title="class in org.wildfly.swarm.config.logging">FileHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/FileHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">FileHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/FileHandler.html" title="class in org.wildfly.swarm.config.logging">FileHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LogFileConsumer.html" title="interface in org.wildfly.swarm.config.logging">LogFileConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LogFile.html" title="class in org.wildfly.swarm.config.logging">LogFile</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LogFileSupplier.html" title="interface in org.wildfly.swarm.config.logging">LogFileSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LogFile.html" title="class in org.wildfly.swarm.config.logging">LogFile</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggerConsumer.html" title="interface in org.wildfly.swarm.config.logging">LoggerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/Logger.html" title="class in org.wildfly.swarm.config.logging">Logger</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggerSupplier.html" title="interface in org.wildfly.swarm.config.logging">LoggerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/Logger.html" title="class in org.wildfly.swarm.config.logging">Logger</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfileConsumer.html" title="interface in org.wildfly.swarm.config.logging">LoggingProfileConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfile.html" title="class in org.wildfly.swarm.config.logging">LoggingProfile</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfileSupplier.html" title="interface in org.wildfly.swarm.config.logging">LoggingProfileSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfile.html" title="class in org.wildfly.swarm.config.logging">LoggingProfile</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatterConsumer.html" title="interface in org.wildfly.swarm.config.logging">PatternFormatterConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatter.html" title="class in org.wildfly.swarm.config.logging">PatternFormatter</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatterSupplier.html" title="interface in org.wildfly.swarm.config.logging">PatternFormatterSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatter.html" title="class in org.wildfly.swarm.config.logging">PatternFormatter</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/RootLoggerConsumer.html" title="interface in org.wildfly.swarm.config.logging">RootLoggerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/RootLogger.html" title="class in org.wildfly.swarm.config.logging">RootLogger</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/RootLoggerSupplier.html" title="interface in org.wildfly.swarm.config.logging">RootLoggerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/RootLogger.html" title="class in org.wildfly.swarm.config.logging">RootLogger</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">SizeRotatingFileHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">SizeRotatingFileHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">SizeRotatingFileHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">SizeRotatingFileHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">SyslogHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.html" title="class in org.wildfly.swarm.config.logging">SyslogHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">SyslogHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.html" title="class in org.wildfly.swarm.config.logging">SyslogHandler</a>></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandler.html" title="class in org.wildfly.swarm.config.logging">AsyncHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandler.html" title="class in org.wildfly.swarm.config.logging">AsyncHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to the sub-handlers in an asynchronous thread.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandler.html" title="class in org.wildfly.swarm.config.logging">ConsoleHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandler.html" title="class in org.wildfly.swarm.config.logging">ConsoleHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to the console.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatter.html" title="class in org.wildfly.swarm.config.logging">CustomFormatter</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatter.html" title="class in org.wildfly.swarm.config.logging">CustomFormatter</a><T>></td>
<td class="colLast">
<div class="block">A custom formatter to be used with handlers.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomHandler.html" title="class in org.wildfly.swarm.config.logging">CustomHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomHandler.html" title="class in org.wildfly.swarm.config.logging">CustomHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a custom logging handler.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/FileHandler.html" title="class in org.wildfly.swarm.config.logging">FileHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/FileHandler.html" title="class in org.wildfly.swarm.config.logging">FileHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to a file.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LogFile.html" title="class in org.wildfly.swarm.config.logging">LogFile</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LogFile.html" title="class in org.wildfly.swarm.config.logging">LogFile</a><T>></td>
<td class="colLast">
<div class="block">Log files that are available to be read.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/Logger.html" title="class in org.wildfly.swarm.config.logging">Logger</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/Logger.html" title="class in org.wildfly.swarm.config.logging">Logger</a><T>></td>
<td class="colLast">
<div class="block">Defines a logger category.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfile.html" title="class in org.wildfly.swarm.config.logging">LoggingProfile</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfile.html" title="class in org.wildfly.swarm.config.logging">LoggingProfile</a><T>></td>
<td class="colLast">
<div class="block">The configuration of the logging subsystem.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfile.LoggingProfileResources.html" title="class in org.wildfly.swarm.config.logging">LoggingProfile.LoggingProfileResources</a></td>
<td class="colLast">
<div class="block">Child mutators for LoggingProfile</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatter.html" title="class in org.wildfly.swarm.config.logging">PatternFormatter</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatter.html" title="class in org.wildfly.swarm.config.logging">PatternFormatter</a><T>></td>
<td class="colLast">
<div class="block">A pattern formatter to be used with handlers.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to a file, rotating the log after a time
period derived from the given suffix string, which should be in a format
understood by java.text.SimpleDateFormat.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to a file, rotating the log after a time
period derived from the given suffix string or after the size of the file
grows beyond a certain point and keeping a fixed number of backups.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/RootLogger.html" title="class in org.wildfly.swarm.config.logging">RootLogger</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/RootLogger.html" title="class in org.wildfly.swarm.config.logging">RootLogger</a><T>></td>
<td class="colLast">
<div class="block">Defines the root logger for this log context.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">SizeRotatingFileHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">SizeRotatingFileHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to a file, rotating the log after the size of
the file grows beyond a certain point and keeping a fixed number of backups.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.html" title="class in org.wildfly.swarm.config.logging">SyslogHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.html" title="class in org.wildfly.swarm.config.logging">SyslogHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a syslog handler.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation">
<caption><span>Enum Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Enum</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandler.OverflowAction.html" title="enum in org.wildfly.swarm.config.logging">AsyncHandler.OverflowAction</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandler.Target.html" title="enum in org.wildfly.swarm.config.logging">ConsoleHandler.Target</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/Level.html" title="enum in org.wildfly.swarm.config.logging">Level</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.Facility.html" title="enum in org.wildfly.swarm.config.logging">SyslogHandler.Facility</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.SyslogFormat.html" title="enum in org.wildfly.swarm.config.logging">SyslogHandler.SyslogFormat</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.9</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/wildfly/swarm/config/jmx/configuration/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../org/wildfly/swarm/config/mail/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/logging/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2016.9/apidocs/org/wildfly/swarm/config/logging/package-summary.html | HTML | apache-2.0 | 26,489 |
define([
"settings",
"views/tags"
], function(panelSettings, TagsView) {
var PanelFileView = codebox.require("views/panels/file");
var PanelOutlineView = PanelFileView.extend({
className: "cb-panel-outline",
FileView: TagsView
});
return PanelOutlineView;
}); | cethap/cbcompiled | addons/cb.panel.outline/views/panel.js | JavaScript | apache-2.0 | 301 |
package com.ticktick.testimagecropper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import com.ticktick.imagecropper.CropImageActivity;
import com.ticktick.imagecropper.CropIntent;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final int REQUEST_CODE_PICK_IMAGE = 0x1;
public static final int REQUEST_CODE_IMAGE_CROPPER = 0x2;
public static final String CROPPED_IMAGE_FILEPATH = "/sdcard/test.jpg";
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView)findViewById(R.id.CroppedImageView);
}
public void onClickButton(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,REQUEST_CODE_PICK_IMAGE);
}
public void startCropImage( Uri uri ) {
Intent intent = new Intent(this,CropImageActivity.class);
intent.setData(uri);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(CROPPED_IMAGE_FILEPATH)));
//intent.putExtra("aspectX",2);
//intent.putExtra("aspectY",1);
//intent.putExtra("outputX",320);
//intent.putExtra("outputY",240);
//intent.putExtra("maxOutputX",640);
//intent.putExtra("maxOutputX",480);
startActivityForResult(intent, REQUEST_CODE_IMAGE_CROPPER);
}
public void startCropImageByCropIntent( Uri uri ) {
CropIntent intent = new CropIntent();
intent.setImagePath(uri);
intent.setOutputPath(CROPPED_IMAGE_FILEPATH);
//intent.setAspect(2, 1);
//intent.setOutputSize(480,320);
//intent.setMaxOutputSize(480,320);
startActivityForResult(intent.getIntent(this), REQUEST_CODE_IMAGE_CROPPER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if( requestCode == REQUEST_CODE_PICK_IMAGE ) {
startCropImage(data.getData());
}
else if( requestCode == REQUEST_CODE_IMAGE_CROPPER ) {
Uri croppedUri = data.getExtras().getParcelable(MediaStore.EXTRA_OUTPUT);
InputStream in = null;
try {
in = getContentResolver().openInputStream(croppedUri);
Bitmap b = BitmapFactory.decodeStream(in);
mImageView.setImageBitmap(b);
Toast.makeText(this,"Crop success,saved at"+CROPPED_IMAGE_FILEPATH,Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| msdgwzhy6/ImageCropper | TestImageCropper/src/com/ticktick/testimagecropper/MainActivity.java | Java | apache-2.0 | 3,086 |
<?php
$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
'Login',
);
?>
<h1>Login</h1>
<p>Please fill out the following form with your login credentials:</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo CHtml::label('Pin','pin'); ?>
<?php echo CHtml::passwordField('pin'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username'); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
<!--
<p class="hint">
Hint: You may login with <tt>demo/demo</tt>.
</p>
-->
</div>
<!--
<div class="row rememberMe">
<?php //echo $form->checkBox($model,'rememberMe'); ?>
<?php //echo $form->label($model,'rememberMe'); ?>
<?php //echo $form->error($model,'rememberMe'); ?>
</div>
-->
<div class="row submit">
<?php echo CHtml::submitButton('Login'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
| fipumjdeveloper/web | views/site/login.php | PHP | apache-2.0 | 1,309 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.deploymentadmin;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import org.osgi.framework.Version;
import org.osgi.service.deploymentadmin.BundleInfo;
import org.osgi.service.deploymentadmin.DeploymentException;
/**
* Implementation of the <code>BundleInfo</code> interface as defined by the OSGi mobile specification.
*/
public class BundleInfoImpl extends AbstractInfo implements BundleInfo {
private final Version m_version;
private final String m_symbolicName;
private final boolean m_customizer;
/**
* Creates an instance of this class.
*
* @param path The path / resource-id of the bundle resource.
* @param attributes Set of attributes describing the bundle resource.
* @throws DeploymentException If the specified attributes do not describe a valid bundle.
*/
public BundleInfoImpl(String path, Attributes attributes) throws DeploymentException {
super(path, attributes);
String bundleSymbolicName = attributes.getValue(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME);
if (bundleSymbolicName == null) {
throw new DeploymentException(DeploymentException.CODE_MISSING_HEADER, "Missing '" + org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME + "' header for manifest entry '" + getPath() + "'");
} else if (bundleSymbolicName.trim().equals("")) {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME + "' header for manifest entry '" + getPath() + "'");
} else {
m_symbolicName = parseSymbolicName(bundleSymbolicName);
}
String version = attributes.getValue(org.osgi.framework.Constants.BUNDLE_VERSION);
if (version == null || version == "") {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_VERSION + "' header for manifest entry '" + getPath() + "'");
}
try {
m_version = Version.parseVersion(version);
} catch (IllegalArgumentException e) {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_VERSION + "' header for manifest entry '" + getPath() + "'");
}
m_customizer = parseBooleanHeader(attributes, Constants.DEPLOYMENTPACKAGE_CUSTOMIZER);
}
/**
* Strips parameters from the bundle symbolic name such as "foo;singleton:=true".
*
* @param name full name as found in the manifest of the deployment package
* @return name without parameters
*/
private String parseSymbolicName(String name) {
// note that we don't explicitly check if there are tokens, because that
// check has already been made before we are invoked here
StringTokenizer st = new StringTokenizer(name, ";");
return st.nextToken();
}
public String getSymbolicName() {
return m_symbolicName;
}
public Version getVersion() {
return m_version;
}
/**
* Determine whether this bundle resource is a customizer bundle.
*
* @return True if the bundle is a customizer bundle, false otherwise.
*/
public boolean isCustomizer() {
return m_customizer;
}
/**
* Verify if the specified attributes describe a bundle resource.
*
* @param attributes Attributes describing the resource
* @return true if the attributes describe a bundle resource, false otherwise
*/
public static boolean isBundleResource(Attributes attributes) {
return (attributes.getValue(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME) != null);
}
}
| boneman1231/org.apache.felix | trunk/deploymentadmin/deploymentadmin/src/main/java/org/apache/felix/deploymentadmin/BundleInfoImpl.java | Java | apache-2.0 | 4,581 |
# Copyright 2014-2015 Isotoma Limited
#
# 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.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
| yaybu/touchdown | touchdown/aws/ec2/instance.py | Python | apache-2.0 | 4,911 |
package com.zlwh.hands.api.domain.base;
public class PageDomain {
private String pageNo;
private String pageSize = "15";
private long pageTime; // 上次刷新时间,分页查询时,防止分页数据错乱
public String getPageNo() {
return pageNo;
}
public void setPageNo(String pageNo) {
this.pageNo = pageNo;
}
public String getPageSize() {
return pageSize;
}
public void setPageSize(String pageSize) {
this.pageSize = pageSize;
}
public long getPageTime() {
return pageTime;
}
public void setPageTime(long pageTime) {
this.pageTime = pageTime;
}
}
| javyuan/jeesite-api | src/main/java/com/zlwh/hands/api/domain/base/PageDomain.java | Java | apache-2.0 | 593 |
package io.github.thankpoint.security.impl;
import java.security.Provider;
import java.security.Security;
import io.github.thankpoint.security.api.provider.SecurityProviderBuilder;
/**
* Implementation of {@link SecurityProviderBuilder}.
*
* @param <B> type of the returned builder.
* @author thks
*/
public interface AbstractSecurityProviderBuilderImpl<B> extends SecurityProviderBuilder<B> {
@Override
default B provider() {
return provider((Provider) null);
}
@Override
default B provider(String name) {
return provider(Security.getProvider(name));
}
}
| thankpoint/thanks4java | security/src/main/java/io/github/thankpoint/security/impl/AbstractSecurityProviderBuilderImpl.java | Java | apache-2.0 | 589 |
<!DOCTYPE html>
<html devsite="">
<head>
<meta name="project_path" value="/dotnet/_project.yaml">
<meta name="book_path" value="/dotnet/_book.yaml">
</head>
<body>
{% verbatim %}
<div>
<article data-uid="Google.Cloud.Asset.V1.TemporalAsset.Types">
<h1 class="page-title">Class TemporalAsset.Types
</h1>
<div class="codewrapper">
<pre class="prettyprint"><code>public static class Types</code></pre>
</div>
<div class="markdown level0 summary"><p>Container for nested types declared in the TemporalAsset message type.</p>
</div>
<div class="inheritance">
<h2>Inheritance</h2>
<span><span class="xref">System.Object</span></span> <span> > </span>
<span class="xref">TemporalAsset.Types</span>
</div>
<div class="inheritedMembers expandable">
<h2 class="showalways">Inherited Members</h2>
<div>
<span class="xref">System.Object.GetHashCode()</span>
</div>
<div>
<span class="xref">System.Object.GetType()</span>
</div>
<div>
<span class="xref">System.Object.MemberwiseClone()</span>
</div>
<div>
<span class="xref">System.Object.ToString()</span>
</div>
</div>
<h2>Namespace</h2>
<a class="xref" href="Google.Cloud.Asset.V1.html">Google.Cloud.Asset.V1</a>
<h2>Assembly</h2>
<p>Google.Cloud.Asset.V1.dll</p>
</article>
</div>
{% endverbatim %}
</body>
</html>
| googleapis/doc-templates | testdata/goldens/dotnet/Google.Cloud.Asset.V1.TemporalAsset.Types.html | HTML | apache-2.0 | 1,451 |
package com.github.saulis.enumerables;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class EmptyIterator<T> implements Iterator<T> {
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
throw new NoSuchElementException();
}
}
| Saulis/enumerables | src/main/java/com/github/saulis/enumerables/EmptyIterator.java | Java | apache-2.0 | 326 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.