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
|
---|---|---|---|---|---|
body {
background-color: #000;
font: 12px "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
color: #9aa6af;
text-rendering: optimizelegibility;
-webkit-tap-highlight-color:rgba(0,0,0,0);
-webkit-text-size-adjust: none;
-webkit-font-smoothing: antialiased;
-moz-tap-highlight-color:rgba(0,0,0,0);
-moz-text-size-adjust: none;
-moz-font-smoothing: antialiased;
-ms-tap-highlight-color:rgba(0,0,0,0);
-ms-text-size-adjust: none;
-ms-font-smoothing: antialiased;
}
a {text-decoration: none;}
.container {
overflow: hidden;
background-color: #000;
/* Prevents Flickering */
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
}
header {
height: 60px;
position: relative;
background-color: #f3f5f6;
}
header h1 {
color: #9aa6af;
text-align: left;
font-size: 27px;
line-height: 60px;
font-weight: bold;
padding-left: 20px;
}
.burger {
position: absolute;
float: left;
padding: 10px;
top: 4px;
left: 10px;
display: none;
}
.burger li {
width: 30px;
height: 4px;
background-color: #fff;
border-radius: 3px;
margin: 5px 0;
}
.burger.open li {background-color: #d9dde1;}
nav {
position: absolute;
top: 0;
right: 5px;
}
nav li {
float: left;
display: inline-block;
}
nav li a {
font-size: 11px;
color: #9aa6af;
padding: 24px 15px;
display: block;
}
nav li a:hover {color: #000;}
/* Removable CSS */
.header-section,
.body-section,
.footer-section
{padding: 20px;}
.header-section {background-color: #ffffff;}
.body-section {background-color: #f4f5f6;}
.footer-section {background-color: #dadee1;}
.placefiller {
text-align: center;
font-size: 20px;
border: 1px dashed rgba(190, 196, 202, 0.5);
}
.header-section .placefiller {line-height: 300px;}
.body-section .placefiller {line-height: 900px;}
.footer-section .placefiller {
line-height: 200px;
border: 1px dashed rgba(190, 196, 202, 0.9);
}
@media only screen and (max-width: 780px) {
header {
height: 60px;
z-index: 2;
background-color: #060a0c;
position: fixed;
top: 0;
right: 0;
left: 0;
/* starting point */
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
header h1 {
color: #ffffff;
text-align: center;
padding-left: 0;
display: block;
}
.burger {display: block;}
/* Nav Drawer Layout */
nav {position: relative;}
nav ul {
height: 100%;
overflow-y: auto;
}
nav li {
display: block;
float: none;
}
nav li a {
padding: 22px 25px;
letter-spacing: 3px;
font-size: 14px;
}
nav li a.logo {
display: none;
}
nav li a.active {
color: #fff;
background-color: #141e23;
}
nav li a:hover {
color: #fff;
background-color: #19252c;
}
nav li:first-child a.active,
nav li:first-child a:hover
{border-radius: 10px 0 0 0;}
.header-section {margin-top: 60px;}
/* NAVIGATION ANNIMATION */
nav {
width: 93%;
height: 100%;
position: fixed;
left: 0;
top: 0;
margin: 0;
background-color: #1d2d35;
border-radius: 8px;
/* starting point */
opacity: .3;
-webkit-transform: translate3d(5%,0,0)scale(.97);
-moz-transform: translate3d(5%,0,0)scale(.97);
transform: translate3d(5%,0,0)scale(.97);
}
/*Nav Expanding Open Effect*/
nav.open {
opacity: 1;
-webkit-transform: translate3d(0,0,0)scale(1);
-webkit-animation: slideIn .35s ease-in-out;
-moz-transform: translate3d(0,0,0)scale(1);
-moz-animation: slideIn .35s ease-in-out;
transform: translate3d(0,0,0)scale(1);
animation: slideIn .35s ease-in-out;
}
@-webkit-keyframes slideIn {
0% {opacity: .3;
-webkit-transform: translate3d(5%,0,0)scale(.97);}
100% {opacity: 1;
-webkit-transform: translate3d(0,0,0)scale(1);}
}
@-moz-keyframes slideIn {
0% {opacity: .3;
-moz-transform: translate3d(5%,0,0)scale(.97);}
100% {opacity: 1;
-moz-transform: translate3d(0,0,0)scale(1);}
}
@keyframes slideIn {
0% {opacity: .3;
transform: translate3d(5%,0,0)scale(.97);}
100% {opacity: 1;
transform: translate3d(0,0,0)scale(1);}
}
/*Nav Shrinking Closed Effect*/
nav.close {
opacity: .3;
-webkit-transform: translate3d(5%,0,0)scale(.97);
-webkit-animation: slideOut .3s ease-in-out;
-moz-transform: translate3d(5%,0,0)scale(.97);
-moz-animation: slideOut .3s ease-in-out;
transform: translate3d(5%,0,0)scale(.97);
animation: slideOut .3s ease-in-out;
}
@-webkit-keyframes slideOut {
0% {opacity: 1;
-webkit-transform: translate3d(0,0,0)scale(1);}
100% {opacity: .3;
-webkit-transform: translate3d(5%,0,0)scale(.97);}
}
@-moz-keyframes slideOut {
0% {opacity: 1;
-moz-transform: translate3d(0,0,0)scale(1);}
100% {opacity: .3;
-moz-transform: translate3d(5%,0,0)scale(.97);}
}
@keyframes slideOut {
0% {opacity: 1;
transform: translate3d(0,0,0)scale(1);}
100% {opacity: .3;
transform: translate3d(5%,0,0)scale(.97);}
}
/* CONTENT ANNIMATION */
.content {
/* starting point */
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
z-index: 1;
}
/*Content Sliding Open Effect*/
header.open,
.content.open
{
-webkit-transform: translate3d(240px,0,0);
-webkit-animation: open .5s ease-in-out;
-moz-transform: translate3d(240px,0,0);
-moz-animation: open .5s ease-in-out;
transform: translate3d(240px,0,0);
animation: open .5s ease-in-out;
}
@-webkit-keyframes open {
0% {-webkit-transform: translate3d(0,0,0);}
70% {-webkit-transform: translate3d(260px,0,0);}
100% {-webkit-transform: translate3d(240px,0,0);}
}
@-moz-keyframes open {
0% {-moz-transform: translate3d(0,0,0);}
70% {-moz-transform: translate3d(260px,0,0);}
100% {-moz-transform: translate3d(240px,0,0);}
}
@keyframes open {
0% {transform: translate3d(0,0,0);}
70% {transform: translate3d(260px,0,0);}
100% {transform: translate3d(240px,0,0);}
}
/*Content Sliding Closed Effect*/
header.close,
.content.close
{
-webkit-transform: translate3d(0,0,0);
-webkit-animation: close .3s ease-in-out;
-moz-transform: translate3d(0,0,0);
-moz-animation: close .3s ease-in-out;
transform: translate3d(0,0,0);
animation: close .3s ease-in-out;
}
@-webkit-keyframes close {
0% {-webkit-transform: translate3d(240px,0,0);}
100% {-webkit-transform: translate3d(0,0,0);}
}
@-moz-keyframes close {
0% {-moz-transform: translate3d(240px,0,0);}
100% {-moz-transform: translate3d(0,0,0);}
}
@keyframes close {
0% {transform: translate3d(240px,0,0);}
100% {transform: translate3d(0,0,0);}
}
}
|
myAmericaDevSummit2015/Ascent
|
www/app/styles/trunk.css
|
CSS
|
apache-2.0
| 6,526 |
/*
* 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.
*/
/*
Utility function that takes a d3 svg:text selection and a max width, and splits the
text's text across multiple tspan lines such that any given line does not exceed max width
If text does not span multiple lines AND adjustedY is passed,
will set the text to the passed val
*/
import d3 from 'd3';
export default function wrapSvgText(text, width, adjustedY) {
const lineHeight = 1;
// ems
text.each(function each() {
const d3Text = d3.select(this);
const words = d3Text.text().split(/\s+/);
let line = [];
let lineNumber = 0;
const x = d3Text.attr('x');
const y = d3Text.attr('y');
const dy = parseFloat(d3Text.attr('dy'));
let tspan = d3Text
.text(null)
.append('tspan')
.attr('x', x)
.attr('y', y)
.attr('dy', `${dy}em`);
let didWrap = false;
words.forEach(word => {
line.push(word);
tspan.text(line.join(' '));
if (tspan.node().getComputedTextLength() > width) {
lineNumber += 1;
line.pop();
// remove word that pushes over the limit
tspan.text(line.join(' '));
line = [word];
tspan = d3Text
.append('tspan')
.attr('x', x)
.attr('y', y)
.attr('dy', `${lineNumber * lineHeight + dy}em`)
.text(word);
didWrap = true;
}
});
if (!didWrap && typeof adjustedY !== 'undefined') {
tspan.attr('y', adjustedY);
}
});
}
|
apache/incubator-superset
|
superset-frontend/plugins/legacy-plugin-chart-sunburst/src/utils/wrapSvgText.js
|
JavaScript
|
apache-2.0
| 2,261 |
/*
* Copyright 2009-2011 WorldWide Conferencing, 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.
*/
package org.json4s
import java.util.Locale.ENGLISH
import java.io.StringWriter
import collection.immutable
object JsonAST {
/**
* Concatenates a sequence of <code>JValue</code>s.
* <p>
* Example:<pre>
* concat(JInt(1), JInt(2)) == JArray(List(JInt(1), JInt(2)))
* </pre>
*/
def concat(xs: JValue*) = xs.foldLeft(JNothing: JValue)(_ ++ _)
// sealed abstract class JsValue[+T] extends immutable.Seq[T] {
// def values: T
// }
// private trait SingleElementJsValue[+T] extends JsValue[T] {
// def length: Int = 1
// def apply(idx: Int): T = if (idx == 0) values else throw new IndexOutOfBoundsException("A JsString only has 1 element")
// def iterator: Iterator[T] = Iterator(values)
// override def isEmpty: Boolean = false
// override def head = values
// override def tail: immutable.Seq[T] = Nil
// override protected[this] def reversed: List[T] = List(values)
// override def nonEmpty: Boolean = true
// }
//
// class JsString(val values: String) extends SingleElementJsValue[String]
// class JsInt(val values: BigInt) extends SingleElementJsValue[BigInt]
// class JsDecimal(val values: BigDecimal) extends SingleElementJsValue[BigDecimal]
// class JsBool(val values: Boolean) extends SingleElementJsValue[Boolean]
// object JsNull extends SingleElementJsValue[Null] { val values: Null = null }
//
// class JsObject(val values: Seq[(String, JsValue[_])]) extends JsValue[(String, JsValue[_])] {
// def length: Int = values.length
// def apply(idx: Int): (String, JsValue[_]) = values(idx)
// def iterator: Iterator[(String, JsValue[_])] = values.iterator
// }
// class JsArray(val values: Seq[JsValue[_]]) extends JsValue[JsValue[_]] {
// def length: Int = values.length
// def apply(idx: Int): JsValue[_] = values.apply(idx)
// def iterator: Iterator[JsValue[_]] = values.iterator
// }
// object JsNothing extends JsValue[Nothing] {
// val values: Nothing = null.asInstanceOf[Nothing]
// val length: Int = 0
// def apply(idx: Int): Nothing = throw new IndexOutOfBoundsException("A JsNothing is empty")
// def iterator: Iterator[Nothing] = Iterator()
//
// override def isEmpty = true
// override def head: Nothing =
// throw new NoSuchElementException("head of JsNothing")
// override def tail: List[Nothing] =
// throw new UnsupportedOperationException("tail of JsNothing")
// // Removal of equals method here might lead to an infinite recursion similar to IntMap.equals.
// override def equals(that: Any) = that match {
// case that1: JsValue[_] => that1.isEmpty
// case _ => false
// }
// }
object JValue extends Merge.Mergeable
/**
* Data type for JSON AST.
*/
sealed abstract class JValue extends Diff.Diffable {
type Values
/**
* Return unboxed values from JSON
* <p>
* Example:<pre>
* JObject(JField("name", JString("joe")) :: Nil).values == Map("name" -> "joe")
* </pre>
*/
def values: Values
/**
* Return direct child elements.
* <p>
* Example:<pre>
* JArray(JInt(1) :: JInt(2) :: Nil).children == List(JInt(1), JInt(2))
* </pre>
*/
def children: List[JValue] = this match {
case JObject(l) ⇒ l map (_._2)
case JArray(l) ⇒ l
case _ ⇒ Nil
}
/**
* Return nth element from JSON.
* Meaningful only to JArray, JObject and JField. Returns JNothing for other types.
* <p>
* Example:<pre>
* JArray(JInt(1) :: JInt(2) :: Nil)(1) == JInt(2)
* </pre>
*/
def apply(i: Int): JValue = JNothing
/**
* Concatenate with another JSON.
* This is a concatenation monoid: (JValue, ++, JNothing)
* <p>
* Example:<pre>
* JArray(JInt(1) :: JInt(2) :: Nil) ++ JArray(JInt(3) :: Nil) ==
* JArray(List(JInt(1), JInt(2), JInt(3)))
* </pre>
*/
def ++(other: JValue) = {
def append(value1: JValue, value2: JValue): JValue = (value1, value2) match {
case (JNothing, x) ⇒ x
case (x, JNothing) ⇒ x
case (JArray(xs), JArray(ys)) ⇒ JArray(xs ::: ys)
case (JArray(xs), v: JValue) ⇒ JArray(xs ::: List(v))
case (v: JValue, JArray(xs)) ⇒ JArray(v :: xs)
case (x, y) ⇒ JArray(x :: y :: Nil)
}
append(this, other)
}
/**
* When this [[org.json4s.JValue]] is a [[org.json4s.JNothing]], this method returns [[scala.None]]
* When it has a value it will return [[scala.Some]]
*/
@deprecated("Use toOption instead", "3.1.0")
def toOpt: Option[JValue] = toOption
/**
* When this [[org.json4s.JValue]] is a [[org.json4s.JNothing]], this method returns [[scala.None]]
* When it has a value it will return [[scala.Some]]
*/
def toOption: Option[JValue] = this match {
case JNothing ⇒ None
case json ⇒ Some(json)
}
}
case object JNothing extends JValue {
type Values = None.type
def values = None
}
case object JNull extends JValue {
type Values = Null
def values = null
}
case class JString(s: String) extends JValue {
type Values = String
def values = s
}
trait JNumber
case class JDouble(num: Double) extends JValue with JNumber {
type Values = Double
def values = num
}
case class JDecimal(num: BigDecimal) extends JValue with JNumber {
type Values = BigDecimal
def values = num
}
case class JInt(num: BigInt) extends JValue with JNumber {
type Values = BigInt
def values = num
}
case class JBool(value: Boolean) extends JValue {
type Values = Boolean
def values = value
}
case class JObject(obj: List[JField]) extends JValue {
type Values = Map[String, Any]
def values = obj.map { case (n, v) ⇒ (n, v.values) } toMap
override def equals(that: Any): Boolean = that match {
case o: JObject ⇒ obj.toSet == o.obj.toSet
case _ ⇒ false
}
override def hashCode = obj.toSet[JField].hashCode
}
case object JObject {
def apply(fs: JField*): JObject = JObject(fs.toList)
}
case class JArray(arr: List[JValue]) extends JValue {
type Values = List[Any]
def values = arr.map(_.values)
override def apply(i: Int): JValue = arr(i)
}
type JField = (String, JValue)
object JField {
def apply(name: String, value: JValue) = (name, value)
def unapply(f: JField): Option[(String, JValue)] = Some(f)
}
private[this] trait StringAppender[T] {
def append(s: String): T
def subj: T
}
private[this] class StringWriterAppender(val subj: java.io.Writer) extends StringAppender[java.io.Writer] {
def append(s: String): java.io.Writer = subj.append(s)
}
private[this] class StringBuilderAppender(val subj: StringBuilder) extends StringAppender[StringBuilder] {
def append(s: String): StringBuilder = subj.append(s)
}
private[json4s] def quote(s: String): String = quote(s, new StringBuilderAppender(new StringBuilder)).toString
private[json4s] def quote(s: String, writer: java.io.Writer): java.io.Writer = quote(s, new StringWriterAppender(writer))
private[this] def quote[T](s: String, appender: StringAppender[T]): T = { // hot path
var i = 0
val l = s.length
while(i < l) {
val c = s(i)
if (c == '"') appender.append("\\\"")
else if (c == '\\') appender.append("\\\\")
else if (c == '\b') appender.append("\\b")
else if (c == '\f') appender.append("\\f")
else if (c == '\n') appender.append("\\n")
else if (c == '\r') appender.append("\\r")
else if (c == '\t') appender.append("\\t")
else if ((c >= '\u0000' && c <= '\u001f') || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100'))
appender.append("\\u%04x".format(c: Int))
else appender.append(c.toString)
i += 1
}
appender.subj
}
}
|
nornagon/json4s
|
ast/src/main/scala/org/json4s/JsonAST.scala
|
Scala
|
apache-2.0
| 8,477 |
//
// ODDiscoverView.h
// AutoPartStore
//
// Created by GoldyMark on 15-3-22.
// Copyright (c) 2015年 GoldyMark. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ODDiscoverViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
@property (strong, nonatomic) NSArray * items;
@property (weak,nonatomic) IBOutlet UICollectionView *collectionView;
@end
|
GoldyMark/iOS-app-demo
|
appDemo/appDemo/ODDiscoverViewController.h
|
C
|
apache-2.0
| 401 |
<h1 class="converter">OutputDirectory</h1>
## Synopsis
Converts into the path to a writable directory.
## String conversion
The string value is interpreted as a path to a directory. The value must be a valid file system path to an existing directory or a descendant to an existing directory with reading, writing and traversal rights for the current user.
## XML conversion
```xml
<param value="PATH"/>
```
or
```xml
<param path="PATH"/>
```
or
```xml
<param file="PATH"/>
```
or
```xml
<param>PATH</param>
```
*PATH* is converted into an *OutputDirectory* as specified by the string conversion.
|
Bibliome/alvisnlp
|
docs/reference/converter/fr.inra.maiage.bibliome.util.files.OutputDirectory.md
|
Markdown
|
apache-2.0
| 627 |
/*
* Copyright 2018 The gRPC 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 io.grpc.alts.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.ReferenceCountUtil;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.concurrent.Future;
import javax.annotation.Nullable;
/**
* Performs The TSI Handshake. When the handshake is complete, it fires a user event with a {@link
* TsiHandshakeCompletionEvent} indicating the result of the handshake.
*/
public final class TsiHandshakeHandler extends ByteToMessageDecoder {
private static final int HANDSHAKE_FRAME_SIZE = 1024;
private final NettyTsiHandshaker handshaker;
private boolean started;
/**
* This buffer doesn't store any state. We just hold onto it in case we end up allocating a buffer
* that ends up being unused.
*/
private ByteBuf buffer;
public TsiHandshakeHandler(NettyTsiHandshaker handshaker) {
this.handshaker = checkNotNull(handshaker);
}
/**
* Event that is fired once the TSI handshake is complete, which may be because it was successful
* or there was an error.
*/
public static final class TsiHandshakeCompletionEvent {
private final Throwable cause;
private final TsiPeer peer;
private final Object context;
private final TsiFrameProtector protector;
/** Creates a new event that indicates a successful handshake. */
@VisibleForTesting
TsiHandshakeCompletionEvent(
TsiFrameProtector protector, TsiPeer peer, @Nullable Object peerObject) {
this.cause = null;
this.peer = checkNotNull(peer);
this.protector = checkNotNull(protector);
this.context = peerObject;
}
/** Creates a new event that indicates an unsuccessful handshake/. */
TsiHandshakeCompletionEvent(Throwable cause) {
this.cause = checkNotNull(cause);
this.peer = null;
this.protector = null;
this.context = null;
}
/** Return {@code true} if the handshake was successful. */
public boolean isSuccess() {
return cause == null;
}
/**
* Return the {@link Throwable} if {@link #isSuccess()} returns {@code false} and so the
* handshake failed.
*/
@Nullable
public Throwable cause() {
return cause;
}
@Nullable
public TsiPeer peer() {
return peer;
}
@Nullable
public Object context() {
return context;
}
@Nullable
TsiFrameProtector protector() {
return protector;
}
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
maybeStart(ctx);
super.handlerAdded(ctx);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
maybeStart(ctx);
super.channelActive(ctx);
}
@Override
public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
close();
super.handlerRemoved0(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.fireUserEventTriggered(new TsiHandshakeCompletionEvent(cause));
super.exceptionCaught(ctx, cause);
}
@Override
protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
throws Exception {
// TODO: Not sure why override is needed. Investigate if it can be removed.
decode(ctx, in, out);
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
// Process the data. If we need to send more data, do so now.
if (handshaker.processBytesFromPeer(in) && handshaker.isInProgress()) {
sendHandshake(ctx);
}
// If the handshake is complete, transition to the framing state.
if (!handshaker.isInProgress()) {
try {
ctx.pipeline().remove(this);
ctx.fireUserEventTriggered(
new TsiHandshakeCompletionEvent(
handshaker.createFrameProtector(ctx.alloc()),
handshaker.extractPeer(),
handshaker.extractPeerObject()));
// No need to do anything with the in buffer, it will be re added to the pipeline when this
// handler is removed.
} finally {
close();
}
}
}
private void maybeStart(ChannelHandlerContext ctx) {
if (!started && ctx.channel().isActive()) {
started = true;
sendHandshake(ctx);
}
}
/** Sends as many bytes as are available from the handshaker to the remote peer. */
private void sendHandshake(ChannelHandlerContext ctx) {
boolean needToFlush = false;
// Iterate until there is nothing left to write.
while (true) {
buffer = getOrCreateBuffer(ctx.alloc());
try {
handshaker.getBytesToSendToPeer(buffer);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
if (!buffer.isReadable()) {
break;
}
needToFlush = true;
@SuppressWarnings("unused") // go/futurereturn-lsc
Future<?> possiblyIgnoredError = ctx.write(buffer);
buffer = null;
}
// If something was written, flush.
if (needToFlush) {
ctx.flush();
}
}
private ByteBuf getOrCreateBuffer(ByteBufAllocator alloc) {
if (buffer == null) {
buffer = alloc.buffer(HANDSHAKE_FRAME_SIZE);
}
return buffer;
}
private void close() {
ReferenceCountUtil.safeRelease(buffer);
buffer = null;
}
}
|
zhangkun83/grpc-java
|
alts/src/main/java/io/grpc/alts/internal/TsiHandshakeHandler.java
|
Java
|
apache-2.0
| 6,233 |
/*
* Copyright 2012-2017 the original author or 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
*
* https://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.
*/
/**
* Jersey support for actuator endpoints.
*/
package org.springframework.boot.actuate.endpoint.web.jersey;
|
lburgazzoli/spring-boot
|
spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/package-info.java
|
Java
|
apache-2.0
| 735 |
// Copyright 2016 The Sawdust 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.
//
/**
* https://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol
*/
package Advanced_Message_Queuing_Protocol_AMQP;
|
BruceZu/KeepTry
|
bow/2-technical-and-design/network/Advanced_Message_Queuing_Protocol_AMQP/package-info.java
|
Java
|
apache-2.0
| 736 |
/*
* 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.geode.cache.query.dunit;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.geode.DataSerializable;
import org.apache.geode.DataSerializer;
public class TestObject implements DataSerializable {
protected String _ticker;
protected int _price;
public int id;
public int important;
public int selection;
public int select;
public TestObject() {}
public TestObject(int id, String ticker) {
this.id = id;
_ticker = ticker;
_price = id;
important = id;
selection = id;
select = id;
}
public int getId() {
return id;
}
public String getTicker() {
return _ticker;
}
public int getPrice() {
return _price;
}
@Override
public void toData(DataOutput out) throws IOException {
out.writeInt(id);
DataSerializer.writeString(_ticker, out);
out.writeInt(_price);
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
id = in.readInt();
_ticker = DataSerializer.readString(in);
_price = in.readInt();
}
@Override
public String toString() {
return "TestObject [" + "id=" + id + "; ticker="
+ _ticker + "; price=" + _price + "]";
}
@Override
public boolean equals(Object o) {
if (!(o instanceof TestObject)) {
return false;
}
TestObject other = (TestObject) o;
return (id == other.id) && (_ticker.equals(other._ticker));
}
@Override
public int hashCode() {
return id;
}
}
|
jdeppe-pivotal/geode
|
geode-dunit/src/main/java/org/apache/geode/cache/query/dunit/TestObject.java
|
Java
|
apache-2.0
| 2,321 |
(function(){
function Rooms($firebaseArray){
var ref = firebase.database().ref().child("rooms");
var rooms = $firebaseArray(ref);
return {
all: rooms,
addRoom: function(newRoomText){
rooms.$add({
name: newRoomText
});
}
};
}
angular
.module('blocChat')
.factory('Rooms', ['$firebaseArray', Rooms]);
})();
|
valoriedodge/Blocchat
|
dist/scripts/services/Room.js
|
JavaScript
|
apache-2.0
| 381 |
package org.fastcatsearch.ir.summary;
import java.util.HashMap;
import java.util.HashSet;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.CharsRefTermAttribute;
import org.apache.lucene.search.highlight.Scorer;
import org.apache.lucene.search.highlight.TextFragment;
import org.apache.lucene.search.highlight.WeightedTerm;
import org.apache.lucene.util.CharsRef;
import org.fastcatsearch.ir.io.CharVector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TokenizedTermScorer implements Scorer {
Logger logger = LoggerFactory.getLogger(TokenizedTermScorer.class);
TextFragment currentTextFragment = null;
HashSet<String> uniqueTermsInFragment;
float totalScore = 0;
float maxTermWeight = 0;
private HashMap<CharVector,WeightedTerm> termsToFind;
private CharTermAttribute termAtt;
private CharsRefTermAttribute refTermAtt;
public TokenizedTermScorer(WeightedTerm[] weightedTerms) {
termsToFind = new HashMap<CharVector,WeightedTerm>();
for (int i = 0; i < weightedTerms.length; i++) {
WeightedTerm existingTerm = termsToFind
.get(weightedTerms[i].getTerm());
if ((existingTerm == null)
|| (existingTerm.getWeight() < weightedTerms[i].getWeight())) {
// if a term is defined more than once, always use the highest scoring
// weight
CharVector cv = new CharVector(weightedTerms[i].getTerm());
cv.setIgnoreCase();
termsToFind.put(cv, weightedTerms[i]);
maxTermWeight = Math.max(maxTermWeight, weightedTerms[i].getWeight());
}
}
}
/* (non-Javadoc)
* @see org.apache.lucene.search.highlight.Scorer#init(org.apache.lucene.analysis.TokenStream)
*/
@Override
public TokenStream init(TokenStream tokenStream) {
termAtt = tokenStream.addAttribute(CharTermAttribute.class);
if(tokenStream.hasAttribute(CharsRefTermAttribute.class)) {
refTermAtt = tokenStream.addAttribute(CharsRefTermAttribute.class);
}
return null;
}
/*
* (non-Javadoc)
*
* @see
* org.apache.lucene.search.highlight.FragmentScorer#startFragment(org.apache
* .lucene.search.highlight.TextFragment)
*/
@Override
public void startFragment(TextFragment newFragment) {
uniqueTermsInFragment = new HashSet<String>();
currentTextFragment = newFragment;
totalScore = 0;
}
/* (non-Javadoc)
* @see org.apache.lucene.search.highlight.Scorer#getTokenScore()
*/
@Override
public float getTokenScore() {
CharVector termText = null;
WeightedTerm queryTerm = null;
termText = new CharVector(termAtt.toString());
termText.setIgnoreCase();
//logger.trace("termAtt : {} in {}",termText, uniqueTermsInFragment);
queryTerm = termsToFind.get(termText);
if (queryTerm != null) {
logger.trace("matched termText {}",termText);
totalScore += queryTerm.getWeight();
//uniqueTermsInFragment.add(termText);
return queryTerm.getWeight();
}
if (refTermAtt != null) {
CharsRef charRef = refTermAtt.charsRef();
if(charRef!=null) {
CharVector cv = new CharVector(charRef.toString());
cv.setIgnoreCase();
queryTerm = termsToFind.get(cv);
if (queryTerm != null && !(charRef.offset > 0 && charRef.length == 1)) {
logger.trace("matched refTermText {}",termText);
totalScore += queryTerm.getWeight();
//uniqueTermsInFragment.add(termText);
return queryTerm.getWeight();
}
}
}
return 0;
}
/* (non-Javadoc)
* @see org.apache.lucene.search.highlight.Scorer#getFragmentScore()
*/
@Override
public float getFragmentScore() {
return totalScore;
}
/*
* (non-Javadoc)
*
* @see
* org.apache.lucene.search.highlight.FragmentScorer#allFragmentsProcessed()
*/
public void allFragmentsProcessed() {
// this class has no special operations to perform at end of processing
}
/**
*
* @return The highest weighted term (useful for passing to GradientFormatter
* to set top end of coloring scale.
*/
public float getMaxTermWeight() {
return maxTermWeight;
}
}
|
fastcat-co/fastcatsearch
|
core/src/main/java/org/fastcatsearch/ir/summary/TokenizedTermScorer.java
|
Java
|
apache-2.0
| 4,082 |
/*
* Copyright (c) 2015 SONATA-NFV, UCL, NOKIA, NCSR Demokritos 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.
*
* Neither the name of the SONATA-NFV, UCL, NOKIA, NCSR Demokritos nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific prior
* written permission.
*
* This work has been performed in the framework of the SONATA project, funded by the European
* Commission under Grant number 671517 through the Horizon 2020 and 5G-PPP programmes. The authors
* would like to acknowledge the contributions of their colleagues of the SONATA partner consortium
* (www.sonata-nfv.eu).
*
* @author Dario Valocchi (Ph.D.), UCL
*
*/
package sonata.kernel.vimadaptor.wrapper.openstack.heat;
import com.fasterxml.jackson.annotation.JsonProperty;
public class HeatNet {
private String cidr;
@JsonProperty("net_id")
private String netId;
@JsonProperty("net_name")
private String netName;
@JsonProperty("segmentation_id")
private int segmentationId;
@JsonProperty("subnet_id")
private String subnetId;
@JsonProperty("subnet_name")
private String subnetName;
public String getCidr() {
return cidr;
}
public String getNetId() {
return netId;
}
public String getNetName() {
return netName;
}
public int getSegmentationId() {
return segmentationId;
}
public String getSubnetId() {
return subnetId;
}
public String getSubnetName() {
return subnetName;
}
public void setCidr(String cidr) {
this.cidr = cidr;
}
public void setNetId(String netId) {
this.netId = netId;
}
public void setNetName(String netName) {
this.netName = netName;
}
public void setSegmentationId(int segmentationId) {
this.segmentationId = segmentationId;
}
public void setSubnetId(String subnetId) {
this.subnetId = subnetId;
}
public void setSubnetName(String subnetName) {
this.subnetName = subnetName;
}
}
|
skolome/son-sp-infrabstract
|
vim-adaptor/adaptor/src/main/java/sonata/kernel/vimadaptor/wrapper/openstack/heat/HeatNet.java
|
Java
|
apache-2.0
| 2,511 |
---
layout: global
title: Configuration Settings
group: Features
priority: 1
---
* Table of Contents
{:toc}
This page explains the configuration settings of Alluxio and also provides recommendation on how to customize the configuration
for Alluxio in different contexts.
## Configuration in Alluxio
Alluxio runtime respects three sources of configuration settings:
1. [Application settings](#application-settings). Setting Alluxio configuration in this way is application-specific,
and is required each time when running an application instance (e.g., a Spark job).
2. [Environment variables](#environment-variables). This is an easy and fast way to set the basic configuration
to manage Alluxio servers and run Alluxio shell commands.
Note that, configuration set through environment variables may not be realized by applications.
3. [Property files](#property-files). This is a general approach to customize any
[supported Alluxio configuration](#appendix). Configuration in those files can be respected by Alluxio servers,
as well as applications.
The priority to load configuration settings, from the highest to the lowest, is
application settings (if any), environment variables, property files and the defaults.
### Application settings
Alluxio shell users can use `-Dkey=property` to specify an Alluxio configuration value in commandline. For example,
{% include Configuration-Settings/specify-conf.md %}
Spark users can add `"-Dkey=property"` to `${SPARK_DAEMON_JAVA_OPTS}` in `conf/spark-env.sh`, or add it to
`spark.executor.extraJavaOptions` (for Spark executors) and `spark.driver.extraJavaOptions` (for Spark drivers).
Hadoop MapReduce users can set `"-Dkey=property"` in `hadoop jar` command-lines to pass it down to Alluxio:
{% include Configuration-Settings/hadoop-specify-conf.md %}
Note that, setting Alluxio configuration in this way is application specific and required for each job or command.
### Environment variables
> When you want to [start Alluxio server processes](Running-Alluxio-Locally.html), or [use Alluxio command line interfaces](Command-Line-Interface.html) with your specific configuration tuning, it is often fast and easy to set environment variables to customize basic Alluxio configuration. However, these environment variables will not affect application processes like Spark or MapReduce that use Alluxio as a client.
Alluxio supports a few basic and very frequently used configuration settings via the environment variables in
`conf/alluxio-env.sh`, including:
<table class="table table-striped">
<tr><th>Environment Variable</th><th>Meaning</th></tr>
<tr>
<td><code class="highlighter-rouge">ALLUXIO_MASTER_HOSTNAME</code></td>
<td>hostname of Alluxio master, defaults to localhost.</td>
</tr>
<tr>
<td><del><code class="highlighter-rouge">ALLUXIO_MASTER_ADDRESS</code></del></td>
<td>deprecated by <code class="highlighter-rouge">ALLUXIO_MASTER_HOSTNAME</code> since version 1.1 and
will be remove in version 2.0.</td>
</tr>
<tr>
<td><code class="highlighter-rouge">ALLUXIO_UNDERFS_ADDRESS</code></td>
<td>under storage system address, defaults to
<code class="highlighter-rouge">${ALLUXIO_HOME}/underFSStorage</code> which is a local file system.</td>
</tr>
<tr>
<td><code class="highlighter-rouge">ALLUXIO_RAM_FOLDER</code></td>
<td>the directory where a worker stores in-memory data, defaults to <code class="highlighter-rouge">/mnt/ramdisk</code>.</td>
</tr>
<tr>
<td><code class="highlighter-rouge">ALLUXIO_JAVA_OPTS</code></td>
<td>Java VM options for both Master, Worker and Alluxio Shell configuration.
Note that, by default <code class="highlighter-rouge">ALLUXIO_JAVA_OPTS</code> is included in both
<code class="highlighter-rouge">ALLUXIO_MASTER_JAVA_OPTS</code>,
<code class="highlighter-rouge">ALLUXIO_WORKER_JAVA_OPTS</code> and
<code class="highlighter-rouge">ALLUXIO_USER_JAVA_OPTS</code>.</td>
</tr>
<tr>
<td><code class="highlighter-rouge">ALLUXIO_MASTER_JAVA_OPTS</code></td>
<td>additional Java VM options for Master configuration.</td>
</tr>
<tr>
<td><code class="highlighter-rouge">ALLUXIO_WORKER_JAVA_OPTS</code></td>
<td>additional Java VM options for Worker configuration. </td>
</tr>
<tr>
<td><code class="highlighter-rouge">ALLUXIO_USER_JAVA_OPTS</code></td>
<td>additional Java VM options for Alluxio shell configuration.</td>
</tr>
<tr>
<td><code class="highlighter-rouge">ALLUXIO_CLASSPATH</code></td>
<td>additional classpath entries for Alluxio processes. This is empty by default.</td>
</tr>
</table>
For example, if you would like to setup an Alluxio master at `localhost` that talks to an HDFS cluster with a namenode
also running at `localhost`, and enable Java remote debugging at port 7001, you can do so before starting master process using:
{% include Configuration-Settings/more-conf.md %}
Users can either set these variables through shell or in `conf/alluxio-env.sh`. If this file does not exist yet,
Alluxio can help you bootstrap the `conf/alluxio-env.sh` file by running
{% include Common-Commands/bootstrapConf.md %}
Alternatively, you can create one from a template we provided in the source code using:
{% include Common-Commands/copy-alluxio-env.md %}
### Property files
> Alluxio site property file `alluxio-site.properties` can overwrite Alluxio configuration regardless the JVM is an Alluxio server process or a job using Alluxio client. For the site property file to be loaded, either the parent directory of this file is a part of the classpath of your target JVM process, or the file is in one of the pre-defined paths.
Using Alluxio supported environment variables has two limitations:
first it only provides basic Alluxio settings, and second it does not affect non-Alluxio JVMs like Spark or MapReduce.
To address them, Alluxio uses site property file `alluxio-site.properties` for users to customize all supported configuration settings, regardless of the JVM process.
On startup, Alluxio runtime checks if the configuration
property file exists and if so, it uses the content to override the default configuration.
To be specific, it searches `alluxio-site.properties` in `${HOME}/.alluxio/`, `/etc/alluxio/` (can be customized by changing the default value
of `alluxio.site.conf.dir`) and the classpath of the relevant Java VM process in order, and skips the remaining paths once
a file is found.
For example, `${ALLUXIO_HOME}/conf/` is by default on the classpath of Alluxio master, worker and shell JVM processes.
So you can simply create `${ALLUXIO_HOME}/conf/alluxio-site.properties` by
```bash
$ cp conf/alluxio-site.properties.template conf/alluxio-site.properties
```
Then customize it to fit your configuration tuning needs to start Alluxio servers or to use Alluxio shell commands:
{% include Common-Commands/copy-alluxio-site-properties.md %}
For applications like Spark or MapReduce to use Alluxio property files, you can append the directory of your site property files to your application classpath.
For example
```bash
$ export SPARK_CLASSPATH=${ALLUXIO_HOME}/conf:${SPARK_CLASSPATH} # for Spark jobs
$ export HADOOP_CLASSPATH=${ALLUXIO_HOME}/conf:${HADOOP_CLASSPATH} # for Hadoop jobs
```
Alternatively, with access to paths like `/etc/`, one can copy the site properties to `/etc/alluxio/`. This configuration will be shared
across processes regardless the JVM is an Alluxio server or a job using Alluxio client.
## Appendix
All Alluxio configuration settings fall into one of the six categories:
[Common](#common-configuration) (shared by Master and Worker),
[Master specific](#master-configuration), [Worker specific](#worker-configuration),
[User specific](#user-configuration), [Cluster specific](#cluster-management) (used for running
Alluxio with cluster managers like Mesos and YARN), and
[Security specific](#security-configuration) (shared by Master, Worker, and User).
### Common Configuration
The common configuration contains constants shared by different components.
<table class="table table-striped">
<tr><th>Property Name</th><th>Default</th><th>Meaning</th></tr>
{% for item in site.data.table.common-configuration %}
<tr>
<td>{{ item.propertyName }}</td>
<td>{{ item.defaultValue }}</td>
<td>{{ site.data.table.en.common-configuration[item.propertyName] }}</td>
</tr>
{% endfor %}
</table>
### Master Configuration
The master configuration specifies information regarding the master node, such as the address and
the port number.
<table class="table table-striped">
<tr><th>Property Name</th><th>Default</th><th>Meaning</th></tr>
{% for item in site.data.table.master-configuration %}
<tr>
<td>{{ item.propertyName }}</td>
<td>{{ item.defaultValue }}</td>
<td>{{ site.data.table.en.master-configuration[item.propertyName] }}</td>
</tr>
{% endfor %}
</table>
### Worker Configuration
The worker configuration specifies information regarding the worker nodes, such as the address and
the port number.
<table class="table table-striped">
<tr><th>Property Name</th><th>Default</th><th>Meaning</th></tr>
{% for item in site.data.table.worker-configuration %}
<tr>
<td>{{ item.propertyName }}</td>
<td>{{ item.defaultValue }}</td>
<td>{{ site.data.table.en.worker-configuration[item.propertyName] }}</td>
</tr>
{% endfor %}
</table>
### User Configuration
The user configuration specifies values regarding file system access.
<table class="table table-striped">
<tr><th>Property Name</th><th>Default</th><th>Meaning</th></tr>
{% for item in site.data.table.user-configuration %}
<tr>
<td>{{ item.propertyName }}</td>
<td>{{ item.defaultValue }}</td>
<td>{{ site.data.table.en.user-configuration[item.propertyName] }}</td>
</tr>
{% endfor %}
</table>
### Resource Manager Configuration
When running Alluxio with resource managers like Mesos and YARN, Alluxio has additional configuration options.
<table class="table table-striped">
<tr><th>Property Name</th><th>Default</th><th>Meaning</th></tr>
{% for item in site.data.table.cluster-management %}
<tr>
<td>{{ item.propertyName }}</td>
<td>{{ item.defaultValue }}</td>
<td>{{ site.data.table.en.cluster-management[item.propertyName] }}</td>
</tr>
{% endfor %}
</table>
### Security Configuration
The security configuration specifies information regarding the security features, such as authentication and file permission. Settings for authentication take effect for master, worker, and user. Settings for file permission only take effect for master. See [Security](Security.html) for more information about security features.
<table class="table table-striped">
<tr><th>Property Name</th><th>Default</th><th>Meaning</th></tr>
{% for item in site.data.table.security-configuration %}
<tr>
<td>{{ item.propertyName }}</td>
<td>{{ item.defaultValue }}</td>
<td>{{ site.data.table.en.security-configuration[item.propertyName] }}</td>
</tr>
{% endfor %}
</table>
### Configure Multihomed Networks
Alluxio configuration provides a way to take advantage of multi-homed networks. If you have more than one NICs and you want your Alluxio master to listen on all NICs, you can specify `alluxio.master.bind.host` to be `0.0.0.0`. As a result, Alluxio clients can reach the master node from connecting to any of its NIC. This is also the same case for other settings suffixed with `bind.host`.
|
jsimsa/alluxio
|
docs/en/Configuration-Settings.md
|
Markdown
|
apache-2.0
| 11,361 |
/*
* 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.wso2.carbon.cassandra.search.data;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* representation of a column of Cassandra
*/
public class Column implements Comparable{
private String name="" ;
private long timeStamp = 0L ;
private String value = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o == this) {
return true;
}
if (!(o instanceof Column)) {
return false;
}
Column column = (Column) o;
return column.getName().equals(this.name)
&& Long.valueOf(column.getTimeStamp()).equals(this.timeStamp)
&& column.getValue().equals(this.value);
}
public int hashCode() {
return new HashCodeBuilder(17, 31).
append(this.name).append(this.timeStamp).
append(this.value).toHashCode();
}
public int compareTo(Object o) {
if (!(o instanceof Column)){
throw new ClassCastException("Invalid object");
}
Column column = (Column) o;
return (Long.valueOf(column.getTimeStamp())).compareTo(timeStamp);
}
}
|
lankavitharana/carbon-storage-management
|
components/cassandra-search/org.wso2.carbon.cassandra.search.mgt/src/main/java/org/wso2/carbon/cassandra/search/data/Column.java
|
Java
|
apache-2.0
| 2,425 |
/*
* Copyright 2012-2019 the original author or 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
*
* https://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.spring.initializr.generator.language.groovy;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import io.spring.initializr.generator.language.Annotatable;
import io.spring.initializr.generator.language.Annotation;
import io.spring.initializr.generator.language.Parameter;
/**
* Declaration of a method written in Groovy.
*
* @author Stephane Nicoll
*/
public final class GroovyMethodDeclaration implements Annotatable {
private final List<Annotation> annotations = new ArrayList<>();
private final String name;
private final String returnType;
private final int modifiers;
private final List<Parameter> parameters;
private final List<GroovyStatement> statements;
private GroovyMethodDeclaration(String name, String returnType, int modifiers, List<Parameter> parameters,
List<GroovyStatement> statements) {
this.name = name;
this.returnType = returnType;
this.modifiers = modifiers;
this.parameters = parameters;
this.statements = statements;
}
public static Builder method(String name) {
return new Builder(name);
}
String getName() {
return this.name;
}
String getReturnType() {
return this.returnType;
}
List<Parameter> getParameters() {
return this.parameters;
}
int getModifiers() {
return this.modifiers;
}
public List<GroovyStatement> getStatements() {
return this.statements;
}
@Override
public void annotate(Annotation annotation) {
this.annotations.add(annotation);
}
@Override
public List<Annotation> getAnnotations() {
return Collections.unmodifiableList(this.annotations);
}
/**
* Builder for creating a {@link GroovyMethodDeclaration}.
*/
public static final class Builder {
private final String name;
private List<Parameter> parameters = new ArrayList<>();
private String returnType = "void";
private int modifiers = Modifier.PUBLIC;
private Builder(String name) {
this.name = name;
}
public Builder modifiers(int modifiers) {
this.modifiers = modifiers;
return this;
}
public Builder returning(String returnType) {
this.returnType = returnType;
return this;
}
public Builder parameters(Parameter... parameters) {
this.parameters = Arrays.asList(parameters);
return this;
}
public GroovyMethodDeclaration body(GroovyStatement... statements) {
return new GroovyMethodDeclaration(this.name, this.returnType, this.modifiers, this.parameters,
Arrays.asList(statements));
}
}
}
|
snicoll/initializr
|
initializr-generator/src/main/java/io/spring/initializr/generator/language/groovy/GroovyMethodDeclaration.java
|
Java
|
apache-2.0
| 3,165 |
/*
* #%L
* ELK OWL Model Implementation
*
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2011 - 2012 Department of Computer Science, University of Oxford
* %%
* 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.
* #L%
*/
/**
*
*/
package org.semanticweb.elk.owl.parsing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Test;
import org.semanticweb.elk.owl.implementation.ElkDataPropertyListRestrictionQualifiedImpl;
import org.semanticweb.elk.owl.interfaces.ElkAnnotationAssertionAxiom;
import org.semanticweb.elk.owl.interfaces.ElkAsymmetricObjectPropertyAxiom;
import org.semanticweb.elk.owl.interfaces.ElkAxiom;
import org.semanticweb.elk.owl.interfaces.ElkClassAssertionAxiom;
import org.semanticweb.elk.owl.interfaces.ElkDataPropertyAssertionAxiom;
import org.semanticweb.elk.owl.interfaces.ElkDataPropertyDomainAxiom;
import org.semanticweb.elk.owl.interfaces.ElkDataPropertyRangeAxiom;
import org.semanticweb.elk.owl.interfaces.ElkDatatypeDefinitionAxiom;
import org.semanticweb.elk.owl.interfaces.ElkDeclarationAxiom;
import org.semanticweb.elk.owl.interfaces.ElkDifferentIndividualsAxiom;
import org.semanticweb.elk.owl.interfaces.ElkDisjointClassesAxiom;
import org.semanticweb.elk.owl.interfaces.ElkDisjointObjectPropertiesAxiom;
import org.semanticweb.elk.owl.interfaces.ElkEquivalentClassesAxiom;
import org.semanticweb.elk.owl.interfaces.ElkEquivalentDataPropertiesAxiom;
import org.semanticweb.elk.owl.interfaces.ElkEquivalentObjectPropertiesAxiom;
import org.semanticweb.elk.owl.interfaces.ElkFunctionalDataPropertyAxiom;
import org.semanticweb.elk.owl.interfaces.ElkFunctionalObjectPropertyAxiom;
import org.semanticweb.elk.owl.interfaces.ElkHasKeyAxiom;
import org.semanticweb.elk.owl.interfaces.ElkInverseFunctionalObjectPropertyAxiom;
import org.semanticweb.elk.owl.interfaces.ElkInverseObjectPropertiesAxiom;
import org.semanticweb.elk.owl.interfaces.ElkIrreflexiveObjectPropertyAxiom;
import org.semanticweb.elk.owl.interfaces.ElkNegativeDataPropertyAssertionAxiom;
import org.semanticweb.elk.owl.interfaces.ElkNegativeObjectPropertyAssertionAxiom;
import org.semanticweb.elk.owl.interfaces.ElkObjectPropertyAssertionAxiom;
import org.semanticweb.elk.owl.interfaces.ElkObjectPropertyDomainAxiom;
import org.semanticweb.elk.owl.interfaces.ElkObjectPropertyRangeAxiom;
import org.semanticweb.elk.owl.interfaces.ElkReflexiveObjectPropertyAxiom;
import org.semanticweb.elk.owl.interfaces.ElkSWRLRule;
import org.semanticweb.elk.owl.interfaces.ElkSameIndividualAxiom;
import org.semanticweb.elk.owl.interfaces.ElkSubClassOfAxiom;
import org.semanticweb.elk.owl.interfaces.ElkSubObjectPropertyOfAxiom;
import org.semanticweb.elk.owl.interfaces.ElkSymmetricObjectPropertyAxiom;
import org.semanticweb.elk.owl.interfaces.ElkTransitiveObjectPropertyAxiom;
import org.semanticweb.elk.owl.predefined.PredefinedElkPrefix;
import org.semanticweb.elk.owl.printers.OwlFunctionalStylePrinter;
/**
* Abstract tests for Elk functional syntax parsers
*
* @author Pavel Klinov
*
* [email protected]
*
*/
public abstract class AbstractOwl2FunctionalSyntaxParseTest {
/*-----------------
* Utility methods
------------------*/
protected InputStream getInputOntology(String fileName) {
return getClass().getClassLoader().getResourceAsStream(fileName);
}
protected ElkTestAxiomProcessor parseOntology(InputStream input)
throws Owl2ParseException {
Owl2Parser parser = instantiateParser(input);
ElkTestAxiomProcessor axiomCounter = new ElkTestAxiomProcessor();
parser.accept(axiomCounter);
return axiomCounter;
}
protected ElkTestAxiomProcessor parseOntology(String input)
throws Owl2ParseException {
Owl2Parser parser = instantiateParser(new StringReader(input));
ElkTestAxiomProcessor axiomCounter = new ElkTestAxiomProcessor();
parser.accept(axiomCounter);
return axiomCounter;
}
protected static void setDefaultPrefixes(Owl2Parser parser) {
for (PredefinedElkPrefix prefix : PredefinedElkPrefix.values())
parser.declarePrefix(prefix);
}
/**
* This method checks that the parser created the correct number of axioms
* of each type (identified by the corresponding Java class name)
*
* @param axiomTypeCounts
* @param checkAll
* If set to true, the check will fail if the parser created
* axioms of other types, in addition to those specified in the
* count map
* @throws IOException
*/
protected static void checkAxiomTypeCounts(ElkTestAxiomProcessor processor,
Map<Class<?>, Integer> axiomTypeCounts, boolean checkAll)
throws IOException {
boolean error = false;
// parsed without errors, check the output
for (Iterator<Entry<Class<?>, List<ElkAxiom>>> actualEntryIter = processor
.getAxiomMapEntries().iterator(); actualEntryIter.hasNext();) {
Map.Entry<Class<?>, List<ElkAxiom>> actualEntry = actualEntryIter
.next();
// check that the parser created the right number of axioms of each
// type
int expectedCount = getExpectedCount(axiomTypeCounts,
actualEntry.getKey());
if (expectedCount != actualEntry.getValue()
.size()) {
error = true;
dumpAxioms(actualEntry.getValue());
System.err.println("Wrong number of axioms parsed. Expected "
+ expectedCount + ", actual "
+ actualEntry.getValue().size());
}
axiomTypeCounts.remove(actualEntry.getKey());
}
/*
* for (Map.Entry<Class<?>, Integer> expectedEntry :
* axiomTypeCounts.entrySet()) {
* System.err.println(expectedEntry.getValue() +
* " axiom(s) of the type " + expectedEntry.getKey() +
* " were not parsed"); error = true; }
*/
assertFalse("Parsing errors detected (see the output above)", error);
}
private static int getExpectedCount(Map<Class<?>, Integer> axiomTypeCounts,
Class<?> actualType) {
int count = 0;
// TODO A bit slow, something like Trie would help here but who cares,
// it's just a test
for (Map.Entry<Class<?>, Integer> entry : axiomTypeCounts.entrySet()) {
if (entry.getKey().isAssignableFrom(actualType)) {
count += entry.getValue();
}
}
return count;
}
private static void dumpAxioms(Iterable<? extends ElkAxiom> axioms) throws IOException {
StringBuilder builder = new StringBuilder();
for (ElkAxiom axiom : axioms) {
OwlFunctionalStylePrinter.append(builder, axiom);
builder.append("\n");
}
System.err.println(builder.toString());
}
protected abstract Owl2Parser instantiateParser(InputStream stream);
protected abstract Owl2Parser instantiateParser(Reader reader);
/*-------------------------
* TESTS
-------------------------*/
/*
* See if we can parse the OWL2 primer sample ontology
*/
@Test
public void testOWL2Primer() throws Exception {
InputStream input = getInputOntology("owl2primer.owl");
assertNotNull(input);
ElkTestAxiomProcessor counter = parseOntology(input);
Map<Class<?>, Integer> expectedCountMap = new HashMap<Class<?>, Integer>();
expectedCountMap.put(ElkSubClassOfAxiom.class, 8);
expectedCountMap.put(ElkEquivalentClassesAxiom.class, 11);
expectedCountMap.put(ElkDisjointClassesAxiom.class, 2);
expectedCountMap.put(ElkSubObjectPropertyOfAxiom.class, 4);
expectedCountMap.put(ElkEquivalentObjectPropertiesAxiom.class, 1);
expectedCountMap.put(ElkEquivalentDataPropertiesAxiom.class, 1);
expectedCountMap.put(ElkDisjointObjectPropertiesAxiom.class, 2);
expectedCountMap.put(ElkInverseObjectPropertiesAxiom.class, 1);
expectedCountMap.put(ElkObjectPropertyDomainAxiom.class, 1);
expectedCountMap.put(ElkObjectPropertyRangeAxiom.class, 1);
expectedCountMap.put(ElkDataPropertyDomainAxiom.class, 1);
expectedCountMap.put(ElkDataPropertyRangeAxiom.class, 1);
expectedCountMap.put(ElkAnnotationAssertionAxiom.class, 1);
expectedCountMap.put(ElkSymmetricObjectPropertyAxiom.class, 1);
expectedCountMap.put(ElkAsymmetricObjectPropertyAxiom.class, 1);
expectedCountMap.put(ElkReflexiveObjectPropertyAxiom.class, 1);
expectedCountMap.put(ElkIrreflexiveObjectPropertyAxiom.class, 1);
expectedCountMap.put(ElkFunctionalObjectPropertyAxiom.class, 1);
expectedCountMap.put(ElkIrreflexiveObjectPropertyAxiom.class, 1);
expectedCountMap.put(ElkInverseFunctionalObjectPropertyAxiom.class, 1);
expectedCountMap.put(ElkTransitiveObjectPropertyAxiom.class, 1);
expectedCountMap.put(ElkFunctionalDataPropertyAxiom.class, 1);
expectedCountMap.put(ElkHasKeyAxiom.class, 1);
expectedCountMap.put(ElkDatatypeDefinitionAxiom.class, 3);
expectedCountMap.put(ElkClassAssertionAxiom.class, 9);
expectedCountMap.put(ElkObjectPropertyAssertionAxiom.class, 1);
expectedCountMap.put(ElkNegativeObjectPropertyAssertionAxiom.class, 2);
expectedCountMap.put(ElkDataPropertyAssertionAxiom.class, 1);
expectedCountMap.put(ElkNegativeDataPropertyAssertionAxiom.class, 1);
expectedCountMap.put(ElkSameIndividualAxiom.class, 3);
expectedCountMap.put(ElkDifferentIndividualsAxiom.class, 1);
expectedCountMap.put(ElkDeclarationAxiom.class, 43);
expectedCountMap.put(ElkSWRLRule.class, 3);
checkAxiomTypeCounts(counter, expectedCountMap, false);
assertEquals(111L, counter.getTotalAxiomCount());
}
@Test
public void testComments() throws Owl2ParseException {
String testString = "#comment at the beginning\r"
+ "Prefix #comments are allowed here\n"
+ "(#and here\r :#and here\n = #and here\r"
+ "<http://www.example.org#>#the last # in <> is not a comment\n"
+ " )#comment after axiom\n"
+ "Prefix(rdfs:#comment\n#commbent\r=#comment#\n"
+ "<http://www.w3.org/2000/01/rdf-schema#>#comment\n)"
+ "Ontology(#comment\n <http://www.my.example.com/example># comment \n"
+ "Declaration(#comment\n Class#comment\n(##\n#\n :Person ) ) \n"
+ "AnnotationAssertion( rdfs:comment :Person\n"
+ "\"Represents the set of#not a comment\n"
+ "all \\\"people#not a comment\\\".\"#comment\r)\n"
+ "# This is a comment \n"
+ "SubClassOf( :Person # another comment: #this doesn't count: SubClassOf( :Person\n"
+ ":Human) #This is another comment\n"
+ ")# comment at the end";
parseOntology(testString);
}
@Test(expected = Owl2ParseException.class)
public void testPrefixDeclarations() throws Owl2ParseException {
String testString = "Ontology( <http://www.my.example.com/example>"
+ "Declaration( Class( :Person ) )"
+ "SubClassOf( :Person owl:Thing )" + ") ";
parseOntology(testString);
fail("Should have thrown Owl2ParseException");
}
@Test
public void testObjectOneOf() throws Owl2ParseException {
String testString = "Ontology(SubClassOf( <A> ObjectOneOf(<i>)))";
parseOntology(testString);
}
@Test
public void testLiteralParsing() throws Owl2ParseException, IOException {
String input = "Prefix ( rdfs: = <http://www.w3.org/2000/01/rdf-schema#> )\n"
+ "Prefix ( a: = <http://www.example.org#> )\n"
+ "Prefix ( xsd: = <http://www.w3.org/2001/XMLSchema#> )\n"
+ "Ontology(<http://www.example.org/>\n"
// Testing if literal parsing is ambiguous
+ "Annotation(rdfs:comment \"String literal with language\"@en)\n"
+ "Annotation(rdfs:comment \"String literal no language\")\n"
+ "Annotation(rdfs:label \"Typed literal\"^^xsd:string)\n"
+ ")";
parseOntology(input);
}
/*
* Testing if DataSomeValuesFrom parsing could be ambiguous
*/
@Test
public void testNaryDataSomeValuesFrom() throws Owl2ParseException {
String input = "Prefix ( rdfs: = <http://www.w3.org/2000/01/rdf-schema#> )\n"
+ "Prefix ( a: = <http://www.example.org#> )\n"
+ "Prefix ( xsd: = <http://www.w3.org/2001/XMLSchema#> )\n"
+ "Ontology(<http://www.example.org/>\n"
+ "SubClassOf(a:2DFigure \n"
+ " DataSomeValuesFrom(a:hasWidth a:hasLength xsd:integer)\n"
+ ")\n"
+ "SubClassOf(a:2DFigure \n"
+ " DataAllValuesFrom(a:hasWidth a:hasLength xsd:integer)\n"
+ ")\n" + ")";
ElkTestAxiomProcessor counter = parseOntology(input);
List<ElkAxiom> axioms = counter
.getAxiomsForType(ElkSubClassOfAxiom.class);
assertEquals(2, axioms.size());
for (ElkAxiom axiom : axioms) {
ElkSubClassOfAxiom sbAxiom = (ElkSubClassOfAxiom) axiom;
assertTrue(sbAxiom.getSuperClassExpression() instanceof ElkDataPropertyListRestrictionQualifiedImpl);
ElkDataPropertyListRestrictionQualifiedImpl superCE = (ElkDataPropertyListRestrictionQualifiedImpl) sbAxiom
.getSuperClassExpression();
assertEquals(2, superCE.getDataPropertyExpressions().size());
}
}
@Test
public void testEmptyPrefix() throws Owl2ParseException {
String testString = "Prefix(:=<>)" + "Ontology("
+ "Declaration(Class(:A))" + ")";
parseOntology(testString);
}
@Test
public void testQualifiedNamesInIris() throws Owl2ParseException {
String testString = "Prefix(p: = <>)" + "Ontology("
+ "SubClassOf(p:Class p:Ontology)" + ")";
parseOntology(testString);
}
@Test
public void testSWRL() throws Owl2ParseException {
String testString = "Prefix(:=<www.example.org>) "
+ "Ontology(<http://www.example.org#swrl-rule-test> " + "DLSafeRule( "
+ "Body( " + "ClassAtom(:A Variable(:x)) " + ") " + "Head( "
+ "ClassAtom(:B Variable(:x) ) ) ) )";
parseOntology(testString);
}
}
|
live-ontologies/elk-reasoner
|
elk-owl-parent/elk-owl-implementation/src/test/java/org/semanticweb/elk/owl/parsing/AbstractOwl2FunctionalSyntaxParseTest.java
|
Java
|
apache-2.0
| 14,115 |
--
-- 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.
--
select min(part_dt) as min_part_dt, max(part_dt) as max_part_dt from KYLIN_SALES
|
apache/kylin
|
build/CI/kylin-system-testing/query/sql/sql/query65.sql
|
SQL
|
apache-2.0
| 886 |
/*
* Copyright 2013-2022 Real Logic 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
*
* https://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 uk.co.real_logic.sbe.ir;
import org.agrona.Verify;
import java.util.function.Supplier;
import static uk.co.real_logic.sbe.ir.Encoding.Presence.CONSTANT;
import static uk.co.real_logic.sbe.ir.Encoding.Presence.OPTIONAL;
/**
* Class to encapsulate a token of information for the message schema stream. This Intermediate Representation (IR)
* is intended to be language, schema, platform independent.
* <p>
* Processing and optimization could be run over a list of Tokens to perform various functions
* <ul>
* <li>re-ordering of fields based on encodedLength</li>
* <li>padding of fields in order to provide expansion room</li>
* <li>computing offsets of individual fields</li>
* <li>etc.</li>
* </ul>
* <p>
* IR could be used to generate code or other specifications. It should be possible to do the
* following:
* <ul>
* <li>generate a FIX/SBE schema from IR</li>
* <li>generate an ASN.1 spec from IR</li>
* <li>generate a GPB spec from IR</li>
* <li>etc.</li>
* </ul>
* <p>
* IR could be serialized to storage or network via code generated by SBE. Then read back in to
* a List of {@link Token}s.
* <p>
* The entire IR of an entity is a {@link java.util.List} of {@link Token} objects. The order of this list is very
* important. Encoding of fields is done by nodes pointing to specific encoding
* {@link uk.co.real_logic.sbe.PrimitiveType} objects. Each encoding node contains encodedLength, offset, byte order,
* and {@link Encoding}. Entities relevant to the encoding such as fields, messages, repeating groups, etc. are
* encapsulated in the list as nodes themselves. Although, they will in most cases never be serialized. The boundaries
* of these entities are delimited by BEGIN and END {@link Signal} values in the node {@link Encoding}.
* A list structure like this allows for each concatenation of encodings as well as easy traversal.
* <p>
* An example encoding of a message headerStructure might be like this.
* <ul>
* <li>Token 0 - Signal = BEGIN_MESSAGE, schemaId = 100</li>
* <li>Token 1 - Signal = BEGIN_FIELD, schemaId = 25</li>
* <li>Token 2 - Signal = ENCODING, PrimitiveType = uint32, encodedLength = 4, offset = 0</li>
* <li>Token 3 - Signal = END_FIELD</li>
* <li>Token 4 - Signal = END_MESSAGE</li>
* </ul>
*/
public class Token
{
/**
* Invalid ID value.
*/
public static final int INVALID_ID = -1;
/**
* Length not determined
*/
public static final int VARIABLE_LENGTH = -1;
private final Signal signal;
private final String name;
private final String referencedName;
private final String description;
private final int id;
private final int version;
private final int deprecated;
private int encodedLength;
private final int offset;
private int componentTokenCount;
private final Encoding encoding;
/**
* Construct an {@link Token} by providing values for all fields.
*
* @param signal for the token role.
* @param name of the token in the message.
* @param referencedName of the type when created from a ref in a composite.
* @param description of what the token is for.
* @param id as the identifier in the message declaration.
* @param version application within the template.
* @param deprecated as of this version.
* @param encodedLength of the component part.
* @param offset in the underlying message as octets.
* @param componentTokenCount number of tokens in this component.
* @param encoding of the primitive field.
*/
public Token(
final Signal signal,
final String name,
final String referencedName,
final String description,
final int id,
final int version,
final int deprecated,
final int encodedLength,
final int offset,
final int componentTokenCount,
final Encoding encoding)
{
Verify.notNull(signal, "signal");
Verify.notNull(name, "name");
Verify.notNull(encoding, "encoding");
this.signal = signal;
this.name = name;
this.referencedName = referencedName;
this.description = description;
this.id = id;
this.version = version;
this.deprecated = deprecated;
this.encodedLength = encodedLength;
this.offset = offset;
this.componentTokenCount = componentTokenCount;
this.encoding = encoding;
}
/**
* Signal the role of this token.
*
* @return the {@link Signal} for the token.
*/
public Signal signal()
{
return signal;
}
/**
* Return the name of the token
*
* @return name of the token
*/
public String name()
{
return name;
}
/**
* Get the name of the type when this is from a reference.
*
* @return the name of the type when this is from a reference.
*/
public String referencedName()
{
return referencedName;
}
/**
* Description for what the token is to be used for.
*
* @return description for what the token is to be used for.
*/
public String description()
{
return description;
}
/**
* Return the ID of the token assigned by the specification
*
* @return ID of the token assigned by the specification
*/
public int id()
{
return id;
}
/**
* The version context for this token. This is the schema version in which the type was introduced.
*
* @return version for this type.
*/
public int version()
{
return version;
}
/**
* The version in which this context was deprecated.
*
* @return the version in which this context was deprecated.
*/
public int deprecated()
{
return deprecated;
}
/**
* Get the name of the type that should be applied in context.
*
* @return the name of the type that should be applied in context.
*/
public String applicableTypeName()
{
return null == referencedName ? name : referencedName;
}
/**
* The encodedLength of this token in bytes.
*
* @return the encodedLength of this node. A value of 0 means the node has no encodedLength when encoded.
* A value of {@link Token#VARIABLE_LENGTH} means this node represents a variable length field.
*/
public int encodedLength()
{
return encodedLength;
}
/**
* Set the encoded length for this node. See {@link #encodedLength()}.
*
* @param encodedLength that is overriding existing value.
*/
public void encodedLength(final int encodedLength)
{
this.encodedLength = encodedLength;
}
/**
* The number of encoded primitives in this type.
*
* @return number of encoded primitives in this type.
*/
public int arrayLength()
{
if (null == encoding.primitiveType() || 0 == encodedLength)
{
return 0;
}
return encodedLength / encoding.primitiveType().size();
}
/**
* Match which approach to take based on the length of the token. If length is zero then an empty
* {@link String} is returned.
*
* @param one to be used when length is one.
* @param many to be used when length is greater than one.
* @return the {@link CharSequence} representing the token depending on the length.
*/
public CharSequence matchOnLength(final Supplier<CharSequence> one, final Supplier<CharSequence> many)
{
final int arrayLength = arrayLength();
if (arrayLength == 1)
{
return one.get();
}
else if (arrayLength > 1)
{
return many.get();
}
return "";
}
/**
* The offset for this token in the message.
*
* @return the offset of this Token. A value of 0 means the node has no relevant offset. A value of
* {@link Token#VARIABLE_LENGTH} means this node's true offset is dependent on variable length
* fields ahead of it in the encoding.
*/
public int offset()
{
return offset;
}
/**
* The number of tokens that make up this component.
*
* @return the number of tokens that make up this component.
*/
public int componentTokenCount()
{
return componentTokenCount;
}
/**
* Set the number of tokens this component has.
*
* @param componentTokenCount the number of tokens this component has.
*/
public void componentTokenCount(final int componentTokenCount)
{
this.componentTokenCount = componentTokenCount;
}
/**
* Return the {@link Encoding} of the {@link Token}.
*
* @return encoding of the {@link Token}
*/
public Encoding encoding()
{
return encoding;
}
/**
* Is the encoding presence is a constant or not?
*
* @return true if the encoding presence is a constant or false if not.
*/
public boolean isConstantEncoding()
{
return encoding.presence() == CONSTANT;
}
/**
* Is the encoding presence is optional or not?
*
* @return true if the encoding presence is optional or false if not.
*/
public boolean isOptionalEncoding()
{
return encoding.presence() == OPTIONAL;
}
/**
* {@inheritDoc}
*/
public String toString()
{
return "Token{" +
"signal=" + signal +
", name='" + name + '\'' +
", referencedName='" + referencedName + '\'' +
", description='" + description + '\'' +
", id=" + id +
", version=" + version +
", deprecated=" + deprecated +
", encodedLength=" + encodedLength +
", offset=" + offset +
", componentTokenCount=" + componentTokenCount +
", encoding=" + encoding +
'}';
}
/**
* Builder for {@link Token} which can simplify construction.
*/
public static class Builder
{
private Signal signal;
private String name;
private String referencedName;
private String description;
private int id = INVALID_ID;
private int version = 0;
private int deprecated = 0;
private int size = 0;
private int offset = 0;
private int componentTokenCount = 1;
private Encoding encoding = new Encoding();
/**
* Signal for the Token.
*
* @param signal for the Token.
* @return this for a fluent API.
*/
public Builder signal(final Signal signal)
{
this.signal = signal;
return this;
}
/**
* Name for the Token.
*
* @param name for the Token.
* @return this for a fluent API.
*/
public Builder name(final String name)
{
this.name = name;
return this;
}
/**
* Referenced type name for the Token.
*
* @param referencedName for the Token.
* @return this for a fluent API.
*/
public Builder referencedName(final String referencedName)
{
this.referencedName = referencedName;
return this;
}
/**
* Description attribute for the Token.
*
* @param description for the Token.
* @return this for a fluent API.
*/
public Builder description(final String description)
{
this.description = description;
return this;
}
/**
* ID attribute for the Token.
*
* @param id for the Token.
* @return this for a fluent API.
*/
public Builder id(final int id)
{
this.id = id;
return this;
}
/**
* Version attribute value for the Token.
*
* @param version for the Token.
* @return this for a fluent API.
*/
public Builder version(final int version)
{
this.version = version;
return this;
}
/**
* Deprecated version attribute for the Token.
*
* @param deprecated version for the Token.
* @return this for a fluent API.
*/
public Builder deprecated(final int deprecated)
{
this.deprecated = deprecated;
return this;
}
/**
* Size of the type for the Token.
*
* @param size for the Token.
* @return this for a fluent API.
*/
public Builder size(final int size)
{
this.size = size;
return this;
}
/**
* Offset in the message for the Token.
*
* @param offset for the Token.
* @return this for a fluent API.
*/
public Builder offset(final int offset)
{
this.offset = offset;
return this;
}
/**
* Count of tokens in the component.
*
* @param componentTokenCount for the component.
* @return this for a fluent API.
*/
public Builder componentTokenCount(final int componentTokenCount)
{
this.componentTokenCount = componentTokenCount;
return this;
}
/**
* Encoding type for the Token.
*
* @param encoding for the Token.
* @return this for a fluent API.
*/
public Builder encoding(final Encoding encoding)
{
this.encoding = encoding;
return this;
}
/**
* Build a new Token based on the values.
*
* @return a new Token based on the values.
*/
public Token build()
{
return new Token(
signal,
name,
referencedName,
description,
id,
version,
deprecated,
size,
offset,
componentTokenCount,
encoding);
}
}
}
|
PKRoma/simple-binary-encoding
|
sbe-tool/src/main/java/uk/co/real_logic/sbe/ir/Token.java
|
Java
|
apache-2.0
| 15,107 |
// Copyright 2022 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ServiceDirectory.V1Beta1.Snippets
{
// [START servicedirectory_v1beta1_generated_RegistrationService_DeleteNamespace_async_flattened]
using Google.Cloud.ServiceDirectory.V1Beta1;
using System.Threading.Tasks;
public sealed partial class GeneratedRegistrationServiceClientSnippets
{
/// <summary>Snippet for DeleteNamespaceAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task DeleteNamespaceAsync()
{
// Create client
RegistrationServiceClient registrationServiceClient = await RegistrationServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/namespaces/[NAMESPACE]";
// Make the request
await registrationServiceClient.DeleteNamespaceAsync(name);
}
}
// [END servicedirectory_v1beta1_generated_RegistrationService_DeleteNamespace_async_flattened]
}
|
googleapis/google-cloud-dotnet
|
apis/Google.Cloud.ServiceDirectory.V1Beta1/Google.Cloud.ServiceDirectory.V1Beta1.GeneratedSnippets/RegistrationServiceClient.DeleteNamespaceAsyncSnippet.g.cs
|
C#
|
apache-2.0
| 1,778 |
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClientService } from '../shared/http-module/http.service';
import { BoardModel } from './../models/board.model';
@Injectable()
export class BoardService {
constructor(private http: HttpClientService) { }
/**
* Usage: this is used to get the board API url from spacetemplate response
* @param spaceTemplateApiUrl
*/
getBoardApiUrl(spaceTemplateApiUrl: string) {
return this.http.get<{ data: any }>(spaceTemplateApiUrl)
.pipe(
map(resp => resp.data),
map(template => template.relationships.workitemboards.links.related)
);
}
/**
* Usage: this is to get the list board for a sapce
* @param boardUrl
*/
getBoards(boardUrl: string): Observable<BoardModel> {
return this.http.get<{ data: any, included: any[] }>(boardUrl)
.pipe(
map(resp => {
return {
data: resp.data,
included: resp.included
};
})
);
}
}
|
fabric8io/fabric8-planner
|
src/app/services/board.service.ts
|
TypeScript
|
apache-2.0
| 1,074 |
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
package Example2
import (
flatbuffers "github.com/google/flatbuffers/go"
)
type MonsterT struct {
}
func (t *MonsterT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
if t == nil { return 0 }
MonsterStart(builder)
return MonsterEnd(builder)
}
func (rcv *Monster) UnPackTo(t *MonsterT) {
}
func (rcv *Monster) UnPack() *MonsterT {
if rcv == nil { return nil }
t := &MonsterT{}
rcv.UnPackTo(t)
return t
}
type Monster struct {
_tab flatbuffers.Table
}
func GetRootAsMonster(buf []byte, offset flatbuffers.UOffsetT) *Monster {
n := flatbuffers.GetUOffsetT(buf[offset:])
x := &Monster{}
x.Init(buf, n+offset)
return x
}
func (rcv *Monster) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i
}
func (rcv *Monster) Table() flatbuffers.Table {
return rcv._tab
}
func MonsterStart(builder *flatbuffers.Builder) {
builder.StartObject(0)
}
func MonsterEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}
|
pjulien/flatbuffers
|
tests/MyGame/Example2/Monster.go
|
GO
|
apache-2.0
| 1,057 |
/* Copyright 2005-2015 Alfresco Software, Ltd.
*
* 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.
*/
'use strict';
flowableAdminApp.controller('CmmnTaskController', ['$scope', '$rootScope', '$http', '$timeout','$location','$routeParams', '$modal', '$translate', '$q', 'gridConstants',
function ($scope, $rootScope, $http, $timeout, $location, $routeParams, $modal, $translate, $q, gridConstants) {
$rootScope.navigation = {main: 'cmmn-engine', sub: 'tasks'};
$scope.tabData = {
tabs: [
{id: 'subTasks', name: 'TASK.TITLE.SUBTASKS'},
{id: 'variables', name: 'TASK.TITLE.VARIABLES'},
{id: 'identityLinks', name: 'TASK.TITLE.IDENTITY-LINKS'}
],
};
$scope.tabData.activeTab = $scope.tabData.tabs[0].id;
$scope.returnToList = function() {
$location.path("/tasks");
};
$scope.openTask = function(taskId) {
if (taskId) {
$location.path("/task/" + taskId);
}
};
$scope.openCaseInstance = function(caseInstanceId) {
if (caseInstanceId) {
$location.path("/case-instance/" + caseInstanceId);
}
};
$scope.openCaseDefinition = function(caseDefinitionId) {
if (caseDefinitionId) {
$location.path("/case-definition/" + caseDefinitionId);
}
};
$scope.loadTask = function() {
$scope.task = undefined;
// Load task
$http({method: 'GET', url: '/app/rest/admin/cmmn-tasks/' + $routeParams.taskId}).
success(function(data, status, headers, config) {
$scope.task = data;
if(data) {
$scope.taskCompleted = data.endTime != undefined;
$scope.taskPartOfCase = data.caseInstanceId != undefined;
}
// Load runtime-task, if available, for accurate delegation-state
$scope.loadRuntimeTask();
// Start loading children
$scope.loadSubTasks();
$scope.loadVariables();
$scope.loadIdentityLinks();
}).
error(function(data, status, headers, config) {
if (data && data.message) {
// Extract error-message
$rootScope.addAlert(data.message, 'error');
} else {
// Use default error-message
$rootScope.addAlert($translate.instant('ALERT.GENERAL.HTTP-ERROR'), 'error');
}
});
};
$scope.loadRuntimeTask = function() {
if($scope.task && !$scope.taskCompleted) {
// Load runtime task, if available to fetch delegation state
$http({method: 'GET', url: '/app/rest/admin/cmmn-tasks/' + $routeParams.taskId,
params: {runtime: 'true'}}).
success(function(data, status, headers, config) {
// Workaround for pre 5.15 installs, historic assignee is not updated when set to null
$scope.task.assignee = data.assignee;
if(data.delegationState) {
$scope.task.delegationState = data.delegationState;
} else {
// Use empty string to trigger delegate-button to show when delegationState is loaded
$scope.task.delegationState = '';
}
$scope.task.delegationStateLoaded = true;
});
}
};
$scope.subTaskSelected = function(task) {
if(task && task.getProperty('id')) {
$scope.openTask(task.getProperty('id'));
}
};
// Config for subtasks grid
$q.all([$translate('TASKS.HEADER.ID'),
$translate('TASKS.HEADER.NAME'),
$translate('TASKS.HEADER.ASSIGNEE'),
$translate('TASKS.HEADER.OWNER')])
.then(function(headers) {
$scope.subTaskGridDefinitions = {
data: 'subTasks.data',
enableRowReordering: false,
multiSelect: false,
keepLastSelected : false,
enableSorting: false,
rowHeight: 36,
afterSelectionChange: $scope.subTaskSelected,
columnDefs: [
{ field: 'id', displayName: headers[0], width: 50, cellTemplate: gridConstants.defaultTemplate},
{ field: 'name', displayName: headers[1], cellTemplate: gridConstants.defaultTemplate},
{ field: 'assignee', displayName: headers[2], width: 100, cellTemplate: gridConstants.defaultTemplate},
{ field: 'owner', displayName: headers[3], width: 100, cellTemplate: gridConstants.defaultTemplate}
]
};
});
$q.all([$translate('VARIABLES.HEADER.NAME'),
$translate('VARIABLES.HEADER.TYPE'),
$translate('VARIABLES.HEADER.VALUE')])
.then(function(headers) {
var variableValueTemplate = '<div><div class="ngCellText">{{row.getProperty("variable.valueUrl") && "(Binary)" || row.getProperty(col.field)}}</div></div>';
var variableTypeTemplate = '<div><div class="ngCellText">{{row.getProperty(col.field) && row.getProperty(col.field) || "null"}}</div></div>';
// Config for variable grid
$scope.variableGridDefinitions = {
data: 'variables.data',
enableRowReordering: false,
multiSelect: false,
keepLastSelected : false,
enableSorting: false,
rowHeight: 36,
columnDefs: [
{ field: 'variable.name', displayName: headers[0]},
{ field: 'variable.type', displayName: headers[1], cellTemplate: variableTypeTemplate},
{ field: 'variable.value', displayName: headers[2], cellTemplate: variableValueTemplate}
]
};
});
$q.all([$translate('IDENTITY-LINKS.HEADER.TYPE'),
$translate('IDENTITY-LINKS.HEADER.GROUP-ID'),
$translate('IDENTITY-LINKS.HEADER.USER-ID')])
.then(function(headers) {
// Config for variable grid
$scope.identityLinkGridDefinitions = {
data: 'identityLinks.data',
enableRowReordering: false,
multiSelect: false,
keepLastSelected : false,
enableSorting: false,
rowHeight: 36,
columnDefs: [
{ field: 'type', displayName: headers[0]},
{ field: 'groupId', displayName: headers[1], cellTemplate: gridConstants.defaultTemplate},
{ field: 'userId', displayName: headers[2], cellTemplate: gridConstants.defaultTemplate}
]
};
});
$scope.showAllSubtasks = function() {
// Populate the task-filter with parentId
$rootScope.filters.forced.cmmnTaskFilter = {
parentTaskId: $scope.task.id
};
$scope.returnToList();
};
$scope.loadSubTasks = function() {
$scope.subTasks = undefined;
$http({method: 'GET', url: '/app/rest/admin/cmmn-tasks/' + $scope.task.id +'/subtasks'}).
success(function(data, status, headers, config) {
$scope.subTasks = data;
$scope.tabData.tabs[0].info = data.total;
});
};
$scope.loadVariables = function() {
$scope.variables = undefined;
$http({method: 'GET', url: '/app/rest/admin/cmmn-tasks/' + $scope.task.id +'/variables'}).
success(function(data, status, headers, config) {
$scope.variables = data;
$scope.tabData.tabs[1].info = data.total;
});
};
$scope.loadIdentityLinks = function() {
$scope.identityLinks = undefined;
$http({method: 'GET', url: '/app/rest/admin/cmmn-tasks/' + $scope.task.id +'/identitylinks'}).
success(function(data, status, headers, config) {
$scope.identityLinks = {data: data, size: data.length};
$scope.tabData.tabs[2].info = data.length;
});
};
$scope.showTaskForm = function() {
if($scope.task.endTime) {
$http({method: 'GET', url: '/app/rest/admin/task-form-instance/' + $scope.task.id}).
success(function(data, status, headers, config) {
$rootScope.submittedForm = data.data[0]; // saving fetched submitted form in root scope to avoid another fetch in submitted form controller
$location.path("/form-instance/" + data.data[0].id);
});
}
};
// Initial load of task
$scope.executeWhenReady(function() {
$scope.loadTask();
});
// Dialogs
var resolve = {
// Reference the current task
task: function () {
return $scope.task;
}
};
$scope.deleteTask = function() {
var modalInstance = $modal.open({
templateUrl: 'views/task-delete-popup.html',
controller: 'CmmnDeleteTaskModalInstanceCtrl',
resolve: resolve
});
modalInstance.result.then(function (deleteTask) {
if(deleteTask) {
$scope.addAlert($translate.instant('ALERT.TASK.DELETED', $scope.task), 'info');
$scope.returnToList();
}
});
};
$scope.completeTask = function() {
var modalInstance = $modal.open({
templateUrl: 'views/task-complete-popup.html',
controller: 'CmmnCompleteModalInstanceCtrl',
resolve: resolve
});
modalInstance.result.then(function (completeTask) {
if(completeTask) {
$scope.addAlert($translate.instant('ALERT.TASK.COMPLETED', $scope.task), 'info');
$scope.loadTask();
}
});
};
$scope.delegateTask = function() {
var modalInstance = $modal.open({
templateUrl: 'views/task-delegate-popup.html',
controller: 'CmmnDelegateModalInstanceCtrl',
resolve: resolve
});
modalInstance.result.then(function (user) {
if(user) {
$scope.addAlert($translate.instant('ALERT.TASK.DELEGATED', {id: $scope.task.id, user: user}), 'info');
$scope.loadTask();
}
});
};
$scope.resolveTask = function() {
var modalInstance = $modal.open({
templateUrl: 'views/task-resolve-popup.html',
controller: 'CmmnResolveTaskModalInstanceCtrl',
resolve: resolve
});
modalInstance.result.then(function (user) {
if(user) {
$scope.addAlert($translate.instant('ALERT.TASK.RESOLVED', $scope.task), 'info');
$scope.loadTask();
}
});
};
$scope.assignTask = function() {
var modalInstance = $modal.open({
templateUrl: 'views/task-assign-popup.html',
controller: 'CmmnAssignModalInstanceCtrl',
resolve: resolve
});
modalInstance.result.then(function (user) {
if(user !== undefined) {
if(user == '') {
$scope.addAlert($translate.instant('ALERT.TASK.UNASSIGNED', $scope.task), 'info');
} else {
$scope.addAlert($translate.instant('ALERT.TASK.ASSIGNED', {id: $scope.task.id, user: user}), 'info');
}
$scope.loadTask();
}
});
};
$scope.editTask = function() {
var modalInstance = $modal.open({
templateUrl: 'views/task-edit-popup.html',
controller: 'CmmnEditTaskModalInstanceCtrl',
resolve: resolve
});
modalInstance.result.then(function (taskUpdated) {
if(taskUpdated) {
$scope.addAlert($translate.instant('ALERT.TASK.UPDATED', $scope.task), 'info');
$scope.loadTask();
}
});
};
}]);
// Popup controllers
flowableAdminApp.controller('CmmnCompleteModalInstanceCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'task', function ($rootScope, $scope, $modalInstance, $http, task) {
$scope.task = task;
$scope.status = {loading: false};
$scope.ok = function () {
$scope.status.loading = true;
$http({method: 'POST', url: '/app/rest/admin/cmmn-tasks/' + $scope.task.id, data: {action: 'complete'}}).
success(function(data, status, headers, config) {
$modalInstance.close(true);
$scope.status.loading = false;
}).error(function(data, status, headers, config) {
$modalInstance.close(false);
$scope.status.loading = false;
});
};
$scope.cancel = function () {
if(!$scope.status.loading) {
$modalInstance.dismiss('cancel');
}
};
}]);
flowableAdminApp.controller('CmmnResolveTaskModalInstanceCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'task', function ($rootScope, $scope, $modalInstance, $http, task) {
$scope.task = task;
$scope.status = {loading: false};
$scope.ok = function () {
$scope.status.loading = true;
$http({method: 'POST', url: '/app/rest/admin/cmmn-tasks/' + $scope.task.id, data: {action: 'resolve'}}).
success(function(data, status, headers, config) {
$modalInstance.close(true);
$scope.status.loading = false;
}).error(function(data, status, headers, config) {
$modalInstance.close(false);
$scope.status.loading = false;
});
};
$scope.cancel = function () {
if(!$scope.status.loading) {
$modalInstance.dismiss('cancel');
}
};
}]);
flowableAdminApp.controller('CmmnDeleteTaskModalInstanceCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'task', function ($rootScope, $scope, $modalInstance, $http, task) {
$scope.task = task;
$scope.status = {loading: false};
$scope.ok = function () {
$scope.status.loading = true;
$http({method: 'DELETE', url: '/app/rest/admin/cmmn-tasks/' + $scope.task.id}).
success(function(data, status, headers, config) {
$modalInstance.close(true);
$scope.status.loading = false;
}).
error(function(data, status, headers, config) {
$modalInstance.close(false);
$scope.status.loading = false;
});
};
$scope.cancel = function () {
if(!$scope.status.loading) {
$modalInstance.dismiss('cancel');
}
};
}]);
flowableAdminApp.controller('CmmnDelegateModalInstanceCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'task', function ($rootScope, $scope, $modalInstance, $http, task) {
$scope.task = task;
$scope.status = {loading: false};
$scope.ok = function () {
$scope.status.loading = true;
$http({method: 'POST', url: '/app/rest/admin/cmmn-tasks/' + $scope.task.id, data: {action: 'delegate', assignee: $scope.status.user}}).
success(function(data, status, headers, config) {
if ($scope.newAssignee && $scope.newAssignee.name) {
$modalInstance.close($scope.newAssignee.name);
} else {
$modalInstance.close($scope.status.user);
}
$scope.status.loading = false;
}).error(function(data, status, headers, config) {
$modalInstance.close(false);
$scope.status.loading = false;
});
};
$scope.cancel = function () {
if(!$scope.status.loading) {
$modalInstance.dismiss('cancel');
}
};
}]);
flowableAdminApp.controller('CmmnAssignModalInstanceCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'task', function ($rootScope, $scope, $modalInstance, $http, task) {
$scope.task = task;
$scope.status = {loading: false};
$scope.ok = function () {
$scope.status.loading = true;
var rawUserValue = $scope.status.user;
var resultUserValue = $scope.status.user;
if(!$scope.status.user) {
rawUserValue = null;
resultUserValue = '';
} else if ($scope.newAssignee && $scope.newAssignee.name) {
resultUserValue = $scope.newAssignee.name;
}
$http({method: 'PUT', url: '/app/rest/admin/cmmn-tasks/' + $scope.task.id, data: {assignee: rawUserValue}}).
success(function(data, status, headers, config) {
$modalInstance.close(resultUserValue);
$scope.status.loading = false;
}).error(function(data, status, headers, config) {
$modalInstance.close(false);
$scope.status.loading = false;
});
};
$scope.cancel = function () {
if(!$scope.status.loading) {
$modalInstance.dismiss('cancel');
}
};
}]);
flowableAdminApp.controller('CmmnEditTaskModalInstanceCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'task', function ($rootScope, $scope, $modalInstance, $http, task) {
$scope.task = task;
$scope.model = {
name: task.name,
description: task.description,
owner: task.owner,
assignee: task.assignee,
dueDate: task.dueDate,
priority: task.priority,
category: task.category,
};
$scope.status = {loading: false};
$scope.ok = function () {
$scope.status.loading = true;
$http({method: 'PUT', url: '/app/rest/admin/cmmn-tasks/' + $scope.task.id, data: $scope.model}).
success(function(data, status, headers, config) {
$modalInstance.close(true);
$scope.status.loading = false;
}).error(function(data, status, headers, config) {
$modalInstance.close(false);
$scope.status.loading = false;
});
};
$scope.cancel = function () {
if(!$scope.status.loading) {
$modalInstance.dismiss('cancel');
}
};
}]);
|
lsmall/flowable-engine
|
modules/flowable-ui-admin/flowable-ui-admin-app/src/main/resources/static/scripts/cmmn-task-controllers.js
|
JavaScript
|
apache-2.0
| 16,799 |
import sdl, sdl_image, zlib
ports = [sdl, sdl_image, zlib]
|
slightperturbation/Cobalt
|
ext/emsdk_portable/emscripten/1.27.0/tools/ports/__init__.py
|
Python
|
apache-2.0
| 61 |
/**
* 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.actionitem;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.joda.time.DateTime;
import org.kuali.rice.core.api.delegation.DelegationType;
import org.kuali.rice.core.api.util.RiceConstants;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.KewApiServiceLocator;
import org.kuali.rice.kew.api.action.ActionItemContract;
import org.kuali.rice.kew.api.action.RecipientType;
import org.kuali.rice.kew.api.actionlist.DisplayParameters;
import org.kuali.rice.kew.api.doctype.DocumentTypePolicy;
import org.kuali.rice.kew.api.preferences.Preferences;
import org.kuali.rice.kew.api.util.CodeTranslator;
import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kim.api.group.Group;
import org.kuali.rice.kim.api.identity.principal.EntityNamePrincipalName;
import org.kuali.rice.kim.api.identity.principal.Principal;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator;
import org.kuali.rice.krad.exception.ValidationException;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
/**
* This is the model for action items. These are displayed as the action list as well. Mapped to ActionItemService.
* NOTE: This object contains denormalized fields that have been copied from related ActionRequestValue and DocumentRouteHeaderValue
* objects for performance reasons. These should be preserved and their related objects should not be added to the OJB
* mapping as we do not want them loaded for each ActionItem object.
*
* @author Kuali Rice Team ([email protected])
*
*/
@MappedSuperclass
public class ActionItemBase implements ActionItemContract, Serializable {
private static final long serialVersionUID = -1079562205125660151L;
@Id
@GeneratedValue(generator = "KREW_ACTN_ITM_S")
@PortableSequenceGenerator(name = "KREW_ACTN_ITM_S")
@Column(name = "ACTN_ITM_ID")
private String id;
@Column(name = "PRNCPL_ID")
private String principalId;
@Column(name = "ASND_DT")
private Timestamp dateAssigned;
@Column(name = "RQST_CD")
private String actionRequestCd;
@Column(name = "ACTN_RQST_ID")
private String actionRequestId;
@Column(name = "DOC_HDR_ID")
private String documentId;
@Column(name = "GRP_ID")
private String groupId;
@Column(name = "DOC_HDR_TTL")
private String docTitle;
@Column(name = "DOC_TYP_LBL")
private String docLabel;
@Column(name = "DOC_HDLR_URL")
private String docHandlerURL;
@Column(name = "DOC_TYP_NM")
private String docName;
@Column(name = "RSP_ID")
private String responsibilityId = "1";
@Column(name = "ROLE_NM")
private String roleName;
@Column(name = "DLGN_PRNCPL_ID")
private String delegatorPrincipalId;
@Column(name = "DLGN_GRP_ID")
private String delegatorGroupId;
@Column(name = "DLGN_TYP")
private String delegationType;
@Column(name = "RQST_LBL")
private String requestLabel;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.DETACH)
@JoinColumn(name = "DOC_HDR_ID", insertable = false, updatable = false)
private DocumentRouteHeaderValue routeHeader;
// used by Document Operations screen
@Transient
private String dateAssignedStringValue;
@Transient
private Timestamp lastApprovedDate;
@Transient
private Map<String, String> customActions = new HashMap<String, String>();
@Transient
private String rowStyleClass;
@Transient
private Integer actionListIndex;
@Transient
private String delegatorName = "";
@Transient
private String groupName = "";
@Transient
private DisplayParameters displayParameters;
@Transient
private boolean isInitialized = false;
@Transient
private DocumentRouteHeaderValue minimalRouteHeader;
@Transient
private boolean lastApprovedDateInitialized = false;
@Transient
private boolean delegatorNameInitialized = false;
@Transient
private boolean groupNameInitialized = false;
@Deprecated
@Override
public String getActionToTake() {
// deprecated, always return null (see the contract javadoc for more details)
return null;
}
@Deprecated
@Override
public String getDateAssignedString() {
// deprecated, always return null (see the contract javadoc for more details)
return null;
}
public String getDateAssignedStringValue() {
if (StringUtils.isBlank(dateAssignedStringValue)) {
return RiceConstants.getDefaultDateFormat().format(getDateAssigned());
}
return dateAssignedStringValue;
}
public void setDateAssignedStringValue(String dateAssignedStringValue) {
this.dateAssignedStringValue = dateAssignedStringValue;
}
@Override
public String getId() {
return id;
}
@Override
public String getPrincipalId() {
return principalId;
}
public Timestamp getDateAssigned() {
return dateAssigned;
}
@Override
public DateTime getDateTimeAssigned() {
return new DateTime(dateAssigned);
}
@Override
public String getActionRequestCd() {
return actionRequestCd;
}
@Override
public String getActionRequestId() {
return actionRequestId;
}
@Override
public String getDocumentId() {
return documentId;
}
@Override
public String getGroupId() {
return groupId;
}
@Override
public String getDocTitle() {
return docTitle;
}
@Override
public String getDocLabel() {
return docLabel;
}
@Override
public String getDocHandlerURL() {
return docHandlerURL;
}
@Override
public String getDocName() {
return docName;
}
@Override
public String getResponsibilityId() {
return responsibilityId;
}
@Override
public String getRoleName() {
return roleName;
}
@Override
public String getDelegatorPrincipalId() {
return delegatorPrincipalId;
}
@Override
public String getDelegatorGroupId() {
return delegatorGroupId;
}
@Override
public DelegationType getDelegationType() {
return DelegationType.fromCode(delegationType);
}
public String getRequestLabel() {
return this.requestLabel;
}
private Group getGroup(String groupId) {
if (StringUtils.isBlank(groupId)) {
return null;
}
return KimApiServiceLocator.getGroupService().getGroup(groupId);
}
public Group getGroup(){
return getGroup(groupId);
}
public String getRecipientTypeCode() {
String recipientTypeCode = RecipientType.PRINCIPAL.getCode();
if (getRoleName() != null) {
recipientTypeCode = RecipientType.ROLE.getCode();
}
if (getGroupId() != null) {
recipientTypeCode = RecipientType.GROUP.getCode();
}
return recipientTypeCode;
}
public String getActionRequestLabel() {
if (StringUtils.isNotBlank(getRequestLabel())) {
return getRequestLabel();
}
return CodeTranslator.getActionRequestLabel(getActionRequestCd());
}
public boolean isWorkgroupItem() {
return getGroupId() != null;
}
public Principal getPrincipal(){
return KimApiServiceLocator.getIdentityService().getPrincipal(principalId);
}
public void setResponsibilityId(String responsibilityId) {
this.responsibilityId = responsibilityId;
}
public void setDocName(String docName) {
this.docName = docName;
}
public void setActionRequestCd(String actionRequestCd) {
this.actionRequestCd = actionRequestCd;
}
public void setDateAssigned(Timestamp dateAssigned) {
this.dateAssigned = dateAssigned;
}
public void setPrincipalId(String principalId) {
this.principalId = principalId;
}
public void setDocumentId(String documentId) {
this.documentId = documentId;
}
public void setId(String id) {
this.id = id;
}
public void setActionRequestId(String actionRequestId) {
this.actionRequestId = actionRequestId;
}
public void setDocHandlerURL(String docHandlerURL) {
this.docHandlerURL = docHandlerURL;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public void setDocLabel(String docLabel) {
this.docLabel = docLabel;
}
public void setDocTitle(String docTitle) {
this.docTitle = docTitle;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setDelegatorPrincipalId(String delegatorPrincipalId) {
this.delegatorPrincipalId = delegatorPrincipalId;
}
public void setDelegatorGroupId(String delegatorGroupId) {
this.delegatorGroupId = delegatorGroupId;
}
public void setDelegationType(DelegationType delegationType) {
this.delegationType = delegationType == null ? null : delegationType.getCode();
}
public void setRequestLabel(String requestLabel) {
this.requestLabel = requestLabel;
}
@Deprecated
@Override
public Integer getActionItemIndex() {
// deprecated, always return null (see the contract javadoc for more details)
return null;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("id", id)
.append("principalId", principalId)
.append("dateAssigned", dateAssigned)
.append("actionRequestCd", actionRequestCd)
.append("actionRequestId", actionRequestId)
.append("documentId", documentId)
.append("groupId", groupId)
.append("docTitle", docTitle)
.append("docLabel", docLabel)
.append("docHandlerURL", docHandlerURL)
.append("docName", docName)
.append("responsibilityId", responsibilityId)
.append("roleName", roleName)
.append("delegatorPrincipalId", delegatorPrincipalId)
.append("delegatorGroupId", delegatorGroupId)
.append("delegationType", delegationType)
.toString();
}
public String getRouteHeaderRouteStatus() {
return getMinimalRouteHeader().getDocRouteStatus();
}
public String getRouteHeaderCombinedStatus() {
return getMinimalRouteHeader().getCombinedStatus();
}
public Timestamp getRouteHeaderCreateDate() {
return getMinimalRouteHeader().getCreateDate();
}
public String getRouteHeaderInitiatorName() {
return getMinimalRouteHeader().getInitiatorDisplayName();
}
public Timestamp getRouteHeaderApprovedDate() {
return getMinimalRouteHeader().getApprovedDate();
}
public String getRouteHeaderCurrentRouteLevelName() {
return getMinimalRouteHeader().getCurrentRouteLevelName();
}
public String getRouteHeaderInitiatorWorkflowId() {
return getMinimalRouteHeader().getInitiatorWorkflowId();
}
public Integer getActionListIndex() {
return actionListIndex;
}
public void setActionListIndex(Integer actionListIndex) {
this.actionListIndex = actionListIndex;
}
public Timestamp getLastApprovedDate() {
initializeLastApprovedDate();
return this.lastApprovedDate;
}
public Map<String, String> getCustomActions() {
return customActions;
}
public void setCustomActions(Map<String, String> customActions) {
this.customActions = customActions;
}
public String getRowStyleClass() {
return rowStyleClass;
}
public void setRowStyleClass(String rowStyleClass) {
this.rowStyleClass = rowStyleClass;
}
public String getDelegatorName() {
initializeDelegatorName();
return delegatorName;
}
public String getGroupName() {
initializeGroupName();
return groupName;
}
public void initialize(Preferences preferences) {
// always re-initialize row style class, just in case they changed a preference!
initializeRowStyleClass(preferences);
if (isInitialized) {
return;
}
if (KewApiConstants.PREFERENCES_YES_VAL.equals(preferences.getShowWorkgroupRequest())) {
initializeGroupName();
}
if (KewApiConstants.PREFERENCES_YES_VAL.equals(preferences.getShowDelegator())) {
initializeDelegatorName();
}
if (KewApiConstants.PREFERENCES_YES_VAL.equals(preferences.getShowDateApproved())) {
initializeLastApprovedDate();
}
isInitialized = true;
}
private void initializeRowStyleClass(Preferences preferences) {
//set background colors for document statuses
String docRouteStatus = getRouteHeaderRouteStatus();
if (KewApiConstants.ROUTE_HEADER_CANCEL_CD.equalsIgnoreCase(docRouteStatus)) {
setRowStyleClass(KewApiConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorCanceled()));
} else if (KewApiConstants.ROUTE_HEADER_DISAPPROVED_CD.equalsIgnoreCase(docRouteStatus)) {
setRowStyleClass(KewApiConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorDisapproved()));
} else if (KewApiConstants.ROUTE_HEADER_ENROUTE_CD.equalsIgnoreCase(docRouteStatus)) {
setRowStyleClass(KewApiConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorEnroute()));
} else if (KewApiConstants.ROUTE_HEADER_EXCEPTION_CD.equalsIgnoreCase(docRouteStatus)) {
setRowStyleClass(KewApiConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorException()));
} else if (KewApiConstants.ROUTE_HEADER_FINAL_CD.equalsIgnoreCase(docRouteStatus)) {
setRowStyleClass(KewApiConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorFinal()));
} else if (KewApiConstants.ROUTE_HEADER_INITIATED_CD.equalsIgnoreCase(docRouteStatus)) {
setRowStyleClass(KewApiConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorInitiated()));
} else if (KewApiConstants.ROUTE_HEADER_PROCESSED_CD.equalsIgnoreCase(docRouteStatus)) {
setRowStyleClass(KewApiConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorProcessed()));
} else if (KewApiConstants.ROUTE_HEADER_SAVED_CD.equalsIgnoreCase(docRouteStatus)) {
setRowStyleClass(KewApiConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorSaved()));
}
}
private void initializeGroupName() {
if (!groupNameInitialized) {
if (getGroupId() != null) {
Group group = this.getGroup();
groupName = group.getName();
}
groupNameInitialized = true;
}
}
private void initializeDelegatorName() {
if (!delegatorNameInitialized) {
if (getDelegatorPrincipalId() != null) {
EntityNamePrincipalName name = KimApiServiceLocator.getIdentityService().getDefaultNamesForPrincipalId(getDelegatorPrincipalId());
if (name != null) {
delegatorName = name.getDefaultName().getCompositeName();
}
}
if (getDelegatorGroupId() != null) {
Group delegatorGroup = KimApiServiceLocator.getGroupService().getGroup(getDelegatorGroupId());
if (delegatorGroup !=null)
delegatorName = delegatorGroup.getName();
}
delegatorNameInitialized = true;
}
}
private void initializeLastApprovedDate() {
if (!lastApprovedDateInitialized) {
lastApprovedDate = KEWServiceLocator.getActionTakenService().getLastApprovedDate(getDocumentId());
lastApprovedDateInitialized = true;
}
}
public DisplayParameters getDisplayParameters() {
return displayParameters;
}
public void setDisplayParameters(DisplayParameters displayParameters) {
this.displayParameters = displayParameters;
}
public DocumentRouteHeaderValue getRouteHeader() {
return routeHeader;
}
public void setRouteHeader(DocumentRouteHeaderValue routeHeader) {
this.routeHeader = routeHeader;
}
public DocumentRouteHeaderValue getMinimalRouteHeader() {
if ( minimalRouteHeader == null ) {
minimalRouteHeader = KEWServiceLocator.getActionListService().getMinimalRouteHeader(documentId);
}
return minimalRouteHeader;
}
protected <T extends ActionItemBase> T deepCopy(Map<Object, Object> visited, Class<T> type) {
if (visited.containsKey(this)) {
return (T)visited.get(this);
}
T copy = null;
try {
copy = type.newInstance();
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
visited.put(this, copy);
copy.setId(id);
copy.setPrincipalId(principalId);
if (dateAssigned != null) {
copy.setDateAssigned(new Timestamp(dateAssigned.getTime()));
}
copy.setActionRequestCd(actionRequestCd);
copy.setActionRequestId(actionRequestId);
copy.setDocumentId(documentId);
copy.setGroupId(groupId);
copy.setDocTitle(docTitle);
copy.setDocLabel(docLabel);
copy.setDocHandlerURL(docHandlerURL);
copy.setDocName(docName);
copy.setResponsibilityId(responsibilityId);
copy.setRoleName(roleName);
copy.setDelegatorPrincipalId(delegatorPrincipalId);
copy.setDelegatorGroupId(delegatorGroupId);
copy.setDelegationType(DelegationType.fromCode(delegationType));
copy.setRequestLabel(requestLabel);
copy.setDateAssignedStringValue(dateAssignedStringValue);
if (routeHeader != null) {
copy.setRouteHeader(routeHeader.deepCopy(visited));
}
return copy;
}
/**
* Called from ActionList.jsp to help determine the 'target' value when building the URL.
*
* @return the value from the DOC_SEARCH_TARGET policy if it exists for this document type
*/
public String getTarget() {
org.kuali.rice.kew.api.doctype.DocumentType documentType = KewApiServiceLocator.getDocumentTypeService().getDocumentTypeByName(this.docName);
Map<DocumentTypePolicy, String> policies = documentType.getPolicies();
for (DocumentTypePolicy policy : policies.keySet()) {
if (policy.getCode().equals(DocumentTypePolicy.DOC_SEARCH_TARGET.getCode())) {
return policies.get(DocumentTypePolicy.DOC_SEARCH_TARGET);
}
}
return null;
}
}
|
mztaylor/rice-git
|
rice-middleware/impl/src/main/java/org/kuali/rice/kew/actionitem/ActionItemBase.java
|
Java
|
apache-2.0
| 20,168 |
package net.gcdc.asn1.uper;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.gcdc.asn1.datatypes.Asn1Optional;
import net.gcdc.asn1.datatypes.HasExtensionMarker;
import net.gcdc.asn1.datatypes.IntRange;
import net.gcdc.asn1.datatypes.IsExtension;
import net.gcdc.asn1.datatypes.SizeRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** A "quick-and-dirty" implementation of ASN.1 encoder for UPER (Unaligned Packed Encoding Rules).
*
* @see ITU-T Recommendation <a
* href="http://www.itu.int/ITU-T/recommendations/rec.aspx?rec=x.691">X.691</a>
*
* TODO: Cover the rest of (useful) ASN.1 datatypes and PER-visible constraints,
* write unit tests for them. Clean-up, do more refactoring.
**/
public final class UperEncoder {
final static Logger logger = LoggerFactory.getLogger(UperEncoder.class);
private final static int NUM_16K = 16384;
@SuppressWarnings("unused")
private final static int NUM_32K = 32768;
@SuppressWarnings("unused")
private final static int NUM_48K = 49152;
@SuppressWarnings("unused")
private final static int NUM_64K = 65536;
private UperEncoder(){}
public static <T> byte[] encode(T obj)
throws IllegalArgumentException, UnsupportedOperationException {
try {
BitBuffer bitbuffer = ByteBitBuffer.createInfinite();
encode2(bitbuffer, obj, new Annotation[] {});
bitbuffer.flip();
byte[] result = Arrays.copyOf(bitbuffer.array(), (bitbuffer.limit() + 7) / 8);
return result;
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Can't encode " + obj.getClass().getName() + ": "
+ e, e);
} catch (Asn1EncodingException e) {
throw new IllegalArgumentException("Can't encode " + obj.getClass().getName() + ":"
+ e.getMessage(), e);
}
}
public static <T> T decode(byte[] bytes, Class<T> classOfT) throws IllegalArgumentException,
UnsupportedOperationException {
BitBuffer bitQueue = bitBufferFromBinaryString(binaryStringFromBytes(bytes));
T result = decode2(bitQueue, classOfT, new Annotation[] {});
if (bitQueue.remaining() > 7) {
throw new IllegalArgumentException("Can't fully decode "
+ classOfT.getName() + ", got (" + result.getClass().getName() + "): " + result
+ "; remaining " + bitQueue.remaining() + " bits: " + bitQueue);
}
return result;
}
static <T> void encode2(BitBuffer bitbuffer, T obj, Annotation[] extraAnnotations) throws Asn1EncodingException {
for (Encoder e : encoders) {
if (e.canEncode(obj, extraAnnotations)) {
e.encode(bitbuffer, obj, extraAnnotations);
return;
}
}
throw new IllegalArgumentException("Can't find encoder for " + obj.getClass().getName()
+ " with extra annotations " + Arrays.asList(extraAnnotations));
}
static <T> T decode2(BitBuffer bitbuffer, Class<T> classOfT, Annotation[] extraAnnotations) {
logger.debug("Decoding classOfT : {}", classOfT);
for (Decoder e : decoders) {
if (e.canDecode(classOfT, extraAnnotations)) {
return e.decode(bitbuffer, classOfT, extraAnnotations);
}
}
throw new IllegalArgumentException("Can't find decoder for " + classOfT.getName()
+ " with extra annotations " + Arrays.asList(extraAnnotations));
}
static IntRange newRange(
final long minValue,
final long maxValue,
final boolean hasExtensionMarker) {
return new IntRange() {
@Override public Class<? extends Annotation> annotationType() {
return IntRange.class;
}
@Override public long minValue() { return minValue; }
@Override public long maxValue() { return maxValue; }
@Override public boolean hasExtensionMarker() { return hasExtensionMarker; }
};
}
static IntRange intRangeFromSizeRange(SizeRange sizeRange) {
return newRange(sizeRange.minValue(), sizeRange.maxValue(), sizeRange.hasExtensionMarker());
}
private static List<Encoder> encoders = new ArrayList<>();
private static List<Decoder> decoders = new ArrayList<>();
static {
encoders.add(new IntCoder());
encoders.add(new BigIntCoder());
encoders.add(new ByteCoder());
encoders.add(new BooleanCoder());
encoders.add(new SequenceCoder());
encoders.add(new ChoiceCoder());
encoders.add(new EnumCoder());
encoders.add(new BitStringCoder());
encoders.add(new SeqOfCoder());
encoders.add(new StringCoder());
decoders.add(new IntCoder());
decoders.add(new BigIntCoder());
decoders.add(new ByteCoder());
decoders.add(new BooleanCoder());
decoders.add(new SequenceCoder());
decoders.add(new ChoiceCoder());
decoders.add(new EnumCoder());
decoders.add(new BitStringCoder());
decoders.add(new SeqOfCoder());
decoders.add(new StringCoder());
}
static <T> void encodeAsOpenType(
BitBuffer bitbuffer, T obj, Annotation[] extraAnnotations)
throws IllegalArgumentException, IllegalAccessException, Asn1EncodingException {
logger.debug("OPEN TYPE for {}. Encoding preceedes length determinant", obj.getClass()
.getName());
BitBuffer tmpbuffer = ByteBitBuffer.createInfinite();
encode2(tmpbuffer, obj, extraAnnotations);
int numBytes = (tmpbuffer.position() + 7) / 8;
logger.debug(
"Encoding open type length determinant ({}) for {} (will be inserted before the open type content)",
numBytes, obj.getClass().getName());
try {
encodeLengthDeterminant(bitbuffer, numBytes);
} catch (Asn1EncodingException e) {
throw new Asn1EncodingException(" length of open type ", e);
}
tmpbuffer.flip();
for (int i = 0; i < tmpbuffer.limit(); i++) {
bitbuffer.put(tmpbuffer.get());
}
}
static <T> T decodeAsOpenType(BitBuffer bitbuffer,
Class<T> classOfT,
Annotation[] extraAnnotations) {
logger.debug("OPEN TYPE for {}. Encoding preceedes length determinant",
classOfT != null ? classOfT.getName() : "null");
long numBytes = decodeLengthDeterminant(bitbuffer);
BitBuffer openTypeBitBuffer = ByteBitBuffer.allocate((int)numBytes * 8);
for (int i = 0; i < numBytes * 8; i++) {
openTypeBitBuffer.put(bitbuffer.get());
}
openTypeBitBuffer.flip();
if (classOfT != null) {
T result = decode2(openTypeBitBuffer, classOfT, extraAnnotations);
// Assert that padding bits are all 0.
logger.debug("open type had {} padding bits");
for (int i = 0; i < openTypeBitBuffer.remaining(); i++) {
boolean paddingBit = openTypeBitBuffer.get();
logger.debug("padding bit {} was <{}>", i, paddingBit ? "1" : "0");
if (paddingBit) { throw new IllegalArgumentException("non-zero padding bit " + i
+ " for open type " + classOfT.getName()); }
}
return result;
} else {
return null;
}
}
static <T> boolean hasNonNullExtensions(
T obj, Asn1ContainerFieldSorter sorter)
throws IllegalArgumentException, IllegalAccessException {
for (Field f : sorter.extensionFields) {
if (f.get(obj) != null) { return true; }
}
return false;
}
private static <T> Constructor<T> findConsturctor(Class<T> classOfT, Object... parameters) {
@SuppressWarnings("unchecked")
Constructor<T>[] declaredConstructors = (Constructor<T>[]) classOfT
.getDeclaredConstructors();
for (Constructor<T> c : declaredConstructors) {
Class<?>[] parameterTypes = c.getParameterTypes();
if (parameterTypes.length == parameters.length) {
boolean constructorIsOk = true;
for (int i = 0; i < parameters.length; i++) {
if (!parameterTypes[i].isAssignableFrom(parameters[i].getClass())) {
constructorIsOk = false;
break;
}
}
if (constructorIsOk) { return c; }
}
}
Class<?>[] parameterTypes = new Class<?>[parameters.length];
for (int i = 0; i < parameters.length; i++) {
parameterTypes[i] = parameters[i].getClass();
}
throw new IllegalArgumentException("Can't get the " + parameters.length +
"-argument constructor for parameter(s) "
+ Arrays.asList(parameters) +
" of type(s) " + Arrays.asList(parameterTypes) + " for class "
+ classOfT.getName() + " (" + classOfT.getClass().getName() + " or " + Arrays.asList(classOfT.getClasses()) + ")" +
", all constructors: " + Arrays.asList(classOfT.getDeclaredConstructors()));
}
/** Instantiate a given class T using given parameters. */
static <T> T instantiate(Class<T> classOfT, Object... parameters) {
Class<?>[] parameterTypes = new Class<?>[parameters.length];
for (int i = 0; i < parameters.length; i++) {
parameterTypes[i] = parameters[i].getClass();
}
Constructor<T> constructor = findConsturctor(classOfT, parameters);
boolean constructorIsAccessible = constructor.isAccessible();
constructor.setAccessible(true);
T result;
try {
result = constructor.newInstance(parameters);
} catch (IllegalArgumentException | InvocationTargetException | InstantiationException
| IllegalAccessException e) {
throw new IllegalArgumentException("Can't instantiate " + classOfT.getName(), e);
}
constructor.setAccessible(constructorIsAccessible);
return result;
}
static long decodeConstrainedInt(BitBuffer bitqueue, IntRange intRange) {
long lowerBound = intRange.minValue();
long upperBound = intRange.maxValue();
boolean hasExtensionMarker = intRange.hasExtensionMarker();
if (upperBound < lowerBound) {
throw new IllegalArgumentException("Lower bound "
+ lowerBound + " is larger that upper bound " + upperBound);
}
if (hasExtensionMarker) {
boolean extensionIsActive = bitqueue.get();
if (extensionIsActive) {
throw new UnsupportedOperationException(
"int extension are not supported yet");
}
}
final long range = upperBound - lowerBound + 1;
if (range == 1) {
return lowerBound;
}
int bitlength = BigInteger.valueOf(range - 1).bitLength();
logger.trace("This int will require {} bits, available {}", bitlength, bitqueue.remaining());
BitBuffer relevantBits = ByteBitBuffer.allocate( ((bitlength + 7) / 8) * 8); // Full bytes.
int numPaddingBits = (8 - (bitlength % 8)) % 8; // Leading padding 0-bits.
for (int i = 0; i < numPaddingBits; i++) {
relevantBits.put(false);
}
for (int i = 0; i < bitlength; i++) {
relevantBits.put(bitqueue.get());
}
relevantBits.flip();
final BigInteger big = new BigInteger(+1, relevantBits.array());
final long result = lowerBound + big.longValue();
logger.debug("bits {} decoded as {} plus lower bound {} give {}",
relevantBits.toBooleanStringFromPosition(0), big.longValue(), lowerBound, result);
if ((result < intRange.minValue() || intRange.maxValue() < result)
&& !intRange.hasExtensionMarker()) {
throw new AssertionError("Decoded value "
+ result + " is outside of range (" + intRange.minValue() + ".."
+ intRange.maxValue() + ")");
}
return result;
}
static boolean hasExtensionMarker(AnnotationStore annotations) {
return annotations.getAnnotation(HasExtensionMarker.class) != null;
}
private static boolean isExtension(Field f) {
return f.getAnnotation(IsExtension.class) != null;
}
static boolean isMandatory(Field f) {
return !isOptional(f);
}
static boolean isOptional(Field f) {
return f.getAnnotation(Asn1Optional.class) != null;
}
static class Asn1ContainerFieldSorter {
/** "Outside extension root" */
List<Field> extensionFields = new ArrayList<>();
/** "Within extension root" */
List<Field> ordinaryFields = new ArrayList<>();
List<Field> mandatoryOrdinaryFields = new ArrayList<>();
List<Field> optionalOrdinaryFields = new ArrayList<>();
List<Field> allFields = new ArrayList<>(); // Excluding test instrumentation.
Map<Field, Boolean> originalAccess = new HashMap<>();
Asn1ContainerFieldSorter(Class<?> type) {
for (Field f : type.getDeclaredFields()) {
if (isTestInstrumentation(f)) {
continue;
}
originalAccess.put(f, f.isAccessible());
f.setAccessible(true);
if (isExtension(f)) {
extensionFields.add(f);
}
else {
ordinaryFields.add(f);
}
allFields.add(f);
}
for (Field f : ordinaryFields) {
if (isMandatory(f)) {
mandatoryOrdinaryFields.add(f);
}
else {
optionalOrdinaryFields.add(f);
}
}
}
public void revertAccess() {
for (Entry<Field, Boolean> entry : originalAccess.entrySet()) {
entry.getKey().setAccessible(entry.getValue());
}
}
}
static boolean isTestInstrumentation(Field f) {
return f.getName().startsWith("$");
}
static void encodeLengthOfBitmask(BitBuffer bitbuffer, int n) throws Asn1EncodingException {
try {
if (n <= 64) {
logger.debug(
"normally small length of bitmask, length {} <= 64 indicated as bit <0>", n);
bitbuffer.put(false);
encodeConstrainedInt(bitbuffer, n, 1, 64);
return;
} else {
logger.debug(
"normally small length of bitmask, length {} > 64 indicated as bit <1>", n);
bitbuffer.put(true);
encodeLengthDeterminant(bitbuffer, n);
return;
}
} catch (Asn1EncodingException e) {
throw new Asn1EncodingException(" length of bitmask ", e);
}
}
static void encodeLengthDeterminant(BitBuffer bitbuffer, int n) throws Asn1EncodingException {
try {
int position = bitbuffer.position();
if (n < 128) {
bitbuffer.put(false);
encodeConstrainedInt(bitbuffer, n, 0, 127);
logger.debug("Length determinant {}, encoded as <{}>", n,
bitbuffer.toBooleanStringFromPosition(position));
if (bitbuffer.position() - position != 8) {
throw new AssertionError(
"length determinant encoded not as 8 bits");
}
return;
} else if (n < NUM_16K) {
bitbuffer.put(true);
bitbuffer.put(false);
encodeConstrainedInt(bitbuffer, n, 0, NUM_16K - 1);
logger.debug("Length determinant {}, encoded as 2bits+14bits: <{}>", n,
bitbuffer.toBooleanStringFromPosition(position));
if (bitbuffer.position() - position != 16) {
throw new AssertionError("length determinant encoded not as 16 bits");
}
return;
} else {
throw new UnsupportedOperationException(
"Length greater than 16K is not supported yet.");
}
} catch (Asn1EncodingException e) {
throw new Asn1EncodingException(" length determinant ", e);
}
}
static long decodeLengthOfBitmask(BitBuffer bitbuffer) {
logger.debug("decoding length of bitmask");
boolean isGreaterThan64 = bitbuffer.get();
logger.debug(
"length determinant extension preamble size flag: <{}> (preamble size {} 64)",
isGreaterThan64 ? "1" : "0", isGreaterThan64 ? ">" : "<=");
if (!isGreaterThan64) {
long result = decodeConstrainedInt(bitbuffer, newRange(1, 64, false));
logger.debug("normally small length of bitmask, length <= 64, decoded as {}",
result);
return result;
} else {
logger.debug("normally small length of bitmask, length > 64, decoding as ordinary length determinant...");
return decodeLengthDeterminant(bitbuffer);
}
}
static long decodeLengthDeterminant(BitBuffer bitbuffer) {
boolean bit8 = bitbuffer.get();
if (!bit8) { // then value is less than 128
long result = decodeConstrainedInt(bitbuffer, newRange(0, 127, false));
logger.debug("length determinant, decoded as {}", result);
return result;
} else {
boolean bit7 = bitbuffer.get();
if (!bit7) { // then value is less than 16K
long result = decodeConstrainedInt(bitbuffer, newRange(0, NUM_16K - 1, false));
logger.debug("length determinant, decoded as {}", result);
return result;
} else { // "Large" n
throw new UnsupportedOperationException(
"lengthes longer than 16K are not supported yet.");
}
}
}
static void encodeConstrainedInt(
final BitBuffer bitbuffer,
final long value,
final long lowerBound,
final long upperBound) throws Asn1EncodingException {
encodeConstrainedInt(bitbuffer, value, lowerBound, upperBound, false);
}
static void encodeConstrainedInt(
final BitBuffer bitbuffer,
final long value,
final long lowerBound,
final long upperBound,
final boolean hasExtensionMarker
) throws Asn1EncodingException {
if (upperBound < lowerBound) {
throw new IllegalArgumentException("Lower bound "
+ lowerBound + " is larger than upper bound " + upperBound);
}
if (!hasExtensionMarker && (value < lowerBound || value > upperBound)) {
throw new Asn1EncodingException(
" Value " + value + " is outside of fixed range " +
lowerBound + ".." + upperBound);
}
final long range = upperBound - lowerBound + 1;
final int position = bitbuffer.position();
if (hasExtensionMarker) {
boolean outsideOfRange = value < lowerBound || value > upperBound;
logger.debug("constrained int with extension marker, {} extension range",
outsideOfRange ? "outside" : "within", outsideOfRange ? "1" : "0");
bitbuffer.put(outsideOfRange);
if (outsideOfRange) {
throw new UnsupportedOperationException(
"INT extensions are not supported yet");
}
}
if (range == 1) {
logger.debug("constrained int of empty range, resulting in empty encoding <>");
return;
}
final BigInteger big = BigInteger.valueOf(value - lowerBound);
final int numPaddingBits = BigInteger.valueOf(range - 1).bitLength() - big.bitLength();
for (int i = 0; i < numPaddingBits; i++) {
bitbuffer.put(false);
}
for (int i = big.bitLength() - 1; i >= 0; i--) {
bitbuffer.put(big.testBit(i));
}
logger.debug("constrained int {} encoded as <{}>", value,
bitbuffer.toBooleanStringFromPosition(position));
return;
}
public static byte[] bytesFromCollection(List<Boolean> bitlist) {
int sizeBytes = (bitlist.size() + 7) / 8;
byte[] result = new byte[sizeBytes];
int byteId = 0;
byte bitId = 7;
for (Boolean b : bitlist) {
logger.trace("bitId: {}, byteId: {}, value: {}", bitId, byteId, b);
result[byteId] |= (b ? 1 : 0) << bitId;
bitId--;
if (bitId < 0) {
bitId = 7;
byteId++;
}
}
int nZeros = sizeBytes * 8 - bitlist.size();
String zeros = nZeros > 0 ? String.format("%0" + nZeros + "d", 0) : "";
logger.debug("Padding bits ({}): <{}>", nZeros, zeros);
return result;
}
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String hexStringFromBytes(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] bytesFromHexString(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
public static String binaryStringFromBytes(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
for (int i = 0; i < Byte.SIZE * bytes.length; i++)
sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
return sb.toString();
}
public static byte[] bytesFromBinaryString(String s) {
int len = s.length();
byte[] result = new byte[(len + Byte.SIZE - 1) / Byte.SIZE];
char c;
for (int i = 0; i < len; i++)
if ((c = s.charAt(i)) == '1') result[i / Byte.SIZE] = (byte) (result[i / Byte.SIZE] | (0x80 >>> (i % Byte.SIZE)));
else if (c != '0')
throw new IllegalArgumentException();
return result;
}
private static BitBuffer bitBufferFromBinaryString(String s) {
ByteBitBuffer result = ByteBitBuffer.allocate(s.length());
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != '1' && s.charAt(i) != '0') {
throw new IllegalArgumentException(
"bad character in 'binary' string " + s.charAt(i));
}
result.put(s.charAt(i) == '1');
}
result.flip();
return result;
}
}
|
RNDITS/geonetworking
|
asn1-uper/src/main/java/net/gcdc/asn1/uper/UperEncoder.java
|
Java
|
apache-2.0
| 23,895 |
/*
* 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.sysds.runtime.controlprogram;
import java.util.ArrayList;
import org.apache.sysds.api.DMLScript;
import org.apache.sysds.parser.IfStatementBlock;
import org.apache.sysds.common.Types.ValueType;
import org.apache.sysds.runtime.DMLRuntimeException;
import org.apache.sysds.runtime.DMLScriptException;
import org.apache.sysds.runtime.controlprogram.context.ExecutionContext;
import org.apache.sysds.runtime.instructions.Instruction;
import org.apache.sysds.runtime.instructions.cp.BooleanObject;
public class IfProgramBlock extends ProgramBlock
{
private ArrayList<Instruction> _predicate;
private ArrayList<ProgramBlock> _childBlocksIfBody;
private ArrayList<ProgramBlock> _childBlocksElseBody;
private int _lineagePathPos = -1;
public IfProgramBlock(Program prog, ArrayList<Instruction> predicate) {
super(prog);
_childBlocksIfBody = new ArrayList<>();
_childBlocksElseBody = new ArrayList<>();
_predicate = predicate;
}
public ArrayList<ProgramBlock> getChildBlocksIfBody() {
return getChildBlocks();
}
public void setChildBlocksIfBody(ArrayList<ProgramBlock> blocks) {
_childBlocksIfBody = blocks;
}
public void addProgramBlockIfBody(ProgramBlock pb) {
_childBlocksIfBody.add(pb);
}
public ArrayList<ProgramBlock> getChildBlocksElseBody() {
return _childBlocksElseBody;
}
public void setChildBlocksElseBody(ArrayList<ProgramBlock> blocks) {
_childBlocksElseBody = blocks;
}
public void addProgramBlockElseBody(ProgramBlock pb) {
_childBlocksElseBody.add(pb);
}
public ArrayList<Instruction> getPredicate(){
return _predicate;
}
public void setPredicate(ArrayList<Instruction> predicate) {
_predicate = predicate;
}
@Override
public ArrayList<ProgramBlock> getChildBlocks() {
return _childBlocksIfBody;
}
@Override
public boolean isNested() {
return true;
}
public void setLineageDedupPathPos(int pos) {
_lineagePathPos = pos;
}
@Override
public void execute(ExecutionContext ec)
{
BooleanObject predResult = executePredicate(ec);
if (DMLScript.LINEAGE_DEDUP)
ec.getLineage().setDedupPathBranch(_lineagePathPos, predResult.getBooleanValue());
//execute if statement
if(predResult.getBooleanValue()) {
try {
for (int i=0 ; i < _childBlocksIfBody.size() ; i++) {
_childBlocksIfBody.get(i).execute(ec);
}
}
catch(DMLScriptException e) {
throw e;
}
catch(Exception e) {
throw new DMLRuntimeException(this.printBlockErrorLocation() + "Error evaluating if statement body ", e);
}
}
else {
try {
for (int i=0 ; i < _childBlocksElseBody.size() ; i++) {
_childBlocksElseBody.get(i).execute(ec);
}
}
catch(DMLScriptException e) {
throw e;
}
catch(Exception e) {
throw new DMLRuntimeException(this.printBlockErrorLocation() + "Error evaluating else statement body ", e);
}
}
//execute exit instructions
executeExitInstructions("if", ec);
}
private BooleanObject executePredicate(ExecutionContext ec)
{
BooleanObject result;
try {
if( _sb != null ) {
IfStatementBlock isb = (IfStatementBlock)_sb;
result = (BooleanObject) executePredicate(_predicate, isb.getPredicateHops(),
isb.requiresPredicateRecompilation(), ValueType.BOOLEAN, ec);
}
else
result = (BooleanObject) executePredicate(_predicate, null, false, ValueType.BOOLEAN, ec);
}
catch(Exception ex) {
throw new DMLRuntimeException(this.printBlockErrorLocation() + "Failed to evaluate the IF predicate.", ex);
}
//(guaranteed to be non-null, see executePredicate/getScalarInput)
return result;
}
@Override
public String printBlockErrorLocation(){
return "ERROR: Runtime error in if program block generated from if statement block between lines " + _beginLine + " and " + _endLine + " -- ";
}
}
|
apache/incubator-systemml
|
src/main/java/org/apache/sysds/runtime/controlprogram/IfProgramBlock.java
|
Java
|
apache-2.0
| 4,640 |
/*
* Copyright (C) 2008 Google 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.google.gxp.compiler;
/**
* Exception indicating that the Configuration is invalid in some way.
*/
public class InvalidConfigException extends Exception {
private static final long serialVersionUID = -1;
public InvalidConfigException(String message) {
super(message);
}
}
|
Primosbookkeeping/gxp
|
java/src/com/google/gxp/compiler/InvalidConfigException.java
|
Java
|
apache-2.0
| 893 |
<?php
namespace BingAds\CustomerBilling;
/**
* Adds an insertion order to the specified account.
*
* @link http://msdn.microsoft.com/en-us/library/dn743758(v=msads.90).aspx AddInsertionOrder Request Object
*
* @uses InsertionOrder
* @used-by BingAdsCustomerBillingService::AddInsertionOrder
*/
final class AddInsertionOrderRequest
{
/**
* An insertion order to add to the account specified in the InsertionOrder object.
*
* @var InsertionOrder
*/
public $InsertionOrder;
}
|
onema/bing-ads-sdk-php
|
src/CustomerBilling/AddInsertionOrderRequest.php
|
PHP
|
apache-2.0
| 510 |
package notifications
import (
"crypto/tls"
"encoding/json"
"fmt"
"mime"
"net"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"strings"
"testing"
"github.com/distribution/distribution/v3/manifest/schema1"
events "github.com/docker/go-events"
)
// TestHTTPSink mocks out an http endpoint and notifies it under a couple of
// conditions, ensuring correct behavior.
func TestHTTPSink(t *testing.T) {
serverHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
t.Fatalf("unexpected request method: %v", r.Method)
return
}
// Extract the content type and make sure it matches
contentType := r.Header.Get("Content-Type")
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
t.Fatalf("error parsing media type: %v, contenttype=%q", err, contentType)
return
}
if mediaType != EventsMediaType {
w.WriteHeader(http.StatusUnsupportedMediaType)
t.Fatalf("incorrect media type: %q != %q", mediaType, EventsMediaType)
return
}
var envelope Envelope
dec := json.NewDecoder(r.Body)
if err := dec.Decode(&envelope); err != nil {
w.WriteHeader(http.StatusBadRequest)
t.Fatalf("error decoding request body: %v", err)
return
}
// Let caller choose the status
status, err := strconv.Atoi(r.FormValue("status"))
if err != nil {
t.Logf("error parsing status: %v", err)
// May just be empty, set status to 200
status = http.StatusOK
}
w.WriteHeader(status)
})
server := httptest.NewTLSServer(serverHandler)
metrics := newSafeMetrics("")
sink := newHTTPSink(server.URL, 0, nil, nil,
&endpointMetricsHTTPStatusListener{safeMetrics: metrics})
// first make sure that the default transport gives x509 untrusted cert error
event := Event{}
err := sink.Write(event)
if !strings.Contains(err.Error(), "x509") && !strings.Contains(err.Error(), "unknown ca") {
t.Fatal("TLS server with default transport should give unknown CA error")
}
if err := sink.Close(); err != nil {
t.Fatalf("unexpected error closing http sink: %v", err)
}
// make sure that passing in the transport no longer gives this error
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
sink = newHTTPSink(server.URL, 0, nil, tr,
&endpointMetricsHTTPStatusListener{safeMetrics: metrics})
err = sink.Write(event)
if err != nil {
t.Fatalf("unexpected error writing event: %v", err)
}
// reset server to standard http server and sink to a basic sink
metrics = newSafeMetrics("")
server = httptest.NewServer(serverHandler)
sink = newHTTPSink(server.URL, 0, nil, nil,
&endpointMetricsHTTPStatusListener{safeMetrics: metrics})
var expectedMetrics EndpointMetrics
expectedMetrics.Statuses = make(map[string]int)
closeL, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("unexpected error creating listener: %v", err)
}
defer closeL.Close()
go func() {
for {
c, err := closeL.Accept()
if err != nil {
return
}
c.Close()
}
}()
for _, tc := range []struct {
event events.Event // events to send
url string
isFailure bool // true if there should be a failure.
isError bool // true if the request returns an error
statusCode int // if not set, no status code should be incremented.
}{
{
statusCode: http.StatusOK,
event: createTestEvent("push", "library/test", schema1.MediaTypeSignedManifest),
},
{
statusCode: http.StatusOK,
event: createTestEvent("push", "library/test", schema1.MediaTypeSignedManifest),
},
{
statusCode: http.StatusOK,
event: createTestEvent("push", "library/test", layerMediaType),
},
{
statusCode: http.StatusOK,
event: createTestEvent("push", "library/test", layerMediaType),
},
{
statusCode: http.StatusTemporaryRedirect,
},
{
statusCode: http.StatusBadRequest,
isFailure: true,
},
{
// Case where connection is immediately closed
url: "http://" + closeL.Addr().String(),
isError: true,
},
} {
if tc.isFailure {
expectedMetrics.Failures++
} else if tc.isError {
expectedMetrics.Errors++
} else {
expectedMetrics.Successes++
}
if tc.statusCode > 0 {
expectedMetrics.Statuses[fmt.Sprintf("%d %s", tc.statusCode, http.StatusText(tc.statusCode))]++
}
url := tc.url
if url == "" {
url = server.URL + "/"
}
// setup endpoint to respond with expected status code.
url += fmt.Sprintf("?status=%v", tc.statusCode)
sink.url = url
t.Logf("testcase: %v, fail=%v, error=%v", url, tc.isFailure, tc.isError)
// Try a simple event emission.
err := sink.Write(tc.event)
if !tc.isFailure && !tc.isError {
if err != nil {
t.Fatalf("unexpected error send event: %v", err)
}
} else {
if err == nil {
t.Fatalf("the endpoint should have rejected the request")
}
t.Logf("write error: %v", err)
}
if !reflect.DeepEqual(metrics.EndpointMetrics, expectedMetrics) {
t.Fatalf("metrics not as expected: %#v != %#v", metrics.EndpointMetrics, expectedMetrics)
}
}
if err := sink.Close(); err != nil {
t.Fatalf("unexpected error closing http sink: %v", err)
}
// double close returns error
if err := sink.Close(); err == nil {
t.Fatalf("second close should have returned error: %v", err)
}
}
func createTestEvent(action, repo, typ string) Event {
event := createEvent(action)
event.Target.MediaType = typ
event.Target.Repository = repo
return *event
}
|
thaJeztah/distribution
|
notifications/http_test.go
|
GO
|
apache-2.0
| 5,587 |
# Copyright 2016 IBM Corp.
#
# 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 uuid
from oslo_config import cfg
from keystone import exception
from keystone.identity import controllers
from keystone.tests import unit
from keystone.tests.unit.ksfixtures import database
CONF = cfg.CONF
_ADMIN_CONTEXT = {'is_admin': True, 'query_string': {}}
class UserTestCaseNoDefaultDomain(unit.TestCase):
def setUp(self):
super(UserTestCaseNoDefaultDomain, self).setUp()
self.useFixture(database.Database())
self.load_backends()
self.user_controller = controllers.User()
def test_setup(self):
# Other tests in this class assume there's no default domain, so make
# sure the setUp worked as expected.
self.assertRaises(
exception.DomainNotFound,
self.resource_api.get_domain, CONF.identity.default_domain_id)
def test_get_users(self):
# When list_users is done and there's no default domain, the result is
# an empty list.
res = self.user_controller.get_users(_ADMIN_CONTEXT)
self.assertEqual([], res['users'])
def test_get_user_by_name(self):
# When get_user_by_name is done and there's no default domain, the
# result is 404 Not Found
user_name = uuid.uuid4().hex
self.assertRaises(
exception.UserNotFound,
self.user_controller.get_user_by_name, _ADMIN_CONTEXT, user_name)
def test_create_user(self):
# When a user is created using the v2 controller and there's no default
# domain, it doesn't fail with can't find domain (a default domain is
# created)
user = {'name': uuid.uuid4().hex}
self.user_controller.create_user(_ADMIN_CONTEXT, user)
# If the above doesn't fail then this is successful.
|
klmitch/keystone
|
keystone/tests/unit/identity/test_controllers.py
|
Python
|
apache-2.0
| 2,334 |
/*
* Copyright 2013-2014 Urs Wolfer
*
* 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.urswolfer.gerrit.client.rest.http.changes;
import com.google.common.reflect.TypeToken;
import com.google.gerrit.extensions.common.FileInfo;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author Thomas Forrer
*/
public class FileInfoParser {
private static final Type TYPE = new TypeToken<LinkedHashMap<String, FileInfo>>() {}.getType();
private final Gson gson;
public FileInfoParser(Gson gson) {
this.gson = gson;
}
public Map<String, FileInfo> parseFileInfos(JsonElement jsonElement) throws RestApiException {
return gson.fromJson(jsonElement, TYPE);
}
}
|
vogellacompany/gerrit-rest-java-client
|
src/main/java/com/urswolfer/gerrit/client/rest/http/changes/FileInfoParser.java
|
Java
|
apache-2.0
| 1,385 |
# 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.
# Dockerfile for installing the necessary dependencies for building Hadoop.
# See BUILDING.txt.
FROM ubuntu:xenial
WORKDIR /root
#####
# Disable suggests/recommends
#####
RUN echo APT::Install-Recommends "0"\; > /etc/apt/apt.conf.d/10disableextras
RUN echo APT::Install-Suggests "0"\; >> /etc/apt/apt.conf.d/10disableextras
ENV DEBIAN_FRONTEND noninteractive
ENV DEBCONF_TERSE true
######
# Install common dependencies from packages. Versions here are either
# sufficient or irrelevant.
#
# WARNING: DO NOT PUT JAVA APPS HERE! Otherwise they will install default
# Ubuntu Java. See Java section below!
######
RUN apt-get -q update && apt-get -q install -y \
apt-utils \
build-essential \
bzip2 \
clang \
curl \
doxygen \
fuse \
g++ \
gcc \
git \
gnupg-agent \
libbz2-dev \
libcurl4-openssl-dev \
libfuse-dev \
libprotobuf-dev \
libprotoc-dev \
libsasl2-dev \
libsnappy-dev \
libssl-dev \
libtool \
locales \
make \
pinentry-curses \
pkg-config \
python \
python2.7 \
python-pip \
python-pkg-resources \
python-setuptools \
python-wheel \
rsync \
software-properties-common \
snappy \
sudo \
valgrind \
zlib1g-dev
#######
# OpenJDK 8
#######
RUN apt-get -q install -y openjdk-8-jdk
#######
# OpenJDK 9
# w/workaround for
# https://bugs.launchpad.net/ubuntu/+source/openjdk-9/+bug/1593191
#######
RUN apt-get -o Dpkg::Options::="--force-overwrite" \
-q install -y \
openjdk-9-jdk-headless
#######
# Set default Java
#######
#
# By default, OpenJDK sets the default Java to the highest version.
# We want the opposite, soooooo....
#
RUN update-java-alternatives --set java-1.8.0-openjdk-amd64
RUN update-alternatives --get-selections | grep -i jdk | \
while read line; do \
alternative=$(echo $line | awk '{print $1}'); \
path=$(echo $line | awk '{print $3}'); \
newpath=$(echo $path | sed -e 's/java-9/java-8/'); \
update-alternatives --set $alternative $newpath; \
done
######
# Install cmake 3.1.0 (3.5.1 ships with Xenial)
######
RUN mkdir -p /opt/cmake && \
curl -L -s -S \
https://cmake.org/files/v3.1/cmake-3.1.0-Linux-x86_64.tar.gz \
-o /opt/cmake.tar.gz && \
tar xzf /opt/cmake.tar.gz --strip-components 1 -C /opt/cmake
ENV CMAKE_HOME /opt/cmake
ENV PATH "${PATH}:/opt/cmake/bin"
######
# Install Google Protobuf 2.5.0 (2.6.0 ships with Xenial)
######
RUN mkdir -p /opt/protobuf-src && \
curl -L -s -S \
https://github.com/google/protobuf/releases/download/v2.5.0/protobuf-2.5.0.tar.gz \
-o /opt/protobuf.tar.gz && \
tar xzf /opt/protobuf.tar.gz --strip-components 1 -C /opt/protobuf-src
RUN cd /opt/protobuf-src && ./configure --prefix=/opt/protobuf && make install
ENV PROTOBUF_HOME /opt/protobuf
ENV PATH "${PATH}:/opt/protobuf/bin"
######
# Install Apache Maven 3.3.9 (3.3.9 ships with Xenial)
######
RUN apt-get -q update && apt-get -q install -y maven
ENV MAVEN_HOME /usr
######
# Install findbugs 3.0.1 (3.0.1 ships with Xenial)
# Ant is needed for findbugs
######
RUN apt-get -q update && apt-get -q install -y findbugs ant
ENV FINDBUGS_HOME /usr
####
# Install shellcheck (0.4.6, the latest as of 2017-09-26)
####
RUN add-apt-repository -y ppa:jonathonf/ghc-8.0.2
RUN apt-get -q update && apt-get -q install -y shellcheck
####
# Install bats (0.4.0, the latest as of 2017-09-26, ships with Xenial)
####
RUN apt-get -q update && apt-get -q install -y bats
####
# Install pylint at fixed version (2.0.0 removed python2 support)
# https://github.com/PyCQA/pylint/issues/2294
####
RUN pip2 install pylint==1.9.2
####
# Install dateutil.parser
####
RUN pip2 install python-dateutil
###
# Install node.js for web UI framework (4.2.6 ships with Xenial)
###
RUN apt-get -y install nodejs && \
ln -s /usr/bin/nodejs /usr/bin/node && \
apt-get -y install npm && \
npm install npm@latest -g && \
npm install -g bower && \
npm install -g ember-cli
###
# Avoid out of memory errors in builds
###
ENV MAVEN_OPTS -Xms256m -Xmx1536m
###
# Everything past this point is either not needed for testing or breaks Yetus.
# So tell Yetus not to read the rest of the file:
# YETUS CUT HERE
###
####
# Install svn & Forrest (for Apache Hadoop website)
###
RUN apt-get -q update && apt-get -q install -y subversion
RUN mkdir -p /opt/apache-forrest && \
curl -L -s -S \
https://archive.apache.org/dist/forrest/0.8/apache-forrest-0.8.tar.gz \
-o /opt/forrest.tar.gz && \
tar xzf /opt/forrest.tar.gz --strip-components 1 -C /opt/apache-forrest
RUN echo 'forrest.home=/opt/apache-forrest' > build.properties
ENV FORREST_HOME=/opt/apache-forrest
# Hugo static website generator (for new hadoop site and Ozone docs)
RUN curl -L -o hugo.deb https://github.com/gohugoio/hugo/releases/download/v0.30.2/hugo_0.30.2_Linux-64bit.deb && dpkg --install hugo.deb && rm hugo.deb
# Add a welcome message and environment checks.
ADD hadoop_env_checks.sh /root/hadoop_env_checks.sh
RUN chmod 755 /root/hadoop_env_checks.sh
RUN echo '~/hadoop_env_checks.sh' >> /root/.bashrc
|
GeLiXin/hadoop
|
dev-support/docker/Dockerfile
|
Dockerfile
|
apache-2.0
| 5,922 |
/*
* 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.commons.lang3.text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
/**
* Tokenizes a string based on delimiters (separators)
* and supporting quoting and ignored character concepts.
* <p>
* This class can split a String into many smaller strings. It aims
* to do a similar job to {@link java.util.StringTokenizer StringTokenizer},
* however it offers much more control and flexibility including implementing
* the {@code ListIterator} interface. By default, it is set up
* like {@code StringTokenizer}.
* <p>
* The input String is split into a number of <i>tokens</i>.
* Each token is separated from the next String by a <i>delimiter</i>.
* One or more delimiter characters must be specified.
* <p>
* Each token may be surrounded by quotes.
* The <i>quote</i> matcher specifies the quote character(s).
* A quote may be escaped within a quoted section by duplicating itself.
* <p>
* Between each token and the delimiter are potentially characters that need trimming.
* The <i>trimmer</i> matcher specifies these characters.
* One usage might be to trim whitespace characters.
* <p>
* At any point outside the quotes there might potentially be invalid characters.
* The <i>ignored</i> matcher specifies these characters to be removed.
* One usage might be to remove new line characters.
* <p>
* Empty tokens may be removed or returned as null.
* <pre>
* "a,b,c" - Three tokens "a","b","c" (comma delimiter)
* " a, b , c " - Three tokens "a","b","c" (default CSV processing trims whitespace)
* "a, ", b ,", c" - Three tokens "a, " , " b ", ", c" (quoted text untouched)
* </pre>
*
* <table>
* <caption>StrTokenizer properties and options</caption>
* <tr>
* <th>Property</th><th>Type</th><th>Default</th>
* </tr>
* <tr>
* <td>delim</td><td>CharSetMatcher</td><td>{ \t\n\r\f}</td>
* </tr>
* <tr>
* <td>quote</td><td>NoneMatcher</td><td>{}</td>
* </tr>
* <tr>
* <td>ignore</td><td>NoneMatcher</td><td>{}</td>
* </tr>
* <tr>
* <td>emptyTokenAsNull</td><td>boolean</td><td>false</td>
* </tr>
* <tr>
* <td>ignoreEmptyTokens</td><td>boolean</td><td>true</td>
* </tr>
* </table>
*
* @since 2.2
* @deprecated As of 3.6, use Apache Commons Text
* <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringTokenizer.html">
* StringTokenizer</a> instead
*/
@Deprecated
public class StrTokenizer implements ListIterator<String>, Cloneable {
private static final StrTokenizer CSV_TOKENIZER_PROTOTYPE;
private static final StrTokenizer TSV_TOKENIZER_PROTOTYPE;
static {
CSV_TOKENIZER_PROTOTYPE = new StrTokenizer();
CSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StrMatcher.commaMatcher());
CSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StrMatcher.doubleQuoteMatcher());
CSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StrMatcher.noneMatcher());
CSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StrMatcher.trimMatcher());
CSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false);
CSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
TSV_TOKENIZER_PROTOTYPE = new StrTokenizer();
TSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StrMatcher.tabMatcher());
TSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StrMatcher.doubleQuoteMatcher());
TSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StrMatcher.noneMatcher());
TSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StrMatcher.trimMatcher());
TSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false);
TSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
}
/** The text to work on. */
private char[] chars;
/** The parsed tokens */
private String[] tokens;
/** The current iteration position */
private int tokenPos;
/** The delimiter matcher */
private StrMatcher delimMatcher = StrMatcher.splitMatcher();
/** The quote matcher */
private StrMatcher quoteMatcher = StrMatcher.noneMatcher();
/** The ignored matcher */
private StrMatcher ignoredMatcher = StrMatcher.noneMatcher();
/** The trimmer matcher */
private StrMatcher trimmerMatcher = StrMatcher.noneMatcher();
/** Whether to return empty tokens as null */
private boolean emptyAsNull;
/** Whether to ignore empty tokens */
private boolean ignoreEmptyTokens = true;
/**
* Returns a clone of {@code CSV_TOKENIZER_PROTOTYPE}.
*
* @return a clone of {@code CSV_TOKENIZER_PROTOTYPE}.
*/
private static StrTokenizer getCSVClone() {
return (StrTokenizer) CSV_TOKENIZER_PROTOTYPE.clone();
}
/**
* Gets a new tokenizer instance which parses Comma Separated Value strings
* initializing it with the given input. The default for CSV processing
* will be trim whitespace from both ends (which can be overridden with
* the setTrimmer method).
* <p>
* You must call a "reset" method to set the string which you want to parse.
* @return a new tokenizer instance which parses Comma Separated Value strings
*/
public static StrTokenizer getCSVInstance() {
return getCSVClone();
}
/**
* Gets a new tokenizer instance which parses Comma Separated Value strings
* initializing it with the given input. The default for CSV processing
* will be trim whitespace from both ends (which can be overridden with
* the setTrimmer method).
*
* @param input the text to parse
* @return a new tokenizer instance which parses Comma Separated Value strings
*/
public static StrTokenizer getCSVInstance(final String input) {
final StrTokenizer tok = getCSVClone();
tok.reset(input);
return tok;
}
/**
* Gets a new tokenizer instance which parses Comma Separated Value strings
* initializing it with the given input. The default for CSV processing
* will be trim whitespace from both ends (which can be overridden with
* the setTrimmer method).
*
* @param input the text to parse
* @return a new tokenizer instance which parses Comma Separated Value strings
*/
public static StrTokenizer getCSVInstance(final char[] input) {
final StrTokenizer tok = getCSVClone();
tok.reset(input);
return tok;
}
/**
* Returns a clone of {@code TSV_TOKENIZER_PROTOTYPE}.
*
* @return a clone of {@code TSV_TOKENIZER_PROTOTYPE}.
*/
private static StrTokenizer getTSVClone() {
return (StrTokenizer) TSV_TOKENIZER_PROTOTYPE.clone();
}
/**
* Gets a new tokenizer instance which parses Tab Separated Value strings.
* The default for CSV processing will be trim whitespace from both ends
* (which can be overridden with the setTrimmer method).
* <p>
* You must call a "reset" method to set the string which you want to parse.
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
public static StrTokenizer getTSVInstance() {
return getTSVClone();
}
/**
* Gets a new tokenizer instance which parses Tab Separated Value strings.
* The default for CSV processing will be trim whitespace from both ends
* (which can be overridden with the setTrimmer method).
* @param input the string to parse
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
public static StrTokenizer getTSVInstance(final String input) {
final StrTokenizer tok = getTSVClone();
tok.reset(input);
return tok;
}
/**
* Gets a new tokenizer instance which parses Tab Separated Value strings.
* The default for CSV processing will be trim whitespace from both ends
* (which can be overridden with the setTrimmer method).
* @param input the string to parse
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
public static StrTokenizer getTSVInstance(final char[] input) {
final StrTokenizer tok = getTSVClone();
tok.reset(input);
return tok;
}
/**
* Constructs a tokenizer splitting on space, tab, newline and formfeed
* as per StringTokenizer, but with no text to tokenize.
* <p>
* This constructor is normally used with {@link #reset(String)}.
*/
public StrTokenizer() {
this.chars = null;
}
/**
* Constructs a tokenizer splitting on space, tab, newline and formfeed
* as per StringTokenizer.
*
* @param input the string which is to be parsed
*/
public StrTokenizer(final String input) {
if (input != null) {
chars = input.toCharArray();
} else {
chars = null;
}
}
/**
* Constructs a tokenizer splitting on the specified delimiter character.
*
* @param input the string which is to be parsed
* @param delim the field delimiter character
*/
public StrTokenizer(final String input, final char delim) {
this(input);
setDelimiterChar(delim);
}
/**
* Constructs a tokenizer splitting on the specified delimiter string.
*
* @param input the string which is to be parsed
* @param delim the field delimiter string
*/
public StrTokenizer(final String input, final String delim) {
this(input);
setDelimiterString(delim);
}
/**
* Constructs a tokenizer splitting using the specified delimiter matcher.
*
* @param input the string which is to be parsed
* @param delim the field delimiter matcher
*/
public StrTokenizer(final String input, final StrMatcher delim) {
this(input);
setDelimiterMatcher(delim);
}
/**
* Constructs a tokenizer splitting on the specified delimiter character
* and handling quotes using the specified quote character.
*
* @param input the string which is to be parsed
* @param delim the field delimiter character
* @param quote the field quoted string character
*/
public StrTokenizer(final String input, final char delim, final char quote) {
this(input, delim);
setQuoteChar(quote);
}
/**
* Constructs a tokenizer splitting using the specified delimiter matcher
* and handling quotes using the specified quote matcher.
*
* @param input the string which is to be parsed
* @param delim the field delimiter matcher
* @param quote the field quoted string matcher
*/
public StrTokenizer(final String input, final StrMatcher delim, final StrMatcher quote) {
this(input, delim);
setQuoteMatcher(quote);
}
/**
* Constructs a tokenizer splitting on space, tab, newline and formfeed
* as per StringTokenizer.
*
* @param input the string which is to be parsed, not cloned
*/
public StrTokenizer(final char[] input) {
this.chars = ArrayUtils.clone(input);
}
/**
* Constructs a tokenizer splitting on the specified character.
*
* @param input the string which is to be parsed, not cloned
* @param delim the field delimiter character
*/
public StrTokenizer(final char[] input, final char delim) {
this(input);
setDelimiterChar(delim);
}
/**
* Constructs a tokenizer splitting on the specified string.
*
* @param input the string which is to be parsed, not cloned
* @param delim the field delimiter string
*/
public StrTokenizer(final char[] input, final String delim) {
this(input);
setDelimiterString(delim);
}
/**
* Constructs a tokenizer splitting using the specified delimiter matcher.
*
* @param input the string which is to be parsed, not cloned
* @param delim the field delimiter matcher
*/
public StrTokenizer(final char[] input, final StrMatcher delim) {
this(input);
setDelimiterMatcher(delim);
}
/**
* Constructs a tokenizer splitting on the specified delimiter character
* and handling quotes using the specified quote character.
*
* @param input the string which is to be parsed, not cloned
* @param delim the field delimiter character
* @param quote the field quoted string character
*/
public StrTokenizer(final char[] input, final char delim, final char quote) {
this(input, delim);
setQuoteChar(quote);
}
/**
* Constructs a tokenizer splitting using the specified delimiter matcher
* and handling quotes using the specified quote matcher.
*
* @param input the string which is to be parsed, not cloned
* @param delim the field delimiter character
* @param quote the field quoted string character
*/
public StrTokenizer(final char[] input, final StrMatcher delim, final StrMatcher quote) {
this(input, delim);
setQuoteMatcher(quote);
}
// API
/**
* Gets the number of tokens found in the String.
*
* @return the number of matched tokens
*/
public int size() {
checkTokenized();
return tokens.length;
}
/**
* Gets the next token from the String.
* Equivalent to {@link #next()} except it returns null rather than
* throwing {@link NoSuchElementException} when no tokens remain.
*
* @return the next sequential token, or null when no more tokens are found
*/
public String nextToken() {
if (hasNext()) {
return tokens[tokenPos++];
}
return null;
}
/**
* Gets the previous token from the String.
*
* @return the previous sequential token, or null when no more tokens are found
*/
public String previousToken() {
if (hasPrevious()) {
return tokens[--tokenPos];
}
return null;
}
/**
* Gets a copy of the full token list as an independent modifiable array.
*
* @return the tokens as a String array
*/
public String[] getTokenArray() {
checkTokenized();
return tokens.clone();
}
/**
* Gets a copy of the full token list as an independent modifiable list.
*
* @return the tokens as a String array
*/
public List<String> getTokenList() {
checkTokenized();
final List<String> list = new ArrayList<>(tokens.length);
list.addAll(Arrays.asList(tokens));
return list;
}
/**
* Resets this tokenizer, forgetting all parsing and iteration already completed.
* <p>
* This method allows the same tokenizer to be reused for the same String.
*
* @return this, to enable chaining
*/
public StrTokenizer reset() {
tokenPos = 0;
tokens = null;
return this;
}
/**
* Reset this tokenizer, giving it a new input string to parse.
* In this manner you can re-use a tokenizer with the same settings
* on multiple input lines.
*
* @param input the new string to tokenize, null sets no text to parse
* @return this, to enable chaining
*/
public StrTokenizer reset(final String input) {
reset();
if (input != null) {
this.chars = input.toCharArray();
} else {
this.chars = null;
}
return this;
}
/**
* Reset this tokenizer, giving it a new input string to parse.
* In this manner you can re-use a tokenizer with the same settings
* on multiple input lines.
*
* @param input the new character array to tokenize, not cloned, null sets no text to parse
* @return this, to enable chaining
*/
public StrTokenizer reset(final char[] input) {
reset();
this.chars = ArrayUtils.clone(input);
return this;
}
// ListIterator
/**
* Checks whether there are any more tokens.
*
* @return true if there are more tokens
*/
@Override
public boolean hasNext() {
checkTokenized();
return tokenPos < tokens.length;
}
/**
* Gets the next token.
*
* @return the next String token
* @throws NoSuchElementException if there are no more elements
*/
@Override
public String next() {
if (hasNext()) {
return tokens[tokenPos++];
}
throw new NoSuchElementException();
}
/**
* Gets the index of the next token to return.
*
* @return the next token index
*/
@Override
public int nextIndex() {
return tokenPos;
}
/**
* Checks whether there are any previous tokens that can be iterated to.
*
* @return true if there are previous tokens
*/
@Override
public boolean hasPrevious() {
checkTokenized();
return tokenPos > 0;
}
/**
* Gets the token previous to the last returned token.
*
* @return the previous token
*/
@Override
public String previous() {
if (hasPrevious()) {
return tokens[--tokenPos];
}
throw new NoSuchElementException();
}
/**
* Gets the index of the previous token.
*
* @return the previous token index
*/
@Override
public int previousIndex() {
return tokenPos - 1;
}
/**
* Unsupported ListIterator operation.
*
* @throws UnsupportedOperationException always
*/
@Override
public void remove() {
throw new UnsupportedOperationException("remove() is unsupported");
}
/**
* Unsupported ListIterator operation.
* @param obj this parameter ignored.
* @throws UnsupportedOperationException always
*/
@Override
public void set(final String obj) {
throw new UnsupportedOperationException("set() is unsupported");
}
/**
* Unsupported ListIterator operation.
* @param obj this parameter ignored.
* @throws UnsupportedOperationException always
*/
@Override
public void add(final String obj) {
throw new UnsupportedOperationException("add() is unsupported");
}
// Implementation
/**
* Checks if tokenization has been done, and if not then do it.
*/
private void checkTokenized() {
if (tokens == null) {
if (chars == null) {
// still call tokenize as subclass may do some work
final List<String> split = tokenize(null, 0, 0);
tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
} else {
final List<String> split = tokenize(chars, 0, chars.length);
tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
}
}
/**
* Internal method to performs the tokenization.
* <p>
* Most users of this class do not need to call this method. This method
* will be called automatically by other (public) methods when required.
* <p>
* This method exists to allow subclasses to add code before or after the
* tokenization. For example, a subclass could alter the character array,
* offset or count to be parsed, or call the tokenizer multiple times on
* multiple strings. It is also be possible to filter the results.
* <p>
* {@code StrTokenizer} will always pass a zero offset and a count
* equal to the length of the array to this method, however a subclass
* may pass other values, or even an entirely different array.
*
* @param srcChars the character array being tokenized, may be null
* @param offset the start position within the character array, must be valid
* @param count the number of characters to tokenize, must be valid
* @return the modifiable list of String tokens, unmodifiable if null array or zero count
*/
protected List<String> tokenize(final char[] srcChars, final int offset, final int count) {
if (srcChars == null || count == 0) {
return Collections.emptyList();
}
final StrBuilder buf = new StrBuilder();
final List<String> tokenList = new ArrayList<>();
int pos = offset;
// loop around the entire buffer
while (pos >= 0 && pos < count) {
// find next token
pos = readNextToken(srcChars, pos, count, buf, tokenList);
// handle case where end of string is a delimiter
if (pos >= count) {
addToken(tokenList, StringUtils.EMPTY);
}
}
return tokenList;
}
/**
* Adds a token to a list, paying attention to the parameters we've set.
*
* @param list the list to add to
* @param tok the token to add
*/
private void addToken(final List<String> list, String tok) {
if (StringUtils.isEmpty(tok)) {
if (isIgnoreEmptyTokens()) {
return;
}
if (isEmptyTokenAsNull()) {
tok = null;
}
}
list.add(tok);
}
/**
* Reads character by character through the String to get the next token.
*
* @param srcChars the character array being tokenized
* @param start the first character of field
* @param len the length of the character array being tokenized
* @param workArea a temporary work area
* @param tokenList the list of parsed tokens
* @return the starting position of the next field (the character
* immediately after the delimiter), or -1 if end of string found
*/
private int readNextToken(final char[] srcChars, int start, final int len, final StrBuilder workArea, final List<String> tokenList) {
// skip all leading whitespace, unless it is the
// field delimiter or the quote character
while (start < len) {
final int removeLen = Math.max(
getIgnoredMatcher().isMatch(srcChars, start, start, len),
getTrimmerMatcher().isMatch(srcChars, start, start, len));
if (removeLen == 0 ||
getDelimiterMatcher().isMatch(srcChars, start, start, len) > 0 ||
getQuoteMatcher().isMatch(srcChars, start, start, len) > 0) {
break;
}
start += removeLen;
}
// handle reaching end
if (start >= len) {
addToken(tokenList, StringUtils.EMPTY);
return -1;
}
// handle empty token
final int delimLen = getDelimiterMatcher().isMatch(srcChars, start, start, len);
if (delimLen > 0) {
addToken(tokenList, StringUtils.EMPTY);
return start + delimLen;
}
// handle found token
final int quoteLen = getQuoteMatcher().isMatch(srcChars, start, start, len);
if (quoteLen > 0) {
return readWithQuotes(srcChars, start + quoteLen, len, workArea, tokenList, start, quoteLen);
}
return readWithQuotes(srcChars, start, len, workArea, tokenList, 0, 0);
}
/**
* Reads a possibly quoted string token.
*
* @param srcChars the character array being tokenized
* @param start the first character of field
* @param len the length of the character array being tokenized
* @param workArea a temporary work area
* @param tokenList the list of parsed tokens
* @param quoteStart the start position of the matched quote, 0 if no quoting
* @param quoteLen the length of the matched quote, 0 if no quoting
* @return the starting position of the next field (the character
* immediately after the delimiter, or if end of string found,
* then the length of string
*/
private int readWithQuotes(final char[] srcChars, final int start, final int len, final StrBuilder workArea,
final List<String> tokenList, final int quoteStart, final int quoteLen) {
// Loop until we've found the end of the quoted
// string or the end of the input
workArea.clear();
int pos = start;
boolean quoting = quoteLen > 0;
int trimStart = 0;
while (pos < len) {
// quoting mode can occur several times throughout a string
// we must switch between quoting and non-quoting until we
// encounter a non-quoted delimiter, or end of string
if (quoting) {
// In quoting mode
// If we've found a quote character, see if it's
// followed by a second quote. If so, then we need
// to actually put the quote character into the token
// rather than end the token.
if (isQuote(srcChars, pos, len, quoteStart, quoteLen)) {
if (isQuote(srcChars, pos + quoteLen, len, quoteStart, quoteLen)) {
// matched pair of quotes, thus an escaped quote
workArea.append(srcChars, pos, quoteLen);
pos += quoteLen * 2;
trimStart = workArea.size();
continue;
}
// end of quoting
quoting = false;
pos += quoteLen;
continue;
}
// copy regular character from inside quotes
workArea.append(srcChars[pos++]);
trimStart = workArea.size();
} else {
// Not in quoting mode
// check for delimiter, and thus end of token
final int delimLen = getDelimiterMatcher().isMatch(srcChars, pos, start, len);
if (delimLen > 0) {
// return condition when end of token found
addToken(tokenList, workArea.substring(0, trimStart));
return pos + delimLen;
}
// check for quote, and thus back into quoting mode
if (quoteLen > 0 && isQuote(srcChars, pos, len, quoteStart, quoteLen)) {
quoting = true;
pos += quoteLen;
continue;
}
// check for ignored (outside quotes), and ignore
final int ignoredLen = getIgnoredMatcher().isMatch(srcChars, pos, start, len);
if (ignoredLen > 0) {
pos += ignoredLen;
continue;
}
// check for trimmed character
// don't yet know if its at the end, so copy to workArea
// use trimStart to keep track of trim at the end
final int trimmedLen = getTrimmerMatcher().isMatch(srcChars, pos, start, len);
if (trimmedLen > 0) {
workArea.append(srcChars, pos, trimmedLen);
pos += trimmedLen;
continue;
}
// copy regular character from outside quotes
workArea.append(srcChars[pos++]);
trimStart = workArea.size();
}
}
// return condition when end of string found
addToken(tokenList, workArea.substring(0, trimStart));
return -1;
}
/**
* Checks if the characters at the index specified match the quote
* already matched in readNextToken().
*
* @param srcChars the character array being tokenized
* @param pos the position to check for a quote
* @param len the length of the character array being tokenized
* @param quoteStart the start position of the matched quote, 0 if no quoting
* @param quoteLen the length of the matched quote, 0 if no quoting
* @return true if a quote is matched
*/
private boolean isQuote(final char[] srcChars, final int pos, final int len, final int quoteStart, final int quoteLen) {
for (int i = 0; i < quoteLen; i++) {
if (pos + i >= len || srcChars[pos + i] != srcChars[quoteStart + i]) {
return false;
}
}
return true;
}
// Delimiter
/**
* Gets the field delimiter matcher.
*
* @return the delimiter matcher in use
*/
public StrMatcher getDelimiterMatcher() {
return this.delimMatcher;
}
/**
* Sets the field delimiter matcher.
* <p>
* The delimiter is used to separate one token from another.
*
* @param delim the delimiter matcher to use
* @return this, to enable chaining
*/
public StrTokenizer setDelimiterMatcher(final StrMatcher delim) {
if (delim == null) {
this.delimMatcher = StrMatcher.noneMatcher();
} else {
this.delimMatcher = delim;
}
return this;
}
/**
* Sets the field delimiter character.
*
* @param delim the delimiter character to use
* @return this, to enable chaining
*/
public StrTokenizer setDelimiterChar(final char delim) {
return setDelimiterMatcher(StrMatcher.charMatcher(delim));
}
/**
* Sets the field delimiter string.
*
* @param delim the delimiter string to use
* @return this, to enable chaining
*/
public StrTokenizer setDelimiterString(final String delim) {
return setDelimiterMatcher(StrMatcher.stringMatcher(delim));
}
// Quote
/**
* Gets the quote matcher currently in use.
* <p>
* The quote character is used to wrap data between the tokens.
* This enables delimiters to be entered as data.
* The default value is '"' (double quote).
*
* @return the quote matcher in use
*/
public StrMatcher getQuoteMatcher() {
return quoteMatcher;
}
/**
* Set the quote matcher to use.
* <p>
* The quote character is used to wrap data between the tokens.
* This enables delimiters to be entered as data.
*
* @param quote the quote matcher to use, null ignored
* @return this, to enable chaining
*/
public StrTokenizer setQuoteMatcher(final StrMatcher quote) {
if (quote != null) {
this.quoteMatcher = quote;
}
return this;
}
/**
* Sets the quote character to use.
* <p>
* The quote character is used to wrap data between the tokens.
* This enables delimiters to be entered as data.
*
* @param quote the quote character to use
* @return this, to enable chaining
*/
public StrTokenizer setQuoteChar(final char quote) {
return setQuoteMatcher(StrMatcher.charMatcher(quote));
}
// Ignored
/**
* Gets the ignored character matcher.
* <p>
* These characters are ignored when parsing the String, unless they are
* within a quoted region.
* The default value is not to ignore anything.
*
* @return the ignored matcher in use
*/
public StrMatcher getIgnoredMatcher() {
return ignoredMatcher;
}
/**
* Set the matcher for characters to ignore.
* <p>
* These characters are ignored when parsing the String, unless they are
* within a quoted region.
*
* @param ignored the ignored matcher to use, null ignored
* @return this, to enable chaining
*/
public StrTokenizer setIgnoredMatcher(final StrMatcher ignored) {
if (ignored != null) {
this.ignoredMatcher = ignored;
}
return this;
}
/**
* Set the character to ignore.
* <p>
* This character is ignored when parsing the String, unless it is
* within a quoted region.
*
* @param ignored the ignored character to use
* @return this, to enable chaining
*/
public StrTokenizer setIgnoredChar(final char ignored) {
return setIgnoredMatcher(StrMatcher.charMatcher(ignored));
}
// Trimmer
/**
* Gets the trimmer character matcher.
* <p>
* These characters are trimmed off on each side of the delimiter
* until the token or quote is found.
* The default value is not to trim anything.
*
* @return the trimmer matcher in use
*/
public StrMatcher getTrimmerMatcher() {
return trimmerMatcher;
}
/**
* Sets the matcher for characters to trim.
* <p>
* These characters are trimmed off on each side of the delimiter
* until the token or quote is found.
*
* @param trimmer the trimmer matcher to use, null ignored
* @return this, to enable chaining
*/
public StrTokenizer setTrimmerMatcher(final StrMatcher trimmer) {
if (trimmer != null) {
this.trimmerMatcher = trimmer;
}
return this;
}
/**
* Gets whether the tokenizer currently returns empty tokens as null.
* The default for this property is false.
*
* @return true if empty tokens are returned as null
*/
public boolean isEmptyTokenAsNull() {
return this.emptyAsNull;
}
/**
* Sets whether the tokenizer should return empty tokens as null.
* The default for this property is false.
*
* @param emptyAsNull whether empty tokens are returned as null
* @return this, to enable chaining
*/
public StrTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) {
this.emptyAsNull = emptyAsNull;
return this;
}
/**
* Gets whether the tokenizer currently ignores empty tokens.
* The default for this property is true.
*
* @return true if empty tokens are not returned
*/
public boolean isIgnoreEmptyTokens() {
return ignoreEmptyTokens;
}
/**
* Sets whether the tokenizer should ignore and not return empty tokens.
* The default for this property is true.
*
* @param ignoreEmptyTokens whether empty tokens are not returned
* @return this, to enable chaining
*/
public StrTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) {
this.ignoreEmptyTokens = ignoreEmptyTokens;
return this;
}
/**
* Gets the String content that the tokenizer is parsing.
*
* @return the string content being parsed
*/
public String getContent() {
if (chars == null) {
return null;
}
return new String(chars);
}
/**
* Creates a new instance of this Tokenizer. The new instance is reset so
* that it will be at the start of the token list.
* If a {@link CloneNotSupportedException} is caught, return {@code null}.
*
* @return a new instance of this Tokenizer which has been reset.
*/
@Override
public Object clone() {
try {
return cloneReset();
} catch (final CloneNotSupportedException ex) {
return null;
}
}
/**
* Creates a new instance of this Tokenizer. The new instance is reset so that
* it will be at the start of the token list.
*
* @return a new instance of this Tokenizer which has been reset.
* @throws CloneNotSupportedException if there is a problem cloning
*/
Object cloneReset() throws CloneNotSupportedException {
// this method exists to enable 100% test coverage
final StrTokenizer cloned = (StrTokenizer) super.clone();
if (cloned.chars != null) {
cloned.chars = cloned.chars.clone();
}
cloned.reset();
return cloned;
}
/**
* Gets the String content that the tokenizer is parsing.
*
* @return the string content being parsed
*/
@Override
public String toString() {
if (tokens == null) {
return "StrTokenizer[not tokenized yet]";
}
return "StrTokenizer" + getTokenList();
}
}
|
apache/commons-lang
|
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
|
Java
|
apache-2.0
| 37,010 |
//
// Copyright 2015 Blu Age Corporation - Plano, Texas
//
// 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.
#region Usings
using NLog;
using Summer.Batch.Core.Explore;
using Summer.Batch.Core.Listener;
using Summer.Batch.Infrastructure.Repeat;
using Summer.Batch.Common.TaskExecution;
using Summer.Batch.Common.Util;
using Summer.Batch.Common.IO;
using System;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using Summer.Batch.Common.Factory;
using Summer.Batch.Core.Scope.Context;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Transactions;
#endregion
namespace Summer.Batch.Core.Step.Tasklet
{
/// <summary>
/// An <see cref="ITasklet"/> that runs a powershell script.
/// The script is executed asynchronously using injected <see cref="ITaskExecutor"/> -
/// timeout value is required to be set, so that the batch job does not hang forever
/// if the external process hangs.
/// Tasklet periodically checks for termination status (i.e.
/// Script finished its execution or timeout expired or job was interrupted).
/// The check interval is given by TerminationCheckInterval.
/// When job interrupt is detected tasklet's execution is terminated immediately
/// by throwing JobInterruptedException.
///
/// NOTE : InterruptOnCancel is not being supported for now.
/// \since 1.1.0
/// </summary>
public class PowerShellTasklet : StepExecutionListenerSupport, IStoppableTasklet, IInitializationPostOperations
{
#region Attributes
/// <summary>
/// Logger.
/// </summary>
protected static readonly Logger Logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// Enumeration of the possible Timeout Bahavior Options...
/// </summary>
public enum TimeoutBehaviorOption
{
/// <summary>
/// Will Set Step ExitStatus to ExitStatus.Failed if script execution times out...
/// </summary>
SetExitStatusToFailed,
/// <summary>
/// Will thow exception if script execution times out...
/// </summary>
ThrowException
}
/// <summary>
/// ScriptResource (i.e. Script File to be exeuted in PowerShell runspace)
/// </summary>
public IResource ScriptResource { private get; set; }
/// <summary>
/// Parameters for powershell script file being executed...i.e. passed on the command line, accessed via Param()
/// </summary>
public IDictionary<string, object> Parameters { private get; set; }
/// <summary>
/// Variables for powershell script file being executed...available in PowerShell Runspace to the script
/// </summary>
public IDictionary<string, object> Variables { private get; set; }
/// <summary>
/// System process exit code mapper property.
/// </summary>
public IPowerShellExitCodeMapper PowerShellExitCodeMapper { private get; set; }
private long _timeout;//defaults to 0
//NOTE : Timeout has to be given in ms
/// <summary>
/// Timeout property.
/// </summary>
public long Timeout { set { _timeout = value; } }
private TimeoutBehaviorOption _timeoutBehavior = TimeoutBehaviorOption.SetExitStatusToFailed;
/// <summary>
/// FileType flag property.
/// </summary>
public TimeoutBehaviorOption TimeoutBehavior
{
get { return _timeoutBehavior; }
set { _timeoutBehavior = value; }
}
private long _checkInterval = 1000;
/// <summary>
/// Termination check interval property.
/// </summary>
public long TerminationCheckInterval { set { _checkInterval = value; } }
private StepExecution _execution;//defaults to null
private volatile bool _stopped; //defaults to false
/// <summary>
/// Job explorer property.
/// </summary>
public IJobExplorer JobExplorer { private get; set; }
private bool _stoppable; //defaults to false
//=> Exit status to pass to powershell runspace...
private ExitStatus _scriptExitStatus;
//=> string buiders...
private readonly StringBuilder _sbOutput = new StringBuilder();
private readonly StringBuilder _sbVerbose = new StringBuilder();
private readonly StringBuilder _sbError = new StringBuilder();
private readonly StringBuilder _sbWarning = new StringBuilder();
private readonly StringBuilder _sbDebug = new StringBuilder();
#endregion
/// <summary>
/// @see IInitializationPostOperations#AfterPropertiesSet.
/// </summary>
public void AfterPropertiesSet()
{
//=> make sure source exists...
Assert.State(ScriptResource.Exists(), ScriptResource.GetDescription() + " does not exist.");
Assert.IsTrue(_timeout > 0, "timeout value must be greater than zero");
_stoppable = (JobExplorer != null);
//=> initialize string builders...
_sbOutput.AppendLine(Environment.NewLine + "*** PowerShell Write-Output Stream ***");
_sbVerbose.AppendLine(Environment.NewLine + "*** PowerShell Write-Verbose Stream ***");
_sbError.AppendLine(Environment.NewLine + "*** PowerShell Write-Error Stream ***");
_sbWarning.AppendLine(Environment.NewLine + "*** PowerShell Write-Warning Stream ***");
_sbDebug.AppendLine(Environment.NewLine + "*** PowerShell Write-Debug Stream ***");
}
/// <summary>
/// IStoppableTasklet#Stop.
/// </summary>
public void Stop()
{
_stopped = true;
}
/// <summary>
/// Wraps command execution into system process call.
/// </summary>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public RepeatStatus Execute(StepContribution contribution, ChunkContext chunkContext)
{
if (Logger.IsTraceEnabled)
{
Logger.Trace("*** Executing PowerShell Script File: {0}", ScriptResource.GetFullPath());
}
//=> PowerShell will throw an error if we do not Suppress ambient transaction...
// see https://msdn.microsoft.com/en-us/library/system.transactions.transaction.current(v=vs.110).aspx#NotExistJustToMakeTheAElementVisible
using (var transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
{
//=> Runspace configuration information includes the assemblies, commands, format and type files,
// providers, and scripts that are available within the runspace.
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
//Creates a single runspace that uses the default host and runspace configuration
using (Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
//=> When this runspace is opened, the default host and runspace configuration
// that are defined by Windows PowerShell will be used.
runSpace.Open();
//=> Set Variables so they are available to user script...
if (Variables != null && Variables.Any())
{
foreach (KeyValuePair<string, object> variable in Variables)
{
runSpace.SessionStateProxy.SetVariable(variable.Key, variable.Value);
}
}
//=> this is exit status variables to be tested on exit from power shell script...
// it is defined in PwerShell global scope...and must be set by scipt writer on exit...
runSpace.SessionStateProxy.SetVariable("ScriptExitStatus", _scriptExitStatus);
//=> Allows the execution of commands from a CLR
//RunspaceInvoke scriptInvoker = new RunspaceInvoke(runSpace);
//scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
using (PowerShell psInstance = PowerShell.Create())
{
try
{
// prepare a new collection to store output stream objects
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += AllStreams_DataAdded;
psInstance.Streams.Error.DataAdded += AllStreams_DataAdded;
psInstance.Streams.Verbose.DataAdded += AllStreams_DataAdded;
psInstance.Streams.Warning.DataAdded += AllStreams_DataAdded;
psInstance.Streams.Debug.DataAdded += AllStreams_DataAdded;
psInstance.Runspace = runSpace;
//=> This tasklet should be in the same dll as ExitStatus, i.e. Summer.Batch.Core.dll
// we need to get the path to loaded Summer.Batch.Core.dll so we can load it in PowerShell
var assemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
//=> need to load Summer.Batch.Core into runspace so we can reference ExitStatus
psInstance.AddScript("[System.Reflection.Assembly]::LoadFrom(\""+assemblyLocation+"\")").AddStatement();
//=> add user command and its parameters...
psInstance.AddCommand(ScriptResource.GetFullPath());
if (Parameters != null && Parameters.Any())
{
foreach (KeyValuePair<string, object> variable in Parameters)
{
psInstance.AddParameter(variable.Key, variable.Value);
}
}
//=> Invoke Asynchronously...
IAsyncResult asyncResult = psInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
// do something else until execution has completed.
long t0 = DateTime.Now.Ticks;
while (!asyncResult.IsCompleted)
{
//=> take a nap and let script do its job...
Thread.Sleep(new TimeSpan(_checkInterval));
//=> to check if job was told to stop...
CheckStoppingState(chunkContext);
//=> lets make sure we did not exceed alloted time...
long timeFromT0 = (long)(new TimeSpan(DateTime.Now.Ticks - t0)).TotalMilliseconds;
if (timeFromT0 > _timeout)
{
//=> Stop PowerShell...
psInstance.Stop();
//=> behave based on TimeoutBehaviorOption
if (_timeoutBehavior.Equals(TimeoutBehaviorOption.SetExitStatusToFailed))
{
contribution.ExitStatus = ExitStatus.Failed;
break;
}
else if (_timeoutBehavior.Equals(TimeoutBehaviorOption.ThrowException))
{
//=> lets dump what we got before throwing an error...
LogStreams();
throw new FatalStepExecutionException("Execution of PowerShell script exceeded allotted time.", null);
}
}
else if (_execution.TerminateOnly)
{
//=> Stop PowerShell...
psInstance.Stop();
//=> lets dump what we got before throwing an error...
LogStreams();
throw new JobInterruptedException(
string.Format("Job interrupted while executing PowerShell script '{0}'", ScriptResource.GetFilename()));
}
else if (_stopped)
{
psInstance.Stop();
contribution.ExitStatus = ExitStatus.Stopped;
break;
}
} // end while scope
//=> Wait to the end of execution...
//psInstance.EndInvoke(_asyncResult);
//NOTE: asyncResult.IsCompleted will be set to true if PowerShell.Stop was called or
// PowerShell completed its work
//=> if status not yet set (script completed)...handle completion...
if (contribution.ExitStatus.IsRunning())
{
//=> script needs to set exit code...if exit code not set we assume 0
var lastExitCode = (int)runSpace.SessionStateProxy.PSVariable.GetValue("LastExitCode", 0);
_scriptExitStatus = runSpace.SessionStateProxy.GetVariable("ScriptExitStatus") as ExitStatus;
//=> set exit status...
if (_scriptExitStatus != null && !_scriptExitStatus.IsRunning())
{
if (Logger.IsTraceEnabled)
{
Logger.Trace("***> ScriptExitStatus returned by script => {0}", _scriptExitStatus);
}
contribution.ExitStatus = _scriptExitStatus;
}
else //=> let user decide on ExitStatus
{
if (Logger.IsTraceEnabled)
{
if (_scriptExitStatus == null)
{
Logger.Trace("***> ScriptExitStatus is null. Using PowerShellExitCodeMapper to determine ExitStatus.");
}
else if (_scriptExitStatus.IsRunning())
{
Logger.Trace("***> ScriptExitStatus is EXECUTING or UNKNOWN. Using PowerShellExitCodeMapper to determine ExitStatus.");
}
}
if (PowerShellExitCodeMapper != null)
{
//=> determine exit status using User Provided PowerShellExitCodeMapper
contribution.ExitStatus = PowerShellExitCodeMapper.GetExitStatus(lastExitCode);
}
else //at this point we are not able to determine exit status, user needs to fix this...
{
//=> lets dump what we got before throwing an error...
LogStreams();
throw new FatalStepExecutionException(
"PowerShellTasklet is not able to determine ExitStatus. ScriptExitStatus is null or (is EXECUTING or UNKNOWN) and "+
"PowerShellExitCodeMapper is NOT defined. Please set $global:ScriptExitStatus or define PowerShellExitCodeMapper.", null);
}
}
}
if (Logger.IsInfoEnabled)
{
Logger.Info("PowerShell execution exit status [{0}]", contribution.ExitStatus);
}
//=> output captured stream data to Log...
LogStreams();
}
catch (RuntimeException ex)
{
Logger.Error(ex.Message);
throw;
}
} // end PowerShell Scope
//=> close Runspace...
runSpace.Close();
//=> we are done...
return RepeatStatus.Finished;
} // end of Runspace Scope
}// end of TransactionScope
}
private void LogStreams()
{
if (Logger.IsTraceEnabled)
{
Logger.Trace(_sbVerbose.ToString());
}
if (Logger.IsInfoEnabled)
{
Logger.Info(_sbOutput.ToString());
}
if (Logger.IsWarnEnabled)
{
Logger.Warn(_sbWarning.ToString());
}
if (Logger.IsErrorEnabled)
{
Logger.Error(_sbError.ToString());
}
if (Logger.IsDebugEnabled)
{
Logger.Debug(_sbDebug.ToString());
}
}
private void CheckStoppingState(ChunkContext chunkContext)
{
if (_stoppable)
{
JobExecution jobExecution = JobExplorer.GetJobExecution(chunkContext.StepContext.StepExecution.GetJobExecutionId().Value);
if (jobExecution.IsStopping())
{
_stopped = true;
}
}
}
/// <summary>
/// @see IStepExecutionListener#BeforeStep.
/// </summary>
/// <param name="stepExecution"></param>
public override void BeforeStep(StepExecution stepExecution)
{
_execution = stepExecution;
_scriptExitStatus = _execution.ExitStatus;
}
/// <summary>
/// Event handler for when data is added to the streams, i.e. all streams redirect to this handler.
/// </summary>
/// <param name="sender">Contains the complete PSDataCollection of all output items.</param>
/// <param name="e">Contains the index ID of the added collection item and the ID of the PowerShell instance this event belongs to.</param>
void AllStreams_DataAdded(object sender, DataAddedEventArgs e)
{
var outputStream = sender as PSDataCollection<PSObject>;
var verboseStream = sender as PSDataCollection<VerboseRecord>;
var errorStream = sender as PSDataCollection<ErrorRecord>;
var warningStream = sender as PSDataCollection<WarningRecord>;
var debugStream = sender as PSDataCollection<DebugRecord>;
if (outputStream != null)
{
if (outputStream[e.Index] != null)
{
_sbOutput.AppendLine(outputStream[e.Index].ToString());
}
}
else if (verboseStream != null)
{
if (verboseStream[e.Index] != null)
{
_sbVerbose.AppendLine(verboseStream[e.Index].ToString());
}
}
else if (errorStream != null)
{
if (errorStream[e.Index] != null)
{
_sbError.AppendLine(errorStream[e.Index].ToString());
}
}
else if (warningStream != null)
{
if (warningStream[e.Index] != null)
{
_sbWarning.AppendLine(warningStream[e.Index].ToString());
}
}
else if (debugStream != null)
{
if (debugStream[e.Index] != null)
{
_sbDebug.AppendLine(debugStream[e.Index].ToString());
}
}
else
{
_sbOutput.AppendLine("Data is comming from stream: " + sender.GetType().FullName);
}
}
}
}
|
SummerBatch/SummerBatch
|
Summer.Batch.Core/Core/Step/Tasklet/PowerShellTasklet.cs
|
C#
|
apache-2.0
| 21,927 |
/*
* 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.spark.sql.avro
import java.io._
import java.net.URI
import org.apache.avro.file.{DataFileReader}
import org.apache.avro.generic.{GenericDatumReader, GenericRecord}
import org.apache.avro.mapred.FsInput
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path
import org.apache.spark.SparkConf
import org.apache.spark.sql._
import org.apache.spark.sql.catalyst.{InternalRow, NoopFilters}
import org.apache.spark.sql.execution.datasources.v2.BatchScanExec
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.internal.SQLConf.LegacyBehaviorPolicy._
import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.sql.types._
import org.apache.spark.sql.v2.avro.AvroScan
class AvroRowReaderSuite
extends QueryTest
with SharedSparkSession {
import testImplicits._
override protected def sparkConf: SparkConf =
super
.sparkConf
.set(SQLConf.USE_V1_SOURCE_LIST, "") // need this for BatchScanExec
test("SPARK-33314: hasNextRow and nextRow properly handle consecutive calls") {
withTempPath { dir =>
Seq((1), (2), (3))
.toDF("value")
.coalesce(1)
.write
.format("avro")
.save(dir.getCanonicalPath)
val df = spark.read.format("avro").load(dir.getCanonicalPath)
val fileScan = df.queryExecution.executedPlan collectFirst {
case BatchScanExec(_, f: AvroScan) => f
}
val filePath = fileScan.get.fileIndex.inputFiles(0)
val fileSize = new File(new URI(filePath)).length
val in = new FsInput(new Path(new URI(filePath)), new Configuration())
val reader = DataFileReader.openReader(in, new GenericDatumReader[GenericRecord]())
val it = new Iterator[InternalRow] with AvroUtils.RowReader {
override val fileReader = reader
override val deserializer = new AvroDeserializer(
reader.getSchema,
StructType(new StructField("value", IntegerType, true) :: Nil),
CORRECTED,
new NoopFilters)
override val stopPosition = fileSize
override def hasNext: Boolean = hasNextRow
override def next: InternalRow = nextRow
}
assert(it.hasNext == true)
assert(it.next.getInt(0) == 1)
// test no intervening next
assert(it.hasNext == true)
assert(it.hasNext == true)
// test no intervening hasNext
assert(it.next.getInt(0) == 2)
assert(it.next.getInt(0) == 3)
assert(it.hasNext == false)
assertThrows[NoSuchElementException] {
it.next
}
}
}
}
|
cloud-fan/spark
|
external/avro/src/test/scala/org/apache/spark/sql/avro/AvroRowReaderSuite.scala
|
Scala
|
apache-2.0
| 3,389 |
#!/usr/bin/env node
var npm = require('npm');
console.log('compiling LESS files');
npm.load(function(e) {
if (e) throw e;
npm.commands.run(['build:less'], function(e, data) {
if (e) throw e;
});
});
|
don/phonegap-app-developer
|
hooks/before_prepare/compile-less.js
|
JavaScript
|
apache-2.0
| 222 |
# -*- coding: utf-8 -*-
'''
Module for controlling Jenkins
.. versionadded:: 2016.3.0
:configuration: This module can be used by either passing an api key and version
directly or by specifying both in a configuration profile in the salt
master/minion config.
For example:
.. code-block:: yaml
jenkins:
api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15
'''
# Import Python libs
from __future__ import absolute_import
import logging
try:
import jenkins
HAS_JENKINS = True
except ImportError:
HAS_JENKINS = False
import salt.utils
# Import 3rd-party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.exceptions import SaltInvocationError
# pylint: enable=import-error,no-name-in-module
log = logging.getLogger(__name__)
__virtualname__ = 'jenkins'
def __virtual__():
'''
Return virtual name of the module.
:return: The virtual name of the module.
'''
if HAS_JENKINS:
return __virtualname__
return (False, 'The jenkins execution module cannot be loaded: '
'python jenkins library is not installed.')
def _connect():
'''
Return server object used to interact with Jenkins.
:return: server object used to interact with Jenkins
'''
jenkins_url = __salt__['config.get']('jenkins.url') or \
__salt__['config.get']('jenkins:url') or \
__salt__['pillar.get']('jenkins.url')
jenkins_user = __salt__['config.get']('jenkins.user') or \
__salt__['config.get']('jenkins:user') or \
__salt__['pillar.get']('jenkins.user')
jenkins_password = __salt__['config.get']('jenkins.password') or \
__salt__['config.get']('jenkins:password') or \
__salt__['pillar.get']('jenkins.password')
if not jenkins_url:
raise SaltInvocationError('No Jenkins URL found.')
if not jenkins_user:
raise SaltInvocationError('No Jenkins User found.')
if not jenkins_password:
raise SaltInvocationError('No Jenkins Password or API token found.')
return jenkins.Jenkins(jenkins_url,
username=jenkins_user,
password=jenkins_password)
def get_version():
'''
Return version of Jenkins
:return: The version of Jenkins
CLI Example:
.. code-block:: bash
salt '*' jenkins.get_version
'''
server = _connect()
version = server.get_version()
if version:
return version
return False
def get_jobs():
'''
Return the currently configured jobs.
:return: The currently configured jobs.
CLI Example:
.. code-block:: bash
salt '*' jenkins.get_jobs
'''
server = _connect()
jobs = server.get_jobs()
if jobs:
return jobs
return {}
def job_exists(name=None):
'''
Check whether the job exists in configured Jenkins jobs.
:param name: The name of the job is check if it exists.
:return: True if job exists, False if job does not exist.
CLI Example:
.. code-block:: bash
salt '*' jenkins.job_exists jobname
'''
if not name:
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if server.job_exists(name):
return True
else:
return False
def get_job_info(name=None):
'''
Return information about the Jenkins job.
:param name: The name of the job is check if it exists.
:return: Information about the Jenkins job.
CLI Example:
.. code-block:: bash
salt '*' jenkins.get_job_info jobname
'''
if not name:
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if not job_exists(name):
raise SaltInvocationError('Job `{0}` does not exist.'.format(name))
job_info = server.get_job_info(name)
if job_info:
return job_info
return False
def build_job(name=None, parameters=None):
'''
Initiate a build for the provided job.
:param name: The name of the job is check if it exists.
:param parameters: Parameters to send to the job.
:return: True is successful, otherwise raise an exception.
CLI Example:
.. code-block:: bash
salt '*' jenkins.build_job jobname
'''
if not name:
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if not job_exists(name):
raise SaltInvocationError('Job `{0}` does not exist.'.format(name))
try:
server.build_job(name, parameters)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
def create_job(name=None,
config_xml=None,
saltenv='base'):
'''
Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configuration file used for the job.
CLI Example:
.. code-block:: bash
salt '*' jenkins.create_job jobname
salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml'
'''
if not name:
raise SaltInvocationError('Required parameter `name` is missing.')
if job_exists(name):
raise SaltInvocationError('Job `{0}` already exists.'.format(name))
if not config_xml:
config_xml = jenkins.EMPTY_CONFIG_XML
else:
config_xml_file = __salt__['cp.cache_file'](config_xml, saltenv)
with salt.utils.fopen(config_xml_file) as _fp:
config_xml = _fp.read()
server = _connect()
try:
server.create_job(name, config_xml)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return config_xml
def update_job(name=None,
config_xml=None,
saltenv='base'):
'''
Return the updated configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configuration file used for the job.
CLI Example:
.. code-block:: bash
salt '*' jenkins.update_job jobname
salt '*' jenkins.update_job jobname config_xml='salt://jenkins/config.xml'
'''
if not name:
raise SaltInvocationError('Required parameter `name` is missing.')
if not config_xml:
config_xml = jenkins.EMPTY_CONFIG_XML
else:
config_xml_file = __salt__['cp.cache_file'](config_xml, saltenv)
with salt.utils.fopen(config_xml_file) as _fp:
config_xml = _fp.read()
server = _connect()
try:
server.reconfig_job(name, config_xml)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return config_xml
def delete_job(name=None):
'''
Return true is job is deleted successfully.
:param name: The name of the job to delete.
:return: Return true if job is deleted successfully.
CLI Example:
.. code-block:: bash
salt '*' jenkins.delete_job jobname
'''
if not name:
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if not job_exists(name):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.delete_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
def enable_job(name=None):
'''
Return true is job is enabled successfully.
:param name: The name of the job to enable.
:return: Return true if job is enabled successfully.
CLI Example:
.. code-block:: bash
salt '*' jenkins.enable_job jobname
'''
if not name:
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if not job_exists(name):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.enable_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
def disable_job(name=None):
'''
Return true is job is disabled successfully.
:param name: The name of the job to disable.
:return: Return true if job is disabled successfully.
CLI Example:
.. code-block:: bash
salt '*' jenkins.disable_job jobname
'''
if not name:
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if not job_exists(name):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.disable_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
def job_status(name=None):
'''
Return the current status, enabled or disabled, of the job.
:param name: The name of the job to return status for
:return: Return true if enabled or false if disabled.
CLI Example:
.. code-block:: bash
salt '*' jenkins.job_status jobname
'''
if not name:
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if not job_exists(name):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
return server.get_job_info('empty')['buildable']
def get_job_config(name=None):
'''
Return the current job configuration for the provided job.
:param name: The name of the job to return the configuration for.
:return: The configuration for the job specified.
CLI Example:
.. code-block:: bash
salt '*' jenkins.get_job_config jobname
'''
if not name:
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if not job_exists(name):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
job_info = server.get_job_config(name)
return job_info
|
stephane-martin/salt-debian-packaging
|
salt-2016.3.3/salt/modules/jenkins.py
|
Python
|
apache-2.0
| 10,363 |
# Copyright 2016 The TensorFlow 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.
# ==============================================================================
"""Tests for losses."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.ops.losses import losses
from tensorflow.python.ops.losses import util
from tensorflow.python.platform import test
from tensorflow.python.training import momentum as momentum_lib
class AbsoluteDifferenceLossTest(test.TestCase):
def setUp(self):
super(AbsoluteDifferenceLossTest, self).setUp()
self._predictions = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
self._labels = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
def testValueErrorThrownWhenWeightIsNone(self):
with self.test_session():
with self.assertRaises(ValueError):
losses.absolute_difference(
self._predictions, self._predictions, weights=None)
def testAllCorrectNoLossWeight(self):
loss = losses.absolute_difference(self._predictions, self._predictions)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testNonZeroLoss(self):
loss = losses.absolute_difference(self._labels, self._predictions)
with self.test_session():
self.assertAlmostEqual(5.5, loss.eval(), 3)
def testNonZeroLossWithPythonScalarWeight(self):
weights = 2.3
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(5.5 * weights, loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.absolute_difference(self._labels, self._predictions,
constant_op.constant(weights))
with self.test_session():
self.assertAlmostEqual(5.5 * weights, loss.eval(), 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
weights = constant_op.constant((1.2, 0.0), shape=(2, 1))
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(5.6, loss.eval(), 3)
def testNonZeroLossWithTwoDimBatchSpecificWeights(self):
weights = constant_op.constant([1.2, 0.0], shape=[2, 1])
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(5.6, loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeights(self):
weights = constant_op.constant([3, 6, 5, 0, 4, 2], shape=[2, 3])
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(16.6, loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeightsMostZero(self):
weights = constant_op.constant([0, 0, 0, 0, 0, 2], shape=[2, 3])
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(6.0, loss.eval(), 3)
def testLossWithSampleSpecificWeightsAllZero(self):
weights = array_ops.zeros((2, 3))
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
class SoftmaxCrossEntropyLossTest(test.TestCase):
def testNoneWeightRaisesValueError(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
with self.test_session():
with self.assertRaises(ValueError):
losses.softmax_cross_entropy(labels, logits, weights=None)
def testAllCorrect(self):
with self.test_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
loss = losses.softmax_cross_entropy(labels, logits)
self.assertEquals('softmax_cross_entropy_loss/value', loss.op.name)
self.assertAlmostEqual(loss.eval(), 0.0, 3)
def testAllWrong(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
def testNonZeroLossWithPythonScalarWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = 2.3
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(weights * 10.0, loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = 2.3
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits,
constant_op.constant(weights))
self.assertAlmostEqual(weights * 10.0, loss.eval(), 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant((1.2, 3.4, 5.6))
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss.eval(), 3)
def testAllWrongAllWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant([0, 0, 0], shape=[3])
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testSomeWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant([1.2, 0, 0], shape=[3])
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(12.0, loss.eval(), 3)
def testSoftmaxWithMeasurementSpecificWeightsRaisesException(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
weights = constant_op.constant([[3, 4, 5], [2, 6, 0], [8, 0, 1]])
with self.assertRaises(ValueError):
losses.softmax_cross_entropy(labels, logits, weights=weights).eval()
def testSoftmaxLabelSmoothing(self):
with self.test_session():
# Softmax Cross Entropy Loss is:
# -\sum_i p_i \log q_i
# where for a softmax activation
# \log q_i = x_i - \log \sum_j \exp x_j
# = x_i - x_max - \log \sum_j \exp (x_j - x_max)
# For our activations, [100, -100, -100] the log partion function becomes
# \log ( exp(0) + exp(-200) + exp(-200) ) = 0
# so our log softmaxes become: [0, -200, -200]
# so our cross entropy loss is:
# -(1 - L + L/n) * 0 + 400 * L/n = 400 L/n
logits = constant_op.constant([[100.0, -100.0, -100.0]])
labels = constant_op.constant([[1, 0, 0]])
label_smoothing = 0.1
loss = losses.softmax_cross_entropy(
labels, logits, label_smoothing=label_smoothing)
self.assertEquals(loss.op.name, 'softmax_cross_entropy_loss/value')
expected_value = 400.0 * label_smoothing / 3.0
self.assertAlmostEqual(loss.eval(), expected_value, 3)
class SparseSoftmaxCrossEntropyLossTest(test.TestCase):
def testNoneWeightRaisesValueError(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0], [1], [2]])
with self.test_session():
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(labels, logits, weights=None)
def testAllCorrectInt32Labels(self):
with self.test_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0], [1], [2]], dtype=dtypes.int32)
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 0.0, 3)
def testAllCorrectInt64Labels(self):
with self.test_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0], [1], [2]], dtype=dtypes.int64)
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 0.0, 3)
def testAllCorrectNonColumnLabels(self):
with self.test_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([0, 1, 2])
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 0.0, 3)
def testAllWrongInt32Labels(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]], dtype=dtypes.int32)
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
def testAllWrongInt64Labels(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]], dtype=dtypes.int64)
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
def testAllWrongNonColumnLabels(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([2, 0, 1])
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
def testNonZeroLossWithPythonScalarWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = 2.3
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(weights * 10.0, loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = 2.3
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits,
constant_op.constant(weights))
self.assertAlmostEqual(weights * 10.0, loss.eval(), 3)
def testNonZeroLossWith1DTensorWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = 2.3
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(
labels, logits, constant_op.constant((weights,)))
self.assertAlmostEqual(weights * 10.0, loss.eval(), 3)
def testNonZeroLossWithPlaceholderForWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0],
[0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = array_ops.placeholder(dtypes.float32)
with self.test_session() as sess:
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
loss_val = sess.run(loss,
feed_dict={weights: ((1.2,), (3.4,), (5.6,))})
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss_val, 3)
def testUnknownShapePlaceholderForLogitsLabelsButScalarWeights(self):
logits = array_ops.placeholder(dtypes.float32)
labels = array_ops.placeholder(dtypes.int32)
weights = 1.0
with self.test_session() as sess:
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
loss_val = sess.run(loss,
feed_dict={
logits: [[10.0, 0.0, 0.0],
[0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]],
labels: [[2], [0], [1]],
})
self.assertAlmostEqual((1.0 + 1.0 + 1.0) * 10.0 / 3.0, loss_val, 3)
def testNonZeroLossWithPlaceholderForLogitsLabelsAndWeights(self):
logits = array_ops.placeholder(dtypes.float32, shape=(None, 3))
labels = array_ops.placeholder(dtypes.int32, shape=(None, 1))
weights = array_ops.placeholder(dtypes.float32)
with self.test_session() as sess:
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
loss_val = sess.run(loss,
feed_dict={
logits: [[10.0, 0.0, 0.0],
[0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]],
labels: [[2], [0], [1]],
weights: ((1.2,), (3.4,), (5.6,)),
})
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss_val, 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([1.2, 3.4, 5.6], shape=(3, 1))
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss.eval(), 3)
def testNonZeroLossWithColumnWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([[1.2], [3.4], [5.6]])
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss.eval(), 3)
def testAllWrongAllWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([0, 0, 0], shape=(3, 1))
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testSomeWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([1.2, 0, 0], shape=(3, 1))
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(12.0, loss.eval(), 3)
def testMeasurementSpecificWeightsRaisesException(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2]])
weights = constant_op.constant([[3, 4, 5], [2, 6, 0], [8, 0, 1]])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
def testInconsistentWeightSizeRaisesException(self):
"""The weight tensor has incorrect number of elements."""
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2]])
weights = constant_op.constant([1.2, 3.4, 5.6, 7.8])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
def testInconsistentLabelSizeRaisesException(self):
"""The label tensor has incorrect number of elements."""
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2], [3]])
weights = constant_op.constant([1.2, 3.4, 5.6])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
def testInconsistentWeightShapeRaisesException(self):
"""The weight tensor has incorrect shape."""
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0, -100.0],
[-100.0, -100.0, 100.0, -100.0],
[-100.0, -100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2], [3]])
weights = constant_op.constant([[1.2, 3.4], [5.6, 7.8]])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
def testInconsistentLabelShapeRaisesException(self):
"""The label tensor has incorrect shape."""
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0, -100.0],
[-100.0, -100.0, 100.0, -100.0],
[-100.0, -100.0, -100.0, 100.0]])
labels = constant_op.constant([[0, 1], [2, 3]])
weights = constant_op.constant(1.2)
with self.assertRaisesRegexp(ValueError, 'dimension'):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
class SigmoidCrossEntropyLossTest(test.TestCase):
def testAllCorrectSigmoid(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(logits.dtype, loss.dtype)
self.assertEquals('sigmoid_cross_entropy_loss/value', loss.op.name)
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testLossWithSingleDimPlaceholderForLogitsAndWeights1(self):
logits = array_ops.placeholder(dtypes.float32, shape=(None, 1))
labels = array_ops.placeholder(dtypes.float32, shape=(None, 1))
weights = array_ops.ones_like(logits, dtype=dtypes.float32)
loss = losses.sigmoid_cross_entropy(labels, logits, weights)
self.assertEquals(logits.dtype, loss.dtype)
with self.test_session() as sess:
loss = sess.run(loss,
feed_dict={
logits: np.ones((32, 1)),
labels: np.ones((32, 1)),
})
self.assertAlmostEqual(0.313, loss, 3)
def testLossWithSingleDimPlaceholderForLogitsAndWeights2(self):
logits = array_ops.placeholder(dtypes.float32, shape=(None, 2))
labels = array_ops.placeholder(dtypes.float32, shape=(None, 2))
weights = array_ops.ones_like(logits, dtype=dtypes.float32)
loss = losses.sigmoid_cross_entropy(labels, logits, weights)
self.assertEquals(logits.dtype, loss.dtype)
with self.test_session() as sess:
loss = sess.run(loss,
feed_dict={
logits: np.ones((32, 2)),
labels: np.ones((32, 2)),
})
self.assertAlmostEqual(0.313, loss, 3)
def testAllWrongSigmoid(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(logits.dtype, loss.dtype)
self.assertEquals('sigmoid_cross_entropy_loss/value', loss.op.name)
self.assertAlmostEqual(loss.eval(), 600.0 / 9.0, 3)
def testAllWrongSigmoidWithMeasurementSpecificWeights(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant([[3, 4, 5], [2, 6, 0], [8, 0, 1]])
loss = losses.sigmoid_cross_entropy(labels, logits, weights)
self.assertEquals(logits.dtype, loss.dtype)
self.assertEquals('sigmoid_cross_entropy_loss/value', loss.op.name)
self.assertAlmostEqual(1700.0 / 7.0, loss.eval(), 3)
def testMultiCorrectSigmoid(self):
logits = constant_op.constant([[100.0, -100.0, 100.0],
[100.0, 100.0, -100.0],
[-100.0, 100.0, 100.0]])
labels = constant_op.constant([[1, 0, 1], [1, 1, 0], [0, 1, 1]])
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(logits.dtype, loss.dtype)
self.assertEquals('sigmoid_cross_entropy_loss/value', loss.op.name)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testSigmoidFloat64(self):
logits = constant_op.constant((
(100.0, -100.0, 100.0),
(100.0, -100.0, 100.0),
(100.0, 100.0, -100.0)
), dtype=dtypes.float64)
labels = constant_op.constant((
(1, 0, 1), (1, 1, 0), (0, 1, 1)
), dtype=dtypes.int64)
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(logits.dtype, loss.dtype)
with self.test_session():
self.assertAlmostEqual(44.444, loss.eval(), 3)
def testSigmoidNoReduction(self):
logits = constant_op.constant((
(100.0, -100.0, 100.0),
(100.0, -100.0, 100.0),
(100.0, 100.0, -100.0)))
labels = constant_op.constant(((1, 0, 1), (1, 1, 0), (0, 1, 1)))
loss = losses.sigmoid_cross_entropy(
labels, logits, reduction=losses.Reduction.NONE)
self.assertEquals(logits.dtype, loss.dtype)
with self.test_session():
self.assertAllClose((
(0., 0., 0.),
(0., 100., 100.),
(100., 0., 100.)
), loss.eval(), 3)
def testSigmoidLabelSmoothingCorrect(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0]])
labels = constant_op.constant([[1, 0, 1]])
# Sigmoid cross entropy loss is:
# max(x,0) - x*z + log(1 + exp(-abs(x)))
# The new labels are:
# z' = z * (1 - L) + 0.5 L
# 1 -> 1 - 0.5 L
# 0 -> 0.5 L
# here we expect:
# 1/3 * (100 - 100 * (1 - 0.5 L) + 0
# + 0 + 100 * (0.5 L) + 0
# + 0 + 100 * (1 - 0.5 L) + 0)
# = 1/3 * (100 + 50 L)
label_smoothing = 0.1
loss = losses.sigmoid_cross_entropy(
labels, logits, label_smoothing=label_smoothing)
self.assertEquals(logits.dtype, loss.dtype)
self.assertEquals('sigmoid_cross_entropy_loss/value', loss.op.name)
expected_value = (100.0 + 50.0 * label_smoothing) / 3.0
self.assertAlmostEqual(loss.eval(), expected_value, 3)
def testSigmoidLabelSmoothingEqualsSoftmaxTwoLabel(self):
with self.test_session():
label_smoothing = 0.1
sigmoid_logits = constant_op.constant([[100.0, -100.0, -100.0]])
sigmoid_labels = constant_op.constant([[1, 0, 1]])
sigmoid_loss = losses.sigmoid_cross_entropy(
sigmoid_labels, sigmoid_logits, label_smoothing=label_smoothing)
self.assertEquals(sigmoid_logits.dtype, sigmoid_loss.dtype)
softmax_logits = constant_op.constant(
[[0.0, 100.0], [100.0, 0.0], [100.0, 0.0]])
softmax_labels = constant_op.constant([[0, 1], [1, 0], [0, 1]])
softmax_loss = losses.softmax_cross_entropy(
softmax_labels, softmax_logits, label_smoothing=label_smoothing)
self.assertAlmostEqual(sigmoid_loss.eval(), softmax_loss.eval(), 3)
class LogLossTest(test.TestCase):
def setUp(self):
super(LogLossTest, self).setUp()
predictions = np.asarray([.9, .2, .2, .8, .4, .6]).reshape((2, 3))
labels = np.asarray([1.0, 0.0, 1.0, 1.0, 0.0, 0.0]).reshape((2, 3))
self._np_predictions = predictions
self._np_labels = labels
epsilon = 1e-7
self._expected_losses = np.multiply(
labels, np.log(predictions + epsilon)) + np.multiply(
1 - labels, np.log(1 - predictions + epsilon))
self._predictions = constant_op.constant(predictions)
self._labels = constant_op.constant(labels)
def testValueErrorThrownWhenWeightIsNone(self):
with self.test_session():
with self.assertRaises(ValueError):
losses.log_loss(self._labels, self._labels, weights=None)
def testAllCorrectNoLossWeight(self):
loss = losses.log_loss(self._labels, self._labels)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testAllCorrectNoLossWeightWithPlaceholder(self):
tf_predictions = array_ops.placeholder(
dtypes.float32, shape=self._np_labels.shape)
loss = losses.log_loss(self._labels, tf_predictions)
with self.test_session():
self.assertAlmostEqual(
0.0, loss.eval(feed_dict={tf_predictions: self._np_labels}), 3)
def testNonZeroLoss(self):
loss = losses.log_loss(self._labels, self._predictions)
with self.test_session():
self.assertAlmostEqual(-np.sum(self._expected_losses) / 6.0,
loss.eval(), 3)
def testNonZeroLossWithPythonScalarWeight(self):
weights = 2.3
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.log_loss(self._labels, self._predictions,
constant_op.constant(weights))
with self.test_session():
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeightAndPlaceholder(self):
tf_predictions = array_ops.placeholder(
dtypes.float32, shape=self._np_predictions.shape)
weights = 2.3
loss = losses.log_loss(self._labels, tf_predictions,
constant_op.constant(weights))
with self.test_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
loss, 3)
def testNonZeroLossWithScalarTensorWeightAndPlaceholderWithRankOnly(self):
tf_predictions = array_ops.placeholder(dtypes.float32, shape=[None, None])
weights = 2.3
loss = losses.log_loss(self._labels, tf_predictions,
constant_op.constant(weights))
with self.test_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
loss, 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
weights = constant_op.constant((1.2, 3.4), shape=(2, 1))
expected_losses = np.multiply(
self._expected_losses,
np.asarray([1.2, 1.2, 1.2, 3.4, 3.4, 3.4]).reshape((2, 3)))
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 6.0, loss.eval(), 3)
def testNonZeroLossWithOneDimBatchSpecificWeightsSomeZero(self):
weights = constant_op.constant((1.2, 0), shape=(2, 1))
expected_losses = np.multiply(self._expected_losses,
np.asarray([1.2, 1.2, 1.2, 0, 0, 0]).reshape(
(2, 3)))
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 3.0, loss.eval(), 3)
def testNonZeroLossWithTwoDimBatchSpecificWeightsSomeZero(self):
weights = constant_op.constant([1.2, 0], shape=[2, 1])
expected_losses = np.multiply(self._expected_losses,
np.asarray([1.2, 1.2, 1.2, 0, 0, 0]).reshape(
(2, 3)))
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 3.0, loss.eval(), 3)
def testWeightsWithSameNumDimsButWrongShapeThrowsException(self):
weights = constant_op.constant(np.random.normal(size=(2, 4)), shape=[2, 4])
with self.test_session():
with self.assertRaises(ValueError):
losses.log_loss(self._labels, self._predictions, weights)
def testNonZeroLossWithMeasurementSpecificWeights(self):
weights = np.array([3, 6, 5, 0, 4, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
loss = losses.log_loss(
self._labels,
self._predictions,
constant_op.constant(
weights, shape=(2, 3)))
with self.test_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 5.0, loss.eval(), 3)
def testNonZeroLossWithMeasurementSpecificWeightsWithPlaceholder(self):
weights = np.array([3, 6, 5, 0, 4, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
tf_predictions = array_ops.placeholder(dtypes.float32, shape=[2, 3])
loss = losses.log_loss(
self._labels,
tf_predictions,
constant_op.constant(
weights, shape=(2, 3)))
with self.test_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(-np.sum(expected_losses) / 5.0, loss, 3)
def testNonZeroLossWithSampleSpecificWeightsMostZero(self):
weights = np.array([0, 0, 0, 0, 0, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
loss = losses.log_loss(
self._labels,
self._predictions,
constant_op.constant(
weights, shape=(2, 3)))
with self.test_session():
self.assertAlmostEqual(-np.sum(expected_losses), loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeightsMostZeroWithPlaceholder(self):
weights = np.array([0, 0, 0, 0, 0, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
tf_predictions = array_ops.placeholder(dtypes.float32, shape=[2, 3])
tf_weights = constant_op.constant(weights, shape=(2, 3))
loss = losses.log_loss(self._labels, tf_predictions, tf_weights)
with self.test_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(-np.sum(expected_losses), loss, 3)
def testLossWithSampleSpecificWeightsAllZero(self):
tf_weights = array_ops.zeros(shape=(2, 3))
loss = losses.log_loss(self._labels, self._predictions, tf_weights)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
class HingeLossTest(test.TestCase):
def testIncompatibleShapes(self):
with self.test_session():
logits = constant_op.constant([[-1.0], [2.1]])
labels = constant_op.constant([0.0, 1.0])
with self.assertRaises(ValueError):
_ = losses.hinge_loss(labels, logits).eval()
def testAllOutsideMargin(self):
with self.test_session():
logits = constant_op.constant([1.2, -1.4, -1.0, 2.1])
labels = constant_op.constant([1.0, 0.0, 0.0, 1.0])
loss = losses.hinge_loss(labels, logits)
self.assertAllClose(loss.eval(), 0.0, atol=1e-3)
def testSomeInsideMargin(self):
with self.test_session():
logits = constant_op.constant([[-0.7], [-1.4], [1.4], [0.6]])
labels = constant_op.constant([[0.0], [0.0], [1.0], [1.0]])
loss = losses.hinge_loss(labels, logits)
# Examples 1 and 4 are on the correct side of the hyperplane but within
# the margin so they incur some (small) loss.
self.assertAllClose(loss.eval(), 0.175, atol=1e-3)
def testSomeMisclassified(self):
with self.test_session():
logits = constant_op.constant([[[1.2], [0.4], [-1.0], [-1.1]]])
labels = constant_op.constant([[[1.0], [0.0], [0.0], [1.0]]])
loss = losses.hinge_loss(labels, logits)
# Examples 2 and 4 are on the wrong side of the hyperplane so they incur
# some (fairly large) loss.
self.assertAllClose(loss.eval(), 0.875, atol=1e-3)
class HuberLossTest(test.TestCase):
def testIncompatibleShapes(self):
with self.test_session():
predictions = constant_op.constant([[-1.0], [2.1]])
labels = constant_op.constant([0.0, 1.0])
with self.assertRaises(ValueError):
_ = losses.huber_loss(labels, predictions).eval()
def testAllQuadratic(self):
with self.test_session():
predictions = constant_op.constant([1.5, -1.4, -1.0, 0.0])
labels = constant_op.constant([1.0, -1.0, 0.0, 0.5])
loss = losses.huber_loss(labels, predictions)
self.assertAllClose(loss.eval(),
0.5 * (0.25 + 0.16 + 1.0 + 0.25) / 4., atol=1e-5)
def testAllLinear(self):
with self.test_session():
predictions = constant_op.constant([1.5, -1.4, -1.0, 0.0])
labels = constant_op.constant([0.0, 1.0, 0.0, 1.5])
loss = losses.huber_loss(labels, predictions)
self.assertAllClose(loss.eval(),
(1.5 + 2.4 + 1.0 + 1.5) / 4. - 0.5, atol=1e-5)
def testMixedQuadraticLinear(self):
with self.test_session():
predictions = constant_op.constant([[1.5, -1.4, -1.0, 0.0],
[1.5, -1.4, -1.0, 0.0]])
labels = constant_op.constant([[1.0, -1.0, 0.0, 0.5],
[0.0, 1.0, 0.0, 1.5]])
loss = losses.huber_loss(labels, predictions)
quadratic = 0.5 * (0.25 + 0.16 + 1.0 + 0.25) / 4.
linear = (1.5 + 2.4 + 1.0 + 1.5) / 4. - 0.5
expected_loss = (quadratic + linear) / 2.
self.assertAllClose(loss.eval(), expected_loss, atol=1e-5)
def testAllQuadraticDelta(self):
with self.test_session():
delta = 0.5
predictions = constant_op.constant([1.5, -1.4, -0.5, 0.0])
labels = constant_op.constant([1.0, -1.0, 0.0, 0.5])
expected = 0.5 * np.array([0.5**2, 0.4**2, 0.5**2, 0.5**2]).mean()
loss = losses.huber_loss(labels, predictions, delta=delta)
self.assertAllClose(expected, loss.eval(), atol=1e-5)
def testAllLinearDelta(self):
delta = 0.5
predictions = constant_op.constant([1.5, -1.4, -1.0, 0.0])
labels = constant_op.constant([0.0, 1.0, 0.0, 1.5])
expected = delta * np.array([1.5, 2.4, 1.0, 1.5]).mean()
expected -= 0.5 * delta**2
loss = losses.huber_loss(labels, predictions, delta=delta)
with self.test_session():
self.assertAllClose(expected, loss.eval(), atol=1e-5)
class MeanSquaredErrorTest(test.TestCase):
def setUp(self):
super(MeanSquaredErrorTest, self).setUp()
self._predictions = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
self._labels = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
def testValueErrorThrownWhenWeightIsNone(self):
with self.test_session():
with self.assertRaises(ValueError):
losses.mean_squared_error(
self._predictions, self._predictions, weights=None)
def testScalar(self):
with self.test_session():
self.assertEqual(
0.0,
losses.mean_squared_error(predictions=constant_op.constant(0),
labels=constant_op.constant(0)).eval())
def testAllCorrectNoLossWeight(self):
loss = losses.mean_squared_error(self._predictions, self._predictions)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testNonZeroLoss(self):
loss = losses.mean_squared_error(self._labels, self._predictions)
with self.test_session():
self.assertAlmostEqual(49.5, loss.eval(), 3)
def testNonZeroLossWithPythonScalarWeight(self):
weights = 2.3
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(49.5 * weights, loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.mean_squared_error(self._labels, self._predictions,
constant_op.constant(weights))
with self.test_session():
self.assertAlmostEqual(49.5 * weights, loss.eval(), 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
weights = constant_op.constant([1.2, 3.4], shape=(2, 1))
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(767.8 / 6.0, loss.eval(), 3)
def testNonZeroLossWithTwoDimBatchSpecificWeights(self):
weights = constant_op.constant([1.2, 3.4], shape=[2, 1])
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(767.8 / 6.0, loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeights(self):
weights = constant_op.constant([3, 6, 5, 0, 4, 2], shape=[2, 3])
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(587 / 5.0, loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeightsMostZero(self):
weights = constant_op.constant([0, 0, 0, 0, 0, 2], shape=[2, 3])
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(18.0, loss.eval(), 3)
def testLossWithSampleSpecificWeightsAllZero(self):
weights = array_ops.zeros((2, 3))
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
class MeanPairwiseSquaredErrorTest(test.TestCase):
def setUp(self):
super(MeanPairwiseSquaredErrorTest, self).setUp()
self._predictions = np.array([[4, 8, 12], [8, 1, 3]])
self._labels = np.array([[1, 9, 2], [-5, -5, 7]])
batch_size, dims = self._labels.shape
# Compute the expected loss 'manually'.
total = np.zeros((batch_size,))
for b in range(batch_size):
for i in range(dims - 1):
for j in range(i + 1, dims):
x = self._predictions[b, i].item() - self._predictions[b, j].item()
y = self._labels[b, i].item() - self._labels[b, j].item()
diff = (x - y)
total[b] += (diff * diff)
self._expected_losses = np.divide(total, 3.0)
def testValueErrorThrownWhenWeightIsNone(self):
with self.test_session():
with self.assertRaises(ValueError):
losses.mean_pairwise_squared_error(
predictions=constant_op.constant(self._labels),
labels=constant_op.constant(self._labels),
weights=None)
def _test_valid_weights(
self, labels, predictions, expected_loss, weights=1.0):
with self.test_session():
static_inputs_op = losses.mean_pairwise_squared_error(
predictions=predictions, labels=labels, weights=weights)
self.assertAlmostEqual(expected_loss, static_inputs_op.eval(), places=3)
predictions_placeholder = array_ops.placeholder(
dtypes.float32, shape=np.asarray(predictions.shape))
labels_placeholder = array_ops.placeholder(
dtypes.int32, shape=np.asarray(labels.shape))
weights_placeholder = array_ops.placeholder(
dtypes.float32, shape=np.asarray(weights).shape)
dynamic_inputs_op = losses.mean_pairwise_squared_error(
predictions=predictions_placeholder,
labels=labels_placeholder,
weights=weights_placeholder)
feed_dict = {
predictions_placeholder: predictions,
labels_placeholder: labels,
weights_placeholder: weights,
}
self.assertAlmostEqual(
expected_loss, dynamic_inputs_op.eval(feed_dict=feed_dict), places=3)
def testAllCorrectNoLossWeight(self):
self._test_valid_weights(
self._labels, self._labels, expected_loss=0.0)
def testNonZeroLoss(self):
self._test_valid_weights(
self._labels, self._predictions,
expected_loss=np.sum(self._expected_losses))
def testGradientWithZeroWeight(self):
with ops.Graph().as_default():
random_seed.set_random_seed(0)
inputs = array_ops.ones((2, 3))
weights = variable_scope.get_variable(
'weights',
shape=[3, 4],
initializer=init_ops.truncated_normal_initializer())
predictions = math_ops.matmul(inputs, weights)
optimizer = momentum_lib.MomentumOptimizer(
learning_rate=0.001, momentum=0.9)
loss = losses.mean_pairwise_squared_error(predictions, predictions, 0)
gradients_to_variables = optimizer.compute_gradients(loss)
init_op = variables.global_variables_initializer()
with self.test_session() as sess:
sess.run(init_op)
for grad, _ in gradients_to_variables:
np_grad = sess.run(grad)
self.assertFalse(np.isnan(np_grad).any())
def testNonZeroLossWithPythonScalarWeight(self):
weight = 2.3
self._test_valid_weights(
self._labels, self._predictions,
expected_loss=weight * np.sum(self._expected_losses),
weights=weight)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.mean_pairwise_squared_error(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
weights=constant_op.constant(weights))
with self.test_session():
self.assertAlmostEqual(weights * np.sum(self._expected_losses),
loss.eval(), 3)
def testNonZeroLossWithScalarZeroWeight(self):
self._test_valid_weights(
self._labels, self._predictions, expected_loss=0.0, weights=0.0)
def test3d(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
self._test_valid_weights(labels, predictions, expected_loss=137.5)
def test3dWeightedScalar(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
weight = 3.0
self._test_valid_weights(
labels, predictions, expected_loss=weight * 137.5, weights=weight)
def _test_invalid_weights(
self, labels, predictions, weights=1.0):
expected_error_msg = 'weights can not be broadcast to values'
# Static check.
with self.assertRaisesRegexp(ValueError, expected_error_msg):
losses.mean_pairwise_squared_error(
predictions=predictions, labels=labels, weights=weights)
# Dynamic check.
predictions_placeholder = array_ops.placeholder(dtypes.float32)
labels_placeholder = array_ops.placeholder(dtypes.int32)
weights_placeholder = array_ops.placeholder(dtypes.float32)
dynamic_inputs_op = losses.mean_pairwise_squared_error(
predictions=predictions_placeholder,
labels=labels_placeholder,
weights=weights_placeholder)
with self.test_session():
with self.assertRaisesRegexp(errors_impl.OpError, expected_error_msg):
dynamic_inputs_op.eval(feed_dict={
predictions_placeholder: predictions,
labels_placeholder: labels,
weights_placeholder: weights,
})
def testInvalid3dWeighted2x0(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
self._test_invalid_weights(
labels, predictions, weights=np.asarray((1.2, 3.4)))
def test3dWeighted2x3x3(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
self._test_valid_weights(
# TODO(ptucker): This doesn't look right.
labels,
predictions,
expected_loss=9 * 137.5,
weights=np.ones((2, 3, 3)))
def testLossWithAllZeroBatchSpecificWeights(self):
self._test_valid_weights(
self._labels, self._predictions, expected_loss=0.0,
weights=np.zeros((2, 1)))
def testLossIsAssociativeAcrossBatchElements(self):
with ops.Graph().as_default():
random_seed.set_random_seed(0)
height = 3
width = 4
shape = (1, height, width, 1)
labels0 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
predictions0 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
labels1 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
predictions1 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
loss0 = losses.mean_pairwise_squared_error(
labels=labels0,
predictions=predictions0)
loss1 = losses.mean_pairwise_squared_error(
labels=labels1,
predictions=predictions1)
loss0_1 = losses.mean_pairwise_squared_error(
labels=array_ops.concat([labels0, labels1], 0),
predictions=array_ops.concat([predictions0, predictions1], 0))
with self.test_session() as session:
loss0, loss1, loss0_1 = session.run([loss0, loss1, loss0_1])
self.assertTrue(loss0 > 0)
self.assertTrue(loss1 > 0)
self.assertAlmostEqual(loss0 + loss1, loss0_1, 5)
class CosineDistanceLossTest(test.TestCase):
def setUp(self):
super(CosineDistanceLossTest, self).setUp()
self._predictions = np.asarray([
[1, 0, 0], # Batch 1
[0, 0, -1],
[1, 0, 0], # Batch 2
[1, 0, 0],
[0, 0, -1], # Batch 3
[1, 0, 0]
]).reshape((3, 2, 3))
self._labels = np.asarray([[1, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0],
[0, 0, 1], [0, 1, 0]]).reshape((3, 2, 3))
def testValueErrorThrownWhenWeightIsNone(self):
with self.test_session():
with self.assertRaises(ValueError):
losses.cosine_distance(
predictions=constant_op.constant(self._labels),
labels=constant_op.constant(self._labels),
dim=2,
weights=None)
def testAllCorrectNoWeights(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._labels),
labels=constant_op.constant(self._labels),
dim=2)
with self.test_session():
self.assertAlmostEqual(0, loss.eval(), 5)
def testPartiallyCorrectWithIntegerValues(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2)
with self.test_session():
self.assertAlmostEqual(1, loss.eval(), 5)
def testPartiallyCorrectFloatingPointValues(self):
predictions = np.matrix(
('0.819031913261206 0.567041924552012 0.087465312324590;'
'-0.665139432070255 -0.739487441769973 -0.103671883216994;'
'0.707106781186548 -0.707106781186548 0'))
labels = np.matrix(('0.819031913261206 0.567041924552012 0.087465312324590;'
'0.665139432070255 0.739487441769973 0.103671883216994;'
'0.707106781186548 0.707106781186548 0'))
tf_preds = constant_op.constant(
predictions, shape=(3, 1, 3), dtype=dtypes.float32)
tf_labels = constant_op.constant(
labels, shape=(3, 1, 3), dtype=dtypes.float32)
loss = losses.cosine_distance(tf_labels, tf_preds, dim=2)
with self.test_session():
self.assertAlmostEqual(1.0, loss.eval(), 5)
def testSampleSpecificWeights(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=np.asarray((1, 0, 0)).reshape((3, 1, 1)))
with self.test_session():
self.assertEqual(1.0, loss.eval())
def testMeasurementSpecificWeights(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=constant_op.constant(
[1, 0, 0, 1, 1, 1], shape=(3, 2, 1)))
with self.test_session():
self.assertEqual(3.0 / 4.0, loss.eval())
def testMeasurementSpecificWeightsWithPlaceholderWithShape(self):
tf_predictions = array_ops.placeholder(
dtypes.float32, shape=self._labels.shape)
loss = losses.cosine_distance(
predictions=tf_predictions,
labels=constant_op.constant(self._labels),
dim=2,
weights=constant_op.constant(
[1, 0, 0, 1, 1, 1], shape=(3, 2, 1)))
with self.test_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._predictions})
self.assertEqual(3.0 / 4.0, loss)
def testZeroLossWhenAllSampleSpecificWeightsAreZero(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=array_ops.zeros((3, 1, 1)))
with self.test_session():
self.assertEqual(0, loss.eval())
def testZeroLossWhenAllMeasurementSpecificWeightsAreZero(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=array_ops.zeros((3, 2, 1)))
with self.test_session():
self.assertEqual(0, loss.eval())
class AddLossTest(test.TestCase):
def testNoCollectLossesBatch2(self):
logits = constant_op.constant([[1.2, 0.4, -1.0, -1.1]] * 2)
labels = constant_op.constant([[1.0, 0.0, 0.0, 1.0]] * 2)
self.assertFalse(util.get_losses())
losses.absolute_difference(logits, labels, loss_collection=None)
losses.log_loss(logits, labels, loss_collection=None)
losses.mean_squared_error(logits, labels, loss_collection=None)
losses.sigmoid_cross_entropy(logits, labels, loss_collection=None)
losses.softmax_cross_entropy(logits, labels, loss_collection=None)
self.assertFalse(util.get_losses())
class ComputeWeightedLossTest(test.TestCase):
def setUp(self):
super(ComputeWeightedLossTest, self).setUp()
self._shape = (3, 2, 4)
raw_losses = np.zeros(self._shape)
next_loss = 0.0
for i in range(self._shape[0]):
for j in range(self._shape[1]):
for k in range(self._shape[2]):
raw_losses[i][j][k] = next_loss
next_loss += 1.0
raw_losses.setflags(write=False)
self._raw_losses = raw_losses
def testUnweighted(self):
for reduction in losses.Reduction.all():
with ops.Graph().as_default() as g:
self.assertEqual(0, len(util.get_losses()))
raw_losses = self._raw_losses
unweighted_losses = (
losses.compute_weighted_loss(raw_losses, reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 1, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 1, 4)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 2, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 2, 4)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((3, 1, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((3, 1, 4)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((3, 2, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones(self._shape), reduction=reduction)
)
self.assertEqual(9, len(util.get_losses()))
with self.test_session(g):
for unweighted_loss in unweighted_losses:
if reduction == losses.Reduction.NONE:
self.assertAllClose(self._raw_losses, unweighted_loss.eval())
elif reduction == losses.Reduction.SUM:
self.assertAllClose(
np.sum(self._raw_losses), unweighted_loss.eval())
else:
# reduction one of MEAN, SUM_OVER_NONZERO_WEIGHTS,
# SUM_BY_NONZERO_WEIGHTS or SUM_OVER_BATCH_SIZE.
self.assertAllClose(
np.mean(self._raw_losses), unweighted_loss.eval())
def testUnweightedFromPlaceholder(self):
for reduction in losses.Reduction.all():
with ops.Graph().as_default() as g:
self.assertEqual(0, len(util.get_losses()))
raw_losses = array_ops.placeholder(dtype=dtypes.float32)
feed_dict = {raw_losses: self._raw_losses}
unweighted_losses = (
losses.compute_weighted_loss(raw_losses, reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 1, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 1, 4)), reduction=reduction),
)
self.assertEqual(3, len(util.get_losses()))
with self.test_session(g):
for unweighted_loss in unweighted_losses:
if reduction == losses.Reduction.NONE:
self.assertAllClose(
self._raw_losses, unweighted_loss.eval(feed_dict))
elif reduction == losses.Reduction.SUM:
self.assertAllClose(
np.sum(self._raw_losses), unweighted_loss.eval(feed_dict))
else:
# reduction one of MEAN, SUM_OVER_NONZERO_WEIGHTS,
# SUM_BY_NONZERO_WEIGHTS or SUM_OVER_BATCH_SIZE.
self.assertAllClose(
np.mean(self._raw_losses), unweighted_loss.eval(feed_dict))
def testScalarWeight(self):
with ops.Graph().as_default():
self.assertEqual(0, len(util.get_losses()))
weight = 17.0
weighted_loss = losses.compute_weighted_loss(
self._raw_losses, weights=weight)
self.assertEqual(1, len(util.get_losses()))
with self.test_session():
self.assertAllClose(
np.mean(weight * self._raw_losses), weighted_loss.eval())
def _test_invalid_weights(self, weights):
with ops.Graph().as_default():
self.assertEqual(0, len(util.get_losses()))
expected_error_msg = 'weights can not be broadcast to values'
# Static check.
with self.assertRaisesRegexp(ValueError, expected_error_msg):
losses.compute_weighted_loss(self._raw_losses, weights=weights)
# Dynamic check.
weights_placeholder = array_ops.placeholder(dtypes.float32)
weighted_loss = losses.compute_weighted_loss(
self._raw_losses, weights=weights_placeholder)
self.assertEqual(1, len(util.get_losses()))
with self.test_session():
with self.assertRaisesRegexp(errors_impl.OpError, expected_error_msg):
weighted_loss.eval(feed_dict={weights_placeholder: weights})
def testInvalidWeightTooManyDims(self):
self._test_invalid_weights(np.zeros(shape=(2, 2, 2, 2)))
def testInvalidWeightMismatchedDim(self):
with ops.Graph().as_default():
raw_losses = array_ops.reshape(self._raw_losses, shape=(3, 2, 4, 1))
weights = np.ones(shape=(3, 2, 4, 2))
expected_error_msg = 'weights can not be broadcast to values'
self.assertEqual(0, len(util.get_losses()))
# Static check.
with self.assertRaisesRegexp(ValueError, expected_error_msg):
losses.compute_weighted_loss(raw_losses, weights=weights)
# Dynamic check.
weights_placeholder = array_ops.placeholder(dtypes.float32)
weighted_loss = losses.compute_weighted_loss(
raw_losses, weights=weights_placeholder)
self.assertEqual(1, len(util.get_losses()))
with self.test_session():
with self.assertRaisesRegexp(errors_impl.OpError, expected_error_msg):
weighted_loss.eval(feed_dict={weights_placeholder: weights})
def testInvalid3Weight(self):
self._test_invalid_weights((17.0, 5.0, 2.0))
def testInvalid3x1Weight(self):
self._test_invalid_weights(((17.0,), (5.0,), (2.0,),))
def testInvalid3x2Weight(self):
self._test_invalid_weights((
(17.0, 3.0),
(5.0, 31.0),
(2.0, 7.0),))
def testInvalid1x2Weight(self):
self._test_invalid_weights((17.0, 3.0,),)
def testInvalidScalar1DWeight(self):
self._test_invalid_weights((17.0,),)
def _test_valid_weights(self, weights):
for reduction in losses.Reduction.all():
with ops.Graph().as_default() as g:
self.assertEqual(0, len(util.get_losses()))
weighted_loss = losses.compute_weighted_loss(
self._raw_losses, weights=weights, reduction=reduction)
self.assertEqual(1, len(util.get_losses()))
with self.test_session(g):
weighted_losses = weights * self._raw_losses
weighted_sum = np.sum(weighted_losses)
if reduction == losses.Reduction.NONE:
self.assertAllClose(weighted_losses, weighted_loss.eval())
elif reduction == losses.Reduction.SUM:
self.assertAllClose(weighted_sum, weighted_loss.eval())
else:
broadcast_weights = weights * np.ones_like(self._raw_losses)
if reduction == losses.Reduction.MEAN:
self.assertAllClose(
weighted_sum / np.sum(broadcast_weights),
weighted_loss.eval())
elif (reduction == losses.Reduction.SUM_OVER_NONZERO_WEIGHTS or
reduction == losses.Reduction.SUM_BY_NONZERO_WEIGHTS):
self.assertAllClose(
weighted_sum / np.count_nonzero(broadcast_weights),
weighted_loss.eval())
elif reduction == losses.Reduction.SUM_OVER_BATCH_SIZE:
self.assertAllClose(
weighted_sum / self._raw_losses.size,
weighted_loss.eval())
def test1x1x1Weight(self):
self._test_valid_weights((((17.0,),),))
def test1x2x1Weight(self):
self._test_valid_weights((((17.0,), (3.0,),),))
def test1x1x4Weight(self):
self._test_valid_weights((((17.0, 0.0, 2.0, 5.0),),))
def test3x1x1Weight(self):
self._test_valid_weights((((17.0,),), ((5.0,),), ((2.0,),),))
def test3x2x1Weight(self):
self._test_valid_weights((
((17.0,), (3.0,)),
((5.0,), (31.0,)),
((2.0,), (7.0,)),
))
def test3x1x4Weight(self):
self._test_valid_weights((
((17.0, 0.0, 2.0, 5.0),),
((5.0, 31.0, 17.0, 5.0),),
((7.0, 3.0, 11.0, 5.0),),
))
def test1x2x4Weight(self):
self._test_valid_weights(((
(17.0, 0.0, 2.0, 5.0),
(3.0, 13.0, 11.0, 2.0),
),))
def test3x2x4Weight(self):
self._test_valid_weights((
((17.0, 0.0, 2.0, 5.0), (3.0, 13.0, 11.0, 2.0),),
((5.0, 31.0, 17.0, 5.0), (13.0, 3.0, 0.0, 11.0),),
((0.0, 3.0, 11.0, 5.0), (13.0, 11.0, 1.0, 7.0),),
))
if __name__ == '__main__':
test.main()
|
nolanliou/tensorflow
|
tensorflow/python/kernel_tests/losses_test.py
|
Python
|
apache-2.0
| 63,551 |
package edu.berkeley.nlp.syntax;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.berkeley.nlp.util.CollectionUtils;
import edu.berkeley.nlp.util.Counter;
import edu.berkeley.nlp.util.Factory;
/**
* Assumes the type V is hashable
*
* @author adampauls
*
* @param <V>
*/
public class UnaryClosureComputer<V> {
public static class Edge<V> {
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((child == null) ? 0 : child.hashCode());
result = prime * result
+ ((parent == null) ? 0 : parent.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Edge other = (Edge) obj;
if (child == null) {
if (other.child != null)
return false;
} else if (!child.equals(other.child))
return false;
if (parent == null) {
if (other.parent != null)
return false;
} else if (!parent.equals(other.parent))
return false;
return true;
}
public void setParent(V parent) {
this.parent = parent;
}
public void setChild(V child) {
this.child = child;
}
private V parent;
private V child;
private double score;
private Edge(V parent, V child) {
this.parent = parent;
this.child = child;
}
public V getParent() {
return parent;
}
public V getChild() {
return child;
}
public double getScore() {
return score;
}
public void setScore(double d) {
score = d;
}
}
private Factory<Edge> unaryRuleFactory = new Factory<Edge>() {
public Edge newInstance(Object... args) {
return new Edge(args[0], args[1]);
}
};
Map<V, List<Edge<V>>> closedUnaryRulesByChild = new HashMap<V, List<Edge<V>>>();
Map<V, List<Edge<V>>> closedUnaryRulesByParent = new HashMap<V, List<Edge<V>>>();
Map<Edge<V>, List<V>> pathMap = new HashMap<Edge<V>, List<V>>();
Set<Edge<V>> unaryRules = new HashSet<Edge<V>>();
private boolean sumInsteadOfMultipy;
/**
* First is parent, second is child;
*
* @return
*/
public Map<V, List<Edge<V>>> getAllClosedRulesByChildren() {
return closedUnaryRulesByChild;
}
public List<Edge<V>> getClosedUnaryRulesByChild(V child) {
return CollectionUtils.getValueList(closedUnaryRulesByChild, child);
}
public List<Edge<V>> getClosedUnaryRulesByParent(V parent) {
return CollectionUtils.getValueList(closedUnaryRulesByParent, parent);
}
public List<V> getPath(Edge unaryRule) {
return pathMap.get(unaryRule);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (V parent : closedUnaryRulesByParent.keySet()) {
for (Edge unaryRule : getClosedUnaryRulesByParent(parent)) {
List<V> path = getPath(unaryRule);
// if (path.size() == 2) continue;
sb.append(unaryRule);
sb.append(" ");
sb.append(path);
sb.append("\n");
}
}
return sb.toString();
}
public UnaryClosureComputer(boolean sumInsteadOfMultiply) {
this.sumInsteadOfMultipy = sumInsteadOfMultiply;
}
public void add(V parent, V child, double score) {
final Edge edge = new Edge(parent, child);
edge.setScore(score);
unaryRules.add(edge);
}
public void solve() {
Map<Edge<V>, List<V>> closureMap = computeUnaryClosure(unaryRules);
for (Edge<V> unaryRule : closureMap.keySet()) {
addUnary(unaryRule, closureMap.get(unaryRule));
}
}
private void addUnary(Edge<V> unaryRule, List<V> path) {
CollectionUtils.addToValueList(closedUnaryRulesByChild,
unaryRule.getChild(), unaryRule);
CollectionUtils.addToValueList(closedUnaryRulesByParent,
unaryRule.getParent(), unaryRule);
pathMap.put(unaryRule, path);
}
private Map<Edge<V>, List<V>> computeUnaryClosure(
Collection<Edge<V>> unaryRules) {
Map<Edge<V>, V> intermediateStates = new HashMap<Edge<V>, V>();
Counter<Edge<V>> pathCosts = new Counter<Edge<V>>();
Map<V, List<Edge<V>>> closedUnaryRulesByChild = new HashMap<V, List<Edge<V>>>();
Map<V, List<Edge<V>>> closedUnaryRulesByParent = new HashMap<V, List<Edge<V>>>();
Set<V> states = new HashSet<V>();
for (Edge<V> unaryRule : unaryRules) {
relax(pathCosts, intermediateStates, closedUnaryRulesByChild,
closedUnaryRulesByParent, unaryRule, null,
unaryRule.getScore());
states.add(unaryRule.getParent());
states.add(unaryRule.getChild());
}
for (V intermediateState : states) {
List<Edge<V>> incomingRules = closedUnaryRulesByChild
.get(intermediateState);
List<Edge<V>> outgoingRules = closedUnaryRulesByParent
.get(intermediateState);
if (incomingRules == null || outgoingRules == null)
continue;
for (Edge<V> incomingRule : incomingRules) {
for (Edge<V> outgoingRule : outgoingRules) {
Edge<V> rule = unaryRuleFactory.newInstance(
incomingRule.getParent(), outgoingRule.getChild());
double newScore = combinePathCosts(pathCosts, incomingRule,
outgoingRule);
relax(pathCosts, intermediateStates,
closedUnaryRulesByChild, closedUnaryRulesByParent,
rule, intermediateState, newScore);
}
}
}
for (V state : states)
{
Edge<V> selfLoopRule = unaryRuleFactory.newInstance(state, state);
relax(pathCosts, intermediateStates, closedUnaryRulesByChild,
closedUnaryRulesByParent, selfLoopRule, null, 0.0);
}
Map<Edge<V>, List<V>> closureMap = new HashMap<Edge<V>, List<V>>();
for (Edge<V> unaryRule : pathCosts.keySet()) {
unaryRule.setScore(pathCosts.getCount(unaryRule));
List<V> path = extractPath(unaryRule, intermediateStates);
closureMap.put(unaryRule, path);
}
return closureMap;
}
/**
* @param pathCosts
* @param incomingRule
* @param outgoingRule
* @return
*/
private double combinePathCosts(Counter<Edge<V>> pathCosts,
Edge<V> incomingRule, Edge<V> outgoingRule) {
return this.sumInsteadOfMultipy ? (pathCosts.getCount(incomingRule) + pathCosts
.getCount(outgoingRule))
: (pathCosts.getCount(incomingRule) * pathCosts
.getCount(outgoingRule));
}
private List<V> extractPath(Edge<V> unaryRule,
Map<Edge<V>, V> intermediateStates) {
List<V> path = new ArrayList<V>();
path.add(unaryRule.getParent());
V intermediateState = intermediateStates.get(unaryRule);
if (intermediateState != null) {
List<V> parentPath = extractPath(unaryRuleFactory.newInstance(
unaryRule.getParent(), intermediateState),
intermediateStates);
for (int i = 1; i < parentPath.size() - 1; i++) {
V state = parentPath.get(i);
path.add(state);
}
path.add(intermediateState);
List<V> childPath = extractPath(
unaryRuleFactory.newInstance(intermediateState,
unaryRule.getChild()), intermediateStates);
for (int i = 1; i < childPath.size() - 1; i++) {
V state = childPath.get(i);
path.add(state);
}
}
if (path.size() == 1 && unaryRule.getParent() == unaryRule.getChild())
return path;
path.add(unaryRule.getChild());
return path;
}
private void relax(Counter<Edge<V>> pathCosts,
Map<Edge<V>, V> intermediateStates,
Map<V, List<Edge<V>>> closedUnaryRulesByChild,
Map<V, List<Edge<V>>> closedUnaryRulesByParent, Edge<V> unaryRule,
V intermediateState, double newScore) {
if (intermediateState != null
&& (intermediateState.equals(unaryRule.getParent()) || intermediateState
.equals(unaryRule.getChild())))
return;
boolean isNewRule = !pathCosts.containsKey(unaryRule);
double oldScore = (isNewRule ? Double.NEGATIVE_INFINITY : pathCosts
.getCount(unaryRule));
if (oldScore > newScore)
return;
if (isNewRule) {
CollectionUtils.addToValueList(closedUnaryRulesByChild,
unaryRule.getChild(), unaryRule);
CollectionUtils.addToValueList(closedUnaryRulesByParent,
unaryRule.getParent(), unaryRule);
}
pathCosts.setCount(unaryRule, newScore);
intermediateStates.put(unaryRule, intermediateState);
}
public double getProb(V parent, V child) {
if (parent == child)
return 0.0;
final List<Edge<V>> byParent = closedUnaryRulesByParent.get(parent);
if (byParent == null)
return Double.POSITIVE_INFINITY;
int childIndex = byParent.indexOf(unaryRuleFactory.newInstance(parent,
child));
if (childIndex < 0)
return Double.POSITIVE_INFINITY;
final Edge<V> unaryRule = byParent.get(childIndex);
return unaryRule.getScore();
}
}
|
text-machine-lab/CliRel
|
model/kim/berkeleyparser/src/edu/berkeley/nlp/syntax/UnaryClosureComputer.java
|
Java
|
apache-2.0
| 8,539 |
---
title: "bucketizer.median"
layout: "function"
isPage: "true"
link: "/warpscript/framework_bucketize"
desc: "Return the median of the values of the interval"
categoryTree: ["reference","frameworks"]
oldPath: ["20-frameworks","101-framework-bucketize","111-bucketizer_median.html.md"]
category: "reference"
---
The `bucketizer.median` function returns the median of all the values found in the interval to bucketize.
The associated location is the centroid of all the encountered locations. The associated elevation is the median of the encountered elevations.
The `bucketizer.median` function can only be applied to values of type **LONG** or **DOUBLE**, when applied to **STRING** or **BOOLEAN** it does not return any value.
## Example ##
Stack:
TOP: {"c":"testname","l":{"label0":"42","label1":"foo"},"a":{},"v":[[100,10],[200,9],[300,8],[400,7],[500,6],[600,5],[700,4],[800,42]]}
WarpScript commands:
// arguments are: GTS or [GTS], bucketizer, lastbucket, bucketspan, bucketcount
[ SWAP bucketizer.median 0 0 2 ] BUCKETIZE
Stack:
TOP: [{"c":"testname","l":{"label0":"42","label1":"foo"},"a":{},"v":[[800,5],[449,8]]}]
## Let's play with it ##
{% raw %}
<warp10-warpscript-widget>NEWGTS
'testname'
RENAME
{ 'label0' '42' 'label1' 'foo' }
RELABEL
100 NaN NaN NaN 10 ADDVALUE
200 NaN NaN NaN 9 ADDVALUE
300 NaN NaN NaN 8 ADDVALUE
400 NaN NaN NaN 7 ADDVALUE
500 NaN NaN NaN 6 ADDVALUE
600 NaN NaN NaN 5 ADDVALUE
700 NaN NaN NaN 4 ADDVALUE
800 NaN NaN NaN 42 ADDVALUE
// arguments are: GTS or [GTS], bucketizer, lastbucket, bucketspan, bucketcount
[ SWAP bucketizer.median 0 0 2 ] BUCKETIZE
</warp10-warpscript-widget>
{% endraw %}
## Unit test ##
{% raw %}
<warp10-warpscript-widget>NEWGTS
'testname'
RENAME
{ 'label0' '42' 'label1' 'foo' }
RELABEL
100 NaN NaN NaN 10 ADDVALUE
200 NaN NaN NaN 9 ADDVALUE
300 NaN NaN NaN 8 ADDVALUE
400 NaN NaN NaN 7 ADDVALUE
500 NaN NaN NaN 6 ADDVALUE
600 NaN NaN NaN 5 ADDVALUE
700 NaN NaN NaN 4 ADDVALUE
800 NaN NaN NaN 42 ADDVALUE
// arguments are: GTS or [GTS], bucketizer, lastbucket, bucketspan, bucketcount
[ SWAP bucketizer.median 0 0 2 ] BUCKETIZE
LIST-> DROP // Exract the GTS from the list
VALUES LIST-> DROP // Expand the list of values
8 == ASSERT 5 == ASSERT
'unit test successful'
</warp10-warpscript-widget>
{% endraw %}
|
slambour/www.warp10.io
|
reference/frameworks/bucketizer_median.md
|
Markdown
|
apache-2.0
| 2,366 |
/*
Copyright 2018 The Kubernetes 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 auth
import (
"bytes"
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/alicloud/alibaba-cloud-sdk-go/sdk/requests"
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/alicloud/alibaba-cloud-sdk-go/sdk/utils"
"sort"
"strings"
)
func signRoaRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) {
completeROASignParams(request, signer, regionId)
stringToSign := buildRoaStringToSign(request)
request.SetStringToSign(stringToSign)
signature := signer.Sign(stringToSign, "")
accessKeyId, err := signer.GetAccessKeyId()
if err != nil {
return nil
}
request.GetHeaders()["Authorization"] = "acs " + accessKeyId + ":" + signature
return
}
func completeROASignParams(request requests.AcsRequest, signer Signer, regionId string) {
headerParams := request.GetHeaders()
// complete query params
queryParams := request.GetQueryParams()
//if _, ok := queryParams["RegionId"]; !ok {
// queryParams["RegionId"] = regionId
//}
if extraParam := signer.GetExtraParam(); extraParam != nil {
for key, value := range extraParam {
if key == "SecurityToken" {
headerParams["x-acs-security-token"] = value
continue
}
queryParams[key] = value
}
}
// complete header params
headerParams["Date"] = utils.GetTimeInFormatRFC2616()
headerParams["x-acs-signature-method"] = signer.GetName()
headerParams["x-acs-signature-version"] = signer.GetVersion()
if request.GetFormParams() != nil && len(request.GetFormParams()) > 0 {
formString := utils.GetUrlFormedMap(request.GetFormParams())
request.SetContent([]byte(formString))
headerParams["Content-Type"] = requests.Form
}
contentMD5 := utils.GetMD5Base64(request.GetContent())
headerParams["Content-MD5"] = contentMD5
if _, contains := headerParams["Content-Type"]; !contains {
headerParams["Content-Type"] = requests.Raw
}
switch format := request.GetAcceptFormat(); format {
case "JSON":
headerParams["Accept"] = requests.Json
case "XML":
headerParams["Accept"] = requests.Xml
default:
headerParams["Accept"] = requests.Raw
}
}
func buildRoaStringToSign(request requests.AcsRequest) (stringToSign string) {
headers := request.GetHeaders()
stringToSignBuilder := bytes.Buffer{}
stringToSignBuilder.WriteString(request.GetMethod())
stringToSignBuilder.WriteString(requests.HeaderSeparator)
// append header keys for sign
appendIfContain(headers, &stringToSignBuilder, "Accept", requests.HeaderSeparator)
appendIfContain(headers, &stringToSignBuilder, "Content-MD5", requests.HeaderSeparator)
appendIfContain(headers, &stringToSignBuilder, "Content-Type", requests.HeaderSeparator)
appendIfContain(headers, &stringToSignBuilder, "Date", requests.HeaderSeparator)
// sort and append headers witch starts with 'x-acs-'
var acsHeaders []string
for key := range headers {
if strings.HasPrefix(key, "x-acs-") {
acsHeaders = append(acsHeaders, key)
}
}
sort.Strings(acsHeaders)
for _, key := range acsHeaders {
stringToSignBuilder.WriteString(key + ":" + headers[key])
stringToSignBuilder.WriteString(requests.HeaderSeparator)
}
// append query params
stringToSignBuilder.WriteString(request.BuildQueries())
stringToSign = stringToSignBuilder.String()
return
}
func appendIfContain(sourceMap map[string]string, target *bytes.Buffer, key, separator string) {
if value, contain := sourceMap[key]; contain && len(value) > 0 {
target.WriteString(sourceMap[key])
target.WriteString(separator)
}
}
|
kubernetes/autoscaler
|
cluster-autoscaler/cloudprovider/alicloud/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go
|
GO
|
apache-2.0
| 4,039 |
// (C) Copyright 2015 Martin Dougiamas
//
// 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.
angular.module('mm.addons.messages')
/**
* Messages handlers factory.
*
* This factory holds the different handlers used for delegates.
*
* @module mm.addons.messages
* @ngdoc service
* @name $mmaMessagesHandlers
*/
.factory('$mmaMessagesHandlers', function($q, $log, $mmaMessages, $mmSite, $state) {
$log = $log.getInstance('$mmaMessagesHandlers');
var self = {};
/**
* Add contact handler.
*
* @module mm.addons.messages
* @ngdoc method
* @name $mmaMessagesHandlers#addContact
*/
self.addContact = function() {
var self = {};
self.isEnabled = function() {
return $mmaMessages.isPluginEnabled();
};
self.isEnabledForUser = function(user, courseId) {
return user.id != $mmSite.getUserId();
};
/**
* Add contact handler controller.
*
* @module mm.addons.messages
* @ngdoc controller
* @name $mmaMessagesHandlers#blockContact:controller
*/
self.getController = function(user, courseid) {
return function($scope, $rootScope) {
var disabled = false;
function updateTitle() {
return $mmaMessages.isContact(user.id).then(function(isContact) {
if (isContact) {
$scope.title = 'mma.messages.removecontact';
} else {
$scope.title = 'mma.messages.addcontact';
}
}).catch(function() {
// This fails for some reason, let's just hide the button.
$scope.hidden = true;
});
}
$scope.title = '';
$scope.spinner = false;
$scope.action = function($event) {
if (disabled) {
return;
}
disabled = true;
$scope.spinner = true;
$mmaMessages.isContact(user.id).then(function(isContact) {
if (isContact) {
return $mmaMessages.removeContact(user.id);
} else {
return $mmaMessages.addContact(user.id);
}
}).finally(function() {
$rootScope.$broadcast('mmaMessagesHandlers:addUpdated');
updateTitle().finally(function() {
disabled = false;
$scope.spinner = false;
});
});
};
$scope.$on('mmaMessagesHandlers:blockUpdated', function() {
updateTitle();
});
updateTitle();
};
};
return self;
};
/**
* Block contact handler.
*
* @module mm.addons.messages
* @ngdoc method
* @name $mmaMessagesHandlers#blockContact
*/
self.blockContact = function() {
var self = {};
self.isEnabled = function() {
return $mmaMessages.isPluginEnabled();
};
self.isEnabledForUser = function(user, courseId) {
return user.id != $mmSite.getUserId();
};
self.getController = function(user, courseid) {
/**
* Block contact handler controller.
*
* @module mm.addons.messages
* @ngdoc controller
* @name $mmaMessagesHandlers#blockContact:controller
*/
return function($scope, $rootScope) {
var disabled = false;
function updateTitle() {
return $mmaMessages.isBlocked(user.id).then(function(isBlocked) {
if (isBlocked) {
$scope.title = 'mma.messages.unblockcontact';
} else {
$scope.title = 'mma.messages.blockcontact';
}
}).catch(function() {
// This fails for some reason, let's just hide the button.
$scope.hidden = true;
});
}
$scope.title = '';
$scope.spinner = false;
$scope.action = function($event) {
if (disabled) {
return;
}
disabled = true;
$scope.spinner = true;
$mmaMessages.isBlocked(user.id).then(function(isBlocked) {
if (isBlocked) {
return $mmaMessages.unblockContact(user.id);
} else {
return $mmaMessages.blockContact(user.id);
}
}).finally(function() {
$rootScope.$broadcast('mmaMessagesHandlers:blockUpdated');
updateTitle().finally(function() {
disabled = false;
$scope.spinner = false;
});
});
};
$scope.$on('mmaMessagesHandlers:addUpdated', function() {
updateTitle();
});
updateTitle();
};
};
return self;
};
/**
* Send message handler.
*
* @module mm.addons.messages
* @ngdoc method
* @name $mmaMessagesHandlers#blockContact
*/
self.sendMessage = function() {
var self = {};
self.isEnabled = function() {
return $mmaMessages.isPluginEnabled();
};
self.isEnabledForUser = function(user, courseId) {
return user.id != $mmSite.getUserId();
};
self.getController = function(user, courseid) {
/**
* Send message handler controller.
*
* @module mm.addons.messages
* @ngdoc controller
* @name $mmaMessagesHandlers#sendMessage:controller
*/
return function($scope) {
$scope.title = 'mma.messages.sendmessage';
$scope.action = function($event) {
$event.preventDefault();
$event.stopPropagation();
$state.go('site.messages-discussion', {
userId: user.id,
userFullname: user.fullname
});
};
};
};
return self;
};
return self;
});
|
crisleo15/moodlemobile2
|
www/addons/messages/services/handlers.js
|
JavaScript
|
apache-2.0
| 7,391 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="IE=edge" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-touch-fullscreen" content="yes">
<link rel="stylesheet" type="text/css" href="assets/css/ionic.min.css" />
<link rel="stylesheet" type="text/css" href="assets/css/styles.css" />
<link rel="stylesheet" type="text/css" href="assets/css/app_effects.css" />
<link rel="stylesheet" type="text/css" href="assets/css/snap.css" />
</head>
<body>
<!-- home-tpl -->
<script id="home-tpl" type="text/x-handlebars-template">
<div class="home-tpl">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<div class="row armorial-wrapper">
<div class="col">
<img src="assets/img/bulgarian-armorial.svg" class="armorial">
<h1 class="title">
<span>Народно събрание на</span></br>
Република България
</h1>
</div>
</div>
</div>
</script>
<!-- END home-tpl -->
<!-- plenary-tpl -->
<script id="plenary-tpl" type="text/x-handlebars-template">
<div class="plenary-tpl">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Пленарни заседания</h1>
<button class="search-btn button button-icon" id="btnSearchPlenary">
<img src="assets/img/search-icon.png" alt="ico" class="ico">
</button>
</div>
<div class="row search-row">
<div class="col hidden" id="searchBoxPlenary">
<div class="search-wrapper">
<input type="text" placeholder="Търси заседание" class="search-field" id="txtSearchPlenary" />
</div>
</div>
</div>
<div class="row">
<div class="col content-wrapper" id="scrollingContent">
{{#each plenary}}
<div class="row short-preview plenariesListItem" data-list-item-id="{{pid}}">
<div class="col-67 description" onclick="openAppUrl('#plenaryDetail?id={{pid}}');">
{{{dscrShort}}}
</div>
<div class="col-33">
<div class="custom-row">
<div class="date">{{startDate}}</div>
{{#ifCond startDate endDate}}
{{else}}
<div class="date">{{endDate}}</div>
{{/ifCond}}
</div>
<div class="custom-row">
<button class="button icon-left ion-eye preview-btn" onclick="openAppUrl('#plenaryDetail?id={{pid}}');">
<span class="txt">Преглед</span>
</button>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END plenary-tpl -->
<!-- plenary-tpl detail -->
<script id="plenary-tpl-detail-preview" type="text/x-handlebars-template">
<div class="plenary-tpl-detail-preview">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Пленарни заседания</h1>
</div>
<div class="row">
<div class="col content-wrapper">
<div class="row detail-preview">
<div class="col">
<div class="row">
<h2 class="title">Пленарно заседание</h2>
</div>
<div class="row">
<div class="custom-row">
<div class="date">{{startDate}}</div>
{{#ifCond startDate endDate}}
{{else}}
<div class="date-separator">-</div>
<div class="date">{{endDate}}</div>
{{/ifCond}}
</div>
</div>
<div class="row">
<div class="col description">
{{#each agenda}}
<div style="margin-bottom: 10px;">
{{id}}. {{itemText}}
{{#ifCond isBill '1'}}
<ul class="external-link-wrapper">
{{#each bills}}
<li>
<a href="javascript:openUrlInExternal('{{link}}')" class="external-link">{{name}}</a>
</li>
{{/each}}
{{#each docs}}
<li>
<a href="javascript:openUrlInExternal('{{link}}')" class="file-link">{{name}}</a>
</li>
{{/each}}
</ul>
{{/ifCond}}
</div>
{{/each}}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END plenary-tpl detail -->
<!-- controll-tpl -->
<script id="controll-tpl" type="text/x-handlebars-template">
<div class="controll-tpl">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Парламентарен контрол</h1>
<button class="search-btn button button-icon" id="btnSearchControll">
<img src="assets/img/search-icon.png" alt="ico" class="ico">
</button>
</div>
<div class="row search-row">
<div class="col hidden" id="searchBoxControll">
<div class="search-wrapper">
<input type="text" placeholder="Търси парламентарен контрол" class="search-field" id="txtSearchControll" />
</div>
</div>
</div>
<div class="row">
<div class="col content-wrapper" id="scrollingContent">
{{#each controll}}
<div class="row short-preview controllListItem" data-list-item-id="{{cid}}">
<div class="col">
<!--<div class="row">
<h2 class="title">Парламентарен контрол</h2>
</div>-->
<div class="row">
<div class="col-67 description" onclick="openAppUrl('#controllDetail?id={{cid}}');">
{{{dscrShort}}}
</div>
<div class="col-33">
<div class="custom-row">
<div class="date">{{date}}</div>
</div>
<div class="custom-row">
<button class="button icon-left ion-eye preview-btn" onclick="openAppUrl('#controllDetail?id={{cid}}');">
<span class="txt">Преглед</span>
</button>
</div>
</div>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- controll-tpl detail -->
<script id="controll-tpl-detail-preview" type="text/x-handlebars-template">
<div class="controll-tpl-detail-preview">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Парламентарен контрол</h1>
</div>
<div class="row screen-wrapper">
<div class="col content-wrapper">
<div class="row detail-preview">
<div class="col">
<div class="row">
<h2 class="title">Парламентарен контрол</h2>
</div>
<div class="row">
<div class="custom-row">
<div class="date">{{date}}</div>
</div>
</div>
<div class="row">
<div class="col description">
Парламентарен контрол - {{time}} </br>
{{#each agenda}}
<div style="margin-top: 15px;">
<strong>{{idRom}}. {{answerer}} ще отговори на:</strong><br />
{{#each questWithAutor}}
{{this}}<br />
{{/each}}
</div>
{{/each}}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END controll-tpl detail -->
<!-- committee-tpl -->
<script id="committee-tpl" type="text/x-handlebars-template">
<div class="committee-tpl">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Заседания на комисии</h1>
<button class="subscribe-list-btn button button-icon" id="committeesListButton">
<img src="assets/img/check-list-icon.png" alt="ico" class="ico">
</button>
<!--<button class="search-btn button button-icon" id="btnSearchCommittee">
<img src="assets/img/search-icon.png" alt="ico" class="ico">
</button>-->
</div>
<div class="row search-row">
<div class="col" id="searchBoxCommittee">
<div class="search-wrapper">
<input type="text" placeholder="Търси заседание" class="search-field" id="txtSearchCommittee" />
</div>
</div>
</div>
<div class="row" style="margin-top: 50px;">
<div class="col content-wrapper" id="scrollingContent">
{{#each committee}}
<div class="row short-preview committeeListItem" data-list-item-id="{{cid}}">
<div class="col">
<div class="row">
<h2 class="title">{{committeeName}}</h2>
</div>
<div class="row">
<div class="col-67 description">
{{{dscrShort}}}
</div>
<div class="col-33">
<div class="custom-row">
<div class="date">{{date}}</div>
</div>
<div class="custom-row">
<button class="button icon-left ion-eye preview-btn" onclick="openAppUrl('#committeeDetail?id={{cid}}');">
<span class="txt">Преглед</span>
</button>
</div>
</div>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END controll-tpl detail -->
<!-- committee-tpl detail -->
<script id="committee-tpl-detail-preview" type="text/x-handlebars-template">
<div class="committee-tpl-detail-preview">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Заседания на комисии</h1>
</div>
<div class="row screen-wrapper">
<div class="col content-wrapper">
<div class="row detail-preview">
<div class="col">
<div class="row">
<h2 class="title">Заседание на {{committeeName}}</h2>
</div>
<div class="row">
<div class="custom-row">
<div class="date">{{date}}</div>
<div class="time">{{time}}</div>
</div>
</div>
<div class="row">
<div class="custom-row address">
<span>{{building}}</span>, зала <span>{{hall}}</span>
</div>
</div>
<div class="row">
<div class="col description">
{{{agenda}}}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END committee-tpl detail -->
<!-- committee-check-list-tpl -->
<script id="committee-check-list-tpl" type="text/x-handlebars-template">
<div class="committee-check-list-tpl" style="height: 93%; overflow: auto;">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Абонамент за комисии</h1>
</div>
<div class="row screen-wrapper">
<div class="col content-wrapper">
{{#each commsList}}
<div class="row short-preview">
<div class="col">
<div class="row relative">
<div class="col description">
<h2 class="title {{#ifCond isSubscribed '0'}}unsubscribedText{{/ifCond}}">
<span class="subscribe-btn {{#ifCond isSubscribed '1'}}active{{/ifCond}} ion-checkmark-circled" data-committee-id="{{commId}}"></span>
{{commName}}
</h2>
</div>
</div>
<div class="row">
<div class="col description">
Председател: <strong>{{chairman}}</strong>
</div>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="tabs tabs-icon-top bottom-tabs">
<button href="javascript:void(0)" id="btn_comm_list_save" class="button icon-left ion-compose save-btn"><span class="txt">Запис</span></button>
</div>
</div>
</script>
<!-- END committee-check-list-tpl -->
<!-- news tpl -->
<script id="news-tpl" type="text/x-handlebars-template">
<div class="news-tpl">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Новини</h1>
<button class="search-btn button button-icon" id="btnSearchNews">
<img src="assets/img/search-icon.png" alt="ico" class="ico">
</button>
</div>
<div class="row search-row">
<div class="col hidden" id="searchBoxNews">
<div class="search-wrapper">
<input type="text" placeholder="Търсене на новини" class="search-field" id="txtSearchNews" />
</div>
</div>
</div>
<div class="row">
<div class="col content-wrapper" id="scrollingContent">
{{#each news}}
<div class="row short-preview newsListItem" data-list-item-id="{{nid}}">
<div class="col">
<div class="row" onclick="openAppUrl('#newsDetail?id={{nid}}');">
<h2 class="title">{{title}}</h2>
</div>
<div class="row">
<div class="col">
<div class="date">{{pubDate}}</div>
</div>
<div class="col">
<button class="button icon-left ion-eye preview-btn" onclick="openAppUrl('#newsDetail?id={{nid}}');">
<span class="txt">Преглед</span>
</button>
</div>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END news-tpl detail -->
<!-- news-tpl detail -->
<script id="news-tpl-detail-preview" type="text/x-handlebars-template">
<div class="news-tpl-detail-preview">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Преглед на новина</h1>
</div>
<div class="row screen-wrapper">
<div class="col content-wrapper">
<div class="row detail-preview">
<div class="col">
<div class="row">
<h2 class="title">{{title}}</h2>
</div>
<div class="row">
<div class="custom-row">
<div class="date">{{pubDate}}</div>
</div>
</div>
<div class="row">
<div class="col description">
<img src="http://www.parliament.bg/pub/Gallery/{{img}}" />
{{{dscr}}}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END news-tpl detail -->
<!-- options-tpl -->
<script id="options-tpl" type="text/x-handlebars-template">
<div class="options-tpl">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Настройки</h1>
</div>
<div class="row">
<div class="col content-wrapper">
<ul class="list">
<li class="item item-toggle" id="liNotifications">
Позволи известия от приложението
<label class="toggle toggle-assertive">
<input type="checkbox" id="chkNotifications" {{#ifCond appNotifAllowed '1'}}checked{{/ifCond}} />
<div class="track">
<div class="handle"></div>
</div>
</label>
</li>
</ul>
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" onclick="javascript:history.back(1)">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
</div>
</div>
</script>
<!-- END options-tpl -->
<!-- bills-tpl -->
<script id="bills-tpl" type="text/x-handlebars-template">
<div class="bills-tpl">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Законопроекти</h1>
<button class="search-btn button button-icon" id="btnSearchBills">
<img src="assets/img/search-icon.png" alt="ico" class="ico">
</button>
</div>
<div class="row search-row">
<div class="col hidden" id="searchBoxBills">
<div class="search-wrapper">
<input type="text" placeholder="Търси законопроекти" class="search-field" id="txtSearchBills" />
</div>
</div>
</div>
<div class="row">
<div class="col content-wrapper" id="scrollingContent">
{{#each bills}}
<div class="row short-preview billsListItem" data-list-item-id="{{bid}}">
<div class="col">
<div class="row" onclick="openAppUrl('#billsDetailUrl?id={{bid}}');">
<h2 class="title">{{billName}}</h2>
</div>
<div class="row">
<div class="col-67 description-labels">
<div class="label">Вносители:</div>
<div class="txt">{{{importersShort}}}</div>
</div>
<div class="col-33">
<div class="custom-row">
<div class="date">{{billDate}}</div>
</div>
<div class="custom-row">
<button class="button icon-left ion-eye preview-btn" onclick="openAppUrl('#billsDetailUrl?id={{bid}}');">
<span class="txt">Преглед</span>
</button>
</div>
</div>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END bills-tpl -->
<!-- bills-tpl-detail-preview -->
<script id="bills-tpl-detail-preview" type="text/x-handlebars-template">
<div class="bills-tpl-detail-preview">
<div class="bar bar-header" style="position: fixed;">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Преглед на законопроект</h1>
</div>
<div class="row">
<div class="col content-wrapper" id="scrollingContent">
<div class="row detail-preview">
<div class="col">
<div class="row">
<h2 class="title">{{billName}}</h2>
</div>
<div class="row">
<div class="col description-labels">
<div class="label">Сигнатура:</div>
<div class="txt">{{signature}}</div>
</div>
</div>
<div class="row">
<div class="col description-labels">
<div class="label">Дата на постъпване:</div>
<div class="txt">{{billDate}}</div>
</div>
</div>
<div class="row">
<div class="col description-labels">
<div class="label">Сесия:</div>
<div class="txt">{{session}}</div>
</div>
</div>
{{#ifCond filesDisplay 1}}
<div class="row">
<div class="col description-labels">
<div class="label">Текст на законопроекта:</div>
<div class="txt">
{{#each files}}
<a href="javascript:openUrlInExternal('{{link}}')" class="file-link">{{type}} формат</a>
{{/each}}
</div>
</div>
</div>
{{/ifCond}}
<div class="row">
<div class="col description-labels">
<div class="label">Вносители:</div>
<div class="txt">
<ul class="description-list">
{{#each importers}}
<li>{{this}}</li>
{{/each}}
</ul>
</div>
</div>
</div>
{{#ifCond commsDisplay 1}}
<div class="row">
<div class="col description-labels">
<div class="label">Разпределение по комисии:</div>
<div class="txt">
<ul class="description-list">
{{#each comms}}
<li>{{name}} ({{role}})</li>
{{/each}}
</ul>
</div>
</div>
</div>
{{/ifCond}}
{{#ifCond reportsDisplay 1}}
<div class="row">
<div class="col description-labels">
<div class="label">Доклади от комисии:</div>
<div class="txt">
<ul class="description-list">
{{#each reports}}
<li><a href="javascript:openUrlInExternal('{{link}}')" class="normal-link">{{author}}</a></li>
{{/each}}
</ul>
</div>
</div>
</div>
{{/ifCond}}
{{#ifCond chronoDisplay 1}}
<div class="row">
<div class="col description-labels">
<div class="label">Хронология:</div>
<div class="txt">
<ul class="description-list">
{{#each chrono}}
<li>{{date}} - {{status}}</li>
{{/each}}
</ul>
</div>
</div>
</div>
{{/ifCond}}
{{#ifCond decided 1}}
<div class="row">
<div class="col description-labels">
<div class="label">Статус:</div>
<div class="txt">приет</div>
</div>
</div>
<div class="row">
<div class="col description-labels">
<div class="label">Обнародван в ДВ:</div>
<div class="txt">брой {{dvNo}}/{{dvYear}}</div>
</div>
</div>
{{/ifCond}}
</div>
</div>
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END bills-tpl-detail-preview -->
<!-- mps-tpl -->
<script id="mps-tpl" type="text/x-handlebars-template">
<div class="mps-tpl">
<div class="bar bar-header">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Народни представители</h1>
<button class="search-btn button button-icon" id="btnSearchMPs">
<img src="assets/img/search-icon.png" alt="ico" class="ico">
</button>
</div>
<div class="row search-row">
<div class="col hidden" id="searchBoxMPs">
<div class="search-wrapper">
<input type="text" placeholder="Търси народни представители" class="search-field" id="txtSearchMPs" />
</div>
</div>
</div>
<div class="row">
<div class="col content-wrapper" id="scrollingContent">
<div class="row section-tabs">
<div class="col tab active" id="mpTabAZ">
<div class="flag-active"></div>
А-Я
</div>
<div class="col tab" id="mpTabGroups">
<div class="flag-active"></div>
ПГ
</div>
<div class="col col-33 tab" id="mpTabComms">
<div class="flag-active"></div>
Комисии
</div>
<div class="col col-33 tab" id="mpTabAreas">
<div class="flag-active"></div>
Район
</div>
</div>
{{#each mps}}
<div class="row short-preview mpsListItem" data-list-item-id="{{mpId}}">
<div class="profile-image" style="background-image: url(http://www.parliament.bg/images/Assembly/{{mpId}}.png)"></div>
<div class="col">
<div class="row">
<h2 class="name">{{mpFName}} {{mpSName}} {{mpFamily}}</h2>
</div>
<div class="row">
<ul class="col col-67 info">
<li>{{politForce}}</li>
<li>{{izbRajon}}</li>
</ul>
<button class="button icon-left ion-eye preview-btn" onclick="openAppUrl('#mpDetailUrl?mpId={{mpId}}');">
<span class="txt">Преглед</span>
</button>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END mps-tpl -->
<!-- mp-area-tpl -->
<script id="mp-area-tpl" type="text/x-handlebars-template">
<div class="mp-area-tpl">
<div class="bar bar-header">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Народни представители</h1>
<!--<button class="search-btn button button-icon" id="btnSearchAreas">
<img src="assets/img/search-icon.png" alt="ico" class="ico">
</button>-->
</div>
<!--<div class="row search-row">
<div class="col hidden" id="searchBoxAreas">
<div class="search-wrapper">
<input type="text" placeholder="Търси народни представители" class="search-field" id="txtSearchAreas" />
</div>
</div>
</div>-->
<div class="row">
<div class="col content-wrapper" id="scrollingContent">
<div class="row section-tabs">
<div class="col tab" id="mpTabAZ">
<div class="flag-active"></div>
А-Я
</div>
<div class="col tab" id="mpTabGroups">
<div class="flag-active"></div>
ПГ
</div>
<div class="col col-33 tab" id="mpTabComms">
<div class="flag-active"></div>
Комисии
</div>
<div class="col col-33 tab active" id="mpTabAreas">
<div class="flag-active"></div>
Район
</div>
</div>
{{#each areas}}
<div class="row short-preview">
<div class="col">
<div class="row">
<h2 class="name">{{areaName}}</h2>
<button class="button icon-left ion-eye preview-btn" onclick="openAppUrl('#mpAZList?areaId={{areaId}}');">
<span class="txt">Преглед</span>
</button>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END mp-area-tpl -->
<!-- mp-groups-tpl -->
<script id="mp-groups-tpl" type="text/x-handlebars-template">
<div class="mp-groups-tpl">
<div class="bar bar-header">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Народни представители</h1>
<!--<button class="search-btn button button-icon" id="btnSearchGroups">
<img src="assets/img/search-icon.png" alt="ico" class="ico">
</button>-->
</div>
<!--<div class="row search-row">
<div class="col hidden" id="searchBoxGroups">
<div class="search-wrapper">
<input type="text" placeholder="Търси народни представители" class="search-field" id="txtSearchGroups" />
</div>
</div>
</div>-->
<div class="row">
<div class="col content-wrapper" id="scrollingContent">
<div class="row section-tabs">
<div class="col tab" id="mpTabAZ">
<div class="flag-active"></div>
А-Я
</div>
<div class="col tab active" id="mpTabGroups">
<div class="flag-active"></div>
ПГ
</div>
<div class="col col-33 tab" id="mpTabComms">
<div class="flag-active"></div>
Комисии
</div>
<div class="col col-33 tab" id="mpTabAreas">
<div class="flag-active"></div>
Район
</div>
</div>
{{#each structs}}
<div class="row short-preview">
<div class="col">
<div class="row">
<h2 class="name">{{structName}}</h2>
</div>
<div class="row">
<ul class="col info">
<li><span class="bold">{{structMembers}}</span> народни представители</li>
</ul>
<button class="button icon-left ion-eye preview-btn" onclick="openAppUrl('#mpAZList?groupId={{structId}}');">
<span class="txt">Преглед</span>
</button>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END mp-groups-tpl -->
<!-- mp-committees-tpl -->
<script id="mp-committees-tpl" type="text/x-handlebars-template">
<div class="mp-committees-tpl">
<div class="bar bar-header">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Народни представители</h1>
<!--<button class="search-btn button button-icon" id="btnSearchGroups">
<img src="assets/img/search-icon.png" alt="ico" class="ico">
</button>-->
</div>
<!--<div class="row search-row">
<div class="col hidden" id="searchBoxGroups">
<div class="search-wrapper">
<input type="text" placeholder="Търси народни представители" class="search-field" id="txtSearchGroups" />
</div>
</div>
</div>-->
<div class="row">
<div class="col content-wrapper" id="scrollingContent">
<div class="row section-tabs">
<div class="col tab" id="mpTabAZ">
<div class="flag-active"></div>
А-Я
</div>
<div class="col tab" id="mpTabGroups">
<div class="flag-active"></div>
ПГ
</div>
<div class="col col-33 tab active" id="mpTabComms">
<div class="flag-active"></div>
Комисии
</div>
<div class="col col-33 tab" id="mpTabAreas">
<div class="flag-active"></div>
Район
</div>
</div>
{{#each structs}}
<div class="row short-preview">
<div class="col">
<div class="row">
<h2 class="name">{{structName}}</h2>
</div>
<div class="row">
<ul class="col info">
<li><span class="bold">{{structMembers}}</span> народни представители</li>
</ul>
<button class="button icon-left ion-eye preview-btn" onclick="openAppUrl('#mpAZList?committeeId={{structId}}');">
<span class="txt">Преглед</span>
</button>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END mp-committees-tpl -->
<!-- mps-tpl-detail-preview -->
<script id="mps-tpl-detail-preview" type="text/x-handlebars-template">
<div class="mps-tpl-detail-preview">
<div class="bar bar-header">
<a href="javascript:void(0)" id="open-left" class="ion-navicon-round side-menu-btn"></a>
<h1 class="title">Народeн представител</h1>
</div>
<div class="row">
<div class="col content-wrapper">
<div class="row short-preview">
<div class="col">
<div class="row">
<div class="profile-image" style="background-image: url(http://www.parliament.bg/images/Assembly/{{mpId}}.png)"></div>
</div>
<div class="row">
<h2 class="name">{{mpFName}} {{mpSName}} {{mpFamily}}</h2>
</div>
<div class="row">
<ul class="col detail-info">
<li><span class="label">Дата на раждане:</span><span class="txt">{{dateOfBirth}}</span></li>
<li><span class="label">Месторождение:</span><span class="txt">{{placeOfBirth}}</span></li>
<li><span class="label">E-mail:</span><span class="txt"><a href="mailto:{{email}}">{{email}}</a></span></li>
<li><span class="label">Политическа сила:</span><span class="txt">{{politicalForce}}</span></li>
<li><span class="label">Изборен район:</span><span class="txt">{{izbRajon}}</span></li>
<li><span class="label">Eзици:</span><span class="txt">{{langs}}</span></li>
<li><span class="label">професия:</span><span class="txt">{{profession}}</span></li>
<!--<li><span class="label">семейно положение:</span><span class="txt">{{maritalStatus}}</span></li>-->
</ul>
</div>
</div>
</div>
<div class="row info-section">
<h2 class="section-title">Парламентарна дейност</h2>
</div>
{{#each structs}}
<div class="row short-preview info-section">
<div class="col">
<div class="row">
<h2 class="name">{{name}}</h2>
</div>
<div class="row">
<ul class="col info">
<li><span class="bold">{{position}}</span> {{sdate}} - {{edate}}</li>
</ul>
</div>
</div>
</div>
{{/each}}
<div class="row info-section">
<h2 class="section-title">Внесени законопроекти</h2>
</div>
{{#each bills}}
<div class="row short-preview info-section">
<div class="col">
<div class="row">
<h2 class="name">
<a class="external-link" href="javascript:openUrlInExternal('{{link}}')">{{billName}}</a>
</h2>
</div>
</div>
</div>
{{/each}}
</div>
</div>
<div class="bar bar-footer">
<button class="back-btn button button-icon" id="footerBackButton">
<img src="assets/img/back-arrow.png" alt="ico" class="ico">
</button>
<button class="button button-icon ion-ios7-gear" id="footerSettingsButton"></button>
</div>
</div>
</script>
<!-- END mps-tpl-detail-preview -->
<div class="snap-drawers">
<div class="snap-drawer snap-drawer-left left-menu">
<div class="row header">
<div class="col-25 armorial">
<img src="assets/img/bulgarian-armorial.svg" alt="bulgarian-armorial">
</div>
<div class="col-75 title center">
<h1>Народно събрание на</h1>
<h2>република България</h2>
</div>
</div>
<div class="row">
<h3 class="group-title">Меню</h3>
</div>
<ul class="menu-sections">
<li class="row liMainMenuItem" id="liMainMenuPlenaries">
<a href="javascript:void(0);" class="col section" id="mainMenuPlenary">
<span class="flag-active"></span>
<span class="flag-new">ново</span>
<span class="ico"><img src="assets/img/plenary-ico-dark.svg" class="section-icons plenary-ico"></span>
<span class="txt">Пленарни заседания</span>
</a>
</li>
<li class="row liMainMenuItem" id="liMainMenuControll">
<a href="javascript:void(0);" class="col section" id="mainMenuControll">
<span class="flag-active"></span>
<span class="flag-new">ново</span>
<span class="ico"><img src="assets/img/controll-ico-dark.svg" class="section-icons controll-ico"></span>
<span class="txt">Парламентарен контрол</span>
</a>
</li>
<li class="row liMainMenuItem" id="liMainMenuCommittee">
<a href="javascript:void(0);" class="col section" id="mainMenuCommittee">
<span class="flag-active"></span>
<span class="flag-new">ново</span>
<span class="ico"><img src="assets/img/committee-ico-dark.svg" class="section-icons committee-ico"></span>
<span class="txt">Заседания на комисии</span>
</a>
</li>
<li class="row liMainMenuItem" id="liMainMenuBills">
<a href="javascript:void(0);" class="col section" id="mainMenuBills">
<span class="flag-active"></span>
<span class="flag-new">ново</span>
<span class="ico"><img src="assets/img/bills-ico.png" class="section-icons bills-ico"></span>
<span class="txt">Законопроекти</span>
</a>
</li>
<li class="row liMainMenuMPs" id="liMainMenuMPs">
<a href="javascript:void(0);" class="col section" id="mainMenuMPs">
<span class="flag-active"></span>
<span class="flag-new">ново</span>
<span class="ico"><img src="assets/img/MPs-ico.png" class="section-icons mps-ico"></span>
<span class="txt">Народни представители</span>
</a>
</li>
<li class="row liMainMenuItem" id="liMainMenuNews">
<a href="javascript:void(0);" class="col section" id="mainMenuNews">
<span class="flag-active"></span>
<span class="flag-new">ново</span>
<span class="ico"><img src="assets/img/news-ico-dark.svg" class="section-icons news-ico"></span>
<span class="txt">Новини</span>
</a>
</li>
</ul>
</div>
<div class="snap-drawer snap-drawer-right"></div>
</div>
<div id="content" class="snap-content">
<div id="page-placeholder" class="placeholder-container" data-snap-ignore="true">
</div>
</div>
<script type="text/javascript" src="js/tools.js"></script>
<script src="cordova.js"></script>
<script src="lib/jquery.js"></script>
<script src="lib/fastclick.js"></script>
<script src="lib/handlebars.js"></script>
<script src="lib/snap.js"></script>
<script src="lib/cryptojs/core-min.js"></script>
<script src="lib/cryptojs/md5-min.js"></script>
<script src="js/adapters/FileStorage.js"></script>
<script src="js/UpdateDataProcessor.js"></script>
<script src="js/AppSettings.js"></script>
<script src="js/HomeView.js"></script>
<script src="js/PlenaryView.js"></script>
<script src="js/ControllView.js"></script>
<script src="js/CommitteeView.js"></script>
<script src="js/CommitteesListView.js"></script>
<script src="js/NewsView.js"></script>
<script src="js/BillsView.js"></script>
<script src="js/MPsView.js"></script>
<script src="js/VotingAreasView.js"></script>
<script src="js/ParlamStructsView.js"></script>
<script src="js/OptionsView.js"></script>
<script src="lib/snap.js"></script>
<script type="text/javascript">
var snapper = new Snap({
element: document.getElementById('content'),
disable: 'right'
});
assignSliderOpenHandler();
</script>
<!-- keep this last in import list because it uses most of above scripts and executes on include -->
<script src="js/app.js"></script>
</body>
</html>
|
momchilk/prlmnt_act
|
www/index.html
|
HTML
|
apache-2.0
| 40,766 |
/*
* 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 java.net;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* This class represents a socket endpoint described by a IP address and a port
* number. It is a concrete implementation of {@code SocketAddress} for IP.
*/
public class InetSocketAddress extends SocketAddress {
private static final long serialVersionUID = 5076001401234631237L;
private String hostname;
private InetAddress addr;
private int port;
private transient boolean gotHostname = false;
/**
* Creates a socket endpoint with the given port number {@code port} and the
* wildcard address {@code InetAddress.ANY}. The range for valid port numbers
* is between 0 and 65535 inclusive.
*
* @param port
* the specified port number to which this socket is bound.
*/
public InetSocketAddress(int port) {
this((InetAddress) null, port);
}
/**
* Creates a socket endpoint with the given port number {@code port} and
* {@code address}. The range for valid port numbers is between 0 and 65535
* inclusive. If {@code address} is {@code null} this socket is bound to the
* wildcard address {@code InetAddress.ANY}.
*
* @param port
* the specified port number to which this socket is bound.
* @param address
* the specified address to which this socket is bound.
*/
public InetSocketAddress(InetAddress address, int port) {
if (port < 0 || port > 65535) {
throw new IllegalArgumentException();
}
if (address == null) {
addr = InetAddress.ANY;
} else {
addr = address;
}
hostname = addr.getHostName();
this.port = port;
}
/**
* Creates a socket endpoint with the given port number {@code port} and the
* hostname {@code host}. The hostname is tried to be resolved and cannot be
* {@code null}. The range for valid port numbers is between 0 and 65535
* inclusive.
*
* @param port
* the specified port number to which this socket is bound.
* @param host
* the specified hostname to which this socket is bound.
* @throws SecurityException
* if a {@link SecurityManager} is installed and its {@code
* checkConnect()} method does not allow the resolving of the
* host name.
*/
public InetSocketAddress(String host, int port) {
this(host, port, true);
}
/*
* Internal constructor for InetSocketAddress(String, int) and
* createUnresolved(String, int);
*/
InetSocketAddress(String host, int port, boolean needResolved) {
if (host == null || port < 0 || port > 65535) {
throw new IllegalArgumentException();
}
hostname = host;
this.port = port;
if (needResolved) {
try {
addr = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
// Ignored
}
} else {
addr = null;
}
}
/**
* Creates an {@code InetSocketAddress} without trying to resolve the
* hostname into an {@code InetAddress}. The address field is marked as
* unresolved.
*
* @param host
* the specified hostname to which this socket is bound.
* @param port
* the specified port number to which this socket is bound.
* @return the created InetSocketAddress instance.
* @throws IllegalArgumentException
* if the hostname {@code host} is {@code null} or the port is
* not in the range between 0 and 65535.
*/
public static InetSocketAddress createUnresolved(String host, int port) {
return new InetSocketAddress(host, port, false);
}
/**
* Gets the port number of this socket.
*
* @return the socket endpoint port number.
*/
public final int getPort() {
return port;
}
/**
* Gets the address of this socket.
*
* @return the socket endpoint address.
*/
public final InetAddress getAddress() {
return addr;
}
/**
* Gets the hostname of this socket.
*
* @return the socket endpoint hostname.
*/
public final String getHostName() {
if (addr != null && !gotHostname) {
gotHostname = true;
hostname = addr.getHostName();
}
return hostname;
}
/**
* Returns whether this socket address is unresolved or not.
*
* @return {@code true} if this socket address is unresolved, {@code false}
* otherwise.
*/
public final boolean isUnresolved() {
return addr == null;
}
/**
* Gets a string representation of this socket included the address and the
* port number.
*
* @return the address and port number as a textual representation.
*/
@Override
public String toString() {
String host;
if (addr != null) {
host = addr.toString();
} else {
host = hostname;
}
return host + ":" + port; //$NON-NLS-1$
}
/**
* Compares two socket endpoints and returns true if they are equal. Two
* socket endpoints are equal if the IP address or the hostname of both are
* equal and they are bound to the same port.
*
* @param socketAddr
* the object to be tested for equality.
* @return {@code true} if this socket and the given socket object {@code
* socketAddr} are equal, {@code false} otherwise.
*/
@Override
public final boolean equals(Object socketAddr) {
if (this == socketAddr) {
return true;
}
if (!(socketAddr instanceof InetSocketAddress)) {
return false;
}
InetSocketAddress iSockAddr = (InetSocketAddress) socketAddr;
// check the ports as we always need to do this
if (port != iSockAddr.port) {
return false;
}
// we only use the hostnames in the comparison if the addrs were not
// resolved
if ((addr == null) && (iSockAddr.addr == null)) {
return hostname.equals(iSockAddr.hostname);
}
// addrs were resolved so use them for the comparison
if (addr == null) {
// if we are here we know iSockAddr is not null so just return
// false
return false;
}
return addr.equals(iSockAddr.addr);
}
/**
* Gets the hashcode of this socket.
*
* @return the appropriate hashcode.
*/
@Override
public final int hashCode() {
if (addr == null) {
return hostname.hashCode() + port;
}
return addr.hashCode() + port;
}
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
stream.defaultReadObject();
}
}
|
freeVM/freeVM
|
enhanced/java/classlib/modules/luni/src/main/java/java/net/InetSocketAddress.java
|
Java
|
apache-2.0
| 7,919 |
/*
* Copyright 2017-present Open Networking Foundation
*
* 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.atomix.protocols.raft.session;
/**
* Session recovery strategy.
*/
public enum RecoveryStrategy {
/**
* Indicates that the session should be recovered when lost.
*/
RECOVER,
/**
* Indicates that the session should be closed when lost.
*/
CLOSE,
}
|
atomix/atomix
|
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RecoveryStrategy.java
|
Java
|
apache-2.0
| 896 |
/*
* (c) Copyright Christian P. Fries, Germany. Contact: [email protected].
*
* Created on 26.12.2012
*/
package net.finmath.marketdata.products;
import net.finmath.marketdata.model.AnalyticModel;
import net.finmath.marketdata.model.curves.DiscountCurve;
import net.finmath.marketdata.model.curves.ForwardCurve;
/**
* Implements the valuation of a forward using curves (discount curve, forward curve).
* The forward value is simply the product of a discount factor and a forward.
* This is similar to a FRA (a forward rate), except that there is no scaling with a period length.
*
* The class can be used to define equity forwards. Here the discount curve can be interpreted
* as a repo curve.
*
* @author Christian Fries
* @version 1.0
*/
public class Forward extends AbstractAnalyticProduct implements AnalyticProduct {
private final double maturity;
private final double paymentOffset;
private final String forwardCurveName;
private final double spread;
private final String discountCurveName;
/**
* Creates a forward. The forward has a unit notional of 1.
*
* @param maturity Maturity, i.e., fixing on the forward curve.
* @param paymentOffset Payment offset, i.e. payment is maturity + paymentOffset.
* @param forwardCurveName Name of the forward curve, leave empty if this is a fix payment.
* @param spread Additional fixed payment (if any).
* @param discountCurveName Name of the discount curve for the forward.
*/
public Forward(final double maturity, final double paymentOffset, final String forwardCurveName, final double spread, final String discountCurveName) {
super();
this.maturity = maturity;
this.paymentOffset = paymentOffset;
this.forwardCurveName = forwardCurveName;
this.spread = spread;
this.discountCurveName = discountCurveName;
}
/* (non-Javadoc)
* @see net.finmath.marketdata.products.AnalyticProductInterface#getValue(double, net.finmath.marketdata.model.AnalyticModelInterface)
*/
@Override
public double getValue(final double evaluationTime, final AnalyticModel model) {
final ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);
final DiscountCurve discountCurve = model.getDiscountCurve(discountCurveName);
DiscountCurve discountCurveForForward = null;
if(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {
// User might like to get forward from discount curve.
discountCurveForForward = model.getDiscountCurve(forwardCurveName);
if(discountCurveForForward == null) {
// User specified a name for the forward curve, but no curve was found.
throw new IllegalArgumentException("No curve of the name " + forwardCurveName + " was found in the model.");
}
}
double forward = spread;
if(forwardCurve != null) {
forward += forwardCurve.getForward(model, maturity);
}
else if(discountCurveForForward != null) {
forward += (discountCurveForForward.getDiscountFactor(maturity) / discountCurveForForward.getDiscountFactor(maturity+paymentOffset) - 1.0) / paymentOffset;
}
final double discountFactor = maturity+paymentOffset > evaluationTime ? discountCurve.getDiscountFactor(model, maturity+paymentOffset) : 0.0;
return forward * discountFactor / discountCurve.getDiscountFactor(model, evaluationTime);
}
}
|
finmath/finmath-lib
|
src/main/java8/net/finmath/marketdata/products/Forward.java
|
Java
|
apache-2.0
| 3,333 |
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# 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 hardware::ups::cyberpower::snmp::plugin;
use strict;
use warnings;
use base qw(centreon::plugins::script_snmp);
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '0.1';
$self->{modes} = {
'battery-status' => 'centreon::common::cps::ups::snmp::mode::batterystatus',
'input-lines' => 'centreon::common::cps::ups::snmp::mode::inputlines',
'output-lines' => 'centreon::common::cps::ups::snmp::mode::outputlines'
};
return $self;
}
1;
__END__
=head1 PLUGIN DESCRIPTION
Check UPS CyberPower Systems in SNMP.
=cut
|
Tpo76/centreon-plugins
|
hardware/ups/cyberpower/snmp/plugin.pm
|
Perl
|
apache-2.0
| 1,389 |
<!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_72-internal) on Mon Mar 14 13:22:07 GMT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Revisioned (Apache Taverna Language APIs (Scufl2, Databundle) 0.15.1-incubating API)</title>
<meta name="date" content="2016-03-14">
<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="Revisioned (Apache Taverna Language APIs (Scufl2, Databundle) 0.15.1-incubating API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":6,"i2":6,"i3":6,"i4":6,"i5":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/Revisioned.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/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/taverna/scufl2/api/annotation/Revisioned.html" target="_top">Frames</a></li>
<li><a href="Revisioned.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>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </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.taverna.scufl2.api.annotation</div>
<h2 title="Interface Revisioned" class="title">Interface Revisioned</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html?is-external=true" title="class or interface in java.lang">Cloneable</a>, <a href="../../../../../../org/apache/taverna/scufl2/api/common/WorkflowBean.html" title="interface in org.apache.taverna.scufl2.api.common">WorkflowBean</a></dd>
</dl>
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../../org/apache/taverna/scufl2/api/common/AbstractRevisioned.html" title="class in org.apache.taverna.scufl2.api.common">AbstractRevisioned</a>, <a href="../../../../../../org/apache/taverna/scufl2/api/profiles/Profile.html" title="class in org.apache.taverna.scufl2.api.profiles">Profile</a>, <a href="../../../../../../org/apache/taverna/scufl2/api/core/Workflow.html" title="class in org.apache.taverna.scufl2.api.core">Workflow</a>, <a href="../../../../../../org/apache/taverna/scufl2/api/container/WorkflowBundle.html" title="class in org.apache.taverna.scufl2.api.container">WorkflowBundle</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="typeNameLabel">Revisioned</span>
extends <a href="../../../../../../org/apache/taverna/scufl2/api/common/WorkflowBean.html" title="interface in org.apache.taverna.scufl2.api.common">WorkflowBean</a></pre>
<div class="block">A WorkflowBean that is revisioned.
<p>
Revisions are expressed as a chain of <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation"><code>Revision</code></a>s linking to the
<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html#getPreviousRevision--"><code>Revision.getPreviousRevision()</code></a>s. The Revision metadata also may
include when and who did the revision.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation">Revision</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getCurrentRevision--">getCurrentRevision</a></span>()</code>
<div class="block">Get the current Revision metadata.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/7/docs/api/java/net/URI.html?is-external=true" title="class or interface in java.net">URI</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getIdentifier--">getIdentifier</a></span>()</code>
<div class="block">Returns the identifier of this bean.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation">Revision</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#newRevision--">newRevision</a></span>()</code>
<div class="block">Make a new Revision to mark structural changes to this workflow bean.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation">Revision</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#newRevision-java.net.URI-">newRevision</a></span>(<a href="http://docs.oracle.com/javase/7/docs/api/java/net/URI.html?is-external=true" title="class or interface in java.net">URI</a> revisionIdentifier)</code>
<div class="block">Make a new Revision to mark structural changes to this workflow bean with
the given identifier.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#setCurrentRevision-org.apache.taverna.scufl2.api.annotation.Revision-">setCurrentRevision</a></span>(<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation">Revision</a> currentRevision)</code>
<div class="block">Set the current Revision.</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#setIdentifier-java.net.URI-">setIdentifier</a></span>(<a href="http://docs.oracle.com/javase/7/docs/api/java/net/URI.html?is-external=true" title="class or interface in java.net">URI</a> workflowIdentifier)</code>
<div class="block">Set the identifier.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.org.apache.taverna.scufl2.api.common.WorkflowBean">
<!-- -->
</a>
<h3>Methods inherited from interface org.apache.taverna.scufl2.api.common.<a href="../../../../../../org/apache/taverna/scufl2/api/common/WorkflowBean.html" title="interface in org.apache.taverna.scufl2.api.common">WorkflowBean</a></h3>
<code><a href="../../../../../../org/apache/taverna/scufl2/api/common/WorkflowBean.html#accept-org.apache.taverna.scufl2.api.common.Visitor-">accept</a>, <a href="../../../../../../org/apache/taverna/scufl2/api/common/WorkflowBean.html#clone--">clone</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getCurrentRevision--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getCurrentRevision</h4>
<pre><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation">Revision</a> getCurrentRevision()</pre>
<div class="block">Get the current Revision metadata.
<p>
The <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation"><code>Revision</code></a> typically contains information about when it was
made, and links to the previous revision chain.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
</dl>
</li>
</ul>
<a name="setCurrentRevision-org.apache.taverna.scufl2.api.annotation.Revision-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setCurrentRevision</h4>
<pre>void setCurrentRevision(<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation">Revision</a> currentRevision)</pre>
<div class="block">Set the current Revision.
<p>
To preserve the existing revision chain, the new revision should point to
the current revision using <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html#setPreviousRevision-org.apache.taverna.scufl2.api.annotation.Revision-"><code>Revision.setPreviousRevision(Revision)</code></a></div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>currentRevision</code> - The <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation"><code>Revision</code></a> to be set</dd>
</dl>
</li>
</ul>
<a name="newRevision--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>newRevision</h4>
<pre><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation">Revision</a> newRevision()</pre>
<div class="block">Make a new Revision to mark structural changes to this workflow bean.
<p>
The identifier of the new <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getCurrentRevision--"><code>getCurrentRevision()</code></a> will also be
identifying the Revisioned workflow bean and be returned from
<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getIdentifier--"><code>getIdentifier()</code></a>.
<p>
The new revision will include the previous Revision as
<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html#getPreviousRevision--"><code>Revision.getPreviousRevision()</code></a> and
<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html#getGeneratedAtTime--"><code>Revision.getGeneratedAtTime()</code></a> on the new revision will match the
current <a href="http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html?is-external=true" title="class or interface in java.util"><code>GregorianCalendar</code></a> by default.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The new <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getCurrentRevision--"><code>getCurrentRevision()</code></a>, for setting any further
details.</dd>
</dl>
</li>
</ul>
<a name="newRevision-java.net.URI-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>newRevision</h4>
<pre><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation">Revision</a> newRevision(<a href="http://docs.oracle.com/javase/7/docs/api/java/net/URI.html?is-external=true" title="class or interface in java.net">URI</a> revisionIdentifier)</pre>
<div class="block">Make a new Revision to mark structural changes to this workflow bean with
the given identifier.
<p>
<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getIdentifier--"><code>getIdentifier()</code></a> will match the new identifier. The new
<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getCurrentRevision--"><code>getCurrentRevision()</code></a> will include the previous revision as
<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html#getPreviousRevision--"><code>Revision.getPreviousRevision()</code></a>.
<p>
Note, unlike the convenience method <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#newRevision--"><code>newRevision()</code></a> this method
will not update <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html#getGeneratedAtTime--"><code>Revision.getGeneratedAtTime()</code></a>.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>revisionIdentifier</code> - The new workflow identifier</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The new <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getCurrentRevision--"><code>getCurrentRevision()</code></a>, for setting any further
details.</dd>
</dl>
</li>
</ul>
<a name="setIdentifier-java.net.URI-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setIdentifier</h4>
<pre>void setIdentifier(<a href="http://docs.oracle.com/javase/7/docs/api/java/net/URI.html?is-external=true" title="class or interface in java.net">URI</a> workflowIdentifier)</pre>
<div class="block">Set the identifier.
<p>
This will delete any previous revisions in <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getCurrentRevision--"><code>getCurrentRevision()</code></a>.
To avoid loosing history, you might instead want to use
<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#newRevision-java.net.URI-"><code>newRevision(URI)</code></a>.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>workflowIdentifier</code> - the identifier</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getIdentifier--"><code>getIdentifier()</code></a>,
<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getCurrentRevision--"><code>getCurrentRevision()</code></a></dd>
</dl>
</li>
</ul>
<a name="getIdentifier--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getIdentifier</h4>
<pre><a href="http://docs.oracle.com/javase/7/docs/api/java/net/URI.html?is-external=true" title="class or interface in java.net">URI</a> getIdentifier()</pre>
<div class="block">Returns the identifier of this bean.
<p>
This identifier matches the <a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revision.html#getIdentifier--"><code>Revision.getIdentifier()</code></a> of
<a href="../../../../../../org/apache/taverna/scufl2/api/annotation/Revisioned.html#getCurrentRevision--"><code>getCurrentRevision()</code></a>.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the identifier</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><code>#setIdentifier(URI)}</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>
<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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/Revisioned.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/taverna/scufl2/api/annotation/Revision.html" title="class in org.apache.taverna.scufl2.api.annotation"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/taverna/scufl2/api/annotation/Revisioned.html" target="_top">Frames</a></li>
<li><a href="Revisioned.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>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </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–2016 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
|
apache/incubator-taverna-site
|
content/javadoc/taverna-language/org/apache/taverna/scufl2/api/annotation/Revisioned.html
|
HTML
|
apache-2.0
| 20,348 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<link rel="stylesheet" href="../../css/team24/style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<!--link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link type="text/css" rel="stylesheet" href="../../css/team24_3_style.css"/>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script src="../../js/jquery.js"></script>
<link href="../../css/header.css" rel="stylesheet">
<script>
$(function(){
$("#header").load("../headerdouble.html");
});
</script>
<script type="text/javascript" src="../../js/team24/team24_task10c.js"></script>
</head>
<body>
<div id="header"></div>
<ul class="nav navbar-inverse nav-pills nav-justified">
<li><a href="team24_index3.html">Home</a></li>
<li><a href="team24_task4.html">NER in CCA Dataset</a></li>
<li><a href="team24_task5.html">Metadata v/s File Sizes</a></li>
<li><a href="team24_task6a.html">TextExtraction vs Parser Heirarchy</a></li>
<li><a href="team24_task6b.html">Metadata vs Parser Heirarchy</a></li>
<li><a href="team24_task7.html">Language Diversity</a></li>
<li><a href="team24_langcloud.html">Language Word Cloud</a></li>
<li><a href="team24_wordsweet.html">Sweet Concepts Word Cloud</a></li>
<li><a href="team24_ner.html">Comparing NER toolkits</a></li>
<li><a href="team24_ner_file.html">NER on Files</a></li>
<li><a href="team24_task10ab.html">Measurements diversity (By Type)</a></li>
<li class="active"><a href="team24_task10c.html">Measurements diversity (By Domain)</a></li>
<li><a href="team24_task10d.html">Measurements diversity (By MIME Type)</a></li>
<li><a href="#"></a></li>
</ul>
<div id="body">
<div class="jumbotron">
<h2>Measurement Visualizations by particular Domain</h2>
<p style="color:grey;">click or option-click to expand or collapse</p>
</div>
</div>
</body>
</html>
|
USCDataScience/polar.usc.edu
|
html/team24/team24_task10c.html
|
HTML
|
apache-2.0
| 2,296 |
#ifndef _DRAWCURVES_H_
#define _DRAWCURVES_H_
#include <string>
#include <sstream>
#include <fstream>
#include <assertext.h>
#include <Log.h>
using std::string;
using std::stringstream;
namespace UTILITY{
/**
* given a set of points (xi,yi), generate a python script to for drawing this
* curve, and save it to a file.
*/
template<class VECTOR>
class PythonScriptDraw2DCurves{
public:
PythonScriptDraw2DCurves(const bool useLabel=false){
_useLabel = useLabel;
}
static bool write(const string fname,const VECTOR &y,const double dx=1.0,const double x0=0.0f,const string style=""){
VECTOR x(y.size());
for (int i = 0; i < x.size(); ++i){
x[i] = x0+i*dx;
}
return write(fname,y,x,style);
}
static bool write(const string fname,const VECTOR &y,const VECTOR &x,const string style=""){
return realWrite(fname,defineCurve(y,x,"",style),false);
}
void setUseLabel(const bool useLabel){
_useLabel = useLabel;
}
bool add(const string name,const VECTOR &y,const double dx=1.0,const double x0=0.0f,const string style=""){
VECTOR x(y.size());
for (int i = 0; i < x.size(); ++i){
x[i] = x0+i*dx;
}
return add(name,y,x,style);
}
bool add(const string name,const VECTOR &y,const VECTOR &x,const string style=""){
const string curve = defineCurve(y,x,name,style);
_curvesData = _curvesData + "\n" + curve;
return (curve.size() > 0);
}
bool write(const string fname,const string saveFigTo="")const{
return realWrite(fname,_curvesData,isUseLabel(),saveFigTo);
}
void clear(){
_curvesData.clear();
}
bool isUseLabel()const{
return _useLabel;
}
protected:
static string head(){
const string line1("\"\"\"Script generated by PythonScriptDraw2DCurves.\"\"\"\n");
const string line2("import numpy as np\n");
const string line3("import matplotlib.pyplot as plt\n");
return line1+line2+line3;
}
static string end(bool useLabel,const string saveFigTo=""){
string e = "";
if (useLabel)
e += string("plt.legend()\n");
if(saveFigTo.size()>0)
e += string("plt.savefig(\"")+saveFigTo+"\"+\".png\")";
else
e += string("plt.show()");
return e;
}
static string defineCurve(const VECTOR &y,const VECTOR &x,const string name="",const string style=""){
assert_eq(x.size(),y.size());
if(y.size() <= 0){
ERROR_LOG("the input data is zero");
return string("");
}
stringstream script;
const string xName = removeSpaces(name+"_x");
const string yName = removeSpaces(name+"_y");
const string labelCmd = string(",label=\'")+name+"\'";
const string styleCmd = style.size()>0?(string(",\'")+style+string("\'")):(string(""));
script<< xName << " = [" << x[0];
for (int i = 1; i < x.size(); ++i){
script << "," << x[i];
}
script << "];\n";
script << yName << " = [" << y[0];
for (int i = 1; i < y.size(); ++i){
script << "," << y[i];
}
script << "];\n";
script << "plt.plot("<<xName<<","<<yName<<styleCmd<<labelCmd<<");\n";
return script.str();
}
static bool realWrite(const string fname, const string curves,bool useLabel=true,const string saveFigTo=""){
const string script = head()+string("\n")+curves+end(useLabel,saveFigTo);
std::ofstream file;
file.open(string(fname+".py").c_str());
ERROR_LOG_COND("failed to open file for writing: "<<fname,file.is_open());
file << script;
const bool succ = file.is_open();
file.close();
return succ;
}
static string removeSpaces(const string ss){
string s = ss;
for (size_t i = 0; i < s.size(); ++i){
if(s[i] == ' ' || s[i] == '\t'){
s[i] = '_';
}
}
return s;
}
private:
string _curvesData;
bool _useLabel;
};
}
#endif /* _DRAWCURVES_H_ */
|
wegatron/embedded_thin_shell
|
src/volume_simulator/solid_elastic/Common/DrawCurves.h
|
C
|
apache-2.0
| 3,695 |
/*
* Copyright (c) 2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#ifndef EMAC_TEST_NETWORK_STACK_H
#define EMAC_TEST_NETWORK_STACK_H
#include "netsocket/nsapi_types.h"
#include "netsocket/EMAC.h"
#include "netsocket/OnboardNetworkStack.h"
#include "emac_TestMemoryManager.h"
class EmacTestNetworkStack : public OnboardNetworkStack, private mbed::NonCopyable<EmacTestNetworkStack> {
public:
static EmacTestNetworkStack &get_instance();
EmacTestNetworkStack();
virtual ~EmacTestNetworkStack() {}
class Interface : public OnboardNetworkStack::Interface {
public:
static Interface &get_instance();
/** Connect the interface to the network
*
* Sets up a connection on specified network interface, using DHCP or provided network details. If the @a dhcp is set to
* true all the remaining parameters are ignored.
*
* @param dhcp true if the network details should be acquired using DHCP
* @param ip IP address to be used for the interface as "W:X:Y:Z" or NULL
* @param netmask Net mask to be used for the interface as "W:X:Y:Z" or NULL
* @param gw Gateway address to be used for the interface as "W:X:Y:Z" or NULL
* @param stack Allow manual selection of IPv4 and/or IPv6.
* @param blocking Specify whether bringup blocks for connection completion.
* @return NSAPI_ERROR_OK on success, or error code
*/
virtual nsapi_error_t bringup(bool dhcp, const char *ip,
const char *netmask, const char *gw,
nsapi_ip_stack_t stack = DEFAULT_STACK,
bool blocking = true
);
/** Disconnect interface from the network
*
* After this call the network interface is inactive, to use it again user needs to call @a mbed_ipstack_bringup again.
*
* @return NSAPI_ERROR_OK on success, or error code
*/
virtual nsapi_error_t bringdown();
/** Register callback for status reporting
*
* The specified status callback function will be called on status changes
* on the network. The parameters on the callback are the event type and
* event-type dependent reason parameter.
*
* @param status_cb The callback for status changes
*/
virtual void attach(mbed::Callback<void(nsapi_event_t, intptr_t)> status_cb);
/** Get the connection status
*
* @return The connection status according to ConnectionStatusType
*/
virtual nsapi_connection_status_t get_connection_status() const;
/** Return MAC address of the network interface
*
* @return MAC address as "V:W:X:Y:Z"
*/
virtual char *get_mac_address(char *buf, nsapi_size_t buflen);
/** Copies IP address of the network interface to user supplied buffer
*
* @param buf buffer to which IP address will be copied as "W:X:Y:Z"
* @param buflen size of supplied buffer
* @return Pointer to a buffer, or NULL if the buffer is too small
*/
virtual nsapi_error_t get_ip_address(SocketAddress *address);
MBED_DEPRECATED_SINCE("mbed-os-5.15", "String-based APIs are deprecated")
virtual char *get_ip_address(char *buf, nsapi_size_t buflen);
/** Copies netmask of the network interface to user supplied buffer
*
* @param buf buffer to which netmask will be copied as "W:X:Y:Z"
* @param buflen size of supplied buffer
* @return Pointer to a buffer, or NULL if the buffer is too small
*/
virtual nsapi_error_t get_netmask(SocketAddress *address);
MBED_DEPRECATED_SINCE("mbed-os-5.15", "String-based APIs are deprecated")
virtual char *get_netmask(char *buf, nsapi_size_t buflen);
/** Copies gateway address of the network interface to user supplied buffer
*
* @param buf buffer to which gateway address will be copied as "W:X:Y:Z"
* @param buflen size of supplied buffer
* @return Pointer to a buffer, or NULL if the buffer is too small
*/
virtual nsapi_error_t get_gateway(SocketAddress *address);
MBED_DEPRECATED_SINCE("mbed-os-5.15", "String-based APIs are deprecated")
virtual char *get_gateway(char *buf, nsapi_size_t buflen);
private:
friend EmacTestNetworkStack;
Interface();
EMAC *m_emac;
};
/** Register a network interface with the IP stack
*
* Connects EMAC layer with the IP stack and initializes all the required infrastructure.
* This function should be called only once for each available interface.
*
* @param emac EMAC HAL implementation for this network interface
* @param default_if true if the interface should be treated as the default one
* @param[out] interface_out pointer to stack interface object controlling the EMAC
* @return NSAPI_ERROR_OK on success, or error code
*/
virtual nsapi_error_t add_ethernet_interface(EMAC &emac, bool default_if, OnboardNetworkStack::Interface **interface_out);
/** Translates a hostname to an IP address with specific version
*
* The hostname may be either a domain name or an IP address. If the
* hostname is an IP address, no network transactions will be performed.
*
* If no stack-specific DNS resolution is provided, the hostname
* will be resolve using a UDP socket on the stack.
*
* @param host Hostname to resolve
* @param address Destination for the host SocketAddress
* @param version IP version of address to resolve, NSAPI_UNSPEC indicates
* version is chosen by the stack (defaults to NSAPI_UNSPEC)
* @return 0 on success, negative error code on failure
*/
virtual nsapi_error_t gethostbyname(const char *host,
SocketAddress *address, nsapi_version_t version = NSAPI_UNSPEC);
/** Add a domain name server to list of servers to query
*
* @param address Destination for the host address
* @return 0 on success, negative error code on failure
*/
virtual nsapi_error_t add_dns_server(const SocketAddress &address);
protected:
/** Opens a socket
*
* Creates a network socket and stores it in the specified handle.
* The handle must be passed to following calls on the socket.
*
* A stack may have a finite number of sockets, in this case
* NSAPI_ERROR_NO_SOCKET is returned if no socket is available.
*
* @param handle Destination for the handle to a newly created socket
* @param proto Protocol of socket to open, NSAPI_TCP or NSAPI_UDP
* @return 0 on success, negative error code on failure
*/
virtual nsapi_error_t socket_open(nsapi_socket_t *handle, nsapi_protocol_t proto);
/** Close the socket
*
* Closes any open connection and deallocates any memory associated
* with the socket.
*
* @param handle Socket handle
* @return 0 on success, negative error code on failure
*/
virtual nsapi_error_t socket_close(nsapi_socket_t handle);
/** Bind a specific address to a socket
*
* Binding a socket specifies the address and port on which to receive
* data. If the IP address is zeroed, only the port is bound.
*
* @param handle Socket handle
* @param address Local address to bind
* @return 0 on success, negative error code on failure.
*/
virtual nsapi_error_t socket_bind(nsapi_socket_t handle, const SocketAddress &address);
/** Listen for connections on a TCP socket
*
* Marks the socket as a passive socket that can be used to accept
* incoming connections.
*
* @param handle Socket handle
* @param backlog Number of pending connections that can be queued
* simultaneously
* @return 0 on success, negative error code on failure
*/
virtual nsapi_error_t socket_listen(nsapi_socket_t handle, int backlog);
/** Connects TCP socket to a remote host
*
* Initiates a connection to a remote server specified by the
* indicated address.
*
* @param handle Socket handle
* @param address The SocketAddress of the remote host
* @return 0 on success, negative error code on failure
*/
virtual nsapi_error_t socket_connect(nsapi_socket_t handle, const SocketAddress &address);
/** Accepts a connection on a TCP socket
*
* The server socket must be bound and set to listen for connections.
* On a new connection, creates a network socket and stores it in the
* specified handle. The handle must be passed to following calls on
* the socket.
*
* A stack may have a finite number of sockets, in this case
* NSAPI_ERROR_NO_SOCKET is returned if no socket is available.
*
* This call is non-blocking. If accept would block,
* NSAPI_ERROR_WOULD_BLOCK is returned immediately.
*
* @param server Socket handle to server to accept from
* @param handle Destination for a handle to the newly created socket
* @param address Destination for the remote address or NULL
* @return 0 on success, negative error code on failure
*/
virtual nsapi_error_t socket_accept(nsapi_socket_t server,
nsapi_socket_t *handle, SocketAddress *address = 0);
/** Send data over a TCP socket
*
* The socket must be connected to a remote host. Returns the number of
* bytes sent from the buffer.
*
* This call is non-blocking. If send would block,
* NSAPI_ERROR_WOULD_BLOCK is returned immediately.
*
* @param handle Socket handle
* @param data Buffer of data to send to the host
* @param size Size of the buffer in bytes
* @return Number of sent bytes on success, negative error
* code on failure
*/
virtual nsapi_size_or_error_t socket_send(nsapi_socket_t handle,
const void *data, nsapi_size_t size);
/** Receive data over a TCP socket
*
* The socket must be connected to a remote host. Returns the number of
* bytes received into the buffer.
*
* This call is non-blocking. If recv would block,
* NSAPI_ERROR_WOULD_BLOCK is returned immediately.
*
* @param handle Socket handle
* @param data Destination buffer for data received from the host
* @param size Size of the buffer in bytes
* @return Number of received bytes on success, negative error
* code on failure
*/
virtual nsapi_size_or_error_t socket_recv(nsapi_socket_t handle,
void *data, nsapi_size_t size);
/** Send a packet over a UDP socket
*
* Sends data to the specified address. Returns the number of bytes
* sent from the buffer.
*
* This call is non-blocking. If sendto would block,
* NSAPI_ERROR_WOULD_BLOCK is returned immediately.
*
* @param handle Socket handle
* @param address The SocketAddress of the remote host
* @param data Buffer of data to send to the host
* @param size Size of the buffer in bytes
* @return Number of sent bytes on success, negative error
* code on failure
*/
virtual nsapi_size_or_error_t socket_sendto(nsapi_socket_t handle, const SocketAddress &address,
const void *data, nsapi_size_t size);
/** Receive a packet over a UDP socket
*
* Receives data and stores the source address in address if address
* is not NULL. Returns the number of bytes received into the buffer.
*
* This call is non-blocking. If recvfrom would block,
* NSAPI_ERROR_WOULD_BLOCK is returned immediately.
*
* @param handle Socket handle
* @param address Destination for the source address or NULL
* @param buffer Destination buffer for data received from the host
* @param size Size of the buffer in bytes
* @return Number of received bytes on success, negative error
* code on failure
*/
virtual nsapi_size_or_error_t socket_recvfrom(nsapi_socket_t handle, SocketAddress *address,
void *buffer, nsapi_size_t size);
/** Register a callback on state change of the socket
*
* The specified callback will be called on state changes such as when
* the socket can recv/send/accept successfully and on when an error
* occurs. The callback may also be called spuriously without reason.
*
* The callback may be called in an interrupt context and should not
* perform expensive operations such as recv/send calls.
*
* @param handle Socket handle
* @param callback Function to call on state change
* @param data Argument to pass to callback
*/
virtual void socket_attach(nsapi_socket_t handle, void (*callback)(void *), void *data);
/* Set stack-specific socket options
*
* The setsockopt allow an application to pass stack-specific hints
* to the underlying stack. For unsupported options,
* NSAPI_ERROR_UNSUPPORTED is returned and the socket is unmodified.
*
* @param handle Socket handle
* @param level Stack-specific protocol level
* @param optname Stack-specific option identifier
* @param optval Option value
* @param optlen Length of the option value
* @return 0 on success, negative error code on failure
*/
virtual nsapi_error_t setsockopt(nsapi_socket_t handle, int level,
int optname, const void *optval, unsigned optlen);
/* Get stack-specific socket options
*
* The getstackopt allow an application to retrieve stack-specific hints
* from the underlying stack. For unsupported options,
* NSAPI_ERROR_UNSUPPORTED is returned and optval is unmodified.
*
* @param handle Socket handle
* @param level Stack-specific protocol level
* @param optname Stack-specific option identifier
* @param optval Destination for option value
* @param optlen Length of the option value
* @return 0 on success, negative error code on failure
*/
virtual nsapi_error_t getsockopt(nsapi_socket_t handle, int level,
int optname, void *optval, unsigned *optlen);
private:
/** Call in callback
*
* Callback is used to call the call in method of the network stack.
*/
typedef mbed::Callback<nsapi_error_t (int delay_ms, mbed::Callback<void()> user_cb)> call_in_callback_cb_t;
/** Get a call in callback
*
* Get a call in callback from the network stack context.
*
* Callback should not take more than 10ms to execute, otherwise it might
* prevent underlying thread processing. A portable user of the callback
* should not make calls to network operations due to stack size limitations.
* The callback should not perform expensive operations such as socket recv/send
* calls or blocking operations.
*
* @return Call in callback
*/
virtual call_in_callback_cb_t get_call_in_callback();
/** Call a callback after a delay
*
* Call a callback from the network stack context after a delay. If function
* returns error callback will not be called.
*
* @param delay Delay in milliseconds
* @param func Callback to be called
* @return 0 on success, negative error code on failure
*/
virtual nsapi_error_t call_in(int delay, mbed::Callback<void()> func);
Interface *m_interface;
};
#endif /* EMAC_TEST_NETWORK_STACK_H */
|
mbedmicro/mbed
|
connectivity/netsocket/tests/TESTS/network/emac/emac_TestNetworkStack.h
|
C
|
apache-2.0
| 17,188 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* MODULE NOTES:
* @update gess 4/1/98
*
* This class is defines the basic notion of a token
* within our system. All other tokens are derived from
* this one. It offers a few basic interfaces, but the
* most important is consume(). The consume() method gets
* called during the tokenization process when an instance
* of that particular token type gets detected in the
* input stream.
*
* CToken objects that are allocated from the heap _must_ be allocated
* using the nsTokenAllocator: the nsTokenAllocator object uses an
* arena to manage the tokens.
*
* The nsTokenAllocator object's arena implementation requires
* object size at destruction time to properly recycle the object;
* therefore, CToken::operator delete() is not public. Instead,
* heap-allocated tokens should be destroyed using the static
* Destroy() method, which accepts a token and the arena from which
* the token was allocated.
*
* Leaf classes (that are actually instantiated from the heap) must
* implement the SizeOf() method, which Destroy() uses to determine
* the size of the token in order to properly recycle it.
*/
#ifndef CTOKEN__
#define CTOKEN__
#include "prtypes.h"
#include "nsString.h"
#include "nsError.h"
#include "nsFixedSizeAllocator.h"
class nsScanner;
class nsTokenAllocator;
enum eContainerInfo {
eWellFormed,
eMalformed,
eFormUnknown
};
/**
* Implement the SizeOf() method; leaf classes derived from CToken
* must declare this.
*/
#define CTOKEN_IMPL_SIZEOF \
protected: \
virtual size_t SizeOf() const { return sizeof(*this); } \
public:
/**
* Token objects represent sequences of characters as they
* are consumed from the input stream (URL). While they're
* pretty general in nature, we use subclasses (found in
* nsHTMLTokens.h) to define <start>, </end>, <text>,
* <comment>, <&entity>, <newline>, and <whitespace> tokens.
*
* @update gess 3/25/98
*/
class CToken {
public:
enum eTokenOrigin {eSource,eResidualStyle};
protected:
// nsTokenAllocator should be the only class that tries to
// allocate tokens from the heap.
friend class nsTokenAllocator;
/**
*
* @update harishd 08/01/00
* @param aSize -
* @param aArena - Allocate memory from this pool.
*/
static void * operator new (size_t aSize,nsFixedSizeAllocator& anArena) CPP_THROW_NEW
{
return anArena.Alloc(aSize);
}
/**
* Hide operator delete; clients should use Destroy() instead.
*/
static void operator delete (void*,size_t) {}
protected:
/**
* destructor
* @update gess5/11/98
*/
virtual ~CToken();
private:
/**
* Destroy a token.
*/
static void Destroy(CToken* aToken,nsFixedSizeAllocator& aArenaPool)
{
size_t sz = aToken->SizeOf();
aToken->~CToken();
aArenaPool.Free(aToken, sz);
}
public:
/**
* Make a note on number of times you have been referenced
* @update harishd 08/02/00
*/
void AddRef() {
++mUseCount;
NS_LOG_ADDREF(this, mUseCount, "CToken", sizeof(*this));
}
/**
* Free yourself if no one is holding you.
* @update harishd 08/02/00
*/
void Release(nsFixedSizeAllocator& aArenaPool) {
--mUseCount;
NS_LOG_RELEASE(this, mUseCount, "CToken");
if (mUseCount==0)
Destroy(this, aArenaPool);
}
/**
* Default constructor
* @update gess7/21/98
*/
CToken(int32_t aTag=0);
/**
* Retrieve string value of the token
* @update gess5/11/98
* @return reference to string containing string value
*/
virtual const nsSubstring& GetStringValue(void) = 0;
/**
* Get string of full contents, suitable for debug dump.
* It should look exactly like the input source.
* @update gess5/11/98
* @return reference to string containing string value
*/
virtual void GetSource(nsString& anOutputString);
/** @update harishd 03/23/00
* @return reference to string containing string value
*/
virtual void AppendSourceTo(nsAString& anOutputString);
/**
* Sets the ordinal value of this token (not currently used)
* @update gess5/11/98
* @param value is the new ord value for this token
*/
void SetTypeID(int32_t aValue) {
mTypeID = aValue;
}
/**
* Getter which retrieves the current ordinal value for this token
* @update gess5/11/98
* @return current ordinal value
*/
virtual int32_t GetTypeID(void);
/**
* Getter which retrieves the current attribute count for this token
* @update gess5/11/98
* @return current attribute count
*/
virtual int16_t GetAttributeCount(void);
/**
* Causes token to consume data from given scanner.
* Note that behavior varies wildly between CToken subclasses.
* @update gess5/11/98
* @param aChar -- most recent char consumed
* @param aScanner -- input source where token should get data
* @return error code (0 means ok)
*/
virtual nsresult Consume(PRUnichar aChar,nsScanner& aScanner,int32_t aMode);
/**
* Getter which retrieves type of token
* @update gess5/11/98
* @return int containing token type
*/
virtual int32_t GetTokenType(void);
/**
* For tokens who care, this can tell us whether the token is
* well formed or not.
*
* @update gess 8/30/00
* @return false; subclasses MUST override if they care.
*/
virtual bool IsWellFormed(void) const {return false;}
virtual bool IsEmpty(void) { return false; }
/**
* If aValue is TRUE then the token represents a short-hand tag
*/
virtual void SetEmpty(bool aValue) { return ; }
int32_t GetNewlineCount()
{
return mNewlineCount;
}
void SetNewlineCount(int32_t aCount)
{
mNewlineCount = aCount;
}
int32_t GetLineNumber()
{
return mLineNumber;
}
void SetLineNumber(int32_t aLineNumber)
{
mLineNumber = mLineNumber == 0 ? aLineNumber : mLineNumber;
}
void SetInError(bool aInError)
{
mInError = aInError;
}
bool IsInError()
{
return mInError;
}
void SetAttributeCount(int16_t aValue) { mAttrCount = aValue; }
/**
* perform self test.
* @update gess5/11/98
*/
virtual void SelfTest(void);
static int GetTokenCount();
protected:
/**
* Returns the size of the token object.
*/
virtual size_t SizeOf() const = 0;
int32_t mTypeID;
int32_t mUseCount;
int32_t mNewlineCount;
uint32_t mLineNumber : 31;
uint32_t mInError : 1;
int16_t mAttrCount;
};
#endif
|
sergecodd/FireFox-OS
|
B2G/gecko/parser/htmlparser/public/nsToken.h
|
C
|
apache-2.0
| 7,154 |
using System;
using System.ComponentModel;
namespace Template10.Common
{
public delegate void TypedEventHandler<T>(object sender, T e);
public class EventArgs<T> : EventArgs
{
public EventArgs(T value)
{
Value = value;
}
public T Value { get; private set; }
}
public class HandledEventArgs<T> : HandledEventArgs
{
public HandledEventArgs(T value)
{
Value = value;
}
public T Value { get; private set; }
}
public class CancelEventArgs<T> : CancelEventArgs
{
public CancelEventArgs(T value)
{
Value = value;
}
public T Value { get; private set; }
}
public class DeferredEventArgs : EventArgs
{
DeferralManager Manager;
public DeferredEventArgs(DeferralManager manager)
{
Manager = manager;
}
public Deferral GetDeferral() => Manager.GetDeferral();
}
}
|
teamneusta/Template10
|
Libraries/Template10.CodeBehind/Common/TypedEventHandler.cs
|
C#
|
apache-2.0
| 998 |
package coursier.credentials
import java.io.File
abstract class Credentials extends Serializable {
// calling this may incur I/O
def get(): Seq[DirectCredentials]
}
object Credentials {
def apply(): DirectCredentials = DirectCredentials()
def apply(host: String, username: String, password: String): DirectCredentials =
DirectCredentials(host, username, password)
def apply(
host: String,
username: String,
password: String,
realm: Option[String]
): DirectCredentials = DirectCredentials(host, username, password, realm)
def apply(host: String, username: String, password: String, realm: String): DirectCredentials =
DirectCredentials(host, username, password, Option(realm))
def apply(
host: String,
username: String,
password: String,
realm: Option[String],
optional: Boolean
): DirectCredentials =
DirectCredentials(host, Some(username), Some(Password(password)), realm, optional)
def apply(
host: String,
username: String,
password: String,
realm: String,
optional: Boolean
): DirectCredentials =
DirectCredentials(host, Some(username), Some(Password(password)), Option(realm), optional)
def apply(f: File): FileCredentials =
FileCredentials(f.getAbsolutePath)
def apply(f: File, optional: Boolean): FileCredentials =
FileCredentials(f.getAbsolutePath, optional)
}
|
alexarchambault/coursier
|
modules/util/jvm/src/main/scala/coursier/credentials/Credentials.scala
|
Scala
|
apache-2.0
| 1,380 |
.msg_pre_view li {
margin-bottom: 20px;
}
.msg_pre_view .title {
width: 50%; text-align: right; display: inline-block; box-sizing: content-box; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; -ms-box-sizing: content-box;
}
.msg_pre_view .msg {
width: 50%; padding-left: 1em; display: inline-block; -ms-word-break: break-all; -ms-zoom: 1; -ms-word-wrap: break-word; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; -ms-box-sizing: border-box;
}
.msg_pre_view .msg .color_panel {
border-radius: 1px; border: 1px solid rgb(255, 255, 255); border-image: none; width: 20px; height: 20px; margin-right: 4px; display: block; box-shadow: 0px 0px 3px #8d8d8d; -moz-box-shadow: 0 0 3px #8d8d8d; -webkit-box-shadow: 0 0 3px #8d8d8d; -webkit-border-radius: 1px; -moz-border-radius: 1px;
}
.msg_pre_view .msg .pre {
margin: 0px; -ms-word-break: break-all; -ms-word-wrap: break-word;
}
.msg_pre_view .msg img {
width: 200px;
}
.msg_pre_view .msg .tips {
color: rgb(163, 163, 163); font-size: 14px;
}
.msg_pre_view .page_top .link {
right: 0px; position: relative;
}
input::-ms-clear {
display: none;
}
.msg_pre_view .title {
width: 30%;
}
.msg_pre_view .msg {
width: 70%;
}
.msg_pre_view .msg .sub_msg {
color: rgb(163, 163, 163);
}
.frm_control_group .frm_controls .input_submsg .frm_input_box {
width: 60px; margin-right: 5px;
}
.frm_control_group.radio_row {
text-align: left;
}
.frm_control_group.radio_row .frm_label {
height: 43px; line-height: 43px; float: none;
}
.frm_control_group.radio_row .frm_controls {
padding: 20px;
}
.frm_control_group.radio_row .frm_controls.frm_vertical_lh {
line-height: normal;
}
.frm_control_group.radio_row .frm_controls .frm_radio_label {
margin-bottom: 15px; display: block;
}
.frm_control_group.radio_row .frm_controls .frm_radio_label .frm_tips {
line-height: normal; padding-top: 0px; padding-left: 23px;
}
.frm_control_group.radio_row .frm_controls :last-child.frm_radio_label {
margin-bottom: 0px;
}
.frm_control_group.radio_row .frm_controls .frm_radio_label.frm_radio_input {
height: 32px; line-height: 32px;
}
.frm_control_group.radio_row .frm_controls .radio_control_group {
display: block;
}
.frm_control_group.radio_row .frm_controls .radio_control_group::after {
height: 0px; clear: both; font-size: 0px; display: block; visibility: hidden; content: ".";
}
.frm_control_group.radio_row .frm_controls .radio_control_group .frm_radio_label {
float: left;
}
.frm_control_group.radio_row .frm_controls .radio_control_group .dropdown_menu {
margin-right: 5px;
}
.frm_control_group.radio_row .frm_controls .radio_control_group .frm_tips {
padding-left: 24px;
}
.table_wrp {
margin-bottom: 20px;
}
.table_wrp .dropdown_menu .dropdown_data_list {
}
.tab_wrp_thead {
border-top-color: rgb(231, 231, 235); border-right-color: rgb(231, 231, 235); border-left-color: rgb(231, 231, 235); border-top-width: 1px; border-right-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-left-style: solid; background-color: rgb(244, 245, 249);
}
.tab_wrp_thead .title h4 {
padding: 0px 1em; height: 38px; line-height: 38px; font-weight: normal;
}
.tab_wrp_thead .title a {
margin-left: 1em;
}
.tab_wrp_thead .title .tab_nav a {
margin-left: 0px;
}
.tab_wrp_thead .dropdown_menu_td {
border-left-color: rgb(231, 231, 235); border-left-width: 1px; border-left-style: solid;
}
.tab_wrp_thead .dropdown_menu_td .dropdown_switch {
background: 0px rgb(244, 245, 249); border: 0px currentColor; border-image: none; height: 38px; line-height: 38px;
}
.tab_wrp_thead .tab_top_oper {
padding: 0px 1em; height: 38px; line-height: 38px; border-left-color: rgb(231, 231, 235); border-left-width: 1px; border-left-style: solid;
}
.tab_wrp_thead .data {
line-height: 38px; border-left-color: rgb(231, 231, 235); border-left-width: 1px; border-left-style: solid;
}
.tab_wrp_thead .data .ta_date {
background: 0px; border: 0px currentColor; border-image: none; line-height: 38px;
}
.tab_wrp_thead .data:hover {
background-color: rgb(231, 231, 235);
}
.tab_wrp_thead .ta_date .opt_sel {
height: 38px; line-height: 38px;
}
.tab_wrp_thead .time_periods {
line-height: 38px; border-left-color: rgb(231, 231, 235); border-left-width: 1px; border-left-style: solid;
}
.tab_wrp_thead .time_periods .btn {
background: 0px; border: 0px currentColor; border-image: none;
}
.tab_wrp_thead .time_periods:hover {
background-color: rgb(231, 231, 235);
}
.tab_wrp_thead.with_oper .td_panel {
padding: 0px;
}
.table {
margin-bottom: 20px; border-right-color: rgb(231, 231, 235); border-left-color: rgb(231, 231, 235); border-right-width: 1px; border-left-width: 1px; border-right-style: solid; border-left-style: solid;
}
.table .btn {
background: 0px; border: 0px currentColor; border-image: none;
}
.table .btn.dropdown_switch {
background: 0px;
}
.table .frm_radio_label {
margin-right: 0px;
}
.table .table_cell {
padding: 0px; text-align: left; line-height: normal;
}
.table .table_cell.with_num {
text-align: right;
}
.table_head {
border-width: 1px 1px 0px; border-style: solid solid none; border-color: rgb(231, 231, 235) rgb(231, 231, 235) currentColor; padding: 6px 1em; border-image: none; background-color: rgb(244, 245, 249);
}
.td_panel {
padding: 10px 1em; -ms-word-break: break-all; -ms-word-wrap: break-word;
}
.thead .table_cell {
line-height: normal;
}
.thead .td_panel {
padding: 10px 1em;
}
.thead .dropdown_switch label {
margin-left: 1em;
}
.tbody {
color: rgb(141, 141, 141);
}
.tbody .table_cell.with_oper .td_panel {
padding-right: 2em;
}
.frm_control_group .hint {
height: 30px; color: rgb(141, 141, 141); line-height: 30px; margin-left: 0.5em;
}
.frm_control_group .frm_controls_hint .frm_input_box {
float: left;
}
.frm_control_group .frm_controls_hint .frm_hint {
margin-left: 0.5em;
}
.pop_task {
padding: 0px 33px;
}
.pop_task .pop_top_tip {
margin-bottom: 20px;
}
.pop_task .frm_control_group {
padding-bottom: 5px;
}
.pop_task .frm_checkbox_group label {
margin-left: 6em;
}
.pop_task .frm_checkbox_group .frm_tips {
margin-left: 6em;
}
.pop_task .frm_input_box {
width: 343px;
}
.pop_task .frm_tips {
width: 375px;
}
.release_method {
padding: 55px 35px;
}
.release_method .radio_row .frm_label {
padding-left: 22px;
}
.release_method .msg_pre_view .title {
width: 40%; color: rgb(141, 141, 141);
}
.release_method .msg_pre_view .msg {
width: 60%; padding-left: 2em;
}
.release_method .page_msg.page_msg_release {
margin: 0px 82px 20px;
}
.first_step .frm_control_group.radio_row {
padding: 0px 0px 0px 155px;
}
.second_step .frm_control_group.radio_row .frm_controls {
padding: 0px;
}
.ic_social {
padding: 1px 3px; color: rgb(255, 255, 255); font-size: 12px; font-style: normal; display: inline-block; -ms-word-break: normal; -ms-word-wrap: normal; background-color: rgb(135, 194, 232); -webkit-font-smoothing: subpixel-antialiased;
}
.release_method {
padding: 55px 35px;
}
.release_method .icon_loading_small {
margin-top: -20px; margin-left: -20px;
}
.release_method .search {
margin-bottom: 10px;
}
.release_method .sub_title_bar {
padding: 0px; line-height: normal;
}
.dialog_desc {
text-align: left; color: rgb(141, 141, 141); padding-left: 112px;
}
.table_wrp.release_method_select_table_wrp .td_panel {
padding: 10px 0px 10px 1em;
}
.table_wrp .table_cell.release_method_select_box {
width: 1%;
}
.table_wrp .table_cell.release_method_select_box .frm_radio_label {
margin-right: 0px;
}
.table_wrp .table_cell.release_method_kind {
width: 12%; color: rgb(0, 0, 0);
}
.table_wrp .table_cell.release_method_name {
width: 17%;
}
.table_wrp .table_cell.release_method_time {
width: 25%;
}
.table_wrp .table_cell.release_method_stock {
width: 15%; text-align: right;
}
.table_wrp .table_cell.release_method_stock .td_panel {
padding: 10px 1em 10px 0px;
}
.table_wrp .table_cell.release_method_stock .icon14_common {
margin-left: 0.5em;
}
.table_wrp .table_cell.release_method_price {
width: 16%; text-align: right;
}
.table_wrp .table_cell.release_method_preview {
width: 7%;
}
.table_wrp .table_cell.release_method_state {
width: 14%; text-align: right;
}
.table_wrp .table_cell.release_method_state .td_panel {
padding: 10px 1em 10px 0px;
}
.table_wrp .thead .release_method_state .td_panel {
border-right-color: currentColor; border-right-width: 0px; border-right-style: none;
}
.table_wrp .thead .release_method_stock .td_panel {
padding-right: 2.8em;
}
.table_wrp .pagination {
text-align: right; margin-top: 10px;
}
.table_wrp .disabled_item {
color: rgb(193, 193, 193); background-color: rgb(245, 245, 245);
}
.table_wrp .disabled_item .table_cell.release_method_kind {
color: rgb(193, 193, 193);
}
.table_wrp .disabled_item:hover {
color: rgb(193, 193, 193); cursor: not-allowed; background-color: rgb(245, 245, 245);
}
.user_list .table_cell .td_panel {
padding: 10px 6px;
}
.msg_pre_view .title {
width: 40%; text-align: right; color: rgb(141, 141, 141);
}
.msg_pre_view .msg {
width: 53%; text-align: left; padding-left: 2em;
}
.msg_pre_view .frm_control_group {
top: -6px; position: relative;
}
.msg_pre_view .frm_control_group .frm_input_box {
width: 60px; margin-right: 5px;
}
.pop_card_preview {
position: relative;
}
.pop_card_preview .hook {
width: 20px; height: 20px; position: absolute;
}
.pop_card_preview .hook .hook_top {
border-width: 10px; border-style: solid; border-color: transparent transparent transparent rgb(231, 231, 235); left: 1px; bottom: 0px; position: absolute;
}
.pop_card_preview .hook .hook_btm {
border-width: 10px; border-style: solid; border-color: transparent transparent transparent rgb(255, 255, 255); left: 0px; bottom: 0px; position: absolute;
}
.pop_card_preview .hook.hook_right_top {
top: 20px; right: -20px;
}
.pop_card_preview .hook.hook_right_center {
top: 50%; right: -20px; margin-top: -10px;
}
.pop_card_preview .hook.hook_right_bottom {
right: -20px; bottom: 20px;
}
.dialog_footer_dec {
color: rgb(141, 141, 141); padding-left: 23px;
}
.dialog_footer_tips {
text-align: center; color: rgb(141, 141, 141); padding-bottom: 2em;
}
.select_card_thumb {
vertical-align: top; display: inline-block;
}
.card_thumb_wrp {
margin: 1em 0px; padding: 1em; border-radius: 4px; border: 1px solid rgb(170, 170, 170); border-image: none;
}
.card_thumb_wrp .card_thumb {
margin: 0px; width: 150px; height: 90px; vertical-align: middle; display: inline-block;
}
.card_thumb_wrp .card_thumb_add {
margin: 0px; width: 150px; height: 90px; vertical-align: middle; display: inline-block;
}
.card_thumb_wrp .card_thumb img:first-child {
width: 150px; height: 90px; max-height: 90px; max-width: 150px;
}
.card_thumb_wrp .card_thumb_add {
border: 2px dashed rgb(136, 136, 136); border-image: none; text-align: center; color: rgb(136, 136, 136); line-height: 86px; font-size: 64px;
}
.card_thumb_wrp .card_thumb_add:hover {
text-decoration: none;
}
.card_thumb_wrp .card_name {
width: 160px; overflow: hidden; margin-left: 1em; vertical-align: middle; display: inline-block; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis; max-width: 160px;
}
.sub_radio_control_group {
clear: both; margin-top: 0.5em; margin-left: 2em;
}
.sub_radio_control_group .frm_control_group {
margin: 0px;
}
.sub_radio_control_group .frm_control_group.textarea_group {
clear: both; margin-left: 0px;
}
.sub_radio_control_group .frm_control_group .frm_controls {
padding: 0px 0px 20px; position: relative;
}
.sub_radio_control_group .frm_control_group .frm_controls .frm_tips {
padding-left: 0px;
}
.sub_radio_control_group .supply_msg {
right: 0px; bottom: 0px; position: absolute;
}
.sub_radio_control_group .frm_tips {
padding-left: 0px;
}
.loading {
padding: 1em 0px; text-align: center;
}
.processor_bar {
border-bottom-color: rgb(206, 206, 206); border-bottom-width: 1px; border-bottom-style: solid; box-shadow: inset 0px 1px 0px 0px #f8f8f8; background-image: linear-gradient(rgb(243, 242, 242) 0px, rgb(223, 223, 223) 100%); background-color: rgb(233, 233, 233); -moz-box-shadow: inset 0 1px 0 0 #f8f8f8; -webkit-box-shadow: inset 0 1px 0 0 #f8f8f8;
}
.dialog .processor_bar {
border-bottom-color: rgb(177, 177, 177); border-bottom-width: 1px; border-bottom-style: solid; box-shadow: inset 0px 1px 0px 0px #f8f8f8, 0px 1px 2px 0px #cacaca; -moz-box-shadow: inset 0 1px 0 0 #f8f8f8, 0 1px 2px 0 #cacaca; -webkit-box-shadow: inset 0 1px 0 0 #f8f8f8, 0 1px 2px 0 #cacaca;
}
.processor_bar.ie .step {
background: url("/mpres/htmledition/common/images/bg/bg_processor_ie218877.png") no-repeat 0px 0px;
}
.processor_bar.ie .step.current {
background-image: none; background-color: rgb(98, 162, 86);
}
.processor_bar .step {
background: url("/mpres/htmledition/common/images/bg/bg_processor218877.png") no-repeat 0px 0px; text-align: center; color: rgb(116, 116, 116); line-height: 36px;
}
.processor_bar .step.pprev {
background-position: right 0px;
}
.processor_bar .step.pprev h4 {
padding-right: 14px;
}
.processor_bar .step.prev {
background-position: right -85px;
}
.processor_bar .step.prev h4 {
padding-right: 14px;
}
.processor_bar .step.current {
color: rgb(255, 255, 255); background-image: linear-gradient(rgb(120, 188, 109) 0px, rgb(79, 141, 68) 100%); background-color: rgb(95, 160, 84);
}
.processor_bar .step.next {
background-position: left -41px;
}
.processor_bar .step.next h4 {
padding-left: 8px;
}
.processor_bar .step.nnext {
background-position: left -1px;
}
.processor_bar .step.nnext h4 {
padding-left: 8px;
}
.processor_bar h4 {
width: auto; overflow: hidden; font-style: normal; font-weight: 400; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis;
}
.processor_bar {
border-color: rgb(230, 231, 234); box-shadow: none; background-image: none; background-color: rgb(255, 255, 255); -moz-box-shadow: none; -webkit-box-shadow: none;
}
.dialog .processor_bar {
border-color: rgb(230, 231, 234); box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none;
}
.processor_bar.ie .step {
background-image: url("/mpres/htmledition/images/bg/bg_processor218877.png");
}
.processor_bar.ie .step.current {
background-color: rgb(68, 181, 73);
}
.processor_bar .step {
background: url("/mpres/htmledition/images/bg/bg_processor218877.png") no-repeat 0px 0px; line-height: 44px;
}
.processor_bar .step.prev {
background-position: right -44px;
}
.processor_bar .step.current {
background-image: none; background-color: rgb(68, 181, 73);
}
.processor_bar .step.next {
background-position: 0px -88px;
}
.processor_bar .step.nnext {
background-position: 0px 0px;
}
.dialog_select_video .video {
padding: 30px 205px;
}
.dialog_select_video .frm_input_box {
width: 440px;
}
.video_preview {
margin: 0px auto 20px; width: 548px; height: 280px; background-color: rgb(244, 245, 249);
}
.dialog_select_video .dialog_bd {
padding: 0px;
}
.dialog_select_video .richvideo_create {
padding: 0px 20px; text-align: right; margin-top: -51px;
}
.dialog_select_video .sub_title_bar.in_dialog {
padding: 0px; border-bottom-color: currentColor; border-bottom-width: 0px; border-bottom-style: none;
}
.img_pick {
padding: 20px;
}
.img_pick .img_item {
text-align: center; float: left;
}
.img_pick .img_item .pic {
border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid; display: block;
}
.img_pick .img_item .pic:hover {
cursor: pointer;
}
.img_pick .img_item .lbl_content {
height: 32px; text-align: left; line-height: 32px; overflow: hidden; white-space: nowrap; -ms-text-overflow: ellipsis;
}
.group_list .num {
color: rgb(141, 141, 141); padding-left: 3px; font-style: normal; display: inline-block;
}
.group_list dt.inner_menu_item {
background-color: rgb(244, 245, 249);
}
.img_pick_panel .icon_loading_small {
left: 50%; top: 50%; margin-top: -20px; margin-left: -20px; position: absolute;
}
.img_pick_panel.side_l.cell_layout .inner_side {
width: 18%;
}
.img_pick_panel .group_list {
height: 460px; -ms-overflow-y: auto;
}
.img_pick_panel .img_pick_area {
height: 460px; position: relative; -ms-overflow-x: hidden; -ms-overflow-y: auto;
}
.img_pick_panel .inner_menu_link {
padding-left: 1.5em;
}
.img_pick_panel .inner_menu_link strong {
max-width: 86px;
}
.img_pick_panel .bubble_tips {
margin-right: 14px;
}
.img_pick {
text-align: center; padding-bottom: 5px;
}
.img_pick .img_list {
margin-right: -20px;
}
.img_pick .img_item {
margin-right: 11px; margin-bottom: 10px; position: relative;
}
.img_pick .img_item .pic {
width: 117px; height: 117px;
}
.img_pick .img_item .lbl_content {
padding: 0px 9px; display: block;
}
.img_pick .img_item .lbl_content .icon_original {
width: 34px; height: 18px; vertical-align: -4px; display: inline-block;
}
.img_pick .img_item .lbl_content .icon_original.accessed {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/page/media/dialog_img_pick_z29843e.png") no-repeat 0px 0px;
}
.img_pick .img_item_bd {
margin: 0px; border: 1px solid rgb(231, 231, 235); border-image: none; width: 117px;
}
.img_pick .img_item_bd.selected .selected_mask {
left: 0px; top: 0px; width: 100%; height: 100%; position: absolute;
}
.img_pick .img_item_bd.selected .selected_mask_inner {
width: 118px; height: 118px; opacity: 0.6; background-color: rgb(0, 0, 0); -moz-opacity: .6; -khtml-opacity: .6;
}
.img_pick .img_item_bd.selected .selected_mask_icon {
background: url("/mpres/htmledition/images/icon/common/icon_card_selected218877.png") no-repeat 50% 50%; left: 0px; top: 0px; width: 117px; height: 117px; vertical-align: middle; display: inline-block; position: absolute;
}
.img_dialog_wrp .dialog_bd {
padding: 0px;
}
.img_dialog_wrp .sub_title_bar.in_dialog {
padding: 10px 20px;
}
.img_dialog_wrp .sub_title_bar.in_dialog .mass_send_tips {
height: 30px; color: rgb(141, 141, 141); line-height: 30px; margin-right: 1em;
}
.img_dialog_wrp .pagination {
padding: 0px 16px 20px; text-align: right;
}
.img_dialog_wrp .dialog_ft_desc {
left: 20px; bottom: 23px; position: absolute;
}
.article_list {
-ms-overflow-y: auto; max-height: 425px;
}
.list_item {
padding: 15px 15px 10px 10px; overflow: hidden; text-decoration: none !important; display: block; position: relative; cursor: default; -webkit-tap-highlight-color: transparent;
}
.list_item::after {
transform-origin: 0% 100%; left: 10px; width: 100%; height: 1px; bottom: 0px; border-bottom-color: rgb(226, 226, 226); border-bottom-width: 1px; border-bottom-style: solid; position: absolute; content: " "; transform: scaleY(0.5); -webkit-transform: scaleY(0.5); -webkit-transform-origin: 0 100%;
}
:last-child.list_item::after {
border: 0px currentColor; border-image: none;
}
.list_item .cover {
margin-right: 10px; float: left;
}
.list_item .cover .img {
width: 80px; height: 60px; display: block;
}
.list_item .cont {
overflow: hidden;
}
.list_item .cont .title {
width: 100%; color: rgb(0, 0, 0); overflow: hidden; font-size: 16px; font-weight: normal; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis;
}
.list_item .cont .desc {
color: rgb(153, 153, 153); line-height: 1.3; overflow: hidden; font-size: 13px; -ms-text-overflow: ellipsis; -webkit-box-orient: vertical; -webkit-line-clamp: 2;
}
.more {
text-align: center;
}
.editor_toolbar {
overflow: hidden; padding-bottom: 10px; border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid;
}
.editor_toolbar .title {
font-weight: normal; margin-right: 10px; float: left;
}
.editor_toolbar .counter {
color: rgb(141, 141, 141); overflow: hidden;
}
.editor_toolbar .ext {
float: right;
}
.editor_toolbar .btn {
padding: 0px 10px; height: 25px; line-height: 25px; margin-left: 5px; min-width: 0px;
}
.articles {
padding: 15px 0px; min-height: 150px;
}
.article {
padding: 5px;
}
.article.dragging {
border: 1px solid rgb(231, 231, 235); border-image: none; background-color: rgb(244, 245, 249);
}
.article .title a {
color: rgb(34, 34, 34);
}
.article .title a:hover {
color: rgb(69, 154, 233);
}
.article .opr {
margin-top: 3px; float: right;
}
.drag_placeholder {
margin: 8px; border: 1px solid rgb(231, 231, 235); border-image: none; height: 32px; background-color: rgb(255, 255, 255);
}
.tab_hd {
height: 44px;
}
.tab_hd_inner {
width: 100%; overflow: hidden; font-size: 0px; background-color: rgb(242, 242, 242);
}
.tab_hd_inner .item {
margin: 10px 0px; height: 24px; text-align: center; color: rgb(0, 0, 0); overflow: hidden; font-size: 15px; text-decoration: none; float: left; -webkit-tap-highlight-color: transparent;
}
.tab_hd_inner .item.active {
color: rgb(33, 177, 0);
}
.tab_hd_inner .item:active {
background-color: rgba(0, 0, 0, 0.1);
}
.tab_hd_inner .item.no_extra {
}
.article_list {
-ms-overflow-y: auto; max-height: 425px;
}
.list_item {
padding: 15px 15px 10px 10px; overflow: hidden; text-decoration: none !important; display: block; position: relative; cursor: default; -webkit-tap-highlight-color: transparent;
}
.list_item::after {
transform-origin: 0% 100%; left: 10px; width: 100%; height: 1px; bottom: 0px; border-bottom-color: rgb(226, 226, 226); border-bottom-width: 1px; border-bottom-style: solid; position: absolute; content: " "; transform: scaleY(0.5); -webkit-transform: scaleY(0.5); -webkit-transform-origin: 0 100%;
}
:last-child.list_item::after {
border: 0px currentColor; border-image: none;
}
.list_item .cover {
margin-right: 10px; float: left;
}
.list_item .cover .img {
width: 80px; height: 60px; display: block;
}
.list_item .cont {
overflow: hidden;
}
.list_item .cont .title {
width: 100%; color: rgb(0, 0, 0); overflow: hidden; font-size: 16px; font-weight: normal; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis;
}
.list_item .cont .desc {
color: rgb(153, 153, 153); line-height: 1.3; overflow: hidden; font-size: 13px; -ms-text-overflow: ellipsis; -webkit-box-orient: vertical; -webkit-line-clamp: 2;
}
.more {
text-align: center;
}
.editor_toolbar {
overflow: hidden; padding-bottom: 10px; border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid;
}
.editor_toolbar .title {
font-weight: normal; margin-right: 10px; float: left;
}
.editor_toolbar .counter {
color: rgb(141, 141, 141); overflow: hidden;
}
.editor_toolbar .ext {
float: right;
}
.editor_toolbar .btn {
padding: 0px 10px; height: 25px; line-height: 25px; margin-left: 5px; min-width: 0px;
}
.articles {
padding: 15px 0px; min-height: 150px;
}
.article {
padding: 5px;
}
.article.dragging {
border: 1px solid rgb(231, 231, 235); border-image: none; background-color: rgb(244, 245, 249);
}
.article .title a {
color: rgb(34, 34, 34);
}
.article .title a:hover {
color: rgb(69, 154, 233);
}
.article .opr {
margin-top: 3px; float: right;
}
.drag_placeholder {
margin: 8px; border: 1px solid rgb(231, 231, 235); border-image: none; height: 32px; background-color: rgb(255, 255, 255);
}
.tab_navs {
text-align: center; line-height: 30px; border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid; box-shadow: inset 0px 1px 0px 0px rgba(255,255,255,0.5); -moz-box-shadow: inset 0 1px 0 0 rgba(255, 255, 255, 0.5); -webkit-box-shadow: inset 0 1px 0 0 rgba(255, 255, 255, 0.5);
}
.tab_navs::after {
height: 0px; clear: both; display: block; content: "\200B";
}
.tab_nav {
font-size: 14px; float: left;
}
.tab_nav a {
padding: 0px 20px; outline: 0px; color: rgb(34, 34, 34); text-decoration: none; display: block;
}
.tab_nav.selected {
background-color: rgb(212, 213, 213);
}
.mt .tab_nav a {
border-right-color: rgb(231, 231, 235); border-right-width: 1px; border-right-style: solid;
}
.mt .tab_nav.selected {
top: -1px; border-top-color: rgb(117, 116, 116); border-top-width: 3px; border-top-style: solid; position: relative;
}
.mt .tab_nav.selected a {
line-height: 29px; margin-bottom: -2px; position: relative; background-color: rgb(212, 213, 213);
}
.mt .tab_nav.no_extra a {
border-right-width: 0px;
}
.section_tab .tab_navs {
border: 0px currentColor; border-image: none; line-height: 14px; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none;
}
.section_tab .tab_nav {
line-height: 30px; border-top-color: rgb(201, 202, 206); border-bottom-color: rgb(201, 202, 206); border-left-color: rgb(201, 202, 206); border-top-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-bottom-style: solid; border-left-style: solid;
}
.section_tab .tab_nav:hover {
text-decoration: none;
}
.section_tab :last-child.tab_nav a {
border: 0px currentColor; border-image: none;
}
.section_tab :first-child.tab_nav {
border-top-left-radius: 3px; border-bottom-left-radius: 3px; -moz-border-radius-topleft: 3px; -webkit-border-top-left-radius: 3px; -moz-border-radius-bottomleft: 3px; -webkit-border-bottom-left-radius: 3px;
}
.section_tab .tab_nav.no_extra {
border-right-color: rgb(201, 202, 206); border-right-width: 1px; border-right-style: solid; border-top-right-radius: 3px; border-bottom-right-radius: 3px; -moz-border-radius-topright: 3px; -webkit-border-top-right-radius: 3px; -moz-border-radius-bottomright: 3px; -webkit-border-bottom-right-radius: 3px;
}
.section_tab .tab_nav.selected {
border-color: rgb(87, 100, 119); text-decoration: none; margin-right: -1px; position: relative; background-color: rgb(87, 100, 119);
}
.section_tab .tab_nav.selected a {
color: rgb(255, 255, 255);
}
.section_tab.with_table {
padding: 10px 20px; border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid; background-color: rgb(244, 245, 249);
}
.section_tab.gap_bottom {
padding-bottom: 20px;
}
.editor_hd {
padding-top: 20px;
}
.section_tab {
height: 40px; overflow: hidden;
}
.section_tab .tab_nav {
margin-bottom: 10px;
}
.section_tab .tab_nav.selected {
border: 0px currentColor; border-image: none;
}
.section_tab .tab_nav .add_nav {
color: rgb(69, 154, 233);
}
.section_form .opr {
float: right;
}
.section_form .frm_input_box {
width: 250px;
}
.swiper {
height: 150px; overflow: hidden; position: relative;
}
.swiper .item {
width: 100%; float: left; position: relative;
}
.swiper .item .img {
width: 100%; height: 150px; display: block;
}
.swiper .item .desc {
padding: 20px 85px 12px 13px; left: 0px; width: auto; height: 1.4em; right: 0px; bottom: 0px; color: rgb(255, 255, 255); overflow: hidden; font-size: 16px; white-space: nowrap; position: absolute; -ms-word-wrap: normal; -ms-text-overflow: ellipsis; text-shadow: 0px 1px 0px rgba(0,0,0,0.5); background-image: linear-gradient(rgba(0, 0, 0, 0) 0px, rgba(0, 0, 0, 0.7) 100%);
}
.slider {
overflow: hidden; position: relative;
}
.indicator {
right: 15px; bottom: 10px; position: absolute;
}
.indicator a {
margin-left: 6px; float: left;
}
.indicator .icon_dot {
border-radius: 100%; width: 5px; height: 5px; vertical-align: middle; display: inline-block; background-color: rgb(208, 205, 209); -webkit-border-radius: 100%; -moz-border-radius: 100%;
}
.indicator .icon_dot.active {
background-color: rgb(106, 102, 111);
}
.editor_toolbar {
overflow: hidden; padding-bottom: 10px; border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid;
}
.editor_toolbar .title {
font-weight: normal; margin-right: 10px; float: left;
}
.editor_toolbar .counter {
color: rgb(141, 141, 141); overflow: hidden;
}
.editor_toolbar .ext {
float: right;
}
.editor_toolbar .btn {
padding: 0px 10px; height: 25px; line-height: 25px; margin-left: 5px; min-width: 0px;
}
.articles {
padding: 15px 0px; min-height: 150px;
}
.article {
padding: 5px;
}
.article.dragging {
border: 1px solid rgb(231, 231, 235); border-image: none; background-color: rgb(244, 245, 249);
}
.article .title a {
color: rgb(34, 34, 34);
}
.article .title a:hover {
color: rgb(69, 154, 233);
}
.article .opr {
margin-top: 3px; float: right;
}
.drag_placeholder {
margin: 8px; border: 1px solid rgb(231, 231, 235); border-image: none; height: 32px; background-color: rgb(255, 255, 255);
}
.pagination_wrp {
text-align: right;
}
.pagination {
}
.page_nav_area {
font-size: 12px; vertical-align: middle; display: inline-block;
}
.goto_area {
font-size: 12px; vertical-align: middle; display: inline-block;
}
.page_nav_area {
letter-spacing: 4px;
}
.page_nav_area .btn {
letter-spacing: normal;
}
.page_nav_area .gap_prev {
letter-spacing: normal; font-size: 14px; margin-right: 4px; margin-left: 4px; vertical-align: middle; display: inline-block;
}
.page_nav_area .gap_next {
letter-spacing: normal; font-size: 14px; margin-right: 4px; margin-left: 4px; vertical-align: middle; display: inline-block;
}
.btn.page_nav {
border-color: rgb(230, 231, 236); margin: 0px; width: auto; height: 30px; color: rgb(34, 34, 34); line-height: 30px; padding-right: 14px; padding-left: 14px; background-image: linear-gradient(rgb(255, 255, 255) 0px, rgb(255, 255, 255) 100%); background-color: rgb(255, 255, 255);
}
.btn.page_nav button {
color: rgb(34, 34, 34);
}
.btn.page_nav:hover {
border-color: rgb(218, 219, 224); color: rgb(0, 0, 0); box-shadow: none; background-image: linear-gradient(rgb(230, 231, 236) 0px, rgb(230, 231, 236) 100%); background-color: rgb(230, 231, 236); -moz-box-shadow: none; -webkit-box-shadow: none;
}
.btn.page_nav:hover button {
color: rgb(34, 34, 34);
}
.btn.page_nav.current {
background: 0px; border: 0px currentColor; border-image: none; cursor: default; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none;
}
.btn.page_prev {
border-color: rgb(230, 231, 236); width: auto; height: 30px; color: rgb(34, 34, 34); line-height: 30px; letter-spacing: -5px; padding-right: 14px; padding-left: 14px; font-size: 0px; position: relative; background-image: linear-gradient(rgb(255, 255, 255) 0px, rgb(255, 255, 255) 100%); background-color: rgb(255, 255, 255);
}
.btn.page_next {
border-color: rgb(230, 231, 236); width: auto; height: 30px; color: rgb(34, 34, 34); line-height: 30px; letter-spacing: -5px; padding-right: 14px; padding-left: 14px; font-size: 0px; position: relative; background-image: linear-gradient(rgb(255, 255, 255) 0px, rgb(255, 255, 255) 100%); background-color: rgb(255, 255, 255);
}
.btn.page_prev button {
color: rgb(34, 34, 34);
}
.btn.page_next button {
color: rgb(34, 34, 34);
}
.btn.page_prev:hover {
border-color: rgb(218, 219, 224); color: rgb(0, 0, 0); box-shadow: none; background-image: linear-gradient(rgb(230, 231, 236) 0px, rgb(230, 231, 236) 100%); background-color: rgb(230, 231, 236); -moz-box-shadow: none; -webkit-box-shadow: none;
}
.btn.page_next:hover {
border-color: rgb(218, 219, 224); color: rgb(0, 0, 0); box-shadow: none; background-image: linear-gradient(rgb(230, 231, 236) 0px, rgb(230, 231, 236) 100%); background-color: rgb(230, 231, 236); -moz-box-shadow: none; -webkit-box-shadow: none;
}
.btn.page_prev:hover button {
color: rgb(34, 34, 34);
}
.btn.page_next:hover button {
color: rgb(34, 34, 34);
}
.btn.page_prev .arrow {
left: 50%; top: 50%; margin-top: -6px; margin-left: -3px; position: absolute;
}
.btn.page_next .arrow {
left: 50%; top: 50%; margin-top: -6px; margin-left: -3px; position: absolute;
}
.btn.page_first {
border-color: rgb(230, 231, 236); width: auto; height: 30px; color: rgb(34, 34, 34); line-height: 30px; padding-right: 20px; padding-left: 20px; background-image: linear-gradient(rgb(255, 255, 255) 0px, rgb(255, 255, 255) 100%); background-color: rgb(255, 255, 255);
}
.btn.page_last {
border-color: rgb(230, 231, 236); width: auto; height: 30px; color: rgb(34, 34, 34); line-height: 30px; padding-right: 20px; padding-left: 20px; background-image: linear-gradient(rgb(255, 255, 255) 0px, rgb(255, 255, 255) 100%); background-color: rgb(255, 255, 255);
}
.btn.page_go {
border-color: rgb(230, 231, 236); width: auto; height: 30px; color: rgb(34, 34, 34); line-height: 30px; padding-right: 20px; padding-left: 20px; background-image: linear-gradient(rgb(255, 255, 255) 0px, rgb(255, 255, 255) 100%); background-color: rgb(255, 255, 255);
}
.btn.page_first button {
color: rgb(34, 34, 34);
}
.btn.page_last button {
color: rgb(34, 34, 34);
}
.btn.page_go button {
color: rgb(34, 34, 34);
}
.btn.page_first:hover {
border-color: rgb(218, 219, 224); color: rgb(0, 0, 0); box-shadow: none; background-image: linear-gradient(rgb(230, 231, 236) 0px, rgb(230, 231, 236) 100%); background-color: rgb(230, 231, 236); -moz-box-shadow: none; -webkit-box-shadow: none;
}
.btn.page_last:hover {
border-color: rgb(218, 219, 224); color: rgb(0, 0, 0); box-shadow: none; background-image: linear-gradient(rgb(230, 231, 236) 0px, rgb(230, 231, 236) 100%); background-color: rgb(230, 231, 236); -moz-box-shadow: none; -webkit-box-shadow: none;
}
.btn.page_go:hover {
border-color: rgb(218, 219, 224); color: rgb(0, 0, 0); box-shadow: none; background-image: linear-gradient(rgb(230, 231, 236) 0px, rgb(230, 231, 236) 100%); background-color: rgb(230, 231, 236); -moz-box-shadow: none; -webkit-box-shadow: none;
}
.btn.page_first:hover button {
color: rgb(34, 34, 34);
}
.btn.page_last:hover button {
color: rgb(34, 34, 34);
}
.btn.page_go:hover button {
color: rgb(34, 34, 34);
}
.page_next .arrow {
border-width: 6px 0px 6px 6px; border-style: dashed dashed dashed solid; border-color: transparent transparent transparent rgb(145, 145, 145); width: 0px; height: 0px; display: inline-block;
}
.page_prev .arrow {
border-width: 6px 6px 6px 0px; border-style: dashed solid dashed dashed; border-color: transparent rgb(145, 145, 145) transparent transparent; width: 0px; height: 0px; display: inline-block;
}
.page_num {
letter-spacing: normal; font-size: 14px; vertical-align: middle; display: inline-block;
}
.goto_area {
margin-left: 8px;
}
.goto_area input[type='text'] {
padding: 4px 0px; border-radius: 3px; border: 1px solid rgb(231, 231, 235); border-image: none; width: 75px; height: 22px; text-align: center; line-height: 22px; font-size: 14px; margin-right: 4px; vertical-align: middle; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none; -webkit-border-radius: 3px; -moz-border-radius: 3px;
}
.pagination .btn {
min-width: 0px;
}
.upload_box {
line-height: 1.6; vertical-align: middle; display: inline-block;
}
.upload_box.has_demo {
margin-left: 114px; position: relative;
}
.upload_box.show_preview .upload_preview {
display: block;
}
.upload_box.tips_inline .upload_tips {
padding-bottom: 0px; font-style: normal; font-weight: 400; margin-left: 3px; vertical-align: middle; display: inline-block;
}
.frm_input_box .upload_box {
margin-top: -0.35em;
}
.frm_input_box .upload_box .upload_file_box {
border-color: rgb(211, 211, 211); border-radius: 0px; -webkit-border-radius: 0; -moz-border-radius: 0;
}
.frm_input_box .upload_box .upload_preview img {
max-height: 100px; max-width: 100px;
}
.upload_demo {
left: -114px; top: 0px; width: 100px; position: absolute;
}
.upload_demo img {
width: 100%;
}
.upload_demo strong {
color: rgb(141, 141, 141); padding-bottom: 5px; font-style: normal; font-weight: 400; display: block;
}
.upload_area {
vertical-align: middle; display: inline-block; position: relative;
}
.upload_area object {
left: 0px; top: 0px; width: 100%; height: 100%; position: absolute; opacity: 0; -moz-opacity: 0; -khtml-opacity: 0;
}
.btn.btn_upload {
border-color: rgb(231, 231, 235); width: auto; height: 30px; color: rgb(34, 34, 34); line-height: 30px; padding-right: 22px; padding-left: 22px; background-image: linear-gradient(rgb(255, 255, 255) 0px, rgb(255, 255, 255) 100%); background-color: rgb(255, 255, 255);
}
.btn.btn_upload button {
color: rgb(34, 34, 34);
}
.btn.btn_upload:hover {
border-color: rgb(218, 219, 224); color: rgb(0, 0, 0); box-shadow: none; background-image: linear-gradient(rgb(231, 231, 235) 0px, rgb(231, 231, 235) 100%); background-color: rgb(231, 231, 235); -moz-box-shadow: none; -webkit-box-shadow: none;
}
.btn.btn_upload:hover button {
color: rgb(34, 34, 34);
}
.upload_tips {
color: rgb(141, 141, 141); padding-bottom: 6px;
}
.upload_file_box {
border-radius: 0px; border: 1px solid rgb(231, 231, 235); border-image: none; left: 0px; top: 100%; white-space: nowrap; position: absolute; box-shadow: none; background-color: rgb(255, 255, 255); -moz-box-shadow: none; -webkit-box-shadow: none; -webkit-border-radius: 0; -moz-border-radius: 0;
}
.upload_file {
padding: 3px 12px;
}
.progress_bar {
border-radius: 0px; width: 200px; overflow: hidden; vertical-align: middle; display: inline-block; background-color: rgb(231, 231, 235); -webkit-border-radius: 0; -moz-border-radius: 0;
}
.progress_bar_thumb {
height: 5px; background-color: rgb(90, 161, 221);
}
.upload_file_name {
width: auto; overflow: hidden; font-style: normal; font-weight: 400; vertical-align: middle; display: inline-block; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis; max-width: 100px;
}
.upload_file_size {
width: auto; color: rgb(141, 141, 141); overflow: hidden; margin-right: 10px; vertical-align: middle; display: inline-block; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis; max-width: 100px;
}
.upload_file_status {
font-style: normal; font-weight: 400; display: none;
}
.upload_file_status.success {
color: rgb(127, 186, 79);
}
.upload_file_status.error {
color: rgb(177, 21, 22);
}
.upload_preview {
margin-top: 10px; display: none;
}
.upload_preview img {
width: 100px;
}
.upload_preview .upload_access {
color: rgb(34, 34, 34); text-decoration: none; vertical-align: top; display: inline-block;
}
.upload_preview .upload_access i {
margin-top: -0.2em;
}
.upload_box {
position: relative; z-index: 1;
}
.upload_box.has_demo {
margin-left: 0px; min-height: 130px;
}
.upload_box.align_right .upload_file_box {
left: auto; right: 0px;
}
.upload_demo {
left: auto; right: 0px; padding-left: 40px; margin-right: -175px; border-left-color: rgb(231, 231, 235); border-left-width: 1px; border-left-style: solid;
}
.upload_demo img {
width: auto; max-height: 100px; max-width: 100px;
}
.upload_area:hover object {
opacity: 0.01; -moz-opacity: .01; -khtml-opacity: .01;
}
.btn.btn_upload_primary {
border-color: rgb(68, 181, 73); color: rgb(255, 255, 255); background-image: linear-gradient(rgb(68, 181, 73) 0px, rgb(68, 181, 73) 100%); background-color: rgb(68, 181, 73);
}
.btn.btn_upload_primary button {
color: rgb(255, 255, 255);
}
.btn.btn_upload_primary:hover {
border-color: rgb(47, 152, 51); color: rgb(255, 255, 255); box-shadow: none; background-image: linear-gradient(rgb(47, 152, 51) 0px, rgb(47, 152, 51) 100%); background-color: rgb(47, 152, 51); -moz-box-shadow: none; -webkit-box-shadow: none;
}
.btn.btn_upload_primary:hover button {
color: rgb(255, 255, 255);
}
.upload_tips {
font-style: normal; font-weight: 400;
}
.upload_msg.warn {
color: rgb(225, 95, 99);
}
.upload_file_box {
padding: 5px 0px; margin-top: -1px; max-height: 300px;
}
.upload_file_box.scroll {
-ms-overflow-x: hidden; -ms-overflow-y: scroll;
}
.upload_file {
padding: 4px 24px;
}
.upload_file:hover {
background-color: rgb(244, 245, 249);
}
.upload_file_name {
width: 95px;
}
.upload_file_size {
width: 80px;
}
.upload_file_status.error {
color: rgb(225, 95, 99);
}
.upload_file_status.success {
color: rgb(127, 186, 79);
}
.upload_file_cancel {
margin-left: 10px;
}
.upload_preview {
display: block;
}
.upload_preview img {
margin-left: 1em; max-height: 100px; max-width: 100px;
}
.upload_preview img:first-child {
margin-left: 0px;
}
.upload_preview .upload_preview_pic {
margin-right: 10px;
}
.bCardPreviewBox #bCardUserInput {
border-width: 1px; border-style: solid; border-color: rgb(102, 102, 102) rgb(170, 170, 170) rgb(170, 170, 170); padding: 5px; outline: 0px; border-image: none; width: 300px; margin-right: 10px; box-shadow: inset 0px 1px 1px #aaa;
}
.bCardPreviewBox .inputArea .desc {
padding: 5px 0px; color: rgb(102, 102, 102);
}
.bCardPreviewBox .inputArea .desc::after {
height: 0px; clear: both; display: block; content: "\200B";
}
.bCardPreviewBox .inputArea a {
color: rgb(69, 113, 163);
}
.bCardPreviewBox .inputArea .desc {
color: rgb(102, 102, 102); padding-bottom: 10px;
}
.bCardPreviewBox #previewBox {
padding: 20px 0px;
}
.bcardBox .bCard {
overflow: hidden; background-color: rgb(255, 255, 255);
}
.bcardBox .bCardHeader {
margin: 2px 10px; color: rgb(170, 170, 170); border-bottom-color: rgb(211, 211, 211); border-bottom-width: 1px; border-bottom-style: solid;
}
.bcardBox .bCardContent {
padding: 8px 10px; overflow: hidden;
}
.bcardBox .bCardContent .bCardAvatar {
width: 48px; height: 48px; float: left;
}
.bcardBox .bCardContent .info {
margin-left: 60px;
}
.bcardBox .bCardContent .info .nickname {
padding-bottom: 3px; font-size: 16px; font-weight: 700;
}
.bcardBox .bCardContent .info .username {
color: rgb(102, 102, 102); font-size: 14px;
}
.audioBox {
width: 80px; height: 80px; display: block; position: relative; background-color: rgb(228, 228, 228);
}
.audioBox .audioIconWrp {
margin: -16px 0px 0px -16px; left: 50%; top: 50%; width: 32px; height: 32px; position: absolute;
}
.audioBox .audioIcon {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px 0px; width: 32px; height: 32px; vertical-align: middle; display: inline-block;
}
.audioBox .audioIconGif {
background: url("/mpres/htmledition/images/icon/media/icon_audio_gray_s218877.gif") no-repeat 0px 0px; width: 32px; height: 32px; vertical-align: middle; display: none;
}
.audioBox b {
right: 5px; bottom: 2px; color: rgb(183, 183, 183); font-size: 12px; font-weight: normal; position: absolute;
}
.audioBox .desc {
left: 90px; top: 0px; color: rgb(34, 34, 34); display: none; white-space: nowrap; position: absolute;
}
.large_audiobox_wrp .audioBox .audioIcon {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -42px; width: 48px; height: 48px; vertical-align: middle; display: inline-block;
}
.large_audiobox_wrp .audioBox .audioIconGif {
background: url("/mpres/htmledition/images/icon/media/icon_audio_gray_b218877.gif") no-repeat 0px 0px; width: 48px; height: 48px; vertical-align: middle; display: none;
}
.large_audiobox_wrp .audioBox .audioIconWrp {
margin: -24px 0px 0px -24px; width: 48px; height: 48px;
}
.large_audiobox_wrp .audioBox b {
font-size: 14px;
}
.wxAudioPlaying .audioBox .audioIcon {
display: none;
}
.wxAudioPlaying .audioBox .audioIconGif {
display: block;
}
.video-js {
padding: 0px; font-size: 12px; vertical-align: middle; position: relative; z-index: 1; -ms-user-select: none; background-color: rgb(0, 0, 0); -webkit-user-select: none; -moz-user-select: none; -o-user-select: none; user-select: none;
}
.video-js .vjs-tech {
left: 0px; top: 0px; width: 100%; height: 100%; position: absolute;
}
body.vjs-full-window {
margin: 0px; padding: 0px; height: 100%; -ms-overflow-y: auto;
}
.video-js.vjs-fullscreen {
left: 0px; top: 0px; width: 100% !important; height: 100% !important; right: 0px; bottom: 0px; overflow: hidden; position: fixed; z-index: 1000; _position: absolute;
}
.vjs-poster {
background-position: 50% 50%; margin: 0px; padding: 0px; width: 100%; height: 100%; position: relative; cursor: pointer; background-repeat: no-repeat; background-size: contain;
}
.vjs-poster img {
margin: 0px auto; padding: 0px; width: 100%; display: block; max-height: 100%;
}
.video-js .vjs-text-track-display {
left: 1em; text-align: center; right: 1em; bottom: 4em; font-family: Arial,sans-serif; position: absolute;
}
.video-js .vjs-text-track {
background: rgba(0, 0, 0, 0.5); text-align: center; font-size: 1.4em; margin-bottom: 0.1em; display: none;
}
.video-js .vjs-subtitles {
color: rgb(255, 255, 255);
}
.video-js .vjs-captions {
color: rgb(255, 204, 102);
}
.vjs-tt-cue {
display: block;
}
.vjs-fade-in {
transition:visibility 0.1s, opacity 0.1s; display: block !important; visibility: visible; opacity: 1; -webkit-transition: visibility .1s, opacity .1s; -moz-transition: visibility .1s, opacity .1s; -o-transition: visibility .1s, opacity .1s;
}
.vjs-fade-out {
transition:; display: block !important; visibility: hidden; opacity: 0; -webkit-transition: visibility 1.5s, opacity 1.5s; -moz-transition: visibility 1.5s, opacity 1.5s; -o-transition: visibility 1.5s, opacity 1.5s; -webkit-transition-delay: 2s; -moz-transition-delay: 2s; -o-transition-delay: 2s;
}
.vjs-default-skin .vjs-hidden {
display: none;
}
.vjs-lock-showing {
display: block !important; visibility: visible; opacity: 1;
}
.vjs-default-skin {
color: rgb(204, 204, 204);
}
.vjs-default-skin .vjs-slider {
background: rgba(100, 100, 100, 0.5); padding: 0px; outline: 0px; position: relative; cursor: pointer;
}
.vjs-default-skin .vjs-slider:focus {
background: rgba(100, 100, 100, 0.7); box-shadow: 0px 0px 2em #fff; -moz-box-shadow: 0 0 2em #fff; -webkit-box-shadow: 0 0 2em #fff;
}
.vjs-default-skin .vjs-slider-handle {
left: 0px; top: 0px; width: 6px; height: 6px; position: absolute;
}
.vjs-default-skin .vjs-control-bar {
margin: 0px; padding: 0px; left: 0px; height: 3em; right: 0px; bottom: 0px; font-family: Arial,sans-serif; font-style: normal; font-weight: normal; display: none; position: absolute; background-color: rgba(7, 40, 50, 0.7);
}
.vjs-default-skin .vjs-control {
margin: 0px; padding: 0px; outline: 0px; width: 4em; height: 3em; text-align: center; float: left; position: relative;
}
.vjs-default-skin .vjs-control::before {
left: 0px; top: 0px; width: 100%; height: 100%; text-align: center; line-height: 2; font-family: VideoJS; font-size: 1.5em; position: absolute; text-shadow: 1px 1px 1px rgba(0,0,0,0.5);
}
.vjs-default-skin .vjs-control:focus::before {
text-shadow: 0px 0px 1em #fff;
}
.vjs-default-skin .vjs-control:hover::before {
text-shadow: 0px 0px 1em #fff;
}
.vjs-default-skin .vjs-control-text {
margin: -1px; padding: 0px; border: 0px currentColor; border-image: none; width: 1px; height: 1px; overflow: hidden; position: absolute; clip: rect(0px, 0px, 0px, 0px);
}
.vjs-default-skin .vjs-play-control {
background: url("/mpres/htmledition/images/icon/media/icon_videojs218877.png") no-repeat 0px 0px; width: 5em; cursor: pointer;
}
.vjs-default-skin.vjs-playing .vjs-play-control {
background-position: -55px 10px;
}
.vjs-default-skin.vjs-paused .vjs-play-control {
background-position: 20px 10px;
}
.vjs-default-skin .vjs-fullscreen-control {
background: url("/mpres/htmledition/images/icon/media/icon_videojs218877.png") no-repeat -142px 10px;
}
.vjs-default-skin.vjs-fullscreen .vjs-fullscreen-control {
background-position: -211px 10px;
}
.vjs-default-skin .vjs-mute-control {
background: url("/mpres/htmledition/images/icon/media/icon_videojs218877.png") no-repeat -142px -50px; display: none;
}
.vjs-default-skin .vjs-mute-control.vjs-vol-3 {
background-position: -142px -50px;
}
.vjs-default-skin .vjs-mute-control.vjs-vol-0 {
background-position: 6px -50px;
}
.vjs-default-skin .vjs-mute-control {
float: right; cursor: pointer;
}
.vjs-default-skin .vjs-volume-menu-button {
float: right; cursor: pointer;
}
.vjs-default-skin .vjs-mute-control::before {
content: "\e006";
}
.vjs-default-skin .vjs-volume-menu-button::before {
content: "\e006";
}
.vjs-default-skin .vjs-mute-control.vjs-vol-0::before {
content: "\e003";
}
.vjs-default-skin .vjs-volume-menu-button.vjs-vol-0::before {
content: "\e003";
}
.vjs-default-skin .vjs-mute-control.vjs-vol-1::before {
content: "\e004";
}
.vjs-default-skin .vjs-volume-menu-button.vjs-vol-1::before {
content: "\e004";
}
.vjs-default-skin .vjs-mute-control.vjs-vol-2::before {
content: "\e005";
}
.vjs-default-skin .vjs-volume-menu-button.vjs-vol-2::before {
content: "\e005";
}
.vjs-default-skin .vjs-volume-control {
width: 5em; float: right;
}
.vjs-default-skin .vjs-volume-bar {
margin: 1.1em auto 0px; width: 5em; height: 5px;
}
.vjs-default-skin .vjs-volume-menu-button .vjs-menu-content {
height: 2.9em;
}
.vjs-default-skin .vjs-volume-level {
left: 0px; top: 0px; height: 5px; position: absolute; background-color: rgb(90, 161, 221);
}
.vjs-default-skin .vjs-volume-bar .vjs-volume-handle {
width: 0.5em; height: 5px;
}
.vjs-default-skin .vjs-volume-handle::before {
left: -0.2em; top: -0.2em; width: 1em; height: 1em; font-size: 0.9em;
}
.vjs-default-skin .vjs-volume-menu-button .vjs-menu .vjs-menu-content {
left: -4em; width: 6em;
}
.vjs-default-skin .vjs-progress-control {
transition:top 0.4s, height 0.4s, font-size 0.4s, transform 0.4s; left: 0px; top: -5px; width: auto; height: 5px; right: 0px; font-size: 0.3em; position: absolute; -webkit-transition: top .4s, height .4s, font-size .4s, -webkit-transform .4s; -moz-transition: top .4s, height .4s, font-size .4s, -moz-transform .4s; -o-transition: top .4s, height .4s, font-size .4s, -o-transform .4s;
}
.vjs-default-skin:hover .vjs-progress-control {
transition:top 0.2s, height 0.2s, font-size 0.2s, transform 0.2s; font-size: 0.9em; -webkit-transition: top .2s, height .2s, font-size .2s, -webkit-transform .2s; -moz-transition: top .2s, height .2s, font-size .2s, -moz-transform .2s; -o-transition: top .2s, height .2s, font-size .2s, -o-transform .2s;
}
.vjs-default-skin .vjs-progress-holder {
height: 100%;
}
.vjs-default-skin .vjs-progress-holder .vjs-play-progress {
margin: 0px; padding: 0px; left: 0px; top: 0px; height: 100%; display: block; position: absolute;
}
.vjs-default-skin .vjs-progress-holder .vjs-load-progress {
margin: 0px; padding: 0px; left: 0px; top: 0px; height: 100%; display: block; position: absolute;
}
.vjs-default-skin .vjs-play-progress {
background-color: rgb(90, 161, 221);
}
.vjs-default-skin .vjs-load-progress {
background: rgba(255, 255, 255, 0.4);
}
.vjs-default-skin .vjs-seek-handle {
width: 1.5em; height: 100%;
}
.vjs-default-skin .vjs-seek-handle::before {
padding-top: 0.1em;
}
.vjs-default-skin .vjs-time-controls {
width: 35px; line-height: 3em; font-size: 1em;
}
.vjs-default-skin .vjs-current-time {
float: left;
}
.vjs-default-skin .vjs-duration {
float: left;
}
.vjs-default-skin .vjs-remaining-time {
float: left; display: none;
}
.vjs-time-divider {
line-height: 3em; float: left;
}
.vjs-default-skin .vjs-fullscreen-control {
width: 3.8em; float: right; cursor: pointer;
}
.vjs-default-skin .vjs-big-play-button {
background: url("/mpres/htmledition/images/icon/media/icon_videojs218877.png") no-repeat -275px 28px rgba(7, 40, 50, 0.7); border-radius: 25px; border: 2px solid rgba(255, 255, 255, 0.25); border-image: none; left: 50%; top: 50%; width: 150px; height: 100px; text-align: center; margin-top: -50px; margin-left: -75px; vertical-align: middle; display: block; position: absolute; z-index: 2; cursor: pointer; opacity: 1; box-shadow: 0px 0px 1em rgba(255,255,255,0.25); -moz-box-shadow: 0 0 1em rgba(255, 255, 255, 0.25); -webkit-box-shadow: 0 0 1em rgba(255, 255, 255, 0.25); -webkit-border-radius: 25px; -moz-border-radius: 25px;
}
.vjs-default-skin:hover .vjs-big-play-button {
outline: 0px; box-shadow: 0px 0px 3em #fff; background-color: rgba(50, 50, 50, 0.75); -moz-box-shadow: 0 0 3em #fff; -webkit-box-shadow: 0 0 3em #fff;
}
.vjs-default-skin .vjs-big-play-button:focus {
outline: 0px; box-shadow: 0px 0px 3em #fff; background-color: rgba(50, 50, 50, 0.75); -moz-box-shadow: 0 0 3em #fff; -webkit-box-shadow: 0 0 3em #fff;
}
.vjs-loading-spinner {
background: url("/mpres/htmledition/images/icon/common/icon32_loading_dark218877.gif") no-repeat 50% 50% rgba(0, 0, 0, 0.75); border-radius: 5px; left: 50%; top: 50%; width: 1em; height: 1em; line-height: 1; font-size: 5em; margin-top: -0.5em; margin-left: -0.5em; display: none; position: absolute; opacity: 0.75; -webkit-border-radius: 5px; -moz-border-radius: 5px;
}
.vjs-default-skin .vjs-menu-button {
float: right; cursor: pointer;
}
.vjs-default-skin .vjs-menu {
left: 0px; width: 0px; height: 0px; bottom: 0px; margin-bottom: 3em; border-top-color: rgba(7, 40, 50, 0.5); border-right-color: transparent; border-left-color: transparent; border-top-width: 1.55em; border-right-width: 2em; border-left-width: 2em; border-top-style: solid; border-right-style: solid; border-left-style: solid; display: none; position: absolute;
}
.vjs-default-skin .vjs-menu-button .vjs-menu .vjs-menu-content {
margin: 0px; padding: 0px; left: -5em; width: 10em; bottom: 1.5em; overflow: auto; display: block; position: absolute; max-height: 15em; box-shadow: -0.2em -0.2em 0.3em rgba(255,255,255,0.2); background-color: rgba(7, 40, 50, 0.7); -moz-box-shadow: 0 0 1em rgba(255, 255, 255, 0.5); -webkit-box-shadow: -20px -20px 0 rgba(255, 255, 255, 0.5);
}
.vjs-default-skin .vjs-menu-button:hover .vjs-menu {
display: block;
}
.vjs-default-skin .vjs-menu-button ul li {
list-style: none; margin: 0px; padding: 0.3em 0px; text-align: center; text-transform: lowercase; line-height: 1.4em; font-size: 1.2em; font-weight: normal;
}
.vjs-default-skin .vjs-menu-button ul li.vjs-selected {
background-color: rgb(0, 0, 0);
}
.vjs-default-skin .vjs-menu-button ul li:focus {
outline: 0px; color: rgb(17, 17, 17); box-shadow: 0px 0px 1em #fff; background-color: rgba(255, 255, 255, 0.75); -moz-box-shadow: 0 0 1em #fff; -webkit-box-shadow: 0 0 1em #fff;
}
.vjs-default-skin .vjs-menu-button ul li:hover {
outline: 0px; color: rgb(17, 17, 17); box-shadow: 0px 0px 1em #fff; background-color: rgba(255, 255, 255, 0.75); -moz-box-shadow: 0 0 1em #fff; -webkit-box-shadow: 0 0 1em #fff;
}
.vjs-default-skin .vjs-menu-button ul li.vjs-selected:focus {
outline: 0px; color: rgb(17, 17, 17); box-shadow: 0px 0px 1em #fff; background-color: rgba(255, 255, 255, 0.75); -moz-box-shadow: 0 0 1em #fff; -webkit-box-shadow: 0 0 1em #fff;
}
.vjs-default-skin .vjs-menu-button ul li.vjs-selected:hover {
outline: 0px; color: rgb(17, 17, 17); box-shadow: 0px 0px 1em #fff; background-color: rgba(255, 255, 255, 0.75); -moz-box-shadow: 0 0 1em #fff; -webkit-box-shadow: 0 0 1em #fff;
}
.vjs-default-skin .vjs-menu-button ul li.vjs-menu-title {
margin: 0px 0px 0.3em; padding: 0px; text-align: center; text-transform: uppercase; line-height: 2em; font-size: 1em; font-weight: bold; cursor: default;
}
.vjs-default-skin .vjs-subtitles-button::before {
content: "\e00c";
}
.vjs-default-skin .vjs-captions-button::before {
content: "\e008";
}
.vjs-default-skin .vjs-captions-button:focus .vjs-control-content::before {
box-shadow: 0px 0px 1em #fff; -moz-box-shadow: 0 0 1em #fff; -webkit-box-shadow: 0 0 1em #fff;
}
.vjs-default-skin .vjs-captions-button:hover .vjs-control-content::before {
box-shadow: 0px 0px 1em #fff; -moz-box-shadow: 0 0 1em #fff; -webkit-box-shadow: 0 0 1em #fff;
}
.mediaBox.smallvideo_box .videoDuration {
display: none;
}
.videoBox .wxVideoPlayContent {
display: none;
}
.videoBox .wxVideoScreenshot {
overflow: hidden; display: block; position: relative;
}
.videoBox .wxImg {
width: 100px; height: 100px; margin-bottom: -4px; display: block;
}
.videoBox .videoDuration {
background: rgba(0, 0, 0, 0.5) !important; left: 0px; width: 100%; text-align: right; bottom: 0px; color: rgb(255, 255, 255); line-height: 20px; padding-right: 8px; margin-top: -6px; position: absolute;
}
.videoBox .videoDuration em {
font-style: normal; font-weight: 400; margin-right: 8px;
}
.videoBox .iconVideo {
left: 50%; top: 50%; margin-top: -18px; margin-left: -18px; position: absolute;
}
.wxVideoPlayer {
border-radius: 5px; overflow: hidden; -webkit-border-radius: 5px; -moz-border-radius: 5px;
}
.wxVideoPlaying .wxVideoPlayContent {
display: block;
}
.wxVideoPlaying .wxVideoScreenshot {
display: none;
}
.video_switch i {
width: 18px; height: 18px; padding-left: 0px; vertical-align: middle; display: inline-block;
}
.video_switch:hover i {
background-position: -28px -280px;
}
.appmsg {
border: 1px solid rgb(231, 231, 235); border-image: none; color: rgb(102, 102, 102); overflow: hidden; margin-bottom: 20px; position: relative; background-color: rgb(255, 255, 255);
}
.appmsg_info {
line-height: 20px; padding-bottom: 10px; font-size: 13px;
}
.appmsg_date {
font-style: normal; font-weight: 400;
}
.appmsg_content {
padding: 0px 14px; position: relative;
}
.appmsg_title {
line-height: 28px; overflow: hidden; padding-top: 10px; font-size: 16px; font-style: normal; font-weight: 400; -ms-word-break: break-all; -ms-word-wrap: break-word; max-height: 56px;
}
.appmsg_title a {
color: rgb(34, 34, 34); display: block;
}
.appmsg_thumb_wrp {
height: 160px; overflow: hidden;
}
.appmsg_thumb {
width: 100%;
}
.appmsg_desc {
padding: 5px 0px 10px; -ms-word-break: break-all; -ms-word-wrap: break-word;
}
.appmsg_opr {
border-top-color: rgb(231, 231, 235); border-top-width: 1px; border-top-style: solid; background-color: rgb(244, 244, 244);
}
.appmsg_opr ul {
overflow: hidden;
}
.appmsg_opr_item {
height: 44px; line-height: 44px; float: left;
}
.appmsg_opr_item a {
text-align: center; text-decoration: none; border-right-color: rgb(231, 231, 235); border-right-width: 1px; border-right-style: solid; display: block;
}
.appmsg_opr_item a:hover {
text-decoration: none;
}
.appmsg_opr_item a.no_extra {
border-right-width: 0px;
}
.appmsg_item {
padding: 20px 14px; border-top-color: rgb(231, 231, 235); border-top-width: 1px; border-top-style: solid; position: relative;
}
.appmsg_item::after {
height: 0px; clear: both; display: block; content: "\200B";
}
.appmsg_item .appmsg_title {
line-height: 24px; overflow: hidden; margin-top: 14px; max-height: 48px;
}
.appmsg_item .appmsg_thumb {
width: 78px; height: 78px; margin-left: 14px; float: right;
}
.multi .appmsg_info {
padding-top: 14px; padding-right: 14px; padding-left: 14px;
}
.multi .appmsg_content {
padding: 0px;
}
.multi .appmsg_title {
padding-top: 0px; font-size: 14px;
}
.cover_appmsg_item {
margin: 0px 14px 14px; position: relative;
}
.cover_appmsg_item .appmsg_title {
background: rgba(0, 0, 0, 0.6) !important; left: 0px; right: 0px; bottom: 0px; position: absolute;
}
.cover_appmsg_item .appmsg_title a {
padding: 0px 8px; color: rgb(255, 255, 255);
}
.first_appmsg_item {
position: relative;
}
.first_appmsg_item .cover_appmsg_item {
margin: 0px;
}
.first_appmsg_item .appmsg_title {
padding: 0px 8px; color: rgb(255, 255, 255);
}
.first_appmsg_item .appmsg_desc {
padding: 5px 8px 10px;
}
.first_appmsg_item .appmsg_edit_mask {
line-height: 197px;
}
.first_appmsg_item:hover .appmsg_edit_mask {
display: block;
}
.appmsg_mask {
left: 0px; top: 0px; width: 100%; height: 100%; display: none; position: absolute; z-index: 1; opacity: 0.6; background-color: rgb(0, 0, 0); -moz-opacity: .6; -khtml-opacity: .6;
}
.appmsg .icon_card_selected {
left: 50%; top: 50%; line-height: 999em; overflow: hidden; margin-top: -23px; margin-left: -23px; display: none; position: absolute; z-index: 1;
}
.dialog_wrp .appmsg:hover {
cursor: pointer;
}
.appmsg:hover .appmsg_mask {
display: block;
}
.appmsg.selected .appmsg_mask {
display: block;
}
.appmsg.selected .icon_card_selected {
display: inline-block;
}
.appmsg_thumb.default {
text-align: center; color: rgb(192, 192, 192); line-height: 160px; font-size: 16px; font-style: normal; font-weight: 400; display: block; background-color: rgb(236, 236, 236);
}
.appmsg_item .appmsg_thumb.default {
line-height: 78px; font-size: 14px;
}
.appmsg_edit_mask {
background: rgba(229, 229, 229, 0.85) !important; left: 0px; top: 0px; text-align: center; right: 0px; bottom: 0px; display: none; position: absolute;
}
.appmsg_item .appmsg_edit_mask {
line-height: 118px;
}
.cover_appmsg_item .appmsg_edit_mask {
line-height: 160px;
}
.appmsg_edit_mask a {
margin-right: 8px; margin-left: 8px;
}
.editing .cover_appmsg_item:hover .appmsg_edit_mask {
display: block;
}
.editing .appmsg_item:hover .appmsg_edit_mask {
display: block;
}
.editing .appmsg_thumb {
display: none;
}
.editing .appmsg_thumb.default {
display: block;
}
.editing .has_thumb .appmsg_thumb {
display: block;
}
.editing .has_thumb .appmsg_thumb.default {
display: none;
}
.editing .appmsg_content {
border-bottom-width: 0px; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none;
}
.editing.multi .appmsg_content {
border-bottom-width: 1px;
}
.appmsg_add {
margin: 20px 14px;
}
.tab_content .appmsg {
width: 320px;
}
.appmsg_list {
margin: 0px 30px; text-align: justify; letter-spacing: -4px; font-size: 0px; -ms-text-justify: distribute-all-lines;
}
.appmsg_list::after {
margin: 0px; padding: 0px; width: 100%; height: 0px; overflow: hidden; font-size: 0px; display: inline-block; content: ".";
}
.appmsg_list .tj_item {
text-align: left; font-size: 14px; -ms-text-justify: auto;
}
.appmsg_col {
width: 32%; text-align: left; letter-spacing: normal; font-size: 14px; vertical-align: top; display: inline-block;
}
.media_dialog.appmsg_list {
margin: 0px; padding: 28px 140px; height: 345px; position: relative; -ms-overflow-y: auto;
}
.media_dialog .appmsg_col {
width: 48%;
}
.qqmusic_audio {
display: inline-block;
}
.audio_switch {
display: inline-block;
}
.icon_qqmusic {
background: url("/mpres/htmledition/images/icon/media/qqmusic/icon_qqmusic_audio_default25df29.png") no-repeat 0px 0px; width: 30px; height: 30px; vertical-align: middle; display: inline-block;
}
.wxAudioPlaying .icon_qqmusic {
background: url("/mpres/htmledition/images/icon/media/qqmusic/icon_qqmusic_audio_playing25df29.gif") no-repeat 50% 50%;
}
.iconAudio {
background: url("/mpres/htmledition/images/icon/media/icon_audio_green218877.gif") no-repeat 0px 0px; width: 20px; height: 20px; vertical-align: middle; display: inline-block;
}
.iconVideo {
background: url("/mpres/htmledition/images/icon/media/icon_video_small238f6c.png") no-repeat 0px 0px; width: 36px; height: 36px; vertical-align: middle; display: inline-block;
}
.smallvideo_box .iconVideo {
background: url("/mpres/htmledition/images/icon_video218877.png") no-repeat 0px 0px; width: 36px; height: 36px; vertical-align: middle; display: inline-block;
}
.icon_tag_gray {
margin: -2px 1em 0px 0.5em; padding: 0px 0.28em; border-radius: 1px; color: rgb(255, 255, 255); line-height: 15px; font-size: 12px; display: inline-block; background-color: rgb(206, 206, 206); -webkit-border-radius: 1px; -moz-border-radius: 1px;
}
.highlight {
color: rgb(68, 181, 73);
}
.mediaBox {
display: inline-block; cursor: pointer;
}
.mediaBox .mediaContent {
float: left;
}
.mediaBox .iconArrow {
left: -7px; top: 8px; display: block; position: absolute;
}
.wxmImg {
display: block; max-width: 100%;
}
.appmsgContentArea {
-ms-word-break: break-all; -ms-word-wrap: break-word;
}
.appmsgImgArea {
padding: 3px; margin-right: 4px; float: left;
}
.appmsgImgArea img {
width: 80px; height: 80px; display: block;
}
.appmsgContentArea {
overflow: hidden;
}
.appmsgContentArea.multiple .appmsgTitle {
margin-top: 10px;
}
.appmsgContentArea.multiple :first-child.appmsgTitle {
margin-top: 0px;
}
.appmsgContentArea .appmsgTitle {
line-height: 21px; font-size: 14px;
}
.appmsgContentArea .appmsgDesc {
color: rgb(141, 141, 141); line-height: 21px; font-size: 14px;
}
.appmsgContentArea .icon_vote {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -100px; width: 18px; height: 16px; vertical-align: middle; display: inline-block;
}
.appmsgFrom {
color: rgb(34, 34, 34); font-size: 12px;
}
.appmsgFrom.resource {
margin-top: 10px; margin-left: 90px;
}
.media_img {
display: inline-block;
}
.appmsgSendedItem {
padding-left: 90px; position: relative; min-height: 80px;
}
.appmsgSendedItem .title_wrp {
color: rgb(34, 34, 34); display: inline-block;
}
.appmsgSendedItem .title_wrp .title.deleted {
color: rgb(141, 141, 141);
}
.appmsgSendedItem .title_wrp .icon {
background-position: 0px 0px; left: 0px; width: 80px; height: 80px; vertical-align: middle; display: inline-block; position: absolute; background-image: none; background-attachment: scroll; background-repeat: no-repeat; background-size: auto; background-origin: padding-box; background-clip: border-box; background-color: rgb(215, 216, 218) !important;
}
.appmsgSendedItem .title_wrp .icon i {
left: 50%; top: 50%; width: 40px; height: 40px; margin-top: -20px; margin-left: -20px; position: absolute; content: " ";
}
.appmsgSendedItem .title_wrp .icon::before {
left: 50%; top: 50%; width: 40px; height: 40px; margin-top: -20px; margin-left: -20px; position: absolute; content: " ";
}
.appmsgSendedItem .title_wrp:hover .icon.icon_lh {
background-color: rgb(197, 198, 200) !important;
}
.appmsgSendedItem .appsmg_item {
margin-top: 10px;
}
.appmsgSendedItem :first-child.appsmg_item {
margin-top: 0px;
}
.appmsgSendedItem .desc {
color: rgb(102, 102, 102);
}
.appmsgSendedItem .desc a.appmsg_desc {
color: rgb(102, 102, 102);
}
.appmsgSendedItem .icon_vote {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -126px; width: 18px; height: 16px; margin-right: 5px; vertical-align: -2px; display: inline-block;
}
.appmsgSendedItem.multiple_appmsg .icon i {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -152px;
}
.appmsgSendedItem.multiple_appmsg .icon::before {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -152px;
}
.appmsgSendedItem.card_ticket .icon i {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -202px;
}
.appmsgSendedItem.card_ticket .icon::before {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -202px;
}
.appmsgSendedItem.textmsg .icon i {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -252px;
}
.appmsgSendedItem.textmsg .icon::before {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -252px;
}
.appmsgSendedItem.simple_audiomsg .icon i {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -302px;
}
.appmsgSendedItem.simple_audiomsg .icon::before {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -302px;
}
.wxAudioPlaying .appmsgSendedItem.simple_audiomsg .icon i {
background: url("/mpres/htmledition/images/icon/media/icon_audio2880f5.gif") no-repeat center;
}
.wxAudioPlaying .appmsgSendedItem.simple_audiomsg .icon::before {
background: url("/mpres/htmledition/images/icon/media/icon_audio2880f5.gif") no-repeat center;
}
.appmsgSendedItem.simple_audiomsg .desc {
display: none;
}
.appmsgSendedItem a {
display: inline-block;
}
.msg_sender .appmsgSendedItem {
padding-left: 0px; display: inline-block;
}
.msg_sender .appmsgSendedItem .icon {
position: static;
}
.msg_sender .audio_msg {
display: inline-block;
}
.msg_sender .appmsg {
display: inline-block;
}
.msg_sender .richvideo {
display: inline-block;
}
.msg_sender .msg_card {
display: inline-block;
}
.msg_sender .audio_msg {
padding: 10px; border: 1px solid rgb(231, 231, 235); border-image: none; width: 300px;
}
.link_dele {
padding-left: 10px; margin-bottom: 5px; vertical-align: bottom; display: inline-block;
}
.qqmusic_dialog .global_mod .frm_input_box {
width: 255px;
}
.qqmusic_box_hd {
padding: 14px 20px; border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid;
}
.qqmusic_box_bd {
min-height: 387px;
}
.qqmusic_list_container .media_list_tips_wrp {
height: 315px;
}
.qqmusic_list_container .qqmusic_list {
height: 315px; -ms-overflow-y: auto;
}
.qqmusic_list_container .media_list_tips_wrp {
text-align: center;
}
.qqmusic_list_container .media_list_tips_wrp .tips {
vertical-align: middle; display: inline-block;
}
.qqmusic_list_container .pagination_wrp {
padding: 20px;
}
.qqmusic_list {
text-align: left;
}
.qqmusic_item {
margin: 0px 0px 0px 20px; padding: 9px 0px; overflow: hidden; border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid; display: block;
}
.qqmusic_item .lbl_content {
vertical-align: top; display: inline-block;
}
.qqmusic_meta {
width: auto; overflow: hidden; float: left; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis;
}
.qqmusic_thumb_info {
width: 500px;
}
.qqmusic_thumb_info .songname {
display: block;
}
.qqmusic_thumb_info .singername {
color: rgb(141, 141, 141); display: inline-block;
}
.qqmusic_songsize {
width: 170px; color: rgb(141, 141, 141);
}
.qqmusic_songtime {
width: 170px; color: rgb(141, 141, 141);
}
.audio_dialog .audio_box_hd {
padding: 14px 20px; border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid;
}
.audio_dialog .audio_box_bd {
min-height: 380px;
}
.audio_dialog .audio_list_container .media_list_tips_wrp {
height: 308px;
}
.audio_dialog .audio_list_container .audio_list {
height: 308px; -ms-overflow-y: auto;
}
.audio_dialog .audio_list_container .media_list_tips_wrp {
text-align: center;
}
.audio_dialog .audio_list_container .media_list_tips_wrp .tips {
vertical-align: middle; display: inline-block;
}
.audio_dialog .audio_list_container .pagination_wrp {
padding: 20px;
}
.audio_dialog .audio_list {
text-align: left;
}
.audio_dialog .audio_item {
margin: 0px 0px 0px 20px; padding: 16px 0px; overflow: hidden; border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid; display: block;
}
.audio_dialog .audio_item .lbl_content {
display: inline-block;
}
.audio_dialog .audio_meta {
width: auto; overflow: hidden; margin-right: 1em; vertical-align: middle; display: inline-block; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis;
}
.audio_dialog .audio_title {
width: 420px;
}
.audio_dialog .audio_date {
width: 190px;
}
.audio_dialog .audio_length {
width: 160px;
}
.audio_msg {
overflow: hidden;
}
.audio_msg .audio_content {
overflow: hidden;
}
.audio_msg .icon_audio_msg {
margin-right: 1em; float: left;
}
.audio_msg .audio_title {
color: rgb(34, 34, 34);
}
.audio_msg .audio_length {
color: rgb(141, 141, 141);
}
.audio_msg .audio_date {
color: rgb(141, 141, 141);
}
.audio_msg_wrp.preview_card {
padding: 10px; border: 1px solid rgb(231, 231, 235); border-image: none;
}
.audio_msg_wrp.preview_card .audio_title {
width: auto; overflow: hidden; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis;
}
.audio_msg_wrp.card .audio_content {
overflow: hidden; position: relative;
}
.audio_msg_wrp.card .audio_length {
top: 0px; right: 0px; margin-left: 1em; position: absolute;
}
.audio_msg_wrp.card .audio_title {
width: auto; overflow: hidden; margin-right: 56px; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis;
}
.icon_audio_msg {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -352px; width: 60px; height: 60px; vertical-align: middle; display: inline-block; cursor: pointer;
}
.wxAudioPlaying .icon_audio_msg {
background: url("/mpres/htmledition/images/icon/media/audio/icon_audio2767e5.gif") no-repeat 0px 0px;
}
.audio_primary .icon_audio_msg {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -422px; width: 80px; height: 80px; vertical-align: middle; display: inline-block;
}
.audio_primary .icon_qqmusic {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -512px; width: 80px; height: 80px; vertical-align: middle; display: inline-block; cursor: pointer;
}
.audio_primary.wxAudioPlaying .icon_audio_msg {
background: url("/mpres/htmledition/images/icon/media/audio/icon_audio_primary2767e5.gif") no-repeat 0px 0px;
}
.audio_primary.wxAudioPlaying .icon_qqmusic {
background: url("/mpres/htmledition/images/icon/media/audio/icon_audio_primary2767e5.gif") no-repeat 0px 0px;
}
.audio_default .icon_qqmusic {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media_z2968da.png") no-repeat 0px -602px; width: 60px; height: 60px; vertical-align: middle; display: inline-block; cursor: pointer;
}
.audio_default.wxAudioPlaying .icon_audio_msg {
background: url("/mpres/htmledition/images/icon/media/audio/icon_audio2767e5.gif") no-repeat 0px 0px;
}
.audio_default.wxAudioPlaying .icon_qqmusic {
background: url("/mpres/htmledition/images/icon/media/audio/icon_audio2767e5.gif") no-repeat 0px 0px;
}
.play_dialog .dialog_bd {
text-align: center;
}
.play_dialog iframe {
vertical-align: top; display: inline-block;
}
.icon_richvideo_create {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/richvideo_z27bb72.png") no-repeat 0px 0px; width: 38px; height: 38px; vertical-align: middle; display: inline-block;
}
a:hover .icon_richvideo_create {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/richvideo_z27bb72.png") no-repeat 0px -48px;
}
.icon_richvideo_small {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/richvideo_z27bb72.png") no-repeat 0px -96px; width: 18px; height: 18px; vertical-align: middle; display: inline-block;
}
a:hover .icon_richvideo_small {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/richvideo_z27bb72.png") no-repeat 0px -124px;
}
.icon_richvideo_error {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/richvideo_z27bb72.png") no-repeat 0px -152px; width: 86px; height: 86px; vertical-align: middle; display: inline-block;
}
.icon_video {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/richvideo_z27bb72.png") no-repeat 0px -248px; width: 50px; height: 50px; vertical-align: middle; display: inline-block;
}
.richvideo_list {
margin: 0px 46px; text-align: justify; letter-spacing: -4px; padding-top: 38px; font-size: 0px; -ms-text-justify: distribute-all-lines;
}
.richvideo_list::after {
margin: 0px; padding: 0px; width: 100%; height: 0px; overflow: hidden; font-size: 0px; display: inline-block; content: ".";
}
.richvideo_list .tj_item {
text-align: left; font-size: 14px; -ms-text-justify: auto;
}
.richvideo_col {
width: 47%; text-align: left; letter-spacing: normal; font-size: 14px; vertical-align: top; display: inline-block;
}
.media_dialog.richvideo_list {
margin: 0px; padding: 28px 150px; height: 315px; position: relative; -ms-overflow-y: scroll;
}
.richvideo {
border: 1px solid rgb(231, 231, 235); border-image: none; color: rgb(141, 141, 141); overflow: hidden; margin-bottom: 20px; position: relative; background-color: rgb(255, 255, 255);
}
.richvideo_content {
padding: 10px 14px 16px; position: relative;
}
.richvideo_content .title {
font-size: 16px; font-style: normal; font-weight: 400; -ms-word-break: break-all; -ms-word-wrap: break-word;
}
.richvideo_content .video_info {
line-height: 20px; padding-bottom: 6px; font-size: 13px;
}
.richvideo_content .video_info::after {
height: 0px; clear: both; display: block; content: "\200B";
}
.richvideo_content .video_info em {
font-style: normal; font-weight: 400;
}
.richvideo_content .video_info .time {
float: left;
}
.richvideo_content .video_info .res {
color: rgb(141, 141, 141);
}
.richvideo_content .video_wrp {
min-height: 160px;
}
.richvideo_content .video_thumb {
width: 100%; height: 100%; display: block;
}
.richvideo_content .video_player {
height: 160px; overflow: hidden; display: none;
}
.richvideo_content .video_player video {
width: 100%; height: 100%;
}
.richvideo_content .video_shot {
height: 160px; position: relative; cursor: pointer;
}
.richvideo_content .video_shot img {
width: 100%; height: 100%; max-height: none; max-width: none;
}
.richvideo_content .icon_video {
left: 50%; top: 50%; margin-top: -32px; margin-left: -18px; position: absolute;
}
.richvideo_content .video_duration {
background: rgba(0, 0, 0, 0.6) !important; left: 0px; width: 100%; height: 24px; text-align: right; bottom: 0px; color: rgb(255, 255, 255); line-height: 24px; position: absolute;
}
.richvideo_content .video_duration em {
font-style: normal; font-weight: 400; margin-right: 14px;
}
.richvideo_content .video_desc {
-ms-word-break: break-all; -ms-word-wrap: break-word;
}
.richvideo_mask {
left: 0px; top: 0px; width: 100%; height: 100%; display: none; position: absolute; z-index: 1; opacity: 0.6; background-color: rgb(0, 0, 0); -moz-opacity: .6; -khtml-opacity: .6;
}
.richvideo .icon_card_selected {
left: 50%; top: 50%; line-height: 999em; overflow: hidden; margin-top: -23px; margin-left: -23px; display: none; position: absolute; z-index: 1;
}
.richvideo .richvideo_tips {
left: 0px; top: 0px; text-align: center; right: 0px; color: rgb(255, 255, 255); margin-top: 35px; display: none; position: absolute; z-index: 1;
}
.richvideo .richvideo_tips .icon_richvideo_error {
margin-bottom: 14px;
}
.richvideo .richvideo_tips a {
color: rgb(31, 149, 192);
}
.richvideo .loading_tips {
background: rgba(0, 0, 0, 0.75) !important; border-radius: 3px; left: 50%; top: 50%; width: 100px; height: 80px; text-align: center; color: rgb(255, 255, 255); margin-top: -40px; margin-left: -50px; position: absolute; z-index: 1; -webkit-border-radius: 3px; -moz-border-radius: 3px;
}
.richvideo .loading_tips i {
margin: 10px 0px 0px; position: static;
}
.dialog_wrp .richvideo:hover {
cursor: pointer;
}
.dialog_wrp .richvideo:hover .richvideo_mask {
display: block;
}
.richvideo.selected .richvideo_mask {
display: block;
}
.richvideo.selected .icon_card_selected {
display: inline-block;
}
.richvideo.no_title .richvideo_mask {
display: block;
}
.richvideo.no_title .richvideo_tips {
display: block;
}
.tab_content .richvideo {
width: 320px;
}
.richvideo_opr {
border-top-color: rgb(231, 231, 235); border-top-width: 1px; border-top-style: solid; background-color: rgb(244, 244, 244);
}
.richvideo_opr_item {
height: 44px; line-height: 44px;
}
.richvideo_opr_item a {
text-align: center; border-right-color: rgb(231, 231, 235); border-right-width: 1px; border-right-style: solid; display: block;
}
.richvideo_opr_item.no_extra a {
border-right-width: 0px;
}
.smallvideo .title {
margin-bottom: 6px;
}
.video_mask {
left: 0px; top: 0px; width: 100%; height: 100%; right: 0px; position: absolute; background-color: rgba(0, 0, 0, 0.5);
}
.video_mask .ic_play {
background: url("/mpres/htmledition/images/icon/media/ic_smallvideo_play238f6c.png") no-repeat 0px 0px; margin: -25px 0px 0px -25px; left: 50%; top: 50%; width: 50px; height: 50px; vertical-align: middle; display: inline-block; position: absolute;
}
.video_extra_info {
height: 160px; position: relative;
}
.video_extra_info .play_mask {
background: rgba(0, 0, 0, 0.35) !important; left: 0px; top: 0px; text-align: center; right: 0px; bottom: 0px; color: rgb(255, 255, 255); line-height: 160px; font-size: 0px; position: absolute;
}
.video_extra_info .status_mask {
background: rgba(0, 0, 0, 0.35) !important; left: 0px; top: 0px; text-align: center; right: 0px; bottom: 0px; color: rgb(255, 255, 255); line-height: 160px; font-size: 0px; position: absolute;
}
.video_extra_info .play_mask {
display: none;
}
.video_extra_info .status_msg {
line-height: 1.6; font-size: 14px; vertical-align: middle; display: inline-block;
}
.video_extra_info .video_length {
background: rgba(0, 0, 0, 0.5) !important; padding: 3px 15px; left: 0px; text-align: right; right: 0px; bottom: 0px; color: rgb(255, 255, 255); position: absolute;
}
.video_extra_info .icon_video_play {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/richvideo_z27bb72.png") no-repeat 0px -308px; width: 48px; height: 49px; vertical-align: middle; display: inline-block;
}
.richvideo_content:hover .play_mask {
display: block; cursor: pointer;
}
.icon_appmsg_create {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px 0px; width: 38px; height: 38px; vertical-align: middle; display: inline-block;
}
a:hover .icon_appmsg_create {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -48px;
}
.icon_appmsg_create.multi {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -96px;
}
a:hover .icon_appmsg_create.multi {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -144px;
}
.icon_shopmsg_create {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -192px; width: 38px; height: 38px; vertical-align: middle; display: inline-block;
}
a:hover .icon_shopmsg_create {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -240px;
}
.icon_shopmsg_create.multi {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -288px;
}
a:hover .icon_shopmsg_create.multi {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -336px;
}
.icon_appmsg_small {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -384px; width: 18px; height: 18px; vertical-align: middle; display: inline-block;
}
a:hover .icon_appmsg_small {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -412px;
}
.icon_appmsg_small.multi {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -440px;
}
a:hover .icon_appmsg_small.multi {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -468px;
}
.icon_shopmsg_small {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -496px; width: 18px; height: 18px; vertical-align: middle; display: inline-block;
}
a:hover .icon_shopmsg_small {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -524px;
}
.icon_shopmsg_small.multi {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -552px;
}
a:hover .icon_shopmsg_small.multi {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/media/media_dialog_z27dcd8.png") no-repeat 0px -580px;
}
.dialog_media_container {
height: 498px; position: relative;
}
.dialog_media_container .icon_loading_small {
left: 50%; top: 50%; margin-top: -20px; margin-left: -20px; position: absolute;
}
.dialog_media_container.no_media {
text-align: center;
}
.dialog_media_container .search_bar {
line-height: 1.6; margin-top: 13px; float: left;
}
.dialog_media_container .sub_title_bar .upload_box {
margin-top: 13px; float: left;
}
.dialog_media_container .icon_loading_small {
left: 50%; top: 50%; margin-top: -20px; margin-left: -20px; position: absolute;
}
.richvideo_create {
-ms-zoom: 1;
}
.richvideo_create a {
margin-left: 8px;
}
.richvideo_create i {
cursor: pointer;
}
.appmsg_create {
}
.appmsg_create a {
margin-left: 8px;
}
.no_media_wrp {
width: 99%; text-align: center; vertical-align: middle; display: inline-block;
}
.no_media_wrp .tips {
color: rgb(141, 141, 141); margin-bottom: 40px;
}
.no_media_wrp .btn.btn_upload {
height: 30px; line-height: 30px; padding-right: 36px; padding-left: 36px;
}
.no_media_wrp .upload_tips {
color: rgb(141, 141, 141); margin-top: 5px; display: block;
}
.dialog_media_list {
height: 420px; position: relative; -ms-overflow-y: scroll;
}
.dialog_media_list.img .media_item {
min-height: 72px;
}
.dialog_media_list.img .media_info {
margin-left: 140px;
}
.dialog_media_list.img .media_info .frm_radio_label {
left: -140px; top: 0px; position: absolute;
}
.dialog_media_list.img .media_content {
left: 30px; top: 20px; padding-top: 0px; margin-left: 0px; position: absolute;
}
.dialog_media_list.img .media_name {
display: block;
}
.dialog_media_list.img .media_time {
top: 0px; right: 0px; position: absolute;
}
.dialog_media_list.img .media_size {
float: none;
}
.dialog_media_list .media_item {
padding: 20px; color: rgb(141, 141, 141); border-bottom-color: rgb(231, 231, 235); border-bottom-width: 1px; border-bottom-style: solid; position: relative;
}
.dialog_media_list .media_info {
position: relative; min-height: 22px;
}
.dialog_media_list .media_content {
padding-top: 8px; margin-left: 24px;
}
.dialog_media_list .media_name {
width: auto; overflow: hidden; font-style: normal; font-weight: 400; display: inline-block; white-space: nowrap; -ms-word-wrap: normal; -ms-text-overflow: ellipsis; max-width: 400px;
}
.dialog_media_list .media_size {
top: 0px; right: 140px; position: absolute;
}
.dialog_media_list .media_time {
top: 0px; width: 130px; text-align: right; right: 0px; position: absolute;
}
.dialog_media_list .media_img img {
max-height: 70px; max-width: 100px;
}
.pagination_wrp {
padding: 25px 20px 0px; background-color: rgb(255, 255, 255);
}
.appmsg_media_dialog {
height: auto;
}
.appmsg_media_dialog .dialog_media_inner {
height: 453px; position: relative;
}
.icon_emotion.emotion_switch {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/emotion_editor_z218878.png") no-repeat 0px 0px; width: 20px; height: 20px; vertical-align: middle; display: inline-block;
}
.icon_emotion.emotion_switch:hover {
background: url("/mpres/zh_CN/htmledition/comm_htmledition/style/widget/emotion_editor_z218878.png") no-repeat 0px -30px;
}
.emotion_editor {
border-radius: 0px; border: 1px solid rgb(231, 231, 235); border-image: none; position: relative; z-index: 1; -webkit-border-radius: 0; -moz-border-radius: 0;
}
.test .emotion_editor {
margin: 20px;
}
.emotion_editor .edit_area {
padding: 14px 20px; outline: 0px; height: 188px; -ms-word-break: break-all; -ms-word-wrap: break-word; border-top-left-radius: 0px; border-top-right-radius: 0px; background-color: rgb(255, 255, 255); -moz-border-radius-topleft: 0; -webkit-border-top-left-radius: 0; -moz-border-radius-topright: 0; -webkit-border-top-right-radius: 0;
}
.emotion_editor .edit_area img {
vertical-align: middle;
}
.editor_toolbar {
padding: 0px 20px; line-height: 36px; border-top-color: rgb(231, 231, 235); border-top-width: 1px; border-top-style: solid; background-color: rgb(255, 255, 255);
}
.editor_toolbar::after {
height: 0px; clear: both; display: block; content: "\200B";
}
.editor_tip {
color: rgb(141, 141, 141); float: right;
}
.editor_tip em {
font-style: normal; font-weight: 400; margin-right: 3px; margin-left: 3px;
}
.editor_tip .warn {
color: rgb(225, 95, 99);
}
.emotion_switch {
height: 28px; line-height: 999em; overflow: hidden; margin-top: 8px; float: left;
}
.emotion_wrp {
left: -1px; top: 100%; width: 421px; display: none; position: absolute;
}
.emotions {
overflow: hidden; border-top-color: rgb(192, 191, 197); border-right-color: rgb(192, 191, 197); border-top-width: 1px; border-right-width: 1px; border-top-style: solid; border-right-style: solid; background-color: rgb(231, 231, 235); -moz-user-select: none;
}
.emotions_item {
width: 27px; height: 27px; text-align: center; line-height: 27px; font-size: 0px; border-bottom-color: rgb(192, 191, 197); border-left-color: rgb(192, 191, 197); border-bottom-width: 1px; border-left-width: 1px; border-bottom-style: solid; border-left-style: solid; float: left; background-color: rgb(255, 255, 255);
}
.emotions_item:hover {
background: rgba(255, 255, 255, 0.75) !important;
}
.emotions_item i {
background: url("/mpres/htmledition/images/icon/emotion/default218877.gif") no-repeat 0px 0px; width: 24px; height: 24px; vertical-align: middle; display: inline-block; cursor: pointer;
}
.emotions_preview {
border: 1px solid rgb(192, 191, 197); border-image: none; top: 0px; width: 80px; height: 80px; text-align: center; right: -81px; line-height: 80px; font-size: 0px; display: block; position: absolute; background-color: rgb(255, 255, 255);
}
.emotions_preview img {
left: 50%; top: 50%; margin-top: -12px; margin-left: -12px; position: absolute;
}
.hook {
left: 21px; top: 0px; position: absolute;
}
.hook .hook_dec {
border-width: 8px; border-style: solid; left: 0px; width: 0px; height: 0px; position: absolute;
}
.hook .hook_top {
border-color: transparent transparent rgb(192, 191, 197); top: -16px;
}
.hook .hook_btm {
border-color: transparent transparent rgb(246, 246, 246); top: -15px;
}
|
xdvalue/mcoding
|
base_dependencies/wechat_module/src/main/webapp/resources/css/wechatApi/emotion_editor23b187.css
|
CSS
|
apache-2.0
| 91,060 |
package org.teavm.classlib.java.nio;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.nio.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.teavm.junit.TeaVMTestRunner;
@RunWith(TeaVMTestRunner.class)
public class ShortBufferTest {
@Test
public void allocatesSimple() {
ShortBuffer buffer = ShortBuffer.allocate(100);
assertThat(buffer.isDirect(), is(false));
assertThat(buffer.isReadOnly(), is(false));
assertThat(buffer.hasArray(), is(true));
assertThat(buffer.capacity(), is(100));
assertThat(buffer.position(), is(0));
assertThat(buffer.limit(), is(100));
try {
buffer.reset();
fail("Mark is expected to be undefined");
} catch (InvalidMarkException e) {
// ok
}
}
@Test(expected = IllegalArgumentException.class)
public void errorIfAllocatingBufferOfNegativeSize() {
ShortBuffer.allocate(-1);
}
@Test
public void wrapsArray() {
short[] array = new short[100];
ShortBuffer buffer = ShortBuffer.wrap(array, 10, 70);
assertThat(buffer.isDirect(), is(false));
assertThat(buffer.isReadOnly(), is(false));
assertThat(buffer.hasArray(), is(true));
assertThat(buffer.array(), is(array));
assertThat(buffer.arrayOffset(), is(0));
assertThat(buffer.capacity(), is(100));
assertThat(buffer.position(), is(10));
assertThat(buffer.limit(), is(80));
try {
buffer.reset();
fail("Mark is expected to be undefined");
} catch (InvalidMarkException e) {
// ok
}
array[0] = 23;
assertThat(buffer.get(0), is((short)23));
buffer.put(1, (short)24);
assertThat(array[1], is((short)24));
}
@Test
public void errorWhenWrappingWithWrongParameters() {
short[] array = new short[100];
try {
ShortBuffer.wrap(array, -1, 10);
} catch (IndexOutOfBoundsException e) {
// ok
}
try {
ShortBuffer.wrap(array, 101, 10);
} catch (IndexOutOfBoundsException e) {
// ok
}
try {
ShortBuffer.wrap(array, 98, 3);
} catch (IndexOutOfBoundsException e) {
// ok
}
try {
ShortBuffer.wrap(array, 98, -1);
} catch (IndexOutOfBoundsException e) {
// ok
}
}
@Test
public void wrapsArrayWithoutOffset() {
short[] array = new short[100];
ShortBuffer buffer = ShortBuffer.wrap(array);
assertThat(buffer.position(), is(0));
assertThat(buffer.limit(), is(100));
}
@Test
public void createsSlice() {
ShortBuffer buffer = ShortBuffer.allocate(100);
buffer.put(new short[60]);
buffer.flip();
buffer.put(new short[15]);
ShortBuffer slice = buffer.slice();
assertThat(slice.array(), is(buffer.array()));
assertThat(slice.position(), is(0));
assertThat(slice.capacity(), is(45));
assertThat(slice.limit(), is(45));
assertThat(slice.isDirect(), is(false));
assertThat(slice.isReadOnly(), is(false));
slice.put(3, (short)23);
assertThat(buffer.get(18), is((short)23));
slice.put((short)24);
assertThat(buffer.get(15), is((short)24));
buffer.put(16, (short)25);
assertThat(slice.get(1), is((short)25));
}
@Test
public void slicePropertiesSameWithOriginal() {
ShortBuffer buffer = ShortBuffer.allocate(100).asReadOnlyBuffer().slice();
assertThat(buffer.isReadOnly(), is(true));
}
@Test
public void createsDuplicate() {
ShortBuffer buffer = ShortBuffer.allocate(100);
buffer.put(new short[60]);
buffer.flip();
buffer.put(new short[15]);
ShortBuffer duplicate = buffer.duplicate();
assertThat(duplicate.array(), is(buffer.array()));
assertThat(duplicate.position(), is(15));
assertThat(duplicate.capacity(), is(100));
assertThat(duplicate.limit(), is(60));
assertThat(duplicate.isDirect(), is(false));
assertThat(duplicate.isReadOnly(), is(false));
duplicate.put(3, (short)23);
assertThat(buffer.get(3), is((short)23));
duplicate.put((short)24);
assertThat(buffer.get(15), is((short)24));
buffer.put(1, (short)25);
assertThat(duplicate.get(1), is((short)25));
assertThat(duplicate.array(), is(sameInstance(buffer.array())));
}
@Test
public void getsShort() {
short[] array = { 2, 3, 5, 7 };
ShortBuffer buffer = ShortBuffer.wrap(array);
assertThat(buffer.get(), is((short)2));
assertThat(buffer.get(), is((short)3));
buffer = buffer.slice();
assertThat(buffer.get(), is((short)5));
assertThat(buffer.get(), is((short)7));
}
@Test
public void gettingShortFromEmptyBufferCausesError() {
short[] array = { 2, 3, 5, 7 };
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.limit(2);
buffer.get();
buffer.get();
try {
buffer.get();
fail("Should have thrown error");
} catch (BufferUnderflowException e) {
// ok
}
}
@Test
public void putsShort() {
short[] array = new short[4];
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.put((short)2).put((short)3).put((short)5).put((short)7);
assertThat(array, is(new short[] { 2, 3, 5, 7 }));
}
@Test
public void puttingShortToEmptyBufferCausesError() {
short[] array = new short[4];
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.limit(2);
buffer.put((short)2).put((short)3);
try {
buffer.put((short)5);
fail("Should have thrown error");
} catch (BufferOverflowException e) {
assertThat(array[2], is((short)0));
}
}
@Test(expected = ReadOnlyBufferException.class)
public void puttingShortToReadOnlyBufferCausesError() {
short[] array = new short[4];
ShortBuffer buffer = ShortBuffer.wrap(array).asReadOnlyBuffer();
buffer.put((short)2);
}
@Test
public void getsShortFromGivenLocation() {
short[] array = { 2, 3, 5, 7 };
ShortBuffer buffer = ShortBuffer.wrap(array);
assertThat(buffer.get(0), is((short)2));
assertThat(buffer.get(1), is((short)3));
buffer.get();
buffer = buffer.slice();
assertThat(buffer.get(1), is((short)5));
assertThat(buffer.get(2), is((short)7));
}
@Test
public void gettingShortFromWrongLocationCausesError() {
short[] array = { 2, 3, 5, 7 };
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.limit(3);
try {
buffer.get(-1);
} catch (IndexOutOfBoundsException e) {
// ok
}
try {
buffer.get(3);
} catch (IndexOutOfBoundsException e) {
// ok
}
}
@Test
public void putsShortToGivenLocation() {
short[] array = new short[4];
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.put(0, (short)2);
buffer.put(1, (short)3);
buffer.get();
buffer = buffer.slice();
buffer.put(1, (short)5);
buffer.put(2, (short)7);
assertThat(array, is(new short[] { 2, 3, 5, 7 }));
}
@Test
public void puttingShortToWrongLocationCausesError() {
short[] array = new short[4];
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.limit(3);
try {
buffer.put(-1, (short)2);
} catch (IndexOutOfBoundsException e) {
// ok
}
try {
buffer.put(3, (short)2);
} catch (IndexOutOfBoundsException e) {
// ok
}
}
@Test(expected = ReadOnlyBufferException.class)
public void puttingShortToGivenLocationOfReadOnlyBufferCausesError() {
short[] array = new short[4];
ShortBuffer buffer = ShortBuffer.wrap(array).asReadOnlyBuffer();
buffer.put(0, (short)2);
}
@Test
public void getsShorts() {
short[] array = { 2, 3, 5, 7 };
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.get();
short[] receiver = new short[2];
buffer.get(receiver, 0, 2);
assertThat(buffer.position(), is(3));
assertThat(receiver, is(new short[] { 3, 5 }));
}
@Test
public void gettingShortsFromEmptyBufferCausesError() {
short[] array = { 2, 3, 5, 7 };
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.limit(3);
short[] receiver = new short[4];
try {
buffer.get(receiver, 0, 4);
fail("Error expected");
} catch (BufferUnderflowException e) {
assertThat(receiver, is(new short[4]));
assertThat(buffer.position(), is(0));
}
}
@Test
public void gettingShortsWithIllegalArgumentsCausesError() {
short[] array = { 2, 3, 5, 7 };
ShortBuffer buffer = ShortBuffer.wrap(array);
short[] receiver = new short[4];
try {
buffer.get(receiver, 0, 5);
} catch (IndexOutOfBoundsException e) {
assertThat(receiver, is(new short[4]));
assertThat(buffer.position(), is(0));
}
try {
buffer.get(receiver, -1, 3);
} catch (IndexOutOfBoundsException e) {
assertThat(receiver, is(new short[4]));
assertThat(buffer.position(), is(0));
}
try {
buffer.get(receiver, 6, 3);
} catch (IndexOutOfBoundsException e) {
assertThat(receiver, is(new short[4]));
assertThat(buffer.position(), is(0));
}
}
@Test
public void putsShorts() {
short[] array = new short[4];
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.get();
short[] data = { 2, 3 };
buffer.put(data, 0, 2);
assertThat(buffer.position(), is(3));
assertThat(array, is(new short[] {0, 2, 3, 0 }));
}
@Test
public void compacts() {
short[] array = { 2, 3, 5, 7 };
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.get();
buffer.mark();
buffer.compact();
assertThat(array, is(new short[] { 3, 5, 7, 7 }));
assertThat(buffer.position(), is(3));
assertThat(buffer.limit(), is(4));
assertThat(buffer.capacity(), is(4));
try {
buffer.reset();
fail("Exception expected");
} catch (InvalidMarkException e) {
// ok
}
}
@Test
public void marksPosition() {
short[] array = { 2, 3, 5, 7 };
ShortBuffer buffer = ShortBuffer.wrap(array);
buffer.position(1);
buffer.mark();
buffer.position(2);
buffer.reset();
assertThat(buffer.position(), is(1));
}
}
|
jtulach/teavm
|
tests/src/test/java/org/teavm/classlib/java/nio/ShortBufferTest.java
|
Java
|
apache-2.0
| 11,268 |
/*
* 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.spark.sql.hive.execution
import scala.collection.JavaConverters._
import org.apache.hadoop.hive.ql.udf.UDAFPercentile
import org.apache.hadoop.hive.ql.udf.generic.{AbstractGenericUDAFResolver, GenericUDAFEvaluator, GenericUDAFMax}
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.{AggregationBuffer, Mode}
import org.apache.hadoop.hive.ql.util.JavaDataModel
import org.apache.hadoop.hive.serde2.objectinspector.{ObjectInspector, ObjectInspectorFactory}
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo
import test.org.apache.spark.sql.MyDoubleAvg
import org.apache.spark.sql.{AnalysisException, QueryTest, Row}
import org.apache.spark.sql.execution.aggregate.ObjectHashAggregateExec
import org.apache.spark.sql.hive.test.TestHiveSingleton
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SQLTestUtils
class HiveUDAFSuite extends QueryTest with TestHiveSingleton with SQLTestUtils {
import testImplicits._
protected override def beforeAll(): Unit = {
super.beforeAll()
sql(s"CREATE TEMPORARY FUNCTION mock AS '${classOf[MockUDAF].getName}'")
sql(s"CREATE TEMPORARY FUNCTION hive_max AS '${classOf[GenericUDAFMax].getName}'")
sql(s"CREATE TEMPORARY FUNCTION mock2 AS '${classOf[MockUDAF2].getName}'")
Seq(
(0: Integer) -> "val_0",
(1: Integer) -> "val_1",
(2: Integer) -> null,
(3: Integer) -> null
).toDF("key", "value").repartition(2).createOrReplaceTempView("t")
}
protected override def afterAll(): Unit = {
try {
sql(s"DROP TEMPORARY FUNCTION IF EXISTS mock")
sql(s"DROP TEMPORARY FUNCTION IF EXISTS hive_max")
} finally {
super.afterAll()
}
}
test("built-in Hive UDAF") {
val df = sql("SELECT key % 2, hive_max(key) FROM t GROUP BY key % 2")
val aggs = df.queryExecution.executedPlan.collect {
case agg: ObjectHashAggregateExec => agg
}
// There should be two aggregate operators, one for partial aggregation, and the other for
// global aggregation.
assert(aggs.length == 2)
checkAnswer(df, Seq(
Row(0, 2),
Row(1, 3)
))
}
test("customized Hive UDAF") {
val df = sql("SELECT key % 2, mock(value) FROM t GROUP BY key % 2")
val aggs = df.queryExecution.executedPlan.collect {
case agg: ObjectHashAggregateExec => agg
}
// There should be two aggregate operators, one for partial aggregation, and the other for
// global aggregation.
assert(aggs.length == 2)
checkAnswer(df, Seq(
Row(0, Row(1, 1)),
Row(1, Row(1, 1))
))
}
test("SPARK-24935: customized Hive UDAF with two aggregation buffers") {
withTempView("v") {
spark.range(100).createTempView("v")
val df = sql("SELECT id % 2, mock2(id) FROM v GROUP BY id % 2")
val aggs = df.queryExecution.executedPlan.collect {
case agg: ObjectHashAggregateExec => agg
}
// There should be two aggregate operators, one for partial aggregation, and the other for
// global aggregation.
assert(aggs.length == 2)
withSQLConf(SQLConf.OBJECT_AGG_SORT_BASED_FALLBACK_THRESHOLD.key -> "1") {
checkAnswer(df, Seq(
Row(0, Row(50, 0)),
Row(1, Row(50, 0))
))
}
withSQLConf(SQLConf.OBJECT_AGG_SORT_BASED_FALLBACK_THRESHOLD.key -> "100") {
checkAnswer(df, Seq(
Row(0, Row(50, 0)),
Row(1, Row(50, 0))
))
}
}
}
test("call JAVA UDAF") {
withTempView("temp") {
withUserDefinedFunction("myDoubleAvg" -> false) {
spark.range(1, 10).toDF("value").createOrReplaceTempView("temp")
sql(s"CREATE FUNCTION myDoubleAvg AS '${classOf[MyDoubleAvg].getName}'")
checkAnswer(
spark.sql("SELECT default.myDoubleAvg(value) as my_avg from temp"),
Row(105.0))
}
}
}
test("non-deterministic children expressions of UDAF") {
withTempView("view1") {
spark.range(1).selectExpr("id as x", "id as y").createTempView("view1")
withUserDefinedFunction("testUDAFPercentile" -> true) {
// non-deterministic children of Hive UDAF
sql(s"CREATE TEMPORARY FUNCTION testUDAFPercentile AS '${classOf[UDAFPercentile].getName}'")
val e1 = intercept[AnalysisException] {
sql("SELECT testUDAFPercentile(x, rand()) from view1 group by y")
}.getMessage
assert(Seq("nondeterministic expression",
"should not appear in the arguments of an aggregate function").forall(e1.contains))
}
}
}
}
/**
* A testing Hive UDAF that computes the counts of both non-null values and nulls of a given column.
*/
class MockUDAF extends AbstractGenericUDAFResolver {
override def getEvaluator(info: Array[TypeInfo]): GenericUDAFEvaluator = new MockUDAFEvaluator
}
class MockUDAF2 extends AbstractGenericUDAFResolver {
override def getEvaluator(info: Array[TypeInfo]): GenericUDAFEvaluator = new MockUDAFEvaluator2
}
class MockUDAFBuffer(var nonNullCount: Long, var nullCount: Long)
extends GenericUDAFEvaluator.AbstractAggregationBuffer {
override def estimate(): Int = JavaDataModel.PRIMITIVES2 * 2
}
class MockUDAFBuffer2(var nonNullCount: Long, var nullCount: Long)
extends GenericUDAFEvaluator.AbstractAggregationBuffer {
override def estimate(): Int = JavaDataModel.PRIMITIVES2 * 2
}
class MockUDAFEvaluator extends GenericUDAFEvaluator {
private val nonNullCountOI = PrimitiveObjectInspectorFactory.javaLongObjectInspector
private val nullCountOI = PrimitiveObjectInspectorFactory.javaLongObjectInspector
private val bufferOI = {
val fieldNames = Seq("nonNullCount", "nullCount").asJava
val fieldOIs = Seq(nonNullCountOI: ObjectInspector, nullCountOI: ObjectInspector).asJava
ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs)
}
private val nonNullCountField = bufferOI.getStructFieldRef("nonNullCount")
private val nullCountField = bufferOI.getStructFieldRef("nullCount")
override def getNewAggregationBuffer: AggregationBuffer = new MockUDAFBuffer(0L, 0L)
override def reset(agg: AggregationBuffer): Unit = {
val buffer = agg.asInstanceOf[MockUDAFBuffer]
buffer.nonNullCount = 0L
buffer.nullCount = 0L
}
override def init(mode: Mode, parameters: Array[ObjectInspector]): ObjectInspector = bufferOI
override def iterate(agg: AggregationBuffer, parameters: Array[AnyRef]): Unit = {
val buffer = agg.asInstanceOf[MockUDAFBuffer]
if (parameters.head eq null) {
buffer.nullCount += 1L
} else {
buffer.nonNullCount += 1L
}
}
override def merge(agg: AggregationBuffer, partial: Object): Unit = {
if (partial ne null) {
val nonNullCount = nonNullCountOI.get(bufferOI.getStructFieldData(partial, nonNullCountField))
val nullCount = nullCountOI.get(bufferOI.getStructFieldData(partial, nullCountField))
val buffer = agg.asInstanceOf[MockUDAFBuffer]
buffer.nonNullCount += nonNullCount
buffer.nullCount += nullCount
}
}
override def terminatePartial(agg: AggregationBuffer): AnyRef = {
val buffer = agg.asInstanceOf[MockUDAFBuffer]
Array[Object](buffer.nonNullCount: java.lang.Long, buffer.nullCount: java.lang.Long)
}
override def terminate(agg: AggregationBuffer): AnyRef = terminatePartial(agg)
}
// Same as MockUDAFEvaluator but using two aggregation buffers, one for PARTIAL1 and the other
// for PARTIAL2.
class MockUDAFEvaluator2 extends GenericUDAFEvaluator {
private val nonNullCountOI = PrimitiveObjectInspectorFactory.javaLongObjectInspector
private val nullCountOI = PrimitiveObjectInspectorFactory.javaLongObjectInspector
private var aggMode: Mode = null
private val bufferOI = {
val fieldNames = Seq("nonNullCount", "nullCount").asJava
val fieldOIs = Seq(nonNullCountOI: ObjectInspector, nullCountOI: ObjectInspector).asJava
ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs)
}
private val nonNullCountField = bufferOI.getStructFieldRef("nonNullCount")
private val nullCountField = bufferOI.getStructFieldRef("nullCount")
override def getNewAggregationBuffer: AggregationBuffer = {
// These 2 modes consume original data.
if (aggMode == Mode.PARTIAL1 || aggMode == Mode.COMPLETE) {
new MockUDAFBuffer(0L, 0L)
} else {
new MockUDAFBuffer2(0L, 0L)
}
}
override def reset(agg: AggregationBuffer): Unit = {
val buffer = agg.asInstanceOf[MockUDAFBuffer]
buffer.nonNullCount = 0L
buffer.nullCount = 0L
}
override def init(mode: Mode, parameters: Array[ObjectInspector]): ObjectInspector = {
aggMode = mode
bufferOI
}
override def iterate(agg: AggregationBuffer, parameters: Array[AnyRef]): Unit = {
val buffer = agg.asInstanceOf[MockUDAFBuffer]
if (parameters.head eq null) {
buffer.nullCount += 1L
} else {
buffer.nonNullCount += 1L
}
}
override def merge(agg: AggregationBuffer, partial: Object): Unit = {
if (partial ne null) {
val nonNullCount = nonNullCountOI.get(bufferOI.getStructFieldData(partial, nonNullCountField))
val nullCount = nullCountOI.get(bufferOI.getStructFieldData(partial, nullCountField))
val buffer = agg.asInstanceOf[MockUDAFBuffer2]
buffer.nonNullCount += nonNullCount
buffer.nullCount += nullCount
}
}
// As this method is called for both states, Partial1 and Partial2, the hack in the method
// to check for class of aggregation buffer was necessary.
override def terminatePartial(agg: AggregationBuffer): AnyRef = {
var result: AnyRef = null
if (agg.getClass.toString.contains("MockUDAFBuffer2")) {
val buffer = agg.asInstanceOf[MockUDAFBuffer2]
result = Array[Object](buffer.nonNullCount: java.lang.Long, buffer.nullCount: java.lang.Long)
} else {
val buffer = agg.asInstanceOf[MockUDAFBuffer]
result = Array[Object](buffer.nonNullCount: java.lang.Long, buffer.nullCount: java.lang.Long)
}
result
}
override def terminate(agg: AggregationBuffer): AnyRef = {
val buffer = agg.asInstanceOf[MockUDAFBuffer2]
Array[Object](buffer.nonNullCount: java.lang.Long, buffer.nullCount: java.lang.Long)
}
}
|
LantaoJin/spark
|
sql/hive/src/test/scala/org/apache/spark/sql/hive/execution/HiveUDAFSuite.scala
|
Scala
|
apache-2.0
| 11,148 |
/*
* 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.empire.db;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.sql.Connection;
import org.apache.empire.DBResource;
import org.apache.empire.DBResource.DB;
import org.apache.empire.db.DBCmdParam;
import org.apache.empire.db.context.DBContextStatic;
import org.apache.empire.dbms.DBMSHandler;
import org.junit.Rule;
import org.junit.Test;
public class PreparedStatementTest{
@Rule
public DBResource dbResource = new DBResource(DB.HSQL);
@Test
public void testPreparedStatement()
{
Connection conn = dbResource.getConnection();
DBMSHandler dbms = dbResource.newDriver();
DBContext context = new DBContextStatic(dbms, conn);
CompanyDB db = new CompanyDB();
db.open(context);
DBSQLScript script = new DBSQLScript(context);
db.getCreateDDLScript(script);
script.executeAll(false);
DBRecord department = new DBRecord(context, db.DEPARTMENT);
department.create();
department.set(db.DEPARTMENT.NAME, "junit");
department.set(db.DEPARTMENT.BUSINESS_UNIT, "test");
department.update();
int id = department.getInt(db.DEPARTMENT.ID);
assertTrue("Department add failed", id > 0);
// Define shortcuts for tables used - not necessary but convenient
CompanyDB.Departments DEP = db.DEPARTMENT;
// Define the query
DBCommand cmd = context.createCommand();
// Create parameters
DBCmdParam empIdParam = cmd.addParam(null);
// the previous line could be shorter
// DBCommandParam empIdParam = cmd.addCmdParam(id);
// create statement
cmd.select(DEP.getColumns());
cmd.where(DEP.ID.is(empIdParam));
// set param value
empIdParam.setValue(id);
// check command
assertTrue(cmd.getSelect().indexOf('?') > 0);
assertNotNull(cmd.getParamValues());
DBReader r = new DBReader(context);
try {
r.open(cmd);
// must have one record
assertEquals(true, r.moveNext());
// Department Id must be correct
assertEquals(id, r.getInt(DEP.ID));
} finally {
r.close();
}
}
}
|
apache/empire-db
|
empire-db/src/test/java/org/apache/empire/db/PreparedStatementTest.java
|
Java
|
apache-2.0
| 3,182 |
{% extends 'core/page.html' %}
{% load i18n %}
{% block page %}
<h1>{% trans "Password reset" %}</h1>
{% if user.is_authenticated %}
{% include "account/snippets/already_logged_in.html" %}
{% endif %}
<p>
{% trans "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}
</p>
<form method="post" action="{% url 'account_reset_password' %}">
{% csrf_token %}
{% include 'core/bootstrap_form_fields.html' %}
<input type="submit" class="btn btn-primary" value="{% trans 'Reset my password' %}" />
</form>
{% endblock %}
|
rdmorganiser/rdmo
|
rdmo/accounts/templates/account/password_reset.html
|
HTML
|
apache-2.0
| 650 |
// Copyright 2011-2016 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.
package com.google.security.zynamics.binnavi.API.debug;
import com.google.security.zynamics.binnavi.debug.connection.packets.replies.ThreadCreatedReply;
public class DebuggerThreadCreatedReply extends DebuggerReply {
public DebuggerThreadCreatedReply(final ThreadCreatedReply reply) {
super(reply);
}
public long getThreadId() {
return ((ThreadCreatedReply) reply).getThreadId();
}
public ThreadState getThreadState() {
return ThreadState.convert(((ThreadCreatedReply) reply).getThreadState());
}
}
|
google/binnavi
|
src/main/java/com/google/security/zynamics/binnavi/API/debug/DebuggerThreadCreatedReply.java
|
Java
|
apache-2.0
| 1,117 |
// Copyright (C) 2015 Nippon Telegraph and Telephone 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 endpoint provides listeners for several RPC protocols
package endpoint
import (
log "github.com/cihub/seelog"
"github.com/osrg/namazu/nmz/endpoint/local"
"github.com/osrg/namazu/nmz/endpoint/pb"
"github.com/osrg/namazu/nmz/endpoint/rest"
"github.com/osrg/namazu/nmz/signal"
"github.com/osrg/namazu/nmz/util/config"
"sync"
)
type endpointType int
const (
endpointTypeLocal endpointType = iota
endpointTypeREST
endpointTypePB
)
var (
muxEventCh = make(chan signal.Event)
muxActionCh chan signal.Action
entityEndpointTypes = make(map[string]endpointType)
entityEndpointTypesMu = sync.RWMutex{}
localEventCh chan signal.Event
localActionCh = make(chan signal.Action)
restEventCh chan signal.Event
restActionCh = make(chan signal.Action)
pbEventCh chan signal.Event
pbActionCh = make(chan signal.Action)
stopActionRCh chan struct{}
stopLocalEventRCh chan struct{}
stopRESTEventRCh chan struct{}
stopPBEventRCh chan struct{}
stoppedActionRCh chan struct{}
stoppedLocalEventRCh chan struct{}
stoppedRESTEventRCh chan struct{}
stoppedPBEventRCh chan struct{}
)
// Starts all the endpoint handlers for multiplexed action channel actionCh.
// It returns an multiplexed event channel
func StartAll(actionCh chan signal.Action, cfg config.Config) (chan signal.Event, chan signal.Control) {
muxActionCh = actionCh
localEventCh = local.SingletonLocalEndpoint.Start(localActionCh)
stopActionRCh = make(chan struct{})
stopLocalEventRCh = make(chan struct{})
stopRESTEventRCh = make(chan struct{})
stopPBEventRCh = make(chan struct{})
stoppedActionRCh = make(chan struct{})
stoppedLocalEventRCh = make(chan struct{})
stoppedRESTEventRCh = make(chan struct{})
stoppedPBEventRCh = make(chan struct{})
var controlCh chan signal.Control
if cfg.IsSet("restPort") {
restPort := cfg.GetInt("restPort")
if restPort >= 0 {
// zero is also legal (auto-assign)
log.Infof("REST port: %d", restPort)
restEventCh, controlCh = rest.SingletonRESTEndpoint.Start(restPort, restActionCh)
} else {
log.Warnf("ignoring restPort: %d", restPort)
}
}
if cfg.IsSet("pbPort") {
pbPort := cfg.GetInt("pbPort")
if pbPort >= 0 {
// zero is also legal (auto-assign)
log.Infof("PB port: %d", pbPort)
restEventCh = pb.SingletonPBEndpoint.Start(pbPort, restActionCh)
} else {
log.Warnf("ignoring pbPort: %d", pbPort)
}
}
go actionRoutine()
go localEventRoutine()
go restEventRoutine()
go pbEventRoutine()
return muxEventCh, controlCh
}
func registerEntityEndpointType(entityID string, typ endpointType) {
entityEndpointTypesMu.Lock()
cur, ok := entityEndpointTypes[entityID]
if ok {
if cur != typ {
log.Errorf("Entity ID conflict: new=%v, cur=%v", typ, cur)
// this is very critical.. should we panic here?
}
} else {
entityEndpointTypes[entityID] = typ
}
entityEndpointTypesMu.Unlock()
}
// Dispatch where action should be sent (localActionCh, restActionCh, pbActionCh..)
func dispatchAction(action signal.Action) {
log.Debugf("EP handling action %s", action)
entityID := action.EntityID()
entityEndpointTypesMu.RLock()
typ, ok := entityEndpointTypes[entityID]
entityEndpointTypesMu.RUnlock()
if ok {
switch typ {
case endpointTypeLocal:
localActionCh <- action
case endpointTypeREST:
restActionCh <- action
case endpointTypePB:
pbActionCh <- action
default:
panic(log.Criticalf("Unknown endpoint type, cur=%s", entityID))
}
} else {
log.Errorf("Unknown Entity ID:%s", entityID)
}
log.Debugf("EP handled action %s", action)
}
// Action sender (Orchestrator->Inspector)
func actionRoutine() {
defer close(stoppedActionRCh)
for {
select {
case action, ok := <-muxActionCh:
if ok {
dispatchAction(action)
}
case <-stopActionRCh:
return
}
}
}
// only xxxEventRoutine() calls this
func onEvent(event signal.Event, typ endpointType) {
log.Debugf("EP handling event %s", event)
muxEventCh <- event
registerEntityEndpointType(event.EntityID(), typ)
log.Debugf("EP handled event %s", event)
}
// Local Event receiver (Inspector->Orchestrator)
func localEventRoutine() {
defer close(stoppedLocalEventRCh)
for {
select {
case event, ok := <-localEventCh:
if ok {
onEvent(event, endpointTypeLocal)
}
case <-stopLocalEventRCh:
return
}
}
}
// REST Event receiver (Inspector->Orchestrator)
func restEventRoutine() {
defer close(stoppedRESTEventRCh)
for {
select {
case event, ok := <-restEventCh:
if ok {
onEvent(event, endpointTypeREST)
}
case <-stopRESTEventRCh:
return
}
}
}
// PB Event receiver (Inspector->Orchestrator)
func pbEventRoutine() {
defer close(stoppedPBEventRCh)
for {
select {
case event, ok := <-pbEventCh:
if ok {
onEvent(event, endpointTypePB)
}
case <-stopPBEventRCh:
return
}
}
}
func ShutdownAll() {
log.Debugf("Shutting down")
close(stopActionRCh)
close(stopLocalEventRCh)
close(stopRESTEventRCh)
close(stopPBEventRCh)
<-stoppedActionRCh
<-stoppedLocalEventRCh
<-stoppedRESTEventRCh
<-stoppedPBEventRCh
local.SingletonLocalEndpoint.Shutdown()
// TODO: how to shutdown REST endpoint?
log.Debugf("Shut down done")
}
|
osrg/earthquake
|
nmz/endpoint/endpoint.go
|
GO
|
apache-2.0
| 5,831 |
/*
* Copyright 2010-2017 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.
*/
#include <aws/resourcegroupstaggingapi/model/TagResourcesRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::ResourceGroupsTaggingAPI::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
TagResourcesRequest::TagResourcesRequest() :
m_resourceARNListHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
Aws::String TagResourcesRequest::SerializePayload() const
{
JsonValue payload;
if(m_resourceARNListHasBeenSet)
{
Array<JsonValue> resourceARNListJsonList(m_resourceARNList.size());
for(unsigned resourceARNListIndex = 0; resourceARNListIndex < resourceARNListJsonList.GetLength(); ++resourceARNListIndex)
{
resourceARNListJsonList[resourceARNListIndex].AsString(m_resourceARNList[resourceARNListIndex]);
}
payload.WithArray("ResourceARNList", std::move(resourceARNListJsonList));
}
if(m_tagsHasBeenSet)
{
JsonValue tagsJsonMap;
for(auto& tagsItem : m_tags)
{
tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
}
payload.WithObject("Tags", std::move(tagsJsonMap));
}
return payload.WriteReadable();
}
Aws::Http::HeaderValueCollection TagResourcesRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "ResourceGroupsTaggingAPI_20170126.TagResources"));
return headers;
}
|
chiaming0914/awe-cpp-sdk
|
aws-cpp-sdk-resourcegroupstaggingapi/source/model/TagResourcesRequest.cpp
|
C++
|
apache-2.0
| 1,987 |
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
namespace goedle_sdk.detail {
public interface IGoedleDownloadBuffer
{
DownloadHandler downloadHandlerBuffer { get; }
string text { get; }
}
public class GoedleDownloadBuffer : IGoedleDownloadBuffer
{
DownloadHandler _downloadHandlerBuffer { get; set; }
public GoedleDownloadBuffer()
{
_downloadHandlerBuffer =(DownloadHandler) new DownloadHandlerBuffer();
}
public DownloadHandler downloadHandlerBuffer
{
get { return _downloadHandlerBuffer; }
}
public string text
{
get { return _downloadHandlerBuffer.text; }
}
}
}
|
DigiArt-project/WordpressUnity3DEditor
|
StandardAssets/Energy/goedle_io/Scripts/detail/GoedleDownloadBuffer.cs
|
C#
|
apache-2.0
| 759 |
/*
* ModeShape (http://www.modeshape.org)
*
* 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.modeshape.jcr;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.security.AccessControlContext;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import javax.jcr.AccessDeniedException;
import javax.jcr.Credentials;
import javax.jcr.LoginException;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.NoInitialContextException;
import javax.naming.OperationNotSupportedException;
import javax.security.auth.login.LoginContext;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import org.jgroups.Channel;
import org.modeshape.common.annotation.Immutable;
import org.modeshape.common.collection.Problems;
import org.modeshape.common.collection.SimpleProblems;
import org.modeshape.common.i18n.I18n;
import org.modeshape.common.logging.Logger;
import org.modeshape.common.util.NamedThreadFactory;
import org.modeshape.jcr.ModeShapeEngine.State;
import org.modeshape.jcr.RepositoryConfiguration.AnonymousSecurity;
import org.modeshape.jcr.RepositoryConfiguration.BinaryStorage;
import org.modeshape.jcr.RepositoryConfiguration.Component;
import org.modeshape.jcr.RepositoryConfiguration.DocumentOptimization;
import org.modeshape.jcr.RepositoryConfiguration.FieldName;
import org.modeshape.jcr.RepositoryConfiguration.GarbageCollection;
import org.modeshape.jcr.RepositoryConfiguration.JaasSecurity;
import org.modeshape.jcr.RepositoryConfiguration.Security;
import org.modeshape.jcr.api.AnonymousCredentials;
import org.modeshape.jcr.api.Repository;
import org.modeshape.jcr.api.RepositoryManager;
import org.modeshape.jcr.api.RestoreOptions;
import org.modeshape.jcr.api.Workspace;
import org.modeshape.jcr.api.monitor.ValueMetric;
import org.modeshape.jcr.api.query.Query;
import org.modeshape.jcr.api.txn.TransactionManagerLookup;
import org.modeshape.jcr.bus.ChangeBus;
import org.modeshape.jcr.bus.ClusteredChangeBus;
import org.modeshape.jcr.bus.RepositoryChangeBus;
import org.modeshape.jcr.cache.NodeCache;
import org.modeshape.jcr.cache.NodeKey;
import org.modeshape.jcr.cache.RepositoryCache;
import org.modeshape.jcr.cache.SessionCache;
import org.modeshape.jcr.cache.WorkspaceNotFoundException;
import org.modeshape.jcr.cache.document.DocumentStore;
import org.modeshape.jcr.cache.document.LocalDocumentStore;
import org.modeshape.jcr.clustering.ClusteringService;
import org.modeshape.jcr.federation.FederatedDocumentStore;
import org.modeshape.jcr.journal.ChangeJournal;
import org.modeshape.jcr.journal.ClusteredJournal;
import org.modeshape.jcr.journal.LocalJournal;
import org.modeshape.jcr.locking.DbLockingService;
import org.modeshape.jcr.locking.JGroupsLockingService;
import org.modeshape.jcr.locking.LockingService;
import org.modeshape.jcr.locking.StandaloneLockingService;
import org.modeshape.jcr.mimetype.MimeTypeDetector;
import org.modeshape.jcr.mimetype.NullMimeTypeDetector;
import org.modeshape.jcr.query.parse.FullTextSearchParser;
import org.modeshape.jcr.query.parse.JcrQomQueryParser;
import org.modeshape.jcr.query.parse.JcrSql2QueryParser;
import org.modeshape.jcr.query.parse.JcrSqlQueryParser;
import org.modeshape.jcr.query.parse.QueryParsers;
import org.modeshape.jcr.query.xpath.XPathQueryParser;
import org.modeshape.jcr.security.AnonymousProvider;
import org.modeshape.jcr.security.AuthenticationProvider;
import org.modeshape.jcr.security.AuthenticationProviders;
import org.modeshape.jcr.security.EnvironmentAuthenticationProvider;
import org.modeshape.jcr.security.JaasProvider;
import org.modeshape.jcr.security.SecurityContext;
import org.modeshape.jcr.txn.Transactions;
import org.modeshape.jcr.value.NamespaceRegistry;
import org.modeshape.jcr.value.ValueFactories;
import org.modeshape.jcr.value.binary.BinaryStore;
import org.modeshape.jmx.RepositoryStatisticsBean;
import org.modeshape.schematic.SchematicDb;
import org.modeshape.schematic.document.Array;
import org.modeshape.schematic.document.Changes;
import org.modeshape.schematic.document.Editor;
import org.modeshape.schematic.document.Path;
import org.modeshape.schematic.internal.document.Paths;
/**
*
*/
public class JcrRepository implements org.modeshape.jcr.api.Repository {
/**
* The set of supported query language string constants.
*
* @see javax.jcr.query.QueryManager#getSupportedQueryLanguages()
* @see javax.jcr.query.QueryManager#createQuery(String, String)
*/
public static final class QueryLanguage {
/**
* The standard JCR 1.0 XPath query language.
*/
@SuppressWarnings( "deprecation" )
public static final String XPATH = Query.XPATH;
/**
* The SQL dialect that is based upon an enhanced version of the JCR-SQL query language defined by the JCR 1.0.1
* specification.
*/
@SuppressWarnings( "deprecation" )
public static final String JCR_SQL = Query.SQL;
/**
* The SQL dialect that is based upon an enhanced version of the JCR-SQL2 query language defined by the JCR 2.0
* specification.
*/
public static final String JCR_SQL2 = Query.JCR_SQL2;
/**
* The enhanced Query Object Model language defined by the JCR 2.0 specification.
*/
public static final String JCR_JQOM = Query.JCR_JQOM;
/**
* The full-text search language defined as part of the abstract query model, in Section 6.7.19 of the JCR 2.0
* specification.
*/
public static final String SEARCH = Query.FULL_TEXT_SEARCH;
}
protected static final Set<String> MISSING_JAAS_POLICIES = new CopyOnWriteArraySet<String>();
private static final boolean AUTO_START_REPO_UPON_LOGIN = true;
private static final String INTERNAL_WORKER_USERNAME = "<modeshape-worker>";
protected final Logger logger;
private final AtomicReference<RepositoryConfiguration> config = new AtomicReference<RepositoryConfiguration>();
private final AtomicReference<String> repositoryName = new AtomicReference<String>();
private final Map<String, Object> descriptors;
private final AtomicReference<RunningState> runningState = new AtomicReference<RunningState>();
private final AtomicReference<State> state = new AtomicReference<State>(State.NOT_RUNNING);
private final Lock stateLock = new ReentrantLock();
private final AtomicBoolean allowAutoStartDuringLogin = new AtomicBoolean(AUTO_START_REPO_UPON_LOGIN);
private Problems configurationProblems = null;
/**
* Create a Repository instance given the {@link RepositoryConfiguration configuration}.
*
* @param configuration the repository configuration; may not be null
* @throws ConfigurationException if there is a problem with the configuration
*/
protected JcrRepository( RepositoryConfiguration configuration ) throws ConfigurationException {
ModeShape.getName(); // force log message right up front
this.config.set(configuration);
RepositoryConfiguration config = this.config.get();
// Validate the configuration to make sure there are no errors ...
Problems results = configuration.validate();
setConfigurationProblems(results);
if (results.hasErrors()) {
String msg = JcrI18n.errorsInRepositoryConfiguration.text(this.repositoryName, results.errorCount(),
results.toString());
throw new ConfigurationException(results, msg);
}
this.repositoryName.set(config.getName());
this.logger = Logger.getLogger(getClass());
this.logger.debug("Activating '{0}' repository", this.repositoryName);
// Set up the descriptors ...
this.descriptors = new HashMap<String, Object>();
initializeDescriptors();
}
void setConfigurationProblems( Problems configurationProblems ) {
this.configurationProblems = configurationProblems;
}
RepositoryConfiguration repositoryConfiguration() {
return config.get();
}
/**
* Get the state of this JCR repository instance.
*
* @return the state; never null
*/
public State getState() {
return state.get();
}
/**
* Get the name of this JCR repository instance.
*
* @return the name; never null
*/
@Override
public String getName() {
return repositoryName.get();
}
@Override
public int getActiveSessionsCount() {
RunningState state = runningState.get();
return state == null ? 0 : state.activeSessionCount();
}
/**
* Get the component that can be used to obtain statistics for this repository.
* <p>
* Note that this provides un-checked access to the statistics, unlike {@link RepositoryManager#getRepositoryMonitor()} in the
* public API which only exposes the statistics if the session's user has administrative privileges.
* </p>
*
* @return the statistics component; never null
* @throws IllegalStateException if the repository is not {@link #getState() running}
* @see Workspace#getRepositoryManager()
* @see RepositoryManager#getRepositoryMonitor()
*/
public RepositoryStatistics getRepositoryStatistics() {
return statistics();
}
/**
* Starts this repository instance (if not already started) and returns all the possible startup problems & warnings which did
* not prevent the repository from starting up.
* <p>
* The are 2 general categories of issues that can be logged as problems:
* <ul>
* <li>configuration warnings - any warnings raised by the structure of the repository configuration file</li>
* <li>startup warnings/error - any warnings/errors raised by various repository components which didn't prevent them from
* starting up, but could mean they are only partly intialized.</li>
* </ul>
* </p>
*
* @return a {@link Problems} instance which may contains errors and warnings raised by various components; may be empty if
* nothing unusual happened during start but never {@code null}
* @throws Exception if there is a problem with underlying resource setup
*/
public Problems getStartupProblems() throws Exception {
doStart();
SimpleProblems result = new SimpleProblems();
result.addAll(this.configurationProblems);
result.addAll(runningState().problems());
return result;
}
/**
* Start this repository instance.
*
* @throws Exception if there is a problem with underlying resource setup
*/
void start() throws Exception {
doStart();
}
/**
* Terminate all active sessions.
*
* @return a future representing the asynchronous session termination process.
*/
Future<Boolean> shutdown() {
// Create a simple executor that will do the backgrounding for us ...
final ExecutorService executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("modeshape-repository-stop"));
try {
// Submit a runnable to terminate all sessions ...
return executor.submit(() -> doShutdown(false));
} finally {
// Now shutdown the executor and return the future ...
executor.shutdown();
}
}
/**
* Apply the supplied changes to this repository's configuration, and if running change the services to reflect the updated
* configuration. Note that this method assumes the proposed changes have already been validated; see
* {@link RepositoryConfiguration#validate(Changes)}.
*
* @param changes the changes for the configuration
* @throws Exception if there is a problem with underlying resources
* @see ModeShapeEngine#update(String, Changes)
*/
void apply( Changes changes ) throws Exception {
try {
stateLock.lock();
logger.debug("Applying changes to '{0}' repository configuration: {1} --> {2}", repositoryName, changes, config);
// Get the configuration and apply the same changes ...
final RepositoryConfiguration oldConfiguration = this.config.get();
Editor copy = oldConfiguration.edit();
ConfigurationChange configChanges = new ConfigurationChange();
copy.apply(changes, configChanges);
// Always update the configuration ...
RunningState oldState = this.runningState.get();
this.config.set(new RepositoryConfiguration(copy.unwrap(), copy.getString(FieldName.NAME),
oldConfiguration.environment()));
if (oldState != null) {
assert state.get() == State.RUNNING;
// Repository is running, so create a new running state ...
this.runningState.set(new RunningState(oldState, configChanges));
// Handle a few special cases that the running state doesn't really handle itself ...
if (!configChanges.storageChanged && configChanges.predefinedWorkspacesChanged) refreshWorkspaces();
if (configChanges.nameChanged) repositoryNameChanged();
}
logger.debug("Applied changes to '{0}' repository configuration: {1} --> {2}", repositoryName, changes, config);
} finally {
stateLock.unlock();
}
}
protected final RunningState doStart() throws Exception {
RunningState state = null;
try {
stateLock.lock();
if (this.state.get() == State.RESTORING) {
throw new IllegalStateException(JcrI18n.repositoryIsBeingRestoredAndCannotBeStarted.text(getName()));
}
state = this.runningState.get();
if (state == null) {
// start the repository by creating the running state ...
this.state.set(State.STARTING);
state = new RunningState();
this.runningState.compareAndSet(null, state);
state.completeInitialization();
this.state.set(State.RUNNING);
state.postInitialize();
}
return state;
} catch (Exception e) {
// we should set the state to NOT_RUNNING regardless of the error/exception that occurs
this.state.set(State.NOT_RUNNING);
throw e;
} finally {
stateLock.unlock();
}
}
protected final boolean doShutdown(boolean rollback) {
if (this.state.get() == State.NOT_RUNNING) return true;
try {
stateLock.lock();
RunningState running = this.runningState.get();
if (running != null) {
// Prevent future 'login(...)' calls from restarting the repository ...
this.allowAutoStartDuringLogin.set(false);
this.state.set(State.STOPPING);
// Terminate each of the still-open sessions ...
running.terminateSessions();
// Now shutdown the running state ...
running.shutdown(rollback);
// Null out the running state ...
this.runningState.set(null);
}
this.state.set(State.NOT_RUNNING);
} finally {
stateLock.unlock();
}
return true;
}
public Transactions transactions() {
return runningState().transactions;
}
protected final DocumentStore documentStore() {
return runningState().documentStore();
}
protected final String repositoryName() {
return repositoryName.get();
}
protected final RepositoryCache repositoryCache() {
return runningState().repositoryCache();
}
protected final RepositoryStatistics statistics() {
return runningState().statistics();
}
protected final RepositoryNodeTypeManager nodeTypeManager() {
return runningState().nodeTypeManager();
}
protected final RepositoryQueryManager queryManager() {
return runningState().queryManager();
}
protected final RepositoryLockManager lockManager() {
return runningState().lockManager();
}
protected final NamespaceRegistry persistentRegistry() {
return runningState().persistentRegistry();
}
protected final String systemWorkspaceName() {
return runningState().systemWorkspaceName();
}
protected final String systemWorkspaceKey() {
return runningState().systemWorkspaceKey();
}
protected final ChangeBus changeBus() {
return runningState().changeBus();
}
protected final String repositoryKey() {
return runningState().repositoryKey();
}
protected final JcrRepository.RunningState runningState() {
RunningState running = runningState.get();
if (running == null) {
throw new IllegalStateException(JcrI18n.repositoryIsNotRunningOrHasBeenShutDown.text(repositoryName()));
}
return running;
}
protected final boolean hasWorkspace( String workspaceName ) {
return repositoryCache().getWorkspaceNames().contains(workspaceName);
}
protected final NodeCache workspaceCache( String workspaceName ) {
return repositoryCache().getWorkspaceCache(workspaceName);
}
final SessionCache createSystemSession( ExecutionContext context,
boolean readOnly ) {
return repositoryCache().createSession(context, systemWorkspaceName(), readOnly);
}
protected final TransactionManager transactionManager() {
return runningState().txnManager();
}
protected final void prepareToRestore() throws RepositoryException {
logger.debug("Preparing to restore '{0}' repository; setting state to RESTORING", getName());
if (getState() == State.RESTORING) {
throw new RepositoryException(JcrI18n.repositoryIsCurrentlyBeingRestored.text(getName()));
}
state.set(State.RESTORING);
}
protected final String journalId() {
return runningState().journalId();
}
protected final ChangeJournal journal() {
return runningState().journal();
}
protected final boolean versioningUsed() {
return runningState().repositoryCache().versioningUsed();
}
protected final boolean lockingUsed() {
return runningState().repositoryCache().lockingUsed();
}
protected final boolean mimeTypeDetectionEnabled() {
return runningState().mimeTypeDetector() != NullMimeTypeDetector.INSTANCE;
}
protected final void completeRestore(RestoreOptions options) throws ExecutionException, Exception {
if (getState() == State.RESTORING) {
logger.debug("Shutting down '{0}' after content has been restored", getName());
doShutdown(false);
logger.debug("Starting '{0}' after content has been restored", getName());
start();
logger.debug("Started '{0}' after content has been restored; beginning indexing of content", getName());
if (options.reindexContentOnFinish()) {
// Reindex all content ...
queryManager().cleanAndReindex(false);
logger.debug("Completed reindexing all content in '{0}' after restore.", getName());
}
}
}
/**
* Get the immutable configuration for this repository.
*
* @return the configuration; never null
*/
public RepositoryConfiguration getConfiguration() {
return this.config.get();
}
@Override
public String getDescriptor( String key ) {
if (key == null) return null;
if (!isSingleValueDescriptor(key)) return null;
JcrValue value = (JcrValue)descriptors.get(key);
try {
return value.getString();
} catch (RepositoryException re) {
throw new IllegalStateException(re);
}
}
@Override
public JcrValue getDescriptorValue( String key ) {
if (key == null) return null;
if (!isSingleValueDescriptor(key)) return null;
return (JcrValue)descriptors.get(key);
}
@Override
public JcrValue[] getDescriptorValues( String key ) {
Object value = descriptors.get(key);
if (value instanceof JcrValue[]) {
// Make a defensive copy of the array; the elements are immutable ...
JcrValue[] values = (JcrValue[])value;
JcrValue[] newValues = new JcrValue[values.length];
System.arraycopy(values, 0, newValues, 0, values.length);
return newValues;
}
if (value instanceof JcrValue) {
return new JcrValue[] {(JcrValue)value};
}
return null;
}
@Override
public boolean isSingleValueDescriptor( String key ) {
if (key == null) return true;
return descriptors.get(key) instanceof JcrValue;
}
@Override
public boolean isStandardDescriptor( String key ) {
return STANDARD_DESCRIPTORS.contains(key);
}
@Override
public String[] getDescriptorKeys() {
return descriptors.keySet().toArray(new String[descriptors.size()]);
}
@Override
public synchronized JcrSession login() throws RepositoryException {
return login(null, null);
}
@Override
public synchronized JcrSession login( Credentials credentials ) throws RepositoryException {
return login(credentials, null);
}
@Override
public synchronized JcrSession login( String workspaceName ) throws RepositoryException {
return login(null, workspaceName);
}
/**
* @throws IllegalArgumentException if <code>credentials</code> is not <code>null</code> but:
* <ul>
* <li>provides neither a <code>getLoginContext()</code> nor a <code>getAccessControlContext()</code> method and is
* not an instance of {@code SimpleCredentials}.</li>
* <li>provides a <code>getLoginContext()</code> method that doesn't return a {@link LoginContext}.
* <li>provides a <code>getLoginContext()</code> method that returns a <code>
* null</code> {@link LoginContext}.
* <li>does not provide a <code>getLoginContext()</code> method, but provides a <code>getAccessControlContext()</code>
* method that doesn't return an {@link AccessControlContext}.
* <li>does not provide a <code>getLoginContext()</code> method, but provides a <code>getAccessControlContext()</code>
* method that returns a <code>null</code> {@link AccessControlContext}.
* </ul>
* @see javax.jcr.Repository#login(javax.jcr.Credentials, java.lang.String)
*/
@Override
public synchronized JcrSession login( final Credentials credentials,
String workspaceName ) throws RepositoryException {
final String repoName = this.repositoryName();
// Get the running state ...
RunningState running = this.runningState.get();
if (running == null) {
if (this.allowAutoStartDuringLogin.get()) {
// Try starting ...
try {
running = doStart();
} catch (Throwable t) {
throw new RepositoryException(JcrI18n.errorStartingRepository.text(repoName, t.getMessage()), t);
}
if (running == null) {
throw new RepositoryException(JcrI18n.repositoryIsNotRunningOrHasBeenShutDown.text(repoName));
}
} else {
throw new RepositoryException(JcrI18n.repositoryIsNotRunningOrHasBeenShutDown.text(repoName));
}
} else {
if (this.state.get() == State.RESTORING) {
throw new RepositoryException(JcrI18n.repositoryIsBeingRestoredAndCannotBeStarted.text(getName()));
}
}
workspaceName = validateWorkspaceName(running, workspaceName);
final AuthenticationProviders authenticators = running.authenticators();
final Credentials anonCredentials = running.anonymousCredentials();
final Map<String, Object> attributes = new HashMap<String, Object>();
// Try to authenticate with the provider(s) ...
ExecutionContext context = running.context();
ExecutionContext sessionContext = authenticators.authenticate(credentials, repoName, workspaceName, context, attributes);
if (sessionContext == null && credentials != null && anonCredentials != null) {
// Failed non-anonymous authentication, so try anonymous authentication ...
if (logger.isDebugEnabled()) logger.debug(JcrI18n.usingAnonymousUser.text());
attributes.clear();
sessionContext = authenticators.authenticate(anonCredentials, repoName, workspaceName, context, attributes);
}
if (sessionContext == null) {
// Failed authentication ...
throw new javax.jcr.LoginException(JcrI18n.loginFailed.text(repoName, workspaceName));
}
// We have successfully authenticated ...
try {
// Look for whether this context is read-only ...
SecurityContext securityContext = sessionContext.getSecurityContext();
boolean writable = JcrSession.hasRole(securityContext, ModeShapeRoles.READWRITE, repoName, workspaceName)
|| JcrSession.hasRole(securityContext, ModeShapeRoles.ADMIN, repoName, workspaceName);
JcrSession session = new JcrSession(this, workspaceName, sessionContext, attributes, !writable);
// Need to make sure that the user has access to this session
session.checkWorkspacePermission(workspaceName, ModeShapePermissions.READ);
running.addSession(session, false);
return session;
} catch (AccessDeniedException ace) {
throw new LoginException(JcrI18n.loginFailed.text(repoName, workspaceName), ace);
} catch (WorkspaceNotFoundException e) {
throw new NoSuchWorkspaceException(e.getMessage(), e);
}
}
private String validateWorkspaceName( RunningState runningState,
String workspaceName ) throws RepositoryException {
if (workspaceName == null) {
return runningState.defaultWorkspaceName();
}
if (runningState.systemWorkspaceName().equals(workspaceName)) {
throw new NoSuchWorkspaceException(JcrI18n.workspaceNameIsInvalid.text(repositoryName(), workspaceName));
}
return workspaceName;
}
protected static class ConfigurationChange implements Editor.Observer {
private final Path SECURITY_PATH = Paths.path(FieldName.SECURITY);
private final Path SEQUENCING_PATH = Paths.path(FieldName.SEQUENCING);
private final Path EXTRACTORS_PATH = Paths.path(FieldName.TEXT_EXTRACTION, FieldName.EXTRACTORS);
private final Path INDEXES_PATH = Paths.path(FieldName.INDEXES);
private final Path INDEX_PROVIDERS_PATH = Paths.path(FieldName.INDEX_PROVIDERS);
private final Path STORAGE_PATH = Paths.path(FieldName.STORAGE);
private final Path BINARY_STORAGE_PATH = Paths.path(FieldName.STORAGE, FieldName.BINARY_STORAGE);
private final Path WORKSPACES_PATH = Paths.path(FieldName.WORKSPACES);
private final Path PREDEFINED_PATH = Paths.path(FieldName.WORKSPACES, FieldName.PREDEFINED);
private final Path JNDI_PATH = Paths.path(FieldName.JNDI_NAME);
private final Path MINIMUM_BINARY_SIZE_IN_BYTES_PATH = Paths.path(FieldName.STORAGE, FieldName.BINARY_STORAGE,
FieldName.MINIMUM_BINARY_SIZE_IN_BYTES);
private final Path NAME_PATH = Paths.path(FieldName.NAME);
private final Path MONITORING_PATH = Paths.path(FieldName.MONITORING);
private final Path[] IGNORE_PATHS = new Path[] {STORAGE_PATH, BINARY_STORAGE_PATH};
protected boolean securityChanged = false;
protected boolean sequencingChanged = false;
protected boolean extractorsChanged = false;
protected boolean storageChanged = false;
protected boolean binaryStorageChanged = false;
protected boolean indexProvidersChanged = false;
protected boolean indexesChanged = false;
protected boolean workspacesChanged = false;
protected boolean predefinedWorkspacesChanged = false;
protected boolean jndiChanged = false;
protected boolean largeValueChanged = false;
protected boolean nameChanged = false;
protected boolean monitoringChanged = false;
@Override
public void setArrayValue( Path path,
Array.Entry entry ) {
checkForChanges(path);
}
@Override
public void addArrayValue( Path path,
Array.Entry entry ) {
checkForChanges(path);
}
@Override
public void removeArrayValue( Path path,
Array.Entry entry ) {
checkForChanges(path);
}
@Override
public void clear( Path path ) {
checkForChanges(path);
}
@Override
public void put( Path parentPath,
String field,
Object newValue ) {
checkForChanges(parentPath.with(field));
}
@Override
public void remove( Path path,
String field ) {
checkForChanges(path.with(field));
}
private void checkForChanges( Path path ) {
for (Path ignorePath : IGNORE_PATHS) {
if (path.equals(ignorePath)) return;
}
if (!largeValueChanged && path.equals(MINIMUM_BINARY_SIZE_IN_BYTES_PATH)) largeValueChanged = true;
else if (!binaryStorageChanged && path.startsWith(BINARY_STORAGE_PATH)) binaryStorageChanged = true;
else if (!storageChanged && path.startsWith(STORAGE_PATH)) storageChanged = true;
if (!sequencingChanged && path.startsWith(SEQUENCING_PATH)) sequencingChanged = true;
if (!extractorsChanged && path.startsWith(EXTRACTORS_PATH)) extractorsChanged = true;
if (!securityChanged && path.startsWith(SECURITY_PATH)) securityChanged = true;
if (!workspacesChanged && path.startsWith(WORKSPACES_PATH) && !path.startsWith(PREDEFINED_PATH)) workspacesChanged = true;
if (!predefinedWorkspacesChanged && path.startsWith(PREDEFINED_PATH)) predefinedWorkspacesChanged = true;
if (!indexesChanged && path.startsWith(INDEXES_PATH)) indexesChanged = true;
if (!indexProvidersChanged && path.startsWith(INDEX_PROVIDERS_PATH)) indexProvidersChanged = true;
if (!jndiChanged && path.equals(JNDI_PATH)) jndiChanged = true;
if (!nameChanged && path.equals(NAME_PATH)) nameChanged = true;
if (!monitoringChanged && path.equals(MONITORING_PATH)) monitoringChanged = true;
}
}
@SuppressWarnings( "deprecation" )
private void initializeDescriptors() {
ValueFactories factories = new ExecutionContext().getValueFactories();
descriptors.put(Repository.LEVEL_1_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.LEVEL_2_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_LOCKING_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_OBSERVATION_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_QUERY_SQL_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_TRANSACTIONS_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_VERSIONING_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.QUERY_XPATH_DOC_ORDER, valueFor(factories, false)); // see MODE-613
descriptors.put(Repository.QUERY_XPATH_POS_INDEX, valueFor(factories, false)); // no support doc order searching in xpath
descriptors.put(Repository.WRITE_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.IDENTIFIER_STABILITY, valueFor(factories, Repository.IDENTIFIER_STABILITY_INDEFINITE_DURATION));
descriptors.put(Repository.OPTION_XML_IMPORT_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_XML_EXPORT_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_UNFILED_CONTENT_SUPPORTED, valueFor(factories, false));
descriptors.put(Repository.OPTION_SIMPLE_VERSIONING_SUPPORTED, valueFor(factories, false));
descriptors.put(Repository.OPTION_ACTIVITIES_SUPPORTED, valueFor(factories, false));
descriptors.put(Repository.OPTION_BASELINES_SUPPORTED, valueFor(factories, false));
descriptors.put(Repository.OPTION_ACCESS_CONTROL_SUPPORTED, valueFor(factories, true));
JcrValue journalingValue = valueFor(factories, repositoryConfiguration().getJournaling().isEnabled());
descriptors.put(Repository.OPTION_JOURNALED_OBSERVATION_SUPPORTED, journalingValue);
descriptors.put(Repository.OPTION_RETENTION_SUPPORTED, valueFor(factories, false));
descriptors.put(Repository.OPTION_LIFECYCLE_SUPPORTED, valueFor(factories, false));
descriptors.put(Repository.OPTION_NODE_AND_PROPERTY_WITH_SAME_NAME_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_UPDATE_PRIMARY_NODE_TYPE_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_UPDATE_MIXIN_NODE_TYPES_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_SHAREABLE_NODES_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.OPTION_NODE_TYPE_MANAGEMENT_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_INHERITANCE,
valueFor(factories, Repository.NODE_TYPE_MANAGEMENT_INHERITANCE_MULTIPLE));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_PRIMARY_ITEM_NAME_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_ORDERABLE_CHILD_NODES_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_RESIDUAL_DEFINITIONS_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_AUTOCREATED_DEFINITIONS_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_SAME_NAME_SIBLINGS_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_PROPERTY_TYPES, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_OVERRIDES_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_MULTIVALUED_PROPERTIES_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_MULTIPLE_BINARY_PROPERTIES_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_VALUE_CONSTRAINTS_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.NODE_TYPE_MANAGEMENT_UPDATE_IN_USE_SUPORTED, valueFor(factories, true));
descriptors.put(Repository.QUERY_LANGUAGES,
new JcrValue[] {valueFor(factories, Query.XPATH), valueFor(factories, Query.JCR_SQL2),
valueFor(factories, Query.SQL), valueFor(factories, Query.JCR_JQOM)});
descriptors.put(Repository.QUERY_STORED_QUERIES_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.QUERY_FULL_TEXT_SEARCH_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.QUERY_JOINS, valueFor(factories, Repository.QUERY_JOINS_INNER_OUTER));
descriptors.put(Repository.SPEC_NAME_DESC, valueFor(factories, JcrI18n.SPEC_NAME_DESC.text()));
descriptors.put(Repository.SPEC_VERSION_DESC, valueFor(factories, "2.0"));
descriptors.put(Repository.REP_NAME_DESC, valueFor(factories, ModeShape.getName()));
descriptors.put(Repository.REP_VENDOR_DESC, valueFor(factories, ModeShape.getVendor()));
descriptors.put(Repository.REP_VENDOR_URL_DESC, valueFor(factories, ModeShape.getUrl()));
descriptors.put(Repository.REP_VERSION_DESC, valueFor(factories, ModeShape.getVersion()));
descriptors.put(Repository.OPTION_WORKSPACE_MANAGEMENT_SUPPORTED, valueFor(factories, true));
descriptors.put(Repository.REPOSITORY_NAME, valueFor(factories, repositoryName()));
}
private static JcrValue valueFor( ValueFactories valueFactories,
int type,
Object value ) {
return new JcrValue(valueFactories, type, value);
}
private static JcrValue valueFor( ValueFactories valueFactories,
String value ) {
return valueFor(valueFactories, PropertyType.STRING, value);
}
private static JcrValue valueFor( ValueFactories valueFactories,
boolean value ) {
return valueFor(valueFactories, PropertyType.BOOLEAN, value);
}
protected void refreshWorkspaces() {
RunningState running = runningState();
if (running != null) {
Set<String> workspaceNames = running.repositoryCache().getWorkspaceNames();
ValueFactories factories = running.context().getValueFactories();
JcrValue[] values = new JcrValue[workspaceNames.size()];
int i = 0;
for (String workspaceName : workspaceNames) {
values[i++] = valueFor(factories, workspaceName);
}
descriptors.put(Repository.REPOSITORY_WORKSPACES, values);
}
}
private void repositoryNameChanged() {
descriptors.put(Repository.REPOSITORY_NAME, repositoryName());
}
@Immutable
protected class RunningState {
private final RepositoryConfiguration config;
private final DocumentStore documentStore;
private final SchematicDb schematicDb;
private final AuthenticationProviders authenticators;
private final Credentials anonymousCredentialsIfSuppliedCredentialsFail;
private final String defaultWorkspaceName;
private final String systemWorkspaceName;
private final String systemWorkspaceKey;
private final RepositoryNodeTypeManager nodeTypes;
private final RepositoryLockManager lockManager;
private final TransactionManagerLookup txMgrLookup;
private final TransactionManager txnMgr;
private final Transactions transactions;
private final String jndiName;
private final SystemNamespaceRegistry persistentRegistry;
private final ExecutionContext context;
private final ExecutionContext internalWorkerContext;
private final ReadWriteLock activeSessionLock = new ReentrantReadWriteLock();
private final WeakHashMap<JcrSession, Object> activeSessions = new WeakHashMap<>();
private final WeakHashMap<JcrSession, Object> internalSessions = new WeakHashMap<>();
private final RepositoryStatistics statistics;
private final RepositoryStatisticsBean mbean;
private final BinaryStore binaryStore;
private final ScheduledExecutorService statsRollupService;
private final Sequencers sequencers;
private final QueryParsers queryParsers;
private final RepositoryQueryManager repositoryQueryManager;
private final ExecutorService indexingExecutor;
private final TextExtractors extractors;
private final ChangeBus changeBus;
private final ExecutorService changeDispatchingQueue;
private final MimeTypeDetector mimeTypeDetector;
private final BackupService backupService;
private final InitialContentImporter initialContentImporter;
private final SystemContentInitializer systemContentInitializer;
private final NodeTypesImporter nodeTypesImporter;
private final Connectors connectors;
private final List<ScheduledFuture<?>> backgroundProcesses = new ArrayList<>();
private final Problems problems;
private final ChangeJournal journal;
private final ClusteringService clusteringService;
private final LockingService lockingService;
private Transaction existingUserTransaction;
private RepositoryCache cache;
protected RunningState() throws Exception {
this(null, null);
}
@SuppressWarnings( "deprecation" )
protected RunningState( JcrRepository.RunningState other,
JcrRepository.ConfigurationChange change ) throws Exception {
this.config = repositoryConfiguration();
this.systemContentInitializer = new SystemContentInitializer();
if (other == null) {
logger.debug("Starting '{0}' repository with configuration: \n{1}", repositoryName(), this.config);
this.problems = new SimpleProblems();
} else {
logger.debug("Updating '{0}' repository with configuration: \n{1}", repositoryName(), this.config);
this.problems = other.problems;
}
ExecutionContext tempContext = new ExecutionContext();
// Set up monitoring (doing this early in the process so it is available to other components to use) ...
if (other != null && !change.monitoringChanged) {
this.statistics = other.statistics;
this.statsRollupService = other.statsRollupService;
this.mbean = other.mbean;
} else {
this.statistics = other != null ? other.statistics : new RepositoryStatistics(tempContext);
if (this.config.getMonitoring().enabled()) {
// Start the Cron service, with a minimum of a single thread ...
this.statsRollupService = tempContext.getScheduledThreadPool("modeshape-stats");
this.statistics.start(this.statsRollupService);
this.mbean = new RepositoryStatisticsBean(statistics, getName());
this.mbean.start();
} else {
this.statsRollupService = null;
this.mbean = null;
}
}
this.systemWorkspaceName = RepositoryConfiguration.SYSTEM_WORKSPACE_NAME;
this.systemWorkspaceKey = NodeKey.keyForWorkspaceName(this.systemWorkspaceName);
if (other != null && !change.workspacesChanged) {
this.defaultWorkspaceName = other.defaultWorkspaceName;
} else {
// Set up some of the defaults ...
this.defaultWorkspaceName = config.getDefaultWorkspaceName();
}
try {
if (other != null) {
if (change.storageChanged) {
// Can't change where we're storing the content while we're running, so take effect upon next startup
warn(JcrI18n.storageRelatedConfigurationChangesWillTakeEffectAfterShutdown, getName());
}
if (change.binaryStorageChanged) {
// Can't change where we're storing the content while we're running, so take effect upon next startup
warn(JcrI18n.storageRelatedConfigurationChangesWillTakeEffectAfterShutdown, getName());
}
// reuse the existing storage-related components ...
this.schematicDb = other.schematicDb;
this.cache = other.cache;
this.context = other.context;
this.connectors = other.connectors;
this.documentStore = other.documentStore;
this.txMgrLookup = other.txMgrLookup;
this.txnMgr = other.txnManager();
this.transactions = other.transactions;
suspendExistingUserTransaction();
if (change.largeValueChanged) {
// We can update the value used in the repository cache dynamically ...
BinaryStorage binaryStorage = config.getBinaryStorage();
this.cache.setLargeStringLength(binaryStorage.getMinimumBinarySizeInBytes());
this.context.getBinaryStore().setMinimumBinarySizeInBytes(binaryStorage.getMinimumBinarySizeInBytes());
}
if (change.predefinedWorkspacesChanged) {
// Make sure that all the predefined workspaces are available ...
for (String workspaceName : config.getPredefinedWorkspaceNames()) {
this.cache.createWorkspace(workspaceName);
}
}
this.mimeTypeDetector = other.mimeTypeDetector;
this.binaryStore = other.binaryStore;
this.changeBus = other.changeBus;
this.internalWorkerContext = other.internalWorkerContext;
this.nodeTypes = other.nodeTypes.with(this, true, true);
this.lockManager = other.lockManager.with(this, other.config.getGarbageCollection());
// We have to register new components that depend on this instance ...
this.changeBus.unregister(other.nodeTypes);
this.changeBus.unregister(other.lockManager);
this.changeBus.register(this.nodeTypes);
this.changeBus.register(this.lockManager);
this.persistentRegistry = other.persistentRegistry;
this.changeDispatchingQueue = other.changeDispatchingQueue;
this.clusteringService = other.clusteringService;
this.journal = other.journal;
this.lockingService = other.lockingService;
} else {
// find the Schematic database
this.schematicDb = environment().getDb(config.getPersistenceConfiguration());
this.txMgrLookup = config.getTransactionManagerLookup();
this.txnMgr = this.txMgrLookup.getTransactionManager();
this.transactions = createTransactions(this.txnMgr, schematicDb);
List<Component> connectorComponents = config.getFederation().getConnectors(this.problems);
Map<String, List<RepositoryConfiguration.ProjectionConfiguration>> preconfiguredProjectionsByWorkspace = config.getFederation()
.getProjectionsByWorkspace();
Set<String> extSources = config.getFederation().getExternalSources();
this.connectors = new Connectors(this, connectorComponents, extSources, preconfiguredProjectionsByWorkspace);
RepositoryConfiguration.Clustering clustering = config.getClustering();
LockingService startupLockingService = null;
long lockTimeoutMillis = config.getLockTimeoutMillis();
if (clustering.isEnabled()) {
final String clusterName = clustering.getClusterName();
Channel channel = environment().getChannel(clusterName);
if (channel != null) {
this.clusteringService = ClusteringService.startStandalone(clusterName, channel);
} else {
this.clusteringService = ClusteringService.startStandalone(clusterName, clustering.getConfiguration());
}
startupLockingService = new JGroupsLockingService(this.clusteringService.getChannel(), lockTimeoutMillis);
this.lockingService = clustering.useDbLocking() ?
new DbLockingService(lockTimeoutMillis, this.schematicDb) : startupLockingService;
} else {
this.clusteringService = null;
this.lockingService = new StandaloneLockingService(lockTimeoutMillis);
}
suspendExistingUserTransaction();
// Start the database
this.schematicDb.start();
// Set up the binary store ...
BinaryStorage binaryStorageConfig = config.getBinaryStorage();
binaryStore = binaryStorageConfig.getBinaryStore();
binaryStore.start();
tempContext = tempContext.with(binaryStore);
// Now create the registry implementation and the execution context that uses it ...
this.persistentRegistry = new SystemNamespaceRegistry(this);
this.mimeTypeDetector = binaryStorageConfig.getMimeTypeDetector(this.config.environment());
this.context = tempContext.with(persistentRegistry);
this.persistentRegistry.setContext(this.context);
this.internalWorkerContext = this.context.with(new InternalSecurityContext(INTERNAL_WORKER_USERNAME));
// Create clustering service and event bus
this.changeDispatchingQueue = this.context().getCachedTreadPool("modeshape-event-dispatcher",
Integer.MAX_VALUE);
ChangeBus localBus = new RepositoryChangeBus(name(), changeDispatchingQueue, statistics(), config.getEventBusSize());
this.changeBus = clusteringService != null ? new ClusteredChangeBus(localBus, clusteringService) : localBus;
this.changeBus.start();
// Set up the event journal
RepositoryConfiguration.Journaling journaling = config.getJournaling();
if (journaling.isEnabled()) {
boolean asyncWritesEnabled = journaling.asyncWritesEnabled();
LocalJournal localJournal = new LocalJournal(journaling.location(), asyncWritesEnabled,
journaling.maxDaysToKeepRecords());
this.journal = clusteringService != null ? new ClusteredJournal(localJournal, clusteringService) : localJournal;
this.journal.start();
if (asyncWritesEnabled) {
// Register the journal as a normal asynchronous listener ...
this.changeBus.register(journal);
} else {
// Register the journal
this.changeBus.registerInThread(journal);
}
} else {
this.journal = null;
}
// Set up the document store and environment
final RepositoryEnvironment repositoryEnvironment = new JcrRepositoryEnvironment(transactions, lockingService,
journalId());
LocalDocumentStore localStore = new LocalDocumentStore(schematicDb, repositoryEnvironment);
this.documentStore = connectors.hasConnectors() ? new FederatedDocumentStore(connectors, localStore) : localStore;
// Set up the repository cache ...
this.cache = new RepositoryCache(context, documentStore, startupLockingService, config, systemContentInitializer,
repositoryEnvironment, changeBus, Upgrades.STANDARD_UPGRADES);
// Set up the node type manager ...
this.nodeTypes = new RepositoryNodeTypeManager(this, true, true);
this.changeBus.register(this.nodeTypes);
// Set up the lock manager ...
this.lockManager = new RepositoryLockManager(this, config.getGarbageCollection());
this.changeBus.register(this.lockManager);
// Set up the monitoring listener ...
this.changeBus.register(this.statistics);
// Refresh several of the components information from the repository cache ...
this.persistentRegistry.refreshFromSystem();
this.lockManager.refreshFromSystem();
if (!this.nodeTypes.refreshFromSystem()) {
try {
// Read in the built-in node types ...
CndImporter importer = new CndImporter(context);
importer.importBuiltIns(this.problems);
this.nodeTypes.registerNodeTypes(importer.getNodeTypeDefinitions(), false, true, true);
} catch (RepositoryException re) {
throw new IllegalStateException("Could not load node type definition files", re);
} catch (IOException ioe) {
throw new IllegalStateException("Could not access node type definition files", ioe);
}
}
// Add the built-ins, ensuring we overwrite any badly-initialized values ...
this.persistentRegistry.register(JcrNamespaceRegistry.STANDARD_BUILT_IN_NAMESPACES_BY_PREFIX);
// Record the number of workspaces that are available/predefined ...
this.statistics.set(ValueMetric.WORKSPACE_COUNT, cache.getWorkspaceNames().size());
}
if (other != null && !change.securityChanged) {
this.authenticators = other.authenticators;
this.anonymousCredentialsIfSuppliedCredentialsFail = other.anonymousCredentialsIfSuppliedCredentialsFail;
} else {
// Set up the security ...
AtomicBoolean useAnonymouOnFailedLogins = new AtomicBoolean();
this.authenticators = createAuthenticationProviders(useAnonymouOnFailedLogins);
this.anonymousCredentialsIfSuppliedCredentialsFail = useAnonymouOnFailedLogins.get() ? new AnonymousCredentials() : null;
}
if (other != null && !change.extractorsChanged) {
this.extractors = new TextExtractors(this, other.config.getTextExtraction());
} else {
this.extractors = new TextExtractors(this, config.getTextExtraction());
}
this.binaryStore.setMimeTypeDetector(this.mimeTypeDetector);
this.binaryStore.setTextExtractors(this.extractors);
if (other != null && !change.sequencingChanged) {
this.sequencers = other.sequencers.with(this);
if (!sequencers.isEmpty()) this.changeBus.register(this.sequencers);
this.changeBus.unregister(other.sequencers);
} else {
this.sequencers = new Sequencers(this, config, cache.getWorkspaceNames());
}
this.indexingExecutor = this.context.getThreadPool("modeshape-reindexing");
this.queryParsers = new QueryParsers(new JcrSql2QueryParser(), new XPathQueryParser(),
new FullTextSearchParser(), new JcrSqlQueryParser(), new JcrQomQueryParser());
RepositoryConfiguration.Reindexing reindexingCfg = config.getReindexing();
this.repositoryQueryManager = new RepositoryQueryManager(this, indexingExecutor, config, reindexingCfg);
if (reindexingCfg.isAsync()) {
this.changeBus.register(this.repositoryQueryManager);
} else {
this.changeBus.registerInThread(this.repositoryQueryManager);
}
// Check that we have parsers for all the required languages ...
assert this.queryParsers.getParserFor(Query.XPATH) != null;
assert this.queryParsers.getParserFor(Query.SQL) != null;
assert this.queryParsers.getParserFor(Query.JCR_SQL2) != null;
assert this.queryParsers.getParserFor(Query.JCR_JQOM) != null;
assert this.queryParsers.getParserFor(QueryLanguage.SEARCH) != null;
if (other != null && !change.jndiChanged) {
// The repository is already registered (or not registered)
this.jndiName = other.jndiName;
} else {
// The JNDI location has changed, so register the new one ...
this.jndiName = config.getJndiName();
bindIntoJndi();
// And unregister the old name ...
if (other != null) {
other.unbindFromJndi();
}
}
// Set up the backup service and executor ...
this.backupService = new BackupService(this);
// Set up the initial content importer
this.initialContentImporter = new InitialContentImporter(config.getInitialContent(), this);
// Set up the node types importer (but don't import them yet)
this.nodeTypesImporter = new NodeTypesImporter(config.getNodeTypes(), this);
} catch (Throwable t) {
try {
shutdown(true);
tempContext.terminateAllPools(0, TimeUnit.MILLISECONDS);
// resume any user transaction that may have been suspended earlier
resumeExistingUserTransaction();
} catch (Exception e) {
logger.debug(e, "Additional exceptions while attempting to shutdown and rollback...");
}
throw (t instanceof Exception) ? (Exception)t : new RuntimeException(t);
}
}
protected Transactions createTransactions(TransactionManager txnMgr,
SchematicDb db) {
if (txnMgr == null) {
throw new ConfigurationException(JcrI18n.repositoryCannotBeStartedWithoutTransactionalSupport.text(getName()));
}
return new Transactions(txnMgr, db);
}
/**
* Performs the steps required after the running state has been created and before a repository is considered
* "initialized"
*
* @throws Exception if anything goes wrong in this phase. If it does, the transaction used for startup should be rolled
* back
*/
protected final void completeInitialization() throws Exception {
try {
refreshWorkspaces();
this.sequencers.initialize();
// import the preconfigured node types before the initial content, in case the latter use custom types
this.nodeTypesImporter.importNodeTypes();
// Load the index definitions AFTER the node types were imported ...
this.queryManager().getIndexManager().importIndexDefinitions();
if (repositoryCache().isInitializingRepository()) {
// import initial content for each of the workspaces; this has to be done after the running state has started
this.cache.runOneTimeSystemInitializationOperation(() -> {
for (String workspaceName : repositoryCache().getWorkspaceNames()) {
initialContentImporter().importInitialContent(workspaceName);
}
return null;
});
}
// connectors must be initialized after initial content because that can have an influence on projections
this.connectors.initialize();
// only mark the query manager as initialed *after* all the other components have finished initializing
// otherwise we risk getting indexing/scanning events for components which have not finished initializing (e.g. connectors)
this.repositoryQueryManager.initialize();
// Now record in the content that we're finished initializing the repository.
// This will commit the startup transaction.
repositoryCache().completeInitialization();
// Now complete the upgrade of the repository, if required. This will be done transactionally.
repositoryCache().completeUpgrade(new Upgrades.Context() {
@Override
public RunningState getRepository() {
return RunningState.this;
}
@Override
public Problems getProblems() {
return RunningState.this.problems();
}
});
} catch (Throwable t) {
try {
doShutdown(true);
resumeExistingUserTransaction();
} catch (Exception e) {
logger.debug(e, "Additional errors while attempting to shutdown and rollback...");
}
throw t instanceof Exception ? (Exception)t : new RuntimeException(t);
}
}
/**
* Perform any initialization code that requires the repository to be in a running state. The repository has been
* considered started up.
*
* @throws Exception if there is a problem during this phase.
*/
protected final void postInitialize() throws Exception {
try {
// Have the query manager tell the providers to initialize the indexes. This may cause a background reindexing ...
queryManager().reindex();
// Register the background processes.
// Do this last since we want the repository running before these are started ...
GarbageCollection gcConfig = config.getGarbageCollection();
String threadPoolName = gcConfig.getThreadPoolName();
long gcInitialTimeInMillis = determineInitialDelay(gcConfig.getInitialTimeExpression());
long gcIntervalInMillis = gcConfig.getIntervalInMillis();
assert gcInitialTimeInMillis >= 0;
ScheduledExecutorService garbageCollectionService = this.context.getScheduledThreadPool(threadPoolName);
backgroundProcesses.add(garbageCollectionService.scheduleAtFixedRate(new LockGarbageCollectionTask(
JcrRepository.this),
gcInitialTimeInMillis,
gcIntervalInMillis,
TimeUnit.MILLISECONDS));
backgroundProcesses.add(garbageCollectionService.scheduleAtFixedRate(new BinaryValueGarbageCollectionTask(
JcrRepository.this),
gcInitialTimeInMillis,
gcIntervalInMillis,
TimeUnit.MILLISECONDS));
DocumentOptimization optConfig = config.getDocumentOptimization();
if (optConfig.isEnabled()) {
warn(JcrI18n.enablingDocumentOptimization, name());
threadPoolName = optConfig.getThreadPoolName();
long optInitialTimeInMillis = determineInitialDelay(optConfig.getInitialTimeExpression());
long optIntervalInHours = optConfig.getIntervalInHours();
int targetCount = optConfig.getChildCountTarget();
int tolerance = optConfig.getChildCountTolerance();
assert optInitialTimeInMillis >= 0;
long optIntervalInMillis = TimeUnit.MILLISECONDS.convert(optIntervalInHours, TimeUnit.HOURS);
ScheduledExecutorService optService = this.context.getScheduledThreadPool(threadPoolName);
OptimizationTask optTask = new OptimizationTask(JcrRepository.this, targetCount, tolerance);
backgroundProcesses.add(optService.scheduleAtFixedRate(optTask, optInitialTimeInMillis, optIntervalInMillis,
TimeUnit.MILLISECONDS));
}
if (journal != null) {
RepositoryConfiguration.Journaling journalingCfg = config.getJournaling();
if (journalingCfg.maxDaysToKeepRecords() > 0) {
threadPoolName = journalingCfg.getThreadPoolName();
long initialTimeInMillis = determineInitialDelay(journalingCfg.getInitialTimeExpression());
assert initialTimeInMillis >= 0;
long intervalInHours = journalingCfg.getIntervalInHours();
long intervalInMillis = TimeUnit.MILLISECONDS.convert(intervalInHours, TimeUnit.HOURS);
ScheduledExecutorService journalingGCService = this.context.getScheduledThreadPool(threadPoolName);
backgroundProcesses.add(journalingGCService.scheduleAtFixedRate(new JournalingGCTask(JcrRepository.this),
initialTimeInMillis, intervalInMillis,
TimeUnit.MILLISECONDS));
}
}
} finally {
resumeExistingUserTransaction();
}
}
protected final Sequencers sequencers() {
return sequencers;
}
final String name() {
return repositoryName();
}
final ExecutionContext context() {
return context;
}
final ExecutionContext internalWorkerContext() {
return internalWorkerContext;
}
final RepositoryCache repositoryCache() {
return cache;
}
final ChangeJournal journal() {
return journal;
}
final String journalId() {
return journal != null ? journal.journalId() : null;
}
final ClusteringService clusteringService() {
return clusteringService;
}
final QueryParsers queryParsers() {
return queryParsers;
}
final RepositoryQueryManager queryManager() {
return repositoryQueryManager;
}
protected final DocumentStore documentStore() {
return documentStore;
}
protected final BinaryStore binaryStore() {
return binaryStore;
}
protected final MimeTypeDetector mimeTypeDetector() {
return mimeTypeDetector;
}
protected final TextExtractors textExtractors() {
return extractors;
}
protected final Environment environment() {
return config.environment();
}
protected final TransactionManager txnManager() {
return transactions.getTransactionManager();
}
protected final RepositoryNodeTypeManager nodeTypeManager() {
return nodeTypes;
}
protected final RepositoryLockManager lockManager() {
return lockManager;
}
protected final String systemWorkspaceName() {
return systemWorkspaceName;
}
protected final String systemWorkspaceKey() {
return systemWorkspaceKey;
}
protected final String defaultWorkspaceName() {
return defaultWorkspaceName;
}
protected final NamespaceRegistry persistentRegistry() {
return persistentRegistry;
}
protected final AuthenticationProviders authenticators() {
return authenticators;
}
protected final RepositoryStatistics statistics() {
return statistics;
}
protected final Credentials anonymousCredentials() {
return anonymousCredentialsIfSuppliedCredentialsFail;
}
protected final ChangeBus changeBus() {
return changeBus;
}
final Connectors connectors() {
return connectors;
}
protected final String repositoryKey() {
return cache.getKey();
}
protected final BackupService backupService() {
return backupService;
}
protected final void warn( I18n message,
Object... params ) {
logger.warn(message, params);
problems.addWarning(message, params);
}
protected final void error( I18n message,
Object... params ) {
logger.error(message, params);
problems.addError(message, params);
}
protected final void error( Throwable t,
I18n message,
Object... params ) {
logger.error(t, message, params);
problems.addError(t, message, params);
}
protected final Problems problems() {
return this.problems;
}
final InitialContentImporter initialContentImporter() {
return initialContentImporter;
}
private AuthenticationProviders createAuthenticationProviders( AtomicBoolean useAnonymouOnFailedLogins ) {
// Prepare to create the authenticators and authorizers ...
AuthenticationProviders authenticators = new AuthenticationProviders();
Security securityConfig = config.getSecurity();
// Set up the JAAS providers ...
JaasSecurity jaasSecurity = securityConfig.getJaas();
if (jaasSecurity != null) {
String policyName = jaasSecurity.getPolicyName();
if (policyName != null && policyName.trim().length() != 0) {
try {
JaasProvider jaasProvider = new JaasProvider(policyName);
authenticators = authenticators.with(jaasProvider);
} catch (java.lang.SecurityException e) {
if (MISSING_JAAS_POLICIES.add(policyName)) {
warn(JcrI18n.loginConfigNotFound, policyName, RepositoryConfiguration.FieldName.SECURITY + "/"
+ RepositoryConfiguration.FieldName.JAAS_POLICY_NAME,
repositoryName());
}
} catch (javax.security.auth.login.LoginException e) {
if (MISSING_JAAS_POLICIES.add(policyName)) {
warn(JcrI18n.loginConfigNotFound, policyName, RepositoryConfiguration.FieldName.SECURITY + "/"
+ RepositoryConfiguration.FieldName.JAAS_POLICY_NAME,
repositoryName());
}
}
}
}
// Set up any custom AuthenticationProvider classes ...
for (Component component : securityConfig.getCustomProviders(problems())) {
try {
AuthenticationProvider provider = component.createInstance();
authenticators = authenticators.with(provider);
if (provider instanceof AnonymousProvider) {
Object value = component.getDocument().get(FieldName.USE_ANONYMOUS_ON_FAILED_LOGINS);
if (Boolean.TRUE.equals(value)) {
useAnonymouOnFailedLogins.set(true);
}
}
if (provider instanceof EnvironmentAuthenticationProvider) {
EnvironmentAuthenticationProvider envProvider = (EnvironmentAuthenticationProvider) provider;
String securityDomain = component.getDocument().getString(FieldName.SECURITY_DOMAIN);
envProvider.setSecurityDomain(securityDomain);
envProvider.setEnvironment(environment());
envProvider.initialize();
}
} catch (Throwable t) {
logger.error(t, JcrI18n.unableToInitializeAuthenticationProvider, component, repositoryName(), t.getMessage());
}
}
// And last set up the anonymous provider ...
AnonymousSecurity anonSecurity = securityConfig.getAnonymous();
if (anonSecurity != null) {
// Set up the anonymous provider (if appropriate) ...
Set<String> anonRoles = anonSecurity.getAnonymousRoles();
if (!anonRoles.isEmpty()) {
String anonUsername = anonSecurity.getAnonymousUsername();
AnonymousProvider anonProvider = new AnonymousProvider(anonUsername, anonRoles);
authenticators = authenticators.with(anonProvider);
logger.debug("Enabling anonymous authentication and authorization.");
}
if (anonSecurity.useAnonymousOnFailedLogings()) {
useAnonymouOnFailedLogins.set(true);
}
}
return authenticators;
}
final SessionCache createSystemSession( ExecutionContext context,
boolean readOnly ) {
return cache.createSession(context, systemWorkspaceName(), readOnly);
}
protected void shutdown(boolean rollback) {
if (repositoryQueryManager != null) {
// if reindexing was asynchronous and is still going on, we need to terminate it before we stop any of caches
// or we do anything that affects the nodes
this.repositoryQueryManager.stopReindexing();
}
if (connectors != null) {
// shutdown the connectors
this.connectors.shutdown();
}
// Remove the scheduled operations ...
for (ScheduledFuture<?> future : backgroundProcesses) {
future.cancel(true);
}
// Unregister from JNDI ...
unbindFromJndi();
if (sequencers != null) {
// Shutdown the sequencers ...
sequencers.shutdown();
}
// Now wait until all the internal sessions are gone ...
if (!internalSessions.isEmpty()) {
try {
int counter = 200; // this will block at most for 10 sec (200*50ms)
while (counter > 0 && !internalSessions.isEmpty()) {
Thread.sleep(50L);
--counter;
}
} catch (InterruptedException e) {
// do nothing ...
}
}
if (cache != null) {
if (rollback) {
cache.rollbackRepositoryInfo();
}
// Now shutdown the repository caches ...
this.cache.startShutdown();
}
// shutdown the clustering service
if (this.clusteringService != null) {
this.clusteringService.shutdown();
}
if (lockingService != clusteringService) {
lockingService.shutdown();
}
// shutdown the event bus
if (this.changeBus != null) {
this.changeBus.shutdown();
}
// shutdown the journal
if (this.journal != null) {
this.journal.shutdown();
}
if (repositoryQueryManager != null) {
// Shutdown the query engine ...
repositoryQueryManager.shutdown();
}
// Shutdown the text extractors
if (extractors != null) {
extractors.shutdown();
}
if (backupService != null) {
backupService.shutdown();
}
if (binaryStore != null) {
// Shutdown the binary store ...
this.binaryStore.shutdown();
}
if (cache != null) {
// Now shutdown the repository caches ...
this.cache.completeShutdown();
}
if (statistics != null) {
statistics.stop();
}
if (mbean != null) {
mbean.stop();
}
if (this.context != null) {
this.context.terminateAllPools(30, TimeUnit.SECONDS);
}
// Shutdown the environment's resources.
this.environment().shutdown();
// shutdown the db...
if (this.schematicDb != null) {
this.schematicDb.stop();
}
}
protected void bindIntoJndi() {
if (jndiName != null && jndiName.trim().length() != 0) {
try {
InitialContext ic = new InitialContext();
ic.bind(jndiName, JcrRepository.this);
} catch (NoInitialContextException e) {
// No JNDI here ...
logger.debug("No JNDI found, so not registering '{0}' repository", getName());
} catch (OperationNotSupportedException e) {
warn(JcrI18n.jndiReadOnly, config.getName(), jndiName);
} catch (NamingException e) {
logger.error(e, JcrI18n.unableToBindToJndi, config.getName(), jndiName, e.getMessage());
} catch (Exception e) {
logger.debug(e, "Error while registering the '{0}' repository from the '{1}' name in JNDI", config.getName(),
jndiName);
}
}
}
protected void unbindFromJndi() {
if (jndiName != null && jndiName.trim().length() != 0) {
try {
InitialContext ic = new InitialContext();
ic.unbind(jndiName);
} catch (NoInitialContextException e) {
// No JNDI here ...
logger.debug("No JNDI found, so not registering '{0}' repository", getName());
} catch (OperationNotSupportedException e) {
warn(JcrI18n.jndiReadOnly, config.getName(), jndiName);
} catch (Exception e) {
logger.warn(JcrI18n.jndiReadOnly, config.getName(), jndiName);
}
}
}
void addSession( JcrSession session,
boolean internal ) {
Map<JcrSession, Object> sessions = internal ? internalSessions : activeSessions;
Lock lock = this.activeSessionLock.writeLock();
try {
lock.lock();
sessions.put(session, null);
} finally {
lock.unlock();
}
}
int activeSessionCount() {
Lock lock = this.activeSessionLock.writeLock();
try {
lock.lock();
return activeSessions.size();
} finally {
lock.unlock();
}
}
void removeSession( JcrSession session ) {
Lock lock = this.activeSessionLock.writeLock();
try {
lock.lock();
if (activeSessions.remove(session) == null) {
internalSessions.remove(session);
}
} finally {
lock.unlock();
}
}
void terminateSessions() {
Lock lock = this.activeSessionLock.writeLock();
try {
lock.lock();
for (JcrSession session : this.activeSessions.keySet()) {
session.terminate(false); // don't remove from active sessions, as we're blocked and iterating on it ...
}
this.activeSessions.clear();
} finally {
lock.unlock();
}
}
/**
* @see LockGarbageCollectionTask
*/
void cleanUpLocks() {
if (logger.isDebugEnabled()) {
logger.debug("Starting lock cleanup in the '{0}' repository", repositoryName());
}
Set<String> activeSessionIds = new HashSet<>();
try {
// Get the IDs for the active sessions ...
Lock lock = this.activeSessionLock.writeLock();
try {
lock.lock();
activeSessionIds = this.activeSessions.keySet()
.stream()
.filter(JcrSession::isLive)
.map(JcrSession::sessionId)
.collect(Collectors.toSet());
this.lockManager().cleanupLocks(activeSessionIds);
if (logger.isDebugEnabled()) {
logger.debug("Finishing lock cleanup in the '{0}' repository", repositoryName());
}
} finally {
lock.unlock();
}
} catch (TimeoutException te) {
// some locks could not be obtained trying to execute the job
// just log the exception since the transaction should've rolled back and we'll retry this job anyway later on
if (logger.isDebugEnabled()) {
logger.debug(te, "A timeout occurred while attempting to clean the JCR locks for the sessions: {0}",
activeSessionIds);
}
} catch (Throwable e) {
logger.error(e, JcrI18n.errorDuringGarbageCollection, e.getMessage());
}
}
/**
* @see BinaryValueGarbageCollectionTask
*/
void cleanUpBinaryValues() {
if (logger.isDebugEnabled()) {
logger.debug("Starting binary value cleanup in the '{0}' repository", repositoryName());
}
try {
this.binaryStore.removeValuesUnusedLongerThan(RepositoryConfiguration.UNUSED_BINARY_VALUE_AGE_IN_MILLIS,
TimeUnit.MILLISECONDS);
} catch (Throwable e) {
logger.error(e, JcrI18n.errorDuringGarbageCollection, e.getMessage());
}
if (logger.isDebugEnabled()) {
logger.debug("Finishing binary value cleanup in the '{0}' repository", repositoryName());
}
}
protected Session loginInternalSession() throws RepositoryException {
return loginInternalSession(defaultWorkspaceName());
}
protected JcrSession loginInternalSession( String workspaceName ) throws RepositoryException {
try {
boolean readOnly = false; // assume not
RunningState running = runningState();
ExecutionContext sessionContext = running.internalWorkerContext();
Map<String, Object> attributes = Collections.emptyMap();
JcrSession session = new JcrSession(JcrRepository.this, workspaceName, sessionContext, attributes, readOnly);
running.addSession(session, true);
return session;
} catch (WorkspaceNotFoundException e) {
throw new NoSuchWorkspaceException(e.getMessage(), e);
}
}
boolean suspendExistingUserTransaction() throws SystemException {
// suspend any potential existing transaction, so that the initialization is "atomic"
this.existingUserTransaction = this.transactions.suspend();
return this.existingUserTransaction != null;
}
void resumeExistingUserTransaction() throws SystemException {
if (transactions != null && existingUserTransaction != null) {
transactions.resume(existingUserTransaction);
existingUserTransaction = null;
}
}
}
protected class JcrRepositoryEnvironment implements RepositoryEnvironment {
private final Transactions transactions;
private final LockingService lockingService;
private final String journalId;
private JcrRepositoryEnvironment(Transactions transactions, LockingService lockingService, String journalId) {
this.transactions = transactions;
this.lockingService = lockingService;
this.journalId = journalId;
}
@Override
public Transactions getTransactions() {
return transactions;
}
@Override
public String journalId() {
return journalId;
}
@Override
public LockingService lockingService() {
return lockingService;
}
@Override
public NodeTypes nodeTypes() {
if (runningState.get() == null) {
// not initialized yet
return null;
}
return runningState().nodeTypeManager().getNodeTypes();
}
}
private final class InternalSecurityContext implements SecurityContext {
private final String username;
protected InternalSecurityContext( String username ) {
this.username = username;
}
@Override
public boolean isAnonymous() {
return false;
}
@Override
public String getUserName() {
return username;
}
@Override
public boolean hasRole( String roleName ) {
return true;
}
@Override
public void logout() {
// do nothing
}
}
/**
* Determine the initial delay before the garbage collection process(es) should be run, based upon the supplied initial
* expression. Note that the initial expression specifies the hours and minutes in local time, whereas this method should
* return the delay in milliseconds after the current time.
*
* @param initialTimeExpression the expression of the form "<code>hh:mm</code>"; never null
* @return the number of milliseconds after now that the process(es) should be started
*/
protected long determineInitialDelay( String initialTimeExpression ) {
Matcher matcher = RepositoryConfiguration.INITIAL_TIME_PATTERN.matcher(initialTimeExpression);
if (matcher.matches()) {
int hours = Integer.valueOf(matcher.group(1));
int mins = Integer.valueOf(matcher.group(2));
LocalDateTime dateTime = LocalDateTime.of(LocalDate.now(ZoneOffset.UTC), LocalTime.of(hours, mins));
long delay = dateTime.toInstant(ZoneOffset.UTC).toEpochMilli() - System.currentTimeMillis();
if (delay <= 0L) {
delay = dateTime.plusDays(1).toInstant(ZoneOffset.UTC).toEpochMilli() - System.currentTimeMillis();
}
if (delay < 10000L) delay += 10000L; // at least 10 second delay to let repository finish starting ...
assert delay >= 0;
return delay;
}
String msg = JcrI18n.invalidGarbageCollectionInitialTime.text(repositoryName(), initialTimeExpression);
throw new IllegalArgumentException(msg);
}
/**
* The garbage collection tasks should get cancelled before the repository is shut down, but just in case we'll use a weak
* reference to hold onto the JcrRepository instance and we'll also check that the repository is running before we actually do
* any work.
*/
protected static abstract class BackgroundRepositoryTask implements Runnable {
private WeakReference<JcrRepository> repositoryRef;
protected BackgroundRepositoryTask( JcrRepository repository ) {
assert repository != null;
this.repositoryRef = new WeakReference<JcrRepository>(repository);
}
@Override
public final void run() {
JcrRepository repository = repositoryRef.get();
if (repository != null && repository.getState() == State.RUNNING) {
doRun(repository);
}
}
/**
* Perform the garbage collection task.
*
* @param repository the non-null and {@link State#RUNNING running} repository instance
*/
protected abstract void doRun( JcrRepository repository );
}
protected static class BinaryValueGarbageCollectionTask extends BackgroundRepositoryTask {
protected BinaryValueGarbageCollectionTask( JcrRepository repository ) {
super(repository);
}
@Override
protected void doRun( JcrRepository repository ) {
repository.runningState().cleanUpBinaryValues();
}
}
protected static class LockGarbageCollectionTask extends BackgroundRepositoryTask {
protected LockGarbageCollectionTask( JcrRepository repository ) {
super(repository);
}
@Override
protected void doRun( JcrRepository repository ) {
repository.runningState().cleanUpLocks();
}
}
protected static class OptimizationTask extends BackgroundRepositoryTask {
private final int targetCount;
private final int tolerance;
protected OptimizationTask( JcrRepository repository,
int targetCount,
int tolerance ) {
super(repository);
this.targetCount = targetCount;
this.tolerance = tolerance;
}
@Override
protected void doRun( JcrRepository repository ) {
repository.runningState().repositoryCache().optimizeChildren(targetCount, tolerance);
}
}
protected static class JournalingGCTask extends BackgroundRepositoryTask {
protected JournalingGCTask( JcrRepository repository ) {
super(repository);
}
@Override
protected void doRun( JcrRepository repository ) {
ChangeJournal journal = repository.runningState().journal();
assert journal != null;
journal.removeOldRecords();
}
}
}
|
okulikov/modeshape
|
modeshape-jcr/src/main/java/org/modeshape/jcr/JcrRepository.java
|
Java
|
apache-2.0
| 94,630 |
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');
} catch (e) {}
|
zhiyicx/thinksns-plus
|
resources/js/bootstrap.js
|
JavaScript
|
apache-2.0
| 331 |
/*
* Copyright (c) 2011-2013, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.factory.geo;
/**
* Used to specify the type of error function used when optimizing multiview geometric functions
*
* @author Peter Abeles
*/
public enum EpipolarError {
/**
* Simple to compute error function. Has a minimum at the global solution, but cost is not the
* same as the"optimal" error
*/
SIMPLE,
/**
* Second order approximation of the "best" error function. Often a good trade between
* accuracy and efficiency.
*/
SAMPSON,
}
|
pacozaa/BoofCV
|
main/geo/src/boofcv/factory/geo/EpipolarError.java
|
Java
|
apache-2.0
| 1,158 |
// Copyright 2017 The Bazel 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 com.google.devtools.build.lib.analysis.test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.devtools.build.lib.analysis.OptionsDiffPredicate;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.CoreOptionConverters.LabelConverter;
import com.google.devtools.build.lib.analysis.config.Fragment;
import com.google.devtools.build.lib.analysis.config.FragmentOptions;
import com.google.devtools.build.lib.analysis.config.PerLabelOptions;
import com.google.devtools.build.lib.analysis.config.RequiresOptions;
import com.google.devtools.build.lib.analysis.test.TestShardingStrategy.ShardingStrategyConverter;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.TestTimeout;
import com.google.devtools.build.lib.util.RegexFilter;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionDefinition;
import com.google.devtools.common.options.OptionDocumentationCategory;
import com.google.devtools.common.options.OptionEffectTag;
import com.google.devtools.common.options.OptionMetadataTag;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsParsingException;
import com.google.devtools.common.options.TriState;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/** Test-related options. */
@RequiresOptions(options = {TestConfiguration.TestOptions.class})
public class TestConfiguration extends Fragment {
public static final OptionsDiffPredicate SHOULD_INVALIDATE_FOR_OPTION_DIFF =
(options, changedOption, oldValue, newValue) -> {
if (TestOptions.ALWAYS_INVALIDATE_WHEN_CHANGED.contains(changedOption)) {
// changes in --trim_test_configuration itself or related flags always prompt invalidation
return true;
}
if (!changedOption.getField().getDeclaringClass().equals(TestOptions.class)) {
// options outside of TestOptions always prompt invalidation
return true;
}
// other options in TestOptions require invalidation when --trim_test_configuration is off
return !options.get(TestOptions.class).trimTestConfiguration;
};
/** Command-line options. */
public static class TestOptions extends FragmentOptions {
private static final ImmutableSet<OptionDefinition> ALWAYS_INVALIDATE_WHEN_CHANGED =
ImmutableSet.of(
OptionsParser.getOptionDefinitionByName(TestOptions.class, "trim_test_configuration"),
OptionsParser.getOptionDefinitionByName(
TestOptions.class, "experimental_retain_test_configuration_across_testonly"));
@Option(
name = "test_timeout",
defaultValue = "-1",
converter = TestTimeout.TestTimeoutConverter.class,
documentationCategory = OptionDocumentationCategory.TESTING,
effectTags = {OptionEffectTag.UNKNOWN},
help =
"Override the default test timeout values for test timeouts (in secs). If a single "
+ "positive integer value is specified it will override all categories. If 4 "
+ "comma-separated integers are specified, they will override the timeouts for "
+ "short, moderate, long and eternal (in that order). In either form, a value of "
+ "-1 tells blaze to use its default timeouts for that category.")
public Map<TestTimeout, Duration> testTimeout;
@Option(
name = "test_filter",
allowMultiple = false,
defaultValue = "null",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
help =
"Specifies a filter to forward to the test framework. Used to limit "
+ "the tests run. Note that this does not affect which targets are built."
)
public String testFilter;
@Option(
name = "test_runner_fail_fast",
defaultValue = "false",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
help =
"Forwards fail fast option to the test runner. The test runner should stop execution"
+ " upon first failure.")
public boolean testRunnerFailFast;
@Option(
name = "cache_test_results",
defaultValue = "auto",
abbrev = 't', // it's useful to toggle this on/off quickly
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
help =
"If set to 'auto', Bazel reruns a test if and only if: "
+ "(1) Bazel detects changes in the test or its dependencies, "
+ "(2) the test is marked as external, "
+ "(3) multiple test runs were requested with --runs_per_test, or"
+ "(4) the test previously failed. "
+ "If set to 'yes', Bazel caches all test results except for tests marked as "
+ "external. If set to 'no', Bazel does not cache any test results."
)
public TriState cacheTestResults;
@Deprecated
@Option(
name = "test_result_expiration",
defaultValue = "-1", // No expiration by default.
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
help = "This option is deprecated and has no effect.")
public int testResultExpiration;
@Option(
name = "trim_test_configuration",
defaultValue = "true",
documentationCategory = OptionDocumentationCategory.BUILD_TIME_OPTIMIZATION,
effectTags = {
OptionEffectTag.LOADING_AND_ANALYSIS,
OptionEffectTag.LOSES_INCREMENTAL_STATE,
},
help =
"When enabled, test-related options will be cleared below the top level of the build."
+ " When this flag is active, tests cannot be built as dependencies of non-test"
+ " rules, but changes to test-related options will not cause non-test rules to be"
+ " re-analyzed.")
public boolean trimTestConfiguration;
@Option(
name = "experimental_retain_test_configuration_across_testonly",
defaultValue = "false",
documentationCategory = OptionDocumentationCategory.BUILD_TIME_OPTIMIZATION,
effectTags = {
OptionEffectTag.LOADING_AND_ANALYSIS,
OptionEffectTag.LOSES_INCREMENTAL_STATE,
},
help =
"When enabled, --trim_test_configuration will not trim the test configuration for rules"
+ " marked testonly=1. This is meant to reduce action conflict issues when non-test"
+ " rules depend on cc_test rules. No effect if --trim_test_configuration is"
+ " false.")
public boolean experimentalRetainTestConfigurationAcrossTestonly;
@Option(
name = "test_arg",
allowMultiple = true,
defaultValue = "null",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
help =
"Specifies additional options and arguments that should be passed to the test "
+ "executable. Can be used multiple times to specify several arguments. "
+ "If multiple tests are executed, each of them will receive identical arguments. "
+ "Used only by the 'bazel test' command.")
public List<String> testArguments;
@Option(
name = "test_sharding_strategy",
defaultValue = "explicit",
converter = ShardingStrategyConverter.class,
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
help =
"Specify strategy for test sharding: "
+ "'explicit' to only use sharding if the 'shard_count' BUILD attribute is "
+ "present. 'disabled' to never use test sharding.")
public TestShardingStrategy testShardingStrategy;
@Option(
name = "experimental_persistent_test_runner",
defaultValue = "false",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
help =
"Allows running java_test targets locally within a persistent worker. "
+ "To enable the persistent test runner one must run bazel test with the flags:"
+ "--test_strategy=local --strategy=TestRunner=worker "
+ " --experimental_persistent_test_runner")
public boolean persistentTestRunner;
@Option(
name = "runs_per_test",
allowMultiple = true,
defaultValue = "1",
converter = RunsPerTestConverter.class,
documentationCategory = OptionDocumentationCategory.TESTING,
effectTags = {OptionEffectTag.UNKNOWN},
help =
"Specifies number of times to run each test. If any of those attempts fail for any"
+ " reason, the whole test is considered failed. Normally the value specified is"
+ " just an integer. Example: --runs_per_test=3 will run all tests 3 times."
+ " Alternate syntax: regex_filter@runs_per_test. Where runs_per_test stands for"
+ " an integer value and regex_filter stands for a list of include and exclude"
+ " regular expression patterns (Also see --instrumentation_filter). Example:"
+ " --runs_per_test=//foo/.*,-//foo/bar/.*@3 runs all tests in //foo/ except those"
+ " under foo/bar three times. This option can be passed multiple times. The most"
+ " recently passed argument that matches takes precedence. If nothing matches,"
+ " the test is only run once.")
public List<PerLabelOptions> runsPerTest;
@Option(
name = "runs_per_test_detects_flakes",
defaultValue = "false",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
help =
"If true, any shard in which at least one run/attempt passes and at least one "
+ "run/attempt fails gets a FLAKY status.")
public boolean runsPerTestDetectsFlakes;
@Option(
name = "experimental_cancel_concurrent_tests",
defaultValue = "false",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.LOADING_AND_ANALYSIS},
help =
"If true, then Blaze will cancel concurrently running tests on the first successful "
+ "run. This is only useful in combination with --runs_per_test_detects_flakes.")
public boolean cancelConcurrentTests;
@Option(
name = "coverage_support",
converter = LabelConverter.class,
defaultValue = "@bazel_tools//tools/test:coverage_support",
documentationCategory = OptionDocumentationCategory.TOOLCHAIN,
effectTags = {
OptionEffectTag.CHANGES_INPUTS,
OptionEffectTag.AFFECTS_OUTPUTS,
OptionEffectTag.LOADING_AND_ANALYSIS
},
help =
"Location of support files that are required on the inputs of every test action "
+ "that collects code coverage. Defaults to '//tools/test:coverage_support'."
)
public Label coverageSupport;
@Option(
name = "coverage_report_generator",
converter = LabelConverter.class,
defaultValue = "@bazel_tools//tools/test:coverage_report_generator",
documentationCategory = OptionDocumentationCategory.TOOLCHAIN,
effectTags = {
OptionEffectTag.CHANGES_INPUTS,
OptionEffectTag.AFFECTS_OUTPUTS,
OptionEffectTag.LOADING_AND_ANALYSIS
},
help =
"Location of the binary that is used to generate coverage reports. This must "
+ "currently be a filegroup that contains a single file, the binary. Defaults to "
+ "'//tools/test:coverage_report_generator'."
)
public Label coverageReportGenerator;
@Option(
name = "experimental_fetch_all_coverage_outputs",
defaultValue = "false",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.LOADING_AND_ANALYSIS},
help =
"If true, then Bazel fetches the entire coverage data directory for each test during a "
+ "coverage run.")
public boolean fetchAllCoverageOutputs;
@Option(
name = "incompatible_exclusive_test_sandboxed",
defaultValue = "false",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
metadataTags = {
OptionMetadataTag.INCOMPATIBLE_CHANGE,
OptionMetadataTag.TRIGGERED_BY_ALL_INCOMPATIBLE_CHANGES
},
help =
"If true, exclusive tests will run with sandboxed strategy. Add 'local' tag to force "
+ "an exclusive test run locally")
public boolean incompatibleExclusiveTestSandboxed;
@Option(
name = "experimental_split_coverage_postprocessing",
defaultValue = "false",
documentationCategory = OptionDocumentationCategory.EXECUTION_STRATEGY,
effectTags = {OptionEffectTag.EXECUTION},
help = "If true, then Bazel will run coverage postprocessing for test in a new spawn.")
public boolean splitCoveragePostProcessing;
@Override
public FragmentOptions getHost() {
TestOptions hostOptions = (TestOptions) getDefault();
// These fields are used in late-bound attributes, which must not be null in the host
// configuration.
hostOptions.coverageSupport = this.coverageSupport;
hostOptions.coverageReportGenerator = this.coverageReportGenerator;
// trimTestConfiguration is a global analysis option and should be platform-agnostic
hostOptions.trimTestConfiguration = this.trimTestConfiguration;
hostOptions.experimentalRetainTestConfigurationAcrossTestonly =
this.experimentalRetainTestConfigurationAcrossTestonly;
return hostOptions;
}
}
private final TestOptions options;
private final ImmutableMap<TestTimeout, Duration> testTimeout;
private final boolean shouldInclude;
public TestConfiguration(BuildOptions buildOptions) {
this.shouldInclude = buildOptions.contains(TestOptions.class);
if (shouldInclude) {
TestOptions options = buildOptions.get(TestOptions.class);
this.options = options;
this.testTimeout = ImmutableMap.copyOf(options.testTimeout);
} else {
this.options = null;
this.testTimeout = null;
}
}
@Override
public boolean shouldInclude() {
return shouldInclude;
}
/** Returns test timeout mapping as set by --test_timeout options. */
public ImmutableMap<TestTimeout, Duration> getTestTimeout() {
return testTimeout;
}
public String getTestFilter() {
return options.testFilter;
}
public boolean getTestRunnerFailFast() {
return options.testRunnerFailFast;
}
public TriState cacheTestResults() {
return options.cacheTestResults;
}
public List<String> getTestArguments() {
return options.testArguments;
}
public TestShardingStrategy testShardingStrategy() {
return options.testShardingStrategy;
}
/**
* Whether the persistent test runner is enabled. Note that not all test rules support this
* feature, in which case Bazel should fall back to the normal test runner. Therefore, this method
* must only be called by test rules, and never for test actions. For actions, use {@code
* TestTargetProperties.isPersistentTestRunner} instead.
*/
public boolean isPersistentTestRunner() {
return options.persistentTestRunner;
}
public Label getCoverageSupport(){
return options.coverageSupport;
}
public Label getCoverageReportGenerator(){
return options.coverageReportGenerator;
}
/**
* @return number of times the given test should run. If the test doesn't match any of the
* filters, runs it once.
*/
public int getRunsPerTestForLabel(Label label) {
for (PerLabelOptions perLabelRuns : Lists.reverse(options.runsPerTest)) {
if (perLabelRuns.isIncluded(label)) {
return Integer.parseInt(Iterables.getOnlyElement(perLabelRuns.getOptions()));
}
}
return 1;
}
public boolean runsPerTestDetectsFlakes() {
return options.runsPerTestDetectsFlakes;
}
public boolean cancelConcurrentTests() {
return options.cancelConcurrentTests;
}
public boolean fetchAllCoverageOutputs() {
return options.fetchAllCoverageOutputs;
}
public boolean incompatibleExclusiveTestSandboxed() {
return options.incompatibleExclusiveTestSandboxed;
}
public boolean splitCoveragePostProcessing() {
return options.splitCoveragePostProcessing;
}
/**
* Option converter that han handle two styles of value for "--runs_per_test":
*
* <ul>
* <li>--runs_per_test=NUMBER: Run each test NUMBER times.
* <li>--runs_per_test=test_regex@NUMBER: Run each test that matches test_regex NUMBER times.
* This form can be repeated with multiple regexes.
* </ul>
*/
public static class RunsPerTestConverter extends PerLabelOptions.PerLabelOptionsConverter {
@Override
public PerLabelOptions convert(String input) throws OptionsParsingException {
try {
return parseAsInteger(input);
} catch (NumberFormatException ignored) {
return parseAsRegex(input);
}
}
private PerLabelOptions parseAsInteger(String input)
throws NumberFormatException, OptionsParsingException {
int numericValue = Integer.parseInt(input);
if (numericValue <= 0) {
throw new OptionsParsingException("'" + input + "' should be >= 1");
} else {
RegexFilter catchAll =
new RegexFilter(Collections.singletonList(".*"), Collections.<String>emptyList());
return new PerLabelOptions(catchAll, Collections.singletonList(input));
}
}
private PerLabelOptions parseAsRegex(String input) throws OptionsParsingException {
PerLabelOptions testRegexps = super.convert(input);
if (testRegexps.getOptions().size() != 1) {
throw new OptionsParsingException("'" + input + "' has multiple runs for a single pattern");
}
String runsPerTest = Iterables.getOnlyElement(testRegexps.getOptions());
try {
int numericRunsPerTest = Integer.parseInt(runsPerTest);
if (numericRunsPerTest <= 0) {
throw new OptionsParsingException("'" + input + "' has a value < 1");
}
} catch (NumberFormatException e) {
throw new OptionsParsingException("'" + input + "' has a non-numeric value", e);
}
return testRegexps;
}
@Override
public String getTypeDescription() {
return "a positive integer or test_regex@runs. This flag may be passed more than once";
}
}
}
|
meteorcloudy/bazel
|
src/main/java/com/google/devtools/build/lib/analysis/test/TestConfiguration.java
|
Java
|
apache-2.0
| 20,107 |
require 'serverspec'
set :backend, :exec
## checking successfull puppet run
describe command('grep fail /var/lib/puppet/state/last_run_summary.yaml |grep -v "fail.*:\ 0”') do
its(:exit_status) { should eq 1 }
end
describe package('jdk') do
it { should be_installed.by('rpm').with_version('1.7.0_79-fcs.x86_64') }
end
describe file('/etc/profile.d/java.sh') do
it { should be_file }
its(:content) { should match /export JAVA_HOME=\/usr\/java\/default/ }
it { should be_mode 644 }
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
end
describe command('alternatives --display java') do
its(:stdout) { should contain('link currently points to /usr/java/jdk1.7.0_79/bin/java') }
its(:stdout) { should contain('/usr/java/jdk1.7.0_79/bin/java - priority 200000') }
end
describe file('/usr/java/latest') do
it { should be_symlink }
it { should be_linked_to '/usr/java/jdk1.7.0_79' }
end
|
jevon71-work/vagrant-working
|
kitchenci/test/integration/default/serverspec/java_spec.rb
|
Ruby
|
apache-2.0
| 925 |
package io.github.mandar2812.dynaml.models.neuralnets
import breeze.linalg.{DenseVector, DenseMatrix}
import io.github.mandar2812.dynaml.models.ParameterizedLearner
/**
* Top level trait defining
* the most important properties
* of a neural network
*/
trait NeuralNetwork[G] extends
ParameterizedLearner[G, Int, List[DenseMatrix[Double]],
DenseVector[Double], DenseVector[Double],
(DenseVector[Double], DenseVector[Double])] {
val inputDimensions: Int
val outputDimensions: Int
val hiddenLayers: Int
val activations: List[(Double) => Double]
val neuronCounts: List[Int]
}
|
sisirkoppaka/bayeslearn
|
src/main/scala/io/github/mandar2812/dynaml/models/neuralnets/NeuralNetwork.scala
|
Scala
|
apache-2.0
| 598 |
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"id": "ch.ti8m.documenthandler.DocumentHandler",
"file": "plugins/ch.ti8m.documenthandler/www/DocumentHandler.js",
"pluginId": "ch.ti8m.documenthandler",
"clobbers": [
"handleDocumentWithURL"
]
},
{
"id": "cordova-plugin-camera.Camera",
"file": "plugins/cordova-plugin-camera/www/CameraConstants.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"Camera"
]
},
{
"id": "cordova-plugin-camera.CameraPopoverOptions",
"file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"CameraPopoverOptions"
]
},
{
"id": "cordova-plugin-camera.camera",
"file": "plugins/cordova-plugin-camera/www/Camera.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"navigator.camera"
]
},
{
"id": "cordova-plugin-camera.CameraPopoverHandle",
"file": "plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"CameraPopoverHandle"
]
},
{
"id": "cordova-plugin-customurlscheme.LaunchMyApp",
"file": "plugins/cordova-plugin-customurlscheme/www/ios/LaunchMyApp.js",
"pluginId": "cordova-plugin-customurlscheme",
"clobbers": [
"window.plugins.launchmyapp"
]
},
{
"id": "cordova-plugin-device.device",
"file": "plugins/cordova-plugin-device/www/device.js",
"pluginId": "cordova-plugin-device",
"clobbers": [
"device"
]
},
{
"id": "cordova-plugin-file.DirectoryEntry",
"file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryEntry"
]
},
{
"id": "cordova-plugin-file.DirectoryReader",
"file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryReader"
]
},
{
"id": "cordova-plugin-file.Entry",
"file": "plugins/cordova-plugin-file/www/Entry.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Entry"
]
},
{
"id": "cordova-plugin-file.File",
"file": "plugins/cordova-plugin-file/www/File.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.File"
]
},
{
"id": "cordova-plugin-file.FileEntry",
"file": "plugins/cordova-plugin-file/www/FileEntry.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileEntry"
]
},
{
"id": "cordova-plugin-file.FileError",
"file": "plugins/cordova-plugin-file/www/FileError.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileError"
]
},
{
"id": "cordova-plugin-file.FileReader",
"file": "plugins/cordova-plugin-file/www/FileReader.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileReader"
]
},
{
"id": "cordova-plugin-file.FileSystem",
"file": "plugins/cordova-plugin-file/www/FileSystem.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileSystem"
]
},
{
"id": "cordova-plugin-file.FileUploadOptions",
"file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadOptions"
]
},
{
"id": "cordova-plugin-file.FileUploadResult",
"file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadResult"
]
},
{
"id": "cordova-plugin-file.FileWriter",
"file": "plugins/cordova-plugin-file/www/FileWriter.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileWriter"
]
},
{
"id": "cordova-plugin-file.Flags",
"file": "plugins/cordova-plugin-file/www/Flags.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Flags"
]
},
{
"id": "cordova-plugin-file.LocalFileSystem",
"file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.LocalFileSystem"
],
"merges": [
"window"
]
},
{
"id": "cordova-plugin-file.Metadata",
"file": "plugins/cordova-plugin-file/www/Metadata.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Metadata"
]
},
{
"id": "cordova-plugin-file.ProgressEvent",
"file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.ProgressEvent"
]
},
{
"id": "cordova-plugin-file.fileSystems",
"file": "plugins/cordova-plugin-file/www/fileSystems.js",
"pluginId": "cordova-plugin-file"
},
{
"id": "cordova-plugin-file.requestFileSystem",
"file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.requestFileSystem"
]
},
{
"id": "cordova-plugin-file.resolveLocalFileSystemURI",
"file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
"pluginId": "cordova-plugin-file",
"merges": [
"window"
]
},
{
"id": "cordova-plugin-file.isChrome",
"file": "plugins/cordova-plugin-file/www/browser/isChrome.js",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"id": "cordova-plugin-file.iosFileSystem",
"file": "plugins/cordova-plugin-file/www/ios/FileSystem.js",
"pluginId": "cordova-plugin-file",
"merges": [
"FileSystem"
]
},
{
"id": "cordova-plugin-file.fileSystems-roots",
"file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"id": "cordova-plugin-file.fileSystemPaths",
"file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
"pluginId": "cordova-plugin-file",
"merges": [
"cordova"
],
"runs": true
},
{
"id": "cordova-plugin-file-transfer.FileTransferError",
"file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js",
"pluginId": "cordova-plugin-file-transfer",
"clobbers": [
"window.FileTransferError"
]
},
{
"id": "cordova-plugin-file-transfer.FileTransfer",
"file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js",
"pluginId": "cordova-plugin-file-transfer",
"clobbers": [
"window.FileTransfer"
]
},
{
"id": "cordova-plugin-globalization.GlobalizationError",
"file": "plugins/cordova-plugin-globalization/www/GlobalizationError.js",
"pluginId": "cordova-plugin-globalization",
"clobbers": [
"window.GlobalizationError"
]
},
{
"id": "cordova-plugin-globalization.globalization",
"file": "plugins/cordova-plugin-globalization/www/globalization.js",
"pluginId": "cordova-plugin-globalization",
"clobbers": [
"navigator.globalization"
]
},
{
"id": "cordova-plugin-inappbrowser.inappbrowser",
"file": "plugins/cordova-plugin-inappbrowser/www/inappbrowser.js",
"pluginId": "cordova-plugin-inappbrowser",
"clobbers": [
"cordova.InAppBrowser.open",
"window.open"
]
},
{
"id": "cordova-plugin-local-notifications-mm.LocalNotification",
"file": "plugins/cordova-plugin-local-notifications-mm/www/local-notification.js",
"pluginId": "cordova-plugin-local-notifications-mm",
"clobbers": [
"cordova.plugins.notification.local",
"plugin.notification.local"
]
},
{
"id": "cordova-plugin-local-notifications-mm.LocalNotification.Core",
"file": "plugins/cordova-plugin-local-notifications-mm/www/local-notification-core.js",
"pluginId": "cordova-plugin-local-notifications-mm",
"clobbers": [
"cordova.plugins.notification.local.core",
"plugin.notification.local.core"
]
},
{
"id": "cordova-plugin-local-notifications-mm.LocalNotification.Util",
"file": "plugins/cordova-plugin-local-notifications-mm/www/local-notification-util.js",
"pluginId": "cordova-plugin-local-notifications-mm",
"merges": [
"cordova.plugins.notification.local.core",
"plugin.notification.local.core"
]
},
{
"id": "cordova-plugin-media-capture.CaptureAudioOptions",
"file": "plugins/cordova-plugin-media-capture/www/CaptureAudioOptions.js",
"pluginId": "cordova-plugin-media-capture",
"clobbers": [
"CaptureAudioOptions"
]
},
{
"id": "cordova-plugin-media-capture.CaptureImageOptions",
"file": "plugins/cordova-plugin-media-capture/www/CaptureImageOptions.js",
"pluginId": "cordova-plugin-media-capture",
"clobbers": [
"CaptureImageOptions"
]
},
{
"id": "cordova-plugin-media-capture.CaptureVideoOptions",
"file": "plugins/cordova-plugin-media-capture/www/CaptureVideoOptions.js",
"pluginId": "cordova-plugin-media-capture",
"clobbers": [
"CaptureVideoOptions"
]
},
{
"id": "cordova-plugin-media-capture.CaptureError",
"file": "plugins/cordova-plugin-media-capture/www/CaptureError.js",
"pluginId": "cordova-plugin-media-capture",
"clobbers": [
"CaptureError"
]
},
{
"id": "cordova-plugin-media-capture.MediaFileData",
"file": "plugins/cordova-plugin-media-capture/www/MediaFileData.js",
"pluginId": "cordova-plugin-media-capture",
"clobbers": [
"MediaFileData"
]
},
{
"id": "cordova-plugin-media-capture.MediaFile",
"file": "plugins/cordova-plugin-media-capture/www/MediaFile.js",
"pluginId": "cordova-plugin-media-capture",
"clobbers": [
"MediaFile"
]
},
{
"id": "cordova-plugin-media-capture.helpers",
"file": "plugins/cordova-plugin-media-capture/www/helpers.js",
"pluginId": "cordova-plugin-media-capture",
"runs": true
},
{
"id": "cordova-plugin-media-capture.capture",
"file": "plugins/cordova-plugin-media-capture/www/capture.js",
"pluginId": "cordova-plugin-media-capture",
"clobbers": [
"navigator.device.capture"
]
},
{
"id": "cordova-plugin-network-information.network",
"file": "plugins/cordova-plugin-network-information/www/network.js",
"pluginId": "cordova-plugin-network-information",
"clobbers": [
"navigator.connection",
"navigator.network.connection"
]
},
{
"id": "cordova-plugin-network-information.Connection",
"file": "plugins/cordova-plugin-network-information/www/Connection.js",
"pluginId": "cordova-plugin-network-information",
"clobbers": [
"Connection"
]
},
{
"id": "cordova-plugin-splashscreen.SplashScreen",
"file": "plugins/cordova-plugin-splashscreen/www/splashscreen.js",
"pluginId": "cordova-plugin-splashscreen",
"clobbers": [
"navigator.splashscreen"
]
},
{
"id": "cordova-plugin-statusbar.statusbar",
"file": "plugins/cordova-plugin-statusbar/www/statusbar.js",
"pluginId": "cordova-plugin-statusbar",
"clobbers": [
"window.StatusBar"
]
},
{
"id": "cordova-plugin-zip.Zip",
"file": "plugins/cordova-plugin-zip/zip.js",
"pluginId": "cordova-plugin-zip",
"clobbers": [
"zip"
]
},
{
"id": "cordova-universal-clipboard.Clipboard",
"file": "plugins/cordova-universal-clipboard/www/clipboard.js",
"pluginId": "cordova-universal-clipboard",
"clobbers": [
"cordova.plugins.clipboard"
]
},
{
"id": "ionic-plugin-keyboard.keyboard",
"file": "plugins/ionic-plugin-keyboard/www/ios/keyboard.js",
"pluginId": "ionic-plugin-keyboard",
"clobbers": [
"cordova.plugins.Keyboard"
],
"runs": true
},
{
"id": "net.tunts.webintent.WebIntent",
"file": "plugins/net.tunts.webintent/www/webintent.js",
"pluginId": "net.tunts.webintent",
"clobbers": [
"WebIntent"
]
},
{
"id": "phonegap-plugin-push.PushNotification",
"file": "plugins/phonegap-plugin-push/www/push.js",
"pluginId": "phonegap-plugin-push",
"clobbers": [
"PushNotification"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"ch.ti8m.documenthandler": "0.2.2",
"cordova-plugin-app-event": "1.2.0",
"cordova-plugin-compat": "1.1.0",
"cordova-plugin-camera": "2.3.1",
"cordova-plugin-customurlscheme": "4.2.0",
"cordova-plugin-device": "1.1.4",
"cordova-plugin-file": "4.3.1",
"cordova-plugin-file-transfer": "1.6.1",
"cordova-plugin-globalization": "1.0.5",
"cordova-plugin-inappbrowser": "1.6.1",
"cordova-plugin-local-notifications-mm": "1.0.5",
"cordova-plugin-media-capture": "1.4.1",
"cordova-plugin-network-information": "1.3.1",
"cordova-plugin-splashscreen": "4.0.1",
"cordova-plugin-statusbar": "2.2.1",
"cordova-plugin-whitelist": "1.3.1",
"cordova-plugin-zip": "3.1.0",
"cordova-universal-clipboard": "0.1.0",
"ionic-plugin-keyboard": "2.2.1",
"net.tunts.webintent": "0.2.1",
"nl.kingsquare.cordova.background-audio": "1.0.1",
"phonegap-plugin-push": "1.8.4"
};
// BOTTOM OF METADATA
});
|
cmtedreyer/icaoExperience
|
platforms/ios/www/cordova_plugins.js
|
JavaScript
|
apache-2.0
| 14,869 |
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef __itkNormalVariateGenerator_h
#define __itkNormalVariateGenerator_h
#include "itkObjectFactory.h"
#include "itkRandomVariateGeneratorBase.h"
namespace itk
{
namespace Statistics
{
/** \class NormalVariateGenerator
* \brief Normal random variate generator
*
* This generation method was initially developed and implemented by
* Martin Styner, University of North Carolina at Chapel Hill,
* and his colleagues.
*
* You should run Initialize() function before call GetNormalVariate()
* function.
*
* The followings are original comments.
*
* Revision date 31 May 1996
* This is a revised version of the algorithm decribed in
*
* ACM Transactions on Mathematical Software, Vol 22, No 1
* March 1996, pp 119-127.
*
* It is somewhat faster, and uses less memory as the vector of variates is
* updated in-situ. It has passed all the same statistical tests as decribed
* in the TOMS article, plus others. Seems OK so far.
*
* Works well with total pool of 1024 variates, and does not need
* two vectors of this size, so does less damage to cache.
* Has been tested for frequency of tail values which
* should occur once in a million. OK. Other usual tests OK.
* About 13 % faster than TOMS version.
*
* FAST GENERATOR OF PSEUDO-RANDOM UNIT NORMAL VARIATES
*
* C.S.Wallace, Monash University, 1994
*
* To use this code, files needing to call the generator should include:
* \code
* #include "FastNorm.h"
* \endcode
* and be linked with the maths library (-lm)
* FastNorm.h contains declaration of the initialization routine
* 'initnorm()', definition of a macro 'FastGauss' used to generate variates,
* and three variables used in the macro.
* Read below for calling conventions.
*
* THIS CODE ASSUMES TWO'S-COMPLEMENT 32-BIT INTEGER ARITHMATIC. IT ALSO
* ASSUMES THE 'C' COMPILER COMPILES THE LEFT-SHIFT OPERATOR "<<" AS A LOGICAL
* SHIFT, DISCARDING THE SIGN DIGIT AND SHIFTING IN ZEROS ON THE RIGHT, SO
* " X << 1" IS EQUIVALENT TO " X+X ". IT ALSO ASSUMES THE RIGHT-SHIFT
* OPERATOR ">>" IS SIGN-PRESERVING, SO ( -2 >> 1) = -1, ( -1>>1) = -1.
*
*
*
* A fast generator of pseudo-random variates from the unit Normal
* distribution. It keeps a pool of about 1000 variates, and generates new
* ones by picking 4 from the pool, rotating the 4-vector with these as its
* components, and replacing the old variates with the components of the
* rotated vector.
*
*
* The program should initialize the generator by calling
* initnorm(seed)
* with seed a int integer seed value. Different seed values will give
* different sequences of Normals.
* Then, wherever the program needs a new Normal variate, it should
* use the macro FastGauss, e.g. in statements like:
* x = FastGauss; (Sets x to a random Normal value)
*
*
* \ingroup Statistics
* \ingroup ITKStatistics
*/
class ITK_EXPORT NormalVariateGenerator:
public RandomVariateGeneratorBase
{
public:
/** Standard class typedefs. */
typedef NormalVariateGenerator Self;
typedef RandomVariateGeneratorBase Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
/** Run-time type information (and related methods). */
itkTypeMacro(NormalVariateGenerator,
RandomVariateGeneratorBase);
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** generate random number table */
void Initialize(int randomSeed);
/** get a variate using FastNorm function */
double GetVariate();
protected:
NormalVariateGenerator();
virtual ~NormalVariateGenerator();
virtual void PrintSelf(std::ostream & os, Indent indent) const;
/** get a variate */
double FastNorm(void);
private:
double m_Scale;
double m_Rscale;
double m_Rcons;
int m_ELEN;
int m_LEN;
int m_LMASK;
int m_TLEN;
int m_Gaussfaze;
int *m_Gausssave;
double m_GScale;
int * m_Vec1;
int m_Nslew;
int m_Irs;
int m_Lseed;
double m_Chic1;
double m_Chic2;
double m_ActualRSD;
}; // end of class
} // end of namespace Statistics
} // end of namespace itk
#endif
|
CapeDrew/DCMTK-ITK
|
Modules/Numerics/Statistics/include/itkNormalVariateGenerator.h
|
C
|
apache-2.0
| 5,017 |
<!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_40) on Thu Apr 16 20:30:00 CDT 2015 -->
<title>DeleteListener (Java Class Library API)</title>
<meta name="date" content="2015-04-16">
<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="DeleteListener (Java Class Library API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/DeleteListener.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/jsimpledb/core/DeletedObjectException.html" title="class in org.jsimpledb.core"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../org/jsimpledb/core/EnumField.html" title="class in org.jsimpledb.core"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/jsimpledb/core/DeleteListener.html" target="_top">Frames</a></li>
<li><a href="DeleteListener.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>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </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.jsimpledb.core</div>
<h2 title="Interface DeleteListener" class="title">Interface DeleteListener</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public interface <a href="../../../src-html/org/jsimpledb/core/DeleteListener.html#line.15">DeleteListener</a></pre>
<div class="block">Listener interface for notifications that an object is about to be deleted.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../org/jsimpledb/core/Transaction.html#addDeleteListener-org.jsimpledb.core.DeleteListener-"><code>Transaction.addDeleteListener()</code></a></dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../org/jsimpledb/core/DeleteListener.html#onDelete-org.jsimpledb.core.Transaction-org.jsimpledb.core.ObjId-">onDelete</a></span>(<a href="../../../org/jsimpledb/core/Transaction.html" title="class in org.jsimpledb.core">Transaction</a> tx,
<a href="../../../org/jsimpledb/core/ObjId.html" title="class in org.jsimpledb.core">ObjId</a> id)</code>
<div class="block">Receive notification of an object being deleted.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="onDelete-org.jsimpledb.core.Transaction-org.jsimpledb.core.ObjId-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>onDelete</h4>
<pre>void <a href="../../../src-html/org/jsimpledb/core/DeleteListener.html#line.29">onDelete</a>(<a href="../../../org/jsimpledb/core/Transaction.html" title="class in org.jsimpledb.core">Transaction</a> tx,
<a href="../../../org/jsimpledb/core/ObjId.html" title="class in org.jsimpledb.core">ObjId</a> id)</pre>
<div class="block">Receive notification of an object being deleted.
<p>
Notifications are delivered in the same thread that is deleting object, before the delete actually occurs.
At most one notification will be delivered for any object, even if <a href="../../../org/jsimpledb/core/Transaction.html#delete-org.jsimpledb.core.ObjId-"><code>Transaction.delete()</code></a>
is invoked reentrantly from within this listener.
</p></div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>tx</code> - associated transaction</dd>
<dd><code>id</code> - the ID of the object about to be deleted</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>
<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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/DeleteListener.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/jsimpledb/core/DeletedObjectException.html" title="class in org.jsimpledb.core"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../org/jsimpledb/core/EnumField.html" title="class in org.jsimpledb.core"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/jsimpledb/core/DeleteListener.html" target="_top">Frames</a></li>
<li><a href="DeleteListener.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>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
mmayorivera/jsimpledb
|
publish/reports/javadoc/org/jsimpledb/core/DeleteListener.html
|
HTML
|
apache-2.0
| 9,107 |
package v1beta1
import (
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
)
func init() {
api.Scheme.AddKnownTypes("v1beta1",
&AccessToken{},
&AccessTokenList{},
&AuthorizeToken{},
&AuthorizeTokenList{},
&Client{},
&ClientList{},
&ClientAuthorization{},
&ClientAuthorizationList{},
)
}
func (*AccessToken) IsAnAPIObject() {}
func (*AuthorizeToken) IsAnAPIObject() {}
func (*Client) IsAnAPIObject() {}
func (*AccessTokenList) IsAnAPIObject() {}
func (*AuthorizeTokenList) IsAnAPIObject() {}
func (*ClientList) IsAnAPIObject() {}
func (*ClientAuthorization) IsAnAPIObject() {}
func (*ClientAuthorizationList) IsAnAPIObject() {}
|
mrunalp/origin
|
pkg/oauth/api/v1beta1/register.go
|
GO
|
apache-2.0
| 719 |
/**
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br>
* This file is part of FI-WARE project.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License.
* </p>
* <p>
* You may obtain a copy of the License at:<br>
* <br>
* http://www.apache.org/licenses/LICENSE-2.0
* </p>
* <p>
* 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.
* </p>
* <p>
* See the License for the specific language governing permissions and limitations under the License.
* </p>
* <p>
* For those usages not covered by the Apache version 2.0 License please contact with [email protected]
* </p>
*/
package com.telefonica.euro_iaas.sdc.dao;
import javax.ws.rs.client.Client;
public interface ChefClientConfig {
Client getClient();
}
|
Fiware/cloud.SDC
|
core/src/main/java/com/telefonica/euro_iaas/sdc/dao/ChefClientConfig.java
|
Java
|
apache-2.0
| 992 |
# coding:utf-8
'''
Email address validation plugin for Google Apps email addresses.
Notes:
must be between 1-64 characters
must use letters, numbers, dash (-), underscore (_), apostrophes ('), and dots (.)
if one character, must be alphanum, underscore (_) or apostrophes (')
otherwise must start with: alphanum, underscore (_), dash (-), or apostrophes(')
otherwise must end with: alphanum, underscore(_), dash(-), or apostrophes(')
plus (+) is allowed, everything after + is ignored
case is ignored
Grammar:
local-part -> main-part [ tags ]
main-part -> google-prefix google-root google-suffix
tags -> { + [ atom ] }
google-prefix -> alphanum | underscore | dash | apostrophe
google-root -> alphanum | underscore | dash | apostrophe | dots
google-suffix -> alphanum | underscore | dash | apostrophe
Other limitations:
1. All characters prefixing the plus symbol (+) must be between 1-64 characters.
'''
import re
from flanker.addresslib.plugins._tokenizer import TokenStream
from flanker.addresslib._parser.lexer import t_ATOM, _UNICODE_CHAR
ATOM = re.compile(t_ATOM, re.MULTILINE | re.VERBOSE)
GOOGLE_BASE = re.compile(r'''
( [A-Za-z0-9_\-'\.]
| {unicode_char}
)+
'''.format(unicode_char=_UNICODE_CHAR),
re.MULTILINE | re.VERBOSE)
ALPHANUM = re.compile(r'''
( [A-Za-z0-9]
| {unicode_char}
)+
'''.format(unicode_char=_UNICODE_CHAR),
re.MULTILINE | re.VERBOSE)
APOSTROPHE = re.compile(r'''
\'
''',
re.MULTILINE | re.VERBOSE)
UNDERSCORE = re.compile(r'\_', re.MULTILINE | re.VERBOSE)
DASH = re.compile(r'\-', re.MULTILINE | re.VERBOSE)
DOTS = '.'
PLUS = '+'
def validate(email_addr):
# Setup for handling EmailAddress type instead of literal string
localpart = email_addr.mailbox
# check string exists and not empty
if not localpart:
return False
lparts = localpart.split('+')
real_localpart = lparts[0]
# length check
l = len(real_localpart)
if l < 0 or l > 64:
return False
# if only one character, must be alphanum, underscore (_), or apostrophe (')
if len(localpart) == 1 or l == 1:
if ALPHANUM.match(localpart) or UNDERSCORE.match(localpart) or \
APOSTROPHE.match(localpart):
return True
return False
# must start with: alphanum, underscore (_), dash (-), or apostrophe(')
if len(real_localpart) > 0:
if not ALPHANUM.match(real_localpart[0]) and not UNDERSCORE.match(real_localpart[0]) \
and not DASH.match(real_localpart[0]) and not APOSTROPHE.match(real_localpart[0]):
return False
else:
return False
# must end with: alphanum, underscore(_), dash(-), or apostrophe(')
if not ALPHANUM.match(real_localpart[-1]) and not UNDERSCORE.match(real_localpart[-1]) \
and not DASH.match(real_localpart[-1]) and not APOSTROPHE.match(real_localpart[-1]):
return False
# grammar check
return _validate(real_localpart)
def _validate(localpart):
stream = TokenStream(localpart)
# get the google base
mpart = stream.get_token(GOOGLE_BASE)
if mpart is None:
return False
# optional tags
tgs = _tags(stream)
if not stream.end_of_stream():
return False
return True
def _tags(stream):
while True:
# plus sign
pls = stream.get_token(PLUS)
# optional atom
if pls:
stream.get_token(ATOM)
else:
break
return True
|
mailgun/flanker
|
flanker/addresslib/plugins/google.py
|
Python
|
apache-2.0
| 3,978 |
/**
* 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.hadoop.hdfs.server.datanode;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import com.google.common.math.LongMath;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.DF;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdfs.server.datanode.checker.VolumeCheckResult;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetImplTestUtils;
import org.apache.hadoop.util.AutoCloseableLock;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.BlockListAsLongs;
import org.apache.hadoop.hdfs.protocol.BlockLocalPathInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.ReplicaState;
import org.apache.hadoop.hdfs.server.datanode.DirectoryScanner.ReportCompiler;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.DataNodeVolumeMetrics;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsDatasetSpi;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeReference;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeSpi;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeSpi.ScanInfo;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.LengthInputStream;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.ReplicaInputStreams;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.ReplicaOutputStreams;
import org.apache.hadoop.hdfs.server.datanode.metrics.DataNodeMetricHelper;
import org.apache.hadoop.hdfs.server.datanode.metrics.FSDatasetMBean;
import org.apache.hadoop.hdfs.server.protocol.BlockRecoveryCommand.RecoveringBlock;
import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage;
import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
import org.apache.hadoop.hdfs.server.protocol.ReplicaRecoveryInfo;
import org.apache.hadoop.hdfs.server.protocol.StorageReport;
import org.apache.hadoop.hdfs.server.protocol.VolumeFailureSummary;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.metrics2.MetricsCollector;
import org.apache.hadoop.metrics2.util.MBeans;
import org.apache.hadoop.util.DataChecksum;
/**
* This class implements a simulated FSDataset.
*
* Blocks that are created are recorded but their data (plus their CRCs) are
* discarded.
* Fixed data is returned when blocks are read; a null CRC meta file is
* created for such data.
*
* This FSDataset does not remember any block information across its
* restarts; it does however offer an operation to inject blocks
* (See the TestInectionForSImulatedStorage()
* for a usage example of injection.
*
* Note the synchronization is coarse grained - it is at each method.
*/
public class SimulatedFSDataset implements FsDatasetSpi<FsVolumeSpi> {
public final static int BYTE_MASK = 0xff;
private final static int DEFAULT_NUM_SIMULATED_DATA_DIRS = 1;
static class Factory extends FsDatasetSpi.Factory<SimulatedFSDataset> {
@Override
public SimulatedFSDataset newInstance(DataNode datanode,
DataStorage storage, Configuration conf) throws IOException {
return new SimulatedFSDataset(datanode, storage, conf);
}
@Override
public boolean isSimulated() {
return true;
}
}
/**
* Used to change the default number of data storages and to mark the
* FSDataset as simulated.
*/
static class TestUtilsFactory
extends FsDatasetTestUtils.Factory<FsDatasetTestUtils> {
@Override
public FsDatasetTestUtils newInstance(DataNode datanode) {
return new FsDatasetImplTestUtils(datanode) {
@Override
public int getDefaultNumOfDataDirs() {
return DEFAULT_NUM_SIMULATED_DATA_DIRS;
}
};
}
@Override
public boolean isSimulated() {
return true;
}
@Override
public int getDefaultNumOfDataDirs() {
return DEFAULT_NUM_SIMULATED_DATA_DIRS;
}
}
public static void setFactory(Configuration conf) {
conf.set(DFSConfigKeys.DFS_DATANODE_FSDATASET_FACTORY_KEY,
Factory.class.getName());
conf.setClass("org.apache.hadoop.hdfs.server.datanode." +
"SimulatedFSDatasetTestUtilsFactory",
TestUtilsFactory.class, FsDatasetTestUtils.Factory.class
);
}
public static byte simulatedByte(Block b, long offsetInBlk) {
byte firstByte = (byte) (b.getBlockId() & BYTE_MASK);
return (byte) ((firstByte + offsetInBlk % 29) & BYTE_MASK);
}
public static final String CONFIG_PROPERTY_CAPACITY =
"dfs.datanode.simulateddatastorage.capacity";
public static final long DEFAULT_CAPACITY = 2L<<40; // 1 terabyte
public static final String CONFIG_PROPERTY_STATE =
"dfs.datanode.simulateddatastorage.state";
private static final DatanodeStorage.State DEFAULT_STATE =
DatanodeStorage.State.NORMAL;
static final byte[] nullCrcFileData;
private final AutoCloseableLock datasetLock;
private final FileIoProvider fileIoProvider;
static {
DataChecksum checksum = DataChecksum.newDataChecksum(
DataChecksum.Type.NULL, 16*1024 );
byte[] nullCrcHeader = checksum.getHeader();
nullCrcFileData = new byte[2 + nullCrcHeader.length];
nullCrcFileData[0] = (byte) ((BlockMetadataHeader.VERSION >>> 8) & 0xff);
nullCrcFileData[1] = (byte) (BlockMetadataHeader.VERSION & 0xff);
for (int i = 0; i < nullCrcHeader.length; i++) {
nullCrcFileData[i+2] = nullCrcHeader[i];
}
}
// information about a single block
private class BInfo implements ReplicaInPipeline {
final Block theBlock;
private boolean finalized = false; // if not finalized => ongoing creation
SimulatedOutputStream oStream = null;
private long bytesAcked;
private long bytesRcvd;
private boolean pinned = false;
BInfo(String bpid, Block b, boolean forWriting) throws IOException {
theBlock = new Block(b);
if (theBlock.getNumBytes() < 0L) {
theBlock.setNumBytes(0L);
}
if (!getStorage(theBlock).alloc(bpid, theBlock.getNumBytes())) {
// expected length - actual length may
// be more - we find out at finalize
DataNode.LOG.warn("Lack of free storage on a block alloc");
throw new IOException("Creating block, no free space available");
}
if (forWriting) {
finalized = false;
oStream = new SimulatedOutputStream();
} else {
finalized = true;
oStream = null;
}
}
@Override
public String getStorageUuid() {
return getStorage(theBlock).getStorageUuid();
}
@Override
synchronized public long getGenerationStamp() {
return theBlock.getGenerationStamp();
}
@Override
synchronized public long getNumBytes() {
if (!finalized) {
return bytesRcvd;
} else {
return theBlock.getNumBytes();
}
}
@Override
synchronized public void setNumBytes(long length) {
if (!finalized) {
bytesRcvd = length;
} else {
theBlock.setNumBytes(length);
}
}
synchronized SimulatedInputStream getIStream() {
if (!finalized) {
// throw new IOException("Trying to read an unfinalized block");
return new SimulatedInputStream(oStream.getLength(), theBlock);
} else {
return new SimulatedInputStream(theBlock.getNumBytes(), theBlock);
}
}
synchronized void finalizeBlock(String bpid, long finalSize)
throws IOException {
if (finalized) {
throw new IOException(
"Finalizing a block that has already been finalized" +
theBlock.getBlockId());
}
if (oStream == null) {
DataNode.LOG.error("Null oStream on unfinalized block - bug");
throw new IOException("Unexpected error on finalize");
}
if (oStream.getLength() != finalSize) {
DataNode.LOG.warn("Size passed to finalize (" + finalSize +
")does not match what was written:" + oStream.getLength());
throw new IOException(
"Size passed to finalize does not match the amount of data written");
}
// We had allocated the expected length when block was created;
// adjust if necessary
long extraLen = finalSize - theBlock.getNumBytes();
if (extraLen > 0L) {
if (!getStorage(theBlock).alloc(bpid, extraLen)) {
DataNode.LOG.warn("Lack of free storage on a block alloc");
throw new IOException("Creating block, no free space available");
}
} else {
getStorage(theBlock).free(bpid, -extraLen);
}
theBlock.setNumBytes(finalSize);
finalized = true;
oStream = null;
return;
}
synchronized void unfinalizeBlock() throws IOException {
if (!finalized) {
throw new IOException("Unfinalized a block that's not finalized "
+ theBlock);
}
finalized = false;
oStream = new SimulatedOutputStream();
long blockLen = theBlock.getNumBytes();
oStream.setLength(blockLen);
bytesRcvd = blockLen;
bytesAcked = blockLen;
}
SimulatedInputStream getMetaIStream() {
return new SimulatedInputStream(nullCrcFileData);
}
synchronized boolean isFinalized() {
return finalized;
}
@Override
synchronized public ReplicaOutputStreams createStreams(boolean isCreate,
DataChecksum requestedChecksum)
throws IOException {
if (finalized) {
throw new IOException("Trying to write to a finalized replica "
+ theBlock);
} else {
SimulatedOutputStream crcStream = new SimulatedOutputStream();
return new ReplicaOutputStreams(oStream, crcStream, requestedChecksum,
getStorage(theBlock).getVolume(), fileIoProvider);
}
}
@Override
public OutputStream createRestartMetaStream() throws IOException {
return new SimulatedOutputStream();
}
@Override
synchronized public long getBlockId() {
return theBlock.getBlockId();
}
@Override
synchronized public long getVisibleLength() {
return getBytesAcked();
}
@Override
public ReplicaState getState() {
return finalized ? ReplicaState.FINALIZED : ReplicaState.RBW;
}
@Override
synchronized public long getBytesAcked() {
if (finalized) {
return theBlock.getNumBytes();
} else {
return bytesAcked;
}
}
@Override
synchronized public void setBytesAcked(long bytesAcked) {
if (!finalized) {
this.bytesAcked = bytesAcked;
}
}
@Override
public void releaseAllBytesReserved() {
}
@Override
synchronized public long getBytesOnDisk() {
if (finalized) {
return theBlock.getNumBytes();
} else {
return oStream.getLength();
}
}
@Override
public void setLastChecksumAndDataLen(long dataLength, byte[] lastChecksum) {
oStream.setLength(dataLength);
}
@Override
public ChunkChecksum getLastChecksumAndDataLen() {
return new ChunkChecksum(oStream.getLength(), null);
}
@Override
public boolean isOnTransientStorage() {
return false;
}
@Override
public ReplicaInfo getReplicaInfo() {
return null;
}
@Override
public void setWriter(Thread writer) {
}
@Override
public void interruptThread() {
}
@Override
public boolean attemptToSetWriter(Thread prevWriter, Thread newWriter) {
return false;
}
@Override
public void stopWriter(long xceiverStopTimeout) throws IOException {
}
@Override
public void waitForMinLength(long minLength, long time, TimeUnit unit)
throws IOException {
final long deadLine = System.currentTimeMillis() + unit.toMillis(time);
do {
if (getBytesOnDisk() >= minLength) {
return;
}
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
throw new IOException(e);
}
} while (deadLine > System.currentTimeMillis());
throw new IOException("Minimum length was not achieved within timeout");
}
}
/**
* Class is used for tracking block pool storage utilization similar
* to {@link BlockPoolSlice}
*/
private static class SimulatedBPStorage {
// in bytes
private long used;
private final Map<Block, BInfo> blockMap = new TreeMap<>();
long getUsed() {
return used;
}
void alloc(long amount) {
used += amount;
}
void free(long amount) {
used -= amount;
}
Map<Block, BInfo> getBlockMap() {
return blockMap;
}
SimulatedBPStorage() {
used = 0L;
}
}
/**
* Class used for tracking datanode level storage utilization similar
* to {@link FSVolumeSet}
*/
private static class SimulatedStorage {
private final Map<String, SimulatedBPStorage> map =
new ConcurrentHashMap<>();
private final long capacity; // in bytes
private final DatanodeStorage dnStorage;
private final SimulatedVolume volume;
synchronized long getFree() {
return capacity - getUsed();
}
long getCapacity() {
return capacity;
}
synchronized long getUsed() {
long used = 0L;
for (SimulatedBPStorage bpStorage : map.values()) {
used += bpStorage.getUsed();
}
return used;
}
synchronized long getBlockPoolUsed(String bpid) throws IOException {
return getBPStorage(bpid).getUsed();
}
int getNumFailedVolumes() {
return 0;
}
synchronized boolean alloc(String bpid, long amount) throws IOException {
if (getFree() >= amount) {
getBPStorage(bpid).alloc(amount);
return true;
}
return false;
}
synchronized void free(String bpid, long amount) throws IOException {
getBPStorage(bpid).free(amount);
}
SimulatedStorage(long cap, DatanodeStorage.State state,
FileIoProvider fileIoProvider, Configuration conf) {
capacity = cap;
dnStorage = new DatanodeStorage(
"SimulatedStorage-" + DatanodeStorage.generateUuid(),
state, StorageType.DEFAULT);
DataNodeVolumeMetrics volumeMetrics =
DataNodeVolumeMetrics.create(conf, dnStorage.getStorageID());
this.volume = new SimulatedVolume(this, fileIoProvider, volumeMetrics);
}
synchronized void addBlockPool(String bpid) {
SimulatedBPStorage bpStorage = map.get(bpid);
if (bpStorage != null) {
return;
}
map.put(bpid, new SimulatedBPStorage());
}
synchronized void removeBlockPool(String bpid) {
map.remove(bpid);
}
private SimulatedBPStorage getBPStorage(String bpid) throws IOException {
SimulatedBPStorage bpStorage = map.get(bpid);
if (bpStorage == null) {
throw new IOException("block pool " + bpid + " not found");
}
return bpStorage;
}
String getStorageUuid() {
return dnStorage.getStorageID();
}
DatanodeStorage getDnStorage() {
return dnStorage;
}
synchronized StorageReport getStorageReport(String bpid) {
return new StorageReport(dnStorage,
false, getCapacity(), getUsed(), getFree(),
map.get(bpid).getUsed(), 0L);
}
SimulatedVolume getVolume() {
return volume;
}
Map<Block, BInfo> getBlockMap(String bpid) throws IOException {
SimulatedBPStorage bpStorage = map.get(bpid);
if (bpStorage == null) {
throw new IOException("Nonexistent block pool: " + bpid);
}
return bpStorage.getBlockMap();
}
}
static class SimulatedVolume implements FsVolumeSpi {
private final SimulatedStorage storage;
private final FileIoProvider fileIoProvider;
private final DataNodeVolumeMetrics metrics;
SimulatedVolume(final SimulatedStorage storage,
final FileIoProvider fileIoProvider,
final DataNodeVolumeMetrics metrics) {
this.storage = storage;
this.fileIoProvider = fileIoProvider;
this.metrics = metrics;
}
@Override
public FsVolumeReference obtainReference() throws ClosedChannelException {
return new FsVolumeReference() {
@Override
public void close() throws IOException {
// no-op.
}
@Override
public FsVolumeSpi getVolume() {
return SimulatedVolume.this;
}
};
}
@Override
public String getStorageID() {
return storage.getStorageUuid();
}
@Override
public String[] getBlockPoolList() {
return new String[0];
}
@Override
public long getAvailable() throws IOException {
return storage.getCapacity() - storage.getUsed();
}
@Override
public StorageType getStorageType() {
return null;
}
@Override
public boolean isTransientStorage() {
return false;
}
@Override
public void reserveSpaceForReplica(long bytesToReserve) {
}
@Override
public void releaseLockedMemory(long bytesToRelease) {
}
@Override
public void releaseReservedSpace(long bytesToRelease) {
}
@Override
public BlockIterator newBlockIterator(String bpid, String name) {
throw new UnsupportedOperationException();
}
@Override
public BlockIterator loadBlockIterator(String bpid, String name)
throws IOException {
throw new UnsupportedOperationException();
}
@Override
public FsDatasetSpi getDataset() {
throw new UnsupportedOperationException();
}
@Override
public StorageLocation getStorageLocation() {
return null;
}
@Override
public URI getBaseURI() {
return null;
}
@Override
public DF getUsageStats(Configuration conf) {
return null;
}
@Override
public byte[] loadLastPartialChunkChecksum(
File blockFile, File metaFile) throws IOException {
return null;
}
@Override
public void compileReport(String bpid,
Collection<ScanInfo> report, ReportCompiler reportCompiler)
throws InterruptedException, IOException {
}
@Override
public FileIoProvider getFileIoProvider() {
return fileIoProvider;
}
@Override
public DataNodeVolumeMetrics getMetrics() {
return metrics;
}
@Override
public VolumeCheckResult check(VolumeCheckContext context)
throws Exception {
return VolumeCheckResult.HEALTHY;
}
}
private final List<SimulatedStorage> storages;
private final String datanodeUuid;
private final DataNode datanode;
public SimulatedFSDataset(DataStorage storage, Configuration conf) {
this(null, storage, conf);
}
public SimulatedFSDataset(DataNode datanode, DataStorage storage, Configuration conf) {
this.datanode = datanode;
int storageCount;
if (storage != null && storage.getNumStorageDirs() > 0) {
storageCount = storage.getNumStorageDirs();
for (int i = 0; i < storage.getNumStorageDirs(); ++i) {
DataStorage.createStorageID(storage.getStorageDir(i), false, conf);
}
this.datanodeUuid = storage.getDatanodeUuid();
} else {
storageCount = DataNode.getStorageLocations(conf).size();
this.datanodeUuid = "SimulatedDatanode-" + DataNode.generateUuid();
}
registerMBean(datanodeUuid);
this.fileIoProvider = new FileIoProvider(conf, datanode);
this.datasetLock = new AutoCloseableLock();
this.storages = new ArrayList<>();
for (int i = 0; i < storageCount; i++) {
this.storages.add(new SimulatedStorage(
conf.getLong(CONFIG_PROPERTY_CAPACITY, DEFAULT_CAPACITY),
conf.getEnum(CONFIG_PROPERTY_STATE, DEFAULT_STATE),
fileIoProvider, conf));
}
}
public synchronized void injectBlocks(String bpid,
Iterable<? extends Block> injectBlocks) throws IOException {
ExtendedBlock blk = new ExtendedBlock();
if (injectBlocks != null) {
for (Block b: injectBlocks) { // if any blocks in list is bad, reject list
if (b == null) {
throw new NullPointerException("Null blocks in block list");
}
blk.set(bpid, b);
if (isValidBlock(blk)) {
throw new IOException("Block already exists in block list");
}
}
for (SimulatedStorage storage : storages) {
storage.addBlockPool(bpid);
}
for (Block b: injectBlocks) {
BInfo binfo = new BInfo(bpid, b, false);
getBlockMap(b, bpid).put(binfo.theBlock, binfo);
}
}
}
/** Get the storage that a given block lives within. */
private SimulatedStorage getStorage(Block b) {
return storages.get(LongMath.mod(b.getBlockId(), storages.size()));
}
/**
* Get the block map that a given block lives within, assuming it is within
* block pool bpid.
* @param b The block to look for
* @param bpid The block pool that contains b
* @return The block map (non-null)
* @throws IOException if bpid does not exist
*/
private Map<Block, BInfo> getBlockMap(Block b, String bpid)
throws IOException {
return getStorage(b).getBlockMap(bpid);
}
/**
* Get the block map that a given block lives within.
* @param b The extended block to look for
* @return The block map (non-null)
* @throws IOException if b is in a nonexistent block pool
*/
private Map<Block, BInfo> getBlockMap(ExtendedBlock b) throws IOException {
return getBlockMap(b.getLocalBlock(), b.getBlockPoolId());
}
@Override // FsDatasetSpi
public synchronized void finalizeBlock(ExtendedBlock b, boolean fsyncDir)
throws IOException {
BInfo binfo = getBlockMap(b).get(b.getLocalBlock());
if (binfo == null) {
throw new IOException("Finalizing a non existing block " + b);
}
binfo.finalizeBlock(b.getBlockPoolId(), b.getNumBytes());
}
@Override // FsDatasetSpi
public synchronized void unfinalizeBlock(ExtendedBlock b) throws IOException{
if (isValidRbw(b)) {
getBlockMap(b).remove(b.getLocalBlock());
}
}
synchronized BlockListAsLongs getBlockReport(String bpid,
SimulatedStorage storage) {
BlockListAsLongs.Builder report = BlockListAsLongs.builder();
try {
for (BInfo b : storage.getBlockMap(bpid).values()) {
if (b.isFinalized()) {
report.add(b);
}
}
} catch (IOException ioe) {
DataNode.LOG.error("Exception while getting block reports", ioe);
}
return report.build();
}
@Override
public synchronized Map<DatanodeStorage, BlockListAsLongs> getBlockReports(
String bpid) {
Map<DatanodeStorage, BlockListAsLongs> blockReports = new HashMap<>();
for (SimulatedStorage storage : storages) {
blockReports.put(storage.getDnStorage(), getBlockReport(bpid, storage));
}
return blockReports;
}
@Override // FsDatasetSpi
public List<Long> getCacheReport(String bpid) {
return Collections.emptyList();
}
@Override // FSDatasetMBean
public long getCapacity() {
long total = 0L;
for (SimulatedStorage storage : storages) {
total += storage.getCapacity();
}
return total;
}
@Override // FSDatasetMBean
public long getDfsUsed() {
long total = 0L;
for (SimulatedStorage storage : storages) {
total += storage.getUsed();
}
return total;
}
@Override // FSDatasetMBean
public long getBlockPoolUsed(String bpid) throws IOException {
long total = 0L;
for (SimulatedStorage storage : storages) {
total += storage.getBlockPoolUsed(bpid);
}
return total;
}
@Override // FSDatasetMBean
public long getRemaining() {
long total = 0L;
for (SimulatedStorage storage : storages) {
total += storage.getFree();
}
return total;
}
@Override // FSDatasetMBean
public int getNumFailedVolumes() {
int total = 0;
for (SimulatedStorage storage : storages) {
total += storage.getNumFailedVolumes();
}
return total;
}
@Override // FSDatasetMBean
public String[] getFailedStorageLocations() {
return null;
}
@Override // FSDatasetMBean
public long getLastVolumeFailureDate() {
return 0L;
}
@Override // FSDatasetMBean
public long getEstimatedCapacityLostTotal() {
return 0L;
}
@Override // FsDatasetSpi
public VolumeFailureSummary getVolumeFailureSummary() {
return new VolumeFailureSummary(ArrayUtils.EMPTY_STRING_ARRAY, 0, 0);
}
@Override // FSDatasetMBean
public long getCacheUsed() {
return 0L;
}
@Override // FSDatasetMBean
public long getCacheCapacity() {
return 0L;
}
@Override // FSDatasetMBean
public long getNumBlocksCached() {
return 0L;
}
@Override
public long getNumBlocksFailedToCache() {
return 0L;
}
@Override
public long getNumBlocksFailedToUncache() {
return 0L;
}
/**
* Get metrics from the metrics source
*
* @param collector to contain the resulting metrics snapshot
* @param all if true, return all metrics even if unchanged.
*/
@Override
public void getMetrics(MetricsCollector collector, boolean all) {
try {
DataNodeMetricHelper.getMetrics(collector, this, "SimulatedFSDataset");
} catch (Exception e){
//ignore Exceptions
}
}
@Override // FsDatasetSpi
public synchronized long getLength(ExtendedBlock b) throws IOException {
BInfo binfo = getBlockMap(b).get(b.getLocalBlock());
if (binfo == null) {
throw new IOException("Finalizing a non existing block " + b);
}
return binfo.getNumBytes();
}
@Override
@Deprecated
public Replica getReplica(String bpid, long blockId) {
Block b = new Block(blockId);
try {
return getBlockMap(b, bpid).get(b);
} catch (IOException ioe) {
return null;
}
}
@Override
public synchronized String getReplicaString(String bpid, long blockId) {
Replica r = null;
try {
Block b = new Block(blockId);
r = getBlockMap(b, bpid).get(b);
} catch (IOException ioe) {
// Ignore
}
return Objects.toString(r);
}
@Override // FsDatasetSpi
public Block getStoredBlock(String bpid, long blkid) throws IOException {
Block b = new Block(blkid);
try {
BInfo binfo = getBlockMap(b, bpid).get(b);
if (binfo == null) {
return null;
}
return new Block(blkid, binfo.getGenerationStamp(), binfo.getNumBytes());
} catch (IOException ioe) {
return null;
}
}
@Override // FsDatasetSpi
public synchronized void invalidate(String bpid, Block[] invalidBlks)
throws IOException {
boolean error = false;
if (invalidBlks == null) {
return;
}
for (Block b: invalidBlks) {
if (b == null) {
continue;
}
Map<Block, BInfo> map = getBlockMap(b, bpid);
BInfo binfo = map.get(b);
if (binfo == null) {
error = true;
DataNode.LOG.warn("Invalidate: Missing block");
continue;
}
getStorage(b).free(bpid, binfo.getNumBytes());
map.remove(b);
if (datanode != null) {
datanode.notifyNamenodeDeletedBlock(new ExtendedBlock(bpid, b),
binfo.getStorageUuid());
}
}
if (error) {
throw new IOException("Invalidate: Missing blocks.");
}
}
@Override // FSDatasetSpi
public void cache(String bpid, long[] cacheBlks) {
throw new UnsupportedOperationException(
"SimulatedFSDataset does not support cache operation!");
}
@Override // FSDatasetSpi
public void uncache(String bpid, long[] uncacheBlks) {
throw new UnsupportedOperationException(
"SimulatedFSDataset does not support uncache operation!");
}
@Override // FSDatasetSpi
public boolean isCached(String bpid, long blockId) {
return false;
}
private BInfo getBInfo(final ExtendedBlock b) {
try {
return getBlockMap(b).get(b.getLocalBlock());
} catch (IOException ioe) {
return null;
}
}
@Override // {@link FsDatasetSpi}
public boolean contains(ExtendedBlock block) {
return getBInfo(block) != null;
}
/**
* Check if a block is valid.
*
* @param b The block to check.
* @param minLength The minimum length that the block must have. May be 0.
* @param state If this is null, it is ignored. If it is non-null, we will
* check that the replica has this state.
*
* @throws ReplicaNotFoundException If the replica is not found
*
* @throws UnexpectedReplicaStateException If the replica is not in the
* expected state.
*/
@Override // {@link FsDatasetSpi}
public void checkBlock(ExtendedBlock b, long minLength, ReplicaState state)
throws ReplicaNotFoundException, UnexpectedReplicaStateException {
final BInfo binfo = getBInfo(b);
if (binfo == null) {
throw new ReplicaNotFoundException(b);
}
if ((state == ReplicaState.FINALIZED && !binfo.isFinalized()) ||
(state != ReplicaState.FINALIZED && binfo.isFinalized())) {
throw new UnexpectedReplicaStateException(b,state);
}
}
@Override // FsDatasetSpi
public synchronized boolean isValidBlock(ExtendedBlock b) {
try {
checkBlock(b, 0, ReplicaState.FINALIZED);
} catch (IOException e) {
return false;
}
return true;
}
/* check if a block is created but not finalized */
@Override
public synchronized boolean isValidRbw(ExtendedBlock b) {
try {
checkBlock(b, 0, ReplicaState.RBW);
} catch (IOException e) {
return false;
}
return true;
}
@Override
public String toString() {
return getStorageInfo();
}
@Override // FsDatasetSpi
public synchronized ReplicaHandler append(
ExtendedBlock b, long newGS, long expectedBlockLen) throws IOException {
BInfo binfo = getBlockMap(b).get(b.getLocalBlock());
if (binfo == null || !binfo.isFinalized()) {
throw new ReplicaNotFoundException("Block " + b
+ " is not valid, and cannot be appended to.");
}
binfo.unfinalizeBlock();
return new ReplicaHandler(binfo, null);
}
@Override // FsDatasetSpi
public synchronized ReplicaHandler recoverAppend(
ExtendedBlock b, long newGS, long expectedBlockLen) throws IOException {
final Map<Block, BInfo> map = getBlockMap(b);
BInfo binfo = map.get(b.getLocalBlock());
if (binfo == null) {
throw new ReplicaNotFoundException("Block " + b
+ " is not valid, and cannot be appended to.");
}
if (binfo.isFinalized()) {
binfo.unfinalizeBlock();
}
map.remove(b);
binfo.theBlock.setGenerationStamp(newGS);
map.put(binfo.theBlock, binfo);
return new ReplicaHandler(binfo, null);
}
@Override // FsDatasetSpi
public Replica recoverClose(ExtendedBlock b, long newGS, long expectedBlockLen)
throws IOException {
final Map<Block, BInfo> map = getBlockMap(b);
BInfo binfo = map.get(b.getLocalBlock());
if (binfo == null) {
throw new ReplicaNotFoundException("Block " + b
+ " is not valid, and cannot be appended to.");
}
if (!binfo.isFinalized()) {
binfo.finalizeBlock(b.getBlockPoolId(), binfo.getNumBytes());
}
map.remove(b.getLocalBlock());
binfo.theBlock.setGenerationStamp(newGS);
map.put(binfo.theBlock, binfo);
return binfo;
}
@Override // FsDatasetSpi
public synchronized ReplicaHandler recoverRbw(
ExtendedBlock b, long newGS, long minBytesRcvd, long maxBytesRcvd)
throws IOException {
final Map<Block, BInfo> map = getBlockMap(b);
BInfo binfo = map.get(b.getLocalBlock());
if ( binfo == null) {
throw new ReplicaNotFoundException("Block " + b
+ " does not exist, and cannot be appended to.");
}
if (binfo.isFinalized()) {
throw new ReplicaAlreadyExistsException("Block " + b
+ " is valid, and cannot be written to.");
}
map.remove(b);
binfo.theBlock.setGenerationStamp(newGS);
map.put(binfo.theBlock, binfo);
return new ReplicaHandler(binfo, null);
}
@Override // FsDatasetSpi
public synchronized ReplicaHandler createRbw(
StorageType storageType, String storageId, ExtendedBlock b,
boolean allowLazyPersist) throws IOException {
return createTemporary(storageType, storageId, b, false);
}
@Override // FsDatasetSpi
public synchronized ReplicaHandler createTemporary(StorageType storageType,
String storageId, ExtendedBlock b, boolean isTransfer)
throws IOException {
if (isValidBlock(b)) {
throw new ReplicaAlreadyExistsException("Block " + b +
" is valid, and cannot be written to.");
}
if (isValidRbw(b)) {
throw new ReplicaAlreadyExistsException("Block " + b +
" is being written, and cannot be written to.");
}
BInfo binfo = new BInfo(b.getBlockPoolId(), b.getLocalBlock(), true);
getBlockMap(b).put(binfo.theBlock, binfo);
return new ReplicaHandler(binfo, null);
}
protected synchronized InputStream getBlockInputStream(ExtendedBlock b)
throws IOException {
BInfo binfo = getBlockMap(b).get(b.getLocalBlock());
if (binfo == null) {
throw new IOException("No such Block " + b);
}
return binfo.getIStream();
}
@Override // FsDatasetSpi
public synchronized InputStream getBlockInputStream(ExtendedBlock b,
long seekOffset) throws IOException {
InputStream result = getBlockInputStream(b);
IOUtils.skipFully(result, seekOffset);
return result;
}
/** Not supported */
@Override // FsDatasetSpi
public ReplicaInputStreams getTmpInputStreams(ExtendedBlock b, long blkoff,
long ckoff) throws IOException {
throw new IOException("Not supported");
}
@Override // FsDatasetSpi
public synchronized LengthInputStream getMetaDataInputStream(ExtendedBlock b
) throws IOException {
BInfo binfo = getBlockMap(b).get(b.getLocalBlock());
if (binfo == null) {
throw new IOException("No such Block " + b);
}
if (!binfo.finalized) {
throw new IOException("Block " + b +
" is being written, its meta cannot be read");
}
final SimulatedInputStream sin = binfo.getMetaIStream();
return new LengthInputStream(sin, sin.getLength());
}
@Override
public void handleVolumeFailures(Set<FsVolumeSpi> failedVolumes) {
}
@Override // FsDatasetSpi
public synchronized void adjustCrcChannelPosition(ExtendedBlock b,
ReplicaOutputStreams stream, int checksumSize) throws IOException {
}
/**
* Simulated input and output streams.
*/
static private class SimulatedInputStream extends java.io.InputStream {
final long length; // bytes
int currentPos = 0;
byte[] data = null;
Block theBlock = null;
/**
* An input stream of size l with repeated bytes.
* @param l size of the stream
* @param iRepeatedData byte that is repeated in the stream
*/
SimulatedInputStream(long l, Block b) {
length = l;
theBlock = b;
}
/**
* An input stream of of the supplied data
* @param iData data to construct the stream
*/
SimulatedInputStream(byte[] iData) {
data = iData;
length = data.length;
}
/**
* @return the lenght of the input stream
*/
long getLength() {
return length;
}
@Override
public int read() throws IOException {
if (currentPos >= length) {
return -1;
}
if (data !=null) {
return data[currentPos++];
} else {
return simulatedByte(theBlock, currentPos++) & BYTE_MASK;
}
}
@Override
public int read(byte[] b) throws IOException {
if (b == null) {
throw new NullPointerException();
}
if (b.length == 0) {
return 0;
}
if (currentPos >= length) { // EOF
return -1;
}
int bytesRead = (int) Math.min(b.length, length-currentPos);
if (data != null) {
System.arraycopy(data, currentPos, b, 0, bytesRead);
} else { // all data is zero
for (int i = 0; i < bytesRead; i++) {
b[i] = simulatedByte(theBlock, currentPos + i);
}
}
currentPos += bytesRead;
return bytesRead;
}
}
/**
* This class implements an output stream that merely throws its data away, but records its
* length.
*/
static private class SimulatedOutputStream extends OutputStream {
long length = 0;
/**
* constructor for Simulated Output Steram
*/
SimulatedOutputStream() {
}
/**
*
* @return the length of the data created so far.
*/
long getLength() {
return length;
}
/**
*/
void setLength(long length) {
this.length = length;
}
@Override
public void write(int arg0) throws IOException {
length++;
}
@Override
public void write(byte[] b) throws IOException {
length += b.length;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
length += len;
}
}
private ObjectName mbeanName;
/**
* Register the FSDataset MBean using the name
* "hadoop:service=DataNode,name=FSDatasetState-<storageid>"
* We use storage id for MBean name since a minicluster within a single
* Java VM may have multiple Simulated Datanodes.
*/
void registerMBean(final String storageId) {
// We wrap to bypass standard mbean naming convetion.
// This wraping can be removed in java 6 as it is more flexible in
// package naming for mbeans and their impl.
StandardMBean bean;
try {
bean = new StandardMBean(this,FSDatasetMBean.class);
mbeanName = MBeans.register("DataNode", "FSDatasetState-"+
storageId, bean);
} catch (NotCompliantMBeanException e) {
DataNode.LOG.warn("Error registering FSDatasetState MBean", e);
}
DataNode.LOG.info("Registered FSDatasetState MBean");
}
@Override
public void shutdown() {
if (mbeanName != null) MBeans.unregister(mbeanName);
}
@Override
public String getStorageInfo() {
return "Simulated FSDataset-" + datanodeUuid;
}
@Override
public boolean hasEnoughResource() {
return true;
}
@Override
public ReplicaRecoveryInfo initReplicaRecovery(RecoveringBlock rBlock)
throws IOException {
ExtendedBlock b = rBlock.getBlock();
BInfo binfo = getBlockMap(b).get(b.getLocalBlock());
if (binfo == null) {
throw new IOException("No such Block " + b);
}
return new ReplicaRecoveryInfo(binfo.getBlockId(), binfo.getBytesOnDisk(),
binfo.getGenerationStamp(),
binfo.isFinalized() ? ReplicaState.FINALIZED : ReplicaState.RBW);
}
@Override // FsDatasetSpi
public Replica updateReplicaUnderRecovery(ExtendedBlock oldBlock,
long recoveryId,
long newBlockId,
long newlength) throws IOException {
return getBInfo(oldBlock);
}
@Override // FsDatasetSpi
public long getReplicaVisibleLength(ExtendedBlock block) {
return block.getNumBytes();
}
@Override // FsDatasetSpi
public void addBlockPool(String bpid, Configuration conf) {
for (SimulatedStorage storage : storages) {
storage.addBlockPool(bpid);
}
}
@Override // FsDatasetSpi
public void shutdownBlockPool(String bpid) {
for (SimulatedStorage storage : storages) {
storage.removeBlockPool(bpid);
}
}
@Override // FsDatasetSpi
public void deleteBlockPool(String bpid, boolean force) {
return;
}
@Override
public ReplicaInPipeline convertTemporaryToRbw(ExtendedBlock temporary)
throws IOException {
final BInfo r = getBlockMap(temporary).get(temporary.getLocalBlock());
if (r == null) {
throw new IOException("Block not found, temporary=" + temporary);
} else if (r.isFinalized()) {
throw new IOException("Replica already finalized, temporary="
+ temporary + ", r=" + r);
}
return r;
}
@Override
public BlockLocalPathInfo getBlockLocalPathInfo(ExtendedBlock b) {
throw new UnsupportedOperationException();
}
@Override
public void enableTrash(String bpid) {
throw new UnsupportedOperationException();
}
@Override
public void clearTrash(String bpid) {
}
@Override
public boolean trashEnabled(String bpid) {
return false;
}
@Override
public void setRollingUpgradeMarker(String bpid) {
}
@Override
public void clearRollingUpgradeMarker(String bpid) {
}
@Override
public void checkAndUpdate(String bpid, ScanInfo info) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public FsVolumeReferences getFsVolumeReferences() {
List<SimulatedVolume> volumes = new ArrayList<>();
for (SimulatedStorage storage : storages) {
volumes.add(storage.getVolume());
}
return new FsVolumeReferences(volumes);
}
@Override
public void addVolume(
final StorageLocation location,
final List<NamespaceInfo> nsInfos) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public DatanodeStorage getStorage(final String storageUuid) {
for (SimulatedStorage storage : storages) {
if (storageUuid.equals(storage.getStorageUuid())) {
return storage.getDnStorage();
}
}
return null;
}
@Override
public StorageReport[] getStorageReports(String bpid) {
List<StorageReport> reports = new ArrayList<>();
for (SimulatedStorage storage : storages) {
reports.add(storage.getStorageReport(bpid));
}
return reports.toArray(new StorageReport[0]);
}
@Override
public List<ReplicaInfo> getFinalizedBlocks(String bpid) {
throw new UnsupportedOperationException();
}
@Override
public Map<String, Object> getVolumeInfoMap() {
throw new UnsupportedOperationException();
}
@Override
public FsVolumeSpi getVolume(ExtendedBlock b) {
return getStorage(b.getLocalBlock()).getVolume();
}
@Override
public synchronized void removeVolumes(Collection<StorageLocation> volumes,
boolean clearFailure) {
throw new UnsupportedOperationException();
}
@Override
public void submitBackgroundSyncFileRangeRequest(ExtendedBlock block,
ReplicaOutputStreams outs, long offset, long nbytes, int flags) {
throw new UnsupportedOperationException();
}
@Override
public void onCompleteLazyPersist(String bpId, long blockId,
long creationTime, File[] savedFiles, FsVolumeSpi targetVolume) {
throw new UnsupportedOperationException();
}
@Override
public void onFailLazyPersist(String bpId, long blockId) {
throw new UnsupportedOperationException();
}
@Override
public ReplicaInfo moveBlockAcrossStorage(ExtendedBlock block,
StorageType targetStorageType, String storageId) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setPinning(ExtendedBlock b) throws IOException {
getBlockMap(b).get(b.getLocalBlock()).pinned = true;
}
@Override
public boolean getPinning(ExtendedBlock b) throws IOException {
return getBlockMap(b).get(b.getLocalBlock()).pinned;
}
@Override
public boolean isDeletingBlock(String bpid, long blockId) {
throw new UnsupportedOperationException();
}
@Override
public ReplicaInfo moveBlockAcrossVolumes(ExtendedBlock block,
FsVolumeSpi destination) throws IOException {
return null;
}
@Override
public AutoCloseableLock acquireDatasetLock() {
return datasetLock.acquire();
}
}
|
xiao-chen/hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/SimulatedFSDataset.java
|
Java
|
apache-2.0
| 45,270 |
---
layout: generated_md
title: BARBADOS için iftar, namaz vakitleri ve hava durumu - il/eyalet seç
permalink: /BARBADOS
---
## BARBADOS için iftar, namaz vakitleri ve hava durumu görmek için bir il/eyalet seç
Aşağıdaki listeden bir şehir ya da semt seçin
* [BRIDGETOWN (BARBADOS) için iftar ve namaz vakitleri](/BARBADOS/BRIDGETOWN)
* [CHRISTCHURCH (BARBADOS) için iftar ve namaz vakitleri](/BARBADOS/CHRISTCHURCH)
* [SPEIGHTSTOWN (BARBADOS) için iftar ve namaz vakitleri](/BARBADOS/SPEIGHTSTOWN)
|
hakanu/iftar
|
_posts_/vakit/BARBADOS/2017-02-01-BARBADOS.markdown
|
Markdown
|
apache-2.0
| 516 |
"""Support for HomematicIP Cloud alarm control panel."""
import logging
from homeassistant.components.alarm_control_panel import AlarmControlPanel
from homeassistant.components.homematicip_cloud import (
DOMAIN as HMIPC_DOMAIN, HMIPC_HAPID, HomematicipGenericDevice)
from homeassistant.const import (
STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED,
STATE_ALARM_TRIGGERED)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['homematicip_cloud']
HMIP_ZONE_AWAY = 'EXTERNAL'
HMIP_ZONE_HOME = 'INTERNAL'
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the HomematicIP Cloud alarm control devices."""
pass
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the HomematicIP alarm control panel from a config entry."""
from homematicip.aio.group import AsyncSecurityZoneGroup
home = hass.data[HMIPC_DOMAIN][config_entry.data[HMIPC_HAPID]].home
devices = []
for group in home.groups:
if isinstance(group, AsyncSecurityZoneGroup):
devices.append(HomematicipSecurityZone(home, group))
if devices:
async_add_entities(devices)
class HomematicipSecurityZone(HomematicipGenericDevice, AlarmControlPanel):
"""Representation of an HomematicIP Cloud security zone group."""
def __init__(self, home, device):
"""Initialize the security zone group."""
device.modelType = 'Group-SecurityZone'
device.windowState = None
super().__init__(home, device)
@property
def state(self):
"""Return the state of the device."""
from homematicip.base.enums import WindowState
if self._device.active:
if (self._device.sabotage or self._device.motionDetected or
self._device.windowState == WindowState.OPEN or
self._device.windowState == WindowState.TILTED):
return STATE_ALARM_TRIGGERED
active = self._home.get_security_zones_activation()
if active == (True, True):
return STATE_ALARM_ARMED_AWAY
if active == (False, True):
return STATE_ALARM_ARMED_HOME
return STATE_ALARM_DISARMED
async def async_alarm_disarm(self, code=None):
"""Send disarm command."""
await self._home.set_security_zones_activation(False, False)
async def async_alarm_arm_home(self, code=None):
"""Send arm home command."""
await self._home.set_security_zones_activation(False, True)
async def async_alarm_arm_away(self, code=None):
"""Send arm away command."""
await self._home.set_security_zones_activation(True, True)
|
HydrelioxGitHub/home-assistant
|
homeassistant/components/homematicip_cloud/alarm_control_panel.py
|
Python
|
apache-2.0
| 2,736 |
package discovery
import (
"errors"
"fmt"
"os"
"testing"
"github.com/pachyderm/pachyderm/src/client/pkg/require"
)
func TestEtcdClient(t *testing.T) {
if os.Getenv("ETCD_PORT_2379_TCP_ADDR") == "" {
t.Skip("skipping test; $ETCD_PORT_2379_TCP_ADDR not set")
}
t.Parallel()
client, err := getEtcdClient()
require.NoError(t, err)
runTest(t, client)
}
func TestEtcdWatch(t *testing.T) {
if os.Getenv("ETCD_PORT_2379_TCP_ADDR") == "" {
t.Skip("skipping test; $ETCD_PORT_2379_TCP_ADDR not set")
}
t.Parallel()
client, err := getEtcdClient()
require.NoError(t, err)
runWatchTest(t, client)
}
func runTest(t *testing.T, client Client) {
err := client.Set("foo", "one", 0)
require.NoError(t, err)
value, err := client.Get("foo")
require.NoError(t, err)
require.Equal(t, "one", value)
//values, err := client.GetAll("foo")
//require.NoError(t, err)
//require.Equal(t, map[string]string{"foo": "one"}, values)
err = client.Set("a/b/foo", "one", 0)
require.NoError(t, err)
err = client.Set("a/b/bar", "two", 0)
require.NoError(t, err)
values, err := client.GetAll("a/b")
require.NoError(t, err)
require.Equal(t, map[string]string{"a/b/foo": "one", "a/b/bar": "two"}, values)
require.NoError(t, client.Close())
}
func runWatchTest(t *testing.T, client Client) {
cancel := make(chan bool)
err := client.Watch(
"watch/foo",
cancel,
func(value string) error {
if value == "" {
return client.Set("watch/foo", "bar", 0)
}
require.Equal(t, "bar", value)
close(cancel)
return nil
},
)
require.Equal(t, ErrCancelled, err)
cancel = make(chan bool)
err = client.WatchAll(
"watchAll/foo",
cancel,
func(value map[string]string) error {
if value == nil {
return client.Set("watchAll/foo/bar", "quux", 0)
}
require.Equal(t, map[string]string{"watchAll/foo/bar": "quux"}, value)
close(cancel)
return nil
},
)
require.Equal(t, ErrCancelled, err)
}
func getEtcdClient() (Client, error) {
etcdAddress, err := getEtcdAddress()
if err != nil {
return nil, err
}
return NewEtcdClient(etcdAddress), nil
}
func getEtcdAddress() (string, error) {
etcdAddr := os.Getenv("ETCD_PORT_2379_TCP_ADDR")
if etcdAddr == "" {
return "", errors.New("ETCD_PORT_2379_TCP_ADDR not set")
}
return fmt.Sprintf("http://%s:2379", etcdAddr), nil
}
|
sambooo/pachyderm
|
src/client/pkg/discovery/discovery_test.go
|
GO
|
apache-2.0
| 2,318 |
// Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google 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.
#include "swift_message.h"
#include <algorithm>
#include <vector>
#include <google/protobuf/stubs/hash.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.pb.h>
#include "swift_enum.h"
#include "swift_extension.h"
#include "swift_helpers.h"
#include "swift_oneof.h"
namespace google { namespace protobuf { namespace compiler { namespace swift {
using internal::WireFormat;
using internal::WireFormatLite;
using namespace std;
namespace {
void SetMapVariables(const Descriptor* descriptor, std::map<string, string>* variables) {
(*variables)["acontrol"] = GetAccessControlType(descriptor->file());
(*variables)["className"] = ClassName(descriptor);
(*variables)["errorType"] = HasOptionForGenerateErrors(descriptor) ? ", Error" : "";
(*variables)["classNameReturnedType"] = ClassNameReturedType(descriptor);
(*variables)["fileName"] = FileClassName(descriptor->file());
}
struct FieldOrderingByNumber {
inline bool operator()(const FieldDescriptor* a,
const FieldDescriptor* b) const {
return a->number() < b->number();
}
};
struct FieldOrderingByType {
inline bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const {
if (a->is_repeated() != b->is_repeated()) {
return b->is_repeated();
}
if (a->type() == FieldDescriptor::TYPE_BOOL &&
b->type() != FieldDescriptor::TYPE_BOOL) {
return true;
}
if (a->type() != FieldDescriptor::TYPE_BOOL &&
b->type() == FieldDescriptor::TYPE_BOOL) {
return false;
}
return a->type() < b->type();
}
};
struct ExtensionRangeOrdering {
bool operator()(const Descriptor::ExtensionRange* a,
const Descriptor::ExtensionRange* b) const {
return a->start < b->start;
}
};
const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) {
const FieldDescriptor** fields = new const FieldDescriptor*[descriptor->field_count()];
for (int i = 0; i < descriptor->field_count(); i++) {
fields[i] = descriptor->field(i);
}
sort(fields, fields + descriptor->field_count(), FieldOrderingByNumber());
return fields;
}
const FieldDescriptor** SortFieldsByType(const Descriptor* descriptor) {
const FieldDescriptor** fields = new const FieldDescriptor*[descriptor->field_count()];
for (int i = 0; i < descriptor->field_count(); i++) {
fields[i] = descriptor->field(i);
}
sort(fields, fields + descriptor->field_count(), FieldOrderingByType());
return fields;
}
static bool HasRequiredFields(
const Descriptor* type,
hash_set<const Descriptor*>* already_seen) {
if (already_seen->count(type) > 0) {
return false;
}
already_seen->insert(type);
if (type->extension_range_count() > 0) {
return true;
}
for (int i = 0; i < type->field_count(); i++) {
const FieldDescriptor* field = type->field(i);
if (field->is_required()) {
return true;
}
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
if (HasRequiredFields(field->message_type(), already_seen)) {
return true;
}
}
}
return false;
}
static bool HasRequiredFields(const Descriptor* type) {
hash_set<const Descriptor*> already_seen;
return HasRequiredFields(type, &already_seen);
}
} // namespace
MessageGenerator::MessageGenerator(const Descriptor* descriptor) : descriptor_(descriptor), field_generators_(descriptor) {
SetMapVariables(descriptor, &variables_);
}
MessageGenerator::~MessageGenerator() {
}
void MessageGenerator::GenerateStaticVariablesInitialization(io::Printer* printer) {
std::map<string, string> vars;
vars["index"] = SimpleItoa(descriptor_->index());
vars["className"] = ClassName(descriptor_);
for (int i = 0; i < descriptor_->extension_count(); i++) {
ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)).GenerateInitializationSource(printer);
}
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
MessageGenerator(descriptor_->nested_type(i)).GenerateStaticVariablesInitialization(printer);
}
}
void MessageGenerator::GenerateStaticVariablesSource(io::Printer* printer) {
std::map<string, string> vars;
vars["index"] = SimpleItoa(descriptor_->index());
vars["classname"] = ClassName(descriptor_);
for (int i = 0; i < descriptor_->extension_count(); i++) {
ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)).GenerateFieldsSource(printer);
}
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
MessageGenerator(descriptor_->nested_type(i)).GenerateStaticVariablesSource(printer);
}
}
void MessageGenerator::GenerateGlobalStaticVariablesSource(io::Printer* printer, string rootclass) {
std::map<string, string> vars;
vars["index"] = SimpleItoa(descriptor_->index());
vars["className"] = ClassName(descriptor_);
for (int i = 0; i < descriptor_->extension_count(); i++) {
ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)).GenerateFieldsGetterSource(printer, rootclass);
}
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
MessageGenerator(descriptor_->nested_type(i)).GenerateGlobalStaticVariablesSource(printer, rootclass);
}
}
void MessageGenerator::GenerateExtensionRegistrationSource(io::Printer* printer) {
for (int i = 0; i < descriptor_->extension_count(); i++) {
ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i))
.GenerateRegistrationSource(printer);
}
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
MessageGenerator(descriptor_->nested_type(i))
.GenerateExtensionRegistrationSource(printer);
}
}
void MessageGenerator::GenerateSource(io::Printer* printer) {
std::unique_ptr<const FieldDescriptor*[]> sorted_fields(SortFieldsByType(descriptor_));
SourceLocation location;
if (descriptor_->GetSourceLocation(&location)) {
string comments;
comments = BuildCommentsString(location);
printer->Print(comments.c_str());
}
if (descriptor_->extension_range_count() > 0) {
printer->Print(variables_,
"final $acontrol$ class $className$ : ExtendableMessage$errorType$ {\n"
);
} else {
printer->Print(variables_,
"final $acontrol$ class $className$ : GeneratedMessage$errorType$ {\n"
);
}
XCodeStandartIndent(printer);
printer->Print(variables_,"$acontrol$ typealias BuilderType = $classNameReturnedType$.Builder\n");
printer->Print("\n");
GenerateMessageIsEqualSource(printer);
//Nested Types
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
printer->Print("\n\n//Nested type declaration start\n\n");
MessageGenerator(descriptor_->nested_type(i)).GenerateSource(printer);
printer->Print("//Nested type declaration end\n\n");
}
///
//Oneof
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
string classNames = ClassNameOneof(descriptor_->oneof_decl(i));
OneofGenerator(descriptor_->oneof_decl(i)).GenerateSource(printer);
printer->Print("fileprivate var storage$storageName$:$classname$ = $classname$.oneOf$storageName$NotSet\n",
"storageName", UnderscoresToCapitalizedCamelCase(descriptor_->oneof_decl(i)->name()),
"classname", classNames);
printer->Print("$acontrol$ func getOneOf$storageName$() -> $classname$ {\n"
" let copyObject$storageName$ = storage$storageName$\n"
" return copyObject$storageName$\n"
"}\n",
"acontrol", GetAccessControlType(descriptor_->file()),
"storageName", UnderscoresToCapitalizedCamelCase(descriptor_->oneof_decl(i)->name()),
"classname", classNames);
}
////
///Enums
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
XCodeStandartIndent(printer);
EnumGenerator(descriptor_->enum_type(i)).GenerateSource(printer);
XCodeStandartOutdent(printer);
}
///
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateVariablesSource(printer);
}
for (int i = 0; i < descriptor_->extension_count(); i++) {
ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)).GenerateMembersSource(printer);
}
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateMembersSource(printer);
}
printer->Print(variables_,"required $acontrol$ init() {\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateInitializationSource(printer);
}
printer->Print(" super.init()\n"
"}\n");
GenerateIsInitializedSource(printer);
GenerateMessageSerializationMethodsSource(printer);
printer->Print(variables_,
"$acontrol$ class func getBuilder() -> $classNameReturnedType$.Builder {\n"
" return $classNameReturnedType$.classBuilder() as! $classNameReturnedType$.Builder\n"
"}\n"
"$acontrol$ func getBuilder() -> $classNameReturnedType$.Builder {\n"
" return classBuilder() as! $classNameReturnedType$.Builder\n"
"}\n"
"override $acontrol$ class func classBuilder() -> ProtocolBuffersMessageBuilder {\n"
" return $classNameReturnedType$.Builder()\n"
"}\n"
"override $acontrol$ func classBuilder() -> ProtocolBuffersMessageBuilder {\n"
" return $classNameReturnedType$.Builder()\n"
"}\n"
"$acontrol$ func toBuilder() throws -> $classNameReturnedType$.Builder {\n"
" return try $classNameReturnedType$.builderWithPrototype(prototype:self)\n"
"}\n"
"$acontrol$ class func builderWithPrototype(prototype:$classNameReturnedType$) throws -> $classNameReturnedType$.Builder {\n"
" return try $classNameReturnedType$.Builder().mergeFrom(other:prototype)\n"
"}\n");
//JSON
GenerateMessageJSONSource(printer);
GenerateMessageDescriptionSource(printer);
GenerateMessageHashSource(printer);
printer->Print("\n\n//Meta information declaration start\n\n");
printer->Print(variables_,
"override $acontrol$ class func className() -> String {\n"
" return \"$classNameReturnedType$\"\n"
"}\n"
"override $acontrol$ func className() -> String {\n"
" return \"$classNameReturnedType$\"\n"
"}\n");
printer->Print("//Meta information declaration end\n\n");
GenerateBuilderSource(printer);
XCodeStandartOutdent(printer);
printer->Print("}\n\n");
}
void MessageGenerator::GenerateMessageSerializationMethodsSource(io::Printer* printer) {
std::unique_ptr<const FieldDescriptor*[]> sorted_fields(SortFieldsByNumber(descriptor_));
std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
sorted_extensions.push_back(descriptor_->extension_range(i));
}
sort(sorted_extensions.begin(), sorted_extensions.end(),
ExtensionRangeOrdering());
printer->Print(variables_,"override $acontrol$ func writeTo(codedOutputStream: CodedOutputStream) throws {\n");
XCodeStandartIndent(printer);
for (int i = 0, j = 0;
i < descriptor_->field_count() || j < sorted_extensions.size(); ) {
if (i == descriptor_->field_count()) {
GenerateSerializeOneExtensionRangeSource(printer, sorted_extensions[j++]);
} else if (j == sorted_extensions.size()) {
GenerateSerializeOneFieldSource(printer, sorted_fields[i++]);
} else if (sorted_fields[i]->number() < sorted_extensions[j]->start) {
GenerateSerializeOneFieldSource(printer, sorted_fields[i++]);
} else {
GenerateSerializeOneExtensionRangeSource(printer, sorted_extensions[j++]);
}
}
if (descriptor_->options().message_set_wire_format()) {
printer->Print("try unknownFields.writeAsMessageSetTo(codedOutputStream: codedOutputStream)\n");
} else {
printer->Print("try unknownFields.writeTo(codedOutputStream: codedOutputStream)\n");
}
XCodeStandartOutdent(printer);
printer->Print("}\n");
printer->Print("override $acontrol$ func serializedSize() -> Int32 {\n",
"acontrol", GetAccessControlType(descriptor_->file()));
XCodeStandartIndent(printer);
printer->Print("var serialize_size:Int32 = memoizedSerializedSize\n"
"if serialize_size != -1 {\n"
" return serialize_size\n"
"}\n"
"\n"
"serialize_size = 0\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCodeSource(printer);
}
if (descriptor_->extension_range_count() > 0) {
printer->Print(
"serialize_size += extensionsSerializedSize()\n");
}
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
"serialize_size += unknownFields.serializedSizeAsMessageSet()\n");
} else {
printer->Print(
"serialize_size += unknownFields.serializedSize()\n");
}
printer->Print(
"memoizedSerializedSize = serialize_size\n"
"return serialize_size\n");
XCodeStandartOutdent(printer);
printer->Print("}\n");
}
void MessageGenerator::GenerateMessageDescriptionSource(io::Printer* printer) {
std::unique_ptr<const FieldDescriptor*[]> sorted_fields(SortFieldsByNumber(descriptor_));
std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
sorted_extensions.push_back(descriptor_->extension_range(i));
}
sort(sorted_extensions.begin(), sorted_extensions.end(), ExtensionRangeOrdering());
printer->Print("override $acontrol$ func getDescription(indent:String) throws -> String {\n","acontrol", GetAccessControlType(descriptor_->file()));
XCodeStandartIndent(printer);
printer->Print("var output = \"\"\n");
for (int i = 0, j = 0;
i < descriptor_->field_count() || j < sorted_extensions.size(); ) {
if (i == descriptor_->field_count()) {
GenerateDescriptionOneExtensionRangeSource(printer, sorted_extensions[j++]);
} else if (j == sorted_extensions.size()) {
GenerateDescriptionOneFieldSource(printer, sorted_fields[i++]);
} else if (sorted_fields[i]->number() < sorted_extensions[j]->start) {
GenerateDescriptionOneFieldSource(printer, sorted_fields[i++]);
} else {
GenerateDescriptionOneExtensionRangeSource(printer, sorted_extensions[j++]);
}
}
printer->Print("output += unknownFields.getDescription(indent: indent)\n");
printer->Print("return output\n");
XCodeStandartOutdent(printer);
printer->Print(
"}\n");
}
void MessageGenerator::GenerateMessageJSONSource(io::Printer* printer) {
//
printer->Print(variables_,"override $acontrol$ func encode() throws -> Dictionary<String,Any> {\n");
XCodeStandartIndent(printer);
printer->Print("try isInitialized()\n");
if (descriptor_->field_count() == 0) {
printer->Print("let jsonMap:Dictionary<String,Any> = Dictionary<String,Any>()\n");
}
else {
printer->Print("var jsonMap:Dictionary<String,Any> = Dictionary<String,Any>()\n");
}
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateJSONEncodeCodeSource(printer);
}
XCodeStandartOutdent(printer);
printer->Print(
" return jsonMap\n"
"}\n");
printer->Print(variables_,"override class $acontrol$ func decode(jsonMap:Dictionary<String,Any>) throws -> $classNameReturnedType$ {\n"
" return try $classNameReturnedType$.Builder.decodeToBuilder(jsonMap:jsonMap).build()\n"
"}\n");
printer->Print(variables_,"override class $acontrol$ func fromJSON(data:Data, options: JSONSerialization.ReadingOptions = []) throws -> $classNameReturnedType$ {\n"
" return try $classNameReturnedType$.Builder.fromJSONToBuilder(data:data, options:options).build()\n"
"}\n");
}
void MessageGenerator::GenerateMessageBuilderJSONSource(io::Printer* printer) {
//
printer->Print(variables_, "class override $acontrol$ func decodeToBuilder(jsonMap:Dictionary<String,Any>) throws -> $classNameReturnedType$.Builder {\n");
XCodeStandartIndent(printer);
printer->Print(variables_,"let resultDecodedBuilder = $classNameReturnedType$.Builder()\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateJSONDecodeCodeSource(printer);
}
printer->Print("return resultDecodedBuilder\n");
//
XCodeStandartOutdent(printer);
printer->Print(
"}\n");
printer->Print(variables_,
"override class $acontrol$ func fromJSONToBuilder(data:Data, options: JSONSerialization.ReadingOptions = []) throws -> $classNameReturnedType$.Builder {\n"
" let jsonData = try JSONSerialization.jsonObject(with:data, options: options)\n"
" guard let jsDataCast = jsonData as? Dictionary<String,Any> else {\n"
" throw ProtocolBuffersError.invalidProtocolBuffer(\"Invalid JSON data\")\n"
" }\n"
" return try $classNameReturnedType$.Builder.decodeToBuilder(jsonMap:jsDataCast)\n"
"}\n");
}
void MessageGenerator::GenerateMessageIsEqualSource(io::Printer* printer) {
std::unique_ptr<const FieldDescriptor*[]> sorted_fields(SortFieldsByNumber(descriptor_));
std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
sorted_extensions.push_back(descriptor_->extension_range(i));
}
sort(sorted_extensions.begin(), sorted_extensions.end(),
ExtensionRangeOrdering());
printer->Print(variables_,"$acontrol$ static func == (lhs: $classNameReturnedType$, rhs: $classNameReturnedType$) -> Bool {\n");
XCodeStandartIndent(printer);
printer->Print("if lhs === rhs {\n"
" return true\n"
"}\n"
);
printer->Print("var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)\n");
for (int i = 0, j = 0; i < descriptor_->field_count() || j < sorted_extensions.size(); ) {
if (i == descriptor_->field_count())
{
printer->Print("fieldCheck = fieldCheck && ");
GenerateIsEqualOneExtensionRangeSource(printer, sorted_extensions[j++]);
printer->Print("\n");
} else if (j == sorted_extensions.size())
{
printer->Print("fieldCheck = fieldCheck && ");
GenerateIsEqualOneFieldSource(printer, sorted_fields[i++]);
printer->Print("\n");
} else if (sorted_fields[i]->number() < sorted_extensions[j]->start) {
printer->Print("fieldCheck = fieldCheck && ");
GenerateIsEqualOneFieldSource(printer, sorted_fields[i++]);
printer->Print("\n");
} else {
printer->Print("fieldCheck = fieldCheck && ");
GenerateIsEqualOneExtensionRangeSource(printer, sorted_extensions[j++]);
printer->Print("\n");
}
}
printer->Print("fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))\n");
printer->Print("return fieldCheck\n");
XCodeStandartOutdent(printer);
printer->Print("}\n\n");
}
void MessageGenerator::GenerateMessageHashSource(io::Printer* printer) {
std::unique_ptr<const FieldDescriptor*[]> sorted_fields(SortFieldsByNumber(descriptor_));
std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
sorted_extensions.push_back(descriptor_->extension_range(i));
}
sort(sorted_extensions.begin(), sorted_extensions.end(),
ExtensionRangeOrdering());
printer->Print(variables_,"override $acontrol$ var hashValue:Int {\n");
XCodeStandartIndent(printer);
printer->Print("get {\n");
XCodeStandartIndent(printer);
printer->Print("var hashCode:Int = 7\n");
for (int i = 0, j = 0;
i < descriptor_->field_count() || j < sorted_extensions.size(); ) {
if (i == descriptor_->field_count()) {
GenerateHashOneExtensionRangeSource(printer, sorted_extensions[j++]);
} else if (j == sorted_extensions.size()) {
GenerateHashOneFieldSource(printer, sorted_fields[i++]);
} else if (sorted_fields[i]->number() < sorted_extensions[j]->start) {
GenerateHashOneFieldSource(printer, sorted_fields[i++]);
} else {
GenerateHashOneExtensionRangeSource(printer, sorted_extensions[j++]);
}
}
printer->Print("hashCode = (hashCode &* 31) &+ unknownFields.hashValue\n"
"return hashCode\n");
XCodeStandartOutdent(printer);
printer->Print("}\n");
XCodeStandartOutdent(printer);
printer->Print(
"}\n");
}
void MessageGenerator::GenerateParseFromMethodsSource(io::Printer* printer) {
printer->Print(variables_,"extension $classNameReturnedType$: GeneratedMessageProtocol {\n");
XCodeStandartIndent(printer);
printer->Print(variables_,
"$acontrol$ class func parseArrayDelimitedFrom(inputStream: InputStream) throws -> Array<$classNameReturnedType$> {\n"
" var mergedArray = Array<$classNameReturnedType$>()\n"
" while let value = try parseDelimitedFrom(inputStream: inputStream) {\n"
" mergedArray.append(value)\n"
" }\n"
" return mergedArray\n"
"}\n"
"$acontrol$ class func parseDelimitedFrom(inputStream: InputStream) throws -> $classNameReturnedType$? {\n"
" return try $classNameReturnedType$.Builder().mergeDelimitedFrom(inputStream: inputStream)?.build()\n"
"}\n"
"$acontrol$ class func parseFrom(data: Data) throws -> $classNameReturnedType$ {\n"
" return try $classNameReturnedType$.Builder().mergeFrom(data: data, extensionRegistry:$fileName$.default.extensionRegistry).build()\n"
"}\n"
"$acontrol$ class func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> $classNameReturnedType$ {\n"
" return try $classNameReturnedType$.Builder().mergeFrom(data: data, extensionRegistry:extensionRegistry).build()\n"
"}\n"
"$acontrol$ class func parseFrom(inputStream: InputStream) throws -> $classNameReturnedType$ {\n"
" return try $classNameReturnedType$.Builder().mergeFrom(inputStream: inputStream).build()\n"
"}\n"
"$acontrol$ class func parseFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> $classNameReturnedType$ {\n"
" return try $classNameReturnedType$.Builder().mergeFrom(inputStream: inputStream, extensionRegistry:extensionRegistry).build()\n"
"}\n"
"$acontrol$ class func parseFrom(codedInputStream: CodedInputStream) throws -> $classNameReturnedType$ {\n"
" return try $classNameReturnedType$.Builder().mergeFrom(codedInputStream: codedInputStream).build()\n"
"}\n"
"$acontrol$ class func parseFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> $classNameReturnedType$ {\n"
" return try $classNameReturnedType$.Builder().mergeFrom(codedInputStream: codedInputStream, extensionRegistry:extensionRegistry).build()\n"
"}\n");
XCodeStandartOutdent(printer);
GenerateSubscript(printer);
printer->Print("}\n");
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
MessageGenerator(descriptor_->nested_type(i)).GenerateParseFromMethodsSource(printer);
}
}
void MessageGenerator::GenerateBuilderExtensions(io::Printer* printer) {
printer->Print(variables_,"extension $classNameReturnedType$.Builder: GeneratedMessageBuilderProtocol {\n");
XCodeStandartIndent(printer);
printer->Print(variables_,"$acontrol$ typealias GeneratedMessageType = $classNameReturnedType$\n");
GenerateSetSubscript(printer);
XCodeStandartOutdent(printer);
printer->Print("}\n");
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
MessageGenerator(descriptor_->nested_type(i)).GenerateBuilderExtensions(printer);
}
}
void MessageGenerator::GenerateSubscript(io::Printer* printer) const {
XCodeStandartIndent(printer);
printer->Print(variables_,"$acontrol$ subscript(key: String) -> Any? {\n");
XCodeStandartIndent(printer);
if (descriptor_->field_count() > 0) {
printer->Print("switch key {\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateSubscript(printer);
}
printer->Print("default: return nil\n");
printer->Print("}\n");
} else {
printer->Print("return nil\n");
}
XCodeStandartOutdent(printer);
printer->Print("}\n");
XCodeStandartOutdent(printer);
}
void MessageGenerator::GenerateSetSubscript(io::Printer* printer) const {
printer->Print(variables_,"$acontrol$ subscript(key: String) -> Any? {\n");
XCodeStandartIndent(printer);
if (descriptor_->field_count() > 0) {
printer->Print("get { \n");
XCodeStandartIndent(printer);
printer->Print("switch key {\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateSubscript(printer);
}
printer->Print("default: return nil\n");
printer->Print("}\n");
XCodeStandartOutdent(printer);
printer->Print("}\n");
printer->Print("set (newSubscriptValue) { \n");
XCodeStandartIndent(printer);
printer->Print("switch key {\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateSetSubscript(printer);
}
printer->Print("default: return\n");
printer->Print("}\n");
XCodeStandartOutdent(printer);
printer->Print("}\n");
} else {
printer->Print("get { return nil }\n");
printer->Print("set { }\n");
}
XCodeStandartOutdent(printer);
printer->Print("}\n");
}
void MessageGenerator::GenerateSerializeOneFieldSource(io::Printer* printer, const FieldDescriptor* field) {
field_generators_.get(field).GenerateSerializationCodeSource(printer);
}
void MessageGenerator::GenerateSerializeOneExtensionRangeSource(io::Printer* printer, const Descriptor::ExtensionRange* range) {
printer->Print(
"try writeExtensionsTo(codedOutputStream: codedOutputStream, startInclusive:$from$, endExclusive:$to$)\n",
"from", SimpleItoa(range->start),
"to", SimpleItoa(range->end));
}
void MessageGenerator::GenerateDescriptionOneFieldSource(io::Printer* printer, const FieldDescriptor* field) {
field_generators_.get(field).GenerateDescriptionCodeSource(printer);
}
void MessageGenerator::GenerateDescriptionOneExtensionRangeSource(io::Printer* printer, const Descriptor::ExtensionRange* range) {
printer->Print(
"output += try getExtensionDescription(startInclusive:$from$, endExclusive:$to$, indent:indent)\n",
"from", SimpleItoa(range->start),
"to", SimpleItoa(range->end));
}
void MessageGenerator::GenerateIsEqualOneFieldSource(io::Printer* printer, const FieldDescriptor* field) {
field_generators_.get(field).GenerateIsEqualCodeSource(printer);
}
void MessageGenerator::GenerateIsEqualOneExtensionRangeSource(io::Printer* printer, const Descriptor::ExtensionRange* range) {
printer->Print(
"lhs.isEqualExtensionsInOther(otherMessage: rhs, startInclusive:$from$, endExclusive:$to$)",
"from", SimpleItoa(range->start), "to", SimpleItoa(range->end));
}
void MessageGenerator::GenerateHashOneFieldSource(io::Printer* printer, const FieldDescriptor* field) {
field_generators_.get(field).GenerateHashCodeSource(printer);
}
void MessageGenerator::GenerateHashOneExtensionRangeSource(io::Printer* printer, const Descriptor::ExtensionRange* range) {
printer->Print(
"hashCode = (hashCode &* 31) &+ Int(hashExtensionsFrom(startInclusive: $from$, endExclusive:$to$))\n",
"from", SimpleItoa(range->start), "to", SimpleItoa(range->end));
}
void MessageGenerator::GenerateBuilderSource(io::Printer* printer) {
if (descriptor_->extension_range_count() > 0) {
printer->Print(variables_,
"final $acontrol$ class Builder : ExtendableMessageBuilder {\n");
} else {
printer->Print(variables_,
"final $acontrol$ class Builder : GeneratedMessageBuilder {\n");
}
XCodeStandartIndent(printer);
printer->Print(variables_,
"fileprivate var builderResult:$classNameReturnedType$ = $classNameReturnedType$()\n"
"$acontrol$ func getMessage() -> $classNameReturnedType$ {\n"
" return builderResult\n"
"}\n\n"
"required override $acontrol$ init () {\n"
" super.init()\n"
"}\n");
//Oneof
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
string classNames = ClassNameOneof(descriptor_->oneof_decl(i));
printer->Print("$acontrol$ func set$storageName$(_ oneOf:$classname$) -> $classNameReturnedType$.Builder {\n"
" builderResult.storage$storageName$ = oneOf\n"
" return self\n"
"}\n",
"acontrol", GetAccessControlType(descriptor_->file()),
"storageName", UnderscoresToCapitalizedCamelCase(descriptor_->oneof_decl(i)->name()),
"classname", classNames,
"classNameReturnedType",ClassNameReturedType(descriptor_));
}
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateBuilderMembersSource(printer);
}
GenerateCommonBuilderMethodsSource(printer);
GenerateBuilderParsingMethodsSource(printer);
GenerateMessageBuilderJSONSource(printer);
XCodeStandartOutdent(printer);
printer->Print("}\n\n");
}
void MessageGenerator::GenerateCommonBuilderMethodsSource(io::Printer* printer) {
if (descriptor_->extension_range_count() > 0) {
printer->Print(variables_,
"override $acontrol$ var internalGetResult:ExtendableMessage {\n"
" get {\n"
" return builderResult\n"
" }\n"
"}\n");
} else {
printer->Print(variables_,
"override $acontrol$ var internalGetResult:GeneratedMessage {\n"
" get {\n"
" return builderResult\n"
" }\n"
"}\n");
}
printer->Print(variables_,
"@discardableResult\n"
"override $acontrol$ func clear() -> $classNameReturnedType$.Builder {\n"
" builderResult = $classNameReturnedType$()\n"
" return self\n"
"}\n"
"override $acontrol$ func clone() throws -> $classNameReturnedType$.Builder {\n"
" return try $classNameReturnedType$.builderWithPrototype(prototype:builderResult)\n"
"}\n");
printer->Print(variables_,
"override $acontrol$ func build() throws -> $classNameReturnedType$ {\n"
" try checkInitialized()\n"
" return buildPartial()\n"
"}\n"
"$acontrol$ func buildPartial() -> $classNameReturnedType$ {\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateBuildingCodeSource(printer);
}
printer->Print(variables_,
" let returnMe:$classNameReturnedType$ = builderResult\n"
" return returnMe\n"
"}\n");
printer->Print(variables_,
"@discardableResult\n"
"$acontrol$ func mergeFrom(other:$classNameReturnedType$) throws -> $classNameReturnedType$.Builder {\n");
XCodeStandartIndent(printer);
printer->Print(variables_,
"if other == $classNameReturnedType$() {\n"
" return self\n"
"}\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i)).GenerateMergingCodeSource(printer);
}
if (descriptor_->extension_range_count() > 0) {
printer->Print("try mergeExtensionFields(other: other)\n");
}
printer->Print("try merge(unknownField: other.unknownFields)\n"
"return self\n");
XCodeStandartOutdent(printer);
printer->Print("}\n");
}
//////////////////////////////////////////////////////////
void MessageGenerator::GenerateBuilderParsingMethodsSource(io::Printer* printer) {
std::unique_ptr<const FieldDescriptor*[]> sorted_fields(SortFieldsByNumber(descriptor_));
printer->Print(variables_,
"@discardableResult\n"
"override $acontrol$ func mergeFrom(codedInputStream: CodedInputStream) throws -> $classNameReturnedType$.Builder {\n"
" return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry())\n"
"}\n"
"@discardableResult\n"
"override $acontrol$ func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> $classNameReturnedType$.Builder {\n");
XCodeStandartIndent(printer);
printer->Print(
"let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields)\n"
"while (true) {\n");
XCodeStandartIndent(printer);
printer->Print("let protobufTag = try codedInputStream.readTag()\n"
"switch protobufTag {\n");
printer->Print("case 0: \n");
XCodeStandartIndent(printer);
printer->Print("self.unknownFields = try unknownFieldsBuilder.build()\n"
"return self\n"
"\n");
XCodeStandartOutdent(printer);
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = sorted_fields[i];
uint32 tag = WireFormatLite::MakeTag(field->number(),
WireFormat::WireTypeForFieldType(field->type()));
if (isPackedTypeProto3(field) && field->is_repeated()) {
tag = WireFormatLite::MakeTag(field->number(),
WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
}
printer->Print("case $tag$:\n",
"tag", SimpleItoa(tag));
XCodeStandartIndent(printer);
field_generators_.get(field).GenerateParsingCodeSource(printer);
XCodeStandartOutdent(printer);
printer->Print("\n");
}
printer->Print("default:\n"
" if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) {\n"
" unknownFields = try unknownFieldsBuilder.build()\n"
" return self\n"
" }\n"
"}\n");
XCodeStandartOutdent(printer);
printer->Print("}\n");
XCodeStandartOutdent(printer);
printer->Print("}\n");
}
void MessageGenerator::GenerateIsInitializedSource(io::Printer* printer) {
printer->Print(variables_,
"override $acontrol$ func isInitialized() throws {\n");
XCodeStandartIndent(printer);
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
if (field->is_required()) {
printer->Print("if !has$capitalized_name$ {\n"
" throw ProtocolBuffersError.invalidProtocolBuffer(\"Uninitialized Message \\($classNameReturnedType$.self): field \\\"$fieldName$\\\" mark required\")\n"
"}\n",
"capitalized_name", UnderscoresToCapitalizedCamelCase(field),
"classNameReturnedType", ClassNameReturedType(descriptor_),
"fieldName", UnderscoresToCamelCase(field));
}
}
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
HasRequiredFields(field->message_type())) {
std::map<string,string> vars;
vars["type"] = ClassName(field->message_type());
vars["name"] = UnderscoresToCamelCase(field);
vars["name_reserved"] = SafeName(UnderscoresToCamelCase(field));
vars["capitalized_name"] = UnderscoresToCapitalizedCamelCase(field);
switch (field->label()) {
case FieldDescriptor::LABEL_REQUIRED:
printer->Print(vars,
"try $name_reserved$.isInitialized()\n");
break;
case FieldDescriptor::LABEL_OPTIONAL:
printer->Print(vars,
"if has$capitalized_name$ {\n"
" try $name_reserved$.isInitialized()\n"
"}\n");
break;
case FieldDescriptor::LABEL_REPEATED:
if (field->is_map()) {
printer->Print(vars,
"for (_, oneElement$capitalized_name$) in $name_reserved$ {\n"
" try oneElement$capitalized_name$.isInitialized()\n"
"}\n"
);
} else {
printer->Print(vars,
"for oneElement$capitalized_name$ in $name_reserved$ {\n"
" try oneElement$capitalized_name$.isInitialized()\n"
"}\n"
// "if !isInit$capitalized_name$ {\n"
// " return isInit$capitalized_name$\n"
// "}\n"
);
}
break;
}
}
}
if (descriptor_->extension_range_count() > 0) {
printer->Print(
"try extensionsAreInitialized()");
}
XCodeStandartOutdent(printer);
printer->Print("}\n");
}
} // namespace swift
} // namespace compiler
} // namespace protobuf
} // namespace google
|
alexeyxo/protobuf-swift
|
plugin/compiler/swift_message.cc
|
C++
|
apache-2.0
| 47,010 |
#include "AbstractStixelWorldEstimator.hpp"
namespace doppia
{
// provide default implementations for some methods
void AbstractStixelWorldEstimator::set_rectified_images_pair(const input_image_const_view_t &left,
const input_image_const_view_t &right)
{
input_left_view = left;
input_right_view = right;
return;
}
AbstractStixelWorldEstimator::~AbstractStixelWorldEstimator()
{
// nothing to do here
return;
}
} // end of namespace doppia
|
LevinJ/Pedestrian-detection-and-tracking
|
src/doppia/src/stereo_matching/stixels/AbstractStixelWorldEstimator.cpp
|
C++
|
apache-2.0
| 578 |
using NUnit.Framework;
using StructureMap.Graph;
using StructureMap.Testing.Widget2;
namespace StructureMap.Testing.Graph
{
[TestFixture]
public class EnumerationTester
{
[Test]
public void BuildClassWithEnumeration()
{
var graph = new PluginGraph();
PluginFamily family = graph.FindFamily(typeof (Cow));
family.AddPlugin(typeof (Cow), "Default");
var manager = new Container(graph);
manager.Configure(r => r.InstanceOf<Cow>().Is.OfConcreteType<Cow>()
.WithName("Angus")
.WithProperty("Name").EqualTo("Bessie")
.WithProperty("Breed").EqualTo("Angus")
.WithProperty("Weight").EqualTo("1200"));
var angus = manager.GetInstance<Cow>("Angus");
Assert.IsNotNull(angus);
Assert.AreEqual("Bessie", angus.Name, "Name");
Assert.AreEqual(BreedEnum.Angus, angus.Breed, "Breed");
Assert.AreEqual(1200, angus.Weight, "Weight");
}
}
}
|
chester89/structuremap-35-client
|
Source/StructureMap.Testing/Graph/EnumerationTester.cs
|
C#
|
apache-2.0
| 1,185 |
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package devopsguru provides the client and types for making API
// requests to Amazon DevOps Guru.
//
// Amazon DevOps Guru is a fully managed service that helps you identify anomalous
// behavior in business critical operational applications. You specify the Amazon
// Web Services resources that you want DevOps Guru to cover, then the Amazon
// CloudWatch metrics and Amazon Web Services CloudTrail events related to those
// resources are analyzed. When anomalous behavior is detected, DevOps Guru
// creates an insight that includes recommendations, related events, and related
// metrics that can help you improve your operational applications. For more
// information, see What is Amazon DevOps Guru (https://docs.aws.amazon.com/devops-guru/latest/userguide/welcome.html).
//
// You can specify 1 or 2 Amazon Simple Notification Service topics so you are
// notified every time a new insight is created. You can also enable DevOps
// Guru to generate an OpsItem in Amazon Web Services Systems Manager for each
// insight to help you manage and track your work addressing insights.
//
// To learn about the DevOps Guru workflow, see How DevOps Guru works (https://docs.aws.amazon.com/devops-guru/latest/userguide/welcome.html#how-it-works).
// To learn about DevOps Guru concepts, see Concepts in DevOps Guru (https://docs.aws.amazon.com/devops-guru/latest/userguide/concepts.html).
//
// See https://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01 for more information on this service.
//
// See devopsguru package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/devopsguru/
//
// Using the Client
//
// To contact Amazon DevOps Guru with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the Amazon DevOps Guru client DevOpsGuru for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/devopsguru/#New
package devopsguru
|
aws/aws-sdk-go
|
service/devopsguru/doc.go
|
GO
|
apache-2.0
| 2,406 |
<?php
/*********
* Author:Mrinmoy Mondal
* Date : 15 Sep 2011
* Modified By:
* Modified Date:
*
* Purpose:
* View For news Add & Edit
*
* @package Content Management
* @subpackage news
*
* @link InfController.php
* @link My_Controller.php
* @link views/admin/news/
*/
?>
<?php
/////////Javascript For List View//////////
?>
<script type="text/javascript" src="js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript" src="js/tinymce/tinymce_load.js"></script>
<script language="javascript">
jQuery.noConflict();///$ can be used by other prototype which is not jquery
jQuery(function($) {
$(document).ready(function(){
var g_controller="<?php echo $pathtoclass;?>";//controller Path
$('input[id^="btn_cancel"]').each(function(i){
$(this).click(function(){
$.blockUI({ message: 'Just a moment please...' });
window.location.href=g_controller+"show_list";
});
});
$('input[id^="btn_save"]').each(function(i){
$(this).click(function(){
$.blockUI({ message: 'Just a moment please...' });
// $("#frm_add_edit").submit();
check_duplicate();
});
});
//////////Checking Duplicate/////////
function check_duplicate(){
var $this = $("#txt_email");
$this.next().remove("#err_msg");
$(".star_err1").remove();
$(".star_succ1").remove();
if($this.val()!="")
{
$.blockUI({ message: 'Checking duplicates.Just a moment please...' });
$.post(g_controller+"ajax_checkduplicate",
{"h_id":$("#h_id").val(),
"h_duplicate_value":$this.val()
},
function(data)
{
if(data!="valid")////invalid
{
$this.focus();
$('<div id="err_msg" class="star_err1">Duplicate title exists.</div>')
.insertAfter("#txt_email");
}
else
{
// $('<div id="err_msg" class="star_succ1">You can choose this year.</div>')
// .insertAfter("#txt_milestones_year");
$("#frm_add_edit").submit();
}
});
}
else
{
$("#frm_add_edit").submit();
}
}
///////////Submitting the form/////////
$("#frm_add_edit").submit(function(){
var b_valid=true;
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var s_err="";
$("#div_err").hide("slow");
if($.trim($("#opt_user_type").val())=="")
{
s_err +='Please select user type.<br />';
b_valid=false;
}
if($.trim($("#txt_first_name").val())=="")
{
s_err +='Please provide firstname.<br />';
b_valid=false;
}
if($.trim($("#txt_last_name").val())=="")
{
s_err +='Please provide lastname.<br />';
b_valid=false;
}
if($.trim($("#txt_email").val())=="")
{
s_err +='Please provide email.<br />';
b_valid=false;
}
else if(!emailPattern.test($.trim($("#txt_email").val())))
{
s_err +='Please provide proper email.<br />';
b_valid=false;
}
if($.trim($("#txt_user_name").val())=="")
{
s_err +='Please provide username.<br />';
b_valid=false;
}
if($.trim($("#txt_pwd").val())=="")
{
s_err +='Please provide password.<br />';
b_valid=false;
}
if($.trim($("#txt_con_pwd").val())=="")
{
s_err +='Please provide confirm password.<br />';
b_valid=false;
}
else if($.trim($("#txt_pwd").val())!=$.trim($("#txt_con_pwd").val()))
{
s_err +='Please give two password same.<br />';
b_valid=false;
}
/////////validating//////
if(!b_valid)
{
$.unblockUI();
$("#div_err").html('<div id="err_msg" class="error_massage">'+s_err+'</div>').show("slow");
}
return b_valid;
});
///////////end Submitting the form/////////
})});
</script>
<?php
/////////end Javascript For List View//////////
/****
<div class="success_massage"><span>SUCCESS!</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
<div class="error_massage"><span>ERROR!</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
<div class="warning_massage"><span>Warning!</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
<div class="info_massage"><span>Information!</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
*/
?>
<div id="right_panel">
<form id="frm_add_edit" name="frm_add_edit" method="post" action="">
<!--<input type="hidden" id="h_mode" name="h_mode" value="<?php echo $posted["h_mode"];?>">-->
<input type="hidden" id="h_id" name="h_id" value="<?php echo $posted["h_id"];?>">
<h2><?php echo $heading;?></h2>
<p> </p>
<div id="div_err">
<?php
show_msg("error");
echo validation_errors();
/* pr($posted);*/
?>
</div>
<div class="left"><!--<input id="btn_save" name="btn_save" type="button" value="Save" title="Click here to save information." /> <input id="btn_cancel" name="btn_cancel" type="button" value="Cancel" title="Click here to cancel saving information and return to previous page."/>--></div>
<div class="add_edit">
<? /*****Modify Section Starts*******/?>
<div>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<th width="30%" align="left"><h4><?php echo $heading;?></h4></th>
<th width="60%" align="left"> </th>
<th width="10%"> </th>
</tr>
<tr>
<td>User Type *:</td>
<td>
<select name="opt_user_type" id="opt_user_type">
<option value="">Select</option>
<?php echo makeOptionUser('',$posted['opt_user_type']) ?>
</select>
</td>
<td> </td>
</tr>
<tr>
<td>Firstname *:</td>
<td><input id="txt_first_name" name="txt_first_name" value="<?php echo $posted["txt_first_name"] ?>" type="text" size="50" autocomplete="off" /></td>
<td> </td>
</tr>
<tr>
<td>Lastname *:</td>
<td><input id="txt_last_name" name="txt_last_name" value="<?php echo $posted["txt_last_name"] ?>" type="text" size="50" autocomplete="off" /></td>
<td> </td>
</tr>
<tr>
<td>Username *:</td>
<td><input id="txt_user_name" name="txt_user_name" value="<?php echo $posted["txt_user_name"] ?>" type="text" size="50" autocomplete="off" /></td>
<td> </td>
</tr>
<tr>
<td>Email Id *:</td>
<td><input id="txt_email" name="txt_email" value="<?php echo $posted["txt_email"] ?>" type="text" size="50" autocomplete="off" /></td>
<td> </td>
</tr>
<tr>
<td>Password *:</td>
<td><input id="txt_pwd" name="txt_pwd" value="" type="password" size="34" maxlength="12" style="border: 1px solid #A7A7A7;" /></td>
<td> </td>
</tr>
<tr>
<td>Confirm Password *:</td>
<td><input id="txt_con_pwd" name="txt_con_pwd" value="" type="password" size="34" maxlength="12" style="border: 1px solid #A7A7A7;" /></td>
<td> </td>
</tr>
<tr>
<td>Active:</td>
<td><input id="i_user_is_active" name="i_user_is_active" value="1" <?php if($posted["i_user_is_active"]==2) echo ''; else echo 'checked="checked"';?> type="checkbox" /></td>
<td> </td>
</tr>
</table>
</div>
<? /***** end Modify Section *******/?>
</div>
<div class="left">
<input id="btn_save" name="btn_save" type="button" value="Save" title="Click here to save information." />
<input id="btn_cancel" name="btn_cancel" type="button" value="Cancel" title="Click here to cancel saving information and return to previous page."/>
</div>
</form>
</div>
|
mrinsss/Full-Repo
|
quoteurjob/system/application/views/admin/user_admin/add-edit.tpl.php
|
PHP
|
apache-2.0
| 8,341 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.jboss.as.quickstarts.ejb_security_plus;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
/**
* Utility class for looking up EJBs
*
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
class EJBUtil {
static SecuredEJBRemote lookupSecuredEJB() throws Exception {
final Hashtable<String, String> jndiProperties = new Hashtable<String, String>();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
return (SecuredEJBRemote) context.lookup("ejb:/jboss-ejb-security-plus/SecuredEJB!"
+ SecuredEJBRemote.class.getName());
}
}
|
wfink/jboss-as-quickstart
|
ejb-security-plus/src/main/java/org/jboss/as/quickstarts/ejb_security_plus/EJBUtil.java
|
Java
|
apache-2.0
| 1,547 |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.jbpm.process.audit;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.jbpm.process.audit.event.AuditEvent;
import org.jbpm.process.audit.event.AuditEventBuilder;
import org.kie.api.runtime.KieRuntime;
@Entity
@SequenceGenerator(name="processInstanceLogIdSeq", sequenceName="PROC_INST_LOG_ID_SEQ", allocationSize=1)
public class ProcessInstanceLog implements Serializable, AuditEvent, org.kie.api.runtime.manager.audit.ProcessInstanceLog {
private static final long serialVersionUID = 510l;
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator="processInstanceLogIdSeq")
private long id;
private long processInstanceId;
private String processId;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "start_date")
private Date start;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "end_date")
private Date end;
@Column(nullable=true)
private Integer status;
@Column(nullable=true)
private Long parentProcessInstanceId;
@Column(nullable=true)
private String outcome;
private Long duration;
@Column(name="user_identity")
private String identity;
private String processVersion;
private String processName;
private String correlationKey;
@Column(nullable=true)
private Integer processType;
/**
* Dependening on the {@link AuditEventBuilder} implementation,
* this can be<ul>
* <li>The {@link KieRuntime} id</li>
* <li>The deployment unit Id</li>
*
*/
private String externalId;
private String processInstanceDescription;
public ProcessInstanceLog() {
}
public ProcessInstanceLog(long processInstanceId, String processId) {
setProcessInstanceId(processInstanceId);
setProcessId(processId);
setStart(new Date());
}
public long getId() {
return id;
}
void setId(long id) {
this.id = id;
}
public Long getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(long processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public String toString() {
return "Process '" + processId + "' [" + processInstanceId + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((end == null) ? 0 : end.hashCode());
result = prime * result + (int) id;
result = prime * result
+ ((processId == null) ? 0 : processId.hashCode());
result = prime * result + (int) processInstanceId;
result = prime * result + ((start == null) ? 0 : start.hashCode());
result = prime * result + ((parentProcessInstanceId == null) ? 0 : parentProcessInstanceId.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((outcome == null) ? 0 : outcome.hashCode());
result = prime * result + ((duration == null) ? 0 : duration.hashCode());
result = prime * result + ((identity == null) ? 0 : identity.hashCode());
result = prime * result + ((externalId == null) ? 0 : externalId.hashCode());
result = prime * result + ((processVersion == null) ? 0 : processVersion.hashCode());
result = prime * result + ((processName == null) ? 0 : processName.hashCode());
result = prime * result + ((processInstanceDescription == null) ? 0 : processInstanceDescription.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProcessInstanceLog other = (ProcessInstanceLog) obj;
if (end == null) {
if (other.end != null)
return false;
} else if (!end.equals(other.end))
return false;
if (id != other.id)
return false;
if (processId == null) {
if (other.processId != null)
return false;
} else if (!processId.equals(other.processId))
return false;
if (processInstanceId != other.processInstanceId)
return false;
if (start == null) {
if (other.start != null)
return false;
} else if (!start.equals(other.start))
return false;
if (parentProcessInstanceId == null) {
if (other.parentProcessInstanceId != null)
return false;
} else if (!parentProcessInstanceId.equals(other.parentProcessInstanceId))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (outcome == null) {
if (other.outcome != null)
return false;
} else if (!outcome.equals(other.outcome))
return false;
if (duration == null) {
if (other.duration != null)
return false;
} else if (!duration.equals(other.duration))
return false;
if (identity == null) {
if (other.identity != null)
return false;
} else if (!identity.equals(other.identity))
return false;
if (externalId == null) {
if (other.externalId != null)
return false;
} else if (!externalId.equals(other.externalId))
return false;
if (processVersion == null) {
if (other.processVersion != null)
return false;
} else if (!processVersion.equals(other.processVersion))
return false;
if (processName == null) {
if (other.processName != null)
return false;
} else if (!processName.equals(other.processName))
return false;
if (processInstanceDescription == null) {
if (other.processInstanceDescription != null)
return false;
} else if (!processInstanceDescription.equals(other.processInstanceDescription))
return false;
return true;
}
public Integer getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Long getParentProcessInstanceId() {
return parentProcessInstanceId;
}
public void setParentProcessInstanceId(long parentProcessInstanceId) {
this.parentProcessInstanceId = parentProcessInstanceId;
}
public String getOutcome() {
return outcome;
}
public void setOutcome(String errorCode) {
this.outcome = errorCode;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
public String getExternalId() {
return externalId;
}
public void setExternalId(String domainId) {
this.externalId = domainId;
}
public String getProcessVersion() {
return processVersion;
}
public void setProcessVersion(String version) {
this.processVersion = version;
}
public String getProcessName() {
return processName;
}
public void setProcessName(String processName) {
this.processName = processName;
}
public String getProcessInstanceDescription() {
return processInstanceDescription;
}
public void setProcessInstanceDescription(String processInstanceDescription) {
this.processInstanceDescription = processInstanceDescription;
}
public String getCorrelationKey() {
return correlationKey;
}
public void setCorrelationKey(String correlationKey) {
this.correlationKey = correlationKey;
}
public Integer getProcessType() {
return processType;
}
public void setProcessType(Integer processType) {
this.processType = processType;
}
}
|
DuncanDoyle/jbpm
|
jbpm-audit/src/main/java/org/jbpm/process/audit/ProcessInstanceLog.java
|
Java
|
apache-2.0
| 9,397 |
/**
* 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.geronimo.web25.deployment.merge.webfragment;
import org.apache.geronimo.common.DeploymentException;
import org.apache.geronimo.web25.deployment.merge.ElementSource;
import org.apache.geronimo.web25.deployment.merge.MergeContext;
import org.apache.geronimo.web25.deployment.merge.MergeItem;
import org.apache.geronimo.web25.deployment.utils.WebDeploymentMessageUtils;
import org.apache.openejb.jee.DataSource;
import org.apache.openejb.jee.WebApp;
import org.apache.openejb.jee.WebFragment;
/**
* @version $Rev$ $Date$
*/
public class DataSourceMergeHandler implements WebFragmentMergeHandler<WebFragment, WebApp> {
@Override
public void merge(WebFragment webFragment, WebApp webApp, MergeContext mergeContext) throws DeploymentException {
for (DataSource srcDataSource : webFragment.getDataSource()) {
String dataSourceKey = createDataSourceKey(srcDataSource, mergeContext);
MergeItem mergeItem = (MergeItem) mergeContext.getAttribute(dataSourceKey);
if (mergeItem != null && mergeItem.isFromWebFragment()) {
throw new DeploymentException(WebDeploymentMessageUtils.createDuplicateJNDIRefMessage("data-source", srcDataSource.getName(), mergeContext.getCurrentJarUrl(), mergeItem
.getBelongedURL()));
}
webApp.getDataSource().add(srcDataSource);
mergeContext.setAttribute(dataSourceKey, new MergeItem(srcDataSource, mergeContext.getCurrentJarUrl(), ElementSource.WEB_FRAGMENT));
}
}
@Override
public void postProcessWebXmlElement(WebApp webApp, MergeContext context) throws DeploymentException {
}
@Override
public void preProcessWebXmlElement(WebApp webApp, MergeContext mergeContext) throws DeploymentException {
for (DataSource dataSource : webApp.getDataSource()) {
mergeContext.setAttribute(createDataSourceKey(dataSource, mergeContext), new MergeItem(dataSource, null, ElementSource.WEB_XML));
}
}
public static String createDataSourceKey(DataSource dataSource, MergeContext mergeContext) {
return "data-source.name." + dataSource.getName();
}
}
|
apache/geronimo
|
plugins/j2ee/geronimo-web-2.5-builder/src/main/java/org/apache/geronimo/web25/deployment/merge/webfragment/DataSourceMergeHandler.java
|
Java
|
apache-2.0
| 3,000 |
# */
# * 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.
# */
# URL Templates for Usergrid
#
# Get all events for a user:
# https://usergrid.net/beacon-sample/event-example/users/jeff/events
#
# Get only enterStore events:
# https://usergrid.net/beacon-sample/event-example/users/jeff/events?ql=select * where eventtype=‘enterStore'
#
# Get/filter beacon events for a user:
# https://usergrid.net/beacon-sample/event-example/users/jeff/events?ql=select * where eventtype=‘beacon'
#
# Get latest beacon event for user:
# https://usergrid.net/beacon-sample/event-example/users/jeff/events?ql=select * where eventtype=‘beacon’&limit=1
#
# Beacon events for store:
# https://usergrid.net/beacon-sample/event-example/users/jeff/events?ql=select * where eventtype=‘beacon'
#
# All events for store:
# https://usergrid.net/beacon-sample/event-example/stores/store_123/events
#
# All events for a beacon:
# https://usergrid.net/beacon-sample/event-example/beacons/store_456-b2/events
#
# Get Users who passed a specific beacon:
# https://usergrid.net/beacon-sample/event-example/beacons/3fd4fccb-d43b-11e5-978a-123320acb31f/events;ql=select%20* where profile=1/connecting/events/users
__author__ = '[email protected]'
import json
import random
import requests
from multiprocessing import Process, Pool
import time
collection_url_template = "{api_url}/{org}/{app}/{collection}"
entity_url_template = "{api_url}/{org}/{app}/{collection}/{entity_id}"
connection_query_url_template = "{api_url}/{org}/{app}/{collection}/{uuid}/{verb}"
connection_create_url_template = "{api_url}/{org}/{app}/{collection}/{uuid}/{verb}/{target_uuid}"
url_data = {
'api_url': 'https://usergridhost/basepath',
'org': 'samples',
'app': 'event-example'
}
session = requests.Session()
class EventGenerator(Process):
def __init__(self, store_id, event_count, user_array, beacons):
super(EventGenerator, self).__init__()
self.store_id = store_id
self.user_array = user_array
self.event_count = event_count
self.beacons = beacons
self.session = requests.Session()
self.create_store(self.store_id)
self.create_users(self.user_array)
def create_store(self, store_id):
url = entity_url_template.format(collection='stores', entity_id=store_id, **url_data)
r = self.session.put(url, data=json.dumps({"name": store_id}))
if r.status_code != 200:
print 'Error creating store [%s] at URL=[%s]: %s' % (store_id, url, r.text)
def create_event(self, user, event):
print 'creating event: %s' % json.dumps(event)
url = collection_url_template.format(collection='general-events', **url_data)
r = self.session.post(url, data=json.dumps(event))
if r.status_code == 200:
res = r.json()
entity = res.get('entities')[0]
event_uuid = entity.get('uuid')
# link to user
create_connection_url = connection_create_url_template.format(collection='users',
uuid=user,
verb='events',
target_uuid=event_uuid,
**url_data)
r_connect = self.session.post(create_connection_url)
if r_connect.status_code == 200:
print 'created connection: %s' % create_connection_url
# link to store
create_connection_url = connection_create_url_template.format(collection='stores',
uuid=event.get('storeId'),
verb='events',
target_uuid=event_uuid,
**url_data)
r_connect = self.session.post(create_connection_url)
if r_connect.status_code == 200:
print 'created connection: %s' % create_connection_url
if event.get('eventType') == 'beacon':
# link to beacon
create_connection_url = connection_create_url_template.format(collection='beacons',
uuid=event.get('beaconId'),
verb='events',
target_uuid=event_uuid,
**url_data)
r_connect = self.session.post(create_connection_url)
if r_connect.status_code == 200:
print 'created connection: %s' % create_connection_url
else:
print 'Error creating connection at URL=[%s]: %s' % (create_connection_url, r.text)
def run(self):
for user in self.user_array:
# store 123
self.create_event(user, {
'storeId': self.store_id,
'eventType': 'enterStore'
})
for x in xrange(0, self.event_count):
beacon_number = random.randint(0, len(self.beacons) - 1)
beacon_name = self.beacons[beacon_number]
event = {
'beaconId': '%s-%s' % (self.store_id, beacon_name),
'storeId': self.store_id,
'eventType': 'beacon'
}
self.create_event(user, event)
self.create_event(user, {
'storeId': self.store_id,
'eventType': 'exitStore'
})
def create_users(self, user_array):
for user in user_array:
self.create_user(user)
def create_user(self, user):
data = {
'username': user,
'email': '%[email protected]' % user
}
url = collection_url_template.format(collection='users', **url_data)
r = self.session.post(url, json.dumps(data))
if r.status_code != 200:
print 'Error creating user [%s] at URL=[%s]: %s' % (user, url, r.text)
def create_entity(entity_type, entity_name):
url = entity_url_template.format(collection=entity_type, entity_id=entity_name, **url_data)
r = session.put(url, data=json.dumps({'name': entity_name}))
if r.status_code != 200:
print 'Error creating %s [%s] at URL=[%s]: %s' % (entity_type, entity_name, url, r.text)
def create_beacon(beacon_name):
create_entity('beacons', beacon_name)
def create_store(store_name):
create_entity('stores', store_name)
def main():
beacons = ["b1", "b2", "b3", "b4", "b5", "b6"]
stores = ['store_123', 'store_456', 'store_789', 'store_901']
beacon_names = []
for store in stores:
for beacon in beacons:
beacon_names.append('%s-%s' % (store, beacon))
pool = Pool(16)
pool.map(create_beacon, beacon_names)
pool.map(create_store, stores)
processes = [
EventGenerator(stores[0], 100, ['jeff', 'julie'], beacons=beacons),
EventGenerator(stores[0], 100, ['russo', 'dunker'], beacons=beacons),
EventGenerator(stores[2], 100, ['jeff', 'julie'], beacons=beacons),
EventGenerator(stores[2], 100, ['russo', 'dunker'], beacons=beacons),
EventGenerator(stores[3], 100, ['jeff', 'julie'], beacons=beacons),
EventGenerator(stores[3], 100, ['russo', 'dunker'], beacons=beacons),
EventGenerator(stores[1], 100, ['bala', 'shankar'], beacons=beacons),
EventGenerator(stores[1], 100, ['chet', 'anant'], beacons=beacons)
]
[p.start() for p in processes]
while len([p for p in processes if p.is_alive()]) > 0:
print 'Processors active, waiting'
time.sleep(1)
main()
|
mdunker/usergrid
|
utils/usergrid-util-python/samples/beacon-event-example.py
|
Python
|
apache-2.0
| 8,908 |
/*
* Copyright (c) 2008-2020, Hazelcast, 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.
*/
package com.hazelcast.collection.impl.txncollection.operations;
import com.hazelcast.collection.impl.collection.CollectionContainer;
import com.hazelcast.collection.impl.collection.CollectionDataSerializerHook;
import com.hazelcast.collection.impl.collection.operations.CollectionOperation;
import com.hazelcast.internal.util.UUIDSerializationUtil;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import java.io.IOException;
import java.util.UUID;
public class CollectionTransactionRollbackOperation extends CollectionOperation {
private UUID transactionId;
public CollectionTransactionRollbackOperation() {
}
public CollectionTransactionRollbackOperation(String name, UUID transactionId) {
super(name);
this.transactionId = transactionId;
}
@Override
public void run() throws Exception {
CollectionContainer collectionContainer = getOrCreateContainer();
collectionContainer.rollbackTransaction(transactionId);
}
@Override
public int getClassId() {
return CollectionDataSerializerHook.TX_ROLLBACK;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
UUIDSerializationUtil.writeUUID(out, transactionId);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
transactionId = UUIDSerializationUtil.readUUID(in);
}
}
|
mdogan/hazelcast
|
hazelcast/src/main/java/com/hazelcast/collection/impl/txncollection/operations/CollectionTransactionRollbackOperation.java
|
Java
|
apache-2.0
| 2,136 |
/**
* 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.camel;
/**
* An exception caused by a specific message {@link Exchange}
*/
public class CamelExchangeException extends CamelException {
private static final long serialVersionUID = -8721487431101572630L;
// exchange is not guaranteed to be serializable so we set it as transient
private final transient Exchange exchange;
public CamelExchangeException(String message, Exchange exchange) {
super(CamelExchangeException.createExceptionMessage(message, exchange, null));
this.exchange = exchange;
}
public CamelExchangeException(String message, Exchange exchange, Throwable cause) {
super(CamelExchangeException.createExceptionMessage(message, exchange, cause), cause);
this.exchange = exchange;
}
/**
* Returns the exchange which caused the exception
*/
public Exchange getExchange() {
return exchange;
}
/**
* Creates an exception message with the provided details.
* <p/>
* All fields is optional so you can pass in only an exception, or just a message etc. or any combination.
*
* @param message the message
* @param exchange the exchange
* @param cause the caused exception
* @return an error message (without stacktrace from exception)
*/
public static String createExceptionMessage(String message, Exchange exchange, Throwable cause) {
StringBuilder sb = new StringBuilder();
if (message != null) {
sb.append(message);
}
if (exchange != null) {
if (sb.length() > 0) {
sb.append(". ");
}
sb.append(exchange);
}
if (cause != null) {
if (sb.length() > 0) {
sb.append(". ");
}
sb.append("Caused by: [" + cause.getClass().getName() + " - " + cause.getMessage() + "]");
}
return sb.toString().trim();
}
}
|
punkhorn/camel-upstream
|
core/camel-api/src/main/java/org/apache/camel/CamelExchangeException.java
|
Java
|
apache-2.0
| 2,766 |
/*
* Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors.
* 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.switchyard.component.common.knowledge.config.model.v1;
import static org.switchyard.component.common.knowledge.config.model.LoggerModel.LOGGER;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.namespace.QName;
import org.switchyard.component.common.knowledge.config.model.LoggerModel;
import org.switchyard.component.common.knowledge.config.model.LoggersModel;
import org.switchyard.config.Configuration;
import org.switchyard.config.model.BaseModel;
import org.switchyard.config.model.Descriptor;
/** A version 1 LoggersModel.
*
* @author David Ward <<a href="mailto:[email protected]">[email protected]</a>> © 2012 Red Hat Inc. */
public class V1LoggersModel extends BaseModel implements LoggersModel {
private List<LoggerModel> _loggers = new ArrayList<LoggerModel>();
/** Creates a new LoggersModel in the specified namespace.
*
* @param namespace the specified namespace */
public V1LoggersModel(String namespace) {
super(new QName(namespace, LOGGERS));
setModelChildrenOrder(LOGGER);
}
/** Creates a new LoggersModel with the specified configuration and descriptor.
*
* @param config the configuration
* @param desc the descriptor */
public V1LoggersModel(Configuration config, Descriptor desc) {
super(config, desc);
for (Configuration logger_config : config.getChildren(LOGGER)) {
LoggerModel logger = (LoggerModel)readModel(logger_config);
if (logger != null) {
_loggers.add(logger);
}
}
setModelChildrenOrder(LOGGER);
}
/** {@inheritDoc} */
@Override
public synchronized List<LoggerModel> getLoggers() {
return Collections.unmodifiableList(_loggers);
}
/** {@inheritDoc} */
@Override
public LoggersModel addLogger(LoggerModel logger) {
addChildModel(logger);
_loggers.add(logger);
return this;
}
}
|
cunningt/fuse-bxms-integ
|
switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1LoggersModel.java
|
Java
|
apache-2.0
| 2,637 |
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef GrGLTextureRenderTarget_DEFINED
#define GrGLTextureRenderTarget_DEFINED
#include "GrGLGpu.h"
#include "GrGLTexture.h"
#include "GrGLRenderTarget.h"
class GrGLGpu;
#ifdef SK_BUILD_FOR_WIN
// Windows gives bogus warnings about inheriting asTexture/asRenderTarget via dominance.
#pragma warning(push)
#pragma warning(disable: 4250)
#endif
class GrGLTextureRenderTarget : public GrGLTexture, public GrGLRenderTarget {
public:
// We're virtually derived from GrSurface (via both GrGLTexture and GrGLRenderTarget) so its
// constructor must be explicitly called.
GrGLTextureRenderTarget(GrGLGpu* gpu,
SkBudgeted budgeted,
const GrSurfaceDesc& desc,
const GrGLTexture::IDDesc& texIDDesc,
const GrGLRenderTarget::IDDesc& rtIDDesc)
: GrSurface(gpu, desc)
, GrGLTexture(gpu, desc, texIDDesc)
, GrGLRenderTarget(gpu, desc, rtIDDesc) {
this->registerWithCache(budgeted);
}
bool canAttemptStencilAttachment() const override;
void dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const override;
static GrGLTextureRenderTarget* CreateWrapped(GrGLGpu* gpu, const GrSurfaceDesc& desc,
const GrGLTexture::IDDesc& texIDDesc,
const GrGLRenderTarget::IDDesc& rtIDDesc);
protected:
void onAbandon() override {
GrGLRenderTarget::onAbandon();
GrGLTexture::onAbandon();
}
void onRelease() override {
GrGLRenderTarget::onRelease();
GrGLTexture::onRelease();
}
private:
// Constructor for instances wrapping backend objects.
GrGLTextureRenderTarget(GrGLGpu* gpu,
const GrSurfaceDesc& desc,
const GrGLTexture::IDDesc& texIDDesc,
const GrGLRenderTarget::IDDesc& rtIDDesc)
: GrSurface(gpu, desc)
, GrGLTexture(gpu, desc, texIDDesc)
, GrGLRenderTarget(gpu, desc, rtIDDesc) {
this->registerWithCacheWrapped();
}
// GrGLRenderTarget accounts for the texture's memory and any MSAA renderbuffer's memory.
size_t onGpuMemorySize() const override {
return GrGLRenderTarget::onGpuMemorySize();
}
};
#ifdef SK_BUILD_FOR_WIN
#pragma warning(pop)
#endif
#endif
|
tmpvar/skia.cc
|
src/gpu/gl/GrGLTextureRenderTarget.h
|
C
|
apache-2.0
| 2,564 |
package com.jlfex.hermes.common;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import com.jlfex.hermes.common.exception.NotSignInException;
import com.jlfex.hermes.common.exception.ServiceException;
import com.jlfex.hermes.common.utils.Strings;
/**
* 应用信息
*
*/
public abstract class App {
private static final String PATH_CONFIG = "/application.conf";
private static ThreadLocal<App> current = new ThreadLocal<App>();
private static Properties properties;
/**
* 读取用户
*
* @return
*/
public abstract AppUser getUser();
/**
* 设置用户
*
* @param user
*/
public abstract void setUser(AppUser user);
/**
* 读取令牌
*
* @return
*/
public abstract String getToken();
/**
* 更新令牌
*
* @return
*/
public abstract String updateToken();
/**
* 读取位置
*
* @return
*/
public abstract Locale getLocale();
/**
* 读取国际化消息
*
* @param key
* @param args
* @return
*/
public abstract String getMessage(String key, Object... args);
/**
* 读取当前应用信息
*
* @return
*/
public static App current() {
return current.get();
}
/**
* 读取当前应用信息
*
* @param requiredType
* @return
*/
public static <T extends App> T current(Class<T> requiredType) {
return requiredType.cast(current());
}
/**
* 设置当前应用信息
*
* @param value
* @return
*/
public static <T extends App> T set(T value) {
current.set(value);
return value;
}
/**
* 当前用户
*
* @return
*/
public static AppUser user() {
return current().getUser();
}
/**
* 检查用户
*/
public static void checkUser() {
if (user() == null) {
throw new NotSignInException();
}
}
/**
* 国际化消息
*
* @param key
* @param args
* @return
*/
public static String message(String key, Object... args) {
return current().getMessage(key, args);
}
/**
* 配置信息
*
* @param key
* @return
*/
public static String config(String key) {
if (properties == null) {
try {
properties = new Properties();
properties.load(App.class.getResourceAsStream(PATH_CONFIG));
} catch (IOException e) {
throw new ServiceException();
}
}
return properties.getProperty(key);
}
/**
* 配置信息<br>
* 若配置为空则返回默认值
*
* @param key
* @param defaultValue
* @return
*/
public static String config(String key, String defaultValue) {
return Strings.empty(config(key), defaultValue);
}
/**
* 设置配置信息
*
* @param values
*/
public static void config(Map<String, String> values) {
if (properties == null) config("0");
properties.putAll(values);
}
}
|
fuhongliang/hermes
|
hermes-common/src/main/java/com/jlfex/hermes/common/App.java
|
Java
|
apache-2.0
| 2,955 |
from flask import (
redirect, url_for, request, current_app, render_template_string, abort, render_template
)
from flask.globals import _app_ctx_stack, _request_ctx_stack
from werkzeug.urls import url_parse
def dispatch_aliases():
"""
When ALIASES_ENABLED == True
This method handle 3 Lingobarter features:
1. Fixed aliases
Alias is defined in ALIASES_MAP setting as a dictionary
2. Managed Redirects
Alias defined in database
3. Channel and Content aliases
Alias defined in specific channel or content
ALIASES_MAP
keys are long_slug
keys should always start with /
& end with / or extension.
{
"/team/": {
"alias_type": "endpoint|long_slug|url|string|template",
"action": "redirect|render",
"to": "authors|/articles/science.html|http://t.co|'<b>Hello</b>'",
"published": True,
"available_at": "",
"available_until: "",
}
}
- 'endpoint' and 'long_slug' by default are rendered
- 'url' is always redirect
- 'string' and 'template' are always rendered
"""
app = current_app
aliases_map = app.config.get('ALIASES_MAP')
if aliases_map and request.path in aliases_map:
alias = aliases_map[request.path]
status = alias.get('status', 200)
if alias['alias_type'] == 'endpoint':
endpoint = alias['to']
if alias.get('action') == 'redirect':
return redirect(url_for(endpoint, **request.args))
else: # render
return app.process_response(
app.make_response(
app.view_functions[endpoint]()
)
)
elif alias['alias_type'] == 'long_slug':
long_slug = alias['to']
if alias.get('action') == 'redirect':
return redirect(long_slug) # pass request.args ?
else: # render
endpoint = route_from(long_slug)[0]
return app.process_response(
app.make_response(
app.view_functions[endpoint]()
)
)
elif alias['alias_type'] == 'url':
return redirect(alias['to'])
elif alias['alias_type'] == 'string':
return render_template_string(alias['to']), status
elif alias['alias_type'] == 'template':
return render_template(alias['to']), status
def route_from(url, method=None):
appctx = _app_ctx_stack.top
reqctx = _request_ctx_stack.top
if appctx is None:
raise RuntimeError('Attempted to match a URL without the '
'application context being pushed. This has to be '
'executed when application context is available.')
if reqctx is not None:
adapter = reqctx.url_adapter
else:
adapter = appctx.url_adapter
if adapter is None:
raise RuntimeError('Application was not able to create a URL '
'adapter for request independent URL matching. '
'You might be able to fix this by setting '
'the SERVER_NAME config variable.')
parsed = url_parse(url)
if parsed.netloc is not "" and parsed.netloc != adapter.server_name:
abort(404)
return adapter.match(parsed.path, method)
|
LeightonStreet/LeightonStreet
|
lingobarter/utils/aliases.py
|
Python
|
apache-2.0
| 3,464 |
FROM balenalib/aarch64-fedora:33-build
LABEL io.balena.device-type="photon-nano"
RUN dnf install -y \
less \
nano \
net-tools \
usbutils \
gnupg \
i2c-tools \
&& dnf clean all
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: ARM v8 \nOS: Fedora 33 \nVariant: build variant \nDefault variable(s): UDEV=off \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/device-base/photon-nano/fedora/33/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 999 |
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
# Copyright (C) 2014 TrilioData, 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.
from http import client as http_client
import os
import socket
import tempfile
from oslo_utils.secretutils import md5
from swiftclient import client as swift
class FakeSwiftClient2(object):
def __init__(self, *args, **kwargs):
pass
@classmethod
def Connection(cls, *args, **kargs):
return FakeSwiftConnection2()
class FakeSwiftConnection2(object):
def __init__(self, *args, **kwargs):
self.tempdir = tempfile.mkdtemp()
def head_container(self, container):
if container == 'missing_container':
raise swift.ClientException('fake exception',
http_status=http_client.NOT_FOUND)
elif container == 'unauthorized_container':
raise swift.ClientException('fake exception',
http_status=http_client.UNAUTHORIZED)
elif container == 'socket_error_on_head':
raise socket.error(111, 'ECONNREFUSED')
def put_container(self, container, headers=None):
pass
def get_container(self, container, **kwargs):
fake_header = None
container_dir = tempfile.gettempdir() + '/' + container
fake_body = []
for f in os.listdir(container_dir):
try:
f.index(kwargs['prefix'])
fake_body.append({'name': f})
except Exception:
pass
return fake_header, fake_body
def head_object(self, container, name):
return {'etag': 'fake-md5-sum'}
def get_object(self, container, name):
if container == 'socket_error_on_get':
raise socket.error(111, 'ECONNREFUSED')
object_path = tempfile.gettempdir() + '/' + container + '/' + name
with open(object_path, 'rb') as object_file:
return (None, object_file.read())
def put_object(self, container, name, reader, content_length=None,
etag=None, chunk_size=None, content_type=None,
headers=None, query_string=None):
object_path = tempfile.gettempdir() + '/' + container + '/' + name
with open(object_path, 'wb') as object_file:
object_file.write(reader.read())
return md5(reader.read(), usedforsecurity=False).hexdigest()
def delete_object(self, container, name):
pass
|
openstack/cinder
|
cinder/tests/unit/backup/fake_swift_client2.py
|
Python
|
apache-2.0
| 3,040 |
# example-jpa_insert_on_merge
Beispiel welches aufzeigt wie sich Hibernate und Eclipselink bei merge() verhält
|
StefanHeimberg/example-jpa_insert_on_merge
|
README.md
|
Markdown
|
apache-2.0
| 112 |
/*
* 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.tomcat.util.net;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.junit.Assert;
import org.junit.Test;
import org.apache.tomcat.util.net.TLSClientHelloExtractor.ExtractorResult;
public class TestTLSClientHelloExtractor {
@Test
public void testInputNeedRead01() throws IOException {
ByteBuffer testInput = ByteBuffer.allocate(1024);
doTestInputNeedRead(testInput);
}
@Test(expected=IOException.class)
public void testInputMalformed01() throws IOException {
ByteBuffer testInput = ByteBuffer.allocate(1024);
// TLS handshake
testInput.put((byte) 22);
// TLS 1.0
testInput.put((byte) 3);
testInput.put((byte) 1);
// Record length 0 (correct, but not legal)
testInput.put((byte) 0);
testInput.put((byte) 0);
doTestInputNeedRead(testInput);
}
@Test(expected=IOException.class)
public void testInputMalformed02() throws IOException {
ByteBuffer testInput = ByteBuffer.allocate(1024);
// TLS handshake
testInput.put((byte) 22);
// TLS 1.0
testInput.put((byte) 3);
testInput.put((byte) 1);
// Record length 4
testInput.put((byte) 0);
testInput.put((byte) 4);
// Type 1 (client hello)
testInput.put((byte) 1);
// Client hello size 0 (correct, but not legal)
testInput.put((byte) 0);
testInput.put((byte) 0);
testInput.put((byte) 0);
doTestInputNeedRead(testInput);
}
public void doTestInputMalformed(ByteBuffer input) throws IOException {
TLSClientHelloExtractor extractor = new TLSClientHelloExtractor(input);
// Expect this to fail
extractor.getResult();
}
public void doTestInputNeedRead(ByteBuffer input) throws IOException {
TLSClientHelloExtractor extractor = new TLSClientHelloExtractor(input);
// Expect this to fail
ExtractorResult result = extractor.getResult();
Assert.assertEquals(ExtractorResult.NEED_READ, result);
}
}
|
apache/tomcat
|
test/org/apache/tomcat/util/net/TestTLSClientHelloExtractor.java
|
Java
|
apache-2.0
| 2,924 |
{% load i18n %}{% load url from future %}{% autoescape off %}
{% blocktrans %}You're receiving this e-mail because you requested a password reset for your user account at Nanolearning.{% endblocktrans %}
{% trans "Please go to the following page and choose a new password:" %}
{% block reset_link %}
http{% if is_secure %}s{% endif %}://{{domain}}{% url 'student.views.password_reset_confirm_wrapper' uidb36=uid token=token %}
{% endblock %}
If you didn't request this change, you can disregard this email - we have not yet reset your password.
{% trans "Thanks for using our site!" %}
{% blocktrans %}The Nanolearning Team{% endblocktrans %}
{% endautoescape %}
|
appliedx/edx-theme
|
templates/registration/password_reset_email.html
|
HTML
|
apache-2.0
| 668 |
package com.payneteasy.superfly.api;
/**
* Thrown if a message could not be sent.
*
* @author Roman Puchkovskiy
* @since 1.2-4
*/
public class MessageSendException extends SSOException {
public MessageSendException() {
super();
}
public MessageSendException(String message, Throwable cause) {
super(message, cause);
}
public MessageSendException(String message) {
super(message);
}
public MessageSendException(Throwable cause) {
super(cause);
}
}
|
rpuch/superfly
|
superfly-remote-api/src/main/java/com/payneteasy/superfly/api/MessageSendException.java
|
Java
|
apache-2.0
| 522 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.