code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
/**
* OBJECT_ID.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package org.openehr.schemas.v1;
public abstract class OBJECT_ID implements java.io.Serializable {
private org.apache.axis.types.Token value;
public OBJECT_ID() {
}
public OBJECT_ID(
org.apache.axis.types.Token value) {
this.value = value;
}
/**
* Gets the value value for this OBJECT_ID.
*
* @return value
*/
public org.apache.axis.types.Token getValue() {
return value;
}
/**
* Sets the value value for this OBJECT_ID.
*
* @param value
*/
public void setValue(org.apache.axis.types.Token value) {
this.value = value;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof OBJECT_ID)) return false;
OBJECT_ID other = (OBJECT_ID) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.value==null && other.getValue()==null) ||
(this.value!=null &&
this.value.equals(other.getValue())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getValue() != null) {
_hashCode += getValue().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(OBJECT_ID.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://schemas.openehr.org/v1", "OBJECT_ID"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("value");
elemField.setXmlName(new javax.xml.namespace.QName("http://schemas.openehr.org/v1", "value"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "token"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| josealmeida/opereffa | bosphorus/src/main/resources/org/openehr/schemas/v1/OBJECT_ID.java | Java | apache-2.0 | 3,452 |
package collections;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class Iterator2 {
public static void main(String args[]) {
List<String> list = new ArrayList<String>();
list.add("abc");
list.add("def");
list.add("ghi");
ListIterator<String> iter =
list.listIterator(list.size());
while (iter.hasPrevious())
System.out.println(iter.previous());
}
}
| rboese/prog | collections/src/main/java/collections/Iterator2.java | Java | apache-2.0 | 482 |
/*
* © Crown Copyright 2013
*
* 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 uk.nhs.hdn.ckan.schema;
import org.jetbrains.annotations.NotNull;
import uk.nhs.hdn.ckan.domain.uniqueNames.TagName;
import uk.nhs.hdn.common.parsers.json.ArrayJsonSchema;
import uk.nhs.hdn.common.parsers.json.jsonParseEventHandlers.constructors.arrayConstructors.ConvertUsingDelegateListCollectingStringArrayConstructor;
import uk.nhs.hdn.common.parsers.json.jsonParseEventHandlers.constructors.arrayConstructors.root.ArrayRootArrayConstructor;
import static uk.nhs.hdn.ckan.schema.arrayCreators.TagArrayCreator.TagArray;
import static uk.nhs.hdn.common.parsers.json.jsonParseEventHandlers.constructors.arrayConstructors.ConvertUsingDelegateListCollectingStringArrayConstructor.convertUsingDelegateListCollectingStringArrayConstructor;
import static uk.nhs.hdn.common.parsers.json.jsonParseEventHandlers.constructors.arrayConstructors.root.NonNullArrayRootArrayConstructor.rootIsArrayOf;
public final class TagsArrayJsonSchema extends ArrayJsonSchema<TagName>
{
@NotNull
public static final ConvertUsingDelegateListCollectingStringArrayConstructor<TagName> ArrayOfTagsConstructor = convertUsingDelegateListCollectingStringArrayConstructor(TagArray, TagName.class);
@NotNull
public static final ArrayRootArrayConstructor<TagName> TagsSchema = rootIsArrayOf
(
TagArray,
ArrayOfTagsConstructor
);
@NotNull
public static final ArrayJsonSchema<TagName> TagsSchemaInstance = new TagsArrayJsonSchema();
private TagsArrayJsonSchema()
{
super(TagsSchema);
}
}
| health-and-care-developer-network/health-and-care-developer-network | source/ckan/ckan-schema/uk/nhs/hdn/ckan/schema/TagsArrayJsonSchema.java | Java | apache-2.0 | 2,076 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_15) on Sat May 04 07:11:50 UTC 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class uk.nhs.interoperability.client.samples.smsp.GetPatientDetailsByNHSNumberServlet (ITK Samples project 0.1-SNAPSHOT API)</title>
<meta name="date" content="2013-05-04">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class uk.nhs.interoperability.client.samples.smsp.GetPatientDetailsByNHSNumberServlet (ITK Samples project 0.1-SNAPSHOT API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../uk/nhs/interoperability/client/samples/smsp/GetPatientDetailsByNHSNumberServlet.html" title="class in uk.nhs.interoperability.client.samples.smsp">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?uk/nhs/interoperability/client/samples/smsp/class-use/GetPatientDetailsByNHSNumberServlet.html" target="_top">Frames</a></li>
<li><a href="GetPatientDetailsByNHSNumberServlet.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class uk.nhs.interoperability.client.samples.smsp.GetPatientDetailsByNHSNumberServlet" class="title">Uses of Class<br>uk.nhs.interoperability.client.samples.smsp.GetPatientDetailsByNHSNumberServlet</h2>
</div>
<div class="classUseContainer">No usage of uk.nhs.interoperability.client.samples.smsp.GetPatientDetailsByNHSNumberServlet</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../uk/nhs/interoperability/client/samples/smsp/GetPatientDetailsByNHSNumberServlet.html" title="class in uk.nhs.interoperability.client.samples.smsp">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?uk/nhs/interoperability/client/samples/smsp/class-use/GetPatientDetailsByNHSNumberServlet.html" target="_top">Frames</a></li>
<li><a href="GetPatientDetailsByNHSNumberServlet.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>All content is available under the <a href="http://www.nationalarchives.gov.uk/doc/open-government-licence/" title="Open Government Licence">Open Government Licence</a>, except where otherwise stated<br/>
All example source code is available under <a href="http://www.apache.org/licenses/LICENSE-2.0.html" title="Apache 2.0 License">Apache 2.0</a>, except where otherwise stated</small></p>
</body>
</html>
| health-and-care-developer-network/health-and-care-developer-network | source/build/package-templates/hdn-itk-documentation/hdn-itk-documentation/srv/hdn-itk-documentation/itk/itk-samples/apidocs/uk/nhs/interoperability/client/samples/smsp/class-use/GetPatientDetailsByNHSNumberServlet.html | HTML | apache-2.0 | 5,284 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.data;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.AbstractProgressIndicatorBase;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.util.VcsLogUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Consumer;
public class VcsLogProgress implements Disposable {
@NotNull private final Object myLock = new Object();
@NotNull private final List<ProgressListener> myListeners = ContainerUtil.newArrayList();
@NotNull private final Set<VcsLogProgressIndicator> myTasksWithVisibleProgress = ContainerUtil.newHashSet();
@NotNull private final Set<ProgressIndicator> myTasksWithSilentProgress = ContainerUtil.newHashSet();
private boolean myDisposed = false;
public VcsLogProgress(@NotNull Project project, @NotNull Disposable parent) {
VcsLogUtil.registerWithParentAndProject(parent, project, this);
}
@NotNull
public ProgressIndicator createProgressIndicator(@NotNull ProgressKey key) {
return createProgressIndicator(true, key);
}
@NotNull
public ProgressIndicator createProgressIndicator(boolean visible, @NotNull ProgressKey key) {
if (ApplicationManager.getApplication().isHeadlessEnvironment()) {
return new EmptyProgressIndicator();
}
return new VcsLogProgressIndicator(visible, key);
}
public void addProgressIndicatorListener(@NotNull ProgressListener listener, @Nullable Disposable parentDisposable) {
synchronized (myLock) {
myListeners.add(listener);
if (parentDisposable != null) {
Disposer.register(parentDisposable, () -> removeProgressIndicatorListener(listener));
}
if (isRunning()) {
Set<ProgressKey> keys = getRunningKeys();
ApplicationManager.getApplication().invokeLater(() -> listener.progressStarted(keys));
}
}
}
public void removeProgressIndicatorListener(@NotNull ProgressListener listener) {
synchronized (myLock) {
myListeners.remove(listener);
}
}
public boolean isRunning() {
synchronized (myLock) {
return !myTasksWithVisibleProgress.isEmpty();
}
}
@NotNull
public Set<ProgressKey> getRunningKeys() {
synchronized (myLock) {
return ContainerUtil.map2Set(myTasksWithVisibleProgress, VcsLogProgressIndicator::getKey);
}
}
private void started(@NotNull VcsLogProgressIndicator indicator) {
synchronized (myLock) {
if (myDisposed) {
indicator.cancel();
return;
}
if (indicator.isVisible()) {
Set<ProgressKey> oldKeys = getRunningKeys();
myTasksWithVisibleProgress.add(indicator);
if (myTasksWithVisibleProgress.size() == 1) {
ProgressKey key = indicator.getKey();
fireNotification(listener -> listener.progressStarted(Collections.singleton(key)));
}
else {
keysUpdated(oldKeys);
}
}
else {
myTasksWithSilentProgress.add(indicator);
}
}
}
private void stopped(@NotNull VcsLogProgressIndicator indicator) {
synchronized (myLock) {
if (indicator.isVisible()) {
myTasksWithVisibleProgress.remove(indicator);
if (myTasksWithVisibleProgress.isEmpty()) fireNotification(ProgressListener::progressStopped);
}
else {
myTasksWithSilentProgress.remove(indicator);
}
}
}
private void keysUpdated(@NotNull Set<ProgressKey> oldKeys) {
synchronized (myLock) {
Set<ProgressKey> newKeys = getRunningKeys();
if (!oldKeys.equals(newKeys)) {
fireNotification(listener -> listener.progressChanged(newKeys));
}
}
}
private void fireNotification(@NotNull Consumer<? super ProgressListener> action) {
synchronized (myLock) {
List<ProgressListener> list = ContainerUtil.newArrayList(myListeners);
ApplicationManager.getApplication().invokeLater(() -> list.forEach(action));
}
}
@Override
public void dispose() {
synchronized (myLock) {
myDisposed = true;
for (ProgressIndicator indicator : myTasksWithVisibleProgress) {
indicator.cancel();
}
for (ProgressIndicator indicator : myTasksWithSilentProgress) {
indicator.cancel();
}
}
}
private class VcsLogProgressIndicator extends AbstractProgressIndicatorBase {
@NotNull private ProgressKey myKey;
private final boolean myVisible;
private VcsLogProgressIndicator(boolean visible, @NotNull ProgressKey key) {
myKey = key;
myVisible = visible;
if (!visible) dontStartActivity();
}
@Override
public synchronized void start() {
super.start();
started(this);
}
@Override
public synchronized void stop() {
super.stop();
stopped(this);
}
public void updateKey(@NotNull ProgressKey key) {
synchronized (myLock) {
Set<ProgressKey> oldKeys = getRunningKeys();
myKey = key;
keysUpdated(oldKeys);
}
}
public boolean isVisible() {
return myVisible;
}
@NotNull
public ProgressKey getKey() {
synchronized (myLock) {
return myKey;
}
}
}
public interface ProgressListener {
void progressStarted(@NotNull Collection<? extends ProgressKey> keys);
void progressChanged(@NotNull Collection<? extends ProgressKey> keys);
void progressStopped();
}
public static class ProgressKey {
@NotNull private final String myName;
public ProgressKey(@NotNull String name) {
myName = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProgressKey key = (ProgressKey)o;
return Objects.equals(myName, key.myName);
}
@Override
public int hashCode() {
return Objects.hash(myName);
}
}
public static void updateCurrentKey(@NotNull ProgressKey key) {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator instanceof VcsLogProgressIndicator) {
((VcsLogProgressIndicator)indicator).updateKey(key);
}
}
}
| msebire/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsLogProgress.java | Java | apache-2.0 | 6,698 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.dynamodbv2.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* GetItemResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetItemResultJsonUnmarshaller implements Unmarshaller<GetItemResult, JsonUnmarshallerContext> {
public GetItemResult unmarshall(JsonUnmarshallerContext context) throws Exception {
GetItemResult getItemResult = new GetItemResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return getItemResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Item", targetDepth)) {
context.nextToken();
getItemResult.setItem(new MapUnmarshaller<String, AttributeValue>(context.getUnmarshaller(String.class), AttributeValueJsonUnmarshaller
.getInstance()).unmarshall(context));
}
if (context.testExpression("ConsumedCapacity", targetDepth)) {
context.nextToken();
getItemResult.setConsumedCapacity(ConsumedCapacityJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return getItemResult;
}
private static GetItemResultJsonUnmarshaller instance;
public static GetItemResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new GetItemResultJsonUnmarshaller();
return instance;
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/transform/GetItemResultJsonUnmarshaller.java | Java | apache-2.0 | 3,100 |
/*
* Copyright 2010-2020 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.
*/
package org.activiti.engine.impl.cfg.multitenant;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.activiti.engine.ActivitiException;
/**
* A {@link DataSource} implementation that switches the currently used datasource based on the
* current values of the {@link TenantInfoHolder}.
*
* When a {@link Connection} is requested from this {@link DataSource}, the correct {@link DataSource}
* for the current tenant will be determined and used.
*
* Heavily influenced and inspired by Spring's AbstractRoutingDataSource.
*
* @deprecated multi-tenant code will be removed in future version of Activiti and Activiti Cloud
*/
@Deprecated
public class TenantAwareDataSource implements DataSource {
protected TenantInfoHolder tenantInfoHolder;
protected Map<Object, DataSource> dataSources = new HashMap<Object, DataSource>();
public TenantAwareDataSource(TenantInfoHolder tenantInfoHolder) {
this.tenantInfoHolder = tenantInfoHolder;
}
public void addDataSource(Object key, DataSource dataSource) {
dataSources.put(key, dataSource);
}
public void removeDataSource(Object key) {
dataSources.remove(key);
}
public Connection getConnection() throws SQLException {
return getCurrentDataSource().getConnection();
}
public Connection getConnection(String username, String password) throws SQLException {
return getCurrentDataSource().getConnection(username, password);
}
protected DataSource getCurrentDataSource() {
String tenantId = tenantInfoHolder.getCurrentTenantId();
DataSource dataSource = dataSources.get(tenantId);
if (dataSource == null) {
throw new ActivitiException("Could not find a dataSource for tenant " + tenantId);
}
return dataSource;
}
public int getLoginTimeout() throws SQLException {
return 0; // Default
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
}
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.isInstance(this)) {
return (T) this;
}
throw new SQLException("Cannot unwrap " + getClass().getName() + " as an instance of " + iface.getName());
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this);
}
public Map<Object, DataSource> getDataSources() {
return dataSources;
}
public void setDataSources(Map<Object, DataSource> dataSources) {
this.dataSources = dataSources;
}
// Unsupported //////////////////////////////////////////////////////////
public PrintWriter getLogWriter() throws SQLException {
throw new UnsupportedOperationException();
}
public void setLogWriter(PrintWriter out) throws SQLException {
throw new UnsupportedOperationException();
}
public void setLoginTimeout(int seconds) throws SQLException {
throw new UnsupportedOperationException();
}
}
| Activiti/Activiti | activiti-core/activiti-engine/src/main/java/org/activiti/engine/impl/cfg/multitenant/TenantAwareDataSource.java | Java | apache-2.0 | 3,773 |
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"dice":[function(require,module,exports){
module.exports=require('lKdn7H');
},{}],"lKdn7H":[function(require,module,exports){
(function(undefined){
/**
*
*/
var utils = require('../utils');
var dice = {};
var defaults = dice.defaults = {
numberOfDie : 1,
typeOfDie : 6,
modifier : 0
}
var die = dice.die = {};
for (var i = 2; i < 101; ++i) {
die['d'+i] = utils.randomize(1, i);
}
var roll = dice.roll = function(numberOfDie, typeOfDie, modifier){
numberOfDie = numberOfDie || defaults.numberOfDie;
typeOfDie = typeOfDie || defaults.typeOfDie;
modifier = modifier || defaults.modifier;
var ret = {
multiple: numberOfDie,
typeOfDie : typeOfDie,
modifier: modifier,
rolls : [],
value : 0
};
var roll = die['d' + typeOfDie];
for(var i = 1; i < numberOfDie + 1; ++i) {
var result = roll();
ret.rolls.push(result);
ret.value += result;
}
ret.value += modifier;
return ret;
}
var createRoll = dice.createRoll = function(numberOfDie, typeOfDie, modifier){
numberOfDie = numberOfDie || defaults.numberOfDie;
typeOfDie = typeOfDie || defaults.typeOfDie;
modifier = modifier || defaults.modifier;
return function() {
return exports.roll(numberOfDie, typeOfDie, modifier);
}
}
var parseString = dice.parseString = function(str) {
if (!!str && str.indexOf('d') > -1) {
var typeOfDice = str.split('d');
var numberOfDice = typeOfDice[0];
typeOfDice = typeOfDice[1];
var modifier = 0;
if (typeOfDice.indexOf('m') > -1) {
modifier = typeOfDice.split('m');
typeOfDice = modifier[0];
if (modifier.length > 1) {
modifier = modifier[1];
} else {
modifier = 0;
}
// console.log(modifier)
}
numberOfDice = parseInt(numberOfDice.toString());
typeOfDice = parseInt(typeOfDice.toString());
modifier = parseInt(modifier.toString());
if (isNaN(numberOfDice)) {
throw new Error("The number of dice is not a number!");
} else if (isNaN(typeOfDice)) {
throw new Error("The type of dice is not a number!");
} else if (isNaN(modifier)) {
throw new Error("The modifier is not a number!");
} else {
return dice.roll(numberOfDice, typeOfDice, modifier);
}
} else {
throw new Error("usage: pass the number of dice, type of dice, and modifier like so: 2d6m-8\nexample: parseString('2d6m-8') or parseString('3d6')");
}
}
var test = dice.test = function(diceSetup, iterations){
iterations = iterations || 100;
var results = {};
var performance = new util.performance();
for(var j = 0; j < diceSetup.length; ++j) {
performance.start();
var multiple = diceSetup[j][0] || defaults.numberOfDie;
var die = diceSetup[j][1] || defaults.typeOfDie;
var modifier = diceSetup[j][2] || defaults.modifier;
console.log("Iterating "+iterations+" times over "+ multiple + 'd' + die + '+' + modifier);
for (var i = 0; i < iterations; ++i) {
var result = exports.roll(multiple, die, modifier);
if (!results[result.value.toString()]) {
results[result.value.toString()] = 0;
}
++(results[result.value.toString()]);
}
console.log(results);
results = {};
console.log('This test took ' + performance.end('ms') + ' ms.')
}
}
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = dice;
} else {
this.dice = dice;
}
})();
},{"../utils":3}],3:[function(require,module,exports){
(function (process){
(function(undefined){
var _utils = require('util');
var utils = {};
// Util methods
utils.bind = function(props) {
for(var key in props) {
this[key] = props[key];
}
}
utils.bind(_utils);
utils.inspect = function(obj, showHidden, depth) {
if (arguments.length == 1) {
showHidden = true;
}
if (arguments.length == 2) {
depth = null;
}
return _utils.inspect(obj, { showHidden: showHidden, depth: depth });
};
utils.censor = function(censor) {
var i = 0;
return function(key, value) {
if(i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value)
return '[Circular]';
if(i >= 29) // seems to be a harded maximum of 30 serialized objects?
return '[Unknown]';
++i; // so we know we aren't using the original object anymore
return value;
}
}
utils.assert = function(condition, message) {
if (!condition) {
console.log(testing);
throw new Error(message || "Assertion failed");
}
return true;
};
/**
*/
utils.randomize = function(min, max, bAsInt) {
min = min || 0;
max = max || 1;
bAsInt = bAsInt || true;
return function() {
if (bAsInt) {
return (Math.floor(Math.random() * (max - min + 1))) + min;
} else {
return (Math.random() * (max - min)) + min;
}
}
}
utils.performance = function() {
var start = process.hrtime();
this.start = function() {
start = process.hrtime();
}
this.end = function(format) {
var diff = process.hrtime(start);
switch(format) {
case "seconds" :
case "s" :
return ((diff[0] * 1e9 + diff[1]) / 1000000000);
break;
case "milliseconds" :
case "ms" :
return ((diff[0] * 1e9 + diff[1]) / 1000000);
break;
case "nanoseconds" :
case "ns" :
default :
return (diff[0] * 1e9 + diff[1]);
break;
}
}
}
/* Returns a number between 0 and 100 */
utils.getPercent = function(numerator, denominator) {
return denominator > 0 ? numerator / denominator * 100 : 0;
}
utils.cloneObject = function(obj) {
var ret = {};
try {
return JSON.parse(JSON.stringify(obj));
} catch (ex) {
for (var key in obj) {
ret[key] = obj[key];
}
return ret;
}
return null;
}
utils.thread = function(fn) {
setTimeout(fn, 20);
}
utils.flipFlop = function(val) {
val = !!val;
val = 1 - val;
return val;
}
utils.trim = function(str) {
return (str || "").toString().replace(/^\s+|\s+$/g, '');
}
utils.clean = function(str) {
return (str || "").toString().replace(/\s+/g, ' ').trim();
}
utils.getValue = function(data, key, defaultVal) {
defaultVal = defaultVal || "";
if (!data || data[key] === null)
return defaultVal;
return data[key];
}
utils.isValidDate = function(date) {
return Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime());
}
utils.slice = function(args, start, finish) {
return Array.prototype.slice.call(args, start, finish || args.length);
}
utils.proto = function(obj, o) {
obj = obj || {};
for (var n in o) {
var v = o[n];
if (n) {
obj.prototype[n] = v;
}
}
return obj;
}
utils.merge = function(obj, o) {
obj = obj || {};
for (var n in o) {
var v = o[n];
if (n) {
obj[n] = v;
}
}
return obj;
}
utils.each = function(arr, fn, bind) {
if (!arr) throw "Argument must be a valid variable";
switch (typeof arr) {
case "array":
for (var i = 0, l = arr.length; i < l; i++) {
if (i in arr)
fn.call(bind, arr[i], i, arr);
}
break;
case "object":
for (var key in arr) {
if (Object.prototype.hasOwnProperty.call(arr, key))
fn.call(bind, arr[key], key, arr);
}
break;
case "string":
case "number":
var chars = arr.toString().split('');
for (var i = 0, l = chars.length; i < l; i++) {
if (i in chars)
fn.call(bind, chars[i], i, chars);
}
break;
default:
}
}
/**
* Randomize array element order in-place.
* Using Fisher-Yates shuffle algorithm.
*/
utils.shuffleArray = function(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
/**
*
*/
utils.isNumber = function(num) {
return !isNaN(num);
}
/**
*
*/
utils.toInt = function(thing) {
var ret = thing;
if (typeof ret == 'string') {
ret = parseInt(ret);
} else if (typeof ret == 'object') {
ret = parseInt(ret.toString())
if (isNaN(ret)) {
ret = parseInt(ret.valueOf());
}
} else if (typeof ret == 'function') {
ret = ret();
} else if (typeof ret == 'number') {
return ret;
}
if (isNaN(ret)) {
console.log("The argument cannot be converted to a number!");
return null;
} else {
return ret;
}
}
utils.capitaliseFirstLetter = function(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = utils;
} else {
this.utils = utils;
}
})();
}).call(this,require("JkpR2F"))
},{"JkpR2F":5,"util":7}],4:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],5:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],6:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],7:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require("JkpR2F"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":6,"JkpR2F":5,"inherits":4}],8:[function(require,module,exports){
// var dice = require('../../../../../../../src/tools/dice.js');
// var characterGen = require('./character');
},{}],"character":[function(require,module,exports){
module.exports=require('IWB0J1');
},{}],"IWB0J1":[function(require,module,exports){
(function(undefined){
function newCharacter() {
return {
Name : '',
Age : 18,
ExtraAttributePoints : 96,
Attributes : {
Strength: 9,
Perception: 9,
Endurance: 9,
Charisma: 9,
Intelligence: 9,
Agility: 9,
Luck: 9,
Willpower: 9
},
HitPoints : function(){
return 15 + this.Attributes.Strength + (this.Attributes.Endurance * 2)
},
Size : function(){
return (this.Attributes.Strength + this.Attributes.Endurance) / 2
},
MovementSpeed : function(){ //in feet per 1 second
return Math.max(1 + this.Attributes.Agility - this.CurrentDamage(), 0);
},
MaxCarryWeight : function(){
return 12 * this.Attributes.Strength
},
Spirit : function(){
return (this.Attributes.Luck / 2) + this.Attributes.Willpower + (this.Attributes.Intelligence / 2) + this.Attributes.Perception
},
Sanity : function(){
return (this.Attributes.Willpower + this.Attributes.Luck) * 4 - this.Attributes.Perception
},
AttackSpeed : function() { //In half seconds
return Math.max(20 - this.Attributes.Agility + this.CurrentDamage(), 1);
},
Skills : {
"Firearms" : function(){
return CreationCharacter.Attributes.Agility + 10
},
"Archery" : function(){
return 2 + (CreationCharacter.Attributes.Agility * 2) + (CreationCharacter.Attributes.Strength / 2)
},
"Explosives" : function(){
return 2 + (CreationCharacter.Attributes.Perception * 2) + (CreationCharacter.Attributes.Luck / 2)
},
"Melee" : function(){
return 30 + (2 * CreationCharacter.Attributes.Agility) + (2 * CreationCharacter.Attributes.Strength)
},
"Throwing" : function(){
return 4 * CreationCharacter.Attributes.Agility
},
"Lockpick" : function(){
return 20 + (CreationCharacter.Attributes.Perception / 2) + (CreationCharacter.Attributes.Agility / 2)
},
"Mechanics" : function(){
return 20 + CreationCharacter.Attributes.Intelligence
},
"Medicine" : function(){
return 2 + (CreationCharacter.Attributes.Intelligence * 2) + (CreationCharacter.Attributes.Luck / 2)
},
"Science" : function(){
return 2 + (CreationCharacter.Attributes.Intelligence * 2) + (CreationCharacter.Attributes.Luck / 2)
},
"Craftsmanship" : function(){
return (CreationCharacter.Attributes.Intelligence / 2) + (CreationCharacter.Attributes.Luck / 2) + (CreationCharacter.Attributes.Perception / 2) + (CreationCharacter.Attributes.Agility / 2)
},
"Stealth" : function(){
return 2 + (CreationCharacter.Attributes.Agility * 2) + (CreationCharacter.Attributes.Luck / 2)
},
"Survival" : function(){
return 2 + CreationCharacter.Attributes.Endurance + CreationCharacter.Attributes.Intelligence + (CreationCharacter.Attributes.Luck / 2)
},
"Barter" : function(){
return 2 + (CreationCharacter.Attributes.Charisma * 2) + (CreationCharacter.Attributes.Luck / 2)
},
"Speech" : function(){
return 2 + (CreationCharacter.Attributes.Charisma * 2) + (CreationCharacter.Attributes.Luck / 2)
},
"Athletics" : function(){
return 2 + CreationCharacter.Attributes.Agility + CreationCharacter.Attributes.Strength + (CreationCharacter.Attributes.Endurance / 2)
},
"History" : function(){
return 2 + (CreationCharacter.Attributes.Intelligence * 2) + (CreationCharacter.Attributes.Perception / 2)
}
},
Specializations : {
"Firearms" : {
"General" : 0,
"Pistol" : -10,
"Submachine Gun" : -15,
"Rifle" : -5,
"Machine Gun" : -15
},
"Archery" : {
"General" : -10,
"Bow" : -10,
"Crossbow" : -5
},
"Explosives" : {
"General" : -20
},
"Melee" : {
"General" : 0,
"Shield" : -10,
"Spear" : -15,
"Knife" : -5,
"Sword" : -10,
"Axe" : -15,
"Hammer" : -10,
"Kung Fu" : -35
},
"Throwing" : {
"General" : 0,
"Spear" : -20,
"Knife" : -10,
"Axe" : -20
},
"Lockpick" : {
"General" : 0
},
"Mechanics" : {
"General" : 0,
"Combustion" : -10,
"Hydraulic" : -20
},
"Medicine" : {
"General" : 0,
"First Aid" : -5
},
"Science" : {
"General" : 0,
"Botany" : -10,
"Mineral" : -15,
"Electronic" : -20,
"Computer" : -10,
"Physics" : -10,
"Nuclear" : -35,
"Rocket" : -50
},
"Craftsmanship" : {
"General" : 0,
"Boatsmithing" : -20,
"Leathersmithing" : 0,
"Armorsmithing" : -10,
"Bladesmithing" : -15,
"Gemsmithing" : -25,
"Blacksmithing" : -10,
"Furrier" : -5,
"Dyeing" : 0,
"Coopersmithing" : -5,
"Goldsmithing" : -15,
"Gunsmithing" : -20,
"Locksmithing" : -20,
"Pottersmithing" : -5,
"Ropesmithing" : -5,
"Stonemasonry" : -10,
"Weaving" : -5,
"Carpentry" : 0
},
"Stealth" : {
"General" : 0,
"Steal" : -10,
"Sneak" : -5
},
"Survival" : {
"General" : 0,
"Forest" : -5,
"Desert" : -20,
"Island" : -30,
"Mountain" : -5
},
"Barter" : {
"General" : 0
},
"Speech" : {
"General" : 0,
"Persuasion" : -10
},
"Piloting" : {
"General" : 0,
"Boat" : -10,
"Aircraft" : -30,
"Automobile" : -5
},
"Athletics" : {
"General" : 0,
"Jump" : -5,
"Climb" : -10,
"Ride" : -10,
"Swim" : -20
},
"History" : {
"General" : 0
}
}
}
}
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
exports.newCharacter = newCharacter;
} else {
this.newCharacter = newCharacter;
}
})();
},{}]},{},[8]); | storjarn/node-toolbox | tools/http/tinyserver/public/assets/bundles/rpg.js | JavaScript | apache-2.0 | 37,993 |
This is the example used to show how to construct an environment with loadbalancing with docker-compose.
Tools
=====
j2cli: https://github.com/kolypto/j2cli
docker-compose up -d
docker-compose scale app=3
Based on:
https://eyenx.ch/2015/04/18/loadbalancing-containers-with-docker-compose/
| CALlanoR/virtual_environments | web/nginx/docker/nginx_haproxy_redis/README.md | Markdown | apache-2.0 | 295 |
# Didymopanax pachycarpus Marchal SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Araliaceae/Schefflera/Schefflera calva/ Syn. Didymopanax pachycarpus/README.md | Markdown | apache-2.0 | 188 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>ovs all: netdev_rxq Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">ovs all
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="classes.html"><span>Data Structure Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('structnetdev__rxq.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#pub-attribs">Data Fields</a> </div>
<div class="headertitle">
<div class="title">netdev_rxq Struct Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><code>#include <<a class="el" href="netdev-provider_8h_source.html">netdev-provider.h</a>></code></p>
<div class="dynheader">
Collaboration diagram for netdev_rxq:</div>
<div class="dyncontent">
<div class="center"><img src="structnetdev__rxq__coll__graph.png" border="0" usemap="#netdev__rxq_coll__map" alt="Collaboration graph"/></div>
<map name="netdev__rxq_coll__map" id="netdev__rxq_coll__map">
</map>
<center><span class="legend">[<a target="top" href="graph_legend.html">legend</a>]</span></center></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Data Fields</h2></td></tr>
<tr class="memitem:aa8878219a4d62648303ddfcc51e68541"><td class="memItemLeft" align="right" valign="top">struct <a class="el" href="structnetdev.html">netdev</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="structnetdev__rxq.html#aa8878219a4d62648303ddfcc51e68541">netdev</a></td></tr>
<tr class="separator:aa8878219a4d62648303ddfcc51e68541"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa5229e06526d7b6b58f9b227390c7429"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="structnetdev__rxq.html#aa5229e06526d7b6b58f9b227390c7429">queue_id</a></td></tr>
<tr class="separator:aa5229e06526d7b6b58f9b227390c7429"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Field Documentation</h2>
<a class="anchor" id="aa8878219a4d62648303ddfcc51e68541"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">struct <a class="el" href="structnetdev.html">netdev</a>* netdev_rxq::netdev</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="aa5229e06526d7b6b58f9b227390c7429"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int netdev_rxq::queue_id</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<hr/>The documentation for this struct was generated from the following file:<ul>
<li>/home/vladn/git/ovs/lib/<a class="el" href="netdev-provider_8h_source.html">netdev-provider.h</a></li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="structnetdev__rxq.html">netdev_rxq</a></li>
<li class="footer">Generated on Wed Sep 9 2015 19:08:08 for ovs all by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.9.1 </li>
</ul>
</div>
</body>
</html>
| vladn-ma/vladn-ovs-doc | doxygen/ovs_all/html/structnetdev__rxq.html | HTML | apache-2.0 | 7,343 |
{% extends "pkspace.html" %}
{% set active_page = "labeler" %}
{% block title %}Labeler{% endblock %}
{% block script %}
<script src="{{ url_for('static', filename='js/utils.js') }}"></script>
<script src="{{ url_for('static', filename='js/labeler.js') }}"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#tabs').tabs();
var labeler = new Labeler({{ PICTURE_WIDTH}}, {{ PICTURE_HEIGHT }});
$('#tabs > div > span').click(function(e) {
labeler.change_image($(this).attr('id'));
});
$('#masks .mask').click(function(e) {
$('#masks .mask').css('border-color', '#ccc');
labeler.change_mask($(this));
});
$('#labcanvas').click(function(e){
if (labeler.image != null) {
labeler.clicked(e.pageX, e.pageY);
}
});
$('#savelabel').click(function(e) {
labeler.save();
});
$('#markall-vacant').click(function(e){
labeler.set_occupancy_of_all(0);
});
$('#markall-occupied').click(function(e){
labeler.set_occupancy_of_all(1);
});
$('#markall-reverse').click(function(e){
labeler.reverse_occupancy_of_all();
});
});
</script>
{% endblock %}
{% block content %}
<div id="labeler">
{% if nojson %}
<div id="labeler-header">
<h1>No json file with polygons found</h1>
<h3>Please <a href="{{ url_for('marker') }}">generate</a> one</h3>
</div>
{% else %}
<div id="tabs">
<ul>
{% for tab in tabs %}
<li><a href="#{{ tab }}">{{ tab }}</a></li>
{% endfor %}
</ul>
{% for subdir, images in imgs.iteritems() %}
<div id="{{ subdir }}">
{% for img in images %}
<span id="{{ img.src }}" {% if img.labeled %}class="green"{% endif %}>
{{ img.src }}
</span>
{% endfor %}
</div>
{% endfor %}
</div>
<div id="labeler-header">
<p>JSON output will be automatically saved into folder where the image
was loaded from</p>
<button id="savelabel" class="btn btn-success">Save labeled image</button>
<button id="markall-occupied" class="btn btn-info">Mark all occupied</button>
<button id="markall-vacant" class="btn btn-info">Mark all vacant</button>
<button id="markall-reverse" class="btn btn-info">Reverse all markings</button>
</div>
<div id="labeler-container">
<div id="masks">
<h4>Choose a mask</h4>
{% for mask in masks %}
<div class="mask" data-key="{{ mask }}">{{ mask }}</div>
{% endfor %}
</div>
<canvas id="labcanvas" width="{{ PICTURE_WIDTH}}" height="{{ PICTURE_HEIGHT}}">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
{% endif %}
</div>
{% endblock %}
| NaiveNeuron/PKSpace | configapp/templates/labeler.html | HTML | apache-2.0 | 2,856 |
#!/bin/bash
code=(
"utils"
)
c1=`pwd`
for c in "${code[@]}"
do
pushd . >& /dev/null
cd ../../$c
make clean
make
popd >& /dev/null
done
cd $c1
make clean
make
echo
echo
echo "*****************"
echo "You may need to restart the rsyslog server: sudo service rsyslog restart"
echo "*****************"
make clean
#./iotClient
| ibm-security-innovation/libsecurity-c | libsecurity/src/examples/appExample/run.sh | Shell | apache-2.0 | 337 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_37) on Thu Nov 29 20:44:26 GMT 2012 -->
<TITLE>
Index (Measurements Tagger JavaDoc)
</TITLE>
<META NAME="date" CONTENT="2012-11-29">
<LINK REL ="stylesheet" TYPE="text/css" HREF="./stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Index (Measurements Tagger JavaDoc)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="./gate/zemanta/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="./gate/zemanta/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="./deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="./help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="./index.html?index-all.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-all.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="./allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="./allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<A HREF="#_E_">E</A> <A HREF="#_G_">G</A> <A HREF="#_I_">I</A> <A HREF="#_P_">P</A> <A HREF="#_R_">R</A> <A HREF="#_S_">S</A> <A HREF="#_Z_">Z</A> <HR>
<A NAME="_E_"><!-- --></A><H2>
<B>E</B></H2>
<DL>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#execute()"><B>execute()</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>Should be called to execute this PR on a document.
</DL>
<HR>
<A NAME="_G_"><!-- --></A><H2>
<B>G</B></H2>
<DL>
<DT><A HREF="./gate/zemanta/package-summary.html"><B>gate.zemanta</B></A> - package gate.zemanta<DD> <DT><A HREF="./gate/zemanta/ZemantaServicePR.html#getApiKey()"><B>getApiKey()</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>developer key.
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#getInputASName()"><B>getInputASName()</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>The PR requires Sentence annotations as input.
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#getNumberOfSentencesInBatch()"><B>getNumberOfSentencesInBatch()</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#getNumberOfSentencesInContext()"><B>getNumberOfSentencesInContext()</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#getOutputASName()"><B>getOutputASName()</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>
</DL>
<HR>
<A NAME="_I_"><!-- --></A><H2>
<B>I</B></H2>
<DL>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#init()"><B>init()</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>Initialise this resource, and return it.
</DL>
<HR>
<A NAME="_P_"><!-- --></A><H2>
<B>P</B></H2>
<DL>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#processFinished()"><B>processFinished()</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#progressChanged(int)"><B>progressChanged(int)</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>
</DL>
<HR>
<A NAME="_R_"><!-- --></A><H2>
<B>R</B></H2>
<DL>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#reInit()"><B>reInit()</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>
</DL>
<HR>
<A NAME="_S_"><!-- --></A><H2>
<B>S</B></H2>
<DL>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#setApiKey(java.lang.String)"><B>setApiKey(String)</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>developer key.
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#setInputASName(java.lang.String)"><B>setInputASName(String)</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>The PR requires Sentence annotations as input.
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#setNumberOfSentencesInBatch(java.lang.Integer)"><B>setNumberOfSentencesInBatch(Integer)</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#setNumberOfSentencesInContext(java.lang.Integer)"><B>setNumberOfSentencesInContext(Integer)</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#setOutputASName(java.lang.String)"><B>setOutputASName(String)</B></A> -
Method in class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>
</DL>
<HR>
<A NAME="_Z_"><!-- --></A><H2>
<B>Z</B></H2>
<DL>
<DT><A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta"><B>ZemantaServicePR</B></A> - Class in <A HREF="./gate/zemanta/package-summary.html">gate.zemanta</A><DD>The PR uses zemanta online service to annotate documents.<DT><A HREF="./gate/zemanta/ZemantaServicePR.html#ZemantaServicePR()"><B>ZemantaServicePR()</B></A> -
Constructor for class gate.zemanta.<A HREF="./gate/zemanta/ZemantaServicePR.html" title="class in gate.zemanta">ZemantaServicePR</A>
<DD>
</DL>
<HR>
<A HREF="#_E_">E</A> <A HREF="#_G_">G</A> <A HREF="#_I_">I</A> <A HREF="#_P_">P</A> <A HREF="#_R_">R</A> <A HREF="#_S_">S</A> <A HREF="#_Z_">Z</A>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="./gate/zemanta/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="./gate/zemanta/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="./deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="./help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="./index.html?index-all.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-all.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="./allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="./allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| Network-of-BioThings/GettinCRAFTy | src/main/resources/gate/plugins/Tagger_Zemanta/doc/javadoc/index-all.html | HTML | apache-2.0 | 9,897 |
// Do NEVER include directly this file, it is already included by assert.hpp!
#ifndef _BOGEYMAN_PRINT_ERROR_LINE
# define _BOGEYMAN_PRINT_ERROR_LINE BOGEYMAN_DEFAULT_PRINT_ERROR_LINE
#endif // !_BOGEYMAN_PRINT_ERROR_LINE_TO_OUTPUT
#if _BOGEYMAN_PRINT_ERROR_LINE == BOGEYMAN_PRINT_ERROR_LINE_TO_OUTPUT
# include <iostream>
# define BOGEYMAN_PRINT_ERROR_LINE() std::cerr << "Assertion error: " << __FILE__ << " line " << __LINE__ << std::endl
#elif _BOGEYMAN_PRINT_ERROR_LINE == BOGEYMAN_LOG_ERROR_LINE_TO_FILE
# include "bogeyman/Logger.hpp"
# define BOGEYMAN_PRINT_ERROR_LINE() bogeyman::Logger::getInstance().logErrorLine(__FILE__, __LINE__)
#elif _BOGEYMAN_PRINT_ERROR_LINE == BOGEYMAN_DONT_PRINT_ERROR_LINE
# define BOGEYMAN_PRINT_ERROR_LINE()
#else // !_BOGEYMAN_PRINT_ERROR_LINE_TO_OUTPUT
# error "Unrecognized value in parameter macro _BOGEYMAN_PRINT_ERROR_LINE_TO_OUTPUT."
#endif // !_BOGEYMAN_PRINT_ERROR_LINE_TO_OUTPUT
| Aracthor/bogeyman | inc/bogeyman/internal/print_error_line.hpp | C++ | apache-2.0 | 931 |
/*
* Copyright 2014 Red Hat, Inc.
*
* Red Hat 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.
*/
/** @module vertx-apex-js/favicon_handler */
var utils = require('vertx-js/util/utils');
var RoutingContext = require('vertx-apex-js/routing_context');
var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JFaviconHandler = io.vertx.ext.apex.handler.FaviconHandler;
/**
A handler that serves favicons.
<p>
If no file system path is specified it will attempt to serve a resource called `favicon.ico` from the classpath.
@class
*/
var FaviconHandler = function(j_val) {
var j_faviconHandler = j_val;
var that = this;
/**
@public
@param arg0 {RoutingContext}
*/
this.handle = function(arg0) {
var __args = arguments;
if (__args.length === 1 && typeof __args[0] === 'object' && __args[0]._jdel) {
j_faviconHandler["handle(io.vertx.ext.apex.RoutingContext)"](arg0._jdel);
} else utils.invalidArgs();
};
// A reference to the underlying Java delegate
// NOTE! This is an internal API and must not be used in user code.
// If you rely on this property your code is likely to break if we change it / remove it without warning.
this._jdel = j_faviconHandler;
};
/**
Create a handler attempting to load favicon file from the specified path, and with the specified max cache time
@memberof module:vertx-apex-js/favicon_handler
@param path {string} the path
@param maxAgeSeconds {number} max how long the file will be cached by browser, in seconds
@return {FaviconHandler} the handler
*/
FaviconHandler.create = function() {
var __args = arguments;
if (__args.length === 0) {
return new FaviconHandler(JFaviconHandler["create()"]());
}else if (__args.length === 1 && typeof __args[0] === 'string') {
return new FaviconHandler(JFaviconHandler["create(java.lang.String)"](__args[0]));
}else if (__args.length === 1 && typeof __args[0] ==='number') {
return new FaviconHandler(JFaviconHandler["create(long)"](__args[0]));
}else if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] ==='number') {
return new FaviconHandler(JFaviconHandler["create(java.lang.String,long)"](__args[0], __args[1]));
} else utils.invalidArgs();
};
// We export the Constructor function
module.exports = FaviconHandler; | remi128/vertx-apex_old | src/main/resources/vertx-apex-js/favicon_handler.js | JavaScript | apache-2.0 | 2,843 |
# Antennaria friesiana var. friesiana VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Antennaria/Antennaria friesiana/ Syn. Antennaria friesiana friesiana/README.md | Markdown | apache-2.0 | 192 |
using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Results;
using System.Net.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LMS.Service;
using LMS.Service.Controllers;
using LMS.Model;
using LMS.Model.Resource;
using LMS.Model.Composite;
using LMS.Data;
using LMS.Model.Resource.Enums;
namespace LMS.Test.Controllers
{
[TestClass]
public class AccountControllerTest
{
private UnitTestContext<Account> Context { get; set; }
[TestInitialize]
public void TestInitialize()
{
Context = new UnitTestContext<Account>();
Context.TestData.Add(Context.LabelRepository.Add(new Label()
{
Name = "lplabelgroup",
Address = new Address()
{
Line = new string[] { "Skansegade 1D", "Vorup" },
PostalCode = "8940",
City = "Randers SV",
Country = "Denmark",
District = "-",
State = "-"
},
Email = "mail@lplabelgroup.com",
Telecom = "+4541990756"
}));
Context.TestData.Add(Context.ArtistRepository.Add(new Artist()
{
StageName = "Tomtek",
Name = new HumanName()
{
Family = new string[] { "Lykke", "Petersen" },
Given = new string[] { "Thomas" }
},
Address = new Address()
{
Line = new string[] { "Skansegade 1D", "Vorup" },
PostalCode = "8940",
City = "Randers SV",
Country = "Denmark",
District = "-",
State = "-"
},
Email = "thomas@ktrecordings.com",
Telecom = "+45 41990756"
}));
Context.Template = new Account()
{
Name = "XXR001",
Status = AccountStatus.Open,
Transactions = null,
Artist = new Reference(Reference.ArtistUri, Context.TestData.Find(m => m is Artist).Id),
Label = new Reference(Reference.LabelUri, Context.TestData.Find(m => m is Label).Id)
};
}
[TestCleanup]
public void TestCleanup()
{
foreach (DomainResource data in Context.TestData)
{
if (data is Label)
Context.LabelRepository.Remove(data.Id);
if (data is Artist)
Context.ArtistRepository.Remove(data.Id);
if (data is Account)
Context.AccountRepository.Remove(data.Id);
if (data is Transaction)
Context.TransactionRepository.Remove(data.Id);
}
}
[TestMethod]
public void AccountCreateTest()
{
AccountController controller = new AccountController();
controller.Configuration = new HttpConfiguration();
controller.Request = new HttpRequestMessage();
Account account = Context.Template;
account.Name = null;
IHttpActionResult resultERR = controller.Create(account);
Assert.IsTrue(resultERR is BadRequestErrorMessageResult);
account.Name = "XXR001";
OkNegotiatedContentResult<Account> resultOK = controller.Create(account) as OkNegotiatedContentResult<Account>;
Context.TestData.Add(resultOK.Content);
Assert.IsNotNull(resultOK.Content);
Assert.IsTrue(resultOK.Content.Id > 0);
Assert.AreEqual(resultOK.Content.Name, account.Name);
Assert.AreEqual(resultOK.Content.Status, account.Status);
Assert.IsNull(resultOK.Content.Transactions);
Assert.IsNotNull(resultOK.Content.Artist);
Assert.AreEqual(resultOK.Content.Artist.GetId(), account.Artist.GetId());
Assert.IsNotNull(resultOK.Content.Label);
Assert.AreEqual(resultOK.Content.Label.GetId(), account.Label.GetId());
}
[TestMethod]
public void AccountReadTest()
{
AccountController controller = new AccountController();
controller.Configuration = new HttpConfiguration();
controller.Request = new HttpRequestMessage();
Account account = Context.Template;
OkNegotiatedContentResult<Account> resultOK = controller.Create(account) as OkNegotiatedContentResult<Account>;
Context.TestData.Add(resultOK.Content);
resultOK = controller.Read(resultOK.Content.Id) as OkNegotiatedContentResult<Account>;
Assert.IsNotNull(resultOK.Content);
Assert.AreEqual(resultOK.Content.Name, account.Name);
Assert.AreEqual(resultOK.Content.Status, account.Status);
Assert.IsNull(resultOK.Content.Transactions);
Assert.IsNotNull(resultOK.Content.Artist);
Assert.AreEqual(resultOK.Content.Artist.GetId(), account.Artist.GetId());
Assert.IsNotNull(resultOK.Content.Label);
Assert.AreEqual(resultOK.Content.Label.GetId(), account.Label.GetId());
}
[TestMethod]
public void AccountUpdateTest()
{
AccountController controller = new AccountController();
controller.Configuration = new HttpConfiguration();
controller.Request = new HttpRequestMessage();
Account account = Context.Template;
OkNegotiatedContentResult<Account> resultOK = controller.Create(account) as OkNegotiatedContentResult<Account>;
Context.TestData.Add(resultOK.Content);
account = resultOK.Content;
account.Name = "XXR001_changed";
account.Status = AccountStatus.Closed;
resultOK = controller.Update(account) as OkNegotiatedContentResult<Account>;
Assert.IsNotNull(resultOK.Content);
Assert.AreEqual(resultOK.Content.Id, account.Id);
Assert.AreEqual(resultOK.Content.Name, account.Name);
Assert.AreEqual(resultOK.Content.Status, account.Status);
}
[TestMethod]
public void AccountDeleteTest()
{
AccountController controller = new AccountController();
controller.Configuration = new HttpConfiguration();
controller.Request = new HttpRequestMessage();
Account account = Context.Template;
OkNegotiatedContentResult<Account> resultOK = controller.Create(account) as OkNegotiatedContentResult<Account>;
Context.TestData.Add(resultOK.Content);
account = resultOK.Content;
controller.Delete(account.Id);
IHttpActionResult resultNotFound = controller.Read(account.Id);
Assert.IsTrue(resultNotFound is NotFoundResult);
// Test that account cannot be deleted, if any related resources are found.
account = Context.Template;
resultOK = controller.Create(account) as OkNegotiatedContentResult<Account>;
Context.TestData.Add(resultOK.Content);
account = resultOK.Content;
Transaction transaction = new Transaction()
{
Account = new Reference(Reference.AccountUri, Context.TestData.Find(m => m is Account).Id),
Amount = -10,
Description = "Advance payment.",
Quarter = "Q4-2016",
Status = TransactionStatus.Committed,
Type = TransactionType.Advance
};
transaction = Context.TransactionRepository.Add(transaction);
Context.TestData.Add(transaction);
IHttpActionResult resultBadRequest = controller.Delete(account.Id);
Assert.IsTrue(resultBadRequest is BadRequestErrorMessageResult);
}
[TestMethod]
public void AccountSearchTest()
{
AccountController controller = new AccountController();
controller.Configuration = new HttpConfiguration();
controller.Request = new HttpRequestMessage();
Account account = Context.Template;
OkNegotiatedContentResult<Account> resultOK = controller.Create(account) as OkNegotiatedContentResult<Account>;
Context.TestData.Add(resultOK.Content);
account = resultOK.Content;
OkNegotiatedContentResult<List<Account>> resultList = controller.List() as OkNegotiatedContentResult<List<Account>>;
Assert.IsNotNull(resultList.Content);
Assert.IsTrue(resultList.Content.Count == 1);
OkNegotiatedContentResult<List<Account>> resultSearch = controller.Search("name|xxr") as OkNegotiatedContentResult<List<Account>>;
Assert.IsNotNull(resultSearch.Content);
Assert.IsTrue(resultSearch.Content.Count == 1);
resultSearch = controller.Search("name|vvr") as OkNegotiatedContentResult<List<Account>>;
Assert.IsNotNull(resultSearch.Content);
Assert.IsTrue(resultSearch.Content.Count == 0);
}
[TestMethod]
public void TransactionCreateTest()
{
AccountController controller = new AccountController();
controller.Configuration = new HttpConfiguration();
controller.Request = new HttpRequestMessage();
Account account = Context.Template;
OkNegotiatedContentResult<Account> resultOK = controller.Create(account) as OkNegotiatedContentResult<Account>;
Context.TestData.Add(resultOK.Content);
account = resultOK.Content;
Transaction transaction = new Transaction()
{
Account = new Reference(Reference.AccountUri, account.Id),
Amount = 12.57,
Description = "Sales added.",
Quarter = "Q4-2016",
Status = TransactionStatus.Committed,
Type = TransactionType.Sales
};
OkNegotiatedContentResult<Transaction> resultTransactionOK = controller.Create(transaction) as OkNegotiatedContentResult<Transaction>;
Context.TestData.Add(resultTransactionOK.Content);
Assert.IsNotNull(resultTransactionOK.Content);
Assert.IsTrue(resultTransactionOK.Content.Id > 0);
Assert.IsNotNull(resultTransactionOK.Content.Account);
Assert.IsNull(resultTransactionOK.Content.Statement);
Assert.AreEqual(resultTransactionOK.Content.Account.GetId(), transaction.Account.GetId());
Assert.AreEqual(resultTransactionOK.Content.Status, transaction.Status);
Assert.AreEqual(resultTransactionOK.Content.Amount, transaction.Amount);
Assert.AreEqual(resultTransactionOK.Content.Description, transaction.Description);
Assert.AreEqual(resultTransactionOK.Content.Quarter, transaction.Quarter);
Assert.AreEqual(resultTransactionOK.Content.Type, transaction.Type);
}
[TestMethod]
public void AccountBalanceTest()
{
AccountController controller = new AccountController();
controller.Configuration = new HttpConfiguration();
controller.Request = new HttpRequestMessage();
Account account = Context.Template;
OkNegotiatedContentResult<Account> resulAccounttOK = controller.Create(account) as OkNegotiatedContentResult<Account>;
Context.TestData.Add(resulAccounttOK.Content);
account = resulAccounttOK.Content;
Transaction transactionA = new Transaction()
{
Account = new Reference(Reference.AccountUri, account.Id),
Amount = 12.57,
Description = "Revenue from streaming.",
Quarter = "Q4-2016",
Status = TransactionStatus.Committed,
Type = TransactionType.Sales
};
OkNegotiatedContentResult<Transaction> resultTransactionOK = controller.Create(transactionA) as OkNegotiatedContentResult<Transaction>;
Context.TestData.Add(resultTransactionOK.Content);
Transaction transactionB = new Transaction()
{
Account = new Reference(Reference.AccountUri, account.Id),
Amount = 17.89,
Description = "Revenue from sales.",
Quarter = "Q4-2016",
Status = TransactionStatus.Committed,
Type = TransactionType.Sales
};
resultTransactionOK = controller.Create(transactionB) as OkNegotiatedContentResult<Transaction>;
Context.TestData.Add(resultTransactionOK.Content);
Transaction transactionC = new Transaction()
{
Account = new Reference(Reference.AccountUri, account.Id),
Amount = -10,
Description = "Advance payment.",
Quarter = "Q4-2016",
Status = TransactionStatus.Failed,
Type = TransactionType.Advance
};
resultTransactionOK = controller.Create(transactionC) as OkNegotiatedContentResult<Transaction>;
Context.TestData.Add(resultTransactionOK.Content);
resulAccounttOK = controller.Read(account.Id) as OkNegotiatedContentResult<Account>;
Assert.IsNotNull(resulAccounttOK.Content);
Assert.AreEqual(resulAccounttOK.Content.Name, account.Name);
Assert.AreEqual(resulAccounttOK.Content.Status, account.Status);
Assert.IsNotNull(resulAccounttOK.Content.Transactions);
Assert.IsTrue(resulAccounttOK.Content.Transactions.Length == 3);
Assert.IsTrue(resulAccounttOK.Content.Balance == (transactionA.Amount + transactionB.Amount));
}
}
}
| dktlp/lms | src/Test/Controllers/AccountControllerTest.cs | C# | apache-2.0 | 14,059 |
// Code generated by easyjson for marshaling/unmarshaling. DO NOT EDIT.
package deviceorientation
import (
json "encoding/json"
easyjson "github.com/mailru/easyjson"
jlexer "github.com/mailru/easyjson/jlexer"
jwriter "github.com/mailru/easyjson/jwriter"
)
// suppress unused package warning
var (
_ *json.RawMessage
_ *jlexer.Lexer
_ *jwriter.Writer
_ easyjson.Marshaler
)
func easyjsonC5a4559bDecodeGithubComKnqChromedpCdpDeviceorientation(in *jlexer.Lexer, out *SetDeviceOrientationOverrideParams) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
in.Consumed()
}
in.Skip()
return
}
in.Delim('{')
for !in.IsDelim('}') {
key := in.UnsafeString()
in.WantColon()
if in.IsNull() {
in.Skip()
in.WantComma()
continue
}
switch key {
case "alpha":
out.Alpha = float64(in.Float64())
case "beta":
out.Beta = float64(in.Float64())
case "gamma":
out.Gamma = float64(in.Float64())
default:
in.SkipRecursive()
}
in.WantComma()
}
in.Delim('}')
if isTopLevel {
in.Consumed()
}
}
func easyjsonC5a4559bEncodeGithubComKnqChromedpCdpDeviceorientation(out *jwriter.Writer, in SetDeviceOrientationOverrideParams) {
out.RawByte('{')
first := true
_ = first
if !first {
out.RawByte(',')
}
first = false
out.RawString("\"alpha\":")
out.Float64(float64(in.Alpha))
if !first {
out.RawByte(',')
}
first = false
out.RawString("\"beta\":")
out.Float64(float64(in.Beta))
if !first {
out.RawByte(',')
}
first = false
out.RawString("\"gamma\":")
out.Float64(float64(in.Gamma))
out.RawByte('}')
}
// MarshalJSON supports json.Marshaler interface
func (v SetDeviceOrientationOverrideParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComKnqChromedpCdpDeviceorientation(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v SetDeviceOrientationOverrideParams) MarshalEasyJSON(w *jwriter.Writer) {
easyjsonC5a4559bEncodeGithubComKnqChromedpCdpDeviceorientation(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *SetDeviceOrientationOverrideParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComKnqChromedpCdpDeviceorientation(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *SetDeviceOrientationOverrideParams) UnmarshalEasyJSON(l *jlexer.Lexer) {
easyjsonC5a4559bDecodeGithubComKnqChromedpCdpDeviceorientation(l, v)
}
func easyjsonC5a4559bDecodeGithubComKnqChromedpCdpDeviceorientation1(in *jlexer.Lexer, out *ClearDeviceOrientationOverrideParams) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
in.Consumed()
}
in.Skip()
return
}
in.Delim('{')
for !in.IsDelim('}') {
key := in.UnsafeString()
in.WantColon()
if in.IsNull() {
in.Skip()
in.WantComma()
continue
}
switch key {
default:
in.SkipRecursive()
}
in.WantComma()
}
in.Delim('}')
if isTopLevel {
in.Consumed()
}
}
func easyjsonC5a4559bEncodeGithubComKnqChromedpCdpDeviceorientation1(out *jwriter.Writer, in ClearDeviceOrientationOverrideParams) {
out.RawByte('{')
first := true
_ = first
out.RawByte('}')
}
// MarshalJSON supports json.Marshaler interface
func (v ClearDeviceOrientationOverrideParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComKnqChromedpCdpDeviceorientation1(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v ClearDeviceOrientationOverrideParams) MarshalEasyJSON(w *jwriter.Writer) {
easyjsonC5a4559bEncodeGithubComKnqChromedpCdpDeviceorientation1(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *ClearDeviceOrientationOverrideParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComKnqChromedpCdpDeviceorientation1(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *ClearDeviceOrientationOverrideParams) UnmarshalEasyJSON(l *jlexer.Lexer) {
easyjsonC5a4559bDecodeGithubComKnqChromedpCdpDeviceorientation1(l, v)
}
| AdityaMili95/Wallte | vendor/github.com/knq/chromedp/cdp/deviceorientation/easyjson.go | GO | apache-2.0 | 4,191 |
package org.fastnate.generator.statements;
import org.fastnate.generator.context.SequenceIdGenerator;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* Base class for {@link ColumnExpression}s which reference an ID by using the value of a sequence.
*
* @author Tobias Liefke
*/
@Getter
@RequiredArgsConstructor
public abstract class SequenceValueExpression implements ColumnExpression {
/** The written sequence. */
private final SequenceIdGenerator sequence;
/** The difference of the referenced ID to the sequence value. */
private final long difference;
/**
* Builds the SQL expression by using the given SQL and the current {@link #difference}.
*
* @param sql
* the SQL expression that references the sequence
* @return the SQL expression that references the sequence and respects the difference
*/
protected String toSql(final String sql) {
if (this.difference == 0) {
return sql;
}
return '(' + sql + " - " + this.difference + ')';
}
}
| liefke/org.fastnate | fastnate-generator/src/main/java/org/fastnate/generator/statements/SequenceValueExpression.java | Java | apache-2.0 | 1,008 |
#include <bits/stdc++.h>
template<typename T> T gcd(T a, T b) {
if(!b) return a;
return gcd(b, a % b);
}
template<typename T> T lcm(T a, T b) {
return a * b / gcd(a, b);
}
template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; }
template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; }
int in() { int x; scanf("%d", &x); return x; }
using namespace std;
#ifdef ONLINE_JUDGE
#define debug(args...)
#else
#define debug(args...) fprintf(stderr,args)
#endif
typedef long long Int;
typedef unsigned long long uInt;
typedef unsigned uint;
const Int MOD = 100000007LL;
const int MAXN = 500005;
int T, N, M;
Int dp[MAXN][300];
Int func_naive(int pos, int used) {
if (pos >= M) {
return used * 2 > N ? 1LL : 0LL;
} else {
Int& ans = dp[pos][used];
if (ans == -1) {
ans = 0;
for (int i = 1; i <= N; i++) {
if (used * 2 <= N && i < 2 * used) {
continue;
}
ans += func_naive(pos + 1, i);
ans = ((ans % MOD) + MOD) % MOD;
}
}
ans = ((ans % MOD) + MOD) % MOD;
return ans;
}
}
Int func(int pos, int last) {
if (pos >= M) {
return last == 1 ? 1LL : 0LL;
} else {
Int& ans = dp[pos][last];
if (ans == -1) {
ans = 0;
if (last == 1) {
ans += ((N + 1) / 2) * func(pos + 1, 1);
ans = ((ans % MOD) + MOD) % MOD;
ans += ((N + 0) / 2) * func(pos + 1, 0);
ans = ((ans % MOD) + MOD) % MOD;
} else {
ans += ((N + 1) / 2) * func(pos + 1, 1);
ans = ((ans % MOD) + MOD) % MOD;
}
}
ans = ((ans % MOD) + MOD) % MOD;
return ans;
}
}
int main(void) {
cin >> T;
for (int t = 1; t <= T; t++) {
cin >> N >> M;
memset(dp, -1, sizeof(dp));
cout << func_naive(0, N) << "\n";
}
return 0;
}
| aajjbb/contest-files | HackerRank/AlienLanguages.cpp | C++ | apache-2.0 | 2,063 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "core/data_render/vm.h"
#include "core/data_render/exec_state.h"
#include "core/data_render/object.h"
#include "core/data_render/class.h"
#include "core/data_render/table.h"
#include "core/data_render/common_error.h"
#include "core/data_render/class_array.h"
#include "core/data_render/monitor/vm_monitor.h"
#include "core/data_render/class_function.h"
namespace weex {
namespace core {
namespace data_render {
void VM::RunFrame(ExecState *exec_state, Frame frame, Value *ret) {
#define LOGTEMP(...)
//#define LOGTEMP(...) printf(__VA_ARGS__)
#if DEBUG
//TimeCost tc;
#endif
Value* a = nullptr;
Value* b = nullptr;
Value* c = nullptr;
auto pc = frame.pc;
while (pc != frame.end) {
Instruction instruction = *pc++;
double d1, d2;
OPCode op(GET_OP_CODE(instruction));
#if DEBUG
//tc.op_start(op);
#endif
switch (op) {
case OP_MOVE:
{
LOGTEMP("OP_MOVE A:%ld B:%ld\n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_Bx(instruction);
if (IsValueRef(a)) {
*a->var = *b;
SetNil(a);
}
else {
*a = *b;
if (a->ref) {
SetRefValue(a);
}
}
break;
}
case OP_LOADNULL:
a = frame.reg + GET_ARG_Ax(instruction);
a->type = Value::Type::NIL;
break;
case OP_LOADK:
LOGTEMP("OP_LOADK A:%ld B:%ld\n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.func->GetConstant((int)GET_ARG_Bx(instruction));
*a = *b;
break;
case OP_GETGLOBAL:
LOGTEMP("OP_GETGLOBAL A:%ld B:%ld\n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = exec_state->global()->Find((int)GET_ARG_Bx(instruction));
*a = *b;
break;
case OP_GETFUNC: {
LOGTEMP("OP_GETFUNC A:%ld\n", GET_ARG_A(instruction));
a = frame.reg + GET_ARG_A(instruction);
FuncState *func_state = frame.func->GetChild(GET_ARG_Bx(instruction));
if (func_state->in_closure().size() > 0) {
*a = exec_state->class_factory()->CreateFuncInstance(func_state);
AddClosure(exec_state, a);
}
else {
a->type = Value::Type::FUNC;
a->f = func_state;
}
break;
}
case OP_ADD:
{
LOGTEMP("OP_ADD A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (IsString(b) || IsString(c)) {
SetSValue(a, StringAdd(exec_state->string_table(), b, c));
}
else if (IsInt(b) && IsInt(c)) {
SetIValue(a, INT_OP(+, IntValue(b), IntValue(c)));
}
else if (ToNum(b, d1) && ToNum(c, d2)) {
SetDValue(a, NUM_OP(+, d1, d2));
}
else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_ADD]", b->type, c->type);
throw VMExecError("Unspport Type with OP_CODE[OP_ADD]");
}
break;
}
case OP_SUB:
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (IsInt(b) && IsInt(c)) {
SetIValue(a, INT_OP(-, IntValue(b), IntValue(c)));
} else if (ToNum(b, d1) && ToNum(c, d2)) {
SetDValue(a, NUM_OP(-, d1, d2));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_SUB]", b->type, c->type);
throw VMExecError("Unspport Type with OP_CODE[OP_SUB]");
}
break;
case OP_MUL:
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (IsInt(b) && IsInt(c)) {
SetIValue(a, INT_OP(*, IntValue(b), IntValue(c)));
} else if (ToNum(b, d1) && ToNum(c, d2)) {
SetDValue(a, NUM_OP(*, d1, d2));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_MUL]", b->type, c->type);
}
break;
case OP_DIV:
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (IsInt(b) && IsInt(c)) {
SetIValue(a, static_cast<int>(NUM_OP(/, IntValue(b), IntValue(c))));
} else if (ToNum(b, d1) && ToNum(c, d2)) {
SetDValue(a, NUM_OP(/, IntValue(b), IntValue(c)));
} else if (IsInt(c) && IsString(b)) {
int64_t bval = 0;
ToInteger(b, 0, bval);
SetIValue(a, static_cast<int>(NUM_OP(/, bval, IntValue(c))));
} else if (IsString(c) && IsString(b)) {
int64_t bval = 0, cval = 0;
ToInteger(b, 0, bval);
ToInteger(c, 0, cval);
SetIValue(a, static_cast<int>(NUM_OP(/, bval, cval)));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_DIV]", b->type, c->type);
}
break;
case OP_IDIV:
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (IsInt(b) && IsInt(c)) {
SetIValue(a, INT_OP(/, IntValue(b), IntValue(c)));
} else if (ToNum(b, d1) && ToNum(c, d2)) {
SetDValue(a, NumIDiv(d1, d2));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_IDIV]", b->type, c->type);
}
break;
case OP_MOD:
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (IsInt(b) && IsInt(c)) {
SetIValue(a, IntMod(static_cast<int>(IntValue(b)), static_cast<int>(IntValue(c))));
} else if (ToNum(b, d1) && ToNum(c, d2)) {
SetDValue(a, NumMod(d1, d2));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_MOD]", b->type, c->type);
}
break;
case OP_POW:
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (IsInt(b) && IsInt(c)) {
SetIValue(a, NumPow(IntValue(b), IntValue(c)));
} else if (ToNum(b, d1) && ToNum(c, d2)) {
SetDValue(a, NumPow(d1, d2));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_POW]", b->type, c->type);
}
break;
case OP_BAND: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
int64_t i1=0, i2=0;
if (ToInteger(b, 0, i1) && ToInteger(c, 0, i2)) {
SetIValue(a, INT_OP(&, i1, i2));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_BAND]", b->type, c->type);
}
}
break;
case OP_CALL: {
LOGTEMP("OP_CALL A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
size_t argc = GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (!IsFunction(c)) {
throw VMExecError("Unspport Type With OP_CODE [OP_CALL]");
}
exec_state->CallFunction(c, argc, a);
LOGTEMP("OP_CALL ret:%ld argc:%ld call:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
break;
}
case OP_JMP: {
LOGTEMP("OP_JMP A:%ld B:%ld \n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
bool con = false;
if (!ToBool(a, con)) {
throw VMExecError("Unspport Type With OP_CODE [OP_JMP]");
}
if (!con) {
pc += GET_ARG_Bx(instruction);
}
break;
}
case OP_TRUE_JMP: {
LOGTEMP("OP_TRUE_JMP A:%ld B:%ld \n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
bool con = false;
if (!ToBool(a, con)) {
throw VMExecError("Unspport Type With OP_CODE [OP_JMP]");
}
if (con) {
pc += GET_ARG_Bx(instruction);
}
break;
}
case OP_JMPTO: {
LOGTEMP("OP_JMPTO A:%ld B:%ld \n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
bool con = false;
if (!ToBool(a, con)) {
throw VMExecError("Unspport Type With OP_CODE [OP_JMP]");
}
if (!con) {
pc = frame.pc + GET_ARG_Bx(instruction);
}
break;
}
case OP_TRUE_JMPTO: {
LOGTEMP("OP_TRUE_JMPTO A:%ld B:%ld \n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
bool con = false;
if (!ToBool(a, con)) {
throw VMExecError("Unspport Type With OP_CODE [OP_JMP]");
}
if (con) {
pc = frame.pc + GET_ARG_Bx(instruction);
}
break;
}
case OP_GOTO: {
pc = frame.pc + GET_ARG_Ax(instruction);
}
break;
case OP_EQ: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
SetBValue(a, ValueEquals(b, c));
break;
}
case OP_SEQ: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
SetBValue(a, ValueStrictEquals(b, c));
break;
}
case OP_LT: {
LOGTEMP("OP_LT A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
SetBValue(a, ValueLT(b, c));
break;
}
case OP_LTE: {
LOGTEMP("OP_LTE A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
SetBValue(a, ValueLTE(b, c));
break;
}
case OP_GT: {
LOGTEMP("OP_GT A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
SetBValue(a, ValueGT(b, c));
break;
}
case OP_GTE: {
LOGTEMP("OP_GTE A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
SetBValue(a, ValueGTE(b, c));
break;
}
case OP_AND: {
LOGTEMP("OP_AND A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
SetBValue(a, ValueAND(b, c));
break;
}
case OP_NOT:
{
LOGTEMP("OP_NOT A:%ld B:%ld \n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_Bx(instruction);
a->type = Value::Type::BOOL;
ToBool(b, a->b);
a->b = !a->b;
break;
}
case OP_OR: {
LOGTEMP("OP_OR A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
bool bval = false;
ToBool(b, bval);
if (bval) {
*a = *b;
}
else {
ToBool(c, bval);
if (bval) {
*a = *c;
}
else {
SetNil(a);
}
}
break;
}
case OP_UNM: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
if (IsInt(b)) {
SetIValue(a, INT_OP(-, 0, IntValue(b)));
} else if (IsNumber(b)) {
SetDValue(a, NUM_OP(-, 0, NumValue(b)));
} else {
LOGE("Unspport Type[%d] with OP_CODE[OP_UNM]", b->type);
}
}
break;
case OP_BNOT: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
int64_t i;
if (ToInteger(b, 0, i)) {
SetIValue(a, INT_OP(^, ~CAST_S2U(0), i));
} else {
LOGE("Unspport Type[%d] with OP_CODE[OP_BNOT]", b->type);
}
}
break;
case OP_BOR: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
int64_t i1=0, i2=0;
if (ToInteger(b, 0, i1) && ToInteger(c, 0, i2)) {
SetIValue(a, INT_OP(|, i1, i2));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_BOR]", b->type, c->type);
}
}
break;
case OP_BXOR: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
int64_t i1=0, i2=0;
if (ToInteger(b, 0, i1) && ToInteger(c, 0, i2)) {
SetIValue(a, INT_OP(^, i1, i2));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_BXOR]", b->type, c->type);
}
}
break;
case OP_SHL: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
int64_t i1=0, i2=0;
if (ToInteger(b, 0, i1) && ToInteger(c, 0, i2)) {
SetIValue(a, static_cast<int>(ShiftLeft(i1, i2)));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_SHL]", b->type, c->type);
}
}
break;
case OP_SHR: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
int64_t i1=0, i2=0;
if (ToInteger(b, 0, i1) && ToInteger(c, 0, i2)) {
SetIValue(a, static_cast<int>(ShiftLeft(i1, -i2)));
} else {
LOGE("Unspport Type[%d,%d] with OP_CODE[OP_SHR]", b->type, c->type);
}
}
break;
case OP_POST_INCR: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_Bx(instruction);
if (IsInt(a)) {
if (NULL != b) {
SetIValue(b, (int)IntValue(a));
}
SetIValue(a, (int)IntValue(a) + 1);
SetRefValue(a);
}
else if (IsNumber(a)) {
if (NULL != b) {
SetDValue(b, NumValue(a));
}
SetDValue(a, NumValue(a) + 1);
SetRefValue(a);
}
else {
LOGE("Unspport Type[%d] with OP_CODE[OP_POST_INCR]", a->type);
}
}
break;
case OP_POST_DECR: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_Bx(instruction);
if (IsInt(a)) {
if (GET_ARG_Bx(instruction) != 0) {
SetIValue(b, (int)IntValue(a));
}
SetIValue(a, (int)IntValue(a) - 1);
}
else if (IsNumber(a)) {
if (GET_ARG_Bx(instruction) != 0) {
SetDValue(b, NumValue(a));
}
SetDValue(a, NumValue(a) - 1);
}
else {
throw VMExecError("Unspport Type with OP_CODE [OP_POST_DECR]");
}
}
break;
case OP_PREV_INCR: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_Bx(instruction);
if (IsInt(a)) {
SetIValue(a, (int)IntValue(a) + 1);
SetRefValue(a);
if (NULL != b) {
SetIValue(b, (int)IntValue(a));
}
} else if (IsNumber(a)) {
SetDValue(a, NumValue(a) + 1);
SetRefValue(a);
if (NULL != b) {
SetDValue(b, NumValue(a));
}
} else {
LOGE("Unspport Type[%d] with OP_CODE[OP_PRE_INCR]", a->type);
}
}
break;
case OP_PREV_DECR: {
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_Bx(instruction);
if (IsInt(a)) {
SetIValue(a, static_cast<int>(IntValue(a)) - 1);
if (GET_ARG_Bx(instruction) != 0) {
SetIValue(b, static_cast<int>(IntValue(a)));
}
} else if (IsNumber(a)) {
SetDValue(a, NumValue(a) - 1);
if (GET_ARG_Bx(instruction) != 0) {
SetDValue(b, NumValue(a));
}
} else {
throw VMExecError("Unspport Type with OP_CODE [OP_PRE_DECR]");
}
}
break;
case OP_NEW: {
LOGTEMP("OP_NEW A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
int index = (int)GET_ARG_B(instruction);
switch (index) {
case Value::TABLE:
{
*a = exec_state->class_factory()->CreateTable();
break;
}
case Value::ARRAY:
{
*a = exec_state->class_factory()->CreateArray();
break;
}
case Value::CLASS_DESC:
{
c = frame.reg + GET_ARG_C(instruction);
if (!IsClass(c)) {
throw VMExecError("Unspport Find Desc with OP_CODE [OP_NEWCLASS]");
}
*a = exec_state->class_factory()->CreateClassInstance(ValueTo<ClassDescriptor>(c));
break;
}
default:
throw VMExecError("Unspport Type with OP_CODE [OP_NEW]");
break;
}
break;
}
case OP_CONSTRUCTOR:
{
a = frame.reg + GET_ARG_A(instruction);
int argc = (int)GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (!IsClassInstance(a)) {
throw VMExecError("only support class instance in [OP_CONSTRUCTOR]");
break;
}
if (argc < 1) {
throw VMExecError("constructor with no args in [OP_CONSTRUCTOR]");
break;
}
if (FindConstructor(ValueTo<ClassInstance>(a), c, c + 1)) {
exec_state->CallFunction(c, argc, a);
}
break;
}
case OP_GETSUPER:
{
LOGTEMP("OP_GETSUPER A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (!IsClassInstance(b)) {
throw VMExecError("Type Error For Class Instance with OP_CODE [OP_GETSUPER]");
}
ClassInstance *inst = ValueTo<ClassInstance>(b);
ClassInstance *inst_super = inst->p_super_;
if (!inst_super) {
throw VMExecError("Instance Can't Find Super With OP_CODE [OP_GETSUPER]");
}
SetCIValue(a, reinterpret_cast<GCObject *>(inst->p_super_));
int index = inst_super->p_desc_->funcs_->IndexOf("constructor");
if (index >= 0) {
*c = *inst_super->p_desc_->funcs_->Find(index);
}
else {
SetNil(c);
}
break;
}
case OP_SETMEMBERVAR:
{
LOGTEMP("OP_SETMEMBERVAR A:%ld B:%ld\n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_Bx(instruction);
if (!IsValueRef(a)) {
throw VMExecError("Only ValueRef Support With OP_CODE [OP_SETMEMBER]");
}
*a->var = *b;
SetNil(a);
break;
}
case OP_GETCLASS:
{
LOGTEMP("OP_GETCLASS A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (!IsClassInstance(b)) {
throw VMExecError("Type Error For Class Instance with OP_CODE [OP_GETCLASS]");
}
if (!IsString(c)) {
throw VMExecError("Type Error For Member with OP_CODE [OP_GETCLASS]");
}
std::string var_name = CStringValue(c);
int index = ValueTo<ClassInstance>(b)->p_desc_->funcs_->IndexOf(var_name);
if (index < 0) {
SetNil(a);
}
else {
*a = *ValueTo<ClassInstance>(b)->p_desc_->funcs_->Find(index);
}
break;
}
case OP_GETMEMBERVAR:
case OP_GETMEMBER:
{
LOGTEMP("OP_GETMEMBER A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (IsValueRef(b)) {
b = b->var;
}
if (!IsClassInstance(b) && !IsClass(b) && !IsArray(b) && !IsTable(b) && !IsString(b)) {
throw VMExecError("Type Error For Class Instance Or Class With OP_CODE [OP_GETMEMBER]");
}
if (!IsString(c)) {
throw VMExecError("Type Error For Member with OP_CODE [OP_GETMEMBER]");
}
std::string var_name = CStringValue(c);
// first find member func
if (IsClassInstance(b)) {
Value *ret = nullptr;
if (op == OP_GETMEMBER) {
ret = GetClassMember(ValueTo<ClassInstance>(b), var_name);
if (!ret) {
throw VMExecError("can't find " + var_name + "[OP_GETMEMBER]");
}
if (IsPrototypeFunction(ret) && ret->f->is_class_func()) {
ret->f->class_inst() = ValueTo<ClassInstance>(b);
}
*a = *ret;
}
else {
ret = GetClassMemberVar(ValueTo<ClassInstance>(b), var_name);
SetValueRef(a, ret);
}
}
else if (IsArray(b)) {
if (var_name == "length") {
*a = GetArraySizeValue(ValueTo<Array>(b));
}
else {
int index = exec_state->global()->IndexOf("Array");
if (index < 0) {
throw VMExecError("Can't Find Array Class With OP_CODE OP_GETMEMBER");
}
Value *class_desc = exec_state->global()->Find(index);
Variables *funcs = ValueTo<ClassDescriptor>(class_desc)->funcs_.get();
index = funcs->IndexOf(var_name);
if (index < 0) {
throw VMExecError("Can't Find Array Func " + var_name + " With OP_CODE [OP_GETMEMBER]");
}
Value *func = funcs->Find(index);
*a = *func;
}
}
else if (IsString(b)) {
int index = exec_state->global()->IndexOf("String");
if (index < 0) {
throw VMExecError("Can't Find String Class With OP_CODE OP_GETMEMBER");
}
Value *class_desc = exec_state->global()->Find(index);
Variables *funcs = ValueTo<ClassDescriptor>(class_desc)->funcs_.get();
index = funcs->IndexOf(var_name);
if (index < 0) {
throw VMExecError("Can't Find String Func " + var_name + " With OP_CODE [OP_GETMEMBER]");
}
Value *func = funcs->Find(index);
*a = *func;
}
else if (IsTable(b)) {
if (op == OP_GETMEMBER) {
Value *ret = GetTableValue(ValueTo<Table>(b), *c);
if (!IsNil(ret)) {
*a = *ret;
}
else {
SetNil(a);
}
}
else {
Value *ret = GetTableVar(ValueTo<Table>(b), *c);
if (ret) {
SetValueRef(a, ret);
}
}
}
else {
// only can find class static funcs;
Variables *statics = ValueTo<ClassDescriptor>(b)->statics_.get();
int index = statics->IndexOf(var_name);
if (index < 0) {
if (op == OP_GETMEMBER) {
throw VMExecError("Can't Find Static Func " + var_name + " With OP_CODE [OP_GETMEMBER]");
break;
}
Value *ret = GetClassStaticMemberVar(ValueTo<ClassDescriptor>(b), var_name);
SetValueRef(a, ret);
}
else {
Value *svar = statics->Find(index);
*a = *svar;
}
}
break;
}
case OP_SETOUTVAR:
{
LOGTEMP("OP_SETOUTVAR A:%ld B:%ld\n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
int index = (int)GET_ARG_Bx(instruction);
ValueRef *ref = exec_state->FindRef(index);
if (!ref) {
throw VMExecError("Can't Find ValueRef " + base::to_string(index) + " [OP_SETOUTVAR]");
}
ref->value() = *a;
ref->value().ref = a;
break;
}
case OP_TYPEOF:
{
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_Bx(instruction);
if (IsNil(b)) {
SetSValue(a, exec_state->string_table()->StringFromUTF8("undefined"));
}
else if (IsTable(b)) {
SetSValue(a, exec_state->string_table()->StringFromUTF8("object"));
}
else if (IsBool(b)) {
SetSValue(a, exec_state->string_table()->StringFromUTF8("boolean"));
}
else if (IsString(b)) {
SetSValue(a, exec_state->string_table()->StringFromUTF8("string"));
}
else if (IsFunction(b) || IsFuncInstance(b)) {
SetSValue(a, exec_state->string_table()->StringFromUTF8("function"));
}
else {
throw VMExecError("Can't Supporting typeof [OP_TYPEOF]");
}
break;
}
case OP_RESETOUTVAR:
{
LOGTEMP("OP_RESETOUTVAR A:%ld\n", GET_ARG_Ax(instruction));
a = frame.reg + GET_ARG_Ax(instruction);
a->ref = NULL;
break;
}
case OP_GETOUTVAR:
{
LOGTEMP("OP_GETOUTVAR A:%ld B:%ld\n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
int index = (int)GET_ARG_Bx(instruction);
ValueRef *ref = exec_state->FindRef(index);
if (!ref) {
throw VMExecError("Can't Find ValueRef " + base::to_string(index) + " [OP_GETOUTVAR]");
}
*a = ref->value();
a->ref = &ref->value();
break;
}
case OP_OUT_CLOSURE:
{
LOGTEMP("OP_OUT_CLOSURE A:%ld B:%ld\n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
int index = (int)GET_ARG_Bx(instruction);
ValueRef *ref = exec_state->FindRef(index);
if (!ref) {
throw VMExecError("Can't Find ValueRef " + base::to_string(index) + " [OP_OUT_CLOSURE]");
}
ref->value() = *a;
ref->value().ref = a;
if (ref->is_closure() && ref->closure()) {
ref->closure()->value() = *a;
}
break;
}
case OP_IN_CLOSURE:
{
LOGTEMP("OP_IN_CLOSURE A:%ld B:%ld\n", GET_ARG_A(instruction), GET_ARG_Bx(instruction));
a = frame.reg + GET_ARG_A(instruction);
int index = (int)GET_ARG_Bx(instruction);
ValueRef *ref = exec_state->FindRef(index);
if (!ref) {
throw VMExecError("Can't Find ValueRef " + base::to_string(index) + " [OP_IN_CLOSURE]");
}
Value *ret = LoadClosure(frame.reg, ref);
if (!ret) {
throw VMExecError("Can't Find Closure [OP_IN_CLOSURE]");
}
*a = *ret;
a->ref = ret;
break;
}
case OP_REMOVE_CLOSURE:
{
LOGTEMP("OP_REMOVE_CLOSURE A:%ld \n", GET_ARG_Ax(instruction));
int index = (int)GET_ARG_Ax(instruction);
ValueRef *ref = exec_state->FindRef(index);
if (!ref) {
throw VMExecError("Can't Find ValueRef " + base::to_string(index) + " [OP_REMOVE_CLOSURE]");
}
ref->value().ref = nullptr;
ref->closure()->SetValueRef(nullptr);
break;
}
case OP_GETINDEXVAR:
{
LOGTEMP("OP_GETINDEXVAR A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (IsArray(b)) {
if (!IsInt(c)) {
throw VMExecError("Array Type Error With OP_CODE [OP_GETINDEXVAR]");
}
Value *ret = GetArrayVar(ValueTo<Array>(b), *c);
if (ret) {
SetValueRef(a, ret);
}
}
else if (IsTable(b)) {
if (!IsString(c)) {
throw VMExecError("Table Type Error With OP_CODE [OP_GETINDEXVAR]");
}
Value *ret = GetTableVar(ValueTo<Table>(b), *c);
if (ret) {
SetValueRef(a, ret);
}
}
else {
throw VMExecError("Unsupport Type Error With OP_CODE [OP_GETINDEXVAR]");
}
break;
}
case OP_GETINDEX: {
LOGTEMP("OP_GETINDEX A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (IsArray(b)) {
if (!IsInt(c)) {
throw VMExecError("Array Type Error With OP_CODE [OP_GETINDEX]");
}
*a = GetArrayValue(ValueTo<Array>(b), *c);
}
else if (IsTable(b)) {
if (!IsString(c)) {
throw VMExecError("Table Type Error With OP_CODE [OP_GETINDEX]");
}
Value *ret = GetTableValue(ValueTo<Table>(b), *c);
if (!IsNil(ret)) {
*a = *ret;
}
else {
SetNil(a);
}
}
else {
throw VMExecError("Unsupport Type Error With OP_CODE [OP_GETINDEX]");
}
break;
}
case OP_SETARRAY: {
LOGTEMP("OP_SETARRAY A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
int index = (int)GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (!IsArray(a)) {
// TODO error
throw VMExecError("Array Type Error With OP_CODE [OP_SETARRAY]");
}
if (!SetArray(ValueTo<Array>(a), index, *c)) {
throw VMExecError("Array Type Error With OP_CODE [OP_SETARRAY]");
}
break;
}
case OP_IN:
{
LOGTEMP("OP_IN A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (!IsArray(c) && !IsTable(c)) {
// TODO error
throw VMExecError("Not Array or Table Type Error With OP_CODE [OP_IN]");
}
//LOGTEMP("[OP_IN]:%s\n", TableToString(ValueTo<Table>(c)).c_str());
if (IsTable(c) && !TableInKey(exec_state->string_table(), ValueTo<Table>(c), a, b)) {
throw VMExecError("Table For In Error With OP_CODE [OP_IN]");
}
break;
}
case OP_SETTABLE: {
LOGTEMP("OP_SETTABLE A:%ld B:%ld C:%ld\n", GET_ARG_A(instruction), GET_ARG_B(instruction), GET_ARG_C(instruction));
a = frame.reg + GET_ARG_A(instruction);
b = frame.reg + GET_ARG_B(instruction);
c = frame.reg + GET_ARG_C(instruction);
if (!IsTable(a)) {
// TODO error
throw VMExecError("Table Type Error With OP_CODE [OP_SETTABLE]");
}
if (IsString(b) || IsTable(b)) {
int ret = SetTableValue(reinterpret_cast<Table *>(a->gc), b, *c);
if (!ret) {
// TODO set faile
throw VMExecError("Set Table Error With OP_CODE [OP_SETTABLE]");
}
}
break;
}
case OP_RETURN0: {
return;
}
case OP_RETURN1: {
LOGTEMP("OP_RETURN1 A:%ld\n", GET_ARG_Ax(instruction));
if (ret == nullptr) {
return;
}
else {
a = frame.reg + GET_ARG_Ax(instruction);
*ret = *a;
return;
}
}
case OP_INVALID: {
throw VMExecError("Error With OP_CODE [OP_INVALID]");
break;
}
default:
break;
}
#if DEBUG
//tc.op_end();
#endif
}
}
} // namespace data_render
} // namespace core
} // namespace weex
| KalicyZhou/incubator-weex | weex_core/Source/core/data_render/vm.cc | C++ | apache-2.0 | 37,317 |
package blended.mgmt.base.internal
import blended.container.context.api.ContainerIdentifierService
import blended.util.logging.Logger
import domino.DominoActivator
import javax.management.{ MBeanServer, ObjectName }
class MgmtBaseActivator extends DominoActivator {
private[this] val log = Logger[MgmtBaseActivator]
whenBundleActive {
whenServicePresent[ContainerIdentifierService] { idSvc =>
log.info("Creating Framework Service instance...")
val fwSvc = new FrameworkService(bundleContext, idSvc.containerContext)
fwSvc.providesService[blended.mgmt.base.FrameworkService]
whenServicePresent[MBeanServer] { server =>
log.info("Registering Framework Service as MBean...")
val objName = new ObjectName("blended:type=FrameworkService")
server.registerMBean(fwSvc, objName)
}
}
}
}
| lefou/blended | blended.mgmt.base/src/main/scala/blended/mgmt/base/internal/MgmtBaseActivator.scala | Scala | apache-2.0 | 854 |
# Cyathus vernicosus var. desmazieri J. Kickx f. VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Fl. Crypt. Flandres 2: 7 (1867)
#### Original name
Cyathus vernicosus var. desmazieri J. Kickx f.
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Agaricaceae/Cyathus/Cyathus olla/Cyathus vernicosus desmazieri/README.md | Markdown | apache-2.0 | 248 |
/*
* 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.cassandra.index;
import java.lang.reflect.Constructor;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutor;
import org.apache.cassandra.concurrent.NamedThreadFactory;
import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.cql3.statements.IndexTarget;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.compaction.CompactionManager;
import org.apache.cassandra.db.filter.RowFilter;
import org.apache.cassandra.db.lifecycle.SSTableSet;
import org.apache.cassandra.db.lifecycle.View;
import org.apache.cassandra.db.partitions.PartitionUpdate;
import org.apache.cassandra.db.rows.*;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.index.internal.CassandraIndex;
import org.apache.cassandra.index.transactions.*;
import org.apache.cassandra.io.sstable.ReducingKeyIterator;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.schema.IndexMetadata;
import org.apache.cassandra.schema.Indexes;
import org.apache.cassandra.tracing.Tracing;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.concurrent.OpOrder;
import org.apache.cassandra.utils.concurrent.Refs;
/**
* Handles the core maintenance functionality associated with indexes: adding/removing them to or from
* a table, (re)building during bootstrap or other streaming operations, flushing, reloading metadata
* and so on.
*
* The Index interface defines a number of methods which return Callable<?>. These are primarily the
* management tasks for an index implementation. Most of them are currently executed in a blocking
* fashion via submission to SIM's blockingExecutor. This provides the desired behaviour in pretty
* much all cases, as tasks like flushing an index needs to be executed synchronously to avoid potentially
* deadlocking on the FlushWriter or PostFlusher. Several of these Callable<?> returning methods on Index could
* then be defined with as void and called directly from SIM (rather than being run via the executor service).
* Separating the task defintion from execution gives us greater flexibility though, so that in future, for example,
* if the flush process allows it we leave open the possibility of executing more of these tasks asynchronously.
*
* The primary exception to the above is the Callable returned from Index#addIndexedColumn. This may
* involve a significant effort, building a new index over any existing data. We perform this task asynchronously;
* as it is called as part of a schema update, which we do not want to block for a long period. Building non-custom
* indexes is performed on the CompactionManager.
*
* This class also provides instances of processors which listen to updates to the base table and forward to
* registered Indexes the info required to keep those indexes up to date.
* There are two variants of these processors, each with a factory method provided by SIM:
* IndexTransaction: deals with updates generated on the regular write path.
* CleanupTransaction: used when partitions are modified during compaction or cleanup operations.
* Further details on their usage and lifecycles can be found in the interface definitions below.
*
* Finally, the bestIndexFor method is used at query time to identify the most selective index of those able
* to satisfy any search predicates defined by a ReadCommand's RowFilter. It returns a thin IndexAccessor object
* which enables the ReadCommand to access the appropriate functions of the Index at various stages in its lifecycle.
* e.g. the getEstimatedResultRows is required when StorageProxy calculates the initial concurrency factor for
* distributing requests to replicas, whereas a Searcher instance is needed when the ReadCommand is executed locally on
* a target replica.
*/
public class SecondaryIndexManager implements IndexRegistry
{
private static final Logger logger = LoggerFactory.getLogger(SecondaryIndexManager.class);
private Map<String, Index> indexes = Maps.newConcurrentMap();
// executes tasks returned by Indexer#addIndexColumn which may require index(es) to be (re)built
private static final ExecutorService asyncExecutor =
new JMXEnabledThreadPoolExecutor(1,
StageManager.KEEPALIVE,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
new NamedThreadFactory("SecondaryIndexManagement"),
"internal");
// executes all blocking tasks produced by Indexers e.g. getFlushTask, getMetadataReloadTask etc
private static final ExecutorService blockingExecutor = MoreExecutors.newDirectExecutorService();
/**
* The underlying column family containing the source data for these indexes
*/
public final ColumnFamilyStore baseCfs;
public SecondaryIndexManager(ColumnFamilyStore baseCfs)
{
this.baseCfs = baseCfs;
}
/**
* Drops and adds new indexes associated with the underlying CF
*/
public void reload()
{
// figure out what needs to be added and dropped.
Indexes tableIndexes = baseCfs.metadata.getIndexes();
indexes.keySet()
.stream()
.filter(indexName -> !tableIndexes.has(indexName))
.forEach(this::removeIndex);
// we call add for every index definition in the collection as
// some may not have been created here yet, only added to schema
for (IndexMetadata tableIndex : tableIndexes)
addIndex(tableIndex);
}
private Future<?> reloadIndex(IndexMetadata indexDef)
{
// if the index metadata has changed, reload the index
IndexMetadata registered = indexes.get(indexDef.name).getIndexMetadata();
if (!registered.equals(indexDef))
{
Index index = indexes.remove(registered.name);
index.register(this);
return blockingExecutor.submit(index.getMetadataReloadTask(indexDef));
}
// otherwise, nothing to do
return Futures.immediateFuture(null);
}
private Future<?> createIndex(IndexMetadata indexDef)
{
Index index = createInstance(indexDef);
index.register(this);
final Callable<?> initialBuildTask = index.getInitializationTask();
return initialBuildTask == null
? Futures.immediateFuture(null)
: asyncExecutor.submit(initialBuildTask);
}
/**
* Adds and builds a index
* @param indexDef the IndexMetadata describing the index
*/
public synchronized Future<?> addIndex(IndexMetadata indexDef)
{
if (indexes.containsKey(indexDef.name))
return reloadIndex(indexDef);
else
return createIndex(indexDef);
}
public synchronized void removeIndex(String indexName)
{
Index index = indexes.remove(indexName);
if (null != index)
{
executeBlocking(index.getInvalidateTask());
unregisterIndex(index);
}
}
/**
* Called when dropping a Table
*/
public void markAllIndexesRemoved()
{
getBuiltIndexNames().forEach(this::markIndexRemoved);
}
/**
* Does a full, blocking rebuild of the indexes specified by columns from the sstables.
* Caller must acquire and release references to the sstables used here.
* Note also that only this method of (re)building indexes:
* a) takes a set of index *names* rather than Indexers
* b) marks exsiting indexes removed prior to rebuilding
*
* @param sstables the data to build from
* @param indexNames the list of indexes to be rebuilt
*/
public void rebuildIndexesBlocking(Collection<SSTableReader> sstables, Set<String> indexNames)
{
Set<Index> toRebuild = indexes.values().stream()
.filter(indexer -> indexNames.contains(indexer.getIndexName()))
.collect(Collectors.toSet());
if (toRebuild.isEmpty())
{
logger.info("No defined indexes with the supplied names");
return;
}
toRebuild.forEach(indexer -> markIndexRemoved(indexer.getIndexName()));
buildIndexesBlocking(sstables, toRebuild);
toRebuild.forEach(indexer -> markIndexBuilt(indexer.getIndexName()));
}
public void buildAllIndexesBlocking(Collection<SSTableReader> sstables)
{
buildIndexesBlocking(sstables, ImmutableSet.copyOf(indexes.values()));
}
// For convenience, may be called directly from Index impls
public void buildIndexBlocking(Index index)
{
try (ColumnFamilyStore.RefViewFragment viewFragment = baseCfs.selectAndReference(View.select(SSTableSet.CANONICAL));
Refs<SSTableReader> sstables = viewFragment.refs)
{
buildIndexesBlocking(sstables, Collections.singleton(index));
markIndexBuilt(index.getIndexName());
}
}
private void buildIndexesBlocking(Collection<SSTableReader> sstables, Set<Index> indexes)
{
if (indexes.isEmpty())
return;
logger.info("Submitting index build of {} for data in {}",
indexes.stream().map(Index::getIndexName).collect(Collectors.joining(",")),
sstables.stream().map(SSTableReader::toString).collect(Collectors.joining(",")));
SecondaryIndexBuilder builder = new SecondaryIndexBuilder(baseCfs,
indexes,
new ReducingKeyIterator(sstables));
Future<?> future = CompactionManager.instance.submitIndexBuild(builder);
FBUtilities.waitOnFuture(future);
flushIndexesBlocking(indexes);
logger.info("Index build of {} complete",
indexes.stream().map(Index::getIndexName).collect(Collectors.joining(",")));
}
private void markIndexBuilt(String indexName)
{
SystemKeyspace.setIndexBuilt(baseCfs.name, indexName);
}
private void markIndexRemoved(String indexName)
{
SystemKeyspace.setIndexRemoved(baseCfs.name, indexName);
}
public Index getIndexByName(String indexName)
{
return indexes.get(indexName);
}
private Index createInstance(IndexMetadata indexDef)
{
Index newIndex;
if (indexDef.isCustom())
{
assert indexDef.options != null;
String className = indexDef.options.get(IndexTarget.CUSTOM_INDEX_OPTION_NAME);
assert ! Strings.isNullOrEmpty(className);
try
{
Class<? extends Index> indexClass = FBUtilities.classForName(className, "Index");
Constructor ctor = indexClass.getConstructor(ColumnFamilyStore.class, IndexMetadata.class);
newIndex = (Index)ctor.newInstance(baseCfs, indexDef);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
else
{
newIndex = CassandraIndex.newIndex(baseCfs, indexDef);
}
return newIndex;
}
/**
* Truncate all indexes
*/
public void truncateAllIndexesBlocking(final long truncatedAt)
{
executeAllBlocking(indexes.values().stream(), (index) -> index.getTruncateTask(truncatedAt));
}
/**
* Remove all indexes
*/
public void invalidateAllIndexesBlocking()
{
executeAllBlocking(indexes.values().stream(), Index::getInvalidateTask);
}
/**
* Perform a blocking flush all indexes
*/
public void flushAllIndexesBlocking()
{
flushIndexesBlocking(ImmutableSet.copyOf(indexes.values()));
}
/**
* Perform a blocking flush of selected indexes
*/
public void flushIndexesBlocking(Set<Index> indexes)
{
if (indexes.isEmpty())
return;
List<Future<?>> wait = new ArrayList<>();
List<Index> nonCfsIndexes = new ArrayList<>();
// for each CFS backed index, submit a flush task which we'll wait on for completion
// for the non-CFS backed indexes, we'll flush those while we wait.
synchronized (baseCfs.getTracker())
{
indexes.forEach(index ->
index.getBackingTable()
.map(cfs -> wait.add(cfs.forceFlush()))
.orElse(nonCfsIndexes.add(index)));
}
executeAllBlocking(nonCfsIndexes.stream(), Index::getBlockingFlushTask);
FBUtilities.waitOnFutures(wait);
}
/**
* Performs a blocking flush of all custom indexes
*/
public void flushAllCustomIndexesBlocking()
{
Set<Index> customIndexers = indexes.values().stream()
.filter(index -> !(index instanceof CassandraIndex))
.collect(Collectors.toSet());
flushIndexesBlocking(customIndexers);
}
/**
* @return all indexes which are marked as built and ready to use
*/
public List<String> getBuiltIndexNames()
{
Set<String> allIndexNames = new HashSet<>();
indexes.values().stream()
.map(Index::getIndexName)
.forEach(allIndexNames::add);
return SystemKeyspace.getBuiltIndexes(baseCfs.keyspace.getName(), allIndexNames);
}
/**
* @return all backing Tables used by registered indexes
*/
public Set<ColumnFamilyStore> getAllIndexColumnFamilyStores()
{
Set<ColumnFamilyStore> backingTables = new HashSet<>();
indexes.values().forEach(index -> index.getBackingTable().ifPresent(backingTables::add));
return backingTables;
}
/**
* @return if there are ANY indexes registered for this table
*/
public boolean hasIndexes()
{
return !indexes.isEmpty();
}
/**
* When building an index against existing data in sstables, add the given partition to the index
*/
public void indexPartition(UnfilteredRowIterator partition, OpOrder.Group opGroup, Set<Index> indexes, int nowInSec)
{
if (!indexes.isEmpty())
{
DecoratedKey key = partition.partitionKey();
Set<Index.Indexer> indexers = indexes.stream()
.map(index -> index.indexerFor(key,
nowInSec,
opGroup,
IndexTransaction.Type.UPDATE))
.collect(Collectors.toSet());
indexers.forEach(Index.Indexer::begin);
try (RowIterator filtered = UnfilteredRowIterators.filter(partition, nowInSec))
{
if (!filtered.staticRow().isEmpty())
indexers.forEach(indexer -> indexer.insertRow(filtered.staticRow()));
while (filtered.hasNext())
{
Row row = filtered.next();
indexers.forEach(indexer -> indexer.insertRow(row));
}
}
indexers.forEach(Index.Indexer::finish);
}
}
/**
* Delete all data from all indexes for this partition.
* For when cleanup rips a partition out entirely.
*
* TODO : improve cleanup transaction to batch updates & perform them async
*/
public void deletePartition(UnfilteredRowIterator partition, int nowInSec)
{
// we need to acquire memtable lock because secondary index deletion may
// cause a race (see CASSANDRA-3712). This is done internally by the
// index transaction when it commits
CleanupTransaction indexTransaction = newCleanupTransaction(partition.partitionKey(),
partition.columns(),
nowInSec);
indexTransaction.start();
indexTransaction.onPartitionDeletion(partition.partitionLevelDeletion());
indexTransaction.commit();
while (partition.hasNext())
{
Unfiltered unfiltered = partition.next();
if (unfiltered.kind() != Unfiltered.Kind.ROW)
continue;
indexTransaction = newCleanupTransaction(partition.partitionKey(),
partition.columns(),
nowInSec);
indexTransaction.start();
indexTransaction.onRowDelete((Row)unfiltered);
indexTransaction.commit();
}
}
/**
* Called at query time to find the most selective of the registered index implementation
* (i.e. the one likely to return the fewest results) from those registered.
* Implementation specific validation of the target expression by the most selective
* index should be performed in the searcherFor method to ensure that we pick the right
* index regardless of the validity of the expression.
*
* This method is called at various points during the lifecycle of a ReadCommand (to obtain a Searcher,
* get the index's underlying CFS for ReadOrderGroup, or an estimate of the result size from an average index
* query).
*
* Ideally, we would do this relatively expensive operation only once, and attach the index to the
* ReadCommand for future reference. This requires the index be passed onto additional commands generated
* to process subranges etc.
*
* @param command ReadCommand to be executed
* @return an Index instance, ready to use during execution of the command, or null if none
* of the registered indexes can support the command.
*/
public Index getBestIndexFor(ReadCommand command, boolean includeInTrace)
{
if (indexes.isEmpty() || command.rowFilter().isEmpty())
return null;
Set<Index> searchableIndexes = new HashSet<>();
for (RowFilter.Expression expression : command.rowFilter())
{
indexes.values().stream()
.filter(index -> index.supportsExpression(expression.column(), expression.operator()))
.forEach(searchableIndexes::add);
}
if (searchableIndexes.isEmpty())
{
logger.debug("No applicable indexes found");
if (includeInTrace)
Tracing.trace("No applicable indexes found");
return null;
}
Index selected = searchableIndexes.stream()
.max((a, b) -> Longs.compare(a.getEstimatedResultRows(),
b.getEstimatedResultRows()))
.orElseThrow(() -> new AssertionError("Could not select most selective index"));
// pay for an additional threadlocal get() rather than build the strings unnecessarily
if (includeInTrace && Tracing.isTracing())
{
Tracing.trace("Index mean cardinalities are {}. Scanning with {}.",
searchableIndexes.stream().map(i -> i.getIndexName() + ':' + i.getEstimatedResultRows())
.collect(Collectors.joining(",")),
selected.getIndexName());
}
return selected;
}
// convenience method which doesn't emit tracing messages
public Index getBestIndexFor(ReadCommand command)
{
return getBestIndexFor(command, false);
}
/**
* Called at write time to ensure that values present in the update
* are valid according to the rules of all registered indexes which
* will process it. The partition key as well as the clustering and
* cell values for each row in the update may be checked by index
* implementations
* @param update PartitionUpdate containing the values to be validated by registered Index implementations
* @throws InvalidRequestException
*/
public void validate(PartitionUpdate update) throws InvalidRequestException
{
indexes.values()
.stream()
.filter(i -> i.indexes(update.columns()))
.forEach(i -> i.validate(update));
}
/**
* IndexRegistry methods
*/
public void registerIndex(Index index)
{
indexes.put(index.getIndexMetadata().name, index);
logger.debug("Registered index {}", index.getIndexMetadata().name);
}
public void unregisterIndex(Index index)
{
Index removed = indexes.remove(index.getIndexMetadata().name);
logger.debug(removed == null ? "Index {} was not registered" : "Removed index {} from registry",
index.getIndexMetadata().name);
}
public Index getIndex(IndexMetadata metadata)
{
return indexes.get(metadata.name);
}
public Collection<Index> listIndexes()
{
return ImmutableSet.copyOf(indexes.values());
}
/**
* Handling of index updates.
* Implementations of the various IndexTransaction interfaces, for keeping indexes in sync with base data
* during updates, compaction and cleanup. Plus factory methods for obtaining transaction instances.
*/
/**
* Transaction for updates on the write path.
*/
public UpdateTransaction newUpdateTransaction(PartitionUpdate update, OpOrder.Group opGroup, int nowInSec)
{
if (!hasIndexes())
return UpdateTransaction.NO_OP;
// todo : optimize lookup, we can probably cache quite a bit of stuff, rather than doing
// a linear scan every time. Holding off that though until CASSANDRA-7771 to figure out
// exactly how indexes are to be identified & associated with a given partition update
Index.Indexer[] indexers = indexes.values().stream()
.filter(i -> i.indexes(update.columns()))
.map(i -> i.indexerFor(update.partitionKey(),
nowInSec,
opGroup,
IndexTransaction.Type.UPDATE))
.toArray(Index.Indexer[]::new);
return indexers.length == 0 ? UpdateTransaction.NO_OP : new WriteTimeTransaction(indexers);
}
/**
* Transaction for use when merging rows during compaction
*/
public CompactionTransaction newCompactionTransaction(DecoratedKey key,
PartitionColumns partitionColumns,
int versions,
int nowInSec)
{
// the check for whether there are any registered indexes is already done in CompactionIterator
Index[] interestedIndexes = indexes.values().stream()
.filter(i -> i.indexes(partitionColumns))
.toArray(Index[]::new);
return interestedIndexes.length == 0
? CompactionTransaction.NO_OP
: new IndexGCTransaction(key, versions, nowInSec, interestedIndexes);
}
/**
* Transaction for use when removing partitions during cleanup
*/
public CleanupTransaction newCleanupTransaction(DecoratedKey key,
PartitionColumns partitionColumns,
int nowInSec)
{
//
if (!hasIndexes())
return CleanupTransaction.NO_OP;
Index[] interestedIndexes = indexes.values().stream()
.filter(i -> i.indexes(partitionColumns))
.toArray(Index[]::new);
return interestedIndexes.length == 0
? CleanupTransaction.NO_OP
: new CleanupGCTransaction(key, nowInSec, interestedIndexes);
}
/**
* A single use transaction for processing a partition update on the regular write path
*/
private static final class WriteTimeTransaction implements UpdateTransaction
{
private final Index.Indexer[] indexers;
private WriteTimeTransaction(Index.Indexer...indexers)
{
// don't allow null indexers, if we don't need any use a NullUpdater object
for (Index.Indexer indexer : indexers) assert indexer != null;
this.indexers = indexers;
}
public void start()
{
Arrays.stream(indexers).forEach(Index.Indexer::begin);
}
public void onPartitionDeletion(DeletionTime deletionTime)
{
Arrays.stream(indexers).forEach(h -> h.partitionDelete(deletionTime));
}
public void onRangeTombstone(RangeTombstone tombstone)
{
Arrays.stream(indexers) .forEach(h -> h.rangeTombstone(tombstone));
}
public void onInserted(Row row)
{
Arrays.stream(indexers).forEach(h -> h.insertRow(row));
}
public void onUpdated(Row existing, Row updated)
{
final Row.Builder toRemove = BTreeRow.sortedBuilder(existing.columns());
toRemove.newRow(existing.clustering());
final Row.Builder toInsert = BTreeRow.sortedBuilder(updated.columns());
toInsert.newRow(updated.clustering());
// diff listener collates the columns to be added & removed from the indexes
RowDiffListener diffListener = new RowDiffListener()
{
public void onPrimaryKeyLivenessInfo(int i, Clustering clustering, LivenessInfo merged, LivenessInfo original)
{
if (merged != null && merged != original)
toInsert.addPrimaryKeyLivenessInfo(merged);
}
public void onDeletion(int i, Clustering clustering, DeletionTime merged, DeletionTime original)
{
}
public void onComplexDeletion(int i, Clustering clustering, ColumnDefinition column, DeletionTime merged, DeletionTime original)
{
}
public void onCell(int i, Clustering clustering, Cell merged, Cell original)
{
if (merged != null && merged != original)
toInsert.addCell(merged);
if (merged == null || (original != null && shouldCleanupOldValue(original, merged)))
toRemove.addCell(original);
}
};
Rows.diff(diffListener, updated, updated.columns().mergeTo(existing.columns()), existing);
Row oldRow = toRemove.build();
Row newRow = toInsert.build();
Arrays.stream(indexers).forEach(i -> i.updateRow(oldRow, newRow));
}
public void commit()
{
Arrays.stream(indexers).forEach(Index.Indexer::finish);
}
private boolean shouldCleanupOldValue(Cell oldCell, Cell newCell)
{
// If either the value or timestamp is different, then we
// should delete from the index. If not, then we can infer that
// at least one of the cells is an ExpiringColumn and that the
// difference is in the expiry time. In this case, we don't want to
// delete the old value from the index as the tombstone we insert
// will just hide the inserted value.
// Completely identical cells (including expiring columns with
// identical ttl & localExpirationTime) will not get this far due
// to the oldCell.equals(newCell) in StandardUpdater.update
return !oldCell.value().equals(newCell.value()) || oldCell.timestamp() != newCell.timestamp();
}
}
/**
* A single-use transaction for updating indexes for a single partition during compaction where the only
* operation is to merge rows
* TODO : make this smarter at batching updates so we can use a single transaction to process multiple rows in
* a single partition
*/
private static final class IndexGCTransaction implements CompactionTransaction
{
private final DecoratedKey key;
private final int versions;
private final int nowInSec;
private final Index[] indexes;
private Row[] rows;
private IndexGCTransaction(DecoratedKey key,
int versions,
int nowInSec,
Index...indexes)
{
// don't allow null indexers, if we don't have any, use a noop transaction
for (Index index : indexes) assert index != null;
this.key = key;
this.versions = versions;
this.indexes = indexes;
this.nowInSec = nowInSec;
}
public void start()
{
if (versions > 0)
rows = new Row[versions];
}
public void onRowMerge(Columns columns, Row merged, Row...versions)
{
// Diff listener constructs rows representing deltas between the merged and original versions
// These delta rows are then passed to registered indexes for removal processing
final Row.Builder[] builders = new Row.Builder[versions.length];
RowDiffListener diffListener = new RowDiffListener()
{
public void onPrimaryKeyLivenessInfo(int i, Clustering clustering, LivenessInfo merged, LivenessInfo original)
{
}
public void onDeletion(int i, Clustering clustering, DeletionTime merged, DeletionTime original)
{
}
public void onComplexDeletion(int i, Clustering clustering, ColumnDefinition column, DeletionTime merged, DeletionTime original)
{
}
public void onCell(int i, Clustering clustering, Cell merged, Cell original)
{
if (original != null && merged == null)
{
if (builders[i] == null)
{
builders[i] = BTreeRow.sortedBuilder(columns);
builders[i].newRow(clustering);
}
builders[i].addCell(original);
}
}
};
Rows.diff(diffListener, merged, columns, versions);
for(int i = 0; i < builders.length; i++)
if (builders[i] != null)
rows[i] = builders[i].build();
}
public void commit()
{
if (rows == null)
return;
try (OpOrder.Group opGroup = Keyspace.writeOrder.start())
{
Index.Indexer[] indexers = Arrays.stream(indexes)
.map(i -> i.indexerFor(key, nowInSec, opGroup, Type.COMPACTION))
.toArray(Index.Indexer[]::new);
Arrays.stream(indexers).forEach(Index.Indexer::begin);
for (Row row : rows)
if (row != null)
Arrays.stream(indexers).forEach(indexer -> indexer.removeRow(row));
Arrays.stream(indexers).forEach(Index.Indexer::finish);
}
}
}
/**
* A single-use transaction for updating indexes for a single partition during cleanup, where
* partitions and rows are only removed
* TODO : make this smarter at batching updates so we can use a single transaction to process multiple rows in
* a single partition
*/
private static final class CleanupGCTransaction implements CleanupTransaction
{
private final DecoratedKey key;
private final int nowInSec;
private final Index[] indexes;
private Row row;
private DeletionTime partitionDelete;
private CleanupGCTransaction(DecoratedKey key,
int nowInSec,
Index...indexes)
{
// don't allow null indexers, if we don't have any, use a noop transaction
for (Index index : indexes) assert index != null;
this.key = key;
this.indexes = indexes;
this.nowInSec = nowInSec;
}
public void start()
{
}
public void onPartitionDeletion(DeletionTime deletionTime)
{
partitionDelete = deletionTime;
}
public void onRowDelete(Row row)
{
this.row = row;
}
public void commit()
{
if (row == null && partitionDelete == null)
return;
try (OpOrder.Group opGroup = Keyspace.writeOrder.start())
{
Index.Indexer[] indexers = Arrays.stream(indexes)
.map(i -> i.indexerFor(key, nowInSec, opGroup, Type.CLEANUP))
.toArray(Index.Indexer[]::new);
Arrays.stream(indexers).forEach(Index.Indexer::begin);
if (partitionDelete != null)
Arrays.stream(indexers).forEach(indexer -> indexer.partitionDelete(partitionDelete));
if (row != null)
Arrays.stream(indexers).forEach(indexer -> indexer.removeRow(row));
Arrays.stream(indexers).forEach(Index.Indexer::finish);
}
}
}
private static void executeBlocking(Callable<?> task)
{
if (null != task)
FBUtilities.waitOnFuture(blockingExecutor.submit(task));
}
private static void executeAllBlocking(Stream<Index> indexers, Function<Index, Callable<?>> function)
{
List<Future<?>> waitFor = new ArrayList<>();
indexers.forEach(indexer -> {
Callable<?> task = function.apply(indexer);
if (null != task)
waitFor.add(blockingExecutor.submit(task));
});
FBUtilities.waitOnFutures(waitFor);
}
}
| fengshao0907/Cassandra-Research | src/java/org/apache/cassandra/index/SecondaryIndexManager.java | Java | apache-2.0 | 36,453 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'report_loglive', language 'vi', branch 'MOODLE_22_STABLE'
*
* @package report_loglive
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['livelogs'] = 'Lưu trữ hoạt động trong một giờ vừa qua';
| carnegiespeech/translations | vi/report_loglive.php | PHP | apache-2.0 | 1,075 |
/* ========================================================================
* ColorPicker.js [1.5.0+]
* ========================================================================
* Copyright (c) 2016 cnezsoft.com; Licensed MIT
* ======================================================================== */
(function($) {
'use strict';
var name = 'Hui.colorPicker'; // modal name
var TEAMPLATE = '<div class="colorpicker"><button type="button" class="btn dropdown-toggle" data-toggle="dropdown"><span class="cp-title"></span><i class="ic"></i></button><ul class="dropdown-menu clearfix"></ul></div>';
var LANG = {
zh_cn: {
errorTip: "不是有效的颜色值"
},
zh_tw: {
errorTip: "不是有效的顏色值"
},
en: {
errorTip: "Not a valid color value"
}
};
// The ColorPicker modal class
var ColorPicker = function(element, options) {
this.name = name;
this.$ = $(element);
this.getOptions(options);
this.init();
};
// default options
ColorPicker.DEFAULTS = {
colors: ['#00BCD4', '#388E3C', '#3280fc', '#3F51B5', '#9C27B0', '#795548', '#F57C00', '#F44336', '#E91E63'],
pullMenuRight: true,
wrapper: 'btn-wrapper',
tileSize: 30,
lineCount: 5,
optional: true,
tooltip: 'top',
icon: 'caret-down',
// btnTip: 'Tool tip in button'
};
ColorPicker.prototype.init = function() {
var options = this.options,
that = this;
this.$picker = $(TEAMPLATE).addClass(options.wrapper);
this.$picker.find('.cp-title').toggle(options.title !== undefined).text(options.title);
this.$menu = this.$picker.find('.dropdown-menu').toggleClass('pull-right', options.pullMenuRight);
this.$btn = this.$picker.find('.btn.dropdown-toggle');
this.$btn.find('.ic').addClass('icon-' + options.icon);
if (options.btnTip) {
this.$picker.attr('data-toggle', 'tooltip').tooltip({
title: options.btnTip,
placement: options.tooltip,
container: 'body'
});
}
this.$.attr('data-provide', null).after(this.$picker);
// init colors
this.colors = {};
$.each(this.options.colors,
function(idx, rawColor) {
if ($.zui.Color.isColor(rawColor)) {
var color = new $.zui.Color(rawColor);
that.colors[color.toCssStr()] = color;
}
});
this.updateColors();
var that = this;
this.$picker.on('click', '.cp-tile',
function() {
that.setValue($(this).data('color'));
});
var $input = this.$;
var setInputColor = function() {
var val = $input.val();
var isColor = $.zui.Color.isColor(val);
$input.parent().toggleClass('has-error', !isColor && !(options.optional && val === ''));
if (isColor) {
that.setValue(val, true);
} else {
if (options.optional && val === '') {
$input.tooltip('hide');
} else if (!$input.is(':focus')) {
$input.tooltip('show', options.errorTip);
}
}
}
if ($input.is('input:not([type=hidden])')) {
if (options.tooltip) {
$input.attr('data-toggle', 'tooltip').tooltip({
trigger: 'manual',
placement: options.tooltip,
tipClass: 'tooltip-danger',
container: 'body'
});
}
$input.on('keyup paste input change', setInputColor);
} else {
$input.appendTo(this.$picker);
}
setInputColor();
};
ColorPicker.prototype.addColor = function(color) {
var hex = color.toCssStr(),
options = this.options;
if (!this.colors[hex]) {
this.colors[hex] = color;
}
var $a = $('<a href="###" class="cp-tile"></a>', {
titile: color
}).data('color', color).css({
'color': color.contrast().toCssStr(),
'background': hex,
'border-color': color.luma() > 0.43 ? '#ccc': 'transparent'
}).attr('data-color', hex);
this.$menu.append($('<li/>').css({
width: options.tileSize,
height: options.tileSize
}).append($a));
if (options.optional) {
this.$menu.find('.cp-tile.empty').parent().detach().appendTo(this.$menu);
}
};
ColorPicker.prototype.updateColors = function(colors) {
var $picker = this.$picker,
$menu = this.$menu.empty(),
options = this.options,
colors = colors || this.colors,
that = this;
var bestLineCount = 0;
$.each(colors,
function(idx, color) {
that.addColor(color);
bestLineCount++;
});
if (options.optional) {
var $li = $('<li><a class="cp-tile empty" href="###"></a></li>').css({
width: options.tileSize,
height: options.tileSize
});
this.$menu.append($li);
bestLineCount++;
}
$menu.css('width', Math.min(bestLineCount, options.lineCount) * options.tileSize + 6);
};
ColorPicker.prototype.setValue = function(color, notSetInput) {
var options = this.options;
this.$menu.find('.cp-tile.active').removeClass('active');
var hex = '';
if (color) {
var c = new $.zui.Color(color);
hex = c.toCssStr().toLowerCase();
this.$btn.css({
background: hex,
color: c.contrast().toCssStr(),
borderColor: c.luma() > 0.43 ? '#ccc': hex
});
if (!this.colors[hex]) {
this.addColor(c);
}
if (!notSetInput && this.$.val().toLowerCase() !== hex) {
this.$.val(hex).trigger('change');
}
this.$menu.find('.cp-tile[data-color=' + hex + ']').addClass('active');
this.$.tooltip('hide');
this.$.trigger('colorchange', c);
} else {
this.$btn.attr('style', null);
if (!notSetInput && this.$.val() !== '') {
this.$.val(hex).trigger('change');
}
if (options.optional) {
this.$.tooltip('hide');
}
this.$menu.find('.cp-tile.empty').addClass('active');
this.$.trigger('colorchange', null);
}
if (options.updateBorder) {
$(options.updateBorder).css('border-color', hex);
}
if (options.updateBackground) {
$(options.updateBackground).css('background-color', hex);
}
if (options.updateColor) {
$(options.updateText).css('color', hex);
}
if (options.updateText) {
$(options.updateText).text(hex);
}
};
// Get and init options
ColorPicker.prototype.getOptions = function(options) {
var thisOptions = $.extend({},
ColorPicker.DEFAULTS, this.$.data(), options);
if (typeof thisOptions.colors === 'string') thisOptions.colors = thisOptions.colors.split(',');
var lang = (thisOptions.lang || $.zui.clientLang()).toLowerCase();
if (!thisOptions.errorTip) {
thisOptions.errorTip = LANG[lang].errorTip;
}
if (!$.fn.tooltip) thisOptions.btnTip = false;
this.options = thisOptions;
};
// Extense jquery element
$.fn.colorPicker = function(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data(name);
var options = typeof option == 'object' && option;
if (!data) $this.data(name, (data = new ColorPicker(this, options)));
if (typeof option == 'string') data[option]();
});
};
$.fn.colorPicker.Constructor = ColorPicker;
// Auto call colorPicker after document load complete
$(function() {
$('[data-provide="colorpicker"]').colorPicker();
});
} (jQuery)); | fengjianheizhao/TP51 | public/static/h-ui/lib/ColorPicker/1.5.0/ColorPicker.js | JavaScript | apache-2.0 | 6,801 |
package org.noob.codewars.train.learn.prac2017.prac170105;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Copyright [2017$] [Wuxinshui]
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Created by wuxinshui on 2017/1/5.
*/
public class EvaluatorTest {
@Test
public void test1() throws Exception {
Evaluator eval = new Evaluator();
assertEquals(10, eval.evaluate("2 3 9 4 / + *"));
assertEquals(70, eval.evaluate("25 45 +"));
}
@Test
public void test2() throws Exception {
BestPractice eval = new BestPractice();
assertEquals(10, eval.evaluator("2 3 9 4 / + *"));
assertEquals(70, eval.evaluator("25 45 +"));
}
}
| wuxinshui/noob | codewars/src/main/java/org/noob/codewars/train/learn/prac2017/prac170105/EvaluatorTest.java | Java | apache-2.0 | 1,245 |
import Vue from 'vue'
/**
* 递归初始化菜单列表,将menu下的子菜单添加tempList中
* */
function initMenu (menu, level, tempList) {
let childList = menu.childList
if (!childList) {
return
}
for (let i = 0; i < childList.length; i++) {
let childMenu = childList[i]
childMenu.level = level
Vue.set(childMenu, 'isShowInTable', level <= 3) // 是否显示,1,2,3级菜单默认显示
Vue.set(childMenu, 'isExpanded', level <= 2) // 是否展开菜单,1,2,3级菜单默认展开
tempList.push(childMenu)
initMenu(childMenu, level + 1, tempList)
}
}
/**
* 切换下一级菜单的状态,主要用于打开,打开的时候只显示下一级,且只修改本级的显示状态
* @param menu
* @param isShowInTable
*/
function toggleChildMenuList (menu, isShowInTable) {
// 修改子节点的显示状态
let list = menu.childList
if (list == null) {
return
}
for (let i = 0; i < list.length; i++) {
let childMenu = list[i]
childMenu.isShowInTable = isShowInTable
}
}
/**
* 递归切换所有菜单的状态,主要用于关闭,关闭的时候需要修改所有子节点的展开及显示状态
* @param menu
* @param isShowInTable
*/
function toggleChildMenuListRecursion (menu, isShowInTable) {
// 修改子节点的现实状态
let list = menu.childList
if (list == null) {
return
}
for (let i = 0; i < list.length; i++) {
let childMenu = list[i]
childMenu.isShowInTable = isShowInTable
childMenu.isExpanded = isShowInTable
toggleChildMenuListRecursion(childMenu, isShowInTable)
}
}
/**
* 收缩 / 展开 全部菜单
* @param topMenu
* @param isShowInTable
*/
function toggleAllMenu (topMenu, isShowInTable) {
let list = topMenu.childList
for (let i = 0; i < list.length; i++) {
let childMenu = list[i]
childMenu.isExpanded = isShowInTable
toggleChildMenuListRecursion(childMenu, isShowInTable)
}
}
function removeFromTopElement (topElement, element) {
let list = topElement.childList
if (list == null) {
return
}
list.forEach((childMenu, i) => {
if (childMenu.id === element.id) {
childMenu.childList = null
list.splice(i, 1)
}
removeFromTopElement(childMenu, element)
})
}
const TreeTableMiXin = {
data: function () {
return {
/**
* 展开状态
*/
toggleStatus: true
}
},
computed: {
dataList: function () {
let tempList = []
if (this.topElement) {
initMenu(this.topElement, 1, tempList)
}
return tempList
}
},
methods: {
/**
* 展开/收缩 菜单
*/
toggle: function (menu) {
let isExpanded = menu.isExpanded
if (isExpanded) {
toggleChildMenuListRecursion(menu, !isExpanded)
} else {
toggleChildMenuList(menu, !isExpanded)
}
menu.isExpanded = !isExpanded
},
/**
* 全部展开/收缩 菜单
*/
toggleAll: function () {
toggleAllMenu(this.topElement, !this.toggleStatus)
this.toggleStatus = !this.toggleStatus
},
/**
* 移除元素以及该元素的子元素
*/
removeElement (element) {
removeFromTopElement(this.topElement, element)
}
}
}
export default TreeTableMiXin
| lcw2004/one | one-ui/src/common/mixins/TreeTableMiXin.js | JavaScript | apache-2.0 | 3,287 |
/**
* A collection of service classes that are internally used by SeLion for all reporting related activities.
*/
package com.paypal.selion.reports.reporter.services; | mengchen2/SeLion_Demo | client/src/main/java/com/paypal/selion/reports/reporter/services/package-info.java | Java | apache-2.0 | 168 |
/* @flow */
export const ALIGN_ITEMS = {
start: 'start',
end: 'end',
center: 'center',
stretch: 'stretch'
};
export const GUTTER_WIDTH = {
xxs: 'xxs',
xs: 'xs',
sm: 'sm',
md: 'md',
lg: 'lg',
xl: 'xl',
xxl: 'xxl'
};
| mineral-ui/mineral-ui | src/library/Grid/constants.js | JavaScript | apache-2.0 | 238 |
/*
Copyright 2017 Shane Lillie
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using EnergonSoftware.BackpackPlanner.Settings;
using EnergonSoftware.BackpackPlanner.Units.Units;
using JetBrains.Annotations;
using Newtonsoft.Json;
namespace EnergonSoftware.BackpackPlanner.DAL.Models.Meals
{
[Serializable]
public class MealEntry<T> : BaseModelEntry<MealEntry<T>, T, Meal> where T: BaseModel<T>, new()
{
#region Static Helpers
public static int GetMealCount<TE>(IReadOnlyCollection<TE> meals, [CanBeNull] ICollection<int> visitedMeals)
where TE: MealEntry<T>
{
int count = 0;
foreach(TE meal in meals) {
if(visitedMeals?.Contains(meal.ModelId) ?? false) {
continue;
}
visitedMeals?.Add(meal.ModelId);
count += meal.Count;
}
return count;
}
public static int GetTotalCalories<TE>(IReadOnlyCollection<TE> meals, [CanBeNull] ICollection<int> visitedMeals)
where TE: MealEntry<T>
{
int calories = 0;
foreach(TE meal in meals) {
if(visitedMeals?.Contains(meal.ModelId) ?? false) {
continue;
}
visitedMeals?.Add(meal.ModelId);
calories += meal.Calories;
}
return calories;
}
public static int GetTotalWeightInGrams<TE>(IReadOnlyCollection<TE> meals, [CanBeNull] ICollection<int> visitedMeals)
where TE: MealEntry<T>
{
int weightInGrams = 0;
foreach(TE meal in meals) {
if(visitedMeals?.Contains(meal.ModelId) ?? false) {
continue;
}
visitedMeals?.Add(meal.ModelId);
weightInGrams += meal.TotalWeightInGrams;
}
return weightInGrams;
}
// ReSharper disable once InconsistentNaming
public static int GetTotalCostInUSDP<TE>(IReadOnlyCollection<TE> meals, [CanBeNull] ICollection<int> visitedMeals)
where TE: MealEntry<T>
{
// ReSharper disable once InconsistentNaming
int costInUSDP = 0;
foreach(TE meal in meals) {
if(visitedMeals?.Contains(meal.ModelId) ?? false) {
continue;
}
visitedMeals?.Add(meal.ModelId);
costInUSDP += meal.TotalCostInUSDP;
}
return costInUSDP;
}
#endregion
public override int Id => MealEntryId;
#region Database Properties
/// <summary>
/// Gets or sets the meal entry identifier.
/// </summary>
/// <value>
/// The meal entry identifier.
/// </value>
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MealEntryId { get; private set; }
[Required, ForeignKey("Model")]
public override int ModelId { get; protected set; }
public override Meal Model { get; protected set; }
#endregion
public override MealEntry<T> DeepCopy()
{
MealEntry<T> mealEntry = base.DeepCopy();
mealEntry.MealEntryId = MealEntryId;
return mealEntry;
}
[NotMapped, JsonIgnore]
public int Calories => Count * (Model?.Calories ?? 0);
[NotMapped, JsonIgnore]
public int TotalWeightInGrams => Count * (Model?.WeightInGrams ?? 0);
public float GetTotalWeightInUnits(BackpackPlannerSettings settings)
{
return settings.Units.WeightFromGrams(TotalWeightInGrams);
}
[NotMapped, JsonIgnore]
// ReSharper disable once InconsistentNaming
public int TotalCostInUSDP => Count * (Model?.CostInUSDP ?? 0);
public MealEntry(Meal meal)
: base(meal)
{
}
public MealEntry()
{
}
}
}
| Luminoth/BackpackPlanner | BackpackPlanner/BackpackPlanner/DAL/Models/Meals/MealEntry.cs | C# | apache-2.0 | 4,668 |
/*
* Copyright 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
*
* 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.github.i49.cascade.core.matchers.simple;
/**
* The matcher which tests if attribute value starts with the specified prefix.
*/
public class PrefixMatcher extends AttributeValueMatcher {
public PrefixMatcher(AttributeNameMatcher nameMatcher, String prefix) {
super(nameMatcher, prefix);
}
@Override
public boolean matchesNever() {
return getExpectedValue().isEmpty();
}
@Override
protected String getSymbol() {
return "^=";
}
@Override
public boolean testValue(String actualValue) {
final String expectedValue = getExpectedValue();
if (expectedValue.isEmpty()) {
return false;
}
return actualValue.startsWith(expectedValue);
}
}
| i49/cascade | cascade/src/main/java/io/github/i49/cascade/core/matchers/simple/PrefixMatcher.java | Java | apache-2.0 | 1,374 |
package cn.com.heaton.blelibrary.ble.callback;
/**
*
* Created by LiuLei on 2017/10/23.
*/
public abstract class BleWriteEntityCallback<T> {
public abstract void onWriteSuccess();
public abstract void onWriteFailed();
public void onWriteProgress(double progress){}
public void onWriteCancel(){}
}
| liulei-0911/BleDemo | core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleWriteEntityCallback.java | Java | apache-2.0 | 318 |
# Dichaea standleyi Ames SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Dichaea/Dichaea acroblepara/ Syn. Dichaea standleyi/README.md | Markdown | apache-2.0 | 179 |
# Geranium umbrosum Waldst. & Kit. in Waldst. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Geraniales/Geraniaceae/Geranium/Geranium pyrenaicum/ Syn. Geranium umbrosum/README.md | Markdown | apache-2.0 | 200 |
# Alchemilla microsphaerica Frohner SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Alchemilla/Alchemilla microsphaerica/README.md | Markdown | apache-2.0 | 183 |
# Pseudofuscophialis Sivan. & H.S. Chang GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Mycol. Res. 99(6): 711 (1995)
#### Original name
Pseudofuscophialis Sivan. & H.S. Chang
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Sordariomycetes/Hypocreales/Pseudofuscophialis/README.md | Markdown | apache-2.0 | 253 |
# Rajania cordata var. eucordata VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Dioscoreales/Dioscoreaceae/Rajania/Rajania cordata/ Syn. Rajania cordata eucordata/README.md | Markdown | apache-2.0 | 187 |
# Heliochia ×vandesii G.D.Rowley SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Heliochia/Heliochia vandesii/README.md | Markdown | apache-2.0 | 181 |
# Cyphomandra amotapensis (Svenson) A.Child SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Solanum/Solanum amotapense/ Syn. Cyphomandra amotapensis/README.md | Markdown | apache-2.0 | 198 |
# Sorbaronia sorbifolia (hort. ex Poir.) C.K.Schneid. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Repert. Spec. Nov. Regni Veg. 3:134. 1906
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Sorbaronia/Sorbaronia sorbifolia/README.md | Markdown | apache-2.0 | 246 |
# Spergularia diandroides L.G.Adams SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Spergularia/Spergularia diandroides/README.md | Markdown | apache-2.0 | 183 |
# Perityle carmenensis A.M.Powell SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Perityle carmenensis/README.md | Markdown | apache-2.0 | 181 |
# Witheringia rhomboidea Dunal SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Witheringia/Witheringia rhomboidea/README.md | Markdown | apache-2.0 | 178 |
package com.juchao.upg.android.entity;
public class InspectionTask {
public int _id;
public long id;
public String taskName;
public String startTime;
public String endTime;
public int index; //任务序号 不保存数据库
public boolean isDownloaded; //是否已经下载对应的点检任务
public int state; //0 :未完成 , 1:已完成
//public int type; //0:定常点检任务 1:自定义点检任务 2:特种设备点检任务
//public int style; //0:定常点检任务 1:自定义点检任务 2:特种设备点检任务
public int status; //0:定常点检任务 1:自定义点检任务 2:特种设备点检任务
public int waitUploadNum; //待上传数
// 存放点检类型值 1、年度;2、 季度;3、 月度;4、周常;5、 日常;6、维修;7、自定义
public int intervalType;
}
| Jack-Xiao/UPG_2 | src/com/juchao/upg/android/entity/InspectionTask.java | Java | apache-2.0 | 856 |
### Description
This moves (0,0) from the bottom left corner of the image to the center of the image.
| lorensen/VTKExamples | src/Cxx/Images/CenterAnImage.md | Markdown | apache-2.0 | 102 |
package com.fcdream.dress.kenny.bo;
import android.os.Environment;
import com.fcdream.dress.kenny.utils.FileUtils;
/**
* Copyright (c) 2017, 北京视达科科技有限责任公司 All rights reserved.
* author:shumeng.du
* date:2017/9/4
* description:
*/
public class MyFilePathEntity {
private String baiduSpeechPath;
public static final String BAIDU_SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female.dat";
public static final String BAIDU_SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male.dat";
public static final String BAIDU_TEXT_MODEL_NAME = "bd_etts_text.dat";
public static final String BAIDU_ENGLISH_SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female_en.dat";
public static final String BAIDU_ENGLISH_SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male_en.dat";
public static final String BAIDU_ENGLISH_TEXT_MODEL_NAME = "bd_etts_text_en.dat";
private static final MyFilePathEntity instance = new MyFilePathEntity();
private MyFilePathEntity() {
String sdcardPath = Environment.getExternalStorageDirectory().toString();
baiduSpeechPath = sdcardPath + "/baiduTTS";
}
public String getSpeechModelPath(String modelName) {
return baiduSpeechPath + "/" + modelName;
}
public void init() {
FileUtils.makeDir(baiduSpeechPath);
}
public static MyFilePathEntity getInstance() {
return instance;
}
}
| dushumeng/DressKenny | app/src/main/java/com/fcdream/dress/kenny/bo/MyFilePathEntity.java | Java | apache-2.0 | 1,415 |
SELECT kdsup FROM m04supl
SELECT t02_id, tanggal,
m03.kd_tabung AS kd_tabung, m03.jenis_tabung AS jenis_tabung,
m03.harga AS harga, m04.kdsup AS kdsup,
m04.nmsup AS nmsup, jumlah, t02.keterangan
FROM kkp.t02beli t02
INNER JOIN m03tabu m03
ON m03.kd_tabung = t02.kd_tabung
INNER JOIN m04supl m04
ON m04.kdsup = t02.kdsupl;
INSERT INTO kkp.t02beli (tanggal, kd_tabung, kdsupl, jumlah, keterangan)
VALUES (?,?,?,?,?);
SELECT t02_id, tanggal,
m03.kd_tabung AS kd_tabung, m03.jenis_tabung AS jenis_tabung,
m03.harga AS harga, m04.kdsup AS kdsup,
m04.nmsup AS nmsup, jumlah, t02.keterangan
FROM kkp.t02beli t02
INNER JOIN m03tabu m03
ON m03.kd_tabung = t02.kd_tabung
INNER JOIN m04supl m04
ON m04.kdsup = t02.kdsupl
WHERE tanggal = ? AND m03.kd_tabung LIKE ? AND m04.kdsup LIKE ?;
DELETE FROM t02beli WHERE t02_id= ?;
UPDATE t02beli SET
tanggal = ?,
kd_tabung= ?,
kdsupl= ?,
jumlah = ?
keterangan = ?
WHERE t02_id = ?; | hidayanto56/KKP | Script/t02beli.sql | SQL | apache-2.0 | 935 |
# Gloeosporium falcatum Dearn. & House SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Bull. N. Y. St. Mus. 188: 133 (1916)
#### Original name
Gloeosporium falcatum Dearn. & House
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Dermateaceae/Marssonina/Gloeosporium falcatum/README.md | Markdown | apache-2.0 | 233 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2017, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.svek;
import net.sourceforge.plantuml.graphic.StringBounder;
public class ShapePseudoImpl implements IShapePseudo {
private final String uid;
private final double width;
private final double height;
public ShapePseudoImpl(String uid, double width, double height) {
this.uid = uid;
this.width = width;
this.height = height;
}
public String getUid() {
return uid;
}
public void appendShape(StringBuilder sb, StringBounder stringBounder) {
sb.append(uid + " [shape=rect,label=\"\"");
sb.append(",width=" + SvekUtils.pixelToInches(width));
sb.append(",height=" + SvekUtils.pixelToInches(height));
sb.append("];");
}
}
| Banno/sbt-plantuml-plugin | src/main/java/net/sourceforge/plantuml/svek/ShapePseudoImpl.java | Java | apache-2.0 | 1,599 |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Management.Monitoring.Autoscale;
namespace Microsoft.WindowsAzure.Management.Monitoring.Autoscale
{
public partial class AutoscaleClient : ServiceClient<AutoscaleClient>, IAutoscaleClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private ISettingOperations _settings;
/// <summary>
/// Operations for managing the autoscale settings.
/// </summary>
public virtual ISettingOperations Settings
{
get { return this._settings; }
}
/// <summary>
/// Initializes a new instance of the AutoscaleClient class.
/// </summary>
private AutoscaleClient()
: base()
{
this._settings = new SettingOperations(this);
this._apiVersion = "2013-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AutoscaleClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public AutoscaleClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutoscaleClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public AutoscaleClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutoscaleClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private AutoscaleClient(HttpClient httpClient)
: base(httpClient)
{
this._settings = new SettingOperations(this);
this._apiVersion = "2013-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AutoscaleClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutoscaleClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutoscaleClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutoscaleClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another AutoscaleClient
/// instance
/// </summary>
/// <param name='client'>
/// Instance of AutoscaleClient to clone to
/// </param>
protected override void Clone(ServiceClient<AutoscaleClient> client)
{
base.Clone(client);
if (client is AutoscaleClient)
{
AutoscaleClient clonedClient = ((AutoscaleClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| jianghaolu/azure-sdk-for-net | src/Monitoring/Generated/Autoscale/AutoscaleClient.cs | C# | apache-2.0 | 9,277 |
/*
* Copyright 2018 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
*
* 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.gradle.internal.resolve.caching;
import org.gradle.api.Transformer;
import org.gradle.api.artifacts.ComponentMetadataContext;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.ResolvedModuleVersion;
import org.gradle.api.internal.artifacts.configurations.dynamicversion.CachePolicy;
import org.gradle.cache.CacheRepository;
import org.gradle.cache.internal.InMemoryCacheDecoratorFactory;
import org.gradle.internal.component.external.model.ModuleComponentResolveMetadata;
import org.gradle.internal.serialize.Serializer;
import org.gradle.internal.snapshot.ValueSnapshotter;
import org.gradle.util.BuildCommencedTimeProvider;
import java.io.Serializable;
public class ComponentMetadataRuleExecutor extends CrossBuildCachingRuleExecutor<ModuleComponentResolveMetadata, ComponentMetadataContext, ModuleComponentResolveMetadata> {
private static Transformer<Object, ModuleComponentResolveMetadata> getKeyToSnapshotableTransformer() {
return new Transformer<Object, ModuleComponentResolveMetadata>() {
@Override
public Serializable transform(ModuleComponentResolveMetadata moduleMetadata) {
return moduleMetadata.getOriginalContentHash().asHexString();
}
};
}
private final Serializer<ModuleComponentResolveMetadata> componentMetadataContextSerializer;
public ComponentMetadataRuleExecutor(CacheRepository cacheRepository,
InMemoryCacheDecoratorFactory cacheDecoratorFactory,
ValueSnapshotter snapshotter,
BuildCommencedTimeProvider timeProvider,
Serializer<ModuleComponentResolveMetadata> componentMetadataContextSerializer) {
super("md-rule", cacheRepository, cacheDecoratorFactory, snapshotter, timeProvider, createValidator(timeProvider), getKeyToSnapshotableTransformer(), componentMetadataContextSerializer);
this.componentMetadataContextSerializer = componentMetadataContextSerializer;
}
public Serializer<ModuleComponentResolveMetadata> getComponentMetadataContextSerializer() {
return componentMetadataContextSerializer;
}
private static EntryValidator<ModuleComponentResolveMetadata> createValidator(final BuildCommencedTimeProvider timeProvider) {
return new CrossBuildCachingRuleExecutor.EntryValidator<ModuleComponentResolveMetadata>() {
@Override
public boolean isValid(CachePolicy policy, final CrossBuildCachingRuleExecutor.CachedEntry<ModuleComponentResolveMetadata> entry) {
long age = timeProvider.getCurrentTime() - entry.getTimestamp();
final ModuleComponentResolveMetadata result = entry.getResult();
boolean mustRefreshModule = policy.mustRefreshModule(new SimpleResolvedModuleVersion(result.getModuleVersionId()), age, result.isChanging());
return !mustRefreshModule;
}
};
}
private static class SimpleResolvedModuleVersion implements ResolvedModuleVersion {
private final ModuleVersionIdentifier identifier;
private SimpleResolvedModuleVersion(ModuleVersionIdentifier identifier) {
this.identifier = identifier;
}
@Override
public ModuleVersionIdentifier getId() {
return identifier;
}
}
}
| robinverduijn/gradle | subprojects/dependency-management/src/main/java/org/gradle/internal/resolve/caching/ComponentMetadataRuleExecutor.java | Java | apache-2.0 | 4,079 |
/*
Copyright 2022 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by injection-gen. DO NOT EDIT.
package fake
import (
context "context"
factoryfiltered "knative.dev/operator/pkg/client/injection/informers/factory/filtered"
filtered "knative.dev/operator/pkg/client/injection/informers/operator/v1alpha1/knativeserving/filtered"
controller "knative.dev/pkg/controller"
injection "knative.dev/pkg/injection"
logging "knative.dev/pkg/logging"
)
var Get = filtered.Get
func init() {
injection.Fake.RegisterFilteredInformers(withInformer)
}
func withInformer(ctx context.Context) (context.Context, []controller.Informer) {
untyped := ctx.Value(factoryfiltered.LabelKey{})
if untyped == nil {
logging.FromContext(ctx).Panic(
"Unable to fetch labelkey from context.")
}
labelSelectors := untyped.([]string)
infs := []controller.Informer{}
for _, selector := range labelSelectors {
f := factoryfiltered.Get(ctx, selector)
inf := f.Operator().V1alpha1().KnativeServings()
ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf)
infs = append(infs, inf.Informer())
}
return ctx, infs
}
| knative/operator | pkg/client/injection/informers/operator/v1alpha1/knativeserving/filtered/fake/fake.go | GO | apache-2.0 | 1,642 |
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../獄/index.html">
<meta http-equiv=refresh content="0; url='../獄/index.html'">
<h1>Redirecting...</h1>
<a href="../獄/index.html">Click here if you are not redirected.</a>
<script>location='../獄/index.html'</script>
| hochanh/hochanh.github.io | rtk/v4/338.html | HTML | apache-2.0 | 316 |
---
layout: kanji
v4: 484
v6: 523
kanji: 境
keyword: boundary
elements: boundary, soil, dirt, ground, mirror, vase, stand up, sun, day, human legs
strokes: 14
image: E5A283
on-yomi: キョウ、ケイ
kun-yomi: さかい
permalink: /rtk/境/
prev: 鏡
next: 亡
---
1) [<a href="http://kanji.koohii.com/profile/nyquil">nyquil</a>] 13-3-2007(195): In the dense cities of Japan even a small garden is a luxury. In this house, the owner has put <em>mirrors</em> on the<strong> boundary</strong> of his <em>land</em> so it feels much bigger.
2) [<a href="http://kanji.koohii.com/profile/brose">brose</a>] 16-12-2006(108): This is an old trick to keep out migrants. You put a bunch of dirty mirrors on the<strong> boundary</strong> of your land and theirs. When they approach the<strong> boundary</strong>, what they see in the mirror is their own land and someone that looks like themselves, only dirtier, so they figure your country isn't any better than their own and they head back home.
3) [<a href="http://kanji.koohii.com/profile/Danieru">Danieru</a>] 25-1-2008(33): <strong>Boundaries</strong> and borders (another meaning of this kanji) used to be protected by daggers and swords (see <strong>environs</strong>, frame 284); but today our <em>lands</em> are protected by one-way <em>mirrors</em> at airport customs with video cameras and interrogation rooms behind them.
4) [<a href="http://kanji.koohii.com/profile/tstuhldreher">tstuhldreher</a>] 6-6-2008(20): In Japan, you often see MIRRORS at intersections. That's because the walls that form the<strong> boundary</strong> of people's LAND make it hard to see around corners.
5) [<a href="http://kanji.koohii.com/profile/Rujiel">Rujiel</a>] 30-7-2009(19): Be aware the right-hand character 竟 really means "endpoint" or "finally"; it's commonly read "つい" (as in "ついに") and usually written in kana alone. A<strong> boundary</strong> represents a country's <em>land</em>'s <em>endpoint</em> (awkward phrasing for order) .
| hochanh/hochanh.github.io | rtk/rtk1-v6/0523.md | Markdown | apache-2.0 | 2,065 |
---
layout: global
title: 在Azure Blob Store上配置Alluxio
nickname: Alluxio使用Azure Blob Store
group: Under Store
priority: 0
---
* 内容列表
{:toc}
该指南介绍了如何配置Alluxio以使用[Azure Blob Store](https://azure.microsoft.com/en-in/services/storage/blobs/)作为底层存储系统。
## 初始步骤
为了在多台机器上运行一个Alluxio集群,你必须在每台机器上部署Alluxio的二进制文件。
你可以[从Alluxio源码编译二进制文件](Building-Alluxio-Master-Branch.html),或者[直接下载已经编译好的Alluxio二进制文件](Running-Alluxio-Locally.html)。
而且,为了在Alluxio上使用Azure Blob Store,在你的Azure storage帐户上创建一个新的container或者使用一个已有的container。你应该注意你在这个container里准备使用的目录,你可以在这个容器里面创建一个目录,或者使用一个已有的目录。鉴于这篇文章的目的,我们将Azure storage帐户名取名为`AZURE_ACCOUNT`,将帐户里的容器取名为`AZURE_CONTAINER`并将该container里面的目录称为`AZURE_DIRECTORY`。更多关于Azure storage帐户的信息,请看[这里](https://docs.microsoft.com/en-us/azure/storage/storage-create-storage-account)。
## 配置Alluxio
你需要通过修改`conf/alluxio-site.properties`配置Alluxio使用底层存储系统。如果这个文件不存在,重命名template文件。
```bash
$ cp conf/alluxio-site.properties.template conf/alluxio-site.properties
```
Alluxio可以通过HDFS接口支持Azure Blob store。你可以在[这里](http://hadoop.apache.org/docs/r2.7.1/hadoop-azure/index.html)找到更多关于在Azure blob store上运行hadoop的信息。
从[这里](https://mvnrepository.com/artifact/com.microsoft.azure/azure-storage)下载azure storage的java库(版本2.2.0)并根据你的Hadoop版本从[这里](https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-azure)下载hadoop azure库。请确定使用了 `azure-storage-2.2.0.jar`而不是任何更高版本的,因为这些版本会与hadoop-azure库冲突。
你需要将上面提到的库加入到`ALLUXIO_CLASSPATH`。你可以通过在`conf/alluxio-env.sh`中添加以下代码来完成:
```
export ALLUXIO_CLASSPATH=PATH_TO_HADOOP_AZURE_JAR/hadoop-azure-2.7.3.jar:PATH_TO_AZURE_STORAGE_JAR/azure-storage-2.2.0.jar
```
你需要配置Alluxio以使用Azure Blob Store作为底层存储系统。第一个需要修改的地方就是指定底层文件系统的地址并且设置hdfs前缀以便Alluxio可以识别 `wasb://`机制,你需要修改`conf/alluxio-site.properties`以包含以下内容:
```
alluxio.underfs.address=wasb://AZURE_CONTAINER@AZURE_ACCOUNT.blob.core.windows.net/AZURE_DIRECTORY/
alluxio.underfs.hdfs.prefixes=hdfs://,glusterfs:///,maprfs:///,wasb://
```
接着你需要通过将下列属性添加到`conf/core-site.xml`中来指定证书和wasb的实现类:
```
<configuration>
<property>
<name>fs.AbstractFileSystem.wasb.impl</name>
<value>org.apache.hadoop.fs.azure.Wasb</value>
</property>
<property>
<name>fs.azure.account.key.AZURE_ACCOUNT.blob.core.windows.net</name>
<value>YOUR ACCESS KEY</value>
</property>
</configuration>
```
完成这些修改后,Alluxio应该已经配置好以使用Azure Blob Store作为底层存储系统,你可以试着使用它本地运行Alluxio。
## 使用Azure Blob Store本地运行Alluxio
完成所有配置之后,你可以本地运行Alluxio,观察是否一切运行正常。
```
$ ./bin/alluxio format
$ ./bin/alluxio-start.sh local
```
该命令应当会启动一个Alluxio master和一个Alluxio worker,可以在浏览器中访问[http://localhost:19999](http://localhost:19999)查看master Web UI。
接着,你可以运行一个简单的示例程序:
```
$ ./bin/alluxio runTests
```
运行成功后,你可以访问你的容器AZURE_CONTAINER,确认其中包含了由Alluxio创建的文件和目录。该测试中,创建的文件名应该像下面这样:
```
AZURE_DIRECTORY/default_tests_files/BASIC_CACHE_PROMOTE_CACHE_THROUGH
```
若要停止Alluxio,你可以运行以下命令:
```
$ ./bin/alluxio-stop.sh local
```
| ChangerYoung/alluxio | docs/cn/Configuring-Alluxio-with-Azure-Blob-Store.md | Markdown | apache-2.0 | 4,185 |
[](https://gitter.im/openzipkin/zipkin) [](https://travis-ci.org/openzipkin/zipkin) [ ](https://bintray.com/openzipkin/zipkin/zipkin/_latestVersion)

[Zipkin](http://twitter.github.com/zipkin) is a distributed tracing system. It is used by Twitter to help gather timing data for all their disparate services. The front end is a "waterfall" style graph of service calls showing call durations as horizontal bars:

## Running Zipkin
Zipkin is a collection of processes (a backend for the data, a
"collector", and query engine, and a web UI) and all of them need to
be running to make any progress:

If you are familiar with Docker, the
quickest way to get started quickly is to use the
[Docker Zipkin](https://github.com/openzipkin/docker-zipkin) project,
which (in addition to being able to build docker images) provides
scripts and a
[`docker-compose.yml`](https://github.com/openzipkin/docker-zipkin/blob/master/deploy/docker-compose.yml)
for launching pre-built images, e.g.
```
$ git clone https://github.com/openzipkin/docker-zipkin
$ cd docker-zipkin/deploy
$ docker-compose up
```
If you are happy building from source you can use the scripts in the
[`bin`](bin) directory of this repository.
Here's how to start zipkin using the default file-based backend and view traces.
```bash
# get the zipkin source and change to its directory
$ git clone https://github.com/openzipkin/zipkin; cd zipkin
# start the collector server in a new terminal session or tab
$ ./bin/collector
# start the query server in a new terminal session or tab
$ ./bin/query
# start the web server in a new terminal session or tab
$ ./bin/web
# create dummy traces
$ ./bin/tracegen
# open the ui and look at them!
$ open http://localhost:8080/
```
## Full documentation
See [http://twitter.github.com/zipkin](http://twitter.github.com/zipkin)
## Get involved
Join the [openzipkin/zipkin gitter chat](https://gitter.im/openzipkin/zipkin)
for questions and to talk with the developers. Otherwise, there are two mailing
lists you can use to get in touch with other users and developers.
Users: [https://groups.google.com/group/zipkin-user](https://groups.google.com/group/zipkin-user)
Developers: [https://groups.google.com/group/zipkin-dev](https://groups.google.com/group/zipkin-dev)
## Issues
Noticed a bug? [Please file an issue](https://github.com/openzipkin/zipkin/issues)
## Contributing
See [CONTRIBUTING.md](https://github.com/openzipkin/zipkin/blob/master/CONTRIBUTING.md) for guidelines.
Areas where we'd love to see contributions:
* adding tracing to more libraries and protocols
* interesting reports generated with Hadoop from the trace data
* extending collector to support more transports and storage systems
* trace data visualizations in the web UI
| yshaojie/zipkin | README.md | Markdown | apache-2.0 | 3,296 |
# Auganthus cortusoides (L.) Soják SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Primulaceae/Auganthus/Auganthus cortusoides/README.md | Markdown | apache-2.0 | 183 |
/*
* Copyright (c) 2008-2015 Citrix Systems, 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.citrix.sdx.nitro.resource.config.mps;
import com.citrix.sdx.nitro.resource.base.*;
import com.citrix.sdx.nitro.datatypes.*;
import com.citrix.sdx.nitro.service.nitro_service;
import com.citrix.sdx.nitro.service.options;
import com.citrix.sdx.nitro.exception.nitro_exception;
import com.citrix.sdx.nitro.util.filtervalue;
class current_timezone_response extends base_response
{
public current_timezone[] current_timezone;
}
class current_timezone_responses extends base_response
{
public current_timezone_response[] current_timezone_response_array;
}
/**
* Configuration for Current timezone resource
*/
public class current_timezone extends base_resource
{
private String timezone;
private Long __count;
protected String get_object_type()
{
return "current_timezone";
}
/**
* Returns the value of object identifier argument.
*/
protected String get_object_id()
{
return null;
}
/**
* <pre>
* Timezone
* </pre>
*/
public void set_timezone(String timezone)
{
this.timezone = timezone;
}
/**
* <pre>
* Timezone
* </pre>
*/
public String get_timezone()
{
return this.timezone;
}
/**
* Use this operation to get the current time zone.
*/
public static current_timezone get(nitro_service client) throws Exception
{
current_timezone resource = new current_timezone();
resource.validate("get");
return ((current_timezone[]) resource.get_resources(client))[0];
}
/**
* <pre>
* Use this operation to modify current time zone.
* </pre>
*/
public static current_timezone update(nitro_service client, current_timezone resource) throws Exception
{
resource.validate("modify");
return ((current_timezone[]) resource.update_resource(client))[0];
}
/**
* Use this API to fetch filtered set of current_timezone resources.
* filter string should be in JSON format.eg: "vm_state:DOWN,name:[a-z]+"
*/
public static current_timezone[] get_filtered(nitro_service service, String filter) throws Exception
{
current_timezone obj = new current_timezone();
options option = new options();
option.set_filter(filter);
current_timezone[] response = (current_timezone[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to fetch filtered set of current_timezone resources.
* set the filter parameter values in filtervalue object.
*/
public static current_timezone[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception
{
current_timezone obj = new current_timezone();
options option = new options();
option.set_filter(filter);
current_timezone[] response = (current_timezone[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to count the current_timezone resources configured on NetScaler SDX.
*/
public static long count(nitro_service service) throws Exception
{
current_timezone obj = new current_timezone();
options option = new options();
option.set_count(true);
current_timezone[] response = (current_timezone[])obj.get_resources(service, option);
if (response != null && response.length > 0)
return response[0].__count;
return 0;
}
/**
* Use this API to count the filtered set of current_timezone resources.
* filter string should be in JSON format.eg: "vm_state:DOWN,name:[a-z]+"
*/
public static long count_filtered(nitro_service service, String filter) throws Exception
{
current_timezone obj = new current_timezone();
options option = new options();
option.set_count(true);
option.set_filter(filter);
current_timezone[] response = (current_timezone[])obj.get_resources(service, option);
if (response != null && response.length > 0)
return response[0].__count;
return 0;
}
/**
* Use this API to count the filtered set of current_timezone resources.
* set the filter parameter values in filtervalue object.
*/
public static long count_filtered(nitro_service service, filtervalue[] filter) throws Exception
{
current_timezone obj = new current_timezone();
options option = new options();
option.set_count(true);
option.set_filter(filter);
current_timezone[] response = (current_timezone[])obj.get_resources(service, option);
if (response != null && response.length > 0)
return response[0].__count;
return 0;
}
/**
* <pre>
* Converts API response into object and returns the object array in case of get request.
* </pre>
*/
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception
{
current_timezone_response result = (current_timezone_response) service.get_payload_formatter().string_to_resource(current_timezone_response.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
if(result.severity != null)
{
if(result.severity.equals("ERROR"))
throw new nitro_exception(result.message, result.errorcode);
}
else
{
throw new nitro_exception(result.message, result.errorcode);
}
}
return result.current_timezone;
}
/**
* <pre>
* Converts API response of bulk operation into object and returns the object array in case of get request.
* </pre>
*/
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
current_timezone_responses result = (current_timezone_responses) service.get_payload_formatter().string_to_resource(current_timezone_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.current_timezone_response_array);
}
current_timezone[] result_current_timezone = new current_timezone[result.current_timezone_response_array.length];
for(int i = 0; i < result.current_timezone_response_array.length; i++)
{
result_current_timezone[i] = result.current_timezone_response_array[i].current_timezone[0];
}
return result_current_timezone;
}
/**
* <pre>
* Performs generic data validation for the operation to be performed
* </pre>
*/
protected void validate(String operationType) throws Exception
{
super.validate(operationType);
MPSString timezone_validator = new MPSString();
timezone_validator.validate(operationType, timezone, "\"timezone\"");
}
}
| netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/mps/current_timezone.java | Java | apache-2.0 | 7,188 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.macie2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.macie2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DisassociateMemberRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DisassociateMemberRequestProtocolMarshaller implements Marshaller<Request<DisassociateMemberRequest>, DisassociateMemberRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/members/disassociate/{id}")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AmazonMacie2").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DisassociateMemberRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DisassociateMemberRequest> marshall(DisassociateMemberRequest disassociateMemberRequest) {
if (disassociateMemberRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DisassociateMemberRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
disassociateMemberRequest);
protocolMarshaller.startMarshalling();
DisassociateMemberRequestMarshaller.getInstance().marshall(disassociateMemberRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/transform/DisassociateMemberRequestProtocolMarshaller.java | Java | apache-2.0 | 2,690 |
package org.example.message
import akka.actor.{Actor, ActorLogging}
import org.example.message.TeacherProtocol._
/**
* Created by kailianghe on 1/8/15.
*/
class TeacherActor extends Actor with ActorLogging {
val quotes = List(
"Moderation is for cowards",
"Anything worth doing is worth overdoing",
"The trouble is you think you have time",
"You never gonna know if you never even try")
def receive = {
case QuoteRequest => {
import scala.util.Random
//Get a random Quote from the list and construct a response
val quoteResponse = QuoteResponse(quotes(Random.nextInt(quotes.size)))
log.info(quoteResponse.toString())
}
}
//We'll cover the purpose of this method in the Testing section
def quoteList = quotes
}
| hekailiang/akka-play | actor-samples/src/main/scala/org/example/message/TeacherActor.scala | Scala | apache-2.0 | 776 |
/*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2004 Michael David Adams.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
/*
* Tree-Structured Filter Bank (TSFB) Library
*
* $Id$
*/
#ifndef JPC_TSFB_H
#define JPC_TSFB_H
/******************************************************************************\
* Includes.
\******************************************************************************/
#include "jasper/jas_seq.h"
#include "jpc_fix.h"
#include "jpc_qmfb.h"
/******************************************************************************\
* Constants.
\******************************************************************************/
#define JPC_TSFB_MAXBANDS (JPC_TSFB_MAXDEPTH * 3 + 1)
#define JPC_TSFB_MAXDEPTH 32
#define JPC_TSFB_RITIMODE JPC_QMFB1D_RITIMODE
#define JPC_TSFB_LL 0
#define JPC_TSFB_LH 1
#define JPC_TSFB_HL 2
#define JPC_TSFB_HH 3
/******************************************************************************\
* Types.
\******************************************************************************/
typedef struct {
int xstart;
int ystart;
int xend;
int yend;
int orient;
int locxstart;
int locystart;
int locxend;
int locyend;
jpc_fix_t synenergywt;
} jpc_tsfb_band_t;
typedef struct {
int numlvls;
jpc_qmfb2d_t *qmfb;
} jpc_tsfb_t;
/******************************************************************************\
* Functions.
\******************************************************************************/
/* Create a TSFB. */
jpc_tsfb_t *jpc_cod_gettsfb(int qmfbid, int numlevels);
/* Destroy a TSFB. */
void jpc_tsfb_destroy(jpc_tsfb_t *tsfb);
/* Perform analysis. */
int jpc_tsfb_analyze(jpc_tsfb_t *tsfb, jas_seq2d_t *x);
/* Perform synthesis. */
int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *x);
int jpc_tsfb_analyze2(jpc_tsfb_t *tsfb, jpc_fix_t *a, int xstart, int ystart,
int width, int height, int stride, int numlvls);
int jpc_tsfb_synthesize2(jpc_tsfb_t *tsfb, jpc_fix_t *a, int xstart, int ystart,
int width, int height, int stride, int numlvls);
/* Get band information for a TSFB. */
int jpc_tsfb_getbands(jpc_tsfb_t *tsfb, uint_fast32_t xstart,
uint_fast32_t ystart, uint_fast32_t xend, uint_fast32_t yend,
jpc_tsfb_band_t *bands);
#endif
| LiberatorUSA/GUCEF | dependencies/jasper/src/libjasper/jpc/jpc_tsfb.h | C | apache-2.0 | 5,251 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pl">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.google.code.play2.provider.play25.Play25Provider (Play! 2.x Provider for Play! 2.5.x 1.0.0-rc5 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.google.code.play2.provider.play25.Play25Provider (Play! 2.x Provider for Play! 2.5.x 1.0.0-rc5 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/google/code/play2/provider/play25/Play25Provider.html" title="class in com.google.code.play2.provider.play25">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/google/code/play2/provider/play25/class-use/Play25Provider.html" target="_top">Frames</a></li>
<li><a href="Play25Provider.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.google.code.play2.provider.play25.Play25Provider" class="title">Uses of Class<br>com.google.code.play2.provider.play25.Play25Provider</h2>
</div>
<div class="classUseContainer">No usage of com.google.code.play2.provider.play25.Play25Provider</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/google/code/play2/provider/play25/Play25Provider.html" title="class in com.google.code.play2.provider.play25">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/google/code/play2/provider/play25/class-use/Play25Provider.html" target="_top">Frames</a></li>
<li><a href="Play25Provider.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2013–2019. All rights reserved.</small></p>
</body>
</html>
| play2-maven-plugin/play2-maven-plugin.github.io | play2-maven-plugin/1.0.0-rc5/play2-providers/play2-provider-play25/apidocs/com/google/code/play2/provider/play25/class-use/Play25Provider.html | HTML | apache-2.0 | 4,811 |
class Chef
module Provisioning
MAAS_DRIVER_VERSION = '0.1.0'
end
end
| chef-partners/chef-provisioning-maas | lib/chef/provisioning/maas_driver/version.rb | Ruby | apache-2.0 | 77 |
from bacnet import BACNetTransform
from cwmp import CWMPTransform
from dns import DNSTransform
from ftp import FTPTransform
from http import HTTPTransform
from http import HTTPWWWTransform
from https import HTTPSTransform
from https import HTTPSGetTransform
from https import HTTPSWWWTransform
from https import HeartbleedTransform
from https import RSAExportTransform
from https import DHETransform
from https import DHEExportTransform
from https import ECDHETransform
from https import TLSv10Transform
from https import TLSv11Transform
from https import TLSv12Transform
from https import TLSv13Transform
from https import SSLv3Transform
from imap import IMAPStartTLSTransform
from imap import IMAPSTransform
from modbus import ModbusTransform
from ntp import NTPTransform
from pop3 import POP3StartTLSTransform
from pop3 import POP3STransform
from s7 import S7Transform
from smtp import SMTPStartTLSTransform
from smtp import SMTPSTransform
from ssh import SSHV2Transform
from telnet import TelnetTransform
from upnp import UPnPTransform
from fox import NiagaraFoxTransform
from dnp3 import DNP3Transform
from sslv2 import SSLv2Transform
from smb import SMBTransform
from oracle import OracleTransform
from postgres import PostgresTransform
from mongodb import MongoDBTransform
from mssql import MSSQLTransform
from mysql import MySQLTransform
from ipp import IPPTransform | zmap/ztag | ztag/transforms/__init__.py | Python | apache-2.0 | 1,377 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (1.8.0_121) on Sun Oct 15 23:06:23 CEST 2017 -->
<title>org.shanerx.faketrollplus.core.data Class Hierarchy</title>
<meta name="date" content="2017-10-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.shanerx.faketrollplus.core.data Class Hierarchy";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.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/shanerx/faketrollplus/core/package-tree.html">Prev</a></li>
<li><a href="../../../../../org/shanerx/faketrollplus/utils/function/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/shanerx/faketrollplus/core/data/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.shanerx.faketrollplus.core.data</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="../../../../../org/shanerx/faketrollplus/core/data/LocalUserCache.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">LocalUserCache</span></a> (implements org.shanerx.faketrollplus.core.data.<a href="../../../../../org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data">UserCache</a>)</li>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="../../../../../org/shanerx/faketrollplus/core/data/RemoteUserCache.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">RemoteUserCache</span></a> (implements org.shanerx.faketrollplus.core.data.<a href="../../../../../org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data">UserCache</a>)</li>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="../../../../../org/shanerx/faketrollplus/core/data/TrollPlayer.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">TrollPlayer</span></a></li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="../../../../../org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">UserCache</span></a></li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.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/shanerx/faketrollplus/core/package-tree.html">Prev</a></li>
<li><a href="../../../../../org/shanerx/faketrollplus/utils/function/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/shanerx/faketrollplus/core/data/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| SparklingComet/FakeTrollPlus | doc/org/shanerx/faketrollplus/core/data/package-tree.html | HTML | apache-2.0 | 6,023 |
<?php
mysql_connect("localhost","root","");
mysql_select_db("my_database_gis");
$strSQL = "SELECT * FROM products";
$objQuery = mysql_query($strSQL) or die(mysql_error());
mysql_query("SET NAMES 'UTF8'");
mysql_query("SET character_set_results='UTF8'");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>admin_page</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/shop-homepage.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="logo pull-left">
<a href="#"><img src="image/logo.png" alt="" /></a>
</div>
</div>
<div class="col-sm-8">
<div class="shop-menu pull-right">
<ul class="nav navbar-nav">
<li><a href="#"><i class="glyphicon glyphicon-user"></i>สวัสดีคุณ Admin</a></li>
<li><a href="login.html"><i class="fa fa-lock"></i> ออกจากระบบ</a></li>
</ul>
</div>
</div>
</div>
</div>
</div><!--/header-middle-->
<!-- /.container -->
</nav>
<!-- Page Content -->
<div class="container">
<ul class="nav nav-tabs">
<li role="presentation"><a href="test.php">ตรวจสมาชิก<span class="badge">5</span></a></li>
<li role="presentation"class="active"><a href="admin.php">ตรวจสินค้า</a></li>
<li role="presentation"><a href="admin2.html">อัพเดทรายการสินค้า</a></li>
<li role="presentation"><a href="adminbuy.php">รายการสั่งซื้อ<span class="badge">2</span></a></li>
<li role="presentation"><a href="admin3.php">จำนวนการสั่งซื้อ</a></li>
<li role="presentation" ><a href="admincon.php">ติดต่อกลับ</a></li>
</ul>
<h2>ระบบตรวจสินค้า</h2>
<div class="col-xs-12 .col-sm-12">
<hr>
</hr>
</div>
<div class="col-xs-12 .col-sm-12">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">ตารางตรวจสอบระบบสินค้า</div>
<div class="panel-body">
<p> <table class="table table-condensed">
<thead>
<tr>
<th>ภาพสินค้า</th>
<th>รหัสสินค้า</th>
<th>ชื่อสินค้า</th>
<th>ราคา</th>
<th>ประเภท</th>
<th>รายละเอียดสินค้า</th>
<th>EDIT</th>
<th>DELETE</th>
<th></th>
</tr>
<?php
while($objResult = mysql_fetch_array($objQuery))
{
?>
<tr>
<th><img src="showpic.php?id=<?php echo $objResult['PID']; ?>" style="width: 72px; height: 72px;""></th>
<th>#<?php echo $objResult["PID"];?></th>
<th><?php echo $objResult["PName"];?></th>
<th><?php echo $objResult["Price"];?>บาท</th>
<th>ประเภทที่ : <?php echo $objResult["Type"];?></th>
<th><?php echo $objResult["Detail"];?></th>
<td align="center"><a href="JavaScript:if(confirm('Confirm Delete?')==true){window.location='adminbuydelete.php?OrderID=<?php echo $objResult["ID"];?>';}">EDIT</a></td>
<td align="center"><a href="JavaScript:if(confirm('Confirm Delete?')==true){window.location='productdelete.php?PID=<?php echo $objResult["PID"];?>';}">Delete</a></td>
</tr>
<?php
}
?>
</thead>
</table></p>
</div>
<!-- Table -->
</div>
</div>
</div>
<!-- /.container -->
<footer id="footer">
<!-- /.container -->
</footer><!--/Footer-->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
| ananpumankong/Helloword | admin.php | PHP | apache-2.0 | 4,812 |
/*
* 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.nifi.audit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import org.apache.nifi.action.Action;
import org.apache.nifi.action.Component;
import org.apache.nifi.action.Operation;
import org.apache.nifi.action.details.ActionDetails;
import org.apache.nifi.action.details.ConfigureDetails;
import org.apache.nifi.action.details.MoveDetails;
import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.web.security.user.NiFiUserUtils;
import org.apache.nifi.user.NiFiUser;
import org.apache.nifi.web.api.dto.ProcessGroupDTO;
import org.apache.nifi.web.dao.ProcessGroupDAO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Audits process group creation/removal and configuration changes.
*/
@Aspect
public class ProcessGroupAuditor extends NiFiAuditor {
private static final Logger logger = LoggerFactory.getLogger(ProcessGroupAuditor.class);
/**
* Audits the creation of process groups via createProcessGroup().
*
* This method only needs to be run 'after returning'. However, in Java 7
* the order in which these methods are returned from
* Class.getDeclaredMethods (even though there is no order guaranteed) seems
* to differ from Java 6. SpringAOP depends on this ordering to determine
* advice precedence. By normalizing all advice into Around advice we can
* alleviate this issue.
*
* @param proceedingJoinPoint
*/
// @AfterReturning(
// pointcut="within(org.apache.nifi.web.dao.ProcessGroupDAO+) && "
// + "execution(org.apache.nifi.web.api.dto.ProcessGroupDTO createProcessGroup(java.lang.String, org.apache.nifi.web.api.dto.ProcessGroupDTO))",
// returning="processGroup"
// )
@Around("within(org.apache.nifi.web.dao.ProcessGroupDAO+) && "
+ "execution(org.apache.nifi.groups.ProcessGroup createProcessGroup(java.lang.String, org.apache.nifi.web.api.dto.ProcessGroupDTO))")
public Object createProcessGroupAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// create the process group
ProcessGroup processGroup = (ProcessGroup) proceedingJoinPoint.proceed();
// if no exceptions were thrown, add the process group action...
// audit process group creation
final Action action = generateAuditRecord(processGroup, Operation.Add);
// save the actions
if (action != null) {
saveAction(action, logger);
}
return processGroup;
}
/**
* Audits the update of process group configuration.
*
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("within(org.apache.nifi.web.dao.ProcessGroupDAO+) && "
+ "execution(org.apache.nifi.groups.ProcessGroup updateProcessGroup(org.apache.nifi.web.api.dto.ProcessGroupDTO)) && "
+ "args(processGroupDTO)")
public Object updateProcessGroupAdvice(ProceedingJoinPoint proceedingJoinPoint, ProcessGroupDTO processGroupDTO) throws Throwable {
ProcessGroupDAO processGroupDAO = getProcessGroupDAO();
ProcessGroup processGroup = processGroupDAO.getProcessGroup(processGroupDTO.getId());
String name = processGroup.getName();
String comments = processGroup.getComments();
// perform the underlying operation
ProcessGroup updatedProcessGroup = (ProcessGroup) proceedingJoinPoint.proceed();
// get the current user
NiFiUser user = NiFiUserUtils.getNiFiUser();
// ensure the user was found
if (user != null) {
Collection<ActionDetails> details = new ArrayList<>();
// see if the name has changed
if (name != null && updatedProcessGroup.getName() != null && !name.equals(updatedProcessGroup.getName())) {
// create the config details
ConfigureDetails configDetails = new ConfigureDetails();
configDetails.setName("name");
configDetails.setValue(updatedProcessGroup.getName());
configDetails.setPreviousValue(name);
details.add(configDetails);
}
// see if the comments has changed
if (comments != null && updatedProcessGroup.getComments() != null && !comments.equals(updatedProcessGroup.getComments())) {
// create the config details
ConfigureDetails configDetails = new ConfigureDetails();
configDetails.setName("comments");
configDetails.setValue(updatedProcessGroup.getComments());
configDetails.setPreviousValue(comments);
details.add(configDetails);
}
// hold all actions
Collection<Action> actions = new ArrayList<>();
// save the actions if necessary
if (!details.isEmpty()) {
Date timestamp = new Date();
// create the actions
for (ActionDetails detail : details) {
// determine the type of operation being performed
Operation operation = Operation.Configure;
if (detail instanceof MoveDetails) {
operation = Operation.Move;
}
// create the port action for updating the name
Action processGroupAction = new Action();
processGroupAction.setUserDn(user.getDn());
processGroupAction.setUserName(user.getUserName());
processGroupAction.setOperation(operation);
processGroupAction.setTimestamp(timestamp);
processGroupAction.setSourceId(updatedProcessGroup.getIdentifier());
processGroupAction.setSourceName(updatedProcessGroup.getName());
processGroupAction.setSourceType(Component.ProcessGroup);
processGroupAction.setActionDetails(detail);
actions.add(processGroupAction);
}
}
// if the user was starting/stopping this process group
if (processGroupDTO.isRunning() != null) {
// create a process group action
Action processGroupAction = new Action();
processGroupAction.setUserDn(user.getDn());
processGroupAction.setUserName(user.getUserName());
processGroupAction.setSourceId(processGroup.getIdentifier());
processGroupAction.setSourceName(processGroup.getName());
processGroupAction.setSourceType(Component.ProcessGroup);
processGroupAction.setTimestamp(new Date());
// determine the running state
if (processGroupDTO.isRunning().booleanValue()) {
processGroupAction.setOperation(Operation.Start);
} else {
processGroupAction.setOperation(Operation.Stop);
}
// add this action
actions.add(processGroupAction);
}
// save actions if necessary
if (!actions.isEmpty()) {
saveActions(actions, logger);
}
}
return updatedProcessGroup;
}
/**
* Audits the removal of a process group via deleteProcessGroup().
*
* @param proceedingJoinPoint
* @param groupId
* @param processGroupDAO
* @throws Throwable
*/
@Around("within(org.apache.nifi.web.dao.ProcessGroupDAO+) && "
+ "execution(void deleteProcessGroup(java.lang.String)) && "
+ "args(groupId)")
public void removeProcessGroupAdvice(ProceedingJoinPoint proceedingJoinPoint, String groupId) throws Throwable {
// get the process group before removing it
ProcessGroupDAO processGroupDAO = getProcessGroupDAO();
ProcessGroup processGroup = processGroupDAO.getProcessGroup(groupId);
// remove the process group
proceedingJoinPoint.proceed();
// if no exceptions were thrown, add removal actions...
// audit the process group removal
final Action action = generateAuditRecord(processGroup, Operation.Remove);
// save the actions
if (action != null) {
saveAction(action, logger);
}
}
/**
* Generates an audit record for the creation of a process group.
*
* @param processGroup
* @return
*/
public Action generateAuditRecord(ProcessGroup processGroup, Operation operation) {
return generateAuditRecord(processGroup, operation, null);
}
/**
* Generates an audit record for the creation of a process group.
*
* @param processGroup
* @return
*/
public Action generateAuditRecord(ProcessGroup processGroup, Operation operation, ActionDetails actionDetails) {
Action action = null;
// get the current user
NiFiUser user = NiFiUserUtils.getNiFiUser();
// ensure the user was found
if (user != null) {
// create the process group action for adding this process group
action = new Action();
action.setUserDn(user.getDn());
action.setUserName(user.getUserName());
action.setOperation(operation);
action.setTimestamp(new Date());
action.setSourceId(processGroup.getIdentifier());
action.setSourceName(processGroup.getName());
action.setSourceType(Component.ProcessGroup);
if (actionDetails != null) {
action.setActionDetails(actionDetails);
}
}
return action;
}
}
| rdblue/incubator-nifi | nar-bundles/framework-bundle/framework/web/nifi-web-api/src/main/java/org/apache/nifi/audit/ProcessGroupAuditor.java | Java | apache-2.0 | 10,704 |
/*
* Copyright 2020 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 by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/speech/v1p1beta1/cloud_speech_adaptation.proto
package com.google.cloud.speech.v1p1beta1;
/**
*
*
* <pre>
* Message returned to the client by the `ListCustomClasses` method.
* </pre>
*
* Protobuf type {@code google.cloud.speech.v1p1beta1.ListCustomClassesResponse}
*/
public final class ListCustomClassesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.speech.v1p1beta1.ListCustomClassesResponse)
ListCustomClassesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListCustomClassesResponse.newBuilder() to construct.
private ListCustomClassesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListCustomClassesResponse() {
customClasses_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListCustomClassesResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ListCustomClassesResponse(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
customClasses_ =
new java.util.ArrayList<com.google.cloud.speech.v1p1beta1.CustomClass>();
mutable_bitField0_ |= 0x00000001;
}
customClasses_.add(
input.readMessage(
com.google.cloud.speech.v1p1beta1.CustomClass.parser(), extensionRegistry));
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
nextPageToken_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
customClasses_ = java.util.Collections.unmodifiableList(customClasses_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto
.internal_static_google_cloud_speech_v1p1beta1_ListCustomClassesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto
.internal_static_google_cloud_speech_v1p1beta1_ListCustomClassesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.class,
com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.Builder.class);
}
public static final int CUSTOM_CLASSES_FIELD_NUMBER = 1;
private java.util.List<com.google.cloud.speech.v1p1beta1.CustomClass> customClasses_;
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.speech.v1p1beta1.CustomClass> getCustomClassesList() {
return customClasses_;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder>
getCustomClassesOrBuilderList() {
return customClasses_;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
@java.lang.Override
public int getCustomClassesCount() {
return customClasses_.size();
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
@java.lang.Override
public com.google.cloud.speech.v1p1beta1.CustomClass getCustomClasses(int index) {
return customClasses_.get(index);
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
@java.lang.Override
public com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder getCustomClassesOrBuilder(
int index) {
return customClasses_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
private volatile java.lang.Object nextPageToken_;
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < customClasses_.size(); i++) {
output.writeMessage(1, customClasses_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < customClasses_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, customClasses_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse)) {
return super.equals(obj);
}
com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse other =
(com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse) obj;
if (!getCustomClassesList().equals(other.getCustomClassesList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getCustomClassesCount() > 0) {
hash = (37 * hash) + CUSTOM_CLASSES_FIELD_NUMBER;
hash = (53 * hash) + getCustomClassesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message returned to the client by the `ListCustomClasses` method.
* </pre>
*
* Protobuf type {@code google.cloud.speech.v1p1beta1.ListCustomClassesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.speech.v1p1beta1.ListCustomClassesResponse)
com.google.cloud.speech.v1p1beta1.ListCustomClassesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto
.internal_static_google_cloud_speech_v1p1beta1_ListCustomClassesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto
.internal_static_google_cloud_speech_v1p1beta1_ListCustomClassesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.class,
com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.Builder.class);
}
// Construct using com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getCustomClassesFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (customClassesBuilder_ == null) {
customClasses_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
customClassesBuilder_.clear();
}
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto
.internal_static_google_cloud_speech_v1p1beta1_ListCustomClassesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse getDefaultInstanceForType() {
return com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse build() {
com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse buildPartial() {
com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse result =
new com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse(this);
int from_bitField0_ = bitField0_;
if (customClassesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
customClasses_ = java.util.Collections.unmodifiableList(customClasses_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.customClasses_ = customClasses_;
} else {
result.customClasses_ = customClassesBuilder_.build();
}
result.nextPageToken_ = nextPageToken_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse) {
return mergeFrom((com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse other) {
if (other == com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.getDefaultInstance())
return this;
if (customClassesBuilder_ == null) {
if (!other.customClasses_.isEmpty()) {
if (customClasses_.isEmpty()) {
customClasses_ = other.customClasses_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureCustomClassesIsMutable();
customClasses_.addAll(other.customClasses_);
}
onChanged();
}
} else {
if (!other.customClasses_.isEmpty()) {
if (customClassesBuilder_.isEmpty()) {
customClassesBuilder_.dispose();
customClassesBuilder_ = null;
customClasses_ = other.customClasses_;
bitField0_ = (bitField0_ & ~0x00000001);
customClassesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getCustomClassesFieldBuilder()
: null;
} else {
customClassesBuilder_.addAllMessages(other.customClasses_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.speech.v1p1beta1.CustomClass> customClasses_ =
java.util.Collections.emptyList();
private void ensureCustomClassesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
customClasses_ =
new java.util.ArrayList<com.google.cloud.speech.v1p1beta1.CustomClass>(customClasses_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.speech.v1p1beta1.CustomClass,
com.google.cloud.speech.v1p1beta1.CustomClass.Builder,
com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder>
customClassesBuilder_;
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public java.util.List<com.google.cloud.speech.v1p1beta1.CustomClass> getCustomClassesList() {
if (customClassesBuilder_ == null) {
return java.util.Collections.unmodifiableList(customClasses_);
} else {
return customClassesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public int getCustomClassesCount() {
if (customClassesBuilder_ == null) {
return customClasses_.size();
} else {
return customClassesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public com.google.cloud.speech.v1p1beta1.CustomClass getCustomClasses(int index) {
if (customClassesBuilder_ == null) {
return customClasses_.get(index);
} else {
return customClassesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public Builder setCustomClasses(
int index, com.google.cloud.speech.v1p1beta1.CustomClass value) {
if (customClassesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomClassesIsMutable();
customClasses_.set(index, value);
onChanged();
} else {
customClassesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public Builder setCustomClasses(
int index, com.google.cloud.speech.v1p1beta1.CustomClass.Builder builderForValue) {
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
customClasses_.set(index, builderForValue.build());
onChanged();
} else {
customClassesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public Builder addCustomClasses(com.google.cloud.speech.v1p1beta1.CustomClass value) {
if (customClassesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomClassesIsMutable();
customClasses_.add(value);
onChanged();
} else {
customClassesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public Builder addCustomClasses(
int index, com.google.cloud.speech.v1p1beta1.CustomClass value) {
if (customClassesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomClassesIsMutable();
customClasses_.add(index, value);
onChanged();
} else {
customClassesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public Builder addCustomClasses(
com.google.cloud.speech.v1p1beta1.CustomClass.Builder builderForValue) {
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
customClasses_.add(builderForValue.build());
onChanged();
} else {
customClassesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public Builder addCustomClasses(
int index, com.google.cloud.speech.v1p1beta1.CustomClass.Builder builderForValue) {
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
customClasses_.add(index, builderForValue.build());
onChanged();
} else {
customClassesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public Builder addAllCustomClasses(
java.lang.Iterable<? extends com.google.cloud.speech.v1p1beta1.CustomClass> values) {
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, customClasses_);
onChanged();
} else {
customClassesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public Builder clearCustomClasses() {
if (customClassesBuilder_ == null) {
customClasses_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
customClassesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public Builder removeCustomClasses(int index) {
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
customClasses_.remove(index);
onChanged();
} else {
customClassesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public com.google.cloud.speech.v1p1beta1.CustomClass.Builder getCustomClassesBuilder(
int index) {
return getCustomClassesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder getCustomClassesOrBuilder(
int index) {
if (customClassesBuilder_ == null) {
return customClasses_.get(index);
} else {
return customClassesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public java.util.List<? extends com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder>
getCustomClassesOrBuilderList() {
if (customClassesBuilder_ != null) {
return customClassesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(customClasses_);
}
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public com.google.cloud.speech.v1p1beta1.CustomClass.Builder addCustomClassesBuilder() {
return getCustomClassesFieldBuilder()
.addBuilder(com.google.cloud.speech.v1p1beta1.CustomClass.getDefaultInstance());
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public com.google.cloud.speech.v1p1beta1.CustomClass.Builder addCustomClassesBuilder(
int index) {
return getCustomClassesFieldBuilder()
.addBuilder(index, com.google.cloud.speech.v1p1beta1.CustomClass.getDefaultInstance());
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code>
*/
public java.util.List<com.google.cloud.speech.v1p1beta1.CustomClass.Builder>
getCustomClassesBuilderList() {
return getCustomClassesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.speech.v1p1beta1.CustomClass,
com.google.cloud.speech.v1p1beta1.CustomClass.Builder,
com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder>
getCustomClassesFieldBuilder() {
if (customClassesBuilder_ == null) {
customClassesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.speech.v1p1beta1.CustomClass,
com.google.cloud.speech.v1p1beta1.CustomClass.Builder,
com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder>(
customClasses_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
customClasses_ = null;
}
return customClassesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.speech.v1p1beta1.ListCustomClassesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.speech.v1p1beta1.ListCustomClassesResponse)
private static final com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse();
}
public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListCustomClassesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListCustomClassesResponse>() {
@java.lang.Override
public ListCustomClassesResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ListCustomClassesResponse(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ListCustomClassesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListCustomClassesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| googleapis/java-speech | proto-google-cloud-speech-v1p1beta1/src/main/java/com/google/cloud/speech/v1p1beta1/ListCustomClassesResponse.java | Java | apache-2.0 | 37,482 |
# Micheevia M.D. Zalessky, 1930 GENUS
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Pteridophyta/Micheevia/README.md | Markdown | apache-2.0 | 193 |
package love.cq.domain;
import java.util.Arrays;
public class Value {
private String keyword;
private String[] paramers = new String[0];
public Value(String keyword, String... paramers) {
this.keyword = keyword;
if (paramers != null) {
this.paramers = paramers;
}
}
public Value(String temp) {
String[] strs = temp.split(TAB);
this.keyword = strs[0];
if (strs.length > 1) {
this.paramers = Arrays.copyOfRange(strs, 1, strs.length);
}
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String[] getParamers() {
return paramers;
}
public void setParamers(String[] paramers) {
this.paramers = paramers;
}
private static final String TAB = "\t";
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(keyword);
for (int i = 0; i < paramers.length; i++) {
sb.append(TAB);
sb.append(paramers[i]);
}
return sb.toString();
}
}
| AllienPhone/elasticsearch-analysis-Ansj | src/love/cq/domain/Value.java | Java | apache-2.0 | 996 |
define(["dojo/_base/declare", "dojo/Deferred", "dojo/promise/all",
"dojo/_base/lang", "dojo/_base/array", "esri/arcgis/utils", "esri/lang",
"esri/tasks/PrintTemplate", "esri/request"
], function(
declare, Deferred, all, lang, array, arcgisUtils, esriLang, PrintTemplate,
esriRequest) {
return declare(null, {
constructor: function(parameters) {
lang.mixin(this.printConfig, parameters);
},
//*********
//Variables
//************
//defaultFormat: "pdf",
printConfig: {
templates: null,
layouts: false,
legendLayers: [],
printi18n: null,
format: "pdf",
printTaskUrl: null,
layoutOptions: {
"titleText": null,
"scalebarUnit": null,
"legendLayers": []
}
},
templates: [],
legendLayers: [],
//optional array of additional search layers to configure from the application config process
createPrintOptions: function() {
var deferred = new Deferred();
all([
this._buildPrintLayouts(), this._createPrintLegend()
]).then(lang.hitch(this, function(results) {
deferred.resolve({
templates: this.templates,
legendLayers: this.legendLayers
});
}));
return deferred.promise;
},
_createPrintLegend: function() {
var deferred = new Deferred();
var layers = arcgisUtils.getLegendLayers(this.printConfig.legendLayers);
this.legendLayers = array.map(layers, function(layer) {
return {
"layerId": layer.layer.id
};
});
deferred.resolve(true);
return deferred.promise;
},
_buildPrintLayouts: function() {
var deferred = new Deferred();
if (this.printConfig.templates) {
this.templates = this.printConfig.templates;
array.forEach(this.templates, lang.hitch(this, function(
template) {
if (template.layout === "MAP_ONLY") {
template.exportOptions = {
width: 670,
height: 500,
dpi: 96
};
}
template.layoutOptions = this.printConfig.layoutOptions;
}));
deferred.resolve(true);
} else if (this.printConfig.layouts) {
esriRequest({
url: this.printConfig.printTaskUrl,
content: {
"f": "json"
},
callbackParamName: "callback"
}).then(lang.hitch(this, function(response) {
var layoutTemplate,
templateNames,
mapOnlyIndex;
layoutTemplate = array.filter(response.parameters,
function(param, idx) {
return param.name === "Layout_Template";
});
if (layoutTemplate.length === 0) {
console.log(
"print service parameters name for templates must be \"Layout_Template\""
);
return;
}
templateNames = layoutTemplate[0].choiceList;
// remove the MAP_ONLY template then add it to the end of the list of templates
mapOnlyIndex = array.indexOf(templateNames,
"MAP_ONLY");
if (mapOnlyIndex > -1) {
var mapOnly = templateNames.splice(mapOnlyIndex,
mapOnlyIndex + 1)[0];
templateNames.push(mapOnly);
}
// create a print template for each choice
this.templates = array.map(templateNames, lang.hitch(
this,
function(name) {
var plate = new PrintTemplate();
plate.layout = plate.label = name;
plate.format = this.printConfig.format;
plate.layoutOptions = this.printConfig.layoutOptions;
return plate;
}));
deferred.resolve(true);
}));
} else {
//var letterAnsiAPlate = new PrintTemplate();
// letterAnsiAPlate.layout = "Letter ANSI A Landscape";
var landscapeFormat = new PrintTemplate();
landscapeFormat.layout = "Letter ANSI A Landscape";
landscapeFormat.layoutOptions = this.printConfig.layoutOptions;
landscapeFormat.format = this.printConfig.format;
landscapeFormat.label = this.printConfig.printi18n.layouts.label1 +
" ( " + this.printConfig.format + " )";
var portraitFormat = new PrintTemplate();
portraitFormat.layout = "Letter ANSI A Portrait";
portraitFormat.layoutOptions = this.printConfig.layoutOptions;
portraitFormat.format = this.printConfig.format;
portraitFormat.label = this.printConfig.printi18n.layouts.label2 +
" ( " + this.printConfig.format + " )";
var landscapeImage = new PrintTemplate();
landscapeImage.layout = "Letter ANSI A Landscape";
landscapeImage.layoutOptions = this.printConfig.layoutOptions;
landscapeImage.format = "png32";
landscapeImage.label = this.printConfig.printi18n.layouts.label3 +
" ( image )";
var portraitImage = new PrintTemplate();
portraitImage.layout = "Letter ANSI A Portrait";
portraitImage.layoutOptions = this.printConfig.layoutOptions;
portraitImage.format = "png32";
portraitImage.label = this.printConfig.printi18n.layouts.label4 +
" ( image )";
this.templates = [landscapeFormat, portraitFormat,
landscapeImage, portraitImage
];
deferred.resolve(true);
}
return deferred.promise;
}
});
});
| Esri/Viewer | js/PrintConfig.js | JavaScript | apache-2.0 | 5,499 |
package org.http4s
package client
import cats.effect._
import fs2.Stream
import scala.concurrent.duration._
class PoolManagerSpec(name: String) extends Http4sSpec {
val _ = name
val key = RequestKey(Uri.Scheme.http, Uri.Authority(host = Uri.IPv4("127.0.0.1")))
val otherKey = RequestKey(Uri.Scheme.http, Uri.Authority(host = Uri.IPv4("localhost")))
class TestConnection extends Connection[IO] {
def isClosed = false
def isRecyclable = true
def requestKey = key
def shutdown() = ()
}
def mkPool(
maxTotal: Int = 1,
maxWaitQueueLimit: Int = 2
) =
ConnectionManager.pool(
builder = _ => IO(new TestConnection()),
maxTotal = maxTotal,
maxWaitQueueLimit = maxWaitQueueLimit,
maxConnectionsPerRequestKey = _ => 5,
responseHeaderTimeout = Duration.Inf,
requestTimeout = Duration.Inf,
executionContext = testExecutionContext
)
"A pool manager" should {
"wait up to maxWaitQueueLimit" in {
(for {
pool <- mkPool(maxTotal = 1, maxWaitQueueLimit = 2)
_ <- pool.borrow(key)
att <- Stream(Stream.eval(pool.borrow(key))).repeat
.take(2)
.covary[IO]
.parJoinUnbounded
.compile
.toList
.attempt
} yield att).unsafeRunTimed(2.seconds) must_== None
}
"throw at maxWaitQueueLimit" in {
(for {
pool <- mkPool(maxTotal = 1, maxWaitQueueLimit = 2)
_ <- pool.borrow(key)
att <- Stream(Stream.eval(pool.borrow(key))).repeat
.take(3)
.covary[IO]
.parJoinUnbounded
.compile
.toList
.attempt
} yield att).unsafeRunTimed(2.seconds) must_== Some(Left(WaitQueueFullFailure()))
}
"wake up a waiting connection on release" in {
(for {
pool <- mkPool(maxTotal = 1, maxWaitQueueLimit = 1)
conn <- pool.borrow(key)
fiber <- pool.borrow(key).start // Should be one waiting
_ <- pool.release(conn.connection)
_ <- fiber.join
} yield ()).unsafeRunTimed(2.seconds) must_== Some(())
}
"wake up a waiting connection on invalidate" in {
(for {
pool <- mkPool(maxTotal = 1, maxWaitQueueLimit = 1)
conn <- pool.borrow(key)
fiber <- pool.borrow(key).start // Should be one waiting
_ <- pool.invalidate(conn.connection)
_ <- fiber.join
} yield ()).unsafeRunTimed(2.seconds) must_== Some(())
}
"close an idle connection when at max total connections" in {
(for {
pool <- mkPool(maxTotal = 1, maxWaitQueueLimit = 1)
conn <- pool.borrow(key)
_ <- pool.release(conn.connection)
fiber <- pool.borrow(otherKey).start
_ <- fiber.join
} yield ()).unsafeRunTimed(2.seconds) must_== Some(())
}
"wake up a waiting connection for a different request key on release" in {
(for {
pool <- mkPool(maxTotal = 1, maxWaitQueueLimit = 1)
conn <- pool.borrow(key)
fiber <- pool.borrow(otherKey).start
_ <- pool.release(conn.connection)
_ <- fiber.join
} yield ()).unsafeRunTimed(2.seconds) must_== Some(())
}
}
"A WaitQueueFullFailure" should {
"render message properly" in {
(new WaitQueueFullFailure).toString() must contain("Wait queue is full")
}
}
}
| aeons/http4s | client/src/test/scala/org/http4s/client/PoolManagerSpec.scala | Scala | apache-2.0 | 3,361 |
#ifndef DEF_GLUT_MGT
#define DEF_GLUT_MGT
#include <iostream>
#include <GL/gl.h>
#include <GL/glut.h>
#include <boost/thread/thread.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#define KEY_ESCAPE 27
#define CHKERR if (glGetError() != GL_NO_ERROR) printf("** I screwed up something\n");
typedef struct {
int width;
int height;
std::string title;
float view_angle;
float z_near;
float z_far;
} glutWindow;
typedef struct {
float eye_x;
float eye_y;
float eye_z;
float observed_x;
float observed_y;
float observed_z;
float sky_x;
float sky_y;
float sky_z;
} glutGlass;
typedef struct {
float x;
float y;
float z;
float r;
float g;
float b;
} point3D;
/**
*
*/
class GlutManager
{
public:
GlutManager();
~GlutManager();
static void keyboardHandler(unsigned char key, int x, int y);
static void mouseHandler(int button, int state, int x, int y);
static void pMouseMotionHandler(int x, int y);
static void idle(void);
static void reshape(int x, int y);
static void display(void);
void initialize();
void mainLoop(int argc, char** argv);
protected:
static int windowId;
int pressed;
glutWindow win;
glutGlass glass;
};
#endif
| hackliff/domobot | client/glClient/GlutManager.h | C | apache-2.0 | 1,301 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.anim;
import java.awt.geom.AffineTransform;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.ugraphic.MinMax;
public class AffineTransformation {
static private final Pattern rotate = Pattern.compile("rotate\\s+(-?\\d+\\.?\\d*)");
static private final Pattern shear = Pattern.compile("shear\\s+(-?\\d+\\.?\\d*)\\s+(-?\\d+\\.?\\d*)");
static private final Pattern translate = Pattern.compile("translate\\s+(-?\\d+\\.?\\d*)\\s+(-?\\d+\\.?\\d*)");
static private final Pattern scale = Pattern.compile("scale\\s+(-?\\d+\\.?\\d*)\\s+(-?\\d+\\.?\\d*)");
static private final Pattern color = Pattern.compile("color\\s+.*");
private final AffineTransform affineTransform;
private Dimension2D dimension;
private AffineTransformation(AffineTransform affineTransform) {
this.affineTransform = Objects.requireNonNull(affineTransform);
}
private AffineTransformation compose(AffineTransformation other) {
final AffineTransform tmp = new AffineTransform(this.affineTransform);
tmp.concatenate(other.affineTransform);
return new AffineTransformation(tmp);
}
public static AffineTransformation from(AffineTransform affineTransform) {
return new AffineTransformation(affineTransform);
}
static AffineTransformation create(String value) {
final StringTokenizer st = new StringTokenizer(value, "|");
AffineTransformation result = null;
while (st.hasMoreTokens()) {
final String s = st.nextToken();
final AffineTransformation tmp = createSimple(s);
if (tmp != null) {
if (result == null) {
result = tmp;
} else {
result = result.compose(tmp);
}
}
}
return result;
}
private static AffineTransformation createSimple(String value) {
Matcher m = rotate.matcher(StringUtils.trin(value));
if (m.find()) {
final double angle = Double.parseDouble(m.group(1));
return new AffineTransformation(AffineTransform.getRotateInstance(angle * Math.PI / 180.0));
}
m = shear.matcher(value);
if (m.find()) {
final double shx = Double.parseDouble(m.group(1));
final double shy = Double.parseDouble(m.group(2));
return new AffineTransformation(AffineTransform.getShearInstance(shx, shy));
}
m = translate.matcher(value);
if (m.find()) {
final double tx = Double.parseDouble(m.group(1));
final double ty = Double.parseDouble(m.group(2));
return new AffineTransformation(AffineTransform.getTranslateInstance(tx, ty));
}
m = scale.matcher(value);
if (m.find()) {
final double scalex = Double.parseDouble(m.group(1));
final double scaley = Double.parseDouble(m.group(2));
return new AffineTransformation(AffineTransform.getScaleInstance(scalex, scaley));
}
m = color.matcher(value);
if (m.find()) {
return new AffineTransformation(new AffineTransform());
}
return null;
}
public final AffineTransform getAffineTransform() {
return getAffineTransform(dimension);
}
private AffineTransform getAffineTransform(Dimension2D dimension) {
if (dimension == null) {
throw new IllegalStateException();
}
final AffineTransform at = AffineTransform.getTranslateInstance(dimension.getWidth() / 2,
dimension.getHeight() / 2);
at.concatenate(affineTransform);
at.translate(-dimension.getWidth() / 2, -dimension.getHeight() / 2);
return at;
}
public void setDimension(Dimension2D dim) {
this.dimension = dim;
}
public MinMax getMinMax(Dimension2D rect) {
MinMax result = MinMax.getEmpty(false);
final AffineTransform tmp = getAffineTransform(rect);
result = result.addPoint(tmp.transform(new Point2D.Double(0, 0), null));
result = result.addPoint(tmp.transform(new Point2D.Double(0, rect.getHeight()), null));
result = result.addPoint(tmp.transform(new Point2D.Double(rect.getWidth(), 0), null));
result = result.addPoint(tmp.transform(new Point2D.Double(rect.getWidth(), rect.getHeight()), null));
return result;
}
}
| talsma-ict/umldoclet | src/plantuml-asl/src/net/sourceforge/plantuml/anim/AffineTransformation.java | Java | apache-2.0 | 5,198 |
<!DOCTYPE html>
<html>
<head>
<script src="http://requirejs.org/docs/release/2.1.11/minified/require.js"></script>
<script>
var token = "020d9948-8cf8-4c46-91bd-72bb11b92549";
var db = require('orchestrate')(token);
db.get('cfg_hives', '*')
.then(function (res) {
console.log(res.body); // prints response body
console.log(res.body.name); // prints 'Bruce Wayne'
})
.fail(function (err) {
console.log(err); // prints error
});
</script>
</head>
<body>
dfdadef
</body>
</html> | Glasgow2015/team-1 | getData.php | PHP | apache-2.0 | 484 |
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package spec4j.asm.tree.analysis;
import java.util.ArrayList;
import java.util.List;
import spec4j.asm.Opcodes;
import spec4j.asm.Type;
import spec4j.asm.tree.AbstractInsnNode;
import spec4j.asm.tree.IincInsnNode;
import spec4j.asm.tree.InvokeDynamicInsnNode;
import spec4j.asm.tree.MethodInsnNode;
import spec4j.asm.tree.MultiANewArrayInsnNode;
import spec4j.asm.tree.VarInsnNode;
/**
* A symbolic execution stack frame. A stack frame contains a set of local
* variable slots, and an operand stack. Warning: long and double values are
* represented by <i>two</i> slots in local variables, and by <i>one</i> slot in
* the operand stack.
*
* @param <V>
* type of the Value used for the analysis.
*
* @author Eric Bruneton
*/
public class Frame<V extends Value> {
/**
* The expected return type of the analyzed method, or <tt>null</tt> if the
* method returns void.
*/
private V returnValue;
/**
* The local variables and operand stack of this frame.
*/
private V[] values;
/**
* The number of local variables of this frame.
*/
private int locals;
/**
* The number of elements in the operand stack.
*/
private int top;
/**
* Constructs a new frame with the given size.
*
* @param nLocals
* the maximum number of local variables of the frame.
* @param nStack
* the maximum stack size of the frame.
*/
@SuppressWarnings("unchecked")
public Frame(final int nLocals, final int nStack) {
this.values = (V[]) new Value[nLocals + nStack];
this.locals = nLocals;
}
/**
* Constructs a new frame that is identical to the given frame.
*
* @param src
* a frame.
*/
public Frame(final Frame<? extends V> src) {
this(src.locals, src.values.length - src.locals);
init(src);
}
/**
* Copies the state of the given frame into this frame.
*
* @param src
* a frame.
* @return this frame.
*/
public Frame<V> init(final Frame<? extends V> src) {
returnValue = src.returnValue;
System.arraycopy(src.values, 0, values, 0, values.length);
top = src.top;
return this;
}
/**
* Sets the expected return type of the analyzed method.
*
* @param v
* the expected return type of the analyzed method, or
* <tt>null</tt> if the method returns void.
*/
public void setReturn(final V v) {
returnValue = v;
}
/**
* Returns the maximum number of local variables of this frame.
*
* @return the maximum number of local variables of this frame.
*/
public int getLocals() {
return locals;
}
/**
* Returns the maximum stack size of this frame.
*
* @return the maximum stack size of this frame.
*/
public int getMaxStackSize() {
return values.length - locals;
}
/**
* Returns the value of the given local variable.
*
* @param i
* a local variable index.
* @return the value of the given local variable.
* @throws IndexOutOfBoundsException
* if the variable does not exist.
*/
public V getLocal(final int i) throws IndexOutOfBoundsException {
if (i >= locals) {
throw new IndexOutOfBoundsException(
"Trying to access an inexistant local variable");
}
return values[i];
}
/**
* Sets the value of the given local variable.
*
* @param i
* a local variable index.
* @param value
* the new value of this local variable.
* @throws IndexOutOfBoundsException
* if the variable does not exist.
*/
public void setLocal(final int i, final V value)
throws IndexOutOfBoundsException {
if (i >= locals) {
throw new IndexOutOfBoundsException(
"Trying to access an inexistant local variable " + i);
}
values[i] = value;
}
/**
* Returns the number of values in the operand stack of this frame. Long and
* double values are treated as single values.
*
* @return the number of values in the operand stack of this frame.
*/
public int getStackSize() {
return top;
}
/**
* Returns the value of the given operand stack slot.
*
* @param i
* the index of an operand stack slot.
* @return the value of the given operand stack slot.
* @throws IndexOutOfBoundsException
* if the operand stack slot does not exist.
*/
public V getStack(final int i) throws IndexOutOfBoundsException {
return values[i + locals];
}
/**
* Clears the operand stack of this frame.
*/
public void clearStack() {
top = 0;
}
/**
* Pops a value from the operand stack of this frame.
*
* @return the value that has been popped from the stack.
* @throws IndexOutOfBoundsException
* if the operand stack is empty.
*/
public V pop() throws IndexOutOfBoundsException {
if (top == 0) {
throw new IndexOutOfBoundsException(
"Cannot pop operand off an empty stack.");
}
return values[--top + locals];
}
/**
* Pushes a value into the operand stack of this frame.
*
* @param value
* the value that must be pushed into the stack.
* @throws IndexOutOfBoundsException
* if the operand stack is full.
*/
public void push(final V value) throws IndexOutOfBoundsException {
if (top + locals >= values.length) {
throw new IndexOutOfBoundsException(
"Insufficient maximum stack size.");
}
values[top++ + locals] = value;
}
public void execute(final AbstractInsnNode insn,
final Interpreter<V> interpreter) throws AnalyzerException {
V value1, value2, value3, value4;
List<V> values;
int var;
switch (insn.getOpcode()) {
case Opcodes.NOP:
break;
case Opcodes.ACONST_NULL:
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
case Opcodes.LCONST_0:
case Opcodes.LCONST_1:
case Opcodes.FCONST_0:
case Opcodes.FCONST_1:
case Opcodes.FCONST_2:
case Opcodes.DCONST_0:
case Opcodes.DCONST_1:
case Opcodes.BIPUSH:
case Opcodes.SIPUSH:
case Opcodes.LDC:
push(interpreter.newOperation(insn));
break;
case Opcodes.ILOAD:
case Opcodes.LLOAD:
case Opcodes.FLOAD:
case Opcodes.DLOAD:
case Opcodes.ALOAD:
push(interpreter.copyOperation(insn,
getLocal(((VarInsnNode) insn).var)));
break;
case Opcodes.IALOAD:
case Opcodes.LALOAD:
case Opcodes.FALOAD:
case Opcodes.DALOAD:
case Opcodes.AALOAD:
case Opcodes.BALOAD:
case Opcodes.CALOAD:
case Opcodes.SALOAD:
value2 = pop();
value1 = pop();
push(interpreter.binaryOperation(insn, value1, value2));
break;
case Opcodes.ISTORE:
case Opcodes.LSTORE:
case Opcodes.FSTORE:
case Opcodes.DSTORE:
case Opcodes.ASTORE:
value1 = interpreter.copyOperation(insn, pop());
var = ((VarInsnNode) insn).var;
setLocal(var, value1);
if (value1.getSize() == 2) {
setLocal(var + 1, interpreter.newValue(null));
}
if (var > 0) {
Value local = getLocal(var - 1);
if (local != null && local.getSize() == 2) {
setLocal(var - 1, interpreter.newValue(null));
}
}
break;
case Opcodes.IASTORE:
case Opcodes.LASTORE:
case Opcodes.FASTORE:
case Opcodes.DASTORE:
case Opcodes.AASTORE:
case Opcodes.BASTORE:
case Opcodes.CASTORE:
case Opcodes.SASTORE:
value3 = pop();
value2 = pop();
value1 = pop();
interpreter.ternaryOperation(insn, value1, value2, value3);
break;
case Opcodes.POP:
if (pop().getSize() == 2) {
throw new AnalyzerException(insn, "Illegal use of POP");
}
break;
case Opcodes.POP2:
if (pop().getSize() == 1) {
if (pop().getSize() != 1) {
throw new AnalyzerException(insn, "Illegal use of POP2");
}
}
break;
case Opcodes.DUP:
value1 = pop();
if (value1.getSize() != 1) {
throw new AnalyzerException(insn, "Illegal use of DUP");
}
push(value1);
push(interpreter.copyOperation(insn, value1));
break;
case Opcodes.DUP_X1:
value1 = pop();
value2 = pop();
if (value1.getSize() != 1 || value2.getSize() != 1) {
throw new AnalyzerException(insn, "Illegal use of DUP_X1");
}
push(interpreter.copyOperation(insn, value1));
push(value2);
push(value1);
break;
case Opcodes.DUP_X2:
value1 = pop();
if (value1.getSize() == 1) {
value2 = pop();
if (value2.getSize() == 1) {
value3 = pop();
if (value3.getSize() == 1) {
push(interpreter.copyOperation(insn, value1));
push(value3);
push(value2);
push(value1);
break;
}
} else {
push(interpreter.copyOperation(insn, value1));
push(value2);
push(value1);
break;
}
}
throw new AnalyzerException(insn, "Illegal use of DUP_X2");
case Opcodes.DUP2:
value1 = pop();
if (value1.getSize() == 1) {
value2 = pop();
if (value2.getSize() == 1) {
push(value2);
push(value1);
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
}
} else {
push(value1);
push(interpreter.copyOperation(insn, value1));
break;
}
throw new AnalyzerException(insn, "Illegal use of DUP2");
case Opcodes.DUP2_X1:
value1 = pop();
if (value1.getSize() == 1) {
value2 = pop();
if (value2.getSize() == 1) {
value3 = pop();
if (value3.getSize() == 1) {
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
push(value3);
push(value2);
push(value1);
break;
}
}
} else {
value2 = pop();
if (value2.getSize() == 1) {
push(interpreter.copyOperation(insn, value1));
push(value2);
push(value1);
break;
}
}
throw new AnalyzerException(insn, "Illegal use of DUP2_X1");
case Opcodes.DUP2_X2:
value1 = pop();
if (value1.getSize() == 1) {
value2 = pop();
if (value2.getSize() == 1) {
value3 = pop();
if (value3.getSize() == 1) {
value4 = pop();
if (value4.getSize() == 1) {
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
push(value4);
push(value3);
push(value2);
push(value1);
break;
}
} else {
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
push(value3);
push(value2);
push(value1);
break;
}
}
} else {
value2 = pop();
if (value2.getSize() == 1) {
value3 = pop();
if (value3.getSize() == 1) {
push(interpreter.copyOperation(insn, value1));
push(value3);
push(value2);
push(value1);
break;
}
} else {
push(interpreter.copyOperation(insn, value1));
push(value2);
push(value1);
break;
}
}
throw new AnalyzerException(insn, "Illegal use of DUP2_X2");
case Opcodes.SWAP:
value2 = pop();
value1 = pop();
if (value1.getSize() != 1 || value2.getSize() != 1) {
throw new AnalyzerException(insn, "Illegal use of SWAP");
}
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
case Opcodes.IADD:
case Opcodes.LADD:
case Opcodes.FADD:
case Opcodes.DADD:
case Opcodes.ISUB:
case Opcodes.LSUB:
case Opcodes.FSUB:
case Opcodes.DSUB:
case Opcodes.IMUL:
case Opcodes.LMUL:
case Opcodes.FMUL:
case Opcodes.DMUL:
case Opcodes.IDIV:
case Opcodes.LDIV:
case Opcodes.FDIV:
case Opcodes.DDIV:
case Opcodes.IREM:
case Opcodes.LREM:
case Opcodes.FREM:
case Opcodes.DREM:
value2 = pop();
value1 = pop();
push(interpreter.binaryOperation(insn, value1, value2));
break;
case Opcodes.INEG:
case Opcodes.LNEG:
case Opcodes.FNEG:
case Opcodes.DNEG:
push(interpreter.unaryOperation(insn, pop()));
break;
case Opcodes.ISHL:
case Opcodes.LSHL:
case Opcodes.ISHR:
case Opcodes.LSHR:
case Opcodes.IUSHR:
case Opcodes.LUSHR:
case Opcodes.IAND:
case Opcodes.LAND:
case Opcodes.IOR:
case Opcodes.LOR:
case Opcodes.IXOR:
case Opcodes.LXOR:
value2 = pop();
value1 = pop();
push(interpreter.binaryOperation(insn, value1, value2));
break;
case Opcodes.IINC:
var = ((IincInsnNode) insn).var;
setLocal(var, interpreter.unaryOperation(insn, getLocal(var)));
break;
case Opcodes.I2L:
case Opcodes.I2F:
case Opcodes.I2D:
case Opcodes.L2I:
case Opcodes.L2F:
case Opcodes.L2D:
case Opcodes.F2I:
case Opcodes.F2L:
case Opcodes.F2D:
case Opcodes.D2I:
case Opcodes.D2L:
case Opcodes.D2F:
case Opcodes.I2B:
case Opcodes.I2C:
case Opcodes.I2S:
push(interpreter.unaryOperation(insn, pop()));
break;
case Opcodes.LCMP:
case Opcodes.FCMPL:
case Opcodes.FCMPG:
case Opcodes.DCMPL:
case Opcodes.DCMPG:
value2 = pop();
value1 = pop();
push(interpreter.binaryOperation(insn, value1, value2));
break;
case Opcodes.IFEQ:
case Opcodes.IFNE:
case Opcodes.IFLT:
case Opcodes.IFGE:
case Opcodes.IFGT:
case Opcodes.IFLE:
interpreter.unaryOperation(insn, pop());
break;
case Opcodes.IF_ICMPEQ:
case Opcodes.IF_ICMPNE:
case Opcodes.IF_ICMPLT:
case Opcodes.IF_ICMPGE:
case Opcodes.IF_ICMPGT:
case Opcodes.IF_ICMPLE:
case Opcodes.IF_ACMPEQ:
case Opcodes.IF_ACMPNE:
value2 = pop();
value1 = pop();
interpreter.binaryOperation(insn, value1, value2);
break;
case Opcodes.GOTO:
break;
case Opcodes.JSR:
push(interpreter.newOperation(insn));
break;
case Opcodes.RET:
break;
case Opcodes.TABLESWITCH:
case Opcodes.LOOKUPSWITCH:
interpreter.unaryOperation(insn, pop());
break;
case Opcodes.IRETURN:
case Opcodes.LRETURN:
case Opcodes.FRETURN:
case Opcodes.DRETURN:
case Opcodes.ARETURN:
value1 = pop();
interpreter.unaryOperation(insn, value1);
interpreter.returnOperation(insn, value1, returnValue);
break;
case Opcodes.RETURN:
if (returnValue != null) {
throw new AnalyzerException(insn, "Incompatible return type");
}
break;
case Opcodes.GETSTATIC:
push(interpreter.newOperation(insn));
break;
case Opcodes.PUTSTATIC:
interpreter.unaryOperation(insn, pop());
break;
case Opcodes.GETFIELD:
push(interpreter.unaryOperation(insn, pop()));
break;
case Opcodes.PUTFIELD:
value2 = pop();
value1 = pop();
interpreter.binaryOperation(insn, value1, value2);
break;
case Opcodes.INVOKEVIRTUAL:
case Opcodes.INVOKESPECIAL:
case Opcodes.INVOKESTATIC:
case Opcodes.INVOKEINTERFACE: {
values = new ArrayList<V>();
String desc = ((MethodInsnNode) insn).desc;
for (int i = Type.getArgumentTypes(desc).length; i > 0; --i) {
values.add(0, pop());
}
if (insn.getOpcode() != Opcodes.INVOKESTATIC) {
values.add(0, pop());
}
if (Type.getReturnType(desc) == Type.VOID_TYPE) {
interpreter.naryOperation(insn, values);
} else {
push(interpreter.naryOperation(insn, values));
}
break;
}
case Opcodes.INVOKEDYNAMIC: {
values = new ArrayList<V>();
String desc = ((InvokeDynamicInsnNode) insn).desc;
for (int i = Type.getArgumentTypes(desc).length; i > 0; --i) {
values.add(0, pop());
}
if (Type.getReturnType(desc) == Type.VOID_TYPE) {
interpreter.naryOperation(insn, values);
} else {
push(interpreter.naryOperation(insn, values));
}
break;
}
case Opcodes.NEW:
push(interpreter.newOperation(insn));
break;
case Opcodes.NEWARRAY:
case Opcodes.ANEWARRAY:
case Opcodes.ARRAYLENGTH:
push(interpreter.unaryOperation(insn, pop()));
break;
case Opcodes.ATHROW:
interpreter.unaryOperation(insn, pop());
break;
case Opcodes.CHECKCAST:
case Opcodes.INSTANCEOF:
push(interpreter.unaryOperation(insn, pop()));
break;
case Opcodes.MONITORENTER:
case Opcodes.MONITOREXIT:
interpreter.unaryOperation(insn, pop());
break;
case Opcodes.MULTIANEWARRAY:
values = new ArrayList<V>();
for (int i = ((MultiANewArrayInsnNode) insn).dims; i > 0; --i) {
values.add(0, pop());
}
push(interpreter.naryOperation(insn, values));
break;
case Opcodes.IFNULL:
case Opcodes.IFNONNULL:
interpreter.unaryOperation(insn, pop());
break;
default:
throw new RuntimeException("Illegal opcode " + insn.getOpcode());
}
}
/**
* Merges this frame with the given frame.
*
* @param frame
* a frame.
* @param interpreter
* the interpreter used to merge values.
* @return <tt>true</tt> if this frame has been changed as a result of the
* merge operation, or <tt>false</tt> otherwise.
* @throws AnalyzerException
* if the frames have incompatible sizes.
*/
public boolean merge(final Frame<? extends V> frame,
final Interpreter<V> interpreter) throws AnalyzerException {
if (top != frame.top) {
throw new AnalyzerException(null, "Incompatible stack heights");
}
boolean changes = false;
for (int i = 0; i < locals + top; ++i) {
V v = interpreter.merge(values[i], frame.values[i]);
if (!v.equals(values[i])) {
values[i] = v;
changes = true;
}
}
return changes;
}
/**
* Merges this frame with the given frame (case of a RET instruction).
*
* @param frame
* a frame
* @param access
* the local variables that have been accessed by the subroutine
* to which the RET instruction corresponds.
* @return <tt>true</tt> if this frame has been changed as a result of the
* merge operation, or <tt>false</tt> otherwise.
*/
public boolean merge(final Frame<? extends V> frame, final boolean[] access) {
boolean changes = false;
for (int i = 0; i < locals; ++i) {
if (!access[i] && !values[i].equals(frame.values[i])) {
values[i] = frame.values[i];
changes = true;
}
}
return changes;
}
/**
* Returns a string representation of this frame.
*
* @return a string representation of this frame.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < getLocals(); ++i) {
sb.append(getLocal(i));
}
sb.append(' ');
for (int i = 0; i < getStackSize(); ++i) {
sb.append(getStack(i).toString());
}
return sb.toString();
}
}
| ikisis/spec4j | spec4j-agent/src/main/java/spec4j/asm/tree/analysis/Frame.java | Java | apache-2.0 | 24,831 |
"""
@author: ArcGIS for Intelligence
@contact: defensesolutions@esri.com
@company: Esri
@version: 1.0
@description: Used to stage the apps for Movement Analysis
@requirements: Python 2.7.x, ArcGIS 10.3.1
@copyright: Esri, 2015
"""
import arcresthelper
from arcresthelper import portalautomation
log_file='./logs/DamageAssessment.log'
configFiles= ['./configs/StageApp.json']
globalLoginInfo = './configs/GlobalLoginInfo.json'
dateTimeFormat = '%Y-%m-%d %H:%M'
pa = portalautomation.portalautomation(globalLoginInfo)
pa.setLog(log_file=log_file)
pa.publishfromconfig(configFiles=configFiles,
combinedApp=None,
dateTimeFormat=dateTimeFormat)
del pa | conklinbd/MovementAnalysis | TemplateInstall/PortalDeploy/StageApp.py | Python | apache-2.0 | 726 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vogar;
import java.io.File;
import java.io.FileFilter;
/**
* Selects files to be kept from a test run.
*/
public final class RetrievedFilesFilter implements FileFilter {
private final boolean profile;
private final File profileFile;
public RetrievedFilesFilter(boolean profile, File profileFile) {
this.profile = profile;
this.profileFile = profileFile;
}
@Override public boolean accept(File file) {
if (file.getName().equals("prefs.xml")) {
return false;
}
if (file.getName().endsWith(".xml")
|| file.getName().equals("caliper-results")
|| file.getName().endsWith(".json")
|| (profile && file.getName().equals(profileFile.getName()))) {
return true;
}
return false;
}
}
| dryganets/vogar | src/vogar/RetrievedFilesFilter.java | Java | apache-2.0 | 1,459 |
/*
* 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.
*/
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/ec2/EC2Request.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/NewDhcpConfiguration.h>
#include <utility>
namespace Aws
{
namespace EC2
{
namespace Model
{
/**
* <p>Contains the parameters for CreateDhcpOptions.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateDhcpOptionsRequest">AWS
* API Reference</a></p>
*/
class AWS_EC2_API CreateDhcpOptionsRequest : public EC2Request
{
public:
CreateDhcpOptionsRequest();
Aws::String SerializePayload() const override;
protected:
void DumpBodyToUrl(Aws::Http::URI& uri ) const override;
public:
/**
* <p>A DHCP configuration option.</p>
*/
inline const Aws::Vector<NewDhcpConfiguration>& GetDhcpConfigurations() const{ return m_dhcpConfigurations; }
/**
* <p>A DHCP configuration option.</p>
*/
inline void SetDhcpConfigurations(const Aws::Vector<NewDhcpConfiguration>& value) { m_dhcpConfigurationsHasBeenSet = true; m_dhcpConfigurations = value; }
/**
* <p>A DHCP configuration option.</p>
*/
inline void SetDhcpConfigurations(Aws::Vector<NewDhcpConfiguration>&& value) { m_dhcpConfigurationsHasBeenSet = true; m_dhcpConfigurations = std::move(value); }
/**
* <p>A DHCP configuration option.</p>
*/
inline CreateDhcpOptionsRequest& WithDhcpConfigurations(const Aws::Vector<NewDhcpConfiguration>& value) { SetDhcpConfigurations(value); return *this;}
/**
* <p>A DHCP configuration option.</p>
*/
inline CreateDhcpOptionsRequest& WithDhcpConfigurations(Aws::Vector<NewDhcpConfiguration>&& value) { SetDhcpConfigurations(std::move(value)); return *this;}
/**
* <p>A DHCP configuration option.</p>
*/
inline CreateDhcpOptionsRequest& AddDhcpConfigurations(const NewDhcpConfiguration& value) { m_dhcpConfigurationsHasBeenSet = true; m_dhcpConfigurations.push_back(value); return *this; }
/**
* <p>A DHCP configuration option.</p>
*/
inline CreateDhcpOptionsRequest& AddDhcpConfigurations(NewDhcpConfiguration&& value) { m_dhcpConfigurationsHasBeenSet = true; m_dhcpConfigurations.push_back(std::move(value)); return *this; }
/**
* <p>Checks whether you have the required permissions for the action, without
* actually making the request, and provides an error response. If you have the
* required permissions, the error response is <code>DryRunOperation</code>.
* Otherwise, it is <code>UnauthorizedOperation</code>.</p>
*/
inline bool GetDryRun() const{ return m_dryRun; }
/**
* <p>Checks whether you have the required permissions for the action, without
* actually making the request, and provides an error response. If you have the
* required permissions, the error response is <code>DryRunOperation</code>.
* Otherwise, it is <code>UnauthorizedOperation</code>.</p>
*/
inline void SetDryRun(bool value) { m_dryRunHasBeenSet = true; m_dryRun = value; }
/**
* <p>Checks whether you have the required permissions for the action, without
* actually making the request, and provides an error response. If you have the
* required permissions, the error response is <code>DryRunOperation</code>.
* Otherwise, it is <code>UnauthorizedOperation</code>.</p>
*/
inline CreateDhcpOptionsRequest& WithDryRun(bool value) { SetDryRun(value); return *this;}
private:
Aws::Vector<NewDhcpConfiguration> m_dhcpConfigurations;
bool m_dhcpConfigurationsHasBeenSet;
bool m_dryRun;
bool m_dryRunHasBeenSet;
};
} // namespace Model
} // namespace EC2
} // namespace Aws
| svagionitis/aws-sdk-cpp | aws-cpp-sdk-ec2/include/aws/ec2/model/CreateDhcpOptionsRequest.h | C | apache-2.0 | 4,297 |
/*******************************************************************************
* Copyright (c) 2006-2010 eBay 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
*******************************************************************************/
package org.ebayopensource.turmeric.monitoring.client.model;
import java.util.HashMap;
import java.util.Map;
/**
* The Class SelectionContext.
*/
public class SelectionContext {
/** The selected objects. */
Map<ObjectType, String> selectedObjects = new HashMap<ObjectType, String>();
/**
* From history token.
*
* @param token the token
* @return the selection context
*/
public static SelectionContext fromHistoryToken (HistoryToken token) {
SelectionContext ctx = new SelectionContext();
String tmp = HistoryToken.getValue(token, HistoryToken.SELECTED_SERVICE_TOKEN);
if (tmp != null)
ctx.select(ObjectType.ServiceName, tmp);
tmp = HistoryToken.getValue(token, HistoryToken.SELECTED_OPERATION_TOKEN);
if (tmp != null)
ctx.select(ObjectType.OperationName, tmp);
tmp = HistoryToken.getValue(token, HistoryToken.SELECTED_CONSUMER_TOKEN);
if (tmp != null)
ctx.select(ObjectType.ConsumerName, tmp);
tmp = HistoryToken.getValue(token, HistoryToken.SELECTED_ERROR_NAME_TOKEN);
if (tmp != null)
ctx.select(ObjectType.ErrorName, tmp);
tmp = HistoryToken.getValue(token, HistoryToken.SELECTED_ERROR_ID_TOKEN);
if (tmp != null)
ctx.select(ObjectType.ErrorId, tmp);
return ctx;
}
/**
* Select all.
*
* @param sc the sc
*/
public void selectAll (SelectionContext sc) {
if (sc == null)
return;
for (Map.Entry<ObjectType, String> entry:sc.getSelections().entrySet()) {
select(entry.getKey(), entry.getValue());
}
}
/**
* Equals.
*
* @param sc the sc
* @return true, if successful
*/
public boolean equals (SelectionContext sc) {
if (sc.getSelections().equals(selectedObjects))
return true;
return false;
}
/**
* Select.
*
* @param t the t
* @param name the name
*/
public void select(ObjectType t, String name) {
selectedObjects.put(t, name);
}
/**
* Unselect.
*
* @param t the t
*/
public void unselect(ObjectType t) {
selectedObjects.remove(t);
}
/**
* Gets the selection.
*
* @param t the t
* @return the selection
*/
public String getSelection(ObjectType t) {
return selectedObjects.get(t);
}
/**
* Checks if is selected.
*
* @param t the t
* @return true, if is selected
*/
public boolean isSelected(ObjectType t) {
return (selectedObjects.get(t)!=null);
}
/**
* Gets the selections.
*
* @return the selections
*/
public Map<ObjectType,String> getSelections () {
return new HashMap<ObjectType,String>(selectedObjects);
}
/**
* To history token.
*
* @param presenterId the presenter id
* @param values the values
* @return the history token
*/
public HistoryToken toHistoryToken (String presenterId, Map<String,String> values) {
HistoryToken token = HistoryToken.newHistoryToken(presenterId, values);
appendSelections(token);
return token;
}
/**
* Append to history token.
*
* @param token the token
* @return the history token
*/
public HistoryToken appendToHistoryToken (HistoryToken token) {
if (token == null)
return token;
appendSelections(token);
return token;
}
/**
* To string.
*
* @return the string
* @see java.lang.Object#toString()
*/
public String toString () {
StringBuffer strbuff = new StringBuffer();
for (Map.Entry<ObjectType,String> entry:selectedObjects.entrySet()) {
strbuff.append(" "+entry.getKey().toString()+"="+entry.getValue()+" ");
}
return strbuff.toString();
}
/**
* Append selections.
*
* @param token the token
*/
protected void appendSelections (HistoryToken token) {
for (ObjectType t:selectedObjects.keySet()) {
switch (t) {
case ServiceName: {
if (selectedObjects.get(t) != null)
token.addValue(HistoryToken.SELECTED_SERVICE_TOKEN, selectedObjects.get(t));
break;
}
case OperationName: {
if (selectedObjects.get(t) != null)
token.addValue(HistoryToken.SELECTED_OPERATION_TOKEN, selectedObjects.get(t));
break;
}
case ConsumerName: {
if (selectedObjects.get(t) != null)
token.addValue(HistoryToken.SELECTED_CONSUMER_TOKEN, selectedObjects.get(t));
break;
}
case ErrorName: {
if (selectedObjects.get(t) != null)
token.addValue(HistoryToken.SELECTED_ERROR_NAME_TOKEN, selectedObjects.get(t));
break;
}
case ErrorId: {
if (selectedObjects.get(t) != null)
token.addValue(HistoryToken.SELECTED_ERROR_ID_TOKEN, selectedObjects.get(t));
break;
}
}
}
}
}
| ebayopensource/turmeric-monitoring | mgmt-console/src/main/java/org/ebayopensource/turmeric/monitoring/client/model/SelectionContext.java | Java | apache-2.0 | 5,896 |
using Neptuo;
using Neptuo.Observables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using WebCamImageCollector.RemoteControl.Services;
using WebCamImageCollector.RemoteControl.ViewModels.Commands;
using WebCamImageCollector.RemoteControl.Views;
namespace WebCamImageCollector.RemoteControl.ViewModels
{
public class RemoteClientEditViewModel : ObservableObject
{
private string name;
public string Name
{
get { return name; }
set
{
if (name != value)
{
name = value;
RaisePropertyChanged();
}
}
}
private string url;
public string Url
{
get { return url; }
set
{
if (url != value)
{
url = value;
RaisePropertyChanged();
}
}
}
private string authenticationToken;
public string AuthenticationToken
{
get { return authenticationToken; }
set
{
if (authenticationToken != value)
{
authenticationToken = value;
RaisePropertyChanged();
}
}
}
public ICommand Save { get; private set; }
public ICommand Delete { get; private set; }
public RemoteClientEditViewModel()
{
Name = "New";
Url = "http://";
Save = new SaveRemoteCommand(this, null);
}
public RemoteClientEditViewModel(Guid key)
{
ClientRepository repository = new ClientRepository();
RemoteClient client = repository.FindRemote(key);
if (client != null)
{
Name = client.Name;
Url = client.Url;
AuthenticationToken = client.AuthenticationToken;
}
Save = new SaveRemoteCommand(this, key);
Delete = new DeleteRemoteCommand(key);
}
}
}
| maraf/WebCamImageCollector | src/WebCamImageCollector.RemoteControl.UI/ViewModels/RemoteClientEditViewModel.cs | C# | apache-2.0 | 2,324 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Tue Jul 19 23:14:44 CEST 2011 -->
<TITLE>
PortComponentRefType
</TITLE>
<META NAME="date" CONTENT="2011-07-19">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PortComponentRefType";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PortComponentRefType.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV CLASS
<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/ServiceRefHandlerChainsType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" target="_top"><B>FRAMES</B></A>
<A HREF="PortComponentRefType.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12</FONT>
<BR>
Interface PortComponentRefType<T></H2>
<DL>
<DT><B>All Superinterfaces:</B> <DD>org.jboss.shrinkwrap.descriptor.api.Child<T></DD>
</DL>
<DL>
<DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/impl/javaeewebservicesclient12/PortComponentRefTypeImpl.html" title="class in org.jboss.shrinkwrap.descriptor.impl.javaeewebservicesclient12">PortComponentRefTypeImpl</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public interface <B>PortComponentRefType<T></B><DT>extends org.jboss.shrinkwrap.descriptor.api.Child<T></DL>
</PRE>
<P>
This interface defines the contract for the <code> port-component-refType </code> xsd type
<p>
Original Documentation:
<p>
<br>
<br>
The port-component-ref element declares a client dependency <br>
on the container for resolving a Service Endpoint Interface <br>
to a WSDL port. It optionally associates the Service Endpoint <br>
Interface with a particular port-component. This is only used <br>
by the container for a Service.getPort(Class) method call. <br>
<br>
<br>
<P>
<P>
<DL>
<DT><B>Since:</B></DT>
<DD>Generation date :2011-07-19T22:54:35.59+02:00</DD>
<DT><B>Author:</B></DT>
<DD><a href="mailto:ralf.battenfeld@bluewin.ch">Ralf Battenfeld</a></DD>
</DL>
<HR>
<P>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html#getPortComponentLink()">getPortComponentLink</A></B>()</CODE>
<BR>
Returns the <code>port-component-link</code> element</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html#getServiceEndpointInterface()">getServiceEndpointInterface</A></B>()</CODE>
<BR>
Returns the <code>service-endpoint-interface</code> element</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.Boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html#isEnableMtom()">isEnableMtom</A></B>()</CODE>
<BR>
Returns the <code>enable-mtom</code> element</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html#removeEnableMtom()">removeEnableMtom</A></B>()</CODE>
<BR>
Removes the <code>enable-mtom</code> element</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html#removePortComponentLink()">removePortComponentLink</A></B>()</CODE>
<BR>
Removes the <code>port-component-link</code> element</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html#removeServiceEndpointInterface()">removeServiceEndpointInterface</A></B>()</CODE>
<BR>
Removes the <code>service-endpoint-interface</code> element</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html#setEnableMtom(java.lang.Boolean)">setEnableMtom</A></B>(java.lang.Boolean enableMtom)</CODE>
<BR>
If not already created, a new <code>enable-mtom</code> element with the given value will be created.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html#setPortComponentLink(java.lang.String)">setPortComponentLink</A></B>(java.lang.String portComponentLink)</CODE>
<BR>
If not already created, a new <code>port-component-link</code> element with the given value will be created.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html#setServiceEndpointInterface(java.lang.String)">setServiceEndpointInterface</A></B>(java.lang.String serviceEndpointInterface)</CODE>
<BR>
If not already created, a new <code>service-endpoint-interface</code> element with the given value will be created.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_org.jboss.shrinkwrap.descriptor.api.Child"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from interface org.jboss.shrinkwrap.descriptor.api.Child</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>up</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="setServiceEndpointInterface(java.lang.String)"><!-- --></A><H3>
setServiceEndpointInterface</H3>
<PRE>
<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>> <B>setServiceEndpointInterface</B>(java.lang.String serviceEndpointInterface)</PRE>
<DL>
<DD>If not already created, a new <code>service-endpoint-interface</code> element with the given value will be created.
Otherwise, the existing <code>service-endpoint-interface</code> element will be updated with the given value.
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the current instance of <CODE>PortComponentRefType<T></CODE></DL>
</DD>
</DL>
<HR>
<A NAME="removeServiceEndpointInterface()"><!-- --></A><H3>
removeServiceEndpointInterface</H3>
<PRE>
<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>> <B>removeServiceEndpointInterface</B>()</PRE>
<DL>
<DD>Removes the <code>service-endpoint-interface</code> element
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the current instance of <CODE>PortComponentRefType<T></CODE></DL>
</DD>
</DL>
<HR>
<A NAME="getServiceEndpointInterface()"><!-- --></A><H3>
getServiceEndpointInterface</H3>
<PRE>
java.lang.String <B>getServiceEndpointInterface</B>()</PRE>
<DL>
<DD>Returns the <code>service-endpoint-interface</code> element
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the node defined for the element <code>service-endpoint-interface</code></DL>
</DD>
</DL>
<HR>
<A NAME="setEnableMtom(java.lang.Boolean)"><!-- --></A><H3>
setEnableMtom</H3>
<PRE>
<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>> <B>setEnableMtom</B>(java.lang.Boolean enableMtom)</PRE>
<DL>
<DD>If not already created, a new <code>enable-mtom</code> element with the given value will be created.
Otherwise, the existing <code>enable-mtom</code> element will be updated with the given value.
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the current instance of <CODE>PortComponentRefType<T></CODE></DL>
</DD>
</DL>
<HR>
<A NAME="removeEnableMtom()"><!-- --></A><H3>
removeEnableMtom</H3>
<PRE>
<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>> <B>removeEnableMtom</B>()</PRE>
<DL>
<DD>Removes the <code>enable-mtom</code> element
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the current instance of <CODE>PortComponentRefType<T></CODE></DL>
</DD>
</DL>
<HR>
<A NAME="isEnableMtom()"><!-- --></A><H3>
isEnableMtom</H3>
<PRE>
java.lang.Boolean <B>isEnableMtom</B>()</PRE>
<DL>
<DD>Returns the <code>enable-mtom</code> element
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the node defined for the element <code>enable-mtom</code></DL>
</DD>
</DL>
<HR>
<A NAME="setPortComponentLink(java.lang.String)"><!-- --></A><H3>
setPortComponentLink</H3>
<PRE>
<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>> <B>setPortComponentLink</B>(java.lang.String portComponentLink)</PRE>
<DL>
<DD>If not already created, a new <code>port-component-link</code> element with the given value will be created.
Otherwise, the existing <code>port-component-link</code> element will be updated with the given value.
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the current instance of <CODE>PortComponentRefType<T></CODE></DL>
</DD>
</DL>
<HR>
<A NAME="removePortComponentLink()"><!-- --></A><H3>
removePortComponentLink</H3>
<PRE>
<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12">PortComponentRefType</A><<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" title="type parameter in PortComponentRefType">T</A>> <B>removePortComponentLink</B>()</PRE>
<DL>
<DD>Removes the <code>port-component-link</code> element
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the current instance of <CODE>PortComponentRefType<T></CODE></DL>
</DD>
</DL>
<HR>
<A NAME="getPortComponentLink()"><!-- --></A><H3>
getPortComponentLink</H3>
<PRE>
java.lang.String <B>getPortComponentLink</B>()</PRE>
<DL>
<DD>Returns the <code>port-component-link</code> element
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the node defined for the element <code>port-component-link</code></DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PortComponentRefType.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV CLASS
<A HREF="../../../../../../org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/ServiceRefHandlerChainsType.html" title="interface in org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html" target="_top"><B>FRAMES</B></A>
<A HREF="PortComponentRefType.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| shrinkwrap/descriptors | gen/doc/org/jboss/shrinkwrap/descriptor/api/javaeewebservicesclient12/PortComponentRefType.html | HTML | apache-2.0 | 22,256 |
package com.rbac.service;
import com.rbac.entity.FunctionEntity;
import com.rbac.entity.MenuEntity;
import com.rbac.vo.PageResult;
import com.rbac.vo.formbean.FunctionFormBean;
import java.util.List;
/**
*
*/
public interface FunctionService {
PageResult<FunctionFormBean> pageQueryFunction(int currentPage, int pageSize, int mid);
int addFunction(FunctionFormBean functionFormBean);
int updateFunction(FunctionFormBean functionFormBean);
FunctionEntity findFunctionByFid(int fid);
List<String> findResourcesByUid(int uid);
int deleteFunctionByFid(int fid);
}
| cx118118/ssm-rbac | src/main/java/com/rbac/service/FunctionService.java | Java | apache-2.0 | 595 |
# ===============================================================================
# Copyright 2013 Jake Ross
#
# 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.
# ===============================================================================
# ============= enthought library imports =======================
from __future__ import absolute_import
from traitsui.api import View, Item, VGroup, InstanceEditor, UItem, EnumEditor, \
RangeEditor, spring, HGroup, Group, ButtonEditor
# ============= standard library imports ========================
# ============= local library imports ==========================
from pychron.core.ui.custom_label_editor import CustomLabel
from pychron.core.ui.led_editor import LEDEditor
from pychron.envisage.icon_button_editor import icon_button_editor
from pychron.lasers.tasks.laser_panes import ClientPane
class AblationCO2ClientPane(ClientPane):
def trait_context(self):
ctx = super(AblationCO2ClientPane, self).trait_context()
ctx['tray_calibration'] = self.model.stage_manager.tray_calibration_manager
ctx['stage_manager'] = self.model.stage_manager
return ctx
def traits_view(self):
pos_grp = VGroup(UItem('move_enabled_button',
editor=ButtonEditor(label_value='move_enabled_label')),
VGroup(HGroup(Item('position'),
UItem('stage_manager.stage_map_name',
editor=EnumEditor(name='stage_manager.stage_map_names')),
UItem('stage_stop_button')),
Item('x', editor=RangeEditor(low_name='stage_manager.xmin',
high_name='stage_manager.xmax')),
Item('y', editor=RangeEditor(low_name='stage_manager.ymin',
high_name='stage_manager.ymax')),
Item('z', editor=RangeEditor(low_name='stage_manager.zmin',
high_name='stage_manager.zmax')),
enabled_when='_move_enabled'),
label='Positioning')
calibration_grp = VGroup(UItem('tray_calibration.style',
enabled_when='not tray_calibration.isCalibrating()'),
UItem('tray_calibration.calibrate',
editor=ButtonEditor(label_value='tray_calibration.calibration_step')),
HGroup(Item('tray_calibration.cx', format_str='%0.3f', style='readonly'),
Item('tray_calibration.cy', format_str='%0.3f', style='readonly')),
Item('tray_calibration.rotation', format_str='%0.3f', style='readonly'),
Item('tray_calibration.scale', format_str='%0.4f', style='readonly'),
Item('tray_calibration.error', format_str='%0.2f', style='readonly'),
UItem('tray_calibration.calibrator', style='custom', editor=InstanceEditor()),
CustomLabel('tray_calibration.calibration_help',
color='green',
height=75, width=300),
label='Tray Calibration')
tgrp = Group(pos_grp, calibration_grp, layout='tabbed')
egrp = HGroup(UItem('enabled', editor=LEDEditor(colors=['red', 'green'])),
UItem('enable', editor=ButtonEditor(label_value='enable_label')),
UItem('fire_laser_button', editor=ButtonEditor(label_value='fire_label'),
enabled_when='enabled'),
Item('output_power', label='Power'),
UItem('units'),
spring,
icon_button_editor('snapshot_button', 'camera'),
icon_button_editor('test_connection_button',
'connect', tooltip='Test Connection'))
v = View(VGroup(egrp, tgrp))
return v
# ============= EOF =============================================
| UManPychron/pychron | pychron/lasers/tasks/panes/ablation.py | Python | apache-2.0 | 4,882 |
#ifndef LPC_INCL_H
#define LPC_INCL_H
#include "std.h"
#include "include/function.h"
#include "include/origin.h"
#include "config.h"
#include "applies.h"
#include "main.h"
#include "program.h"
#include "buffer.h"
#include "interpret.h"
#include "simulate.h"
#include "file.h"
#include "stralloc.h"
#endif
| holtsoftware/potential-octo-wallhack | School C++/other/lpc/lpc_incl.h | C | apache-2.0 | 307 |
/*
* Copyright 2012, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.builder;
import org.jf.dexlib2.Format;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.util.Preconditions;
public abstract class BuilderInstruction implements Instruction {
protected final Opcode opcode;
MethodLocation location;
protected BuilderInstruction( Opcode opcode) {
Preconditions.checkFormat(opcode, getFormat());
this.opcode = opcode;
}
public Opcode getOpcode() {
return opcode;
}
public abstract Format getFormat();
public int getCodeUnits() {
return getFormat().size / 2;
}
public MethodLocation getLocation() {
if (location == null) {
throw new IllegalStateException("Cannot get the location of an instruction that hasn't been added to a " +
"method.");
}
return location;
}
}
| AndreJCL/JCL | JCL_Android/app/src/main/java/org/jf/dexlib2/builder/BuilderInstruction.java | Java | apache-2.0 | 2,483 |
using System;
using System.Collections.Generic;
using System.Linq;
using Stardust.Aadb2c.AuthenticationFilter.Core;
using Stardust.Particles;
namespace Stardust.Aadb2c.Swagger
{
public static class B2cGlobalSwaggerConfig
{
private static readonly object Triowing = new object();
private static ScopeDescription[] _scopes;
public static ScopeDescription[] Scopes
{
get
{
if (_scopes != null) return _scopes;
lock (Triowing)
{
if (_scopes == null)
{
var internalList = new List<ScopeDescription>();
var scopes = ConfigurationManagerHelper.GetValueOnKey("aadScopes").Split('|');
foreach (var scope in scopes)
{
var parts = scope.Split(';');
if (parts.Length == 0) continue;
// ReSharper disable once NotResolvedInText
if (parts.Length > 2)
throw new ArgumentException(
$"scope {parts[0]} contains ; in either the scope name part or in the description ({scope})",
"aadScopes");
internalList.Add(
new ScopeDescription { ScopeName = parts[0], Description = parts.Last() });
}
_scopes = internalList.ToArray();
return _scopes;
}
else
{
return _scopes;
}
}
}
set
{
ConfigurationManagerHelper.SetValueOnKey("aadScopes", string.Join("|", value.Select(v => $"{v.ScopeName};{v.Description}")));
}
}
public static string ApplicationDescription
{
get
{
return ConfigurationManagerHelper.GetValueOnKey("aadFlowDescription", "OAuth2 Implicit Grant");
}
set
{
ConfigurationManagerHelper.SetValueOnKey("aadFlowDescription", value, true);
}
}
public static bool UseV2Endpoint
{
get
{
return ConfigurationManagerHelper.GetValueOnKey("aadUseV2Endpoint", true);
}
set
{
ConfigurationManagerHelper.SetValueOnKey("aadUseV2Endpoint", value.ToString(), true);
}
}
public static string TenantId
{
get
{
return ConfigurationManagerHelper.GetValueOnKey("aadTenantId");
}
set
{
ConfigurationManagerHelper.SetValueOnKey("aadTenantId", value, true);
}
}
public static string ClientId
{
get
{
return ConfigurationManagerHelper.GetValueOnKey("swaggerClientId");
}
set
{
ConfigurationManagerHelper.SetValueOnKey("swaggerClientId", value, true);
}
}
public static string ClientSecret
{
get
{
return ConfigurationManagerHelper.GetValueOnKey("swaggerClientSecret");
}
set
{
ConfigurationManagerHelper.SetValueOnKey("swaggerClientSecret", value, true);
}
}
public static string AppName
{
get
{
return ConfigurationManagerHelper.GetValueOnKey("swaggerAppName");
}
set
{
ConfigurationManagerHelper.SetValueOnKey("swaggerAppName", value, true);
}
}
public static string Policy
{
get { return B2CGlobalConfiguration.AadPolicy; }
set
{
B2CGlobalConfiguration.AadPolicy = value;
}
}
}
} | JonasSyrstad/Stardust.Aadb2c.AuthenticationFilter | src/Stardust.Aadb2c.Swagger/B2cGlobalSwaggerConfig.cs | C# | apache-2.0 | 4,193 |
/*
* Copyright 2016-2021 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.lettuce.core.cluster.pubsub.api.sync;
import io.lettuce.core.cluster.api.sync.Executions;
/**
* Synchronous executed commands on a node selection for Pub/Sub.
*
* @author Mark Paluch
* @since 4.4
*/
public interface NodeSelectionPubSubCommands<K, V> {
/**
* Listen for messages published to channels matching the given patterns.
*
* @param patterns the patterns
* @return Executions to synchronize {@code psubscribe} completion
*/
Executions<Void> psubscribe(K... patterns);
/**
* Stop listening for messages posted to channels matching the given patterns.
*
* @param patterns the patterns
* @return Executions Future to synchronize {@code punsubscribe} completion
*/
Executions<Void> punsubscribe(K... patterns);
/**
* Listen for messages published to the given channels.
*
* @param channels the channels
* @return Executions Future to synchronize {@code subscribe} completion
*/
Executions<Void> subscribe(K... channels);
/**
* Stop listening for messages posted to the given channels.
*
* @param channels the channels
* @return Executions Future to synchronize {@code unsubscribe} completion.
*/
Executions<Void> unsubscribe(K... channels);
}
| mp911de/lettuce | src/main/java/io/lettuce/core/cluster/pubsub/api/sync/NodeSelectionPubSubCommands.java | Java | apache-2.0 | 1,923 |
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.exec.store.parquet;
import static org.apache.parquet.schema.Type.Repetition.REPEATED;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.parquet.column.ColumnDescriptor;
import org.apache.parquet.hadoop.metadata.BlockMetaData;
import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
import org.apache.parquet.schema.DecimalMetadata;
import org.apache.parquet.schema.GroupType;
import org.apache.parquet.schema.MessageType;
import org.apache.parquet.schema.OriginalType;
import org.apache.parquet.schema.PrimitiveType;
import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName;
import org.apache.parquet.schema.Type;
import org.apache.parquet.schema.Type.Repetition;
import com.dremio.common.exceptions.UserException;
import com.dremio.common.expression.CompleteType;
import com.dremio.common.expression.SchemaPath;
import com.dremio.common.types.TypeProtos.DataMode;
import com.dremio.common.types.TypeProtos.MajorType;
import com.dremio.common.types.TypeProtos.MinorType;
import com.dremio.exec.store.parquet2.LogicalListL1Converter;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
public class ParquetTypeHelper {
private static Map<MinorType, PrimitiveTypeName> typeMap;
private static Map<DataMode, Repetition> modeMap;
private static Map<MinorType, OriginalType> originalTypeMap;
static {
typeMap = new HashMap<>();
typeMap.put(MinorType.TINYINT, PrimitiveTypeName.INT32);
typeMap.put(MinorType.UINT1, PrimitiveTypeName.INT32);
typeMap.put(MinorType.UINT2, PrimitiveTypeName.INT32);
typeMap.put(MinorType.SMALLINT, PrimitiveTypeName.INT32);
typeMap.put(MinorType.INT, PrimitiveTypeName.INT32);
typeMap.put(MinorType.UINT4, PrimitiveTypeName.INT32);
typeMap.put(MinorType.FLOAT4, PrimitiveTypeName.FLOAT);
typeMap.put(MinorType.INTERVALYEAR, PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY);
typeMap.put(MinorType.TIME, PrimitiveTypeName.INT32);
typeMap.put(MinorType.BIGINT, PrimitiveTypeName.INT64);
typeMap.put(MinorType.UINT8, PrimitiveTypeName.INT64);
typeMap.put(MinorType.FLOAT8, PrimitiveTypeName.DOUBLE);
typeMap.put(MinorType.DATE, PrimitiveTypeName.INT32);
typeMap.put(MinorType.TIMESTAMP, PrimitiveTypeName.INT64);
typeMap.put(MinorType.INTERVALDAY, PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY);
typeMap.put(MinorType.DECIMAL, PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY);
typeMap.put(MinorType.VARBINARY, PrimitiveTypeName.BINARY);
typeMap.put(MinorType.VARCHAR, PrimitiveTypeName.BINARY);
typeMap.put(MinorType.BIT, PrimitiveTypeName.BOOLEAN);
originalTypeMap = new HashMap<>();
originalTypeMap.put(MinorType.DECIMAL, OriginalType.DECIMAL);
originalTypeMap.put(MinorType.VARCHAR, OriginalType.UTF8);
originalTypeMap.put(MinorType.DATE, OriginalType.DATE);
originalTypeMap.put(MinorType.TIME, OriginalType.TIME_MILLIS);
originalTypeMap.put(MinorType.TIMESTAMP, OriginalType.TIMESTAMP_MILLIS);
originalTypeMap.put(MinorType.INTERVALDAY, OriginalType.INTERVAL);
originalTypeMap.put(MinorType.INTERVALYEAR, OriginalType.INTERVAL);
originalTypeMap.put(MinorType.INTERVAL, OriginalType.INTERVAL);
}
public static PrimitiveTypeName getPrimitiveTypeNameForMinorType(MinorType minorType) {
PrimitiveTypeName primitiveTypeName = typeMap.get(minorType);
return primitiveTypeName;
}
public static OriginalType getOriginalTypeForMinorType(MinorType minorType) {
return originalTypeMap.get(minorType);
}
public static DecimalMetadata getDecimalMetadataForField(MajorType type) {
switch (type.getMinorType()) {
case DECIMAL:
case DECIMAL9:
case DECIMAL18:
case DECIMAL28SPARSE:
case DECIMAL28DENSE:
case DECIMAL38SPARSE:
case DECIMAL38DENSE:
return new DecimalMetadata(type.getPrecision(), type.getScale());
default:
return null;
}
}
public static int getLengthForMinorType(MinorType minorType) {
switch (minorType) {
case INTERVALDAY:
case INTERVALYEAR:
case INTERVAL:
return 12;
case DECIMAL28SPARSE:
return 12;
case DECIMAL:
case DECIMAL38SPARSE:
return 16;
default:
return 0;
}
}
/**
* Returns an arrow vector field for a parquet primitive field
*
* @param colPath schema path of the column
* @param primitiveType parquet primitive type
* @param originalType parquet original type
* @param schemaHelper schema helper used for type conversions
* @return arrow vector field
*/
public static Field createField(SchemaPath colPath,
PrimitiveType primitiveType,
OriginalType originalType,
SchemaDerivationHelper schemaHelper) {
final String colName = colPath.getAsNamePart().getName();
switch (primitiveType.getPrimitiveTypeName()) {
case BINARY:
case FIXED_LEN_BYTE_ARRAY:
if (originalType == OriginalType.UTF8) {
return CompleteType.VARCHAR.toField(colName);
}
if (originalType == OriginalType.DECIMAL) {
return CompleteType.fromDecimalPrecisionScale(primitiveType.getDecimalMetadata()
.getPrecision(), primitiveType.getDecimalMetadata().getScale()).toField(colName);
}
if (schemaHelper.isVarChar(colPath)) {
return CompleteType.VARCHAR.toField(colName);
}
return CompleteType.VARBINARY.toField(colName);
case BOOLEAN:
return CompleteType.BIT.toField(colName);
case DOUBLE:
return CompleteType.DOUBLE.toField(colName);
case FLOAT:
return CompleteType.FLOAT.toField(colName);
case INT32:
if (originalType == OriginalType.DATE) {
return CompleteType.DATE.toField(colName);
} else if (originalType == OriginalType.TIME_MILLIS) {
return CompleteType.TIME.toField(colName);
} else if (originalType == OriginalType.DECIMAL) {
return CompleteType.fromDecimalPrecisionScale(primitiveType.getDecimalMetadata()
.getPrecision(), primitiveType.getDecimalMetadata().getScale()).toField(colName);
}
return CompleteType.INT.toField(colName);
case INT64:
if (originalType == OriginalType.TIMESTAMP_MILLIS || originalType == OriginalType.TIMESTAMP_MICROS) {
return CompleteType.TIMESTAMP.toField(colName);
} else if (originalType == OriginalType.TIME_MICROS) {
return CompleteType.TIME.toField(colName);
} else if (originalType == OriginalType.DECIMAL) {
return CompleteType.fromDecimalPrecisionScale(primitiveType.getDecimalMetadata()
.getPrecision(), primitiveType.getDecimalMetadata().getScale()).toField(colName);
}
return CompleteType.BIGINT.toField(colName);
case INT96:
if (schemaHelper.readInt96AsTimeStamp()) {
return CompleteType.TIMESTAMP.toField(colName);
}
return CompleteType.VARBINARY.toField(colName);
default:
throw UserException.unsupportedError()
.message("Parquet Primitive Type '%s', Original Type '%s' combination not supported. Column '%s'",
primitiveType.toString(), originalType != null ? originalType : "Not Available", colName)
.build();
}
}
public static Optional<Field> toField(final Type parquetField, final SchemaDerivationHelper schemaHelper) {
return toField(parquetField, schemaHelper, false);
}
private static Optional<Field> toField(final Type parquetField, final SchemaDerivationHelper schemaHelper, boolean convertToStruct) {
if (parquetField.isPrimitive()) {
SchemaPath columnSchemaPath = SchemaPath.getCompoundPath(parquetField.getName());
Field field = createField(columnSchemaPath, parquetField.asPrimitiveType(), parquetField.getOriginalType(), schemaHelper);
if (parquetField.isRepetition(REPEATED)) {
Field listChild = new Field("$data$", true, field.getType(), field.getChildren());
return Optional.of(new Field(field.getName(), true, new ArrowType.List(), Arrays.asList(listChild)));
}
return Optional.of(field);
}
// Handle non-primitive cases
final GroupType complexField = (GroupType) parquetField;
if (OriginalType.LIST == complexField.getOriginalType() && LogicalListL1Converter.isSupportedSchema(complexField)) {
GroupType repeatedField = (GroupType) complexField.getFields().get(0);
Optional<Field> subField = toField(repeatedField.getFields().get(0), schemaHelper);
subField = subField.map(sf -> new Field("$data$", true, sf.getType(), sf.getChildren()));
return subField.map(sf -> new Field(complexField.getName(), true, new ArrowType.List(), Arrays.asList(new Field[] {sf})));
} else if (OriginalType.LIST == complexField.getOriginalType()) {
if (complexField.getFieldCount() == 1) {
Type type = complexField.getType(0);
Optional<Field> subField = toField(type, schemaHelper);
if (complexField.isRepetition(REPEATED)) {
subField = subField.map(sf -> new Field("$data$", true, new ArrowType.Struct(), Arrays.asList(new Field[] {sf})));
return subField.map(sf -> new Field(complexField.getName(), true, new ArrowType.List(), Arrays.asList(new Field[] {sf})));
} else {
return subField.map(sf -> new Field(complexField.getName(), true, new ArrowType.Struct(), Arrays.asList(new Field[] {sf})));
}
}
throw UserException.unsupportedError()
.message("Parquet List Type is expected to contain only one sub type. Column '%s' contains %d", parquetField.getName(), complexField.getFieldCount())
.build();
}
if (OriginalType.MAP == complexField.getOriginalType() && !convertToStruct) {
GroupType repeatedField = (GroupType) complexField.getFields().get(0);
// should have only one child field type
if (repeatedField.isPrimitive() || !repeatedField.isRepetition(REPEATED) || repeatedField.asGroupType().getFields().size() != 2) {
throw UserException.unsupportedError()
.message("Parquet Map Type is expected to contain key and value fields. Column '%s' contains %d", parquetField.getName(), repeatedField.getFieldCount())
.build();
}
Optional<Field> subField = toField(repeatedField, schemaHelper,true);
if (complexField.isRepetition(REPEATED)) {
subField = subField.map(sf -> new Field("$data$", true, sf.getType(), sf.getChildren()));
subField = subField.map(sf -> new Field(repeatedField.getName(), true, new ArrowType.List(), Arrays.asList(new Field[] {sf})));
subField = subField.map(sf -> new Field("$data$", true, new ArrowType.Struct(), Arrays.asList(new Field[] {sf})));
return subField.map(sf -> new Field(complexField.getName(), true, new ArrowType.List(), Arrays.asList(new Field[] {sf})));
} else {
subField = subField.map(sf -> new Field("$data$", true, sf.getType(), sf.getChildren()));
subField = subField.map(sf -> new Field(repeatedField.getName(), true, new ArrowType.List(), Arrays.asList(new Field[] {sf})));
return subField.map(sf -> new Field(complexField.getName(), true, new ArrowType.Struct(), Arrays.asList(new Field[] {sf})));
}
}
final boolean isStructType = complexField.getOriginalType() == null || convertToStruct;
if (isStructType) { // it is struct
return toComplexField(complexField, new ArrowType.Struct(), schemaHelper, convertToStruct);
}
// Unsupported complex type
return Optional.empty();
}
private static Optional<Field> toComplexField(GroupType complexField, ArrowType arrowType, SchemaDerivationHelper schemaHelper, boolean convertToStruct) {
List<Field> subFields = new ArrayList<>(complexField.getFieldCount());
for (int fieldIdx = 0; fieldIdx < complexField.getFieldCount(); fieldIdx++) {
Optional<Field> subField = toField(complexField.getType(fieldIdx), schemaHelper);
if (!subField.isPresent()) {
return Optional.empty();
} else {
subFields.add(subField.get());
}
}
Field field = new Field(complexField.getName(), true, arrowType, subFields);
if (complexField.isRepetition(REPEATED)
&& !convertToStruct
&& OriginalType.MAP_KEY_VALUE != complexField.getOriginalType()
&& OriginalType.MAP != complexField.getOriginalType()
&& OriginalType.LIST != complexField.getOriginalType()) {
Field listChild = new Field("$data$", true, field.getType(), field.getChildren());
return Optional.of(new Field(field.getName(), true, new ArrowType.List(), Arrays.asList(listChild)));
}
return Optional.of(field);
}
private static boolean includeChunk(String name, SortedSet<String> allProjectedPaths, boolean allowPartialMatch) {
boolean included = allProjectedPaths == null ||
allProjectedPaths.contains(name);
if (!included && allowPartialMatch) {
included = !allProjectedPaths.subSet(name + ".", name + "." + Character.MAX_VALUE).isEmpty();
}
return included;
}
public static SortedMap<String, ColumnChunkMetaData> unWrapParquetSchema(BlockMetaData block, MessageType schema,
SortedSet<String> allProjectedPaths) {
SortedMap<String, ColumnChunkMetaData> unwrappedColumns = new TreeMap<>(String::compareToIgnoreCase);
for(ColumnChunkMetaData c : block.getColumns()) {
ColumnDescriptor columnDesc = schema.getColumnDescription(c.getPath().toArray());
Type type = schema;
List<String> columnPath = Lists.newArrayList(columnDesc.getPath());
int index = 0;
boolean chunkIncluded = includeChunk(columnPath.get(0), allProjectedPaths, true);
if (!chunkIncluded) {
continue;
}
chunkIncluded = false;
StringBuilder stringBuilder = new StringBuilder();
while (!type.isPrimitive()) {
type = type.asGroupType().getType(columnPath.get(index));
if (index > 0) {
stringBuilder.append(".");
}
stringBuilder.append(columnPath.get(index));
chunkIncluded = chunkIncluded || includeChunk(stringBuilder.toString(), allProjectedPaths, false);
if (type.getOriginalType() == OriginalType.LIST) {
if (!LogicalListL1Converter.isSupportedSchema(type.asGroupType())) {
throw UserException.dataReadError()
.message("Unsupported LOGICAL LIST parquet schema")
.addContext("schema", schema)
.buildSilently();
}
type = type.asGroupType().getType(columnPath.get(index+1));
stringBuilder.append(".list");
columnPath.remove(index+1);
type = type.asGroupType().getType(columnPath.get(index+1));
while(type.getOriginalType() == OriginalType.LIST) {
if (!LogicalListL1Converter.isSupportedSchema(type.asGroupType())) {
throw UserException.dataReadError()
.message("Unsupported LOGICAL LIST parquet schema")
.addContext("schema", schema)
.buildSilently();
}
stringBuilder.append(".element");
chunkIncluded = chunkIncluded || includeChunk(stringBuilder.toString(), allProjectedPaths, false);
columnPath.remove(index+1);
type = type.asGroupType().getType(columnPath.get(index+1));
stringBuilder.append(".list");
columnPath.remove(index+1);
type = type.asGroupType().getType(columnPath.get(index+1));
}
stringBuilder.append(".element");
chunkIncluded = chunkIncluded || includeChunk(stringBuilder.toString(), allProjectedPaths, false);
columnPath.remove(index+1);
}
if (type.getOriginalType() == OriginalType.MAP) {
index++;
Preconditions.checkState(type.asGroupType().getFieldCount() == 1, "Map column has more than one field");
type = type.asGroupType().getFields().get(0);
stringBuilder.append("." + type.getName());
chunkIncluded = chunkIncluded || includeChunk(stringBuilder.toString(), allProjectedPaths, false);
stringBuilder.append(".list.element");
chunkIncluded = chunkIncluded || includeChunk(stringBuilder.toString(), allProjectedPaths, false);
}
index++;
}
if (chunkIncluded) {
unwrappedColumns.put(stringBuilder.toString().toLowerCase(), c);
}
}
return unwrappedColumns;
}
}
| dremio/dremio-oss | sabot/kernel/src/main/java/com/dremio/exec/store/parquet/ParquetTypeHelper.java | Java | apache-2.0 | 17,594 |
package authz
import (
"net"
"testing"
)
func sp(s string) *string {
return &s
}
func TestValidation(t *testing.T) {
cases := []struct {
mc MatchConditions
ok bool
}{
// Valid stuff
{MatchConditions{}, true},
{MatchConditions{Account: sp("foo")}, true},
{MatchConditions{Account: sp("foo?*")}, true},
{MatchConditions{Account: sp("/foo.*/")}, true},
{MatchConditions{Type: sp("foo")}, true},
{MatchConditions{Type: sp("foo?*")}, true},
{MatchConditions{Type: sp("/foo.*/")}, true},
{MatchConditions{Name: sp("foo")}, true},
{MatchConditions{Name: sp("foo?*")}, true},
{MatchConditions{Name: sp("/foo.*/")}, true},
{MatchConditions{Service: sp("foo")}, true},
{MatchConditions{Service: sp("foo?*")}, true},
{MatchConditions{Service: sp("/foo.*/")}, true},
{MatchConditions{IP: sp("192.168.0.1")}, true},
{MatchConditions{IP: sp("192.168.0.0/16")}, true},
{MatchConditions{IP: sp("2001:db8::1")}, true},
{MatchConditions{IP: sp("2001:db8::/48")}, true},
{MatchConditions{Labels: map[string]string{"foo": "bar"}}, true},
// Invalid stuff
{MatchConditions{Account: sp("/foo?*/")}, false},
{MatchConditions{Type: sp("/foo?*/")}, false},
{MatchConditions{Name: sp("/foo?*/")}, false},
{MatchConditions{Service: sp("/foo?*/")}, false},
{MatchConditions{IP: sp("192.168.0.1/100")}, false},
{MatchConditions{IP: sp("192.168.0.*")}, false},
{MatchConditions{IP: sp("foo")}, false},
{MatchConditions{IP: sp("2001:db8::/222")}, false},
{MatchConditions{Labels: map[string]string{"foo": "/bar?*/"}}, false},
}
for i, c := range cases {
result := validateMatchConditions(&c.mc)
if c.ok && result != nil {
t.Errorf("%d: %q: expected to pass, got %s", i, c.mc, result)
} else if !c.ok && result == nil {
t.Errorf("%d: %q: expected to fail, but it passed", i, c.mc)
}
}
}
func TestMatching(t *testing.T) {
ai1 := AuthRequestInfo{Account: "foo", Type: "bar", Name: "baz", Service: "notary"}
ai2 := AuthRequestInfo{Account: "foo", Type: "bar", Name: "baz", Service: "notary",
Labels: map[string][]string{"group": []string{"admins", "VIP"}}}
cases := []struct {
mc MatchConditions
ai AuthRequestInfo
matches bool
}{
{MatchConditions{}, ai1, true},
{MatchConditions{Account: sp("foo")}, ai1, true},
{MatchConditions{Account: sp("foo"), Type: sp("bar")}, ai1, true},
{MatchConditions{Account: sp("foo"), Type: sp("baz")}, ai1, false},
{MatchConditions{Account: sp("fo?"), Type: sp("b*"), Name: sp("/z$/")}, ai1, true},
{MatchConditions{Account: sp("fo?"), Type: sp("b*"), Name: sp("/^z/")}, ai1, false},
{MatchConditions{Name: sp("${account}")}, AuthRequestInfo{Account: "foo", Name: "foo"}, true}, // Var subst
{MatchConditions{Name: sp("/${account}_.*/")}, AuthRequestInfo{Account: "foo", Name: "foo_x"}, true},
{MatchConditions{Name: sp("/${account}_.*/")}, AuthRequestInfo{Account: ".*", Name: "foo_x"}, false}, // Quoting
{MatchConditions{Account: sp(`/^(.+)@test\.com$/`), Name: sp(`${account:1}/*`)}, AuthRequestInfo{Account: "john.smith@test.com", Name: "john.smith/test"}, true},
{MatchConditions{Account: sp(`/^(.+)@test\.com$/`), Name: sp(`${account:3}/*`)}, AuthRequestInfo{Account: "john.smith@test.com", Name: "john.smith/test"}, false},
{MatchConditions{Account: sp(`/^(.+)@(.+?).test\.com$/`), Name: sp(`${account:1}-${account:2}/*`)}, AuthRequestInfo{Account: "john.smith@it.test.com", Name: "john.smith-it/test"}, true},
{MatchConditions{Service: sp("notary"), Type: sp("bar")}, ai1, true},
{MatchConditions{Service: sp("notary"), Type: sp("baz")}, ai1, false},
{MatchConditions{Service: sp("notary1"), Type: sp("bar")}, ai1, false},
// IP matching
{MatchConditions{IP: sp("127.0.0.1")}, AuthRequestInfo{IP: nil}, false},
{MatchConditions{IP: sp("127.0.0.1")}, AuthRequestInfo{IP: net.IPv4(127, 0, 0, 1)}, true},
{MatchConditions{IP: sp("127.0.0.1")}, AuthRequestInfo{IP: net.IPv4(127, 0, 0, 2)}, false},
{MatchConditions{IP: sp("127.0.0.2")}, AuthRequestInfo{IP: net.IPv4(127, 0, 0, 1)}, false},
{MatchConditions{IP: sp("127.0.0.0/8")}, AuthRequestInfo{IP: net.IPv4(127, 0, 0, 1)}, true},
{MatchConditions{IP: sp("127.0.0.0/8")}, AuthRequestInfo{IP: net.IPv4(127, 0, 0, 2)}, true},
{MatchConditions{IP: sp("2001:db8::1")}, AuthRequestInfo{IP: nil}, false},
{MatchConditions{IP: sp("2001:db8::1")}, AuthRequestInfo{IP: net.ParseIP("2001:db8::1")}, true},
{MatchConditions{IP: sp("2001:db8::1")}, AuthRequestInfo{IP: net.ParseIP("2001:db8::2")}, false},
{MatchConditions{IP: sp("2001:db8::2")}, AuthRequestInfo{IP: net.ParseIP("2001:db8::1")}, false},
{MatchConditions{IP: sp("2001:db8::/48")}, AuthRequestInfo{IP: net.ParseIP("2001:db8::1")}, true},
{MatchConditions{IP: sp("2001:db8::/48")}, AuthRequestInfo{IP: net.ParseIP("2001:db8::2")}, true},
// Label matching
{MatchConditions{Labels: map[string]string{"foo": "bar"}}, ai1, false},
{MatchConditions{Labels: map[string]string{"foo": "bar"}}, ai2, false},
{MatchConditions{Labels: map[string]string{"group": "admins"}}, ai2, true},
{MatchConditions{Labels: map[string]string{"foo": "bar", "group": "admins"}}, ai2, false}, // "and" logic
{MatchConditions{Labels: map[string]string{"group": "VIP"}}, ai2, true},
{MatchConditions{Labels: map[string]string{"group": "a*"}}, ai2, true},
{MatchConditions{Labels: map[string]string{"group": "/(admins|VIP)/"}}, ai2, true},
}
for i, c := range cases {
if result := c.mc.Matches(&c.ai); result != c.matches {
t.Errorf("%d: %#v vs %#v: expected %t, got %t", i, c.mc, c.ai, c.matches, result)
}
}
}
| tangfeixiong/go-to-exercise | vendor/github.com/cesanta/docker_auth/auth_server/authz/acl_test.go | GO | apache-2.0 | 5,582 |
Titanium.include( "../models/notice.js" );
Titanium.include( "../models/product.js" );
Titanium.include( "../helpers/bottom_menu.js" );
var win = Titanium.UI.currentWindow;
var tableView, listeners = [];
function main() {
// HACK: get active tab index.
win.tabGroup.addEventListener( "focus", function( e ) {
setTimeout( function() {
if ( 1 === win.tabGroup.activeTab ) {
_loadNotices();
}
}, 100 );
} );
_loadNotices();
_buildMenu();
}
function _loadNotices() {
var indicator = Barrel.UI.statusInidicator();
indicator.show();
var notice = new Notice();
var notices = notice.list();
notice.close();
Ti.API.debug( "notices length: " + notices.length );
if ( 0 == notices.length ) {
win.remove( tableView );
var row = Titanium.UI.createTableViewRow( {
height: 80,
className: "row"
} );
var label = Titanium.UI.createLabel( {
text: "\\\\ no existe ningún producto para realizar notificaciones! \\\\",
font: {fontSize: 10, fontWeight: "bold"},
color: "#ffffff",
textAlign: "left",
width: "auto"
} );
row.add( label );
tableView = Titanium.UI.createTableView();
tableView.data = [];
tableView.setData( [row] );
win.add( tableView );
indicator.hide();
notice.close();
Titanium.App.Properties.setBool( "noNotices", true );
// go away!.
return;
}
var data = _buildTable( notices );
win.remove( tableView );
tableView = Titanium.UI.createTableView();
tableView.data = [];
tableView.setData( data );
win.add( tableView );
indicator.hide();
}
function _buildTable( notices ) {
if ( typeof notices != "object" ) {
alert( "notices must be an object" );
return [];
}
var data = [];
for ( var key = 0; key < notices.length; key++ ) ( function ( key ) {
if ( listeners[key] ) {
clearInterval( listeners[key] ); // clear listener
}
var row = Titanium.UI.createTableViewRow( {
height: 80
} );
var productDataView = Titanium.UI.createView( {
height: 80,
width: "auto"
} );
var _openProductUrl = function ( e ) {
Titanium.Platform.openURL( notices[key].url );
}
productDataView.addEventListener( "click", _openProductUrl );
var image = Titanium.UI.createImageView( {
image: notices[key].image,
top: 17,
left: 10,
width: 48,
height: 48
} );
productDataView.add( image );
var name = Titanium.UI.createLabel( {
text: notices[key].name,
font: {fontSize: 12, fontWeight: "bold"},
textAlign: "left",
left: 70,
top: 5,
height: 30,
width: 200
} );
productDataView.add( name );
var users = Titanium.UI.createLabel( {
text: "\\\\ usuarios \\\\ " + notices[key].users,
font: {fontSize: 10, fontWeight: "bold"},
color: "#ffffff",
textAlign: "left",
left: 70,
top: 35,
height: 20,
width: 200
} );
productDataView.add( users );
var price = Titanium.UI.createLabel( {
text: "\\\\ precio actual \\\\ $" + Barrel.Text.numberFormat( notices[key].price, 0, "", "." ),
font: {fontSize: 10, fontWeight: "bold"},
color: "#ffffff",
textAlign: "left",
left: 70,
top: 50,
height: 20,
width: 200
} );
productDataView.add( price );
row.add( productDataView );
var skullIcon = Titanium.UI.createImageView( {
image: "../../images/icons/22-skull-n-crossbones-white.png",
top: 25,
right: 5,
width: 32,
height: 32,
canScale: false
} );
var _removeNotification = function ( e ) {
var confirmation = Titanium.UI.createAlertDialog( {
title: "alerta!",
message: "desea borrar este producto de las notificaciones de precios?",
buttonNames: ["si", "no"],
cancel: 1
} );
confirmation.addEventListener( "click", function ( e ) {
switch ( parseInt( e.index ) ) {
case 0:
var notice = new Notice();
notice.destroy( notices[key].id );
notice.close();
_loadNotices();
break;
case 1:
this.hide();
break;
}
} );
confirmation.show();
}
skullIcon.addEventListener( "click", _removeNotification );
row.add( skullIcon );
row.className = "item" + key;
data[key] = row;
listeners[key] = setInterval( function () {
_askPrice( notices[key] );
}, CONFIG.NOTICES_INTERVAL );
} )( key );
return data;
}
function _askPrice( data ) {
if ( typeof data != "object" ) {
alert( "data must be an object" );
return;
}
Ti.API.debug( "asking price: " + data.name + " -- " + data.price );
var product = new Product();
product.list( function () {
if ( 200 == this.status ) {
var response = eval( "(" + this.responseText + ")" );
var productData = response["products"][0];
Ti.API.debug( "asking price kactoos: " + data.name + " -- " + productData.precio_actual );
Ti.API.debug( productData );
if ( productData.precio_actual != data.price ) {
var notice = new Notice();
notice.update( {price: productData.precio_actual, users: productData.usuarios}, {"id = ?": data.id} );
notice.close();
var notification = Barrel.UI.notification( data.name + " cambio de precio!, $" + Barrel.Text.numberFormat( productData.precio_actual, 0, "", "." ) );
notification.show();
_loadNotices();
}
}
}, {idProduct: data.product_id, limit: 1} );
}
function _buildMenu() {
var menu = Titanium.UI.Android.OptionMenu.createMenu();
var refreshItem = Titanium.UI.Android.OptionMenu.createMenuItem( {
title : "actualizar",
icon: "/images/icons/01-refresh.png"
} );
refreshItem.addEventListener( "click", _refreshMenu );
menu.add( refreshItem );
Titanium.UI.Android.OptionMenu.setMenu( menu );
}
function _refreshMenu() {
var notice = new Notice();
var notices = notice.list();
notice.close();
var product = new Product();
Ti.API.debug( "notices length refresh: " + notices.length );
// can't get multiple products at once :\.
for ( var key = 0; key < notices.length; key++ ) ( function ( key ) {
clearInterval( listeners[key] ); // clear listener
product.list( function () {
if ( 200 == this.status ) {
var response = eval( "(" + this.responseText + ")" );
var productData = response["products"][0];
Ti.API.debug( "producy refresh data: " + notices[key].name + " -- " + notices[key].price );
var notice = new Notice();
// if this product is not active then don't draw it.
if ( 1 != parseInt( productData.activo ) ) {
notice.destroy( notices[key].id );
tableView.deleteRow( key, {animationStyle: Titanium.UI.iPhone.RowAnimationStyle.UP} );
var notification = Barrel.UI.notification( notices[key].name + " parece que ya no está activo :(" );
notification.show();
return;
}
if ( productData.precio_actual || productData.usuarios ) {
notice.update( {price: productData.precio_actual, users: productData.usuarios}, {"id = ?": notices[key].id} );
}
notice.close();
}
}, {idProduct: notices[key].product_id, limit: 1} );
} )( key );
// delay two secs to update the table, cause kactoos api doesn't have a method
// to get data for multiple products at once.
setTimeout( function () {
_loadNotices();
}, 2000 );
}
main(); | nebiros/barrel | Resources/app/windows/notices.js | JavaScript | apache-2.0 | 8,802 |
package network
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// ExpressRouteCircuitAuthorizationsClient is the network Client
type ExpressRouteCircuitAuthorizationsClient struct {
BaseClient
}
// NewExpressRouteCircuitAuthorizationsClient creates an instance of the ExpressRouteCircuitAuthorizationsClient
// client.
func NewExpressRouteCircuitAuthorizationsClient(subscriptionID string) ExpressRouteCircuitAuthorizationsClient {
return NewExpressRouteCircuitAuthorizationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewExpressRouteCircuitAuthorizationsClientWithBaseURI creates an instance of the
// ExpressRouteCircuitAuthorizationsClient client.
func NewExpressRouteCircuitAuthorizationsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitAuthorizationsClient {
return ExpressRouteCircuitAuthorizationsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate creates or updates an authorization in the specified express route circuit.
//
// resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit.
// authorizationName is the name of the authorization. authorizationParameters is parameters supplied to the create
// or update express route circuit authorization operation.
func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization) (result ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture, err error) {
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, authorizationName, authorizationParameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
result, err = client.CreateOrUpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization) (*http.Request, error) {
pathParameters := map[string]interface{}{
"authorizationName": autorest.Encode("path", authorizationName),
"circuitName": autorest.Encode("path", circuitName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters),
autorest.WithJSON(authorizationParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
return
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the specified authorization from the specified express route circuit.
//
// resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit.
// authorizationName is the name of the authorization.
func (client ExpressRouteCircuitAuthorizationsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorizationsDeleteFuture, err error) {
req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName, authorizationName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client ExpressRouteCircuitAuthorizationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"authorizationName": autorest.Encode("path", authorizationName),
"circuitName": autorest.Encode("path", circuitName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRouteCircuitAuthorizationsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitAuthorizationsDeleteFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client ExpressRouteCircuitAuthorizationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets the specified authorization from the specified express route circuit.
//
// resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit.
// authorizationName is the name of the authorization.
func (client ExpressRouteCircuitAuthorizationsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorization, err error) {
req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, authorizationName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client ExpressRouteCircuitAuthorizationsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"authorizationName": autorest.Encode("path", authorizationName),
"circuitName": autorest.Encode("path", circuitName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRouteCircuitAuthorizationsClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ExpressRouteCircuitAuthorizationsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List gets all authorizations in an express route circuit.
//
// resourceGroupName is the name of the resource group. circuitName is the name of the circuit.
func (client ExpressRouteCircuitAuthorizationsClient) List(ctx context.Context, resourceGroupName string, circuitName string) (result AuthorizationListResultPage, err error) {
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx, resourceGroupName, circuitName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.alr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure sending request")
return
}
result.alr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client ExpressRouteCircuitAuthorizationsClient) ListPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"circuitName": autorest.Encode("path", circuitName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRouteCircuitAuthorizationsClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client ExpressRouteCircuitAuthorizationsClient) ListResponder(resp *http.Response) (result AuthorizationListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client ExpressRouteCircuitAuthorizationsClient) listNextResults(lastResults AuthorizationListResult) (result AuthorizationListResult, err error) {
req, err := lastResults.authorizationListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client ExpressRouteCircuitAuthorizationsClient) ListComplete(ctx context.Context, resourceGroupName string, circuitName string) (result AuthorizationListResultIterator, err error) {
result.page, err = client.List(ctx, resourceGroupName, circuitName)
return
}
| marstr/azure-sdk-for-go | services/network/mgmt/2016-09-01/network/expressroutecircuitauthorizations.go | GO | apache-2.0 | 15,776 |
require 'spec_helper'
module Bosh::Director
describe DiffLines do
subject(:diff_lines) { described_class.new }
describe 'order' do
context 'when simple' do
before do
diff_lines << Line.new(0, 'jobs:', nil)
diff_lines << Line.new(0, 'variables:', nil)
diff_lines << Line.new(0, 'azs:', nil)
end
it 're-orders lines based on desired manifest keys order' do
expect(diff_lines.map(&:to_s)).to eq([
'jobs:',
'variables:',
'azs:',
])
diff_lines.order
expect(diff_lines.map(&:to_s)).to eq([
'azs:',
'',
'jobs:',
'',
'variables:'
])
end
end
context 'when indented' do
before do
diff_lines << Line.new(0, 'vm_extensions:', nil)
diff_lines << Line.new(0, '- name: pub-lbs', nil)
diff_lines << Line.new(1, 'cloud_properties:', nil)
diff_lines << Line.new(2, 'elbs: [main]', nil)
diff_lines << Line.new(0, 'variables:', nil)
diff_lines << Line.new(0, '- name: new-var', nil)
diff_lines << Line.new(1, 'type: password', nil)
diff_lines << Line.new(1, 'default: secret', nil)
diff_lines << Line.new(0, 'vm_types:', nil)
diff_lines << Line.new(0, ' - name: default', nil)
diff_lines << Line.new(1, 'cloud_properties: {instance_type: m1.small, availability_zone: us-east-1c}', nil)
diff_lines << Line.new(0, 'jobs:', nil)
diff_lines << Line.new(0, '- name: job1', nil)
diff_lines << Line.new(0, ' properties:', nil)
diff_lines << Line.new(2, 'foo: bar', nil)
diff_lines << Line.new(0, 'azs:', nil)
diff_lines << Line.new(0, '- name: z1', nil)
diff_lines << Line.new(1, 'cloud_properties:', nil)
diff_lines << Line.new(2, 'baz: qux', nil)
end
it 're-orders lines based on desired manifest keys order' do
expect(diff_lines.map(&:to_s)).to eq([
'vm_extensions:',
'- name: pub-lbs',
' cloud_properties:',
' elbs: [main]',
'variables:',
'- name: new-var',
' type: password',
' default: secret',
'vm_types:',
' - name: default',
' cloud_properties: {instance_type: m1.small, availability_zone: us-east-1c}',
'jobs:',
'- name: job1',
' properties:',
' foo: bar',
'azs:',
'- name: z1',
' cloud_properties:',
' baz: qux',
])
diff_lines.order
expect(diff_lines.map(&:to_s)).to eq([
'azs:',
'- name: z1',
' cloud_properties:',
' baz: qux',
'',
'vm_types:',
' - name: default',
' cloud_properties: {instance_type: m1.small, availability_zone: us-east-1c}',
'',
'vm_extensions:',
'- name: pub-lbs',
' cloud_properties:',
' elbs: [main]',
'',
'jobs:',
'- name: job1',
' properties:',
' foo: bar',
'',
'variables:',
'- name: new-var',
' type: password',
' default: secret',
])
end
end
context 'when extra sections defined' do
before do
diff_lines << Line.new(0, 'foo:', nil)
diff_lines << Line.new(0, ' bar: baz', nil)
diff_lines << Line.new(0, 'jobs:', nil)
diff_lines << Line.new(0, 'azs:', nil)
end
it 're-orders lines based on desired manifest keys order' do
expect(diff_lines.map(&:to_s)).to eq([
'foo:',
' bar: baz',
'jobs:',
'azs:',
])
diff_lines.order
expect(diff_lines.map(&:to_s)).to eq([
'azs:',
'',
'jobs:',
'',
'foo:',
' bar: baz',
])
end
end
end
end
end
| barthy1/bosh | src/bosh-director/spec/unit/manifest/diff_lines_spec.rb | Ruby | apache-2.0 | 4,263 |
/*
* Copyright 2015 the original author or authors.
* @https://github.com/scouter-project/scouter
*
* 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 scouter.client.xlog.views;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import scouter.client.Images;
import scouter.client.model.TextProxy;
import scouter.client.model.XLogData;
import scouter.client.popup.XLogYValueMaxDialog;
import scouter.client.preferences.PManager;
import scouter.client.preferences.PreferenceConstants;
import scouter.client.threads.ObjectSelectManager;
import scouter.client.util.ChartUtil;
import scouter.client.util.ColorUtil;
import scouter.client.util.TimeUtil;
import scouter.client.xlog.ImageCache;
import scouter.client.xlog.XLogFilterStatus;
import scouter.client.xlog.XLogYAxisEnum;
import scouter.lang.pack.XLogPack;
import scouter.util.DateUtil;
import scouter.util.FormatUtil;
import scouter.util.HashUtil;
import scouter.util.IPUtil;
import scouter.util.LongKeyLinkedMap;
import scouter.util.Pair;
import scouter.util.StrMatch;
import scouter.util.StringUtil;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Enumeration;
public class XLogViewPainter {
public static Color color_black = new Color(null, 0, 0, 0);
public static Color color_white = new Color(null, 255, 255, 255);
public static Color color_grid_narrow = new Color(null, 220, 228, 255);
public static Color color_grid_wide = new Color(null, 200, 208, 255);
public static Color color_blue = new Color(null, 0, 0, 255);
public static Color color_red = new Color(null, 255, 0, 0);
public static Color ignore_area = new Color(null, 234, 234, 234);
public long xTimeRange = DateUtil.MILLIS_PER_MINUTE * 5;
public long originalRange = xTimeRange;
private double yValueMax;
private double yValueMin = 0;
private boolean viewIsInAdditionalDataLoading = false;
public long lastDrawTimeStart = 0L;
public long lastDrawTimeEnd = 0L;
private XLogViewMouse mouse;
private PointMap pointMap = new PointMap();
private final LongKeyLinkedMap<XLogData> xLogPerfData;
private ImageCache dotImage = ImageCache.getInstance();
public int selectedUrlHash = 0;
XLogFilterStatus filterStatus;
public XLogYAxisEnum yAxisMode = XLogYAxisEnum.ELAPSED;
private int filter_hash = 0;
public StrMatch objNameMat;
public StrMatch serviceMat;
public StrMatch ipMat;
public Pair<Long, Long> startFromToMat;
public Pair<Integer, Integer> resFromToMat;
public StrMatch loginMat;
public StrMatch descMat;
public StrMatch text1Mat;
public StrMatch text2Mat;
public StrMatch text3Mat;
public StrMatch text4Mat;
public StrMatch text5Mat;
public StrMatch userAgentMat;
public String profileSizeExpr;
public String profileByteExpr;
public String txtHasDump;
public String yyyymmdd;
ITimeChange callback;
int serverId;
public XLogViewPainter(LongKeyLinkedMap<XLogData> xLogPerfData, XLogViewMouse mouse, ITimeChange callback) {
this.mouse = mouse;
this.xLogPerfData = xLogPerfData;
this.callback = callback;
}
private long endTime;
public void setEndTime(long etime) {
this.endTime = etime;
if (this.endTime <= 0)
this.endTime = 0;
}
public void setTimeRange(long range) {
// if (range < DateUtil.MILLIS_PER_MINUTE) {
// range = DateUtil.MILLIS_PER_MINUTE;
// }
this.originalRange = this.xTimeRange = range;
}
public void setViewIsInAdditionalDataLoading(boolean b) {
this.viewIsInAdditionalDataLoading = b;
}
public long getTimeRange() {
return this.xTimeRange;
}
public void setValueRange(double minValue, double maxValue) {
this.yValueMin = minValue;
this.yValueMax = maxValue;
}
public void dispose() {
if (this.ibuffer != null)
this.ibuffer.dispose();
}
public void set(Rectangle area) {
this.area = area;
}
private Rectangle area;
private Image ibuffer;
boolean onGoing = false;
private Object lock = new Object();
public void build() {
if (area == null)
return;
synchronized (lock) {
if(onGoing)
return;
onGoing = true;
}
int work_w = area.width < 200 ? 200 : area.width;
int work_h = area.height < 200 ? 200 : area.height;
Image img = new Image(null, work_w, work_h);
GC gc = new GC(img);
draw(gc, work_w, work_h);
gc.dispose();
Image old = ibuffer;
ibuffer = img;
if (old != null) {
old.dispose();
}
synchronized (lock) {
onGoing = false;
}
}
int chart_x;
long paintedEndTime;
public long getLastTime() {
return paintedEndTime;
}
private void draw(GC gc, int work_w, int work_h) {
if (area == null)
return;
String maxLabel = FormatUtil.print(new Double(yValueMax), "#,##0.00");
chart_x = maxLabel.length() * 6 + 30;
int chart_y = 30;
int chart_w = work_w - chart_x - 30;
int chart_h = work_h - chart_y - 30;
pointMap.reset(chart_w, chart_h);
long time_end = ((this.endTime > 0) ? this.endTime : TimeUtil.getCurrentTime(serverId)) + moveWidth;
long time_start = time_end - xTimeRange;
if (zoomMode) {
time_end = zoomEndtime + moveWidth;
time_start = time_end - xTimeRange;
}
paintedEndTime = time_end;
gc.setForeground(color_black);
if (filter_hash != new XLogFilterStatus().hashCode()) {
gc.setBackground(ColorUtil.getInstance().getColor("azure"));
} else {
gc.setBackground(color_white);
}
gc.fillRectangle(0, 0, work_w, work_h);
if (yAxisMode == XLogYAxisEnum.ELAPSED) {
int ignoreMs = PManager.getInstance().getInt(PreferenceConstants.P_XLOG_IGNORE_TIME);
if (yValueMin == 0 && ignoreMs > 0) {
gc.setBackground(ignore_area);
int chart_igreno_h = (int) ((ignoreMs / (yValueMax * 1000)) * chart_h);
if (chart_igreno_h > chart_h) {
chart_igreno_h = chart_h;
}
gc.fillRoundRectangle(chart_x, 30 + chart_h - chart_igreno_h, chart_w + 5, chart_igreno_h + 5, 1, 1);
gc.setBackground(color_white);
}
}
gc.setLineWidth(1);
gc.setLineStyle(SWT.LINE_DOT);
double valueRange = yValueMax - yValueMin;
double yUnit = ChartUtil.getYaxisUnit(valueRange, chart_h);
for (double yValue = 0; yValue <= valueRange; yValue += yUnit) {
int y = (int) (chart_y + chart_h - chart_h * yValue / valueRange);
gc.setForeground(color_grid_narrow);
gc.drawLine(chart_x, y, (int) (chart_x + chart_w), y);
String s = FormatUtil.print(new Double(yValue + yValueMin), "#,##0.00");
gc.setForeground(color_black);
gc.drawString(s, chart_x - (15 + s.length() * 6), y - 5);
}
double xUnit = ChartUtil.getSplitTimeUnit(xTimeRange, chart_w);
String xLabelFormat = ChartUtil.getTimeFormat((long) xUnit);
long spareTime = time_end % (long) xUnit;
int labelOnNum = (int) (time_end % (xUnit * 5) / xUnit);
int xi = 0;
for (double timeDelta = xTimeRange - spareTime; timeDelta > 0; timeDelta -= xUnit) {
boolean labelOn = (xi++ % 5 == labelOnNum);
if (labelOn) {
gc.setForeground(color_grid_wide);
gc.setLineStyle(SWT.LINE_SOLID);
} else {
gc.setForeground(color_grid_narrow);
gc.setLineStyle(SWT.LINE_DOT);
}
int x = (int) (chart_x + (chart_w * timeDelta / xTimeRange));
gc.drawLine(x, chart_y, x, chart_y + chart_h);
if (labelOn) {
gc.setForeground(color_black);
String s = FormatUtil.print(new Date(time_start + (long) timeDelta), xLabelFormat);
gc.drawString(s, x - 25, chart_y + chart_h + 5 + 5);
}
}
lastDrawTimeStart = time_start;
lastDrawTimeEnd = time_end;
drawXPerfData(gc, time_start, time_end, chart_x, chart_y, chart_w, chart_h);
drawChartBorder(gc, chart_x, chart_y, chart_w, chart_h);
drawYaxisDescription(gc, chart_x, chart_y);
drawTxCount(gc, chart_x, chart_w, chart_y);
if (zoomMode) {
drawZoomMode(gc, chart_x, chart_y, chart_w, time_start, time_end);
drawZoomOut(gc, chart_x, chart_y, chart_w, chart_h);
} else {
if (moveWidth != 0 || originalRange != xTimeRange) {
drawCircle(gc, chart_x, chart_y, chart_w, chart_h);
}
}
}
private void drawZoomMode(GC gc, int chart_x, int chart_y, int chart_w, long stime, long etime) {
String cntText = "Zoom Mode(" + DateUtil.format(stime, "HH:mm") + "~" + DateUtil.format(etime, "HH:mm") + ")";
gc.drawText(cntText, chart_x + chart_w - 140, chart_y - 20);
}
private void drawTxCount(GC gc, int chart_x, int chart_w, int chart_y) {
gc.setFont(null);
String cntText = " Count : " + FormatUtil.print(new Long(count), "#,##0");
int strLen = gc.stringExtent(cntText).x;
gc.drawText(cntText, chart_x + chart_w - strLen - 10, chart_y - 20);
}
private void drawYaxisDescription(GC gc, int chart_x, int chart_y) {
gc.setFont(null);
String desc = " " + yAxisMode.getDesc();
gc.drawText(desc, chart_x, chart_y - 20);
}
private void drawChartBorder(GC gc, int chart_sx, int chart_sy, int chart_w, int chart_h) {
// gc.setLineStyle(SWT.LINE_SOLID);
// gc.setLineWidth(5);
// gc.setForeground(color_red);
// gc.drawRoundRectangle(chart_sx - 2, chart_sy - 2, chart_w + 4, chart_h + 4, 1, 1);
gc.setLineStyle(SWT.LINE_SOLID);
gc.setLineWidth(1);
gc.setForeground(color_black);
gc.drawRoundRectangle(chart_sx, chart_sy, chart_w + 5, chart_h + 5, 1, 1);
}
public void drawImageBuffer(GC gc) {
if (ibuffer != null)
gc.drawImage(ibuffer, 0, 0);
}
public void drawSelectArea(GC gc) {
if (mouse.x1 >= 0 && mouse.y1 >= 0) {
if (mouse.x2 + mouse.y2 > 0) {
Color color = null;
switch (mouse.mode) {
case LIST_XLOG:
color = XLogViewPainter.color_blue;
break;
case ZOOM_AREA:
color = XLogViewPainter.color_red;
break;
default:
break;
}
if (color != null) {
gc.setBackground(color);
gc.setAlpha(15);
gc.setLineStyle(SWT.LINE_SOLID);
gc.fillRectangle(mouse.x1, mouse.y1, mouse.x2 - mouse.x1, mouse.y2 - mouse.y1);
gc.setAlpha(150);
gc.setLineWidth(1);
gc.setForeground(color);
gc.drawRectangle(mouse.x1, mouse.y1, mouse.x2 - mouse.x1, mouse.y2 - mouse.y1);
}
}
}
}
int mouseX;
int mouseY;
public void drawCircle(GC gc, int chart_x, int chart_y, int chart_w, int chart_h){
mouseX = chart_x + chart_w+ 5;
mouseY = (chart_h / 2) + chart_y - 16 ;
gc.drawImage(Images.circle, mouseX, mouseY);
}
public void drawZoomOut(GC gc, int chart_x, int chart_y, int chart_w, int chart_h){
mouseX = chart_x + chart_w+ 10;
mouseY = (chart_h / 2) + chart_y - 16 ;
gc.drawImage(Images.zoomout, mouseX, mouseY);
}
public boolean onMouseDoubleClick(int x, int y) {
boolean isChange = false;
if (x < chart_x) {
Display display = Display.getCurrent();
if (display == null) {
display = Display.getDefault();
}
XLogYValueMaxDialog dialog = new XLogYValueMaxDialog(display, this);
dialog.show();
isChange = true;
}
return isChange;
}
private void initializeChart() {
moveWidth = 0;
xTimeRange = originalRange;
load();
zoomMode = false;
build();
}
public boolean onMouseClick(int x, int y) {
boolean isChange = false;
if (moveWidth != 0 || xTimeRange != originalRange) {
if (x > mouseX && x < mouseX + 32
&& y > mouseY && y < mouseY + 32) {
initializeChart();
isChange = true;
}
}
return isChange;
}
private void removeOutsidePerfData(long time_start, long time_end) {
if (zoomMode) {
return;
}
while (xLogPerfData.size() > 0 && xLogPerfData.getFirstValue().p.endTime < time_start) {
xLogPerfData.removeFirst();
}
if (this.endTime > 0) {
while (xLogPerfData.size() > 0 && xLogPerfData.getLastValue().p.endTime > time_end) {
xLogPerfData.removeLast();
}
}
}
ObjectSelectManager objSelMgr = ObjectSelectManager.getInstance();
int count;
private void drawXPerfData(GC gc, long time_start, long time_end, int chart_x,
int chart_y, int chart_w, int chart_h) {
count = 0;
if (xLogPerfData.size() == 0) {
return;
}
if (viewIsInAdditionalDataLoading == false) {
removeOutsidePerfData(time_start - (DateUtil.MILLIS_PER_SECOND * 10), time_end);
}
Enumeration<XLogData> en = xLogPerfData.values();
while (en.hasMoreElements()) {
XLogData d = en.nextElement();
if (d == null || d.p.endTime < time_start || d.p.endTime > time_end) {
continue;
}
if (d.filter_hash != filter_hash) {
if (isFilterOk(d)) {
d.filter_ok = true;
} else {
d.filter_ok = false;
}
d.filter_hash = filter_hash;
}
if (d.filter_ok) {
if (objSelMgr.isUnselectedObject(d.p.objHash)) {
d.x = d.y = -1;
continue;
}
int x = (int) (chart_w * (d.p.endTime - time_start) / xTimeRange);
d.x = chart_x + x;
int y = 0;
double value = 0;
switch(yAxisMode) {
case ELAPSED:
if ((double) d.p.elapsed / 1000 >= yValueMax) {
value = -1;
} else {
value = (double) d.p.elapsed / 1000;
}
break;
case CPU:
if (d.p.cpu >= yValueMax) {
value = -1;
} else {
value = (double) d.p.cpu;
}
break;
case SQL_TIME:
if ((double) d.p.sqlTime / 1000 >= yValueMax) {
value = -1;
} else {
value = (double) d.p.sqlTime / 1000;
}
break;
case SQL_COUNT:
if ((double) d.p.sqlCount >= yValueMax) {
value = -1;
} else {
value = (double) d.p.sqlCount;
}
break;
case APICALL_TIME:
if ((double) d.p.apicallTime / 1000 >= yValueMax) {
value = -1;
} else {
value = (double) d.p.apicallTime / 1000;
}
break;
case APICALL_COUNT:
if ((double) d.p.apicallCount >= yValueMax) {
value = -1;
} else {
value = (double) d.p.apicallCount;
}
break;
case HEAP_USED:
if (d.p.kbytes >= yValueMax) {
value = -1;
} else {
value = d.p.kbytes;
}
break;
default:
if ((double) d.p.elapsed / 1000 >= yValueMax) {
value = -1;
} else {
value = (double) d.p.elapsed / 1000;
}
break;
}
if (value < 0) {
y = chart_h - 1;
} else {
y = (int) (chart_h * (value - yValueMin) / (yValueMax - yValueMin));
}
d.y = chart_h + chart_y - y;
if (pointMap.check(x, y)) {
try {
if (d.p.error != 0) {
// gc.setForeground(ColorUtil.getInstance().getColor("red"));
// gc.drawString(MARK, d.x, d.y, true);
gc.drawImage(dotImage.getXPErrorImage(d.p.xType), d.x, d.y);
} else {
// gc.setForeground(AgentColorManager.getInstance().getColor(d.p.objHash));
// gc.drawString(MARK, d.x, d.y, true);
gc.drawImage(dotImage.getXPImage(d.p.objHash, d.p.xType), d.x, d.y);
}
} catch (Throwable t) {
}
}
count++;
}
}
}
public double getYValue() {
return yValueMax;
}
public void setYValueMaxValue(double max) {
yValueMax = max;
build();
mouse.setNewYValue();
}
public int moveWidth = 0;
public void keyPressed(int keyCode) {
switch (keyCode) {
case 16777217:// UP Key
yValueMax += yValueMax >= 2 ? 1 : 0.1;
break;
case 16777218: // DOWN Key
yValueMax -= yValueMax >= 2 ? 1 : (yValueMax < 0.5 ? 0.05 : 0.1);
if (yValueMax < 0.05)
yValueMax = 0.05;
break;
case 16777261:
case 45: // -
xTimeRange += DateUtil.MILLIS_PER_MINUTE;
load();
break;
case 16777259:
case 61: // +
xTimeRange -= DateUtil.MILLIS_PER_MINUTE;
if (xTimeRange < DateUtil.MILLIS_PER_MINUTE)
xTimeRange = DateUtil.MILLIS_PER_MINUTE;
break;
case 16777219: // left arrow
moveWidth -= DateUtil.MILLIS_PER_SECOND * 10;
load();
break;
case 16777220: // right arrow
moveWidth += DateUtil.MILLIS_PER_SECOND * 10;
load();
break;
}
}
private boolean zoomMode = false;
private long zoomEndtime;
public boolean zoomIn(long stime, long etime) {
if (this.endTime < etime
|| this.endTime - xTimeRange > stime
|| etime < stime) {
MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Warning", "MaxRange is between " + DateUtil.format(this.endTime - xTimeRange, "HH:mm") + " and " + DateUtil.format(this.endTime, "HH:mm"));
return false;
}
zoomEndtime = etime;
xTimeRange = etime - stime;
moveWidth = 0;
zoomMode = true;
build();
return true;
}
public void endZoom() {
initializeChart();
}
public boolean isZoomMode() {
return zoomMode;
}
public void setServerId(int serverId) {
this.serverId = serverId;
}
private void load() {
if (zoomMode) {
return;
}
long time_current = TimeUtil.getCurrentTime(serverId);
long time_end = (this.endTime > 0 ? this.endTime : time_current) + moveWidth ;
long time_start = time_end - xTimeRange;
if (time_end > time_current) {
moveWidth -= DateUtil.MILLIS_PER_SECOND * 10;
return;
}
callback.timeRangeChanged(time_start, time_end);
}
public boolean isFilterOk(XLogData d) {
return isObjNameFilterOk(d)
&& isServiceFilterOk(d)
&& isIpFilterOk(d.p)
&& isStartTimeFilterOk(d.p)
&& isResponseTimeFilterOk(d.p)
&& isLoginFilterOk(d)
&& isDescFilterOk(d)
&& isDumpYnOk(d)
&& isText1FilterOk(d)
&& isText2FilterOk(d)
&& isText3FilterOk(d)
&& isText4FilterOk(d)
&& isText5FilterOk(d)
&& isUserAgentFilterOk(d)
&& isErrorFilterOk(d.p)
&& isApicallFilterOk(d.p)
&& isSqlFilterOk(d.p)
&& isSyncOk(d.p)
&& isAsyncOk(d.p)
&& isProfileSizeFilterOk(d.p)
&& isProfileByteFilterOk(d.p)
;
}
public boolean isObjNameFilterOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.objName)) {
return true;
}
if (objNameMat.getComp() == StrMatch.COMP.EQU) {
return d.p.objHash == HashUtil.hash(objNameMat.getPattern());
} else {
String objName = TextProxy.object.getLoadText(yyyymmdd, d.p.objHash, d.serverId);
return objNameMat.include(objName);
}
}
public boolean isServiceFilterOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.service)) {
return true;
}
if (serviceMat.getComp() == StrMatch.COMP.EQU) {
return d.p.service == HashUtil.hash(serviceMat.getPattern());
} else {
String serviceName = TextProxy.service.getLoadText(yyyymmdd, d.p.service, d.serverId);
return serviceMat.include(serviceName);
}
}
public boolean isIpFilterOk(XLogPack p) {
if (StringUtil.isEmpty(filterStatus.ip)) {
return true;
}
String value = IPUtil.toString(p.ipaddr);
return ipMat.include(value);
}
public boolean isStartTimeFilterOk(XLogPack p) {
if (StringUtil.isEmpty(filterStatus.startHmsFrom) || StringUtil.isEmpty(filterStatus.startHmsTo)) {
return true;
}
long start = p.endTime - p.elapsed;
return startFromToMat.getLeft() <= start && start <= startFromToMat.getRight();
}
public boolean isResponseTimeFilterOk(XLogPack p) {
if (StringUtil.isEmpty(filterStatus.responseTimeFrom) || StringUtil.isEmpty(filterStatus.responseTimeTo)) {
return true;
}
return resFromToMat.getLeft() <= p.elapsed && p.elapsed <= resFromToMat.getRight();
}
public boolean isLoginFilterOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.login)) {
return true;
}
if (loginMat.getComp() == StrMatch.COMP.EQU) {
return d.p.login == HashUtil.hash(loginMat.getPattern());
} else {
String login = TextProxy.login.getLoadText(yyyymmdd, d.p.login, d.serverId);
return loginMat.include(login);
}
}
public boolean isDescFilterOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.desc)) {
return true;
}
if (descMat.getComp() == StrMatch.COMP.EQU) {
return d.p.desc == HashUtil.hash(descMat.getPattern());
} else {
String desc = TextProxy.desc.getLoadText(yyyymmdd, d.p.desc, d.serverId);
return descMat.include(desc);
}
}
public boolean isDumpYnOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.hasDumpYn)) {
return true;
}
if (filterStatus.hasDumpYn.equals("Y")) {
return d.p.hasDump == 1;
} else {
return d.p.hasDump == 0;
}
}
public boolean isText1FilterOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.text1)) {
return true;
}
return text1Mat.include(d.p.text1);
}
public boolean isText2FilterOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.text2)) {
return true;
}
return text2Mat.include(d.p.text2);
}
public boolean isText3FilterOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.text3)) {
return true;
}
return text3Mat.include(d.p.text3);
}
public boolean isText4FilterOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.text4)) {
return true;
}
return text4Mat.include(d.p.text4);
}
public boolean isText5FilterOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.text5)) {
return true;
}
return text5Mat.include(d.p.text5);
}
public boolean isUserAgentFilterOk(XLogData d) {
if (StringUtil.isEmpty(filterStatus.userAgent)) {
return true;
}
if (userAgentMat.getComp() == StrMatch.COMP.EQU) {
return d.p.userAgent == HashUtil.hash(userAgentMat.getPattern());
} else {
String userAgent = TextProxy.userAgent.getLoadText(yyyymmdd, d.p.userAgent, d.serverId);
return userAgentMat.include(userAgent);
}
}
public boolean isProfileSizeFilterOk(XLogPack p) {
if (StringUtil.isEmpty(filterStatus.profileSizeText)) {
return true;
}
String exp = filterStatus.profileSizeText.trim();
char sign0 = exp.charAt(0);
char sign1 = exp.length() >= 2 ? exp.charAt(1) : '\0';
try {
if (sign0 == '>') {
if(sign1 == '=') {
return p.profileCount >= Integer.parseInt(exp.substring(2));
} else {
return p.profileCount > Integer.parseInt(exp.substring(1));
}
} else if (sign0 == '<') {
if(sign1 == '=') {
return p.profileCount <= Integer.parseInt(exp.substring(2));
} else {
return p.profileCount < Integer.parseInt(exp.substring(1));
}
} else if (sign0 == '=') {
if(sign1 == '=') {
return p.profileCount == Integer.parseInt(exp.substring(2));
} else {
return p.profileCount == Integer.parseInt(exp.substring(1));
}
} else {
return p.profileCount == Integer.parseInt(exp);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return true;
}
public boolean isProfileByteFilterOk(XLogPack p) {
if (StringUtil.isEmpty(filterStatus.profileBytesText)) {
return true;
}
String exp = filterStatus.profileBytesText.trim();
char sign0 = exp.charAt(0);
char sign1 = exp.length() >= 2 ? exp.charAt(1) : '\0';
try {
if (sign0 == '>') {
if(sign1 == '=') {
return p.profileSize >= Integer.parseInt(exp.substring(2));
} else {
return p.profileSize > Integer.parseInt(exp.substring(1));
}
} else if (sign0 == '<') {
if(sign1 == '=') {
return p.profileSize <= Integer.parseInt(exp.substring(2));
} else {
return p.profileSize < Integer.parseInt(exp.substring(1));
}
} else if (sign0 == '=') {
if(sign1 == '=') {
return p.profileSize == Integer.parseInt(exp.substring(2));
} else {
return p.profileSize == Integer.parseInt(exp.substring(1));
}
} else {
return p.profileSize == Integer.parseInt(exp);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return true;
}
public boolean isErrorFilterOk(XLogPack p) {
if (filterStatus.onlyError) {
return p.error != 0;
}
return true;
}
public boolean isSqlFilterOk(XLogPack p) {
if (filterStatus.onlySql) {
return p.sqlCount > 0;
}
return true;
}
public boolean isSyncOk(XLogPack p) {
if (filterStatus.onlySync) {
return p.xType != 2 && p.xType != 3 && p.xType != 4;
}
return true;
}
public boolean isAsyncOk(XLogPack p) {
if (filterStatus.onlyAsync) {
return p.xType == 2 || p.xType == 3 || p.xType == 4;
}
return true;
}
public boolean isApicallFilterOk(XLogPack p) {
if (filterStatus.onlyApicall) {
return p.apicallCount > 0;
}
return true;
}
public interface ITimeChange {
public void timeRangeChanged(long stime, long etime);
}
public void setYAxisMode(XLogYAxisEnum yAxis) {
this.yAxisMode = yAxis;
this.yValueMax = yAxis.getDefaultMax();
this.yValueMin = 0;
}
private DateTimeFormatter hmsFormatter = DateTimeFormatter.ofPattern("HHmmss");
public void setFilterStatus(XLogFilterStatus status) {
this.filterStatus = status;
filter_hash = filterStatus.hashCode();
objNameMat = new StrMatch(status.objName);
serviceMat = new StrMatch(status.service);
ipMat = new StrMatch(status.ip);
loginMat = new StrMatch(status.login);
text1Mat = new StrMatch(status.text1);
text2Mat = new StrMatch(status.text2);
text3Mat = new StrMatch(status.text3);
text4Mat = new StrMatch(status.text4);
text5Mat = new StrMatch(status.text5);
descMat = new StrMatch(status.desc);
userAgentMat = new StrMatch(status.userAgent);
txtHasDump = status.hasDumpYn;
profileSizeExpr = status.profileSizeText;
profileByteExpr = status.profileBytesText;
if (status.startHmsFrom.length() >= 1 && status.startHmsTo.length() >= 1) {
try {
resFromToMat = new Pair<>(Integer.parseInt(status.responseTimeFrom), Integer.parseInt(status.responseTimeTo));
} catch (NumberFormatException ignored) {
}
}
if (status.startHmsFrom.length() == 6 && status.startHmsTo.length() == 6) {
long dateMillis = DateUtil.dateUnitToTimeMillis(DateUtil.getDateUnit(paintedEndTime));
long startFrom = dateMillis + LocalTime.parse(status.startHmsFrom, hmsFormatter).toSecondOfDay() * 1000;
long startTo = dateMillis + LocalTime.parse(status.startHmsTo, hmsFormatter).toSecondOfDay() * 1000;
startFromToMat = new Pair<>(startFrom, startTo);
} else {
startFromToMat = new Pair<>(0L, 0L);
}
}
}
| scouter-project/scouter | scouter.client/src/scouter/client/xlog/views/XLogViewPainter.java | Java | apache-2.0 | 26,327 |
<!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_91) on Mon Jun 06 14:51:22 EDT 2016 -->
<title>Uses of Class org.apache.cassandra.serializers.UUIDSerializer (apache-cassandra API)</title>
<meta name="date" content="2016-06-06">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.cassandra.serializers.UUIDSerializer (apache-cassandra API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/serializers/UUIDSerializer.html" title="class in org.apache.cassandra.serializers">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/serializers/class-use/UUIDSerializer.html" target="_top">Frames</a></li>
<li><a href="UUIDSerializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.cassandra.serializers.UUIDSerializer" class="title">Uses of Class<br>org.apache.cassandra.serializers.UUIDSerializer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/cassandra/serializers/UUIDSerializer.html" title="class in org.apache.cassandra.serializers">UUIDSerializer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.cassandra.serializers">org.apache.cassandra.serializers</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.cassandra.serializers">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/apache/cassandra/serializers/UUIDSerializer.html" title="class in org.apache.cassandra.serializers">UUIDSerializer</a> in <a href="../../../../../org/apache/cassandra/serializers/package-summary.html">org.apache.cassandra.serializers</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../org/apache/cassandra/serializers/UUIDSerializer.html" title="class in org.apache.cassandra.serializers">UUIDSerializer</a> in <a href="../../../../../org/apache/cassandra/serializers/package-summary.html">org.apache.cassandra.serializers</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/cassandra/serializers/TimeUUIDSerializer.html" title="class in org.apache.cassandra.serializers">TimeUUIDSerializer</a></span></code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../org/apache/cassandra/serializers/package-summary.html">org.apache.cassandra.serializers</a> declared as <a href="../../../../../org/apache/cassandra/serializers/UUIDSerializer.html" title="class in org.apache.cassandra.serializers">UUIDSerializer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/serializers/UUIDSerializer.html" title="class in org.apache.cassandra.serializers">UUIDSerializer</a></code></td>
<td class="colLast"><span class="typeNameLabel">UUIDSerializer.</span><code><span class="memberNameLink"><a href="../../../../../org/apache/cassandra/serializers/UUIDSerializer.html#instance">instance</a></span></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/serializers/UUIDSerializer.html" title="class in org.apache.cassandra.serializers">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/serializers/class-use/UUIDSerializer.html" target="_top">Frames</a></li>
<li><a href="UUIDSerializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 The Apache Software Foundation</small></p>
</body>
</html>
| jasonwee/videoOnCloud | lib/cassandra/apache-cassandra-3.7/javadoc/org/apache/cassandra/serializers/class-use/UUIDSerializer.html | HTML | apache-2.0 | 7,751 |
// 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
//
// 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.
// Code generated by cloud.google.com/go/internal/gapicgen/gensnippets. DO NOT EDIT.
// [START compute_v1_generated_NetworkEndpointGroups_DetachNetworkEndpoints_sync]
package main
import (
"context"
compute "cloud.google.com/go/compute/apiv1"
computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
)
func main() {
ctx := context.Background()
c, err := compute.NewNetworkEndpointGroupsRESTClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &computepb.DetachNetworkEndpointsNetworkEndpointGroupRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/compute/v1#DetachNetworkEndpointsNetworkEndpointGroupRequest.
}
op, err := c.DetachNetworkEndpoints(ctx, req)
if err != nil {
// TODO: Handle error.
}
err = op.Wait(ctx)
if err != nil {
// TODO: Handle error.
}
}
// [END compute_v1_generated_NetworkEndpointGroups_DetachNetworkEndpoints_sync]
| googleapis/google-cloud-go | internal/generated/snippets/compute/apiv1/NetworkEndpointGroupsClient/DetachNetworkEndpoints/main.go | GO | apache-2.0 | 1,561 |
#include "common/http/filter/lua/wrappers.h"
#include "test/test_common/lua_wrappers.h"
#include "test/test_common/utility.h"
using testing::InSequence;
namespace Envoy {
namespace Http {
namespace Filter {
namespace Lua {
class LuaHeaderMapWrapperTest : public Envoy::Lua::LuaWrappersTestBase<HeaderMapWrapper> {
public:
virtual void setup(const std::string& script) {
Envoy::Lua::LuaWrappersTestBase<HeaderMapWrapper>::setup(script);
state_->registerType<HeaderMapIterator>();
}
};
// Basic methods test for the header wrapper.
TEST_F(LuaHeaderMapWrapperTest, Methods) {
const std::string SCRIPT{R"EOF(
function callMe(object)
object:add("HELLO", "WORLD")
testPrint(object:get("hELLo"))
object:add("header1", "")
object:add("header2", "foo")
for key, value in pairs(object) do
testPrint(string.format("'%s' '%s'", key, value))
end
object:remove("header1")
for key, value in pairs(object) do
testPrint(string.format("'%s' '%s'", key, value))
end
end
)EOF"};
InSequence s;
setup(SCRIPT);
TestHeaderMapImpl headers;
HeaderMapWrapper::create(coroutine_->luaState(), headers, []() { return true; });
EXPECT_CALL(*this, testPrint("WORLD"));
EXPECT_CALL(*this, testPrint("'hello' 'WORLD'"));
EXPECT_CALL(*this, testPrint("'header1' ''"));
EXPECT_CALL(*this, testPrint("'header2' 'foo'"));
EXPECT_CALL(*this, testPrint("'hello' 'WORLD'"));
EXPECT_CALL(*this, testPrint("'header2' 'foo'"));
start("callMe");
}
// Test modifiable methods.
TEST_F(LuaHeaderMapWrapperTest, ModifiableMethods) {
const std::string SCRIPT{R"EOF(
function shouldBeOk(object)
object:get("hELLo")
for key, value in pairs(object) do
end
end
function shouldFailRemove(object)
object:remove("foo")
end
function shouldFailAdd(object)
object:add("foo")
end
function shouldFailReplace(object)
object:replace("foo")
end
)EOF"};
InSequence s;
setup(SCRIPT);
TestHeaderMapImpl headers;
HeaderMapWrapper::create(coroutine_->luaState(), headers, []() { return false; });
start("shouldBeOk");
setup(SCRIPT);
HeaderMapWrapper::create(coroutine_->luaState(), headers, []() { return false; });
EXPECT_THROW_WITH_MESSAGE(start("shouldFailRemove"), Envoy::Lua::LuaException,
"[string \"...\"]:9: header map can no longer be modified");
setup(SCRIPT);
HeaderMapWrapper::create(coroutine_->luaState(), headers, []() { return false; });
EXPECT_THROW_WITH_MESSAGE(start("shouldFailAdd"), Envoy::Lua::LuaException,
"[string \"...\"]:13: header map can no longer be modified");
setup(SCRIPT);
HeaderMapWrapper::create(coroutine_->luaState(), headers, []() { return false; });
EXPECT_THROW_WITH_MESSAGE(start("shouldFailReplace"), Envoy::Lua::LuaException,
"[string \"...\"]:17: header map can no longer be modified");
}
// Verify that replace works correctly with both inline and normal headers.
TEST_F(LuaHeaderMapWrapperTest, Replace) {
const std::string SCRIPT{R"EOF(
function callMe(object)
object:replace(":path", "/new_path")
object:replace("other_header", "other_header_value")
object:replace("new_header", "new_header_value")
end
)EOF"};
InSequence s;
setup(SCRIPT);
TestHeaderMapImpl headers{{":path", "/"}, {"other_header", "hello"}};
HeaderMapWrapper::create(coroutine_->luaState(), headers, []() { return true; });
start("callMe");
EXPECT_EQ((TestHeaderMapImpl{{":path", "/new_path"},
{"other_header", "other_header_value"},
{"new_header", "new_header_value"}}),
headers);
}
// Modify during iteration.
TEST_F(LuaHeaderMapWrapperTest, ModifyDuringIteration) {
const std::string SCRIPT{R"EOF(
function callMe(object)
for key, value in pairs(object) do
object:add("hello", "world")
end
end
)EOF"};
InSequence s;
setup(SCRIPT);
TestHeaderMapImpl headers{{"foo", "bar"}};
HeaderMapWrapper::create(coroutine_->luaState(), headers, []() { return true; });
EXPECT_THROW_WITH_MESSAGE(start("callMe"), Envoy::Lua::LuaException,
"[string \"...\"]:4: header map cannot be modified while iterating");
}
// Modify after iteration.
TEST_F(LuaHeaderMapWrapperTest, ModifyAfterIteration) {
const std::string SCRIPT{R"EOF(
function callMe(object)
for key, value in pairs(object) do
testPrint(string.format("'%s' '%s'", key, value))
end
object:add("hello", "world")
for key, value in pairs(object) do
testPrint(string.format("'%s' '%s'", key, value))
end
end
)EOF"};
InSequence s;
setup(SCRIPT);
TestHeaderMapImpl headers{{"foo", "bar"}};
HeaderMapWrapper::create(coroutine_->luaState(), headers, []() { return true; });
EXPECT_CALL(*this, testPrint("'foo' 'bar'"));
EXPECT_CALL(*this, testPrint("'foo' 'bar'"));
EXPECT_CALL(*this, testPrint("'hello' 'world'"));
start("callMe");
}
// Don't finish iteration.
TEST_F(LuaHeaderMapWrapperTest, DontFinishIteration) {
const std::string SCRIPT{R"EOF(
function callMe(object)
iterator = pairs(object)
key, value = iterator()
iterator2 = pairs(object)
end
)EOF"};
InSequence s;
setup(SCRIPT);
TestHeaderMapImpl headers{{"foo", "bar"}, {"hello", "world"}};
HeaderMapWrapper::create(coroutine_->luaState(), headers, []() { return true; });
EXPECT_THROW_WITH_MESSAGE(
start("callMe"), Envoy::Lua::LuaException,
"[string \"...\"]:5: cannot create a second iterator before completing the first");
}
// Use iterator across yield.
TEST_F(LuaHeaderMapWrapperTest, IteratorAcrossYield) {
const std::string SCRIPT{R"EOF(
function callMe(object)
iterator = pairs(object)
coroutine.yield()
iterator()
end
)EOF"};
InSequence s;
setup(SCRIPT);
TestHeaderMapImpl headers{{"foo", "bar"}, {"hello", "world"}};
Envoy::Lua::LuaDeathRef<HeaderMapWrapper> wrapper(
HeaderMapWrapper::create(coroutine_->luaState(), headers, []() { return true; }), true);
yield_callback_ = [] {};
start("callMe");
wrapper.reset();
EXPECT_THROW_WITH_MESSAGE(coroutine_->resume(0, [] {}), Envoy::Lua::LuaException,
"[string \"...\"]:5: object used outside of proper scope");
}
} // namespace Lua
} // namespace Filter
} // namespace Http
} // namespace Envoy
| craffert0/envoy | test/common/http/filter/lua/wrappers_test.cc | C++ | apache-2.0 | 6,529 |
package org.jboss.resteasy.test.injection;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.test.injection.resource.ProviderInjectionProviderReader;
import org.junit.Assert;
import org.junit.Test;
/**
* @tpSubChapter Injection tests
* @tpChapter Unit tests
* @tpTestCaseDetails Test for correct injection in registered custom provider.
* @tpSince RESTEasy 3.0.16
*/
public class ProviderInjectionTest {
private static final String ERROR_MSG = String.format("%s provider was not successfully registered.",
ProviderInjectionProviderReader.class.getSimpleName());
/**
* @tpTestDetails Test for injected HttpHeaders and Providers
* @tpSince RESTEasy 3.0.16
*/
@Test
public void testCacheControl() {
ProviderInjectionProviderReader reader = new ProviderInjectionProviderReader();
ResteasyProviderFactory.getInstance().registerProviderInstance(reader);
Assert.assertNotNull(ERROR_MSG, reader.headers);
Assert.assertNotNull(ERROR_MSG, reader.workers);
}
} | awhitford/Resteasy | testsuite/unit-tests/src/test/java/org/jboss/resteasy/test/injection/ProviderInjectionTest.java | Java | apache-2.0 | 1,069 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.