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
|
|---|---|---|---|---|---|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/elasticache/ElastiCache_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/elasticache/model/AvailabilityZone.h>
#include <aws/elasticache/model/SubnetOutpost.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace ElastiCache
{
namespace Model
{
/**
* <p>Represents the subnet associated with a cluster. This parameter refers to
* subnets defined in Amazon Virtual Private Cloud (Amazon VPC) and used with
* ElastiCache.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/Subnet">AWS
* API Reference</a></p>
*/
class AWS_ELASTICACHE_API Subnet
{
public:
Subnet();
Subnet(const Aws::Utils::Xml::XmlNode& xmlNode);
Subnet& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
void OutputToStream(Aws::OStream& oStream, const char* location) const;
/**
* <p>The unique identifier for the subnet.</p>
*/
inline const Aws::String& GetSubnetIdentifier() const{ return m_subnetIdentifier; }
/**
* <p>The unique identifier for the subnet.</p>
*/
inline bool SubnetIdentifierHasBeenSet() const { return m_subnetIdentifierHasBeenSet; }
/**
* <p>The unique identifier for the subnet.</p>
*/
inline void SetSubnetIdentifier(const Aws::String& value) { m_subnetIdentifierHasBeenSet = true; m_subnetIdentifier = value; }
/**
* <p>The unique identifier for the subnet.</p>
*/
inline void SetSubnetIdentifier(Aws::String&& value) { m_subnetIdentifierHasBeenSet = true; m_subnetIdentifier = std::move(value); }
/**
* <p>The unique identifier for the subnet.</p>
*/
inline void SetSubnetIdentifier(const char* value) { m_subnetIdentifierHasBeenSet = true; m_subnetIdentifier.assign(value); }
/**
* <p>The unique identifier for the subnet.</p>
*/
inline Subnet& WithSubnetIdentifier(const Aws::String& value) { SetSubnetIdentifier(value); return *this;}
/**
* <p>The unique identifier for the subnet.</p>
*/
inline Subnet& WithSubnetIdentifier(Aws::String&& value) { SetSubnetIdentifier(std::move(value)); return *this;}
/**
* <p>The unique identifier for the subnet.</p>
*/
inline Subnet& WithSubnetIdentifier(const char* value) { SetSubnetIdentifier(value); return *this;}
/**
* <p>The Availability Zone associated with the subnet.</p>
*/
inline const AvailabilityZone& GetSubnetAvailabilityZone() const{ return m_subnetAvailabilityZone; }
/**
* <p>The Availability Zone associated with the subnet.</p>
*/
inline bool SubnetAvailabilityZoneHasBeenSet() const { return m_subnetAvailabilityZoneHasBeenSet; }
/**
* <p>The Availability Zone associated with the subnet.</p>
*/
inline void SetSubnetAvailabilityZone(const AvailabilityZone& value) { m_subnetAvailabilityZoneHasBeenSet = true; m_subnetAvailabilityZone = value; }
/**
* <p>The Availability Zone associated with the subnet.</p>
*/
inline void SetSubnetAvailabilityZone(AvailabilityZone&& value) { m_subnetAvailabilityZoneHasBeenSet = true; m_subnetAvailabilityZone = std::move(value); }
/**
* <p>The Availability Zone associated with the subnet.</p>
*/
inline Subnet& WithSubnetAvailabilityZone(const AvailabilityZone& value) { SetSubnetAvailabilityZone(value); return *this;}
/**
* <p>The Availability Zone associated with the subnet.</p>
*/
inline Subnet& WithSubnetAvailabilityZone(AvailabilityZone&& value) { SetSubnetAvailabilityZone(std::move(value)); return *this;}
/**
* <p>The outpost ARN of the subnet.</p>
*/
inline const SubnetOutpost& GetSubnetOutpost() const{ return m_subnetOutpost; }
/**
* <p>The outpost ARN of the subnet.</p>
*/
inline bool SubnetOutpostHasBeenSet() const { return m_subnetOutpostHasBeenSet; }
/**
* <p>The outpost ARN of the subnet.</p>
*/
inline void SetSubnetOutpost(const SubnetOutpost& value) { m_subnetOutpostHasBeenSet = true; m_subnetOutpost = value; }
/**
* <p>The outpost ARN of the subnet.</p>
*/
inline void SetSubnetOutpost(SubnetOutpost&& value) { m_subnetOutpostHasBeenSet = true; m_subnetOutpost = std::move(value); }
/**
* <p>The outpost ARN of the subnet.</p>
*/
inline Subnet& WithSubnetOutpost(const SubnetOutpost& value) { SetSubnetOutpost(value); return *this;}
/**
* <p>The outpost ARN of the subnet.</p>
*/
inline Subnet& WithSubnetOutpost(SubnetOutpost&& value) { SetSubnetOutpost(std::move(value)); return *this;}
private:
Aws::String m_subnetIdentifier;
bool m_subnetIdentifierHasBeenSet;
AvailabilityZone m_subnetAvailabilityZone;
bool m_subnetAvailabilityZoneHasBeenSet;
SubnetOutpost m_subnetOutpost;
bool m_subnetOutpostHasBeenSet;
};
} // namespace Model
} // namespace ElastiCache
} // namespace Aws
|
awslabs/aws-sdk-cpp
|
aws-cpp-sdk-elasticache/include/aws/elasticache/model/Subnet.h
|
C
|
apache-2.0
| 5,344
|
#ifndef __YUMA_ABSTRACT_NC_SESSION_H
#define __YUMA_ABSTRACT_NC_SESSION_H
// ---------------------------------------------------------------------------|
#include <cstdint>
#include <string>
#include <map>
#include <memory>
#include <fstream>
// ---------------------------------------------------------------------------|
namespace YumaTest
{
class AbstractYumaOpLogPolicy;
// ---------------------------------------------------------------------------|
/**
* Abstract base class for Netconf sessions.
*/
class AbstractNCSession
{
public:
/**
* Constructor.
*
* \param policy the log filename generation policy
* \param sessionId the session id.
*/
AbstractNCSession( std::shared_ptr< AbstractYumaOpLogPolicy > policy,
uint16_t sessionId );
/** Desstructor */
virtual ~AbstractNCSession();
/**
* Inject the query into netconf. This function is used to inject
* the supplied XML NC query. It returns the id of the message
* that was used to inject the query.
*
* \param queryStr a string containing the XML message to inject.
* \return the id of the message used to inject the query.
*/
virtual uint16_t injectMessage( const std::string& queryStr ) = 0;
/**
* Get the output of the query.
*
* \param messageId the id of the message containing the initial
* query.
* \return the query output returned by Yuma.
*/
virtual std::string getSessionResult( uint16_t messageId ) const;
/**
* Allocate a messageId.
*
* \return the next message id;
*/
uint16_t allocateMessageId()
{ return ++messageCount_; }
/**
* Return sessionId.
*
* \return the session id;
*/
uint16_t getId()
{ return sessionId_; }
protected:
/**
* Genearte a new log filename and add it to the internal map
* of messages to coressponding lig filename.
*
* \param queryStr the query to generate a new log file for.
*/
std::string newQueryLogFilename( const std::string& queryStr );
/**
* Get the log filename associated with the message id.
*
* \param messageId the message id.
* \return the associated log filename.
*/
std::string retrieveLogFilename( const uint16_t messageId ) const;
/**
* Concatenate all of thye logfiles genearted by this session into
* a single large logfile.
*/
void concatenateLogFiles();
/**
* Concatenate the associated logfile top op.
*
* \param op the output stream
* \param key the key associated with the input filename;
*/
void appendLog( std::ofstream& op, uint16_t key );
protected:
/** The session id */
uint16_t sessionId_;
/** next message id */
uint16_t messageCount_;
/** Output log filename generation policy */
std::shared_ptr< AbstractYumaOpLogPolicy > opLogFilenamePolicy_;
/** A map of messageIds to output log filenames */
std::map< uint16_t, std::string > messageIdToLogMap_;
};
} // namespace YumaTest
#endif // __YUMA_ABSTRACT_NC_SESSION_H
|
hsnlab/escape
|
OpenYuma/netconf/test/support/nc-session/abstract-nc-session.h
|
C
|
apache-2.0
| 3,160
|
// 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 org.jetbrains.plugins.groovy.lang.psi.stubs.elements;
import com.intellij.psi.impl.java.stubs.index.JavaStubIndexKeys;
import com.intellij.psi.stubs.IndexSink;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.stubs.StubInputStream;
import com.intellij.psi.stubs.StubOutputStream;
import com.intellij.util.ArrayUtil;
import com.intellij.util.io.StringRef;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.GrFieldImpl;
import org.jetbrains.plugins.groovy.lang.psi.stubs.GrFieldStub;
import org.jetbrains.plugins.groovy.lang.psi.stubs.GrStubUtils;
import org.jetbrains.plugins.groovy.lang.psi.stubs.index.GrAnnotatedMemberIndex;
import org.jetbrains.plugins.groovy.lang.psi.stubs.index.GrFieldNameIndex;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
/**
* @author ilyas
*/
public class GrFieldElementType extends GrStubElementType<GrFieldStub, GrField> {
public GrFieldElementType(String debugName) {
super(debugName);
}
@Override
public GrField createPsi(@NotNull GrFieldStub stub) {
return new GrFieldImpl(stub);
}
@NotNull
@Override
public GrFieldStub createStub(@NotNull GrField psi, StubElement parentStub) {
String[] annNames = GrStubUtils.getAnnotationNames(psi);
Set<String> namedParameters = Collections.emptySet();
if (psi instanceof GrFieldImpl){
namedParameters = psi.getNamedParameters().keySet();
}
return new GrFieldStub(parentStub, StringRef.fromString(psi.getName()), annNames,
namedParameters.toArray(ArrayUtil.EMPTY_STRING_ARRAY),
GroovyElementTypes.FIELD, GrFieldStub.buildFlags(psi),
GrStubUtils.getTypeText(psi.getTypeElementGroovy()));
}
@Override
public void serialize(@NotNull GrFieldStub stub, @NotNull StubOutputStream dataStream) throws IOException {
serializeFieldStub(stub, dataStream);
}
@Override
@NotNull
public GrFieldStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException {
return deserializeFieldStub(dataStream, parentStub);
}
@Override
public void indexStub(@NotNull GrFieldStub stub, @NotNull IndexSink sink) {
indexFieldStub(stub, sink);
}
/*
* ****************************************************************************************************************
*/
static void serializeFieldStub(GrFieldStub stub, StubOutputStream dataStream) throws IOException {
dataStream.writeName(stub.getName());
GrStubUtils.writeStringArray(dataStream, stub.getAnnotations());
GrStubUtils.writeStringArray(dataStream, stub.getNamedParameters());
dataStream.writeByte(stub.getFlags());
GrStubUtils.writeNullableString(dataStream, stub.getTypeText());
}
static GrFieldStub deserializeFieldStub(StubInputStream dataStream, StubElement parentStub) throws IOException {
StringRef ref = dataStream.readName();
final String[] annNames = GrStubUtils.readStringArray(dataStream);
final String[] namedParameters = GrStubUtils.readStringArray(dataStream);
byte flags = dataStream.readByte();
final String typeText = GrStubUtils.readNullableString(dataStream);
return new GrFieldStub(parentStub, ref, annNames, namedParameters, GrFieldStub.isEnumConstant(flags) ? GroovyElementTypes.ENUM_CONSTANT
: GroovyElementTypes.FIELD,
flags, typeText);
}
static void indexFieldStub(GrFieldStub stub, IndexSink sink) {
String name = stub.getName();
sink.occurrence(GrFieldNameIndex.KEY, name);
if (GrStubUtils.isGroovyStaticMemberStub(stub)) {
sink.occurrence(JavaStubIndexKeys.JVM_STATIC_MEMBERS_NAMES, name);
sink.occurrence(JavaStubIndexKeys.JVM_STATIC_MEMBERS_TYPES, GrStubUtils.getShortTypeText(stub.getTypeText()));
}
for (String annName : stub.getAnnotations()) {
if (annName != null) {
sink.occurrence(GrAnnotatedMemberIndex.KEY, annName);
}
}
}
}
|
jk1/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrFieldElementType.java
|
Java
|
apache-2.0
| 4,429
|
# Dependencies
[Pandoc](http://johnmacfarlane.net/pandoc/installing.html), a universal
document converter, is required to generate docs as HTML from Rust's
source code.
[po4a](http://po4a.alioth.debian.org/) is required for generating translated
docs from the master (English) docs.
[GNU gettext](http://www.gnu.org/software/gettext/) is required for managing
the translation data.
# Building
To generate all the docs, just run `make docs` from the root of the repository.
This will convert the distributed Markdown docs to HTML and generate HTML doc
for the 'std' and 'extra' libraries.
To generate HTML documentation from one source file/crate, do something like:
~~~~
rustdoc --output html-doc/ --output-format html ../src/libstd/path.rs
~~~~
(This, of course, requires a working build of the `rustdoc` tool.)
# Additional notes
To generate an HTML version of a doc from Markdown manually, you can do
something like:
~~~~
pandoc --from=markdown --to=html5 --number-sections -o rust.html rust.md
~~~~
(rust.md being the Rust Reference Manual.)
The syntax for pandoc flavored markdown can be found at:
http://johnmacfarlane.net/pandoc/README.html#pandocs-markdown
A nice quick reference (for non-pandoc markdown) is at:
http://kramdown.rubyforge.org/quickref.html
# Notes for translators
Notice: The procedure described below is a work in progress. We are working on
translation system but the procedure contains some manual operations for now.
To start the translation for a new language, see po4a.conf at first.
To generate .pot and .po files, do something like:
~~~~
po4a --copyright-holder="The Rust Project Developers" \
--package-name="Rust" \
--package-version="0.11.0" \
-M UTF-8 -L UTF-8 \
src/doc/po4a.conf
~~~~
(the version number must be changed if it is not 0.11.0 now.)
Now you can translate documents with .po files, commonly used with gettext. If
you are not familiar with gettext-based translation, please read the online
manual linked from http://www.gnu.org/software/gettext/ . We use UTF-8 as the
file encoding of .po files.
When you want to make a commit, do the command below before staging your
change:
~~~~
for f in src/doc/po/**/*.po; do
msgattrib --translated $f -o $f.strip
if [ -e $f.strip ]; then
mv $f.strip $f
else
rm $f
fi
done
~~~~
This removes untranslated entries from .po files to save disk space.
|
erickt/rust
|
src/doc/README.md
|
Markdown
|
apache-2.0
| 2,405
|
/*
* 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.isis.viewer.dnd.field;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.viewer.dnd.drawing.Color;
import org.apache.isis.viewer.dnd.drawing.ColorsAndFonts;
import org.apache.isis.viewer.dnd.drawing.Size;
import org.apache.isis.viewer.dnd.drawing.Text;
import org.apache.isis.viewer.dnd.form.InternalFormSpecification;
import org.apache.isis.viewer.dnd.list.SimpleListSpecification;
import org.apache.isis.viewer.dnd.view.Axes;
import org.apache.isis.viewer.dnd.view.Content;
import org.apache.isis.viewer.dnd.view.Toolkit;
import org.apache.isis.viewer.dnd.view.View;
import org.apache.isis.viewer.dnd.view.ViewRequirement;
import org.apache.isis.viewer.dnd.view.ViewSpecification;
import org.apache.isis.viewer.dnd.view.border.IconBorder;
import org.apache.isis.viewer.dnd.view.composite.CompositeView;
import org.apache.isis.viewer.dnd.view.content.FieldContent;
import org.apache.isis.viewer.dnd.view.text.TitleText;
public class FieldOfSpecification implements ViewSpecification {
@Override
public boolean canDisplay(final ViewRequirement requirement) {
return requirement.isOpen() && !requirement.isSubview() && requirement.getContent() instanceof FieldContent;
}
@Override
public String getName() {
return "Field Of";
}
@Override
public boolean isAligned() {
return false;
}
@Override
public boolean isOpen() {
return false;
}
@Override
public boolean isReplaceable() {
return false;
}
@Override
public boolean isResizeable() {
return false;
}
@Override
public boolean isSubView() {
return false;
}
@Override
public View createView(final Content content, final Axes axes, final int sequence) {
final FieldContent fieldContent = (FieldContent) content;
final ObjectAdapter parent = fieldContent.getParent();
final Content parentContent = Toolkit.getContentFactory().createRootContent(parent);
View view = new InternalFieldView(parentContent, fieldContent, axes, this);
view = addBorder(parentContent, fieldContent, view);
return view;
}
private View addBorder(final Content parentContent, final FieldContent fieldContent, View view) {
final Text textStyle = Toolkit.getText(ColorsAndFonts.TEXT_TITLE);
final Color colorStyle = Toolkit.getColor(ColorsAndFonts.COLOR_BLACK);
final TitleText titleText = new TitleText(view, textStyle, colorStyle) {
@Override
protected String title() {
return parentContent.title() + "/" + fieldContent.getFieldName();
}
};
view = new IconBorder(view, titleText, null, textStyle);
return view;
}
}
class InternalFieldView extends CompositeView {
// final View[] subviews = new View[1];
private final Content fieldContent;
public InternalFieldView(final Content content, final Content fieldContent, final Axes axes, final ViewSpecification specification) {
super(content, specification);
this.fieldContent = fieldContent;
}
/*
* public void draw(Canvas canvas) { subviews[0].draw(canvas); }
*
* public View[] getSubviews() { return subviews; }
*/
@Override
public Size requiredSize(final Size availableSpace) {
return getSubviews()[0].getRequiredSize(availableSpace);
}
@Override
protected void doLayout(final Size maximumSize) {
final View view = getSubviews()[0];
view.setSize(view.getRequiredSize(maximumSize));
view.layout();
}
@Override
protected void buildView() {
ViewSpecification internalSpecification;
if (fieldContent.isCollection()) {
internalSpecification = new SimpleListSpecification();
} else {
internalSpecification = new InternalFormSpecification();
}
addView(internalSpecification.createView(fieldContent, new Axes(), 0));
}
}
|
howepeng/isis
|
mothballed/component/viewer/dnd/impl/src/main/java/org/apache/isis/viewer/dnd/field/FieldOfSpecification.java
|
Java
|
apache-2.0
| 4,876
|
/*
* Copyright 2011-2019 Asakusa Framework Team.
*
* 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.asakusafw.spark.extensions.iterativebatch
import com.asakusafw.spark.runtime.{ AsakusafwConfPrefix, Props }
package object runtime {
val IterativeBatchPropsPrefix = s"${AsakusafwConfPrefix}.iterativebatch"
object IterativeBatchProps {
val NumSlots = s"${IterativeBatchPropsPrefix}.slots"
val StopOnFail = s"${IterativeBatchPropsPrefix}.stopOnFail"
val DefaultNumSlots = Int.MaxValue
val DefaultStopOnFail = true
}
implicit class AugmentedProps(val props: Props.type) extends AnyVal {
def NumSlots = IterativeBatchProps.NumSlots // scalastyle:ignore
def StopOnFail = IterativeBatchProps.StopOnFail // scalastyle:ignore
def DefaultNumSlots = IterativeBatchProps.DefaultNumSlots // scalastyle:ignore
def DefaultStopOnFail = IterativeBatchProps.DefaultStopOnFail // scalastyle:ignore
}
}
|
ashigeru/asakusafw-spark
|
extensions/iterativebatch/runtime/core/src/main/scala/com/asakusafw/spark/extensions/iterativebatch/runtime/package.scala
|
Scala
|
apache-2.0
| 1,458
|
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/translate/v3/translation_service.proto
namespace Google\Cloud\Translate\V3;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* Request message for CreateGlossary.
*
* Generated from protobuf message <code>google.cloud.translation.v3.CreateGlossaryRequest</code>
*/
class CreateGlossaryRequest extends \Google\Protobuf\Internal\Message
{
/**
* Required. The project name.
*
* Generated from protobuf field <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code>
*/
private $parent = '';
/**
* Required. The glossary to create.
*
* Generated from protobuf field <code>.google.cloud.translation.v3.Glossary glossary = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private $glossary = null;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $parent
* Required. The project name.
* @type \Google\Cloud\Translate\V3\Glossary $glossary
* Required. The glossary to create.
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Cloud\Translate\V3\TranslationService::initOnce();
parent::__construct($data);
}
/**
* Required. The project name.
*
* Generated from protobuf field <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code>
* @return string
*/
public function getParent()
{
return $this->parent;
}
/**
* Required. The project name.
*
* Generated from protobuf field <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code>
* @param string $var
* @return $this
*/
public function setParent($var)
{
GPBUtil::checkString($var, True);
$this->parent = $var;
return $this;
}
/**
* Required. The glossary to create.
*
* Generated from protobuf field <code>.google.cloud.translation.v3.Glossary glossary = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return \Google\Cloud\Translate\V3\Glossary|null
*/
public function getGlossary()
{
return $this->glossary;
}
public function hasGlossary()
{
return isset($this->glossary);
}
public function clearGlossary()
{
unset($this->glossary);
}
/**
* Required. The glossary to create.
*
* Generated from protobuf field <code>.google.cloud.translation.v3.Glossary glossary = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @param \Google\Cloud\Translate\V3\Glossary $var
* @return $this
*/
public function setGlossary($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Translate\V3\Glossary::class);
$this->glossary = $var;
return $this;
}
}
|
googleapis/google-cloud-php-translate
|
src/V3/CreateGlossaryRequest.php
|
PHP
|
apache-2.0
| 3,168
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.as2;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.as2.api.AS2MessageStructure;
import org.apache.camel.component.as2.internal.AS2ApiName;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriParams;
import org.apache.camel.spi.UriPath;
import org.apache.http.entity.ContentType;
/**
* Component configuration for AS2 component.
*/
@UriParams
public class AS2Configuration {
@UriPath
@Metadata(required = "true")
private AS2ApiName apiName;
@UriParam
@Metadata(required = "true")
private String methodName;
@UriParam(defaultValue = "1.1", enums = "1.0,1.1")
private String as2Version = "1.1";
@UriParam(defaultValue = "Camel AS2 Client Endpoint")
private String userAgent = "Camel AS2 Client Endpoint";
@UriParam(defaultValue = "Camel AS2 Server Endpoint")
private String server = "Camel AS2 Server Endpoint";
@UriParam(defaultValue = "camel.apache.org")
private String serverFqdn = "camel.apache.org";
@UriParam
private String targetHostname;
@UriParam
private Integer targetPortNumber;
@UriParam(defaultValue = "camel.apache.org")
private String clientFqdn = "camel.apache.org";
@UriParam
private Integer serverPortNumber;
@UriParam(defaultValue = "/")
private String requestUri = "/";
@UriParam
private ContentType ediMessageType;
@UriParam
private String ediMessageTransferEncoding;
@UriParam
private AS2MessageStructure as2MessageStructure;
@UriParam
private String subject;
@UriParam
private String from;
@UriParam
private String as2From;
@UriParam
private String as2To;
@UriParam
private String signingAlgorithmName;
@UriParam
private Certificate[] signingCertificateChain;
@UriParam
private PrivateKey signingPrivateKey;
@UriParam
private String dispositionNotificationTo;
@UriParam
private String[] signedReceiptMicAlgorithms;
@UriParam
private String encryptingAlgorithmName;
@UriParam
private Certificate[] encryptingCertificateChain;
@UriParam
private PrivateKey encryptingPrivateKey;
public AS2ApiName getApiName() {
return apiName;
}
/**
* What kind of operation to perform
*/
public void setApiName(AS2ApiName apiName) {
this.apiName = apiName;
}
public String getMethodName() {
return methodName;
}
/**
* What sub operation to use for the selected operation
*/
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getAs2Version() {
return as2Version;
}
/**
* The version of the AS2 protocol.
*/
public void setAs2Version(String as2Version) {
if (!as2Version.equals("1.0") && !as2Version.equals("1.1")) {
throw new IllegalArgumentException(String.format(
"Value '%s' of configuration parameter 'as2Version' must be either '1.0' or '1.1'", as2Version));
}
this.as2Version = as2Version;
}
public String getUserAgent() {
return userAgent;
}
/**
* The value included in the User-Agent message header identifying
* the AS2 user agent.
*/
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public String getServer() {
return server;
}
/**
* The value included in the Server message header identifying the
* AS2 Server.
*/
public void setServer(String server) {
this.server = server;
}
public String getServerFqdn() {
return serverFqdn;
}
/**
* The Server Fully Qualified Domain Name (FQDN).
* Used in message ids sent by endpoint.
*/
public void setServerFqdn(String serverFqdn) {
if (clientFqdn == null) {
throw new RuntimeCamelException("Parameter 'serverFqdn' can not be null");
}
this.serverFqdn = serverFqdn;
}
public String getTargetHostname() {
return targetHostname;
}
/**
* The host name (IP or DNS name) of target host.
*/
public void setTargetHostname(String targetHostname) {
this.targetHostname = targetHostname;
}
public int getTargetPortNumber() {
return targetPortNumber;
}
/**
* The port number of target host. -1 indicates the scheme default port.
*/
public void setTargetPortNumber(String targetPortNumber) {
try {
this.targetPortNumber = Integer.valueOf(targetPortNumber);
} catch (NumberFormatException e) {
throw new RuntimeCamelException(String.format("Invalid target port number: %s", targetPortNumber));
}
}
/**
* The port number of target host. -1 indicates the scheme default port.
*/
public void setTargetPortNumber(Integer targetPortNumber) {
this.targetPortNumber = targetPortNumber;
}
public String getClientFqdn() {
return clientFqdn;
}
/**
* The Client Fully Qualified Domain Name (FQDN).
* Used in message ids sent by endpoint.
*/
public void setClientFqdn(String clientFqdn) {
if (clientFqdn == null) {
throw new RuntimeCamelException("Parameter 'clientFqdn' can not be null");
}
this.clientFqdn = clientFqdn;
}
public Integer getServerPortNumber() {
return serverPortNumber;
}
/**
* The port number of server.
*/
public void setServerPortNumber(String serverPortNumber) {
try {
this.serverPortNumber = Integer.valueOf(serverPortNumber);
} catch (NumberFormatException e) {
throw new RuntimeCamelException(String.format("Invalid target port number: %s", targetPortNumber));
}
}
/**
* The port number of server.
*/
public void setServerPortNumber(Integer serverPortNumber) {
this.serverPortNumber = serverPortNumber;
}
public String getRequestUri() {
return requestUri;
}
/**
* The request URI of EDI message.
*/
public void setRequestUri(String requestUri) {
this.requestUri = requestUri;
}
public ContentType getEdiMessageType() {
return ediMessageType;
}
/**
* The content type of EDI message.
* One of application/edifact, application/edi-x12, application/edi-consent
*/
public void setEdiMessageType(ContentType ediMessageType) {
this.ediMessageType = ediMessageType;
}
public String getEdiMessageTransferEncoding() {
return ediMessageTransferEncoding;
}
/**
* The transfer encoding of EDI message.
*/
public void setEdiMessageTransferEncoding(String ediMessageTransferEncoding) {
this.ediMessageTransferEncoding = ediMessageTransferEncoding;
}
public AS2MessageStructure getAs2MessageStructure() {
return as2MessageStructure;
}
/**
* The structure of AS2 Message. One of:
* PLAIN - No encryption, no signature,
* SIGNED - No encryption, signature,
* ENCRYPTED - Encryption, no signature,
* ENCRYPTED_SIGNED - Encryption, signature
*/
public void setAs2MessageStructure(AS2MessageStructure as2MessageStructure) {
this.as2MessageStructure = as2MessageStructure;
}
public String getSubject() {
return subject;
}
/**
* The value of Subject header of AS2 message.
*/
public void setSubject(String subject) {
this.subject = subject;
}
public String getFrom() {
return from;
}
/**
* The value of the From header of AS2 message.
*/
public void setFrom(String from) {
this.from = from;
}
public String getAs2From() {
return as2From;
}
/**
* The value of the AS2From header of AS2 message.
*/
public void setAs2From(String as2From) {
this.as2From = as2From;
}
public String getAs2To() {
return as2To;
}
/**
* The value of the AS2To header of AS2 message.
*/
public void setAs2To(String as2To) {
this.as2To = as2To;
}
public String getSigningAlgorithmName() {
return signingAlgorithmName;
}
/**
* The name of algorithm used to sign EDI message.
*/
public void setSigningAlgorithmName(String signingAlgorithmName) {
this.signingAlgorithmName = signingAlgorithmName;
}
public Certificate[] getSigningCertificateChain() {
return signingCertificateChain;
}
/**
* The chain of certificates used to sign EDI message.
*/
public void setSigningCertificateChain(Certificate[] signingCertificateChain) {
this.signingCertificateChain = signingCertificateChain;
}
public PrivateKey getSigningPrivateKey() {
return signingPrivateKey;
}
/**
* The key used to sign the EDI message.
*/
public void setSigningPrivateKey(PrivateKey signingPrivateKey) {
this.signingPrivateKey = signingPrivateKey;
}
public String getDispositionNotificationTo() {
return dispositionNotificationTo;
}
/**
* The value of the Disposition-Notification-To header.
*
* Assigning a value to this parameter requests a message disposition
* notification (MDN) for the AS2 message.
*/
public void setDispositionNotificationTo(String dispositionNotificationTo) {
this.dispositionNotificationTo = dispositionNotificationTo;
}
public String[] getSignedReceiptMicAlgorithms() {
return signedReceiptMicAlgorithms;
}
/**
* The list of algorithms, in order of preference, requested to generate a
* message integrity check (MIC) returned in message dispostion notification
* (MDN)
*/
public void setSignedReceiptMicAlgorithms(String[] signedReceiptMicAlgorithms) {
this.signedReceiptMicAlgorithms = signedReceiptMicAlgorithms;
}
public String getEncryptingingAlgorithmName() {
return signingAlgorithmName;
}
/**
* The name of algorithm used to encrypt EDI message.
*/
public void setEncryptingAlgorithmName(String signingAlgorithmName) {
this.encryptingAlgorithmName = signingAlgorithmName;
}
public Certificate[] getEncryptingCertificateChain() {
return encryptingCertificateChain;
}
/**
* The chain of certificates used to encrypt EDI message.
*/
public void setEncryptingCertificateChain(Certificate[] signingCertificateChain) {
this.encryptingCertificateChain = signingCertificateChain;
}
public PrivateKey getEncryptingPrivateKey() {
return encryptingPrivateKey;
}
/**
* The key used to encrypt the EDI message.
*/
public void setEncryptingPrivateKey(PrivateKey signingPrivateKey) {
this.encryptingPrivateKey = signingPrivateKey;
}
}
|
sverkera/camel
|
components/camel-as2/camel-as2-component/src/main/java/org/apache/camel/component/as2/AS2Configuration.java
|
Java
|
apache-2.0
| 11,999
|
/*
* Copyright 2010-2016 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.cognitoidp.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Represents the request to add custom attributes.
* </p>
*/
public class AddCustomAttributesRequest extends AmazonWebServiceRequest
implements Serializable, Cloneable {
/**
* <p>
* The user pool ID for the user pool where you want to add custom
* attributes.
* </p>
*/
private String userPoolId;
/**
* <p>
* An array of custom attributes, such as Mutable and Name.
* </p>
*/
private java.util.List<SchemaAttributeType> customAttributes;
/**
* <p>
* The user pool ID for the user pool where you want to add custom
* attributes.
* </p>
*
* @param userPoolId
* The user pool ID for the user pool where you want to add custom
* attributes.
*/
public void setUserPoolId(String userPoolId) {
this.userPoolId = userPoolId;
}
/**
* <p>
* The user pool ID for the user pool where you want to add custom
* attributes.
* </p>
*
* @return The user pool ID for the user pool where you want to add custom
* attributes.
*/
public String getUserPoolId() {
return this.userPoolId;
}
/**
* <p>
* The user pool ID for the user pool where you want to add custom
* attributes.
* </p>
*
* @param userPoolId
* The user pool ID for the user pool where you want to add custom
* attributes.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public AddCustomAttributesRequest withUserPoolId(String userPoolId) {
setUserPoolId(userPoolId);
return this;
}
/**
* <p>
* An array of custom attributes, such as Mutable and Name.
* </p>
*
* @return An array of custom attributes, such as Mutable and Name.
*/
public java.util.List<SchemaAttributeType> getCustomAttributes() {
return customAttributes;
}
/**
* <p>
* An array of custom attributes, such as Mutable and Name.
* </p>
*
* @param customAttributes
* An array of custom attributes, such as Mutable and Name.
*/
public void setCustomAttributes(
java.util.Collection<SchemaAttributeType> customAttributes) {
if (customAttributes == null) {
this.customAttributes = null;
return;
}
this.customAttributes = new java.util.ArrayList<SchemaAttributeType>(
customAttributes);
}
/**
* <p>
* An array of custom attributes, such as Mutable and Name.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setCustomAttributes(java.util.Collection)} or
* {@link #withCustomAttributes(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param customAttributes
* An array of custom attributes, such as Mutable and Name.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public AddCustomAttributesRequest withCustomAttributes(
SchemaAttributeType... customAttributes) {
if (this.customAttributes == null) {
setCustomAttributes(new java.util.ArrayList<SchemaAttributeType>(
customAttributes.length));
}
for (SchemaAttributeType ele : customAttributes) {
this.customAttributes.add(ele);
}
return this;
}
/**
* <p>
* An array of custom attributes, such as Mutable and Name.
* </p>
*
* @param customAttributes
* An array of custom attributes, such as Mutable and Name.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public AddCustomAttributesRequest withCustomAttributes(
java.util.Collection<SchemaAttributeType> customAttributes) {
setCustomAttributes(customAttributes);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getUserPoolId() != null)
sb.append("UserPoolId: " + getUserPoolId() + ",");
if (getCustomAttributes() != null)
sb.append("CustomAttributes: " + getCustomAttributes());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AddCustomAttributesRequest == false)
return false;
AddCustomAttributesRequest other = (AddCustomAttributesRequest) obj;
if (other.getUserPoolId() == null ^ this.getUserPoolId() == null)
return false;
if (other.getUserPoolId() != null
&& other.getUserPoolId().equals(this.getUserPoolId()) == false)
return false;
if (other.getCustomAttributes() == null
^ this.getCustomAttributes() == null)
return false;
if (other.getCustomAttributes() != null
&& other.getCustomAttributes().equals(
this.getCustomAttributes()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getUserPoolId() == null) ? 0 : getUserPoolId().hashCode());
hashCode = prime
* hashCode
+ ((getCustomAttributes() == null) ? 0 : getCustomAttributes()
.hashCode());
return hashCode;
}
@Override
public AddCustomAttributesRequest clone() {
return (AddCustomAttributesRequest) super.clone();
}
}
|
mhurne/aws-sdk-java
|
aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/AddCustomAttributesRequest.java
|
Java
|
apache-2.0
| 6,937
|
/*
* 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.
*/
/* $Id$ */
package org.apache.fop.traits;
import java.awt.Color;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.fo.expr.PropertyException;
import org.apache.fop.util.ColorUtil;
/**
* Border properties.
* Class to store border trait properties for the area tree.
*/
public class BorderProps implements Serializable {
private static final long serialVersionUID = 8022237892391068187L;
public enum Mode {
SEPARATE("separate") {
@Override
int getClippedWidth(BorderProps bp) {
return 0;
}
},
COLLAPSE_INNER("collapse-inner"), // for borders inside a table
COLLAPSE_OUTER("collapse-outer"); // for borders at the table's outer border
private final String value;
Mode(String value) {
this.value = value;
}
int getClippedWidth(BorderProps bp) {
return bp.width / 2;
};
}
/** Border style (one of EN_*) */
public final int style; // Enum for border style
/** Border color */
public final Color color;
/** Border width */
public final int width;
private final int radiusStart;
private final int radiusEnd;
/** Border mode */
private final Mode mode;
/**
* Constructs a new BorderProps instance.
* @param style border style (one of EN_*)
* @param width border width
* @param radiusStart radius of start corner in the direction perpendicular to border segment
* @param radiusEnd radius of end corner in the direction perpendicular to border segment
* @param color border color
* @param mode border mode ((one of SEPARATE, COLLAPSE_INNER and COLLAPSE_OUTER)
*/
public BorderProps(int style, int width, int radiusStart, int radiusEnd, Color color, Mode mode) {
this.style = style;
this.width = width;
this.radiusStart = radiusStart;
this.radiusEnd = radiusEnd;
this.color = color;
this.mode = mode;
}
/**
* Factory method for a new BorderProps instance with rectangular corners.
* @param style border style (one of EN_*)
* @param width border width
* @param color border color
* @param mode border mode ((one of SEPARATE, COLLAPSE_INNER and COLLAPSE_OUTER)
*/
public static BorderProps makeRectangular(int style, int width, Color color, Mode mode) {
return new BorderProps(style, width, 0, 0, color, mode);
}
private BorderProps(String style, int width, int radiusStart, int radiusEnd, Color color, Mode mode) {
this(getConstantForStyle(style), width, radiusStart, radiusEnd, color, mode);
}
/**
*
* @return the radius of the corner adjacent to the before or start border
*/
public int getRadiusStart() {
return radiusStart;
}
/**
* @return the radius of the corner adjacent to the after or end border
*/
public int getRadiusEnd() {
return radiusEnd;
}
/**
* @return the border mode ((one of SEPARATE, COLLAPSE_INNER and COLLAPSE_OUTER)
*/
public Mode getMode() {
return mode;
}
/**
* @param bp the border properties or null
* @return the effective width of the clipped part of the border
*/
public static int getClippedWidth(BorderProps bp) {
return bp == null ? 0 : bp.mode.getClippedWidth(bp);
}
private String getStyleString() {
return BorderStyle.valueOf(style).getName();
}
private static int getConstantForStyle(String style) {
return BorderStyle.valueOf(style).getEnumValue();
}
public boolean isCollapseOuter() {
return mode == Mode.COLLAPSE_OUTER;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return toString().hashCode();
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj == this) {
return true;
} else {
if (obj instanceof BorderProps) {
BorderProps other = (BorderProps) obj;
return (style == other.style)
&& org.apache.xmlgraphics.java2d.color.ColorUtil.isSameColor(
color, other.color)
&& width == other.width
&& mode == other.mode
&& radiusStart == other.radiusStart
&& radiusEnd == other.radiusEnd;
}
}
return false;
}
/**
* Returns a BorderProps represtation of a string of the format as written by
* BorderProps.toString().
* @param foUserAgent FOP user agent caching ICC profiles
* @param s the string
* @return a BorderProps instance
*/
public static BorderProps valueOf(FOUserAgent foUserAgent, String s) {
return BorderPropsDeserializer.INSTANCE.valueOf(foUserAgent, s);
}
/** {@inheritDoc} */
@Override
public String toString() {
StringBuffer sbuf = new StringBuffer();
sbuf.append('(')
.append(getStyleString()).append(',')
.append(ColorUtil.colorToString(color)).append(',')
.append(width);
if (!mode.equals(Mode.SEPARATE)) {
sbuf.append(",").append(mode.value);
}
if (radiusStart != 0 || radiusEnd != 0) {
if (mode.equals(Mode.SEPARATE)) {
// Because of the corner radii properties the mode must be set
// so that the parameter index is consistent
sbuf.append(",").append(Mode.SEPARATE.value);
}
sbuf.append(',').append(radiusStart)
.append(',').append(radiusEnd);
}
sbuf.append(')');
return sbuf.toString();
}
private static final class BorderPropsDeserializer {
private static final BorderPropsDeserializer INSTANCE = new BorderPropsDeserializer();
private static final Pattern PATTERN = Pattern.compile("([^,\\(]+(?:\\(.*\\))?)");
private BorderPropsDeserializer() {
}
public BorderProps valueOf(FOUserAgent foUserAgent, String s) {
if (s.startsWith("(") && s.endsWith(")")) {
s = s.substring(1, s.length() - 1);
Matcher m = PATTERN.matcher(s);
m.find();
String style = m.group();
m.find();
String color = m.group();
m.find();
int width = Integer.parseInt(m.group());
Mode mode = Mode.SEPARATE;
if (m.find()) {
String ms = m.group();
if (Mode.COLLAPSE_INNER.value.equalsIgnoreCase(ms)) {
mode = Mode.COLLAPSE_INNER;
} else if (Mode.COLLAPSE_OUTER.value.equalsIgnoreCase(ms)) {
mode = Mode.COLLAPSE_OUTER;
}
}
Color c;
try {
c = ColorUtil.parseColorString(foUserAgent, color);
} catch (PropertyException e) {
throw new IllegalArgumentException(e.getMessage());
}
int startRadius = 0;
int endRadius = 0;
if (m.find()) {
startRadius = Integer.parseInt(m.group());
m.find();
endRadius = Integer.parseInt(m.group());
}
return new BorderProps(style, width, startRadius, endRadius, c, mode);
} else {
throw new IllegalArgumentException("BorderProps must be surrounded by parentheses");
}
}
}
}
|
chunlinyao/fop
|
fop-core/src/main/java/org/apache/fop/traits/BorderProps.java
|
Java
|
apache-2.0
| 8,730
|
---
datafolder: engine-cli-edge
datafile: docker_image_tag
title: docker image tag
---
<!--
Sorry, but the contents of this page are automatically generated from
Docker's source code. If you want to suggest a change to the text that appears
here, you'll need to find the string by searching this repo:
https://www.github.com/moby/moby
-->
{% if page.datafolder contains '-edge' %}
{% include edge_only.md section="cliref" %}
{% endif %}
{% include cli.md datafolder=page.datafolder datafile=page.datafile %}
|
phiroict/docker
|
edge/engine/reference/commandline/image_tag.md
|
Markdown
|
apache-2.0
| 513
|
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Newtonsoft.Json;
using NUnit.Framework;
using System.Collections.Generic;
using QuantConnect.Optimizer.Parameters;
namespace QuantConnect.Tests.API
{
[TestFixture]
public class ParameterSetJsonConverterTests
{
private const string ValidSerialization = "{\"parameterSet\":{\"pinocho\":\"19\",\"pepe\":\"-1\"}}";
[Test]
public void SerializationNulls()
{
var parameterSet = new ParameterSet(0, null);
var serialized = JsonConvert.SerializeObject(parameterSet);
Assert.AreEqual("{}", serialized);
}
[Test]
public void Serialization()
{
var parameterSet = new ParameterSet(18,
new Dictionary<string, string>
{
{ "pinocho", "19" },
{ "pepe", "-1" }
});
var serialized = JsonConvert.SerializeObject(parameterSet);
Assert.AreEqual(ValidSerialization, serialized);
}
[TestCase("{}", 0)]
[TestCase("[]", 0)]
[TestCase(ValidSerialization, 2)]
public void Deserialization(string validSerialization, int count)
{
var deserialized = JsonConvert.DeserializeObject<ParameterSet>(validSerialization);
Assert.IsNotNull(deserialized);
Assert.AreEqual(-1, deserialized.Id);
Assert.AreEqual(count, deserialized.Value.Count);
if (count != 0)
{
Assert.IsTrue(deserialized.Value["pinocho"] == "19");
Assert.IsTrue(deserialized.Value["pepe"] == "-1");
}
}
}
}
|
AlexCatarino/Lean
|
Tests/Api/ParameterSetJsonConverterTests.cs
|
C#
|
apache-2.0
| 2,367
|
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/dialogflow/v2/fulfillment.proto
namespace Google\Cloud\Dialogflow\V2;
if (false) {
/**
* This class is deprecated. Use Google\Cloud\Dialogflow\V2\Fulfillment\Feature instead.
* @deprecated
*/
class Fulfillment_Feature {}
}
class_exists(Fulfillment\Feature::class);
@trigger_error('Google\Cloud\Dialogflow\V2\Fulfillment_Feature is deprecated and will be removed in a future release. Use Google\Cloud\Dialogflow\V2\Fulfillment\Feature instead', E_USER_DEPRECATED);
|
googleapis/google-cloud-php-dialogflow
|
src/V2/Fulfillment_Feature.php
|
PHP
|
apache-2.0
| 578
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.scxml2.model;
/**
* Defines the allowable Transition type attribute values,
* <p>
* The Transition type determines whether the source state is exited in transitions
* whose target state is a descendant of the source state.
* </p>
* @see <a href="https://www.w3.org/TR/2015/REC-scxml-20150901/#transition">
* https://www.w3.org/TR/2015/REC-scxml-20150901/#transition</a>
*/
public enum TransitionType {
internal,
external
}
|
apache/commons-scxml
|
src/main/java/org/apache/commons/scxml2/model/TransitionType.java
|
Java
|
apache-2.0
| 1,273
|
package ro.isdc.wro.extensions.http;
import java.util.ArrayList;
import java.util.List;
import ro.isdc.wro.extensions.processor.css.Less4jProcessor;
import ro.isdc.wro.http.support.AbstractProcessorsFilter;
import ro.isdc.wro.model.resource.Resource;
import ro.isdc.wro.model.resource.ResourceType;
import ro.isdc.wro.model.resource.processor.ResourcePreProcessor;
/**
* A filter which transforms a less resource into css.
*
* @author Alex Objelean
* @since 1.7.4
* @created 20 Mar 2014
*/
public class Less4jFilter
extends AbstractProcessorsFilter {
private final List<ResourcePreProcessor> list = new ArrayList<ResourcePreProcessor>();
public Less4jFilter() {
list.add(new Less4jProcessor());
}
@Override
protected List<ResourcePreProcessor> getProcessorsList() {
return list;
}
@Override
protected Resource createResource(final String requestUri) {
return Resource.create(requestUri, ResourceType.CSS);
}
}
|
UAK-35/wro4j
|
wro4j-extensions/src/main/java/ro/isdc/wro/extensions/http/Less4jFilter.java
|
Java
|
apache-2.0
| 956
|
Puppet::Type.newtype(:quantum_dhcp_agent_config) do
ensurable
newparam(:name, :namevar => true) do
desc 'Section/setting name to manage from dhcp_agent.ini'
newvalues(/\S+\/\S+/)
end
newproperty(:value) do
desc 'The value of the setting to be defined.'
munge do |v|
v.to_s.strip
end
end
end
|
enovance/openstack-quantum-puppet
|
lib/puppet/type/quantum_dhcp_agent_config.rb
|
Ruby
|
apache-2.0
| 330
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/forecast/ForecastService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/forecast/model/PredictorExecution.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace ForecastService
{
namespace Model
{
/**
* <p>Contains details on the backtests performed to evaluate the accuracy of the
* predictor. The tests are returned in descending order of accuracy, with the most
* accurate backtest appearing first. You specify the number of backtests to
* perform when you call the operation.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/forecast-2018-06-26/PredictorExecutionDetails">AWS
* API Reference</a></p>
*/
class AWS_FORECASTSERVICE_API PredictorExecutionDetails
{
public:
PredictorExecutionDetails();
PredictorExecutionDetails(Aws::Utils::Json::JsonView jsonValue);
PredictorExecutionDetails& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>An array of the backtests performed to evaluate the accuracy of the predictor
* against a particular algorithm. The <code>NumberOfBacktestWindows</code> from
* the object determines the number of windows in the array.</p>
*/
inline const Aws::Vector<PredictorExecution>& GetPredictorExecutions() const{ return m_predictorExecutions; }
/**
* <p>An array of the backtests performed to evaluate the accuracy of the predictor
* against a particular algorithm. The <code>NumberOfBacktestWindows</code> from
* the object determines the number of windows in the array.</p>
*/
inline bool PredictorExecutionsHasBeenSet() const { return m_predictorExecutionsHasBeenSet; }
/**
* <p>An array of the backtests performed to evaluate the accuracy of the predictor
* against a particular algorithm. The <code>NumberOfBacktestWindows</code> from
* the object determines the number of windows in the array.</p>
*/
inline void SetPredictorExecutions(const Aws::Vector<PredictorExecution>& value) { m_predictorExecutionsHasBeenSet = true; m_predictorExecutions = value; }
/**
* <p>An array of the backtests performed to evaluate the accuracy of the predictor
* against a particular algorithm. The <code>NumberOfBacktestWindows</code> from
* the object determines the number of windows in the array.</p>
*/
inline void SetPredictorExecutions(Aws::Vector<PredictorExecution>&& value) { m_predictorExecutionsHasBeenSet = true; m_predictorExecutions = std::move(value); }
/**
* <p>An array of the backtests performed to evaluate the accuracy of the predictor
* against a particular algorithm. The <code>NumberOfBacktestWindows</code> from
* the object determines the number of windows in the array.</p>
*/
inline PredictorExecutionDetails& WithPredictorExecutions(const Aws::Vector<PredictorExecution>& value) { SetPredictorExecutions(value); return *this;}
/**
* <p>An array of the backtests performed to evaluate the accuracy of the predictor
* against a particular algorithm. The <code>NumberOfBacktestWindows</code> from
* the object determines the number of windows in the array.</p>
*/
inline PredictorExecutionDetails& WithPredictorExecutions(Aws::Vector<PredictorExecution>&& value) { SetPredictorExecutions(std::move(value)); return *this;}
/**
* <p>An array of the backtests performed to evaluate the accuracy of the predictor
* against a particular algorithm. The <code>NumberOfBacktestWindows</code> from
* the object determines the number of windows in the array.</p>
*/
inline PredictorExecutionDetails& AddPredictorExecutions(const PredictorExecution& value) { m_predictorExecutionsHasBeenSet = true; m_predictorExecutions.push_back(value); return *this; }
/**
* <p>An array of the backtests performed to evaluate the accuracy of the predictor
* against a particular algorithm. The <code>NumberOfBacktestWindows</code> from
* the object determines the number of windows in the array.</p>
*/
inline PredictorExecutionDetails& AddPredictorExecutions(PredictorExecution&& value) { m_predictorExecutionsHasBeenSet = true; m_predictorExecutions.push_back(std::move(value)); return *this; }
private:
Aws::Vector<PredictorExecution> m_predictorExecutions;
bool m_predictorExecutionsHasBeenSet;
};
} // namespace Model
} // namespace ForecastService
} // namespace Aws
|
awslabs/aws-sdk-cpp
|
aws-cpp-sdk-forecast/include/aws/forecast/model/PredictorExecutionDetails.h
|
C
|
apache-2.0
| 4,755
|
# Copyright 2014, 2015 SAP SE.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: //www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import pytest
from pyhdb.cursor import format_operation
from pyhdb.exceptions import ProgrammingError
import tests.helper
TABLE = 'PYHDB_TEST_1'
TABLE_FIELDS = 'TEST VARCHAR(255)'
@pytest.fixture
def test_table_1(request, connection):
"""Fixture to create table for testing, and dropping it after test run"""
tests.helper.create_table_fixture(request, connection, TABLE, TABLE_FIELDS)
@pytest.fixture
def content_table_1(request, connection):
"""Additional fixture to test_table_1, inserts some rows for testing"""
cursor = connection.cursor()
cursor.execute("insert into PYHDB_TEST_1 values('row1')")
cursor.execute("insert into PYHDB_TEST_1 values('row2')")
cursor.execute("insert into PYHDB_TEST_1 values('row3')")
@pytest.mark.parametrize("parameters", [
None,
(),
[]
])
def test_format_operation_without_parameters(parameters):
"""Test that providing no parameter produces correct result."""
operation = "SELECT * FROM TEST WHERE fuu = 'bar'"
assert format_operation(operation, parameters) == operation
def test_format_operation_with_positional_parameters():
"""Test that correct number of parameters produces correct result."""
assert format_operation(
"INSERT INTO TEST VALUES(%s, %s)", ('Hello World', 2)
) == "INSERT INTO TEST VALUES('Hello World', 2)"
def test_format_operation_with_too_few_positional_parameters_raises():
"""Test that providing too few parameters raises exception"""
with pytest.raises(ProgrammingError):
format_operation("INSERT INTO TEST VALUES(%s, %s)", ('Hello World',))
def test_format_operation_with_too_many_positional_parameters_raises():
"""Test that providing too many parameters raises exception"""
with pytest.raises(ProgrammingError):
format_operation("INSERT INTO TEST VALUES(%s)", ('Hello World', 2))
def test_format_operation_with_named_parameters():
"""format_operation() is used for Python style parameter expansion"""
assert format_operation(
"INSERT INTO TEST VALUES(%(name)s, %(val)s)",
{'name': 'Hello World', 'val': 2}
) == "INSERT INTO TEST VALUES('Hello World', 2)"
@pytest.mark.hanatest
def test_cursor_fetch_without_execution(connection):
cursor = connection.cursor()
with pytest.raises(ProgrammingError):
cursor.fetchone()
@pytest.mark.hanatest
def test_cursor_fetchall_single_row(connection):
cursor = connection.cursor()
cursor.execute("SELECT 1 FROM DUMMY")
result = cursor.fetchall()
assert result == [(1,)]
@pytest.mark.hanatest
def test_cursor_fetchall_multiple_rows(connection):
cursor = connection.cursor()
cursor.execute('SELECT "VIEW_NAME" FROM "PUBLIC"."VIEWS" LIMIT 10')
result = cursor.fetchall()
assert len(result) == 10
# Test cases for different parameter style expansion
#
# paramstyle Meaning
# ---------------------------------------------------------
# 1) qmark Question mark style, e.g. ...WHERE name=?
# 2) numeric Numeric, positional style, e.g. ...WHERE name=:1
# 3) named Named style, e.g. ...WHERE name=:name -> NOT IMPLEMENTED !!
# 4) format ANSI C printf format codes, e.g. ...WHERE name=%s
# 5) pyformat Python extended format codes, e.g. ...WHERE name=%(name)s
@pytest.mark.hanatest
def test_cursor_execute_with_params1(connection, test_table_1, content_table_1):
"""Test qmark parameter expansion style - uses cursor.prepare*() methods"""
# Note: use fetchall() to check that only one row gets returned
cursor = connection.cursor()
sql = 'select test from PYHDB_TEST_1 where test=?'
# correct way:
assert cursor.execute(sql, ['row2']).fetchall() == [('row2',)]
# invalid - extra unexpected parameter
with pytest.raises(ProgrammingError):
cursor.execute(sql, ['row2', 'extra']).fetchall()
@pytest.mark.hanatest
def test_cursor_execute_with_params2(connection, test_table_1, content_table_1):
"""Test numeric parameter expansion style - uses cursor.prepare() methods"""
# Note: use fetchall() to check that only one row gets returned
cursor = connection.cursor()
sql = 'select test from PYHDB_TEST_1 where test=?'
# correct way:
assert cursor.execute(sql, ['row2']).fetchall() == [('row2',)]
# invalid - extra unexpected parameter
with pytest.raises(ProgrammingError):
cursor.execute(sql, ['row2', 'extra']).fetchall()
@pytest.mark.hanatest
def test_cursor_execute_with_params4(connection, test_table_1, content_table_1):
"""Test format (positional) parameter expansion style"""
# Uses prepare_operation method
cursor = connection.cursor()
sql = 'select test from PYHDB_TEST_1 where test=%s'
# correct way:
assert cursor.execute(sql, ['row2']).fetchall() == [('row2',)]
# invalid - extra unexpected parameter
with pytest.raises(ProgrammingError):
cursor.execute(sql, ['row2', 'extra']).fetchall()
@pytest.mark.hanatest
def test_cursor_execute_with_params5(connection, test_table_1, content_table_1):
"""Test pyformat (named) parameter expansion style"""
# Note: use fetchall() to check that only one row gets returned
cursor = connection.cursor()
sql = 'select test from {} where test=%(test)s'.format(TABLE)
# correct way:
assert cursor.execute(sql, {'test': 'row2'}).fetchall() == [('row2',)]
# also correct way, additional dict value should just be ignored
assert cursor.execute(sql, {'test': 'row2', 'd': 2}).fetchall() == \
[('row2',)]
@pytest.mark.hanatest
def test_cursor_insert_commit(connection, test_table_1):
cursor = connection.cursor()
cursor.execute("SELECT COUNT(*) FROM %s" % TABLE)
assert cursor.fetchone() == (0,)
cursor.execute("INSERT INTO %s VALUES('Hello World')" % TABLE)
assert cursor.rowcount == 1
cursor.execute("SELECT COUNT(*) FROM %s" % TABLE)
assert cursor.fetchone() == (1,)
connection.commit()
@pytest.mark.hanatest
def test_cursor_create_and_drop_table(connection):
cursor = connection.cursor()
if tests.helper.exists_table(connection, TABLE):
cursor.execute('DROP TABLE "%s"' % TABLE)
assert not tests.helper.exists_table(connection, TABLE)
cursor.execute('CREATE TABLE "%s" ("TEST" VARCHAR(255))' % TABLE)
assert tests.helper.exists_table(connection, TABLE)
cursor.execute('DROP TABLE "%s"' % TABLE)
@pytest.mark.hanatest
def test_received_last_resultset_part_resets_after_execute(connection):
# The private attribute was not reseted to False after
# executing another statement
cursor = connection.cursor()
cursor.execute("SELECT 1 FROM DUMMY")
# Result is very small we got everything direct into buffer
assert cursor._received_last_resultset_part
cursor.execute("SELECT VIEW_NAME FROM PUBLIC.VIEWS")
# Result is not small enouth for single resultset part
assert not cursor._received_last_resultset_part
@pytest.mark.hanatest
@pytest.mark.parametrize("method", [
'fetchone',
'fetchall',
'fetchmany',
])
def test_fetch_raises_error_after_close(connection, method):
cursor = connection.cursor()
cursor.close()
with pytest.raises(ProgrammingError):
getattr(cursor, method)()
@pytest.mark.hanatest
def test_execute_raises_error_after_close(connection):
cursor = connection.cursor()
cursor.close()
with pytest.raises(ProgrammingError):
cursor.execute("SELECT TEST FROM DUMMY")
@pytest.mark.hanatest
def test_cursor_description_after_execution(connection):
cursor = connection.cursor()
assert cursor.description is None
cursor.execute("SELECT 'Hello World' AS TEST FROM DUMMY")
assert cursor.description == ((u'TEST', 9, None, 11, 0, None, 0),)
@pytest.mark.hanatest
def test_cursor_executemany_python_expansion(connection, test_table_1):
cursor = connection.cursor()
cursor.executemany(
"INSERT INTO {} VALUES(%s)".format(TABLE),
(
("Statement 1",),
("Statement 2",)
)
)
cursor.execute("SELECT * FROM %s" % TABLE)
result = cursor.fetchall()
assert result == [('Statement 1',), ('Statement 2',)]
@pytest.mark.hanatest
def test_cursor_executemany_hana_expansion(connection, test_table_1):
cursor = connection.cursor()
cursor.executemany(
"INSERT INTO %s VALUES(:1)" % TABLE,
(
("Statement 1",),
("Statement 2",)
)
)
cursor.execute("SELECT * FROM %s" % TABLE)
result = cursor.fetchall()
assert result == [('Statement 1',), ('Statement 2',)]
|
ralhei/PyHDB
|
tests/test_cursor.py
|
Python
|
apache-2.0
| 9,174
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/appmesh/AppMesh_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace AppMesh
{
namespace Model
{
/**
* <p>An object that represents metadata for a resource.</p><p><h3>See Also:</h3>
* <a
* href="http://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ResourceMetadata">AWS
* API Reference</a></p>
*/
class AWS_APPMESH_API ResourceMetadata
{
public:
ResourceMetadata();
ResourceMetadata(Aws::Utils::Json::JsonView jsonValue);
ResourceMetadata& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The full Amazon Resource Name (ARN) for the resource.</p>
*/
inline const Aws::String& GetArn() const{ return m_arn; }
/**
* <p>The full Amazon Resource Name (ARN) for the resource.</p>
*/
inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }
/**
* <p>The full Amazon Resource Name (ARN) for the resource.</p>
*/
inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }
/**
* <p>The full Amazon Resource Name (ARN) for the resource.</p>
*/
inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }
/**
* <p>The full Amazon Resource Name (ARN) for the resource.</p>
*/
inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }
/**
* <p>The full Amazon Resource Name (ARN) for the resource.</p>
*/
inline ResourceMetadata& WithArn(const Aws::String& value) { SetArn(value); return *this;}
/**
* <p>The full Amazon Resource Name (ARN) for the resource.</p>
*/
inline ResourceMetadata& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}
/**
* <p>The full Amazon Resource Name (ARN) for the resource.</p>
*/
inline ResourceMetadata& WithArn(const char* value) { SetArn(value); return *this;}
/**
* <p>The Unix epoch timestamp in seconds for when the resource was created.</p>
*/
inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; }
/**
* <p>The Unix epoch timestamp in seconds for when the resource was created.</p>
*/
inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; }
/**
* <p>The Unix epoch timestamp in seconds for when the resource was created.</p>
*/
inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; }
/**
* <p>The Unix epoch timestamp in seconds for when the resource was created.</p>
*/
inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); }
/**
* <p>The Unix epoch timestamp in seconds for when the resource was created.</p>
*/
inline ResourceMetadata& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;}
/**
* <p>The Unix epoch timestamp in seconds for when the resource was created.</p>
*/
inline ResourceMetadata& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;}
/**
* <p>The Unix epoch timestamp in seconds for when the resource was last
* updated.</p>
*/
inline const Aws::Utils::DateTime& GetLastUpdatedAt() const{ return m_lastUpdatedAt; }
/**
* <p>The Unix epoch timestamp in seconds for when the resource was last
* updated.</p>
*/
inline bool LastUpdatedAtHasBeenSet() const { return m_lastUpdatedAtHasBeenSet; }
/**
* <p>The Unix epoch timestamp in seconds for when the resource was last
* updated.</p>
*/
inline void SetLastUpdatedAt(const Aws::Utils::DateTime& value) { m_lastUpdatedAtHasBeenSet = true; m_lastUpdatedAt = value; }
/**
* <p>The Unix epoch timestamp in seconds for when the resource was last
* updated.</p>
*/
inline void SetLastUpdatedAt(Aws::Utils::DateTime&& value) { m_lastUpdatedAtHasBeenSet = true; m_lastUpdatedAt = std::move(value); }
/**
* <p>The Unix epoch timestamp in seconds for when the resource was last
* updated.</p>
*/
inline ResourceMetadata& WithLastUpdatedAt(const Aws::Utils::DateTime& value) { SetLastUpdatedAt(value); return *this;}
/**
* <p>The Unix epoch timestamp in seconds for when the resource was last
* updated.</p>
*/
inline ResourceMetadata& WithLastUpdatedAt(Aws::Utils::DateTime&& value) { SetLastUpdatedAt(std::move(value)); return *this;}
/**
* <p>The AWS IAM account ID of the service mesh owner. If the account ID is not
* your own, then it's the ID of the account that shared the mesh with your
* account. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline const Aws::String& GetMeshOwner() const{ return m_meshOwner; }
/**
* <p>The AWS IAM account ID of the service mesh owner. If the account ID is not
* your own, then it's the ID of the account that shared the mesh with your
* account. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline bool MeshOwnerHasBeenSet() const { return m_meshOwnerHasBeenSet; }
/**
* <p>The AWS IAM account ID of the service mesh owner. If the account ID is not
* your own, then it's the ID of the account that shared the mesh with your
* account. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline void SetMeshOwner(const Aws::String& value) { m_meshOwnerHasBeenSet = true; m_meshOwner = value; }
/**
* <p>The AWS IAM account ID of the service mesh owner. If the account ID is not
* your own, then it's the ID of the account that shared the mesh with your
* account. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline void SetMeshOwner(Aws::String&& value) { m_meshOwnerHasBeenSet = true; m_meshOwner = std::move(value); }
/**
* <p>The AWS IAM account ID of the service mesh owner. If the account ID is not
* your own, then it's the ID of the account that shared the mesh with your
* account. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline void SetMeshOwner(const char* value) { m_meshOwnerHasBeenSet = true; m_meshOwner.assign(value); }
/**
* <p>The AWS IAM account ID of the service mesh owner. If the account ID is not
* your own, then it's the ID of the account that shared the mesh with your
* account. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline ResourceMetadata& WithMeshOwner(const Aws::String& value) { SetMeshOwner(value); return *this;}
/**
* <p>The AWS IAM account ID of the service mesh owner. If the account ID is not
* your own, then it's the ID of the account that shared the mesh with your
* account. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline ResourceMetadata& WithMeshOwner(Aws::String&& value) { SetMeshOwner(std::move(value)); return *this;}
/**
* <p>The AWS IAM account ID of the service mesh owner. If the account ID is not
* your own, then it's the ID of the account that shared the mesh with your
* account. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline ResourceMetadata& WithMeshOwner(const char* value) { SetMeshOwner(value); return *this;}
/**
* <p>The AWS IAM account ID of the resource owner. If the account ID is not your
* own, then it's the ID of the mesh owner or of another account that the mesh is
* shared with. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline const Aws::String& GetResourceOwner() const{ return m_resourceOwner; }
/**
* <p>The AWS IAM account ID of the resource owner. If the account ID is not your
* own, then it's the ID of the mesh owner or of another account that the mesh is
* shared with. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline bool ResourceOwnerHasBeenSet() const { return m_resourceOwnerHasBeenSet; }
/**
* <p>The AWS IAM account ID of the resource owner. If the account ID is not your
* own, then it's the ID of the mesh owner or of another account that the mesh is
* shared with. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline void SetResourceOwner(const Aws::String& value) { m_resourceOwnerHasBeenSet = true; m_resourceOwner = value; }
/**
* <p>The AWS IAM account ID of the resource owner. If the account ID is not your
* own, then it's the ID of the mesh owner or of another account that the mesh is
* shared with. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline void SetResourceOwner(Aws::String&& value) { m_resourceOwnerHasBeenSet = true; m_resourceOwner = std::move(value); }
/**
* <p>The AWS IAM account ID of the resource owner. If the account ID is not your
* own, then it's the ID of the mesh owner or of another account that the mesh is
* shared with. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline void SetResourceOwner(const char* value) { m_resourceOwnerHasBeenSet = true; m_resourceOwner.assign(value); }
/**
* <p>The AWS IAM account ID of the resource owner. If the account ID is not your
* own, then it's the ID of the mesh owner or of another account that the mesh is
* shared with. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline ResourceMetadata& WithResourceOwner(const Aws::String& value) { SetResourceOwner(value); return *this;}
/**
* <p>The AWS IAM account ID of the resource owner. If the account ID is not your
* own, then it's the ID of the mesh owner or of another account that the mesh is
* shared with. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline ResourceMetadata& WithResourceOwner(Aws::String&& value) { SetResourceOwner(std::move(value)); return *this;}
/**
* <p>The AWS IAM account ID of the resource owner. If the account ID is not your
* own, then it's the ID of the mesh owner or of another account that the mesh is
* shared with. For more information about mesh sharing, see <a
* href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
* with shared meshes</a>.</p>
*/
inline ResourceMetadata& WithResourceOwner(const char* value) { SetResourceOwner(value); return *this;}
/**
* <p>The unique identifier for the resource.</p>
*/
inline const Aws::String& GetUid() const{ return m_uid; }
/**
* <p>The unique identifier for the resource.</p>
*/
inline bool UidHasBeenSet() const { return m_uidHasBeenSet; }
/**
* <p>The unique identifier for the resource.</p>
*/
inline void SetUid(const Aws::String& value) { m_uidHasBeenSet = true; m_uid = value; }
/**
* <p>The unique identifier for the resource.</p>
*/
inline void SetUid(Aws::String&& value) { m_uidHasBeenSet = true; m_uid = std::move(value); }
/**
* <p>The unique identifier for the resource.</p>
*/
inline void SetUid(const char* value) { m_uidHasBeenSet = true; m_uid.assign(value); }
/**
* <p>The unique identifier for the resource.</p>
*/
inline ResourceMetadata& WithUid(const Aws::String& value) { SetUid(value); return *this;}
/**
* <p>The unique identifier for the resource.</p>
*/
inline ResourceMetadata& WithUid(Aws::String&& value) { SetUid(std::move(value)); return *this;}
/**
* <p>The unique identifier for the resource.</p>
*/
inline ResourceMetadata& WithUid(const char* value) { SetUid(value); return *this;}
/**
* <p>The version of the resource. Resources are created at version 1, and this
* version is incremented each time that they're updated.</p>
*/
inline long long GetVersion() const{ return m_version; }
/**
* <p>The version of the resource. Resources are created at version 1, and this
* version is incremented each time that they're updated.</p>
*/
inline bool VersionHasBeenSet() const { return m_versionHasBeenSet; }
/**
* <p>The version of the resource. Resources are created at version 1, and this
* version is incremented each time that they're updated.</p>
*/
inline void SetVersion(long long value) { m_versionHasBeenSet = true; m_version = value; }
/**
* <p>The version of the resource. Resources are created at version 1, and this
* version is incremented each time that they're updated.</p>
*/
inline ResourceMetadata& WithVersion(long long value) { SetVersion(value); return *this;}
private:
Aws::String m_arn;
bool m_arnHasBeenSet;
Aws::Utils::DateTime m_createdAt;
bool m_createdAtHasBeenSet;
Aws::Utils::DateTime m_lastUpdatedAt;
bool m_lastUpdatedAtHasBeenSet;
Aws::String m_meshOwner;
bool m_meshOwnerHasBeenSet;
Aws::String m_resourceOwner;
bool m_resourceOwnerHasBeenSet;
Aws::String m_uid;
bool m_uidHasBeenSet;
long long m_version;
bool m_versionHasBeenSet;
};
} // namespace Model
} // namespace AppMesh
} // namespace Aws
|
aws/aws-sdk-cpp
|
aws-cpp-sdk-appmesh/include/aws/appmesh/model/ResourceMetadata.h
|
C
|
apache-2.0
| 15,421
|
/*
* 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.uima.simpleserver.output;
import java.util.List;
/*
* Represent the result of analysis. The result is the input text plus a list of metadata.
*/
public interface Result {
/*
*
*/
public List<ResultEntry> getResultEntries();
/*
* the whole text passed to the analysis engine
*/
public String getText();
}
|
apache/uima-addons
|
SimpleServer/src/main/java/org/apache/uima/simpleserver/output/Result.java
|
Java
|
apache-2.0
| 1,162
|
// Copyright 2014 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Directive for pie chart visualization.
*/
angular.module('oppia').component('pieChart', {
bindings: {
// A read-only array representing the table of chart data.
data: '&',
// A read-only object containing several chart options. This object
// should have the following keys: pieHole, pieSliceTextStyleColor,
// chartAreaWidth, colors, height, legendPosition, width.
options: '&'
},
controller: ['$element', '$scope', 'WindowDimensionsService', function(
$element, $scope, WindowDimensionsService) {
var ctrl = this;
ctrl.resizeSubscription = null;
ctrl.$onInit = function() {
if (!$.isArray(ctrl.data())) {
return;
}
var options = ctrl.options();
var chart = null;
var redrawChart = function() {
if (chart !== null) {
chart.draw(google.visualization.arrayToDataTable(ctrl.data()), {
title: options.title,
pieHole: options.pieHole,
pieSliceTextStyle: {
color: options.pieSliceTextStyleColor,
},
pieSliceBorderColor: options.pieSliceBorderColor,
pieSliceText: 'none',
chartArea: {
left: options.left,
width: options.chartAreaWidth
},
colors: options.colors,
height: options.height,
legend: {
position: options.legendPosition || 'none'
},
width: options.width
});
}
};
// Need to wait for load statement in editor template to finish.
// https://stackoverflow.com/questions/42714876/
google.charts.setOnLoadCallback(function() {
if (!chart) {
chart = new google.visualization.PieChart($element[0]);
redrawChart();
$scope.$applyAsync();
}
});
$scope.$watch('data()', redrawChart);
ctrl.resizeSubscription = WindowDimensionsService.getResizeEvent()
.subscribe(evt => {
redrawChart();
$scope.$applyAsync();
});
};
ctrl.$onDestroy = function() {
if (ctrl.resizeSubscription) {
ctrl.resizeSubscription.unsubscribe();
}
};
}]
});
|
brianrodri/oppia
|
core/templates/pages/exploration-editor-page/statistics-tab/charts/pie-chart.component.ts
|
TypeScript
|
apache-2.0
| 2,859
|
package org.apereo.cas.ticket.registry.queue;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.extern.slf4j.Slf4j;
import org.apereo.cas.StringBean;
import org.apereo.cas.ticket.Ticket;
import org.apereo.cas.ticket.registry.TicketRegistry;
/**
* This is {@link AddTicketMessageQueueCommand}.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@Slf4j
public class AddTicketMessageQueueCommand extends BaseMessageQueueCommand {
@JsonProperty
private Ticket ticket;
@JsonCreator
public AddTicketMessageQueueCommand(@JsonProperty("id") final StringBean id, @JsonProperty("ticket") final Ticket ticket) {
super(id);
this.ticket = ticket;
}
public Ticket getTicket() {
return ticket;
}
@Override
public void execute(final TicketRegistry registry) {
LOGGER.debug("Executing queue command on ticket registry id [{}] to add ticket [{}]", getId().getId(), ticket);
registry.addTicket(ticket);
}
}
|
dodok1/cas
|
support/cas-server-support-jms-ticket-registry/src/main/java/org/apereo/cas/ticket/registry/queue/AddTicketMessageQueueCommand.java
|
Java
|
apache-2.0
| 1,178
|
#include <catch.hpp>
#include <chi/Context.hpp>
#include <chi/GraphFunction.hpp>
#include <chi/GraphModule.hpp>
#include <chi/GraphStruct.hpp>
#include <chi/LangModule.hpp>
#include <chi/NodeInstance.hpp>
#include <chi/NodeType.hpp>
#include <chi/Support/Result.hpp>
using namespace chi;
using namespace nlohmann;
TEST_CASE("Create and manipulate local varables in GraphFunctions", "") {
Context c;
Result res;
res += c.loadModule("lang");
REQUIRE(!!res);
auto& langMod = *c.langModule();
auto mod = c.newGraphModule("test/main");
auto func = mod->getOrCreateFunction("main", {}, {}, {"In Exec"}, {"Out Exec"});
REQUIRE(func->localVariables().size() == 0);
REQUIRE_FALSE(func->localVariableFromName("var").valid());
WHEN("We add a local variable everything should be OK") {
bool inserted;
auto ty = func->getOrCreateLocalVariable("var", langMod.typeFromName("i32"), &inserted);
REQUIRE(ty.valid() == true);
REQUIRE(inserted == true);
REQUIRE(ty.name == "var");
REQUIRE(ty.type == langMod.typeFromName("i32"));
REQUIRE(func->localVariables().size() == 1);
REQUIRE(func->localVariables()[0] == ty);
REQUIRE(func->localVariableFromName("var") == ty);
WHEN("We add some set and get nodes") {
NodeInstance* setInst = nullptr;
res = func->insertNode("test/main", "_set_var", "lang:i32", 0.f, 0.f, Uuid::random(),
&setInst);
REQUIRE(!!res);
REQUIRE(setInst != nullptr);
REQUIRE_FALSE(setInst->type().pure());
REQUIRE(setInst->type().execInputs().size() == 1);
REQUIRE(setInst->type().execOutputs().size() == 1);
REQUIRE(setInst->type().dataInputs().size() == 1);
REQUIRE(setInst->type().dataInputs()[0].type == langMod.typeFromName("i32"));
REQUIRE(setInst->type().dataOutputs().size() == 0);
NodeInstance* getInst = nullptr;
res = func->insertNode("test/main", "_get_var", "lang:i32", 0.f, 0.f, Uuid::random(),
&getInst);
REQUIRE(!!res);
REQUIRE(getInst != nullptr);
REQUIRE(getInst->type().pure());
REQUIRE(getInst->type().dataOutputs().size() == 1);
REQUIRE(getInst->type().dataOutputs()[0].type == langMod.typeFromName("i32"));
REQUIRE(getInst->type().dataInputs().size() == 0);
REQUIRE(func->nodes().size() == 2);
WHEN("We add another local var with the name var inserted should be false") {
auto ty2 =
func->getOrCreateLocalVariable("var", langMod.typeFromName("i8*"), &inserted);
REQUIRE(inserted == false);
REQUIRE(ty2.name == "var");
REQUIRE(ty2.type == langMod.typeFromName("i32"));
REQUIRE(ty2 == ty);
}
WHEN("We remove that variable") {
REQUIRE(func->removeLocalVariable("var"));
REQUIRE(func->localVariables().size() == 0);
REQUIRE_FALSE(func->localVariableFromName("var").valid());
THEN("The get and set nodes should be deleted") {
REQUIRE(func->nodes().size() == 0);
}
}
WHEN("We we rename that variable") {
func->renameLocalVariable("var", "thevar");
// it should have retyped the nodes
REQUIRE(func->nodes().size() == 2);
REQUIRE(setInst->type().name() == "_set_thevar");
REQUIRE(getInst->type().name() == "_get_thevar");
}
WHEN("We retype that variable") {
func->retypeLocalVariable("var", langMod.typeFromName("i1"));
// it should have retyped the nodes
REQUIRE(func->nodes().size() == 2);
REQUIRE(setInst->type().name() == "_set_var");
REQUIRE(getInst->type().name() == "_get_var");
REQUIRE_FALSE(setInst->type().pure());
REQUIRE(setInst->type().execInputs().size() == 1);
REQUIRE(setInst->type().execOutputs().size() == 1);
REQUIRE(setInst->type().dataInputs().size() == 1);
REQUIRE(setInst->type().dataInputs()[0].type == langMod.typeFromName("i1"));
REQUIRE(setInst->type().dataOutputs().size() == 0);
REQUIRE(getInst->type().pure());
REQUIRE(getInst->type().dataOutputs().size() == 1);
REQUIRE(getInst->type().dataOutputs()[0].type == langMod.typeFromName("i1"));
REQUIRE(getInst->type().dataInputs().size() == 0);
}
WHEN("We remove the wrong name") {
REQUIRE_FALSE(func->removeLocalVariable("notvar"));
REQUIRE(func->localVariables().size() == 1);
REQUIRE(func->localVariables()[0] == ty);
REQUIRE(func->localVariableFromName("var") == ty);
REQUIRE(func->nodes().size() == 2);
}
}
}
}
|
chigraph/chigraph
|
test/GraphFunctionLocalsTest.cpp
|
C++
|
apache-2.0
| 4,354
|
/**
* This header is generated by class-dump-z 0.2a.
* class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3.
*
* Source: /System/Library/PrivateFrameworks/BackRow.framework/BackRow
*/
#import "BackRow-Structs.h"
#import "BRControl.h"
@class BRListControl, BRDropShadowControl;
__attribute__((visibility("hidden")))
@interface BRBoxListControl : BRControl {
@private
BRListControl *_list; // 40 = 0x28
BRDropShadowControl *_shadow; // 44 = 0x2c
}
@property(retain) id providers; // G=0x315dfe81; S=0x315dfea1; converted property
- (id)init; // 0x315e09d5
- (void)dealloc; // 0x315dff09
- (void)layoutSubcontrols; // 0x315e0b61
- (float)listHeightToMaximum:(float)maximum; // 0x315dfe61
// converted property getter: - (id)providers; // 0x315dfe81
- (void)setProvider:(id)provider; // 0x315dfed5
// converted property setter: - (void)setProviders:(id)providers; // 0x315dfea1
@end
|
bboyle18/AppleTV-LiveTV
|
theos/include/BackRow/BRBoxListControl.h
|
C
|
apache-2.0
| 906
|
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.behindscenes.step5;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.ModelLoader;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.graphics.g3d.model.data.ModelData;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.TextureProvider;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.JsonReader;
/**
* See: http://blog.xoppa.com/behind-the-3d-scenes-part2/
* @author Xoppa
*/
public class BehindTheScenesTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public Model model;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public Array<ModelInstance> blocks = new Array<ModelInstance>();
public Array<ModelInstance> invaders = new Array<ModelInstance>();
public ModelInstance ship;
public ModelInstance space;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader());
ModelData modelData = modelLoader.loadModelData(Gdx.files.internal(data+"/invaderscene.g3dj"));
model = new Model(modelData, new TextureProvider.FileTextureProvider());
doneLoading();
}
private void doneLoading() {
for (int i = 0; i < model.nodes.size; i++) {
String id = model.nodes.get(i).id;
ModelInstance instance = new ModelInstance(model, id);
Node node = instance.getNode(id);
instance.transform.set(node.globalTransform);
node.translation.set(0,0,0);
node.scale.set(1,1,1);
node.rotation.idt();
instance.calculateTransforms();
if (id.equals("space")) {
space = instance;
continue;
}
instances.add(instance);
if (id.equals("ship"))
ship = instance;
else if (id.startsWith("block"))
blocks.add(instance);
else if (id.startsWith("invader"))
invaders.add(instance);
}
for (ModelInstance block : blocks) {
float r = 0.5f + 0.5f * (float)Math.random();
float g = 0.5f + 0.5f * (float)Math.random();
float b = 0.5f + 0.5f * (float)Math.random();
block.materials.get(0).set(ColorAttribute.createDiffuse(r, g, b, 1));
}
}
@Override
public void render () {
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
modelBatch.render(instances, environment);
if (space != null)
modelBatch.render(space);
modelBatch.end();
}
@Override
public void dispose () {
modelBatch.dispose();
instances.clear();
model.dispose();
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
}
|
JuudeDemos/blog
|
tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step5/BehindTheScenesTest.java
|
Java
|
apache-2.0
| 5,226
|
/*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.spi.impl;
import com.hazelcast.spi.FragmentedMigrationAwareService;
import com.hazelcast.spi.MigrationAwareService;
import com.hazelcast.spi.Operation;
import com.hazelcast.spi.PartitionMigrationEvent;
import com.hazelcast.spi.PartitionReplicationEvent;
import com.hazelcast.spi.ServiceNamespace;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A {@link MigrationAwareService} that delegates to another {@link MigrationAwareService} and keeps track of the number of
* migrations concerning the partition owner (either as current or new replica index) currently in-flight.
*/
public class CountingMigrationAwareService implements FragmentedMigrationAwareService {
static final int PRIMARY_REPLICA_INDEX = 0;
static final int IN_FLIGHT_MIGRATION_STAMP = -1;
private final FragmentedMigrationAwareService migrationAwareService;
// number of started migrations on the partition owner
private final AtomicInteger ownerMigrationsStarted;
// number of completed migrations on the partition owner
private final AtomicInteger ownerMigrationsCompleted;
public CountingMigrationAwareService(FragmentedMigrationAwareService migrationAwareService) {
this.migrationAwareService = migrationAwareService;
this.ownerMigrationsStarted = new AtomicInteger();
this.ownerMigrationsCompleted = new AtomicInteger();
}
@Override
public Collection<ServiceNamespace> getAllServiceNamespaces(PartitionReplicationEvent event) {
return migrationAwareService.getAllServiceNamespaces(event);
}
@Override
public boolean isKnownServiceNamespace(ServiceNamespace namespace) {
return migrationAwareService.isKnownServiceNamespace(namespace);
}
@Override
public Operation prepareReplicationOperation(PartitionReplicationEvent event) {
return migrationAwareService.prepareReplicationOperation(event);
}
@Override
public Operation prepareReplicationOperation(PartitionReplicationEvent event,
Collection<ServiceNamespace> namespaces) {
return migrationAwareService.prepareReplicationOperation(event, namespaces);
}
@Override
public void beforeMigration(PartitionMigrationEvent event) {
if (isPrimaryReplicaMigrationEvent(event)) {
ownerMigrationsStarted.incrementAndGet();
}
migrationAwareService.beforeMigration(event);
}
@Override
public void commitMigration(PartitionMigrationEvent event) {
try {
migrationAwareService.commitMigration(event);
} finally {
if (isPrimaryReplicaMigrationEvent(event)) {
int completed = ownerMigrationsCompleted.incrementAndGet();
assert completed <= ownerMigrationsStarted.get();
}
}
}
@Override
public void rollbackMigration(PartitionMigrationEvent event) {
try {
migrationAwareService.rollbackMigration(event);
} finally {
if (isPrimaryReplicaMigrationEvent(event)) {
int completed = ownerMigrationsCompleted.incrementAndGet();
assert completed <= ownerMigrationsStarted.get();
}
}
}
/**
* Returns whether event involves primary replica migration.
* @param event migration event
* @return true if migration involves primary replica, false otherwise
*/
static boolean isPrimaryReplicaMigrationEvent(PartitionMigrationEvent event) {
return (event.getCurrentReplicaIndex() == PRIMARY_REPLICA_INDEX || event.getNewReplicaIndex() == PRIMARY_REPLICA_INDEX);
}
/**
* Returns a stamp to denote current migration state which can later be validated
* using {@link #validateMigrationStamp(int)}.
*
* @return migration stamp
*/
public int getMigrationStamp() {
int completed = ownerMigrationsCompleted.get();
int started = ownerMigrationsStarted.get();
return completed == started ? completed : IN_FLIGHT_MIGRATION_STAMP;
}
/**
* Returns true if there's no primary replica migrations started and/or completed
* since issuance of the given stamp. Otherwise returns false, if there's an ongoing migration
* when stamp is issued or a new migration is started (and optionally completed) after stamp is issued.
*
* @param stamp a stamp
* @return true stamp is valid since issuance of the given stamp, false otherwise
*/
public boolean validateMigrationStamp(int stamp) {
int completed = ownerMigrationsCompleted.get();
int started = ownerMigrationsStarted.get();
return stamp == completed && stamp == started;
}
}
|
juanavelez/hazelcast
|
hazelcast/src/main/java/com/hazelcast/spi/impl/CountingMigrationAwareService.java
|
Java
|
apache-2.0
| 5,378
|
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.provisioning;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
* @since 5.0
*/
@ExtendWith(SpringExtension.class)
public class UserDetailsManagerResourceFactoryBeanPropertiesResourceLocationITests {
@Autowired
UserDetailsManager users;
@Test
public void loadUserByUsernameWhenUserFoundThenNotNull() {
assertThat(this.users.loadUserByUsername("user")).isNotNull();
}
@Configuration
static class Config {
@Bean
UserDetailsManagerResourceFactoryBean userDetailsService() {
return UserDetailsManagerResourceFactoryBean.fromResourceLocation("classpath:users.properties");
}
}
}
|
djechelon/spring-security
|
config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanPropertiesResourceLocationITests.java
|
Java
|
apache-2.0
| 1,707
|
/*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.lang.reflect;
public interface IPropertyInfo extends IAttributedFeatureInfo, IIntrinsicTypeReference
{
/**
* @return true if the property is readable given the visibility constraint passed in,
* false otherwise.
*/
public boolean isReadable();
/**
* @return True if the property is writable given the visibility constraint passed in,
* false otherwise.
*/
public boolean isWritable();
/**
* @param whosAskin The type querying the property writability. For example, passing in the type the property is on will
* allow properties that have private access in the setter to be written to. Passing in an unrelated type will only
* allow properties that are public to be written to.
*
* @return True if the property is writable given the visibility constraint passed in,
* false otherwise.
*/
public boolean isWritable( IType whosAskin );
/**
* @return the PropertyAccessor (for getting and setting) this property.
*/
public IPropertyAccessor getAccessor();
public IPresentationInfo getPresentationInfo();
}
|
pdalbora/gosu-lang
|
gosu-core-api/src/main/java/gw/lang/reflect/IPropertyInfo.java
|
Java
|
apache-2.0
| 1,163
|
/*
* Copyright (C) 2013 Salzburg Research.
*
* 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.
*/
(function ($) {
AjaxSolr.theme.prototype.result = function (doc, snippet) {
var output = '<div><h3 class="supertitle"><p id="links_' + doc.id + '"class="metainfo"></p></h3>';
if (__configuration.results.title && __configuration.results.title != "") {
if (__configuration.results.link && __configuration.results.link != "") {
output += '<h4 class="title"> <a href="'+doc[__configuration.results.link]+'">' + doc[__configuration.results.title] + '</a></h4>';
} else {
output += '<h4 class="title">' + doc[__configuration.results.title] + '</h4>';
}
}
if (__configuration.results.author && __configuration.results.author != "") {
output += '<h5>by '+doc[__configuration.results.author]+'</h5>';
}
if(__configuration.results.thumb && __configuration.results.thumb != "" && doc[__configuration.results.thumb]) {
output += '<img class="left" src="'+doc[__configuration.results.thumb]+'"/>';
}
if (snippet) {
output += '<p class="preview">' + snippet + '</p>';
}
if (__configuration.results.created && __configuration.results.created != "") {
var date = new Date(doc[__configuration.results.created]);
var yesterday = new Date();
yesterday.setDate(yesterday.getDate()-1);
var strDate;
if (date.strftime('%x') == yesterday.strftime('%x')) {
strDate = "gestern";
} else {
strDate = date.strftime('%x');
}
output += '<p class="meta">' + 'created: ' + strDate + '</div></li>';
}
return output;
};
AjaxSolr.theme.prototype.snippet = function (doc, response) {
if (!__configuration.results.description || __configuration.results.description == "") return null;
if (response && response.highlighting && response.highlighting[doc.id] && response.highlighting[doc.id][__configuration.results.description]) {
var desc = response.highlighting[doc.id][__configuration.results.description];
if (!desc) return null;
else return desc + '';
} else {
var desc = doc[__configuration.results.description];
if (!desc) return null;
var output = '';
if (desc.length > 300) {
output += desc.substring(0, 300) + " " + "...";
output += '<span style="display:none;">' + desc.substring(300);
output += '</span> <a href="#" class="more">[read more]</a>';
} else {
output += desc;
}
return output;
}
return null;
};
AjaxSolr.theme.prototype.tag = function (facet, weight, handler) {
var title = facet.value;
if (title.length > 30) {
title = title.substring(0,30) + "...";
}
var output = $('<li/>', {"class":(facet.active?"checked":"notchecked")}).append($('<a class="" href="#">' + title + '</a>').click(handler)).append('<span class="checkbox"></span>' + '<span class="facNum">' + facet.count + '</span>');
return output;
};
AjaxSolr.theme.prototype.facet_link = function (value, handler) {
return $('<a href="#"/>').text(value).click(handler);
};
AjaxSolr.theme.prototype.no_items_found = function () {
return 'no items found in current selection';
};
})(jQuery);
|
wikier/marmotta-search
|
src/main/resources/web/configurator/js/search.theme.js
|
JavaScript
|
apache-2.0
| 3,764
|
export * from 'backbone-decorators';
export function protoprop(target, name, descriptor) {
target[name] = descriptor.initializer();
}
export function behavior(name, config = {}) {
return function({prototype}) {
prototype.behaviors = Object.assign({
[name]: config
}, prototype.behaviors);
};
}
export function className(name) {
return function(target) {
target.prototype.className = name;
};
}
export function region(selector) {
return function(target, name, descriptor) {
delete descriptor.initializer;
descriptor.writable = true;
target.regions = Object.assign({
[name]: selector
}, target.regions);
};
}
|
allure-framework/allure1
|
allure-report-face/src/decorators/index.js
|
JavaScript
|
apache-2.0
| 719
|
<?php
$thisurl = ADMIN_URL.'user.php';
?>
<style type="text/css"> .contentbox table th{ font-size:12px; text-align:center}</style>
<div class="contentbox">
<table cellspacing="2" cellpadding="5" width="100%">
<tr>
<th colspan="6" align="left" style="text-align:left">分红列表</th>
</tr>
<tr>
<th width="50"><label><input type="checkbox" class="quxuanall" value="checkbox" />编号</label></th>
<th>营业额</th>
<th>人数</th>
<th>金额</th>
<th>时间</th>
<th width="50">操作</th>
</tr>
<?php if(!empty($rt))foreach($rt as $row){?>
<tr>
<td><input type="checkbox" name="quanxuan" value="<?php echo $row['id'];?>" class="gids"/></td>
<td><?php echo $row['sum'];?></td>
<td><?php echo $row['count'];?></td>
<td><?php echo $row['percent'];?></td>
<td><?php echo date('Y-m-d H:i:s',$row['linetime']);?></td>
<td><a href="<?php echo ADMIN_URL.'user.php?type=user_bonus_detail&id='.$row['id'];?>"><img src="<?php echo $this->img('icon_view.gif');?>" title="明细" alt="明细" id="<?php echo $row['id'];?>"/></a></td>
</tr>
<?php } ?>
</table>
<?php $this->element('page',array('pagelink'=>$pagelink));?>
</div>
<script type="text/javascript">
//全选
$('.quxuanall').click(function (){
if(this.checked==true){
$("input[name='quanxuan']").each(function(){this.checked=true;});
document.getElementById("bathdel").disabled = false;
}else{
$("input[name='quanxuan']").each(function(){this.checked=false;});
document.getElementById("bathdel").disabled = true;
}
});
</script>
|
zhaoshengloveqingqing/fenxiao
|
admin/app/user/template/user_bonus_list.php
|
PHP
|
apache-2.0
| 1,609
|
/*!
* ${copyright}
*/
sap.ui.define(['sap/ui/unified/calendar/CalendarDate', 'sap/ui/core/date/UniversalDate'],
function(CalendarDate, UniversalDate) {
"use strict";
/*
* Inside the YearPickerRenderer CalendarDate objects are used. But in the API JS dates are used.
* So conversion must be done on API functions.
*/
/**
* YearPicker renderer.
* @namespace
*/
var YearPickerRenderer = {
};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
* @param {sap.ui.unified.calendar.YearPicker} oYP an object representation of the control that should be rendered
*/
YearPickerRenderer.render = function(oRm, oYP){
var sTooltip = oYP.getTooltip_AsString();
var sId = oYP.getId();
var oCurrentDate = oYP._getDate();
var iCurrentYear = oCurrentDate.getYear();
var iYears = oYP.getYears();
var iColumns = oYP.getColumns();
var sWidth = "";
oRm.write("<div");
oRm.writeControlData(oYP);
oRm.addClass("sapUiCalYearPicker");
oRm.writeClasses();
if (sTooltip) {
oRm.writeAttributeEscaped('title', sTooltip);
}
oRm.writeAccessibilityState(oYP, {
role: "grid",
readonly: "true",
multiselectable: "false"
});
oRm.write(">"); // div element
var oDate = new CalendarDate(oCurrentDate, oYP.getPrimaryCalendarType());
oDate.setYear(oDate.getYear() - Math.floor(iYears / 2));
var bEnabledCheck = false; // check for disabled years only needed if borders touched
var oFirstDate = oYP._checkFirstDate(oDate);
if (!oFirstDate.isSame(oDate)) {
oDate = oFirstDate;
bEnabledCheck = true;
}
if (iColumns > 0) {
sWidth = ( 100 / iColumns ) + "%";
} else {
sWidth = ( 100 / iYears ) + "%";
}
for ( var i = 0; i < iYears; i++) {
var sYyyymmdd = oYP._oFormatYyyymmdd.format(oDate.toUTCJSDate(), true);
var mAccProps = {
role: "gridcell"
};
var bEnabled = true;
if (bEnabledCheck) {
bEnabled = oYP._checkDateEnabled(oDate);
}
if (iColumns > 0 && i % iColumns == 0) {
// begin of row
oRm.write("<div");
oRm.writeAccessibilityState(null, {role: "row"});
oRm.write(">"); // div element
}
oRm.write("<div");
oRm.writeAttribute("id", sId + "-y" + sYyyymmdd);
oRm.addClass("sapUiCalItem");
if ( oDate.getYear() == iCurrentYear) {
oRm.addClass("sapUiCalItemSel");
mAccProps["selected"] = true;
} else {
mAccProps["selected"] = false;
}
if (!bEnabled) {
oRm.addClass("sapUiCalItemDsbl"); // year disabled
mAccProps["disabled"] = true;
}
oRm.writeAttribute("tabindex", "-1");
oRm.writeAttribute("data-sap-year-start", sYyyymmdd);
oRm.addStyle("width", sWidth);
oRm.writeClasses();
oRm.writeStyles();
oRm.writeAccessibilityState(null, mAccProps);
oRm.write(">"); // div element
// to render era in Japanese, UniversalDate is used, since CalendarDate.toUTCJSDate() will convert the date in Gregorian
oRm.write(oYP._oYearFormat.format(UniversalDate.getInstance(oDate.toUTCJSDate(), oDate.getCalendarType()), true)); // to render era in Japanese
oRm.write("</div>");
oDate.setYear(oDate.getYear() + 1);
if (iColumns > 0 && ((i + 1) % iColumns == 0)) {
// end of row
oRm.write("</div>");
}
}
oRm.write("</div>");
};
return YearPickerRenderer;
}, /* bExport= */ true);
|
SQCLabs/openui5
|
src/sap.ui.unified/src/sap/ui/unified/calendar/YearPickerRenderer.js
|
JavaScript
|
apache-2.0
| 3,459
|
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto
namespace Google\Cloud\Compute\V1\FileContentBuffer;
use UnexpectedValueException;
/**
* The file type of source file.
*
* Protobuf type <code>google.cloud.compute.v1.FileContentBuffer.FileType</code>
*/
class FileType
{
/**
* A value indicating that the enum field is not set.
*
* Generated from protobuf enum <code>UNDEFINED_FILE_TYPE = 0;</code>
*/
const UNDEFINED_FILE_TYPE = 0;
/**
* Generated from protobuf enum <code>BIN = 65767;</code>
*/
const BIN = 65767;
/**
* Generated from protobuf enum <code>UNDEFINED = 137851184;</code>
*/
const UNDEFINED = 137851184;
/**
* Generated from protobuf enum <code>X509 = 2674086;</code>
*/
const X509 = 2674086;
private static $valueToName = [
self::UNDEFINED_FILE_TYPE => 'UNDEFINED_FILE_TYPE',
self::BIN => 'BIN',
self::UNDEFINED => 'UNDEFINED',
self::X509 => 'X509',
];
public static function name($value)
{
if (!isset(self::$valueToName[$value])) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no name defined for value %s', __CLASS__, $value));
}
return self::$valueToName[$value];
}
public static function value($name)
{
$const = __CLASS__ . '::' . strtoupper($name);
if (!defined($const)) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no value defined for name %s', __CLASS__, $name));
}
return constant($const);
}
}
|
googleapis/google-cloud-php-compute
|
src/V1/FileContentBuffer/FileType.php
|
PHP
|
apache-2.0
| 1,687
|
// 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.kudu.client;
import java.util.List;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.yetus.audience.InterfaceStability;
import org.apache.kudu.Schema;
/**
* A partition schema describes how the rows of a table are distributed among
* tablets.
*
* Primarily, a table's partition schema is responsible for translating the
* primary key column values of a row into a partition key that can be used to
* find the tablet containing the key.
*
* The partition schema is made up of zero or more hash bucket components,
* followed by a single range component.
*
* Each hash bucket component includes one or more columns from the primary key
* column set, with the restriction that an individual primary key column may
* only be included in a single hash component.
*
* This class is new, and not considered stable or suitable for public use.
*/
@InterfaceAudience.LimitedPrivate("Impala")
@InterfaceStability.Unstable
public class PartitionSchema {
private final RangeSchema rangeSchema;
private final List<HashBucketSchema> hashBucketSchemas;
private final boolean isSimple;
/**
* Creates a new partition schema from the range and hash bucket schemas.
*
* @param rangeSchema the range schema
* @param hashBucketSchemas the hash bucket schemas
* @param schema the table schema
*/
public PartitionSchema(RangeSchema rangeSchema,
List<HashBucketSchema> hashBucketSchemas,
Schema schema) {
this.rangeSchema = rangeSchema;
this.hashBucketSchemas = hashBucketSchemas;
boolean isSimple = hashBucketSchemas.isEmpty() &&
rangeSchema.columns.size() == schema.getPrimaryKeyColumnCount();
if (isSimple) {
int i = 0;
for (Integer id : rangeSchema.columns) {
if (schema.getColumnIndex(id) != i++) {
isSimple = false;
break;
}
}
}
this.isSimple = isSimple;
}
/**
* Returns the encoded partition key of the row.
* @return a byte array containing the encoded partition key of the row
*/
public byte[] encodePartitionKey(PartialRow row) {
return KeyEncoder.encodePartitionKey(row, this);
}
public RangeSchema getRangeSchema() {
return rangeSchema;
}
public List<HashBucketSchema> getHashBucketSchemas() {
return hashBucketSchemas;
}
/**
* Returns true if the partition schema if the partition schema does not include any hash
* components, and the range columns match the table's primary key columns.
*
* @return whether the partition schema is the default simple range partitioning.
*/
boolean isSimpleRangePartitioning() {
return isSimple;
}
public static class RangeSchema {
private final List<Integer> columns;
public RangeSchema(List<Integer> columns) {
this.columns = columns;
}
/**
* Gets the column IDs of the columns in the range partition.
* @return the column IDs of the columns in the range partition
* @deprecated Use {@link #getColumnIds} instead.
*/
@Deprecated
public List<Integer> getColumns() {
return columns;
}
/**
* Gets the column IDs of the columns in the range partition.
* @return the column IDs of the columns in the range partition
*/
public List<Integer> getColumnIds() {
return columns;
}
}
public static class HashBucketSchema {
private final List<Integer> columnIds;
private int numBuckets;
private int seed;
public HashBucketSchema(List<Integer> columnIds, int numBuckets, int seed) {
this.columnIds = columnIds;
this.numBuckets = numBuckets;
this.seed = seed;
}
/**
* Gets the column IDs of the columns in the hash partition.
* @return the column IDs of the columns in the hash partition
*/
public List<Integer> getColumnIds() {
return columnIds;
}
public int getNumBuckets() {
return numBuckets;
}
public int getSeed() {
return seed;
}
}
}
|
helifu/kudu
|
java/kudu-client/src/main/java/org/apache/kudu/client/PartitionSchema.java
|
Java
|
apache-2.0
| 4,839
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.view;
import android.view.accessibility.AccessibilityEvent;
import java.util.List;
/**
* A simple decorator stub for Window.Callback that passes through any calls
* to the wrapped instance as a base implementation. Call super.foo() to call into
* the wrapped callback for any subclasses.
*
* @hide for internal use
*/
public class WindowCallbackWrapper implements Window.Callback {
private Window.Callback mWrapped;
public WindowCallbackWrapper(Window.Callback wrapped) {
if (wrapped == null) {
throw new IllegalArgumentException("Window callback may not be null");
}
mWrapped = wrapped;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
return mWrapped.dispatchKeyEvent(event);
}
@Override
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
return mWrapped.dispatchKeyShortcutEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
return mWrapped.dispatchTouchEvent(event);
}
@Override
public boolean dispatchTrackballEvent(MotionEvent event) {
return mWrapped.dispatchTrackballEvent(event);
}
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
return mWrapped.dispatchGenericMotionEvent(event);
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
return mWrapped.dispatchPopulateAccessibilityEvent(event);
}
@Override
public View onCreatePanelView(int featureId) {
return mWrapped.onCreatePanelView(featureId);
}
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
return mWrapped.onCreatePanelMenu(featureId, menu);
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
return mWrapped.onPreparePanel(featureId, view, menu);
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
return mWrapped.onMenuOpened(featureId, menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
return mWrapped.onMenuItemSelected(featureId, item);
}
@Override
public void onWindowAttributesChanged(WindowManager.LayoutParams attrs) {
mWrapped.onWindowAttributesChanged(attrs);
}
@Override
public void onContentChanged() {
mWrapped.onContentChanged();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
mWrapped.onWindowFocusChanged(hasFocus);
}
@Override
public void onAttachedToWindow() {
mWrapped.onAttachedToWindow();
}
@Override
public void onDetachedFromWindow() {
mWrapped.onDetachedFromWindow();
}
@Override
public void onPanelClosed(int featureId, Menu menu) {
mWrapped.onPanelClosed(featureId, menu);
}
@Override
public boolean onSearchRequested(SearchEvent searchEvent) {
return mWrapped.onSearchRequested(searchEvent);
}
@Override
public boolean onSearchRequested() {
return mWrapped.onSearchRequested();
}
@Override
public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
return mWrapped.onWindowStartingActionMode(callback);
}
@Override
public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
return mWrapped.onWindowStartingActionMode(callback, type);
}
@Override
public void onActionModeStarted(ActionMode mode) {
mWrapped.onActionModeStarted(mode);
}
@Override
public void onActionModeFinished(ActionMode mode) {
mWrapped.onActionModeFinished(mode);
}
@Override
public void onProvideKeyboardShortcuts(
List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {
mWrapped.onProvideKeyboardShortcuts(data, menu, deviceId);
}
}
|
daiqiquan/framework-base
|
core/java/android/view/WindowCallbackWrapper.java
|
Java
|
apache-2.0
| 4,598
|
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>TestRegionSizeCalculator xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />
</head>
<body>
<div id="overview"><a href="../../../../../../testapidocs/org/apache/hadoop/hbase/util/TestRegionSizeCalculator.html">View Javadoc</a></div><pre>
<a class="jxr_linenumber" name="1" href="#1">1</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="2" href="#2">2</a> <em class="jxr_javadoccomment"> * Licensed to the Apache Software Foundation (ASF) under one</em>
<a class="jxr_linenumber" name="3" href="#3">3</a> <em class="jxr_javadoccomment"> * or more contributor license agreements. See the NOTICE file</em>
<a class="jxr_linenumber" name="4" href="#4">4</a> <em class="jxr_javadoccomment"> * distributed with this work for additional information</em>
<a class="jxr_linenumber" name="5" href="#5">5</a> <em class="jxr_javadoccomment"> * regarding copyright ownership. The ASF licenses this file</em>
<a class="jxr_linenumber" name="6" href="#6">6</a> <em class="jxr_javadoccomment"> * to you under the Apache License, Version 2.0 (the</em>
<a class="jxr_linenumber" name="7" href="#7">7</a> <em class="jxr_javadoccomment"> * "License"); you may not use this file except in compliance</em>
<a class="jxr_linenumber" name="8" href="#8">8</a> <em class="jxr_javadoccomment"> * with the License. You may obtain a copy of the License at</em>
<a class="jxr_linenumber" name="9" href="#9">9</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="10" href="#10">10</a> <em class="jxr_javadoccomment"> * <a href="http://www.apache.org/licenses/LICENSE-2.0" target="alexandria_uri">http://www.apache.org/licenses/LICENSE-2.0</a></em>
<a class="jxr_linenumber" name="11" href="#11">11</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="12" href="#12">12</a> <em class="jxr_javadoccomment"> * Unless required by applicable law or agreed to in writing, software</em>
<a class="jxr_linenumber" name="13" href="#13">13</a> <em class="jxr_javadoccomment"> * distributed under the License is distributed on an "AS IS" BASIS,</em>
<a class="jxr_linenumber" name="14" href="#14">14</a> <em class="jxr_javadoccomment"> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</em>
<a class="jxr_linenumber" name="15" href="#15">15</a> <em class="jxr_javadoccomment"> * See the License for the specific language governing permissions and</em>
<a class="jxr_linenumber" name="16" href="#16">16</a> <em class="jxr_javadoccomment"> * limitations under the License.</em>
<a class="jxr_linenumber" name="17" href="#17">17</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="18" href="#18">18</a> <strong class="jxr_keyword">package</strong> org.apache.hadoop.hbase.util;
<a class="jxr_linenumber" name="19" href="#19">19</a>
<a class="jxr_linenumber" name="20" href="#20">20</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.conf.Configuration;
<a class="jxr_linenumber" name="21" href="#21">21</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.ClusterStatus;
<a class="jxr_linenumber" name="22" href="#22">22</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.HRegionInfo;
<a class="jxr_linenumber" name="23" href="#23">23</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.RegionLoad;
<a class="jxr_linenumber" name="24" href="#24">24</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.ServerLoad;
<a class="jxr_linenumber" name="25" href="#25">25</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.ServerName;
<a class="jxr_linenumber" name="26" href="#26">26</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.SmallTests;
<a class="jxr_linenumber" name="27" href="#27">27</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.client.HBaseAdmin;
<a class="jxr_linenumber" name="28" href="#28">28</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.client.HTable;
<a class="jxr_linenumber" name="29" href="#29">29</a> <strong class="jxr_keyword">import</strong> org.junit.Test;
<a class="jxr_linenumber" name="30" href="#30">30</a> <strong class="jxr_keyword">import</strong> org.junit.experimental.categories.Category;
<a class="jxr_linenumber" name="31" href="#31">31</a> <strong class="jxr_keyword">import</strong> org.mockito.Mockito;
<a class="jxr_linenumber" name="32" href="#32">32</a>
<a class="jxr_linenumber" name="33" href="#33">33</a> <strong class="jxr_keyword">import</strong> java.io.IOException;
<a class="jxr_linenumber" name="34" href="#34">34</a> <strong class="jxr_keyword">import</strong> java.util.ArrayList;
<a class="jxr_linenumber" name="35" href="#35">35</a> <strong class="jxr_keyword">import</strong> java.util.List;
<a class="jxr_linenumber" name="36" href="#36">36</a> <strong class="jxr_keyword">import</strong> java.util.Map;
<a class="jxr_linenumber" name="37" href="#37">37</a> <strong class="jxr_keyword">import</strong> java.util.NavigableMap;
<a class="jxr_linenumber" name="38" href="#38">38</a> <strong class="jxr_keyword">import</strong> java.util.TreeMap;
<a class="jxr_linenumber" name="39" href="#39">39</a>
<a class="jxr_linenumber" name="40" href="#40">40</a> <strong class="jxr_keyword">import</strong> <strong class="jxr_keyword">static</strong> org.junit.Assert.assertEquals;
<a class="jxr_linenumber" name="41" href="#41">41</a> <strong class="jxr_keyword">import</strong> <strong class="jxr_keyword">static</strong> org.mockito.Mockito.mock;
<a class="jxr_linenumber" name="42" href="#42">42</a> <strong class="jxr_keyword">import</strong> <strong class="jxr_keyword">static</strong> org.mockito.Mockito.when;
<a class="jxr_linenumber" name="43" href="#43">43</a>
<a class="jxr_linenumber" name="44" href="#44">44</a> @Category(SmallTests.<strong class="jxr_keyword">class</strong>)
<a class="jxr_linenumber" name="45" href="#45">45</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../../org/apache/hadoop/hbase/util/TestRegionSizeCalculator.html">TestRegionSizeCalculator</a> {
<a class="jxr_linenumber" name="46" href="#46">46</a>
<a class="jxr_linenumber" name="47" href="#47">47</a> <strong class="jxr_keyword">private</strong> Configuration configuration = <strong class="jxr_keyword">new</strong> Configuration();
<a class="jxr_linenumber" name="48" href="#48">48</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">long</strong> megabyte = 1024L * 1024L;
<a class="jxr_linenumber" name="49" href="#49">49</a>
<a class="jxr_linenumber" name="50" href="#50">50</a> @Test
<a class="jxr_linenumber" name="51" href="#51">51</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> testSimpleTestCase() <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="52" href="#52">52</a>
<a class="jxr_linenumber" name="53" href="#53">53</a> HTable table = mockTable(<span class="jxr_string">"region1"</span>, <span class="jxr_string">"region2"</span>, <span class="jxr_string">"region3"</span>);
<a class="jxr_linenumber" name="54" href="#54">54</a>
<a class="jxr_linenumber" name="55" href="#55">55</a> HBaseAdmin admin = mockAdmin(
<a class="jxr_linenumber" name="56" href="#56">56</a> mockServer(
<a class="jxr_linenumber" name="57" href="#57">57</a> mockRegion(<span class="jxr_string">"region1"</span>, 123),
<a class="jxr_linenumber" name="58" href="#58">58</a> mockRegion(<span class="jxr_string">"region3"</span>, 1232)
<a class="jxr_linenumber" name="59" href="#59">59</a> ),
<a class="jxr_linenumber" name="60" href="#60">60</a> mockServer(
<a class="jxr_linenumber" name="61" href="#61">61</a> mockRegion(<span class="jxr_string">"region2"</span>, 54321),
<a class="jxr_linenumber" name="62" href="#62">62</a> mockRegion(<span class="jxr_string">"otherTableRegion"</span>, 110)
<a class="jxr_linenumber" name="63" href="#63">63</a> )
<a class="jxr_linenumber" name="64" href="#64">64</a> );
<a class="jxr_linenumber" name="65" href="#65">65</a>
<a class="jxr_linenumber" name="66" href="#66">66</a> RegionSizeCalculator calculator = <strong class="jxr_keyword">new</strong> RegionSizeCalculator(table, admin);
<a class="jxr_linenumber" name="67" href="#67">67</a>
<a class="jxr_linenumber" name="68" href="#68">68</a> assertEquals(123 * megabyte, calculator.getRegionSize(<span class="jxr_string">"region1"</span>.getBytes()));
<a class="jxr_linenumber" name="69" href="#69">69</a> assertEquals(54321 * megabyte, calculator.getRegionSize(<span class="jxr_string">"region2"</span>.getBytes()));
<a class="jxr_linenumber" name="70" href="#70">70</a> assertEquals(1232 * megabyte, calculator.getRegionSize(<span class="jxr_string">"region3"</span>.getBytes()));
<a class="jxr_linenumber" name="71" href="#71">71</a> <em class="jxr_comment">// if region is not inside our table, it should return 0</em>
<a class="jxr_linenumber" name="72" href="#72">72</a> assertEquals(0 * megabyte, calculator.getRegionSize(<span class="jxr_string">"otherTableRegion"</span>.getBytes()));
<a class="jxr_linenumber" name="73" href="#73">73</a>
<a class="jxr_linenumber" name="74" href="#74">74</a> assertEquals(3, calculator.getRegionSizeMap().size());
<a class="jxr_linenumber" name="75" href="#75">75</a> }
<a class="jxr_linenumber" name="76" href="#76">76</a>
<a class="jxr_linenumber" name="77" href="#77">77</a>
<a class="jxr_linenumber" name="78" href="#78">78</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="79" href="#79">79</a> <em class="jxr_javadoccomment"> * When size of region in megabytes is larger than largest possible integer there could be</em>
<a class="jxr_linenumber" name="80" href="#80">80</a> <em class="jxr_javadoccomment"> * error caused by lost of precision.</em>
<a class="jxr_linenumber" name="81" href="#81">81</a> <em class="jxr_javadoccomment"> * */</em>
<a class="jxr_linenumber" name="82" href="#82">82</a> @Test
<a class="jxr_linenumber" name="83" href="#83">83</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> testLargeRegion() <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="84" href="#84">84</a>
<a class="jxr_linenumber" name="85" href="#85">85</a> HTable table = mockTable(<span class="jxr_string">"largeRegion"</span>);
<a class="jxr_linenumber" name="86" href="#86">86</a>
<a class="jxr_linenumber" name="87" href="#87">87</a> HBaseAdmin admin = mockAdmin(
<a class="jxr_linenumber" name="88" href="#88">88</a> mockServer(
<a class="jxr_linenumber" name="89" href="#89">89</a> mockRegion(<span class="jxr_string">"largeRegion"</span>, Integer.MAX_VALUE)
<a class="jxr_linenumber" name="90" href="#90">90</a> )
<a class="jxr_linenumber" name="91" href="#91">91</a> );
<a class="jxr_linenumber" name="92" href="#92">92</a>
<a class="jxr_linenumber" name="93" href="#93">93</a> RegionSizeCalculator calculator = <strong class="jxr_keyword">new</strong> RegionSizeCalculator(table, admin);
<a class="jxr_linenumber" name="94" href="#94">94</a>
<a class="jxr_linenumber" name="95" href="#95">95</a> assertEquals(((<strong class="jxr_keyword">long</strong>) Integer.MAX_VALUE) * megabyte, calculator.getRegionSize(<span class="jxr_string">"largeRegion"</span>.getBytes()));
<a class="jxr_linenumber" name="96" href="#96">96</a> }
<a class="jxr_linenumber" name="97" href="#97">97</a>
<a class="jxr_linenumber" name="98" href="#98">98</a> <em class="jxr_javadoccomment">/**</em><em class="jxr_javadoccomment"> When calculator is disabled, it should return 0 for each request.*/</em>
<a class="jxr_linenumber" name="99" href="#99">99</a> @Test
<a class="jxr_linenumber" name="100" href="#100">100</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> testDisabled() <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="101" href="#101">101</a> String regionName = <span class="jxr_string">"cz.goout:/index.html"</span>;
<a class="jxr_linenumber" name="102" href="#102">102</a> HTable table = mockTable(regionName);
<a class="jxr_linenumber" name="103" href="#103">103</a>
<a class="jxr_linenumber" name="104" href="#104">104</a> HBaseAdmin admin = mockAdmin(
<a class="jxr_linenumber" name="105" href="#105">105</a> mockServer(
<a class="jxr_linenumber" name="106" href="#106">106</a> mockRegion(regionName, 999)
<a class="jxr_linenumber" name="107" href="#107">107</a> )
<a class="jxr_linenumber" name="108" href="#108">108</a> );
<a class="jxr_linenumber" name="109" href="#109">109</a>
<a class="jxr_linenumber" name="110" href="#110">110</a> <em class="jxr_comment">//first request on enabled calculator</em>
<a class="jxr_linenumber" name="111" href="#111">111</a> RegionSizeCalculator calculator = <strong class="jxr_keyword">new</strong> RegionSizeCalculator(table, admin);
<a class="jxr_linenumber" name="112" href="#112">112</a> assertEquals(999 * megabyte, calculator.getRegionSize(regionName.getBytes()));
<a class="jxr_linenumber" name="113" href="#113">113</a>
<a class="jxr_linenumber" name="114" href="#114">114</a> <em class="jxr_comment">//then disabled calculator.</em>
<a class="jxr_linenumber" name="115" href="#115">115</a> configuration.setBoolean(RegionSizeCalculator.ENABLE_REGIONSIZECALCULATOR, false);
<a class="jxr_linenumber" name="116" href="#116">116</a> RegionSizeCalculator disabledCalculator = <strong class="jxr_keyword">new</strong> RegionSizeCalculator(table, admin);
<a class="jxr_linenumber" name="117" href="#117">117</a> assertEquals(0 * megabyte, disabledCalculator.getRegionSize(regionName.getBytes()));
<a class="jxr_linenumber" name="118" href="#118">118</a>
<a class="jxr_linenumber" name="119" href="#119">119</a> assertEquals(0, disabledCalculator.getRegionSizeMap().size());
<a class="jxr_linenumber" name="120" href="#120">120</a> }
<a class="jxr_linenumber" name="121" href="#121">121</a>
<a class="jxr_linenumber" name="122" href="#122">122</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="123" href="#123">123</a> <em class="jxr_javadoccomment"> * Makes some table with given region names.</em>
<a class="jxr_linenumber" name="124" href="#124">124</a> <em class="jxr_javadoccomment"> * */</em>
<a class="jxr_linenumber" name="125" href="#125">125</a> <strong class="jxr_keyword">private</strong> HTable mockTable(String... regionNames) <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="126" href="#126">126</a> HTable mockedTable = Mockito.mock(HTable.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="127" href="#127">127</a> when(mockedTable.getConfiguration()).thenReturn(configuration);
<a class="jxr_linenumber" name="128" href="#128">128</a> when(mockedTable.getTableName()).thenReturn(<span class="jxr_string">"sizeTestTable"</span>.getBytes());
<a class="jxr_linenumber" name="129" href="#129">129</a> NavigableMap<HRegionInfo, ServerName> regionLocations = <strong class="jxr_keyword">new</strong> TreeMap<HRegionInfo, ServerName>();
<a class="jxr_linenumber" name="130" href="#130">130</a> when(mockedTable.getRegionLocations()).thenReturn(regionLocations);
<a class="jxr_linenumber" name="131" href="#131">131</a>
<a class="jxr_linenumber" name="132" href="#132">132</a> <strong class="jxr_keyword">for</strong> (String regionName : regionNames) {
<a class="jxr_linenumber" name="133" href="#133">133</a> HRegionInfo info = Mockito.mock(HRegionInfo.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="134" href="#134">134</a> when(info.getRegionName()).thenReturn(regionName.getBytes());
<a class="jxr_linenumber" name="135" href="#135">135</a> regionLocations.put(info, <strong class="jxr_keyword">null</strong>);<em class="jxr_comment">//we are not interested in values</em>
<a class="jxr_linenumber" name="136" href="#136">136</a> }
<a class="jxr_linenumber" name="137" href="#137">137</a>
<a class="jxr_linenumber" name="138" href="#138">138</a> <strong class="jxr_keyword">return</strong> mockedTable;
<a class="jxr_linenumber" name="139" href="#139">139</a> }
<a class="jxr_linenumber" name="140" href="#140">140</a>
<a class="jxr_linenumber" name="141" href="#141">141</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="142" href="#142">142</a> <em class="jxr_javadoccomment"> * Creates mock returing ClusterStatus info about given servers.</em>
<a class="jxr_linenumber" name="143" href="#143">143</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="144" href="#144">144</a> <strong class="jxr_keyword">private</strong> HBaseAdmin mockAdmin(ServerLoad... servers) <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="145" href="#145">145</a> <em class="jxr_comment">//get clusterstatus</em>
<a class="jxr_linenumber" name="146" href="#146">146</a> HBaseAdmin mockAdmin = Mockito.mock(HBaseAdmin.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="147" href="#147">147</a> ClusterStatus clusterStatus = mockCluster(servers);
<a class="jxr_linenumber" name="148" href="#148">148</a> when(mockAdmin.getClusterStatus()).thenReturn(clusterStatus);
<a class="jxr_linenumber" name="149" href="#149">149</a> <strong class="jxr_keyword">return</strong> mockAdmin;
<a class="jxr_linenumber" name="150" href="#150">150</a> }
<a class="jxr_linenumber" name="151" href="#151">151</a>
<a class="jxr_linenumber" name="152" href="#152">152</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="153" href="#153">153</a> <em class="jxr_javadoccomment"> * Creates mock of region with given name and size.</em>
<a class="jxr_linenumber" name="154" href="#154">154</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="155" href="#155">155</a> <em class="jxr_javadoccomment"> * @param fileSizeMb number of megabytes occupied by region in file store in megabytes</em>
<a class="jxr_linenumber" name="156" href="#156">156</a> <em class="jxr_javadoccomment"> * */</em>
<a class="jxr_linenumber" name="157" href="#157">157</a> <strong class="jxr_keyword">private</strong> RegionLoad mockRegion(String regionName, <strong class="jxr_keyword">int</strong> fileSizeMb) {
<a class="jxr_linenumber" name="158" href="#158">158</a> RegionLoad region = Mockito.mock(RegionLoad.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="159" href="#159">159</a> when(region.getName()).thenReturn(regionName.getBytes());
<a class="jxr_linenumber" name="160" href="#160">160</a> when(region.getNameAsString()).thenReturn(regionName);
<a class="jxr_linenumber" name="161" href="#161">161</a> when(region.getStorefileSizeMB()).thenReturn(fileSizeMb);
<a class="jxr_linenumber" name="162" href="#162">162</a> <strong class="jxr_keyword">return</strong> region;
<a class="jxr_linenumber" name="163" href="#163">163</a> }
<a class="jxr_linenumber" name="164" href="#164">164</a>
<a class="jxr_linenumber" name="165" href="#165">165</a> <strong class="jxr_keyword">private</strong> ClusterStatus mockCluster(ServerLoad[] servers) {
<a class="jxr_linenumber" name="166" href="#166">166</a> List<ServerName> serverNames = <strong class="jxr_keyword">new</strong> ArrayList<ServerName>();
<a class="jxr_linenumber" name="167" href="#167">167</a>
<a class="jxr_linenumber" name="168" href="#168">168</a> ClusterStatus clusterStatus = Mockito.mock(ClusterStatus.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="169" href="#169">169</a> when(clusterStatus.getServers()).thenReturn(serverNames);
<a class="jxr_linenumber" name="170" href="#170">170</a>
<a class="jxr_linenumber" name="171" href="#171">171</a> <strong class="jxr_keyword">int</strong> serverCounter = 0;
<a class="jxr_linenumber" name="172" href="#172">172</a> <strong class="jxr_keyword">for</strong> (ServerLoad server : servers) {
<a class="jxr_linenumber" name="173" href="#173">173</a> ServerName serverName = mock(ServerName.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="174" href="#174">174</a> when(serverName.getServerName()).thenReturn(<span class="jxr_string">"server"</span> + (serverCounter++));
<a class="jxr_linenumber" name="175" href="#175">175</a> serverNames.add(serverName);
<a class="jxr_linenumber" name="176" href="#176">176</a> when(clusterStatus.getLoad(serverName)).thenReturn(server);
<a class="jxr_linenumber" name="177" href="#177">177</a> }
<a class="jxr_linenumber" name="178" href="#178">178</a>
<a class="jxr_linenumber" name="179" href="#179">179</a> <strong class="jxr_keyword">return</strong> clusterStatus;
<a class="jxr_linenumber" name="180" href="#180">180</a> }
<a class="jxr_linenumber" name="181" href="#181">181</a>
<a class="jxr_linenumber" name="182" href="#182">182</a> <em class="jxr_javadoccomment">/**</em><em class="jxr_javadoccomment"> Creates mock of region server with given regions*/</em>
<a class="jxr_linenumber" name="183" href="#183">183</a> <strong class="jxr_keyword">private</strong> ServerLoad mockServer(RegionLoad... regions) {
<a class="jxr_linenumber" name="184" href="#184">184</a> ServerLoad serverLoad = Mockito.mock(ServerLoad.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="185" href="#185">185</a> Map<byte[], RegionLoad> regionMap = <strong class="jxr_keyword">new</strong> TreeMap<byte[], RegionLoad>(Bytes.BYTES_COMPARATOR);
<a class="jxr_linenumber" name="186" href="#186">186</a>
<a class="jxr_linenumber" name="187" href="#187">187</a> <strong class="jxr_keyword">for</strong> (RegionLoad regionName : regions) {
<a class="jxr_linenumber" name="188" href="#188">188</a> regionMap.put(regionName.getName(), regionName);
<a class="jxr_linenumber" name="189" href="#189">189</a> }
<a class="jxr_linenumber" name="190" href="#190">190</a>
<a class="jxr_linenumber" name="191" href="#191">191</a> when(serverLoad.getRegionsLoad()).thenReturn(regionMap);
<a class="jxr_linenumber" name="192" href="#192">192</a> <strong class="jxr_keyword">return</strong> serverLoad;
<a class="jxr_linenumber" name="193" href="#193">193</a> }
<a class="jxr_linenumber" name="194" href="#194">194</a>
<a class="jxr_linenumber" name="195" href="#195">195</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html>
|
gsoundar/mambo-ec2-deploy
|
packages/hbase-0.98.7-hadoop2/docs/xref-test/org/apache/hadoop/hbase/util/TestRegionSizeCalculator.html
|
HTML
|
apache-2.0
| 23,479
|
package org.jboss.resteasy.test.providers.jaxb;
import org.jboss.resteasy.plugins.providers.jaxb.JAXBContextFinder;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.test.BaseResourceTest;
import org.junit.Assert;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Providers;
import javax.xml.bind.JAXBContext;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class JaxbCacheTest extends BaseResourceTest
{
@Test
public void testCache() throws Exception
{
ResteasyProviderFactory.pushContext(Providers.class, getProviderFactory());
{
ContextResolver<JAXBContextFinder> resolver = getProviderFactory().getContextResolver(JAXBContextFinder.class, MediaType.APPLICATION_XML_TYPE);
JAXBContextFinder finder = resolver.getContext(Child.class);
JAXBContext ctx = finder.findCachedContext(Child.class, MediaType.APPLICATION_XML_TYPE, null);
JAXBContext ctx2 = finder.findCachedContext(Child.class, MediaType.APPLICATION_XML_TYPE, null);
Assert.assertTrue(ctx == ctx2);
}
{
ContextResolver<JAXBContextFinder> resolver = getProviderFactory().getContextResolver(JAXBContextFinder.class, MediaType.APPLICATION_JSON_TYPE);
JAXBContextFinder finder = resolver.getContext(Child.class);
JAXBContext ctx = finder.findCachedContext(Child.class, MediaType.APPLICATION_JSON_TYPE, null);
JAXBContext ctx2 = finder.findCachedContext(Child.class, MediaType.APPLICATION_JSON_TYPE, null);
Assert.assertTrue(ctx == ctx2);
}
{
MediaType mediaType = new MediaType("application", "fastinfoset");
ContextResolver<JAXBContextFinder> resolver = getProviderFactory().getContextResolver(JAXBContextFinder.class, mediaType);
JAXBContextFinder finder = resolver.getContext(Child.class);
JAXBContext ctx = finder.findCachedContext(Child.class, mediaType, null);
JAXBContext ctx2 = finder.findCachedContext(Child.class, mediaType, null);
Assert.assertTrue(ctx == ctx2);
}
}
@Test
public void testCache2() throws Exception
{
ResteasyProviderFactory.pushContext(Providers.class, getProviderFactory());
{
ContextResolver<JAXBContextFinder> resolver = getProviderFactory().getContextResolver(JAXBContextFinder.class, MediaType.APPLICATION_XML_TYPE);
JAXBContextFinder finder = resolver.getContext(Child.class);
JAXBContext ctx = finder.findCacheContext(MediaType.APPLICATION_XML_TYPE, null, Child.class, Parent.class);
JAXBContext ctx2 = finder.findCacheContext(MediaType.APPLICATION_XML_TYPE, null, Child.class, Parent.class);
Assert.assertTrue(ctx == ctx2);
}
{
ContextResolver<JAXBContextFinder> resolver = getProviderFactory().getContextResolver(JAXBContextFinder.class, MediaType.APPLICATION_JSON_TYPE);
JAXBContextFinder finder = resolver.getContext(Child.class);
JAXBContext ctx = finder.findCacheContext(MediaType.APPLICATION_JSON_TYPE, null, Child.class, Parent.class);
JAXBContext ctx2 = finder.findCacheContext(MediaType.APPLICATION_JSON_TYPE, null, Child.class, Parent.class);
Assert.assertTrue(ctx == ctx2);
}
{
MediaType mediaType = new MediaType("application", "fastinfoset");
ContextResolver<JAXBContextFinder> resolver = getProviderFactory().getContextResolver(JAXBContextFinder.class, mediaType);
JAXBContextFinder finder = resolver.getContext(Child.class);
JAXBContext ctx = finder.findCacheContext(mediaType, null, Child.class, Parent.class);
JAXBContext ctx2 = finder.findCacheContext(mediaType, null, Child.class, Parent.class);
Assert.assertTrue(ctx == ctx2);
}
}
}
|
raphaelning/resteasy-client-android
|
jaxrs/providers/test-all-jaxb/src/test/java/org/jboss/resteasy/test/providers/jaxb/JaxbCacheTest.java
|
Java
|
apache-2.0
| 3,927
|
<?php
namespace Topxia\Common;
use DateTime;
use DateTimeZone;
class TimeMachine {
private $timezone;
public function __construct ($timezone) {
$this->timezone = $timezone;
}
public function format($format, $timestamp = null) {
$datetime = new DateTime(null, new DateTimeZone($this->timezone));
$datetime->setTimestamp($timestamp ? : time());
return $datetime->format($format);
}
public function inSameDay ($timestamp1, $timestamp2) {
$datetime = new DateTime(null, new DateTimeZone($this->timezone));
$datetime->setTimestamp($timestamp1);
$date1 = $datetime->format('Y-m-d');
$datetime->setTimestamp($timestamp2);
$date2 = $datetime->format('Y-m-d');
return $date1 == $date2;
}
public function getDayTimeRange ($timestamp) {
$datetime = new DateTime(null, new DateTimeZone($this->timezone));
$datetime->setTimestamp($timestamp);
$date = $datetime->format('Y-m-d');
$datetime = new DateTime($date, new DateTimeZone($this->timezone));
$startTime = $datetime->getTimestamp();
$endTime = $startTime + 86400;
return array($startTime , $endTime);
}
public function diffDays ($timestamp1, $timestamp2) {
$datetime1 = new DateTime(null, new DateTimeZone($this->timezone));
$datetime1->setTimestamp($timestamp1);
$datetime1->setTime(0, 0, 0);
$datetime2 = new DateTime(null, new DateTimeZone($this->timezone));
$datetime2->setTimestamp($timestamp2);
$datetime2->setTime(0, 0, 0);
$diff = $datetime1->diff($datetime2);
return $diff->d;
}
}
|
18826252059/im
|
src/Topxia/Common/TimeMachine.php
|
PHP
|
apache-2.0
| 1,774
|
<!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_45) on Fri Aug 28 09:51:31 EDT 2015 -->
<title>Uses of Class org.apache.cassandra.client.RingCache (apache-cassandra API)</title>
<meta name="date" content="2015-08-28">
<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.client.RingCache (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/client/RingCache.html" title="class in org.apache.cassandra.client">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/client/class-use/RingCache.html" target="_top">Frames</a></li>
<li><a href="RingCache.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.client.RingCache" class="title">Uses of Class<br>org.apache.cassandra.client.RingCache</h2>
</div>
<div class="classUseContainer">No usage of org.apache.cassandra.client.RingCache</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/client/RingCache.html" title="class in org.apache.cassandra.client">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/client/class-use/RingCache.html" target="_top">Frames</a></li>
<li><a href="RingCache.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 © 2015 The Apache Software Foundation</small></p>
</body>
</html>
|
mitch-kyle/message-board
|
support/apache-cassandra-2.2.1/javadoc/org/apache/cassandra/client/class-use/RingCache.html
|
HTML
|
apache-2.0
| 4,532
|
/*
* Copyright 2008 The Closure Compiler 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 com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Joiner;
import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
import com.google.javascript.jscomp.ControlFlowGraph.Branch;
import com.google.javascript.jscomp.DataFlowAnalysis.FlowState;
import com.google.javascript.jscomp.LiveVariablesAnalysis.LiveVariableLattice;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
import com.google.javascript.jscomp.graph.GraphColoring;
import com.google.javascript.jscomp.graph.GraphColoring.GreedyGraphColoring;
import com.google.javascript.jscomp.graph.GraphNode;
import com.google.javascript.jscomp.graph.LinkedUndirectedGraph;
import com.google.javascript.jscomp.graph.UndiGraph;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.Nullable;
/**
* Reuse variable names if possible.
*
* <p>For example, from <code>var x = 1; print(x); var y = 2; print(y); </code>
* to <code>var x = 1; print(x); x = 2; print(x)</code>. The benefits are
* slightly shorter code because of the removed <code>var<code> declaration,
* less unique variables in hope for better renaming, and finally better gzip
* compression.
*
* <p>The pass operates similar to a typical register allocator found in an
* optimizing compiler by first computing live ranges with
* {@link LiveVariablesAnalysis} and a variable interference graph. Then it uses
* graph coloring in {@link GraphColoring} to determine which two variables can
* be merge together safely.
*
*/
class CoalesceVariableNames extends AbstractPostOrderCallback implements
CompilerPass, ScopedCallback {
private final AbstractCompiler compiler;
private final Deque<GraphColoring<Var, Void>> colorings;
private final Deque<LiveVariablesAnalysis> liveAnalyses;
private final boolean usePseudoNames;
private LiveVariablesAnalysis liveness;
private final Comparator<Var> coloringTieBreaker =
new Comparator<Var>() {
@Override
public int compare(Var v1, Var v2) {
return liveness.getVarIndex(v1.getName()) - liveness.getVarIndex(v2.getName());
}
};
/**
* @param usePseudoNames For debug purposes, when merging variable foo and bar
* to foo, rename both variable to foo_bar.
*/
CoalesceVariableNames(AbstractCompiler compiler, boolean usePseudoNames) {
// The code is normalized at this point in the compilation process. This allows us to use the
// fact that all variables have been given unique names. We can hoist coalesced variables to
// VARS because we know that shadowing can't occur.
checkState(compiler.getLifeCycleStage().isNormalized());
this.compiler = compiler;
colorings = new ArrayDeque<>();
liveAnalyses = new ArrayDeque<>();
this.usePseudoNames = usePseudoNames;
}
@Override
public void process(Node externs, Node root) {
checkNotNull(externs);
checkNotNull(root);
NodeTraversal.traverse(compiler, root, this);
compiler.setLifeCycleStage(LifeCycleStage.RAW);
}
private static boolean shouldOptimizeScope(NodeTraversal t) {
// TODO(user): We CAN do this in the global scope, just need to be
// careful when something is exported. Liveness uses bit-vector for live
// sets so I don't see compilation time will be a problem for running this
// pass in the global scope.
if (!t.getScopeRoot().isFunction()) {
return false;
}
Map<String, Var> allVarsInFn = new HashMap<>();
List<Var> orderedVars = new ArrayList<>();
NodeUtil.getAllVarsDeclaredInFunction(
allVarsInFn, orderedVars, t.getCompiler(), t.getScopeCreator(), t.getScope());
return LiveVariablesAnalysis.MAX_VARIABLES_TO_ANALYZE > orderedVars.size();
}
@Override
public void enterScope(NodeTraversal t) {
Scope scope = t.getScope();
if (!shouldOptimizeScope(t)) {
return;
}
checkState(scope.isFunctionScope(), scope);
// live variables analysis is based off of the control flow graph
ControlFlowGraph<Node> cfg = t.getControlFlowGraph();
liveness =
new LiveVariablesAnalysis(
cfg, scope, null, compiler, new Es6SyntacticScopeCreator(compiler));
if (FeatureSet.ES3.contains(compiler.getOptions().getOutputFeatureSet())) {
// If the function has exactly 2 params, mark them as escaped. This is a work-around for a
// bug in IE 8 and below, where it throws an exception if you write to the parameters of the
// callback in a sort(). See http://blickly.github.io/closure-compiler-issues/#58 and
// https://www.zachleat.com/web/array-sort/
Node enclosingFunction = scope.getRootNode();
if (NodeUtil.getFunctionParameters(enclosingFunction).hasTwoChildren()) {
liveness.markAllParametersEscaped();
}
}
liveness.analyze();
liveAnalyses.push(liveness);
// The interference graph has the function's variables as its nodes and any interference
// between the variables as the edges. Interference between two variables means that they are
// alive at overlapping times, which means that their variable names cannot be coalesced.
UndiGraph<Var, Void> interferenceGraph =
computeVariableNamesInterferenceGraph(cfg, liveness.getEscapedLocals());
// Color any interfering variables with different colors and any variables that can be safely
// coalesced wih the same color.
GraphColoring<Var, Void> coloring =
new GreedyGraphColoring<>(interferenceGraph, coloringTieBreaker);
coloring.color();
colorings.push(coloring);
}
@Override
public void exitScope(NodeTraversal t) {
if (!shouldOptimizeScope(t)) {
return;
}
colorings.pop();
liveAnalyses.pop();
liveness = liveAnalyses.peek();
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (colorings.isEmpty() || !n.isName() || parent.isFunction()) {
// Don't rename named functions.
return;
}
Var var = liveness.getAllVariables().get(n.getString());
GraphNode<Var, Void> vNode = colorings.peek().getGraph().getNode(var);
if (vNode == null) {
// This is not a local.
return;
}
Var coalescedVar = colorings.peek().getPartitionSuperNode(var);
if (!usePseudoNames) {
if (vNode.getValue().equals(coalescedVar)) {
// The coalesced name is itself, nothing to do.
return;
}
// Rename.
n.setString(coalescedVar.name);
compiler.reportChangeToEnclosingScope(n);
if (NodeUtil.isNameDeclaration(parent)
|| NodeUtil.getEnclosingType(n, Token.DESTRUCTURING_LHS) != null) {
makeDeclarationVar(coalescedVar);
removeVarDeclaration(n);
}
} else {
// This code block is slow but since usePseudoName is for debugging,
// we should not sacrifice performance for non-debugging compilation to
// make this fast.
String pseudoName = null;
Set<String> allMergedNames = new TreeSet<>();
for (Var iVar : liveness.getAllVariablesInOrder()) {
// Look for all the variables that can be merged (in the graph by now)
// and it is merged with the current coalescedVar.
if (colorings.peek().getGraph().getNode(iVar) != null
&& coalescedVar.equals(colorings.peek().getPartitionSuperNode(iVar))) {
allMergedNames.add(iVar.name);
}
}
// Keep its original name.
if (allMergedNames.size() == 1) {
return;
}
pseudoName = Joiner.on("_").join(allMergedNames);
while (t.getScope().hasSlot(pseudoName)) {
pseudoName += "$";
}
// Rename.
n.setString(pseudoName);
compiler.reportChangeToEnclosingScope(n);
if (!vNode.getValue().equals(coalescedVar)
&& (NodeUtil.isNameDeclaration(parent)
|| NodeUtil.getEnclosingType(n, Token.DESTRUCTURING_LHS) != null)) {
makeDeclarationVar(coalescedVar);
removeVarDeclaration(n);
}
}
}
/**
* In order to determine when it is appropriate to coalesce two variables, we use a live variables
* analysis to make sure they are not alive at the same time. We take every pairing of variables
* and for every CFG node, determine whether the two variables are alive at the same time. If two
* variables are alive at the same time, we create an edge between them in the interference graph.
* The interference graph is the input to a graph coloring algorithm that ensures any interfering
* variables are marked in different color groups, while variables that can safely be coalesced
* are assigned the same color group.
*
* @param cfg
* @param escaped we don't want to coalesce any escaped variables
* @return graph with variable nodes and edges representing variable interference
*/
private UndiGraph<Var, Void> computeVariableNamesInterferenceGraph(
ControlFlowGraph<Node> cfg, Set<? extends Var> escaped) {
UndiGraph<Var, Void> interferenceGraph = LinkedUndirectedGraph.create();
// First create a node for each non-escaped variable. We add these nodes in the order in which
// they appear in the code because we want the names that appear earlier in the code to be used
// when coalescing to variables that appear later in the code.
List<Var> orderedVariables = liveness.getAllVariablesInOrder();
for (Var v : orderedVariables) {
if (escaped.contains(v)) {
continue;
}
// NOTE(user): In theory, we CAN coalesce function names just like any variables. Our
// Liveness analysis captures this just like it as described in the specification. However, we
// saw some zipped and unzipped size increase after this. We are not totally sure why
// that is but, for now, we will respect the dead functions and not play around with it
if (v.getParentNode().isFunction()) {
continue;
}
// NOTE: we skip class declarations for a combination of two reasons:
// 1. they are block-scoped, so we would need to rewrite them as class expressions
// e.g. `class C {}` -> `var C = class {}` to avoid incorrect semantics
// (see testDontCoalesceClassDeclarationsWithDestructuringDeclaration).
// This is possible but increases pre-gzip code size and complexity.
// 2. since function declaration coalescing seems to cause a size regression (as discussed
// above) we assume that coalescing class names may cause a similar size regression.
if (v.getParentNode().isClass()) {
continue;
}
// Skip lets and consts that have multiple variables declared in them, otherwise this produces
// incorrect semantics. See test case "testCapture".
if (v.isLet() || v.isConst()) {
Node nameDecl = NodeUtil.getEnclosingNode(v.getNode(), NodeUtil::isNameDeclaration);
if (NodeUtil.findLhsNodesInNode(nameDecl).size() > 1) {
continue;
}
}
interferenceGraph.createNode(v);
}
// Go through each variable and try to connect them.
int v1Index = -1;
for (Var v1 : orderedVariables) {
v1Index++;
int v2Index = -1;
NEXT_VAR_PAIR:
for (Var v2 : orderedVariables) {
v2Index++;
// Skip duplicate pairs.
if (v1Index > v2Index) {
continue;
}
if (!interferenceGraph.hasNode(v1) || !interferenceGraph.hasNode(v2)) {
// Skip nodes that were not added. They are globals and escaped
// locals. Also avoid merging a variable with itself.
continue NEXT_VAR_PAIR;
}
if (v1.isParam() && v2.isParam()) {
interferenceGraph.connectIfNotFound(v1, null, v2);
continue NEXT_VAR_PAIR;
}
// Go through every CFG node in the program and look at
// this variable pair. If they are both live at the same
// time, add an edge between them and continue to the next pair.
NEXT_CROSS_CFG_NODE:
for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) {
if (cfg.isImplicitReturn(cfgNode)) {
continue NEXT_CROSS_CFG_NODE;
}
FlowState<LiveVariableLattice> state = cfgNode.getAnnotation();
// Check the live states and add edge when possible.
if ((state.getIn().isLive(v1Index) && state.getIn().isLive(v2Index))
|| (state.getOut().isLive(v1Index) && state.getOut().isLive(v2Index))) {
interferenceGraph.connectIfNotFound(v1, null, v2);
continue NEXT_VAR_PAIR;
}
}
// v1 and v2 might not have an edge between them! woohoo. there's
// one last sanity check that we have to do: we have to check
// if there's a collision *within* the cfg node.
NEXT_INTRA_CFG_NODE:
for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) {
if (cfg.isImplicitReturn(cfgNode)) {
continue NEXT_INTRA_CFG_NODE;
}
FlowState<LiveVariableLattice> state = cfgNode.getAnnotation();
boolean v1OutLive = state.getOut().isLive(v1Index);
boolean v2OutLive = state.getOut().isLive(v2Index);
CombinedLiveRangeChecker checker = new CombinedLiveRangeChecker(
cfgNode.getValue(),
new LiveRangeChecker(v1, v2OutLive ? null : v2),
new LiveRangeChecker(v2, v1OutLive ? null : v1));
checker.check(cfgNode.getValue());
if (checker.connectIfCrossed(interferenceGraph)) {
continue NEXT_VAR_PAIR;
}
}
}
}
return interferenceGraph;
}
/**
* A simple wrapper to call two LiveRangeChecker callbacks during the same traversal.
*/
private static class CombinedLiveRangeChecker {
private final Node root;
private final LiveRangeChecker callback1;
private final LiveRangeChecker callback2;
CombinedLiveRangeChecker(
Node root,
LiveRangeChecker callback1,
LiveRangeChecker callback2) {
this.root = root;
this.callback1 = callback1;
this.callback2 = callback2;
}
void check(Node n) {
// For most AST nodes, traverse the subtree in postorder because that's how the expressions
// are evaluated.
if (n == root || !ControlFlowGraph.isEnteringNewCfgNode(n)) {
if ((n.isDestructuringLhs() && n.hasTwoChildren())
|| (n.isAssign() && n.getFirstChild().isDestructuringPattern())
|| n.isDefaultValue()) {
// Evaluate the rhs of a destructuring assignment/declaration before the lhs.
check(n.getSecondChild());
check(n.getFirstChild());
} else {
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
check(c);
}
}
visit(n, n.getParent());
}
}
void visit(Node n, Node parent) {
if (LiveRangeChecker.shouldVisit(n)) {
callback1.visit(n, parent);
callback2.visit(n, parent);
}
}
boolean connectIfCrossed(UndiGraph<Var, Void> interferenceGraph) {
if (callback1.crossed || callback2.crossed) {
Var v1 = callback1.def;
Var v2 = callback2.def;
interferenceGraph.connectIfNotFound(v1, null, v2);
return true;
}
return false;
}
}
/**
* Tries to remove variable declaration if the variable has been coalesced with another variable
* that has already been declared. Any lets or consts are redeclared as vars because at this point
* in the compilation, the code is normalized, so we can safely hoist variables without worrying
* about shadowing.
*
* @param name name node of the variable being coalesced
*/
private static void removeVarDeclaration(Node name) {
Node var = NodeUtil.getEnclosingNode(name, NodeUtil::isNameDeclaration);
Node parent = var.getParent();
if (!var.isVar()) {
var.setToken(Token.VAR);
}
checkState(var.isVar(), var);
// Special case for enhanced for-loops
if (NodeUtil.isEnhancedFor(parent)) {
var.removeChild(name);
parent.replaceChild(var, name);
} else if (var.hasOneChild() && var.getFirstChild() == name) {
// The removal is easy when there is only one variable in the VAR node.
if (name.hasChildren()) {
Node value = name.removeFirstChild();
var.removeChild(name);
Node assign = IR.assign(name, value).srcref(name);
// We don't need to wrapped it with EXPR node if it is within a FOR.
if (!parent.isVanillaFor()) {
assign = NodeUtil.newExpr(assign);
}
parent.replaceChild(var, assign);
} else {
// In a FOR( ; ; ) node, we must replace it with an EMPTY or else it
// becomes a FOR-IN node.
NodeUtil.removeChild(parent, var);
}
} else {
if (var.getFirstChild() == name && !name.hasChildren()) {
name.detach();
}
// We are going to leave duplicated declaration otherwise.
}
}
/**
* Because the code has already been normalized by the time this pass runs, we can safely
* redeclare any let and const coalesced variables as vars
*/
private static void makeDeclarationVar(Var coalescedName) {
if (coalescedName.isLet() || coalescedName.isConst()) {
Node declNode =
NodeUtil.getEnclosingNode(coalescedName.getParentNode(), NodeUtil::isNameDeclaration);
declNode.setToken(Token.VAR);
}
}
private static class LiveRangeChecker {
boolean defFound = false;
boolean crossed = false;
private final Var def;
@Nullable
private final Var use;
public LiveRangeChecker(Var def, Var use) {
this.def = checkNotNull(def);
this.use = use;
}
/**
* @return Whether any LiveRangeChecker would be interested in the node.
*/
public static boolean shouldVisit(Node n) {
return (n.isName() || (n.hasChildren() && n.getFirstChild().isName()));
}
void visit(Node n, Node parent) {
if (!defFound && isAssignTo(def, n, parent)) {
defFound = true;
}
if (defFound && (use == null || isReadFrom(use, n))) {
crossed = true;
}
}
static boolean isAssignTo(Var var, Node n, Node parent) {
if (n.isName()) {
if (parent.isParamList()) {
// In a function declaration, the formal parameters are assigned.
return var.getName().equals(n.getString());
} else if (NodeUtil.isNameDeclaration(parent) && n.hasChildren()) {
// If this is a VAR declaration, if the name node has a child, we are
// assigning to that name.
return var.getName().equals(n.getString());
} else if (NodeUtil.isLhsByDestructuring(n)) {
return var.getName().equals(n.getString());
}
} else if (NodeUtil.isAssignmentOp(n)) {
// Lastly, any assignmentOP is also an assign.
Node name = n.getFirstChild();
return name.isName() && var.getName().equals(name.getString());
}
return false; // Definitely a read.
}
static boolean isReadFrom(Var var, Node name) {
return name.isName()
&& var.getName().equals(name.getString())
&& !NodeUtil.isNameDeclOrSimpleAssignLhs(name, name.getParent());
}
}
}
|
shantanusharma/closure-compiler
|
src/com/google/javascript/jscomp/CoalesceVariableNames.java
|
Java
|
apache-2.0
| 20,624
|
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.19.1
// source: envoy/type/matcher/v3/string.proto
package envoy_type_matcher_v3
import (
_ "github.com/cncf/xds/go/udpa/annotations"
_ "github.com/envoyproxy/protoc-gen-validate/validate"
proto "github.com/golang/protobuf/proto"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
// Specifies the way to match a string.
// [#next-free-field: 8]
type StringMatcher struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Types that are assignable to MatchPattern:
// *StringMatcher_Exact
// *StringMatcher_Prefix
// *StringMatcher_Suffix
// *StringMatcher_SafeRegex
// *StringMatcher_Contains
MatchPattern isStringMatcher_MatchPattern `protobuf_oneof:"match_pattern"`
// If true, indicates the exact/prefix/suffix/contains matching should be case insensitive. This
// has no effect for the safe_regex match.
// For example, the matcher *data* will match both input string *Data* and *data* if set to true.
IgnoreCase bool `protobuf:"varint,6,opt,name=ignore_case,json=ignoreCase,proto3" json:"ignore_case,omitempty"`
}
func (x *StringMatcher) Reset() {
*x = StringMatcher{}
if protoimpl.UnsafeEnabled {
mi := &file_envoy_type_matcher_v3_string_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *StringMatcher) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StringMatcher) ProtoMessage() {}
func (x *StringMatcher) ProtoReflect() protoreflect.Message {
mi := &file_envoy_type_matcher_v3_string_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use StringMatcher.ProtoReflect.Descriptor instead.
func (*StringMatcher) Descriptor() ([]byte, []int) {
return file_envoy_type_matcher_v3_string_proto_rawDescGZIP(), []int{0}
}
func (m *StringMatcher) GetMatchPattern() isStringMatcher_MatchPattern {
if m != nil {
return m.MatchPattern
}
return nil
}
func (x *StringMatcher) GetExact() string {
if x, ok := x.GetMatchPattern().(*StringMatcher_Exact); ok {
return x.Exact
}
return ""
}
func (x *StringMatcher) GetPrefix() string {
if x, ok := x.GetMatchPattern().(*StringMatcher_Prefix); ok {
return x.Prefix
}
return ""
}
func (x *StringMatcher) GetSuffix() string {
if x, ok := x.GetMatchPattern().(*StringMatcher_Suffix); ok {
return x.Suffix
}
return ""
}
func (x *StringMatcher) GetSafeRegex() *RegexMatcher {
if x, ok := x.GetMatchPattern().(*StringMatcher_SafeRegex); ok {
return x.SafeRegex
}
return nil
}
func (x *StringMatcher) GetContains() string {
if x, ok := x.GetMatchPattern().(*StringMatcher_Contains); ok {
return x.Contains
}
return ""
}
func (x *StringMatcher) GetIgnoreCase() bool {
if x != nil {
return x.IgnoreCase
}
return false
}
type isStringMatcher_MatchPattern interface {
isStringMatcher_MatchPattern()
}
type StringMatcher_Exact struct {
// The input string must match exactly the string specified here.
//
// Examples:
//
// * *abc* only matches the value *abc*.
Exact string `protobuf:"bytes,1,opt,name=exact,proto3,oneof"`
}
type StringMatcher_Prefix struct {
// The input string must have the prefix specified here.
// Note: empty prefix is not allowed, please use regex instead.
//
// Examples:
//
// * *abc* matches the value *abc.xyz*
Prefix string `protobuf:"bytes,2,opt,name=prefix,proto3,oneof"`
}
type StringMatcher_Suffix struct {
// The input string must have the suffix specified here.
// Note: empty prefix is not allowed, please use regex instead.
//
// Examples:
//
// * *abc* matches the value *xyz.abc*
Suffix string `protobuf:"bytes,3,opt,name=suffix,proto3,oneof"`
}
type StringMatcher_SafeRegex struct {
// The input string must match the regular expression specified here.
SafeRegex *RegexMatcher `protobuf:"bytes,5,opt,name=safe_regex,json=safeRegex,proto3,oneof"`
}
type StringMatcher_Contains struct {
// The input string must have the substring specified here.
// Note: empty contains match is not allowed, please use regex instead.
//
// Examples:
//
// * *abc* matches the value *xyz.abc.def*
Contains string `protobuf:"bytes,7,opt,name=contains,proto3,oneof"`
}
func (*StringMatcher_Exact) isStringMatcher_MatchPattern() {}
func (*StringMatcher_Prefix) isStringMatcher_MatchPattern() {}
func (*StringMatcher_Suffix) isStringMatcher_MatchPattern() {}
func (*StringMatcher_SafeRegex) isStringMatcher_MatchPattern() {}
func (*StringMatcher_Contains) isStringMatcher_MatchPattern() {}
// Specifies a list of ways to match a string.
type ListStringMatcher struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Patterns []*StringMatcher `protobuf:"bytes,1,rep,name=patterns,proto3" json:"patterns,omitempty"`
}
func (x *ListStringMatcher) Reset() {
*x = ListStringMatcher{}
if protoimpl.UnsafeEnabled {
mi := &file_envoy_type_matcher_v3_string_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ListStringMatcher) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListStringMatcher) ProtoMessage() {}
func (x *ListStringMatcher) ProtoReflect() protoreflect.Message {
mi := &file_envoy_type_matcher_v3_string_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListStringMatcher.ProtoReflect.Descriptor instead.
func (*ListStringMatcher) Descriptor() ([]byte, []int) {
return file_envoy_type_matcher_v3_string_proto_rawDescGZIP(), []int{1}
}
func (x *ListStringMatcher) GetPatterns() []*StringMatcher {
if x != nil {
return x.Patterns
}
return nil
}
var File_envoy_type_matcher_v3_string_proto protoreflect.FileDescriptor
var file_envoy_type_matcher_v3_string_proto_rawDesc = []byte{
0x0a, 0x22, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74,
0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65,
0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x1a, 0x21, 0x65, 0x6e, 0x76,
0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f,
0x76, 0x33, 0x2f, 0x72, 0x65, 0x67, 0x65, 0x78, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1d,
0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73,
0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x21, 0x75,
0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f,
0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x1a, 0x17, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, 0x76, 0x61, 0x6c, 0x69, 0x64,
0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xd1, 0x02, 0x0a, 0x0d, 0x53, 0x74,
0x72, 0x69, 0x6e, 0x67, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x05, 0x65,
0x78, 0x61, 0x63, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x05, 0x65, 0x78,
0x61, 0x63, 0x74, 0x12, 0x21, 0x0a, 0x06, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x18, 0x02, 0x20,
0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x48, 0x00, 0x52, 0x06,
0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x12, 0x21, 0x0a, 0x06, 0x73, 0x75, 0x66, 0x66, 0x69, 0x78,
0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x48,
0x00, 0x52, 0x06, 0x73, 0x75, 0x66, 0x66, 0x69, 0x78, 0x12, 0x4e, 0x0a, 0x0a, 0x73, 0x61, 0x66,
0x65, 0x5f, 0x72, 0x65, 0x67, 0x65, 0x78, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e,
0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68,
0x65, 0x72, 0x2e, 0x76, 0x33, 0x2e, 0x52, 0x65, 0x67, 0x65, 0x78, 0x4d, 0x61, 0x74, 0x63, 0x68,
0x65, 0x72, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x48, 0x00, 0x52, 0x09,
0x73, 0x61, 0x66, 0x65, 0x52, 0x65, 0x67, 0x65, 0x78, 0x12, 0x25, 0x0a, 0x08, 0x63, 0x6f, 0x6e,
0x74, 0x61, 0x69, 0x6e, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04,
0x72, 0x02, 0x10, 0x01, 0x48, 0x00, 0x52, 0x08, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73,
0x12, 0x1f, 0x0a, 0x0b, 0x69, 0x67, 0x6e, 0x6f, 0x72, 0x65, 0x5f, 0x63, 0x61, 0x73, 0x65, 0x18,
0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x69, 0x67, 0x6e, 0x6f, 0x72, 0x65, 0x43, 0x61, 0x73,
0x65, 0x3a, 0x27, 0x9a, 0xc5, 0x88, 0x1e, 0x22, 0x0a, 0x20, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e,
0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x53, 0x74, 0x72,
0x69, 0x6e, 0x67, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x14, 0x0a, 0x0d, 0x6d, 0x61,
0x74, 0x63, 0x68, 0x5f, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x12, 0x03, 0xf8, 0x42, 0x01,
0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x52, 0x05, 0x72, 0x65, 0x67, 0x65, 0x78, 0x22, 0x8c, 0x01,
0x0a, 0x11, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x4d, 0x61, 0x74, 0x63,
0x68, 0x65, 0x72, 0x12, 0x4a, 0x0a, 0x08, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x73, 0x18,
0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79,
0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x74,
0x72, 0x69, 0x6e, 0x67, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x08, 0xfa, 0x42, 0x05,
0x92, 0x01, 0x02, 0x08, 0x01, 0x52, 0x08, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x73, 0x3a,
0x2b, 0x9a, 0xc5, 0x88, 0x1e, 0x26, 0x0a, 0x24, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79,
0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53,
0x74, 0x72, 0x69, 0x6e, 0x67, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x3c, 0x0a, 0x23,
0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e,
0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72,
0x2e, 0x76, 0x33, 0x42, 0x0b, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x50, 0x72, 0x6f, 0x74, 0x6f,
0x50, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x33,
}
var (
file_envoy_type_matcher_v3_string_proto_rawDescOnce sync.Once
file_envoy_type_matcher_v3_string_proto_rawDescData = file_envoy_type_matcher_v3_string_proto_rawDesc
)
func file_envoy_type_matcher_v3_string_proto_rawDescGZIP() []byte {
file_envoy_type_matcher_v3_string_proto_rawDescOnce.Do(func() {
file_envoy_type_matcher_v3_string_proto_rawDescData = protoimpl.X.CompressGZIP(file_envoy_type_matcher_v3_string_proto_rawDescData)
})
return file_envoy_type_matcher_v3_string_proto_rawDescData
}
var file_envoy_type_matcher_v3_string_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_envoy_type_matcher_v3_string_proto_goTypes = []interface{}{
(*StringMatcher)(nil), // 0: envoy.type.matcher.v3.StringMatcher
(*ListStringMatcher)(nil), // 1: envoy.type.matcher.v3.ListStringMatcher
(*RegexMatcher)(nil), // 2: envoy.type.matcher.v3.RegexMatcher
}
var file_envoy_type_matcher_v3_string_proto_depIdxs = []int32{
2, // 0: envoy.type.matcher.v3.StringMatcher.safe_regex:type_name -> envoy.type.matcher.v3.RegexMatcher
0, // 1: envoy.type.matcher.v3.ListStringMatcher.patterns:type_name -> envoy.type.matcher.v3.StringMatcher
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_envoy_type_matcher_v3_string_proto_init() }
func file_envoy_type_matcher_v3_string_proto_init() {
if File_envoy_type_matcher_v3_string_proto != nil {
return
}
file_envoy_type_matcher_v3_regex_proto_init()
if !protoimpl.UnsafeEnabled {
file_envoy_type_matcher_v3_string_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*StringMatcher); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_envoy_type_matcher_v3_string_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ListStringMatcher); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
file_envoy_type_matcher_v3_string_proto_msgTypes[0].OneofWrappers = []interface{}{
(*StringMatcher_Exact)(nil),
(*StringMatcher_Prefix)(nil),
(*StringMatcher_Suffix)(nil),
(*StringMatcher_SafeRegex)(nil),
(*StringMatcher_Contains)(nil),
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_envoy_type_matcher_v3_string_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_envoy_type_matcher_v3_string_proto_goTypes,
DependencyIndexes: file_envoy_type_matcher_v3_string_proto_depIdxs,
MessageInfos: file_envoy_type_matcher_v3_string_proto_msgTypes,
}.Build()
File_envoy_type_matcher_v3_string_proto = out.File
file_envoy_type_matcher_v3_string_proto_rawDesc = nil
file_envoy_type_matcher_v3_string_proto_goTypes = nil
file_envoy_type_matcher_v3_string_proto_depIdxs = nil
}
|
knative-sandbox/net-kourier
|
vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/string.pb.go
|
GO
|
apache-2.0
| 14,477
|
<?php
App::uses('AppModel', 'Model');
class ActivityRequisiteSummary extends AppModel {
public $useTable = 'activity_requisite_summary';
}
|
davigbr/agileleagues
|
app/Model/ActivityRequisiteSummary.php
|
PHP
|
apache-2.0
| 144
|
/**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.common.json.moduleconfig;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.jboss.pnc.common.util.IoUtils;
import javax.ws.rs.DefaultValue;
import java.io.File;
import java.io.IOException;
import java.util.Map;
/**
* @author <a href="mailto:matejonnet@gmail.com">Matej Lazar</a>
*/
@Getter
@Slf4j
public class KeycloakClientConfig {
private final String realm;
private final String realmPublicKey;
private final String authServerUrl;
private final Boolean sslRequired;
private final String resource;
private final Map<String, String> credentials;
@JsonCreator
public KeycloakClientConfig(
@JsonProperty("realm") String realm,
@JsonProperty("realm-public-key") String realmPublicKey,
@JsonProperty("auth-server-url") String authServerUrl,
@JsonProperty("ssl-required") Boolean sslRequired,
@JsonProperty("resource") String resource,
@JsonProperty("credentials") @DefaultValue("{}") Map<String, String> credentials) {
this.realm = realm;
this.realmPublicKey = realmPublicKey;
this.authServerUrl = authServerUrl;
this.sslRequired = sslRequired;
this.resource = resource;
this.credentials = credentials;
}
@JsonIgnore
public String getSecret() {
String secretPath = credentials.get("secretFileLocation");
try {
return IoUtils.readFileAsString(new File(secretPath)).trim();
} catch (IOException e) {
log.error("Error while getting secret token", e);
throw new RuntimeException(e);
}
}
}
|
matedo1/pnc
|
moduleconfig/src/main/java/org/jboss/pnc/common/json/moduleconfig/KeycloakClientConfig.java
|
Java
|
apache-2.0
| 2,532
|
/*
* Copyright 2010 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.api.plugins;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.distribution.DistributionContainer;
import org.gradle.api.distribution.plugins.DistributionPlugin;
import org.gradle.api.file.CopySpec;
/**
* A {@link Plugin} which package a Java project as a distribution including the JAR and runtime dependencies.
*
* @see <a href="https://docs.gradle.org/current/userguide/java_library_distribution_plugin.html">Java Library Distribution plugin reference</a>
*/
public class JavaLibraryDistributionPlugin implements Plugin<Project> {
@Override
public void apply(final Project project) {
project.getPluginManager().apply(JavaLibraryPlugin.class);
project.getPluginManager().apply(DistributionPlugin.class);
DistributionContainer distributionContainer = (DistributionContainer)project.getExtensions().getByName("distributions");
distributionContainer.named(DistributionPlugin.MAIN_DISTRIBUTION_NAME).configure(dist -> {
CopySpec childSpec = project.copySpec();
childSpec.from(project.getTasks().named(JavaPlugin.JAR_TASK_NAME));
childSpec.from(project.file("src/dist"));
CopySpec libSpec = project.copySpec();
libSpec.into("lib");
libSpec.from(project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME));
childSpec.with(libSpec);
dist.getContents().with(childSpec);
});
}
}
|
gradle/gradle
|
subprojects/plugins/src/main/java/org/gradle/api/plugins/JavaLibraryDistributionPlugin.java
|
Java
|
apache-2.0
| 2,126
|
---
layout: post101
title: Services Manager
categories: XAP101NET
parent: installation-overview.html
weight: 500
---
When installing the Service Grid on a Microsoft Windows environment, many administrators prefer to setup the Service Grid as A *Windows Service*, which have several advantages over standard console applications:
- A service can be configured to start automatically when the machine boots, without any user logging in.
- A service can be configured to run under predefined credentials, e.g. SYSTEM.
- A service has no console/GUI which clutters up the desktop (and might be closed accidentally...).
- Windows provides standard management console, command line and API to manage services, which makes managing services a common task for system administrators.
This page explains how to install a Service Grid as a Windows Service and manage it.
# Usage
The Windows Services management console lets users start/stop installed services and modify their properties, but does not support installing new services. This task is can be done via a command line, or during installation of an application.
Instead, GigaSpaces XAP.NET provides a supplementary tool called **GigaSpaces Services Manager** (located at the `bin` folder) which simplifies common administration tasks:
- Install/uninstall Service instances of `Grid Service Agent` as you please.
- Perform common operations directly from the tool, no need to switch to the Windows Console (e.g. Start, Stop, change startup type).
- Side-by-side support for GigaSpaces Installations of different versions on the same machine.
- Automatically creates a folder for new service instances, with an XML configuration and log files.
- Create custom templates of different service grid configurations.

{% note %}
**Note:** Some operations require elevated permissions - make sure you run with appropriate permissions. If you're using Windows Vista or later and UAC is turned on, it is recommended to use 'Run As Administrator' (for more info see: [http://support.microsoft.com/kb/922708](http://support.microsoft.com/kb/922708))
{%endnote%}
# Advanced
## Service Properties
To view a service properties, right-click it and select **Properties**, or simply double-click it. A dialog window with the service properties will appear.
## Configuration
The Service Properties window shows the name of the service configuration file. Either Click the configuration label to open the configuration file using your default XML viewer, or click the location label to open the service folder, then edit the configuration file using your favorite XML editor.
{% note %}
**Note:** In order for configuration changes to take effect the service needs to be stopped and restarted.
{%endnote%}
|
barakb/gigaspaces-wiki-jekyll
|
xap101net/gigaspaces-services-manager.markdown
|
Markdown
|
apache-2.0
| 2,820
|
# Copyright 2010-2011 OpenStack Foundation
# Copyright 2012-2013 IBM Corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from oslotest import base as test_base
from oslo.db.sqlalchemy import test_migrations as migrate
class TestWalkVersions(test_base.BaseTestCase, migrate.WalkVersionsMixin):
def setUp(self):
super(TestWalkVersions, self).setUp()
self.migration_api = mock.MagicMock()
self.engine = mock.MagicMock()
self.REPOSITORY = mock.MagicMock()
self.INIT_VERSION = 4
def test_migrate_up(self):
self.migration_api.db_version.return_value = 141
self._migrate_up(self.engine, 141)
self.migration_api.upgrade.assert_called_with(
self.engine, self.REPOSITORY, 141)
self.migration_api.db_version.assert_called_with(
self.engine, self.REPOSITORY)
def test_migrate_up_with_data(self):
test_value = {"a": 1, "b": 2}
self.migration_api.db_version.return_value = 141
self._pre_upgrade_141 = mock.MagicMock()
self._pre_upgrade_141.return_value = test_value
self._check_141 = mock.MagicMock()
self._migrate_up(self.engine, 141, True)
self._pre_upgrade_141.assert_called_with(self.engine)
self._check_141.assert_called_with(self.engine, test_value)
def test_migrate_down(self):
self.migration_api.db_version.return_value = 42
self.assertTrue(self._migrate_down(self.engine, 42))
self.migration_api.db_version.assert_called_with(
self.engine, self.REPOSITORY)
def test_migrate_down_not_implemented(self):
self.migration_api.downgrade.side_effect = NotImplementedError
self.assertFalse(self._migrate_down(self.engine, 42))
def test_migrate_down_with_data(self):
self._post_downgrade_043 = mock.MagicMock()
self.migration_api.db_version.return_value = 42
self._migrate_down(self.engine, 42, True)
self._post_downgrade_043.assert_called_with(self.engine)
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_up')
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_down')
def test_walk_versions_all_default(self, _migrate_up, _migrate_down):
self.REPOSITORY.latest = 20
self.migration_api.db_version.return_value = self.INIT_VERSION
self._walk_versions()
self.migration_api.version_control.assert_called_with(
None, self.REPOSITORY, self.INIT_VERSION)
self.migration_api.db_version.assert_called_with(
None, self.REPOSITORY)
versions = range(self.INIT_VERSION + 1, self.REPOSITORY.latest + 1)
upgraded = [mock.call(None, v, with_data=True) for v in versions]
self.assertEqual(self._migrate_up.call_args_list, upgraded)
downgraded = [mock.call(None, v - 1) for v in reversed(versions)]
self.assertEqual(self._migrate_down.call_args_list, downgraded)
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_up')
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_down')
def test_walk_versions_all_true(self, _migrate_up, _migrate_down):
self.REPOSITORY.latest = 20
self.migration_api.db_version.return_value = self.INIT_VERSION
self._walk_versions(self.engine, snake_walk=True, downgrade=True)
versions = range(self.INIT_VERSION + 1, self.REPOSITORY.latest + 1)
upgraded = []
for v in versions:
upgraded.append(mock.call(self.engine, v, with_data=True))
upgraded.append(mock.call(self.engine, v))
upgraded.extend(
[mock.call(self.engine, v) for v in reversed(versions)]
)
self.assertEqual(upgraded, self._migrate_up.call_args_list)
downgraded_1 = [
mock.call(self.engine, v - 1, with_data=True) for v in versions
]
downgraded_2 = []
for v in reversed(versions):
downgraded_2.append(mock.call(self.engine, v - 1))
downgraded_2.append(mock.call(self.engine, v - 1))
downgraded = downgraded_1 + downgraded_2
self.assertEqual(self._migrate_down.call_args_list, downgraded)
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_up')
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_down')
def test_walk_versions_true_false(self, _migrate_up, _migrate_down):
self.REPOSITORY.latest = 20
self.migration_api.db_version.return_value = self.INIT_VERSION
self._walk_versions(self.engine, snake_walk=True, downgrade=False)
versions = range(self.INIT_VERSION + 1, self.REPOSITORY.latest + 1)
upgraded = []
for v in versions:
upgraded.append(mock.call(self.engine, v, with_data=True))
upgraded.append(mock.call(self.engine, v))
self.assertEqual(upgraded, self._migrate_up.call_args_list)
downgraded = [
mock.call(self.engine, v - 1, with_data=True) for v in versions
]
self.assertEqual(self._migrate_down.call_args_list, downgraded)
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_up')
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_down')
def test_walk_versions_all_false(self, _migrate_up, _migrate_down):
self.REPOSITORY.latest = 20
self.migration_api.db_version.return_value = self.INIT_VERSION
self._walk_versions(self.engine, snake_walk=False, downgrade=False)
versions = range(self.INIT_VERSION + 1, self.REPOSITORY.latest + 1)
upgraded = [
mock.call(self.engine, v, with_data=True) for v in versions
]
self.assertEqual(upgraded, self._migrate_up.call_args_list)
|
malor/oslo.db
|
tests/sqlalchemy/test_migrations.py
|
Python
|
apache-2.0
| 6,274
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class LambdaParameterParsingTests : ParsingTests
{
public LambdaParameterParsingTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: options);
}
protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseExpression(text, options: options);
}
[Fact]
public void EndOfFileAfterOut()
{
UsingTree(@"
class C {
void Goo() {
System.Func<int, int> f = (out
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "Func");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "f");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.CloseParenToken);
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void EndOfFileAfterOutType()
{
UsingTree(@"
class C {
void Goo() {
System.Func<int, int> f = (out C
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "Func");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "f");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.CloseParenToken);
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void EndOfFileAfterOutTypeIdentifier()
{
UsingTree(@"
class C {
void Goo() {
System.Func<int, int> f = (out C c
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "Func");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "f");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.CloseParenToken);
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "c");
}
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void EndOfFileAfterOutTypeIdentifierParen()
{
UsingTree(@"
class C {
void Goo() {
System.Func<int, int> f = (out C c
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "Func");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "f");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.CloseParenToken);
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "c");
}
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void EndOfFileAfterOutTypeIdentifierComma()
{
UsingTree(@"
class C {
void Goo() {
System.Func<int, int> f = (out C c,
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "Func");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "f");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.CloseParenToken);
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "c");
}
N(SyntaxKind.CommaToken);
M(SyntaxKind.VariableDeclarator);
{
M(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(14167, "https://github.com/dotnet/roslyn/issues/14167")]
public void HangingLambdaParsing_Bug14167()
{
var tree = UsingNode(@"(int a, int b Main();");
tree.GetDiagnostics().Verify(
// (1,1): error CS1073: Unexpected token 'b'
// (int a, int b Main();
Diagnostic(ErrorCode.ERR_UnexpectedToken, "(int a, int ").WithArguments("b").WithLocation(1, 1),
// (1,9): error CS1525: Invalid expression term 'int'
// (int a, int b Main();
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(1, 9),
// (1,13): error CS1026: ) expected
// (int a, int b Main();
Diagnostic(ErrorCode.ERR_CloseParenExpected, "b").WithLocation(1, 13)
);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
M(SyntaxKind.CloseParenToken);
}
EOF();
}
[Fact]
public void Arglist_01()
{
string source = "(__arglist) => { }";
UsingExpression(source,
// (1,1): error CS1073: Unexpected token '=>'
// (__arglist) => { }
Diagnostic(ErrorCode.ERR_UnexpectedToken, "(__arglist)").WithArguments("=>").WithLocation(1, 1));
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.ArgListExpression);
{
N(SyntaxKind.ArgListKeyword);
}
N(SyntaxKind.CloseParenToken);
}
EOF();
}
[Fact]
public void Arglist_02()
{
string source = "(int x, __arglist) => { }";
UsingExpression(source,
// (1,1): error CS1073: Unexpected token '=>'
// (int x, __arglist) => { }
Diagnostic(ErrorCode.ERR_UnexpectedToken, "(int x, __arglist)").WithArguments("=>").WithLocation(1, 1));
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.ArgListExpression);
{
N(SyntaxKind.ArgListKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
EOF();
}
[Fact]
public void Arglist_03()
{
string source = "static (__arglist) => { }";
UsingExpression(source,
// (1,9): error CS1041: Identifier expected; '__arglist' is a keyword
// static (__arglist) => { }
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "__arglist").WithArguments("", "__arglist").WithLocation(1, 9));
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
}
}
|
physhi/roslyn
|
src/Compilers/CSharp/Test/Syntax/Parsing/LambdaParameterParsingTests.cs
|
C#
|
apache-2.0
| 30,371
|
package org.apereo.cas.config;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.model.support.jpa.JpaConfigurationContext;
import org.apereo.cas.configuration.support.JpaBeans;
import org.apereo.cas.jpa.JpaBeanFactory;
import org.apereo.cas.support.events.CasEventRepository;
import org.apereo.cas.support.events.CasEventRepositoryFilter;
import org.apereo.cas.support.events.jpa.JpaCasEvent;
import org.apereo.cas.support.events.jpa.JpaCasEventRepository;
import org.apereo.cas.util.CollectionUtils;
import lombok.val;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Set;
/**
* This is {@link JpaEventsConfiguration}, defines certain beans via configuration
* while delegating some to Spring namespaces inside the context config file.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
@Configuration("jpaEventsConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
@EnableTransactionManagement(proxyTargetClass = true)
public class JpaEventsConfiguration {
@Autowired
@Qualifier("jpaBeanFactory")
private ObjectProvider<JpaBeanFactory> jpaBeanFactory;
@Autowired
private CasConfigurationProperties casProperties;
@RefreshScope
@Bean
public JpaVendorAdapter jpaEventVendorAdapter() {
return jpaBeanFactory.getObject().newJpaVendorAdapter(casProperties.getJdbc());
}
@Bean
@ConditionalOnMissingBean(name = "dataSourceEvent")
@RefreshScope
public DataSource dataSourceEvent() {
return JpaBeans.newDataSource(casProperties.getEvents().getJpa());
}
@Bean
public Set<String> jpaEventPackagesToScan() {
return CollectionUtils.wrapSet(JpaCasEvent.class.getPackage().getName());
}
@Lazy
@Bean
public LocalContainerEntityManagerFactoryBean eventsEntityManagerFactory() {
val factory = jpaBeanFactory.getObject();
val ctx = JpaConfigurationContext.builder()
.jpaVendorAdapter(jpaEventVendorAdapter())
.persistenceUnitName("jpaEventRegistryContext")
.dataSource(dataSourceEvent())
.packagesToScan(jpaEventPackagesToScan())
.build();
return factory.newEntityManagerFactoryBean(ctx, casProperties.getEvents().getJpa());
}
@Autowired
@Bean
public PlatformTransactionManager transactionManagerEvents(@Qualifier("eventsEntityManagerFactory") final EntityManagerFactory emf) {
val mgmr = new JpaTransactionManager();
mgmr.setEntityManagerFactory(emf);
return mgmr;
}
@ConditionalOnMissingBean(name = "jpaEventRepositoryFilter")
@Bean
public CasEventRepositoryFilter jpaEventRepositoryFilter() {
return CasEventRepositoryFilter.noOp();
}
@Bean
@Autowired
public CasEventRepository casEventRepository(@Qualifier("transactionManagerEvents") final PlatformTransactionManager transactionManager) {
return new JpaCasEventRepository(jpaEventRepositoryFilter(), transactionManager);
}
}
|
fogbeam/cas_mirror
|
support/cas-server-support-events-jpa/src/main/java/org/apereo/cas/config/JpaEventsConfiguration.java
|
Java
|
apache-2.0
| 3,995
|
[expect php]
[file]
<?
include('Phalanger.inc');
__var_dump(html_entity_decode(NULL));
__var_dump(html_entity_decode(""));
?>
|
DEVSENSE/Phalanger
|
Testing/Tests/@PHP/standard/strings/bug21338.php
|
PHP
|
apache-2.0
| 133
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/rds/RDS_EXPORTS.h>
#include <aws/rds/RDSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace RDS
{
namespace Model
{
/**
*/
class AWS_RDS_API StopDBClusterRequest : public RDSRequest
{
public:
StopDBClusterRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "StopDBCluster"; }
Aws::String SerializePayload() const override;
protected:
void DumpBodyToUrl(Aws::Http::URI& uri ) const override;
public:
/**
* <p>The DB cluster identifier of the Amazon Aurora DB cluster to be stopped. This
* parameter is stored as a lowercase string.</p>
*/
inline const Aws::String& GetDBClusterIdentifier() const{ return m_dBClusterIdentifier; }
/**
* <p>The DB cluster identifier of the Amazon Aurora DB cluster to be stopped. This
* parameter is stored as a lowercase string.</p>
*/
inline bool DBClusterIdentifierHasBeenSet() const { return m_dBClusterIdentifierHasBeenSet; }
/**
* <p>The DB cluster identifier of the Amazon Aurora DB cluster to be stopped. This
* parameter is stored as a lowercase string.</p>
*/
inline void SetDBClusterIdentifier(const Aws::String& value) { m_dBClusterIdentifierHasBeenSet = true; m_dBClusterIdentifier = value; }
/**
* <p>The DB cluster identifier of the Amazon Aurora DB cluster to be stopped. This
* parameter is stored as a lowercase string.</p>
*/
inline void SetDBClusterIdentifier(Aws::String&& value) { m_dBClusterIdentifierHasBeenSet = true; m_dBClusterIdentifier = std::move(value); }
/**
* <p>The DB cluster identifier of the Amazon Aurora DB cluster to be stopped. This
* parameter is stored as a lowercase string.</p>
*/
inline void SetDBClusterIdentifier(const char* value) { m_dBClusterIdentifierHasBeenSet = true; m_dBClusterIdentifier.assign(value); }
/**
* <p>The DB cluster identifier of the Amazon Aurora DB cluster to be stopped. This
* parameter is stored as a lowercase string.</p>
*/
inline StopDBClusterRequest& WithDBClusterIdentifier(const Aws::String& value) { SetDBClusterIdentifier(value); return *this;}
/**
* <p>The DB cluster identifier of the Amazon Aurora DB cluster to be stopped. This
* parameter is stored as a lowercase string.</p>
*/
inline StopDBClusterRequest& WithDBClusterIdentifier(Aws::String&& value) { SetDBClusterIdentifier(std::move(value)); return *this;}
/**
* <p>The DB cluster identifier of the Amazon Aurora DB cluster to be stopped. This
* parameter is stored as a lowercase string.</p>
*/
inline StopDBClusterRequest& WithDBClusterIdentifier(const char* value) { SetDBClusterIdentifier(value); return *this;}
private:
Aws::String m_dBClusterIdentifier;
bool m_dBClusterIdentifierHasBeenSet;
};
} // namespace Model
} // namespace RDS
} // namespace Aws
|
jt70471/aws-sdk-cpp
|
aws-cpp-sdk-rds/include/aws/rds/model/StopDBClusterRequest.h
|
C
|
apache-2.0
| 3,459
|
// Modified or written by Lambdascale SRL for inclusion with lambdaj.
// Copyright (c) 2009-2010 Mario Fusco.
// Licensed under the Apache License, Version 2.0 (the "License")
package ch.lambdaj.function.closure;
import java.util.*;
/**
* A closure with a single free variable
* @author Mario Fusco
*/
public class Closure1<A> extends AbstractClosure {
/**
* Invokes this closure once by applying the given variable to it.
* @param var The variable used to invoke this closure
* @return The result of the closure invocation
*/
public Object apply(A var) {
return closeOne(var);
}
/**
* Invokes this closure once for each passed variable.
* @param vars The set of variables used to invoke this closure once for each variable
* @return A list of Object containing the results of each closure invocation
*/
public List<?> each(A... vars) {
return closeAll(vars);
}
/**
* Invokes this closure once for each item in the given iterable.
* @param vars The variables used to invoke this closure once for each of its item
* @return A list of Object containing the results of each closure invocation
*/
public List<?> each(Iterable<? extends A> vars) {
return closeAll(vars);
}
/**
* Curry this closure by fixing its only free variable to a given value.
* @param curry The value to which the free variable should be curry
* @return A Closure having no free variable
*/
public Closure0 curry(A curry) {
return curry(new Closure0(), curry, 1);
}
/**
* Defines the method invoked by this closure.
* @param closedObject The object on which the closure has to be invoked. It can be a fixed object or a Class.
* In this last case, if the method is not static, it is treated as it was an
* unbound argument defined through the {@link ch.lambdaj.Lambda#var(Class)} method
* @param methodName The name of the method invoked by this closure or {@link AbstractClosure#CONSTRUCTOR}
* if you want to call a constructor
* @param args The arguments used to invoke this closure. They can be a mixed of fixed value and
* unbound one defined through the {@link ch.lambdaj.Lambda#var(Class)} method
* @return The closure itself
*/
@Override
public Closure1<A> of(Object closedObject, String methodName, Object ... args) {
return (Closure1<A>)super.of(closedObject, methodName, args);
}
}
|
paul-hammant/coverage_data_comparison
|
src/main/java/ch/lambdaj/function/closure/Closure1.java
|
Java
|
apache-2.0
| 2,535
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/transcribe/model/Type.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace TranscribeService
{
namespace Model
{
namespace TypeMapper
{
static const int CONVERSATION_HASH = HashingUtils::HashString("CONVERSATION");
static const int DICTATION_HASH = HashingUtils::HashString("DICTATION");
Type GetTypeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == CONVERSATION_HASH)
{
return Type::CONVERSATION;
}
else if (hashCode == DICTATION_HASH)
{
return Type::DICTATION;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<Type>(hashCode);
}
return Type::NOT_SET;
}
Aws::String GetNameForType(Type enumValue)
{
switch(enumValue)
{
case Type::CONVERSATION:
return "CONVERSATION";
case Type::DICTATION:
return "DICTATION";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace TypeMapper
} // namespace Model
} // namespace TranscribeService
} // namespace Aws
|
awslabs/aws-sdk-cpp
|
aws-cpp-sdk-transcribe/source/model/Type.cpp
|
C++
|
apache-2.0
| 1,898
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/pinpoint-email/PinpointEmail_EXPORTS.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace PinpointEmail
{
namespace Model
{
/**
* <p>An HTTP 200 response if the request succeeds, or an error message if the
* request fails.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutConfigurationSetSendingOptionsResponse">AWS
* API Reference</a></p>
*/
class AWS_PINPOINTEMAIL_API PutConfigurationSetSendingOptionsResult
{
public:
PutConfigurationSetSendingOptionsResult();
PutConfigurationSetSendingOptionsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
PutConfigurationSetSendingOptionsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
};
} // namespace Model
} // namespace PinpointEmail
} // namespace Aws
|
awslabs/aws-sdk-cpp
|
aws-cpp-sdk-pinpoint-email/include/aws/pinpoint-email/model/PutConfigurationSetSendingOptionsResult.h
|
C
|
apache-2.0
| 1,152
|
import * as React from "react";
import { Observable } from "babylonjs/Misc/observable";
import { PropertyChangedEvent } from "../../../../propertyChangedEvent";
import { CommonControlPropertyGridComponent } from "./commonControlPropertyGridComponent";
import { InputText } from "babylonjs-gui/2D/controls/inputText";
import { LineContainerComponent } from "../../../lineContainerComponent";
import { TextInputLineComponent } from "../../../lines/textInputLineComponent";
import { SliderLineComponent } from "../../../lines/sliderLineComponent";
import { CheckBoxLineComponent } from "../../../lines/checkBoxLineComponent";
import { FloatLineComponent } from "../../../lines/floatLineComponent";
import { LockObject } from "../lockObject";
import { GlobalState } from '../../../../globalState';
interface IInputTextPropertyGridComponentProps {
globalState: GlobalState;
inputText: InputText;
lockObject: LockObject;
onPropertyChangedObservable?: Observable<PropertyChangedEvent>;
}
export class InputTextPropertyGridComponent extends React.Component<IInputTextPropertyGridComponentProps> {
constructor(props: IInputTextPropertyGridComponentProps) {
super(props);
}
render() {
const inputText = this.props.inputText;
return (
<div className="pane">
<CommonControlPropertyGridComponent globalState={this.props.globalState} lockObject={this.props.lockObject} control={inputText} onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<LineContainerComponent globalState={this.props.globalState} title="INPUTTEXT">
<TextInputLineComponent lockObject={this.props.lockObject} label="Text" target={inputText} propertyName="text" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<TextInputLineComponent lockObject={this.props.lockObject} label="Prompt" target={inputText} propertyName="promptMessage" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<TextInputLineComponent lockObject={this.props.lockObject} label="Max width" target={inputText} propertyName="maxWidth" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<TextInputLineComponent lockObject={this.props.lockObject} label="Highlight color" target={inputText} propertyName="textHighlightColor" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<SliderLineComponent label="Highligher opacity" minimum={0} maximum={1} step={0.01} target={inputText} propertyName="highligherOpacity" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<CheckBoxLineComponent label="On focus select all" target={inputText} propertyName="onFocusSelectAll" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<TextInputLineComponent lockObject={this.props.lockObject} label="Focused background" target={inputText} propertyName="focusedBackground" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<TextInputLineComponent lockObject={this.props.lockObject} label="Max width" target={inputText} propertyName="maxWidth" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<TextInputLineComponent lockObject={this.props.lockObject} label="Margin" target={inputText} propertyName="margin" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<CheckBoxLineComponent label="Auto stretch width" target={inputText} propertyName="autoStretchWidth" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<FloatLineComponent lockObject={this.props.lockObject} label="Thickness" target={inputText} propertyName="thickness" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<TextInputLineComponent lockObject={this.props.lockObject} label="Placeholder text" target={inputText} propertyName="placeholderText" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
<TextInputLineComponent lockObject={this.props.lockObject} label="Placeholder color" target={inputText} propertyName="placeholderColor" onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
</LineContainerComponent>
</div>
);
}
}
|
Kesshi/Babylon.js
|
inspector/src/components/actionTabs/tabs/propertyGrids/gui/inputTextPropertyGridComponent.tsx
|
TypeScript
|
apache-2.0
| 4,539
|
<!--
~ 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.
~
~
-->
<html>
<body>
<h2>HTTP Library.</h2>
</body>
</html>
|
Qi4j/qi4j-sdk
|
libraries/http/src/main/java/org/apache/polygene/library/http/package.html
|
HTML
|
apache-2.0
| 915
|
package fr.castorflex.android.smoothprogressbar.sample;
/**
* Backport
*/
class FastOutSlowInInterpolator extends LookupTableInterpolator {
private static final float[] VALUES = new float[] {
0.0000f, 0.0001f, 0.0002f, 0.0005f, 0.0009f, 0.0014f, 0.0020f,
0.0027f, 0.0036f, 0.0046f, 0.0058f, 0.0071f, 0.0085f, 0.0101f,
0.0118f, 0.0137f, 0.0158f, 0.0180f, 0.0205f, 0.0231f, 0.0259f,
0.0289f, 0.0321f, 0.0355f, 0.0391f, 0.0430f, 0.0471f, 0.0514f,
0.0560f, 0.0608f, 0.0660f, 0.0714f, 0.0771f, 0.0830f, 0.0893f,
0.0959f, 0.1029f, 0.1101f, 0.1177f, 0.1257f, 0.1339f, 0.1426f,
0.1516f, 0.1610f, 0.1707f, 0.1808f, 0.1913f, 0.2021f, 0.2133f,
0.2248f, 0.2366f, 0.2487f, 0.2611f, 0.2738f, 0.2867f, 0.2998f,
0.3131f, 0.3265f, 0.3400f, 0.3536f, 0.3673f, 0.3810f, 0.3946f,
0.4082f, 0.4217f, 0.4352f, 0.4485f, 0.4616f, 0.4746f, 0.4874f,
0.5000f, 0.5124f, 0.5246f, 0.5365f, 0.5482f, 0.5597f, 0.5710f,
0.5820f, 0.5928f, 0.6033f, 0.6136f, 0.6237f, 0.6335f, 0.6431f,
0.6525f, 0.6616f, 0.6706f, 0.6793f, 0.6878f, 0.6961f, 0.7043f,
0.7122f, 0.7199f, 0.7275f, 0.7349f, 0.7421f, 0.7491f, 0.7559f,
0.7626f, 0.7692f, 0.7756f, 0.7818f, 0.7879f, 0.7938f, 0.7996f,
0.8053f, 0.8108f, 0.8162f, 0.8215f, 0.8266f, 0.8317f, 0.8366f,
0.8414f, 0.8461f, 0.8507f, 0.8551f, 0.8595f, 0.8638f, 0.8679f,
0.8720f, 0.8760f, 0.8798f, 0.8836f, 0.8873f, 0.8909f, 0.8945f,
0.8979f, 0.9013f, 0.9046f, 0.9078f, 0.9109f, 0.9139f, 0.9169f,
0.9198f, 0.9227f, 0.9254f, 0.9281f, 0.9307f, 0.9333f, 0.9358f,
0.9382f, 0.9406f, 0.9429f, 0.9452f, 0.9474f, 0.9495f, 0.9516f,
0.9536f, 0.9556f, 0.9575f, 0.9594f, 0.9612f, 0.9629f, 0.9646f,
0.9663f, 0.9679f, 0.9695f, 0.9710f, 0.9725f, 0.9739f, 0.9753f,
0.9766f, 0.9779f, 0.9791f, 0.9803f, 0.9815f, 0.9826f, 0.9837f,
0.9848f, 0.9858f, 0.9867f, 0.9877f, 0.9885f, 0.9894f, 0.9902f,
0.9910f, 0.9917f, 0.9924f, 0.9931f, 0.9937f, 0.9944f, 0.9949f,
0.9955f, 0.9960f, 0.9964f, 0.9969f, 0.9973f, 0.9977f, 0.9980f,
0.9984f, 0.9986f, 0.9989f, 0.9991f, 0.9993f, 0.9995f, 0.9997f,
0.9998f, 0.9999f, 0.9999f, 1.0000f, 1.0000f
};
public FastOutSlowInInterpolator() {
super(VALUES);
}
}
|
castorflex/SmoothProgressBar
|
sample/src/main/java/fr/castorflex/android/smoothprogressbar/sample/FastOutSlowInInterpolator.java
|
Java
|
apache-2.0
| 2,249
|
/**
* Copyright (c) 2017, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved.
*
* WSO2.Telco Inc. licences this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wso2telco.workflow.approval.exception;
public class ApprovalWorkflowException extends Exception {
private static final long serialVersionUID = -8281288328030356863L;
public ApprovalWorkflowException(String message) {
super(message);
}
public ApprovalWorkflowException(String message, Throwable cause) {
super(message, cause);
}
}
|
azhamn/component-dep
|
components/workflow/workflow-approval/src/main/java/com/wso2telco/workflow/approval/exception/ApprovalWorkflowException.java
|
Java
|
apache-2.0
| 1,039
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) The GNU Lesser General Public License as published by the Free *
* Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* This library 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
#include "ode/ode.h"
#include "objects.h"
#include "joint.h"
#include "util.h"
#define ALLOCA dALLOCA16
//****************************************************************************
// Auto disabling
void dInternalHandleAutoDisabling (dxWorld *world, dReal stepsize)
{
/*
dxBody *bb;
for (bb=world->firstbody; bb; bb=(dxBody*)bb->next) {
// nothing to do unless this body is currently enabled and has
// the auto-disable flag set
if ((bb->flags & (dxBodyAutoDisable|dxBodyDisabled)) != dxBodyAutoDisable) continue;
// see if the body is idle
int idle = 1; // initial assumption
dReal lspeed2 = dDOT(bb->lvel,bb->lvel);
if (lspeed2 > bb->adis.linear_threshold) {
idle = 0; // moving fast - not idle
}
else {
dReal aspeed = dDOT(bb->avel,bb->avel);
if (aspeed > bb->adis.angular_threshold) {
idle = 0; // turning fast - not idle
}
}
// if it's idle, accumulate steps and time.
// these counters won't overflow because this code doesn't run for disabled bodies.
if (idle) {
bb->adis_stepsleft--;
bb->adis_timeleft -= stepsize;
}
else {
bb->adis_stepsleft = bb->adis.idle_steps;
bb->adis_timeleft = bb->adis.idle_time;
}
// disable the body if it's idle for a long enough time
if (bb->adis_stepsleft < 0 && bb->adis_timeleft < 0) {
bb->flags |= dxBodyDisabled;
}
}
*/
}
//****************************************************************************
// body rotation
// return sin(x)/x. this has a singularity at 0 so special handling is needed
// for small arguments.
static inline dReal sinc (dReal x)
{
// if |x| < 1e-4 then use a taylor series expansion. this two term expansion
// is actually accurate to one LS bit within this range if double precision
// is being used - so don't worry!
if (dFabs(x) < 1.0e-4) return REAL(1.0) - x*x*REAL(0.166666666666666666667);
else return dSin(x)/x;
}
// given a body b, apply its linear and angular rotation over the time
// interval h, thereby adjusting its position and orientation.
void dxStepBody (dxBody *b, dReal h)
{
int j;
#ifdef DEBUG_VALID
dIASSERT(dValid(b->avel[0])&&dValid(b->avel[1])&&dValid(b->avel[2]));
#endif
// handle linear velocity
for (j=0; j<3; j++) b->pos[j] += h * b->lvel[j];
if (b->flags & dxBodyFlagFiniteRotation) {
dVector3 irv; // infitesimal rotation vector
dQuaternion q; // quaternion for finite rotation
if (b->flags & dxBodyFlagFiniteRotationAxis) {
// split the angular velocity vector into a component along the finite
// rotation axis, and a component orthogonal to it.
dVector3 frv; // finite rotation vector
dReal k = dDOT (b->finite_rot_axis,b->avel);
frv[0] = b->finite_rot_axis[0] * k;
frv[1] = b->finite_rot_axis[1] * k;
frv[2] = b->finite_rot_axis[2] * k;
irv[0] = b->avel[0] - frv[0];
irv[1] = b->avel[1] - frv[1];
irv[2] = b->avel[2] - frv[2];
// make a rotation quaternion q that corresponds to frv * h.
// compare this with the full-finite-rotation case below.
h *= REAL(0.5);
dReal theta = k * h;
q[0] = dCos(theta);
dReal s = sinc(theta) * h;
q[1] = frv[0] * s;
q[2] = frv[1] * s;
q[3] = frv[2] * s;
}
else {
// make a rotation quaternion q that corresponds to w * h
dReal wlen = dSqrt (b->avel[0]*b->avel[0] + b->avel[1]*b->avel[1] +
b->avel[2]*b->avel[2]);
h *= REAL(0.5);
dReal theta = wlen * h;
q[0] = dCos(theta);
dReal s = sinc(theta) * h;
q[1] = b->avel[0] * s;
q[2] = b->avel[1] * s;
q[3] = b->avel[2] * s;
}
// do the finite rotation
dQuaternion q2;
dQMultiply0 (q2,q,b->q);
for (j=0; j<4; j++) b->q[j] = q2[j];
// do the infitesimal rotation if required
if (b->flags & dxBodyFlagFiniteRotationAxis) {
dReal dq[4];
dWtoDQ (irv,b->q,dq);
for (j=0; j<4; j++) b->q[j] += h * dq[j];
}
}
else {
// the normal way - do an infitesimal rotation
dReal dq[4];
dWtoDQ (b->avel,b->q,dq);
for (j=0; j<4; j++) b->q[j] += h * dq[j];
}
// normalize the quaternion and convert it to a rotation matrix
dNormalize4 (b->q);
dQtoR (b->q,b->R);
// notify all attached geoms that this body has moved
for (dxGeom *geom = b->geom; geom; geom = dGeomGetBodyNext (geom))
dGeomMoved (geom);
#ifdef DEBUG_VALID
dIASSERT(dValid(b->avel[0])&&dValid(b->avel[1])&&dValid(b->avel[2]));
#endif
}
//****************************************************************************
// island processing
// this groups all joints and bodies in a world into islands. all objects
// in an island are reachable by going through connected bodies and joints.
// each island can be simulated separately.
// note that joints that are not attached to anything will not be included
// in any island, an so they do not affect the simulation.
//
// this function starts new island from unvisited bodies. however, it will
// never start a new islands from a disabled body. thus islands of disabled
// bodies will not be included in the simulation. disabled bodies are
// re-enabled if they are found to be part of an active island.
//no need Island collecting! @slipch
/*
void dxProcessIslands (dxWorld *world, dReal stepsize, dstepper_fn_t stepper)
{
dxBody *b,*bb,**body;
dxJoint *j,**joint;
// nothing to do if no bodies
if (world->nb <= 0) return;
// handle auto-disabling of bodies
dInternalHandleAutoDisabling (world,stepsize);
// make arrays for body and joint lists (for a single island) to go into
body = (dxBody**) ALLOCA (world->nb * sizeof(dxBody*));
joint = (dxJoint**) ALLOCA (world->nj * sizeof(dxJoint*));
int bcount = 0; // number of bodies in `body'
int jcount = 0; // number of joints in `joint'
// set all body/joint tags to 0
for (b=world->firstbody; b; b=(dxBody*)b->next) b->tag = 0;
for (j=world->firstjoint; j; j=(dxJoint*)j->next) j->tag = 0;
// allocate a stack of unvisited bodies in the island. the maximum size of
// the stack can be the lesser of the number of bodies or joints, because
// new bodies are only ever added to the stack by going through untagged
// joints. all the bodies in the stack must be tagged!
int stackalloc = (world->nj < world->nb) ? world->nj : world->nb;
dxBody **stack = (dxBody**) ALLOCA (stackalloc * sizeof(dxBody*));
for (bb=world->firstbody; bb; bb=(dxBody*)bb->next) {
// get bb = the next enabled, untagged body, and tag it
if (bb->tag || (bb->flags & dxBodyDisabled)) continue;
bb->tag = 1;
// tag all bodies and joints starting from bb.
int stacksize = 0;
b = bb;
body[0] = bb;
bcount = 1;
jcount = 0;
goto quickstart;
while (stacksize > 0) {
b = stack[--stacksize]; // pop body off stack
body[bcount++] = b; // put body on body list
quickstart:
// traverse and tag all body's joints, add untagged connected bodies
// to stack
for (dxJointNode *n=b->firstjoint; n; n=n->next) {
if (!n->joint->tag) {
n->joint->tag = 1;
joint[jcount++] = n->joint;
if (n->body && !n->body->tag) {
n->body->tag = 1;
stack[stacksize++] = n->body;
}
}
}
dIASSERT(stacksize <= world->nb);
dIASSERT(stacksize <= world->nj);
}
// now do something with body and joint lists
stepper (world,body,bcount,joint,jcount,stepsize);
// what we've just done may have altered the body/joint tag values.
// we must make sure that these tags are nonzero.
// also make sure all bodies are in the enabled state.
int i;
for (i=0; i<bcount; i++) {
body[i]->tag = 1;
body[i]->flags &= ~dxBodyDisabled;
}
for (i=0; i<jcount; i++) joint[i]->tag = 1;
}
// if debugging, check that all objects (except for disabled bodies,
// unconnected joints, and joints that are connected to disabled bodies)
// were tagged.
# ifndef dNODEBUG
for (b=world->firstbody; b; b=(dxBody*)b->next) {
if (b->flags & dxBodyDisabled) {
if (b->tag) dDebug (0,"disabled body tagged");
}
else {
if (!b->tag) dDebug (0,"enabled body not tagged");
}
}
for (j=world->firstjoint; j; j=(dxJoint*)j->next) {
if ((j->node[0].body && (j->node[0].body->flags & dxBodyDisabled)==0) ||
(j->node[1].body && (j->node[1].body->flags & dxBodyDisabled)==0)) {
if (!j->tag) dDebug (0,"attached enabled joint not tagged");
}
else {
if (j->tag) dDebug (0,"unattached or disabled joint tagged");
}
}
# endif
}
*/
void dxProcessIslands (dxWorld *world, dReal stepsize, dstepper_fn_t stepper)
{
// nothing to do if no bodies
if (world->nb <= 0)
return;
# ifdef TIMING
dTimerStart ("creating joint and body arrays");
# endif
dxBody **bodies, *body;
dxJoint **joints, *joint;
joints = (dxJoint **) ALLOCA (world->nj * sizeof (dxJoint *));
bodies = (dxBody **) ALLOCA (world->nb * sizeof (dxBody *));
int nj = 0;
for (joint = world->firstjoint; joint; joint = (dxJoint *) joint->next)
joints[nj++] = joint;
int nb = 0;
for (body = world->firstbody; body; body = (dxBody *) body->next)
{
body->flags &= ~dxBodyDisabled;
bodies[nb++] = body;
}
// now do something with body and joint lists
stepper (world,bodies,nb,joints,nj,stepsize);
//stepper (world,body,bcount,joint,jcount,stepsize);
# ifdef TIMING
dTimerEnd ();
dTimerReport (stdout, 1);
# endif
}
|
OLR-xray/OLR-3.0
|
src/xray/xrODE/ode/src/util.cpp
|
C++
|
apache-2.0
| 10,985
|
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Client for interacting with the Stackdriver Logging API"""
import traceback
import google.cloud.logging.client
import six
class HTTPContext(object):
"""HTTPContext defines an object that captures the parameter for the
httpRequest part of Error Reporting API
:type method: str
:param method: The type of HTTP request, such as GET, POST, etc.
:type url: str
:param url: The URL of the request
:type user_agent: str
:param user_agent: The user agent information that is provided with the
request.
:type referrer: str
:param referrer: The referrer information that is provided with the
request.
:type response_status_code: int
:param response_status_code: The HTTP response status code for the request.
:type remote_ip: str
:param remote_ip: The IP address from which the request originated. This
can be IPv4, IPv6, or a token which is derived from
the IP address, depending on the data that has been
provided in the error report.
"""
def __init__(self, method=None, url=None,
user_agent=None, referrer=None,
response_status_code=None, remote_ip=None):
self.method = method
self.url = url
# intentionally camel case for mapping to JSON API expects
# pylint: disable=invalid-name
self.userAgent = user_agent
self.referrer = referrer
self.responseStatusCode = response_status_code
self.remoteIp = remote_ip
class Client(object):
"""Error Reporting client. Currently Error Reporting is done by creating
a Logging client.
:type project: str
:param project: the project which the client acts on behalf of. If not
passed falls back to the default inferred from the
environment.
:type credentials: :class:`oauth2client.client.OAuth2Credentials` or
:class:`NoneType`
:param credentials: The OAuth2 Credentials to use for the connection
owned by this client. If not passed (and if no ``http``
object is passed), falls back to the default inferred
from the environment.
:type http: :class:`httplib2.Http` or class that defines ``request()``.
:param http: An optional HTTP object to make requests. If not passed, an
``http`` object is created that is bound to the
``credentials`` for the current object.
:type service: str
:param service: An identifier of the service, such as the name of the
executable, job, or Google App Engine service name. This
field is expected to have a low number of values that are
relatively stable over time, as opposed to version,
which can be changed whenever new code is deployed.
:type version: str
:param version: Represents the source code version that the developer
provided, which could represent a version label or a Git
SHA-1 hash, for example. If the developer did not provide
a version, the value is set to default.
:raises: :class:`ValueError` if the project is neither passed in nor
set in the environment.
"""
def __init__(self, project=None,
credentials=None,
http=None,
service=None,
version=None):
self.logging_client = google.cloud.logging.client.Client(
project, credentials, http)
self.service = service if service else self.DEFAULT_SERVICE
self.version = version
DEFAULT_SERVICE = 'python'
def _send_error_report(self, message,
report_location=None, http_context=None, user=None):
"""Makes the call to the Error Reporting API via the log stream.
This is the lower-level interface to build the payload, generally
users will use either report() or report_exception() to automatically
gather the parameters for this method.
Currently this method sends the Error Report by formatting a structured
log message according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
:param message: The stack trace that was reported or logged by the
service.
:type report_location: dict
:param report_location: The location in the source code where the
decision was made to report the error, usually the place
where it was logged. For a logged exception this would be the
source line where the exception is logged, usually close to
the place where it was caught.
This should be a Python dict that contains the keys 'filePath',
'lineNumber', and 'functionName'
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This can
be a user ID, an email address, or an arbitrary token that
uniquely identifies the user. When sending an error
report, leave this field empty if the user was not
logged in. In this case the Error Reporting system will
use other data, such as remote IP address,
to distinguish affected users.
"""
payload = {
'serviceContext': {
'service': self.service,
},
'message': '{0}'.format(message)
}
if self.version:
payload['serviceContext']['version'] = self.version
if report_location or http_context or user:
payload['context'] = {}
if report_location:
payload['context']['reportLocation'] = report_location
if http_context:
http_context_dict = http_context.__dict__
# strip out None values
payload['context']['httpContext'] = {
key: value for key, value in six.iteritems(http_context_dict)
if value is not None
}
if user:
payload['context']['user'] = user
logger = self.logging_client.logger('errors')
logger.log_struct(payload)
def report(self, message, http_context=None, user=None):
""" Reports a message to Stackdriver Error Reporting
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
:param message: A user-supplied message to report
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This
can be a user ID, an email address, or an arbitrary
token that uniquely identifies the user. When sending
an error report, leave this field empty if the user
was not logged in. In this case the Error Reporting
system will use other data, such as remote IP address,
to distinguish affected users.
Example:
.. code-block:: python
>>> client.report("Something went wrong!")
"""
stack = traceback.extract_stack()
last_call = stack[-2]
file_path = last_call[0]
line_number = last_call[1]
function_name = last_call[2]
report_location = {
'filePath': file_path,
'lineNumber': line_number,
'functionName': function_name
}
self._send_error_report(message,
http_context=http_context,
user=user,
report_location=report_location)
def report_exception(self, http_context=None, user=None):
""" Reports the details of the latest exceptions to Stackdriver Error
Reporting.
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This
can be a user ID, an email address, or an arbitrary
token that uniquely identifies the user. When sending an
error report, leave this field empty if the user was
not logged in. In this case the Error Reporting system
will use other data, such as remote IP address,
to distinguish affected users.
Example::
>>> try:
>>> raise NameError
>>> except Exception:
>>> client.report_exception()
"""
self._send_error_report(traceback.format_exc(),
http_context=http_context,
user=user)
|
jgeewax/gcloud-python
|
error_reporting/google/cloud/error_reporting/client.py
|
Python
|
apache-2.0
| 10,193
|
+++
Title = "Jeffrey Snover"
Twitter = "jsnover"
image = "jeffrey-snover.png"
type = "speaker"
linktitle = "jeffrey-snover"
+++
Jeffrey Snover is a Technical Fellow at Microsoft and the Chief Architect for Azure Storage and Edge Cloud Group where he focuses on Azure Stack. Snover is the inventor of Windows PowerShell, an object-based distributed automation engine, scripting language, and command line shell. Snover joined Microsoft in 1999 as divisional architect for the Management and Services Division, providing technical direction across Microsoft's management technologies and products.
Snover has over 35 years of industry experience with a focus on management technologies and solutions. He was an architect in the office of the CTO at Tivoli and a development manager at NetView. He has worked also as a consulting engineer and development manager at DEC, where he led various network and systems management projects.
Snover is a frequent speaker at industry and research conferences on a variety of cloud, management and language topics.
|
gomex/devopsdays-web
|
content/events/2019-seattle/speakers/jeffrey-snover.md
|
Markdown
|
apache-2.0
| 1,057
|
// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "codegen/llvm-codegen.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <boost/thread/mutex.hpp>
#include <llvm/ADT/Triple.h>
#include <llvm/Analysis/InstructionSimplify.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/Linker.h>
#include <llvm/PassManager.h>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/NoFolder.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/system_error.h>
#include <llvm/Target/TargetLibraryInfo.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include "common/logging.h"
#include "codegen/codegen-anyval.h"
#include "codegen/subexpr-elimination.h"
#include "codegen/instruction-counter.h"
#include "impala-ir/impala-ir-names.h"
#include "runtime/hdfs-fs-cache.h"
#include "util/cpu-info.h"
#include "util/hdfs-util.h"
#include "util/path-builder.h"
using namespace boost;
using namespace llvm;
using namespace std;
DEFINE_bool(print_llvm_ir_instruction_count, false,
"if true, prints the instruction counts of all JIT'd functions");
DEFINE_bool(disable_optimization_passes, false,
"if true, disables llvm optimization passes (used for testing)");
DEFINE_bool(dump_ir, false, "if true, output IR after optimization passes");
DEFINE_string(unopt_module_dir, "",
"if set, saves unoptimized generated IR modules to the specified directory.");
DEFINE_string(opt_module_dir, "",
"if set, saves optimized generated IR modules to the specified directory.");
DECLARE_string(local_library_dir);
namespace impala {
static mutex llvm_initialization_lock;
static bool llvm_initialized = false;
void LlvmCodeGen::InitializeLlvm(bool load_backend) {
mutex::scoped_lock initialization_lock(llvm_initialization_lock);
if (llvm_initialized) return;
// This allocates a global llvm struct and enables multithreading.
// There is no real good time to clean this up but we only make it once.
bool result = llvm::llvm_start_multithreaded();
DCHECK(result);
// This can *only* be called once per process and is used to setup
// dynamically linking jitted code.
llvm::InitializeNativeTarget();
llvm_initialized = true;
if (load_backend) {
string path;
// For test env, we have to load libfesupport.so to provide sym for LLVM.
PathBuilder::GetFullBuildPath("service/libfesupport.so", &path);
bool failed = llvm::sys::DynamicLibrary::LoadLibraryPermanently(path.c_str());
DCHECK_EQ(failed, 0);
}
}
LlvmCodeGen::LlvmCodeGen(ObjectPool* pool, const string& id) :
id_(id),
profile_(pool, "CodeGen"),
optimizations_enabled_(false),
is_corrupt_(false),
is_compiled_(false),
context_(new llvm::LLVMContext()),
module_(NULL),
execution_engine_(NULL),
debug_trace_fn_(NULL) {
DCHECK(llvm_initialized) << "Must call LlvmCodeGen::InitializeLlvm first.";
load_module_timer_ = ADD_TIMER(&profile_, "LoadTime");
prepare_module_timer_ = ADD_TIMER(&profile_, "PrepareTime");
module_file_size_ = ADD_COUNTER(&profile_, "ModuleFileSize", TUnit::BYTES);
codegen_timer_ = ADD_TIMER(&profile_, "CodegenTime");
optimization_timer_ = ADD_TIMER(&profile_, "OptimizationTime");
compile_timer_ = ADD_TIMER(&profile_, "CompileTime");
loaded_functions_.resize(IRFunction::FN_END);
}
Status LlvmCodeGen::LoadFromFile(ObjectPool* pool,
const string& file, const string& id, scoped_ptr<LlvmCodeGen>* codegen) {
codegen->reset(new LlvmCodeGen(pool, id));
SCOPED_TIMER((*codegen)->profile_.total_time_counter());
Module* loaded_module;
RETURN_IF_ERROR(LoadModule(codegen->get(), file, &loaded_module));
(*codegen)->module_ = loaded_module;
return (*codegen)->Init();
}
Status LlvmCodeGen::LoadModule(LlvmCodeGen* codegen, const string& file,
Module** module) {
OwningPtr<MemoryBuffer> file_buffer;
{
SCOPED_TIMER(codegen->load_module_timer_);
llvm::error_code err = MemoryBuffer::getFile(file, file_buffer);
if (err.value() != 0) {
stringstream ss;
ss << "Could not load module " << file << ": " << err.message();
return Status(ss.str());
}
}
COUNTER_ADD(codegen->module_file_size_, file_buffer->getBufferSize());
SCOPED_TIMER(codegen->prepare_module_timer_);
string error;
*module = ParseBitcodeFile(file_buffer.get(), codegen->context(), &error);
if (*module == NULL) {
stringstream ss;
ss << "Could not parse module " << file << ": " << error;
return Status(ss.str());
}
return Status::OK;
}
// TODO: Create separate counters/timers (file size, load time) for each module linked
Status LlvmCodeGen::LinkModule(const string& file) {
if (linked_modules_.find(file) != linked_modules_.end()) return Status::OK;
SCOPED_TIMER(profile_.total_time_counter());
Module* new_module;
RETURN_IF_ERROR(LoadModule(this, file, &new_module));
string error_msg;
bool error =
Linker::LinkModules(module_, new_module, Linker::DestroySource, &error_msg);
if (error) {
stringstream ss;
ss << "Problem linking " << file << " to main module: " << error_msg;
return Status(ss.str());
}
linked_modules_.insert(file);
return Status::OK;
}
Status LlvmCodeGen::LoadImpalaIR(
ObjectPool* pool, const string& id, scoped_ptr<LlvmCodeGen>* codegen_ret) {
// Load the statically cross compiled file. We cannot load an ll file with sse
// instructions on a machine without sse support (the load fails, doesn't matter
// if those instructions end up getting run or not).
string module_file;
if (CpuInfo::IsSupported(CpuInfo::SSE4_2)) {
PathBuilder::GetFullPath("llvm-ir/impala-sse.ll", &module_file);
} else {
PathBuilder::GetFullPath("llvm-ir/impala-no-sse.ll", &module_file);
}
RETURN_IF_ERROR(LoadFromFile(pool, module_file, id, codegen_ret));
LlvmCodeGen* codegen = codegen_ret->get();
// Parse module for cross compiled functions and types
SCOPED_TIMER(codegen->profile_.total_time_counter());
SCOPED_TIMER(codegen->prepare_module_timer_);
// Get type for StringValue
codegen->string_val_type_ = codegen->GetType(StringValue::LLVM_CLASS_NAME);
// Get type for TimestampValue
codegen->timestamp_val_type_ = codegen->GetType(TimestampValue::LLVM_CLASS_NAME);
// Verify size is correct
const DataLayout* data_layout = codegen->execution_engine()->getDataLayout();
const StructLayout* layout =
data_layout->getStructLayout(static_cast<StructType*>(codegen->string_val_type_));
if (layout->getSizeInBytes() != sizeof(StringValue)) {
DCHECK_EQ(layout->getSizeInBytes(), sizeof(StringValue));
return Status("Could not create llvm struct type for StringVal");
}
// Parse functions from module
vector<Function*> functions;
codegen->GetFunctions(&functions);
int parsed_functions = 0;
for (int i = 0; i < functions.size(); ++i) {
string fn_name = functions[i]->getName();
for (int j = IRFunction::FN_START; j < IRFunction::FN_END; ++j) {
// Substring match to match precompiled functions. The compiled function names
// will be mangled.
// TODO: reconsider this. Substring match is probably not strict enough but
// undoing the mangling is no fun either.
if (fn_name.find(FN_MAPPINGS[j].fn_name) != string::npos) {
if (codegen->loaded_functions_[FN_MAPPINGS[j].fn] != NULL) {
return Status("Duplicate definition found for function: " + fn_name);
}
functions[i]->addFnAttr(Attribute::AlwaysInline);
codegen->loaded_functions_[FN_MAPPINGS[j].fn] = functions[i];
++parsed_functions;
}
}
}
if (parsed_functions != IRFunction::FN_END) {
stringstream ss;
ss << "Unable to find these precompiled functions: ";
bool first = true;
for (int i = IRFunction::FN_START; i != IRFunction::FN_END; ++i) {
if (codegen->loaded_functions_[i] == NULL) {
if (!first) ss << ", ";
ss << FN_MAPPINGS[i].fn_name;
first = false;
}
}
return Status(ss.str());
}
return Status::OK;
}
Status LlvmCodeGen::Init() {
if (module_ == NULL) {
module_ = new Module(id_, context());
}
llvm::CodeGenOpt::Level opt_level = CodeGenOpt::Aggressive;
#ifndef NDEBUG
// For debug builds, don't generate JIT compiled optimized assembly.
// This takes a non-neglible amount of time (~.5 ms per function) and
// blows up the fe tests (which take ~10-20 ms each).
opt_level = CodeGenOpt::None;
#endif
execution_engine_.reset(
ExecutionEngine::createJIT(module_, &error_string_, NULL, opt_level));
if (execution_engine_ == NULL) {
// execution_engine_ will take ownership of the module if it is created
delete module_;
stringstream ss;
ss << "Could not create ExecutionEngine: " << error_string_;
return Status(ss.str());
}
void_type_ = Type::getVoidTy(context());
ptr_type_ = PointerType::get(GetType(TYPE_TINYINT), 0);
true_value_ = ConstantInt::get(context(), APInt(1, true, true));
false_value_ = ConstantInt::get(context(), APInt(1, false, true));
RETURN_IF_ERROR(LoadIntrinsics());
return Status::OK;
}
LlvmCodeGen::~LlvmCodeGen() {
for (map<Function*, bool>::iterator iter = jitted_functions_.begin();
iter != jitted_functions_.end(); ++iter) {
execution_engine_->freeMachineCodeForFunction(iter->first);
}
}
void LlvmCodeGen::EnableOptimizations(bool enable) {
optimizations_enabled_ = enable;
}
string LlvmCodeGen::GetIR(bool full_module) const {
string str;
raw_string_ostream stream(str);
if (full_module) {
module_->print(stream, NULL);
} else {
for (int i = 0; i < codegend_functions_.size(); ++i) {
codegend_functions_[i]->print(stream, NULL);
}
}
return str;
}
Type* LlvmCodeGen::GetType(const ColumnType& type) {
switch (type.type) {
case TYPE_NULL:
return Type::getInt1Ty(context());
case TYPE_BOOLEAN:
return Type::getInt1Ty(context());
case TYPE_TINYINT:
return Type::getInt8Ty(context());
case TYPE_SMALLINT:
return Type::getInt16Ty(context());
case TYPE_INT:
return Type::getInt32Ty(context());
case TYPE_BIGINT:
return Type::getInt64Ty(context());
case TYPE_FLOAT:
return Type::getFloatTy(context());
case TYPE_DOUBLE:
return Type::getDoubleTy(context());
case TYPE_STRING:
case TYPE_VARCHAR:
case TYPE_CHAR:
return string_val_type_;
case TYPE_TIMESTAMP:
return timestamp_val_type_;
case TYPE_DECIMAL:
return Type::getIntNTy(context(), type.GetByteSize() * 8);
default:
DCHECK(false) << "Invalid type: " << type;
return NULL;
}
}
PointerType* LlvmCodeGen::GetPtrType(const ColumnType& type) {
return PointerType::get(GetType(type), 0);
}
Type* LlvmCodeGen::GetType(const string& name) {
Type* type = module_->getTypeByName(name);
DCHECK_NOTNULL(type);
return type;
}
PointerType* LlvmCodeGen::GetPtrType(const string& name) {
Type* type = GetType(name);
DCHECK(type != NULL) << name;
return PointerType::get(type, 0);
}
PointerType* LlvmCodeGen::GetPtrType(Type* type) {
return PointerType::get(type, 0);
}
// Llvm doesn't let you create a PointerValue from a c-side ptr. Instead
// cast it to an int and then to 'type'.
Value* LlvmCodeGen::CastPtrToLlvmPtr(Type* type, const void* ptr) {
Constant* const_int = ConstantInt::get(Type::getInt64Ty(context()), (int64_t)ptr);
return ConstantExpr::getIntToPtr(const_int, type);
}
Value* LlvmCodeGen::GetIntConstant(PrimitiveType type, int64_t val) {
switch (type) {
case TYPE_TINYINT:
return ConstantInt::get(context(), APInt(8, val));
case TYPE_SMALLINT:
return ConstantInt::get(context(), APInt(16, val));
case TYPE_INT:
return ConstantInt::get(context(), APInt(32, val));
case TYPE_BIGINT:
return ConstantInt::get(context(), APInt(64, val));
default:
DCHECK(false);
return NULL;
}
}
AllocaInst* LlvmCodeGen::CreateEntryBlockAlloca(Function* f, const NamedVariable& var) {
IRBuilder<> tmp(&f->getEntryBlock(), f->getEntryBlock().begin());
AllocaInst* alloca = tmp.CreateAlloca(var.type, 0, var.name.c_str());
if (var.type == GetType(CodegenAnyVal::LLVM_DECIMALVAL_NAME)) {
// Generated functions may manipulate DecimalVal arguments via SIMD instructions such
// as 'movaps' that require 16-byte memory alignment. LLVM uses 8-byte alignment by
// default, so explicitly set the alignment for DecimalVals.
alloca->setAlignment(16);
}
return alloca;
}
AllocaInst* LlvmCodeGen::CreateEntryBlockAlloca(const LlvmBuilder& builder, Type* type,
const char* name) {
return CreateEntryBlockAlloca(builder.GetInsertBlock()->getParent(),
NamedVariable(name, type));
}
void LlvmCodeGen::CreateIfElseBlocks(Function* fn, const string& if_name,
const string& else_name, BasicBlock** if_block, BasicBlock** else_block,
BasicBlock* insert_before) {
*if_block = BasicBlock::Create(context(), if_name, fn, insert_before);
*else_block = BasicBlock::Create(context(), else_name, fn, insert_before);
}
Function* LlvmCodeGen::GetLibCFunction(FnPrototype* prototype) {
if (external_functions_.find(prototype->name()) != external_functions_.end()) {
return external_functions_[prototype->name()];
}
Function* func = prototype->GeneratePrototype();
external_functions_[prototype->name()] = func;
return func;
}
Function* LlvmCodeGen::GetFunction(IRFunction::Type function) {
DCHECK(loaded_functions_[function] != NULL);
return loaded_functions_[function];
}
// There is an llvm bug (#10957) that causes the first step of the verifier to always
// abort the process if it runs into an issue and ignores ReturnStatusAction. This
// would cause impalad to go down if one query has a problem.
// To work around this, we will copy that step here and not abort on error.
// TODO: doesn't seem there is much traction in getting this fixed but we'll see
bool LlvmCodeGen::VerifyFunction(Function* fn) {
if (is_corrupt_) return false;
// Verify the function is valid. Adapted from the pre-verifier function pass.
for (Function::iterator i = fn->begin(), e = fn->end(); i != e; ++i) {
if (i->empty() || !i->back().isTerminator()) {
LOG(ERROR) << "Basic block must end with terminator: \n" << Print(&(*i));
is_corrupt_ = true;
break;
}
}
if (!is_corrupt_) is_corrupt_ = llvm::verifyFunction(*fn, PrintMessageAction);
if (is_corrupt_) {
string fn_name = fn->getName(); // llvm has some fancy operator overloading
LOG(ERROR) << "Function corrupt: " << fn_name;
fn->dump();
return false;
}
return true;
}
LlvmCodeGen::FnPrototype::FnPrototype(
LlvmCodeGen* gen, const string& name, Type* ret_type) :
codegen_(gen), name_(name), ret_type_(ret_type) {
DCHECK(!codegen_->is_compiled_) << "Not valid to add additional functions";
}
Function* LlvmCodeGen::FnPrototype::GeneratePrototype(
LlvmBuilder* builder, Value** params) {
vector<Type*> arguments;
for (int i = 0; i < args_.size(); ++i) {
arguments.push_back(args_[i].type);
}
FunctionType* prototype = FunctionType::get(ret_type_, arguments, false);
Function* fn = Function::Create(
prototype, Function::ExternalLinkage, name_, codegen_->module_);
DCHECK(fn != NULL);
// Name the arguments
int idx = 0;
for (Function::arg_iterator iter = fn->arg_begin();
iter != fn->arg_end(); ++iter, ++idx) {
iter->setName(args_[idx].name);
if (params != NULL) params[idx] = iter;
}
if (builder != NULL) {
BasicBlock* entry_block = BasicBlock::Create(codegen_->context(), "entry", fn);
builder->SetInsertPoint(entry_block);
}
codegen_->codegend_functions_.push_back(fn);
return fn;
}
Function* LlvmCodeGen::ReplaceCallSites(Function* caller, bool update_in_place,
Function* new_fn, const string& replacee_name, int* replaced) {
DCHECK(caller->getParent() == module_);
DCHECK(caller != NULL);
DCHECK(new_fn != NULL);
if (!update_in_place) {
caller = CloneFunction(caller);
} else if (jitted_functions_.find(caller) != jitted_functions_.end()) {
// This function is already dynamically linked, unlink it.
execution_engine_->freeMachineCodeForFunction(caller);
jitted_functions_.erase(caller);
}
*replaced = 0;
// loop over all blocks
Function::iterator block_iter = caller->begin();
while (block_iter != caller->end()) {
BasicBlock* block = block_iter++;
// loop over instructions in the block
BasicBlock::iterator instr_iter = block->begin();
while (instr_iter != block->end()) {
Instruction* instr = instr_iter++;
// look for call instructions
if (CallInst::classof(instr)) {
CallInst* call_instr = reinterpret_cast<CallInst*>(instr);
Function* old_fn = call_instr->getCalledFunction();
// look for call instruction that matches the name
if (old_fn != NULL && old_fn->getName().find(replacee_name) != string::npos) {
// Replace the called function
call_instr->setCalledFunction(new_fn);
++*replaced;
}
}
}
}
return caller;
}
Function* LlvmCodeGen::CloneFunction(Function* fn) {
ValueToValueMapTy dummy_vmap;
// CloneFunction() automatically gives the new function a unique name
Function* fn_clone = llvm::CloneFunction(fn, dummy_vmap, false);
fn_clone->copyAttributesFrom(fn);
module_->getFunctionList().push_back(fn_clone);
return fn_clone;
}
// TODO: revisit this. Inlining all call sites might not be the right call. We
// probably need to make this more complicated and somewhat cost based or write
// our own optimization passes.
int LlvmCodeGen::InlineCallSites(Function* fn, bool skip_registered_fns) {
int functions_inlined = 0;
// Collect all call sites
vector<CallInst*> call_sites;
// loop over all blocks
Function::iterator block_iter = fn->begin();
while (block_iter != fn->end()) {
BasicBlock* block = block_iter++;
// loop over instructions in the block
BasicBlock::iterator instr_iter = block->begin();
while (instr_iter != block->end()) {
Instruction* instr = instr_iter++;
// look for call instructions
if (CallInst::classof(instr)) {
CallInst* call_instr = reinterpret_cast<CallInst*>(instr);
Function* called_fn = call_instr->getCalledFunction();
// called_fn will be NULL if it's a virtual function call, etc.
if (called_fn == NULL || !called_fn->hasFnAttribute(Attribute::AlwaysInline)) {
continue;
}
if (skip_registered_fns) {
if (registered_exprs_.find(called_fn) != registered_exprs_.end()) {
continue;
}
}
call_sites.push_back(call_instr);
}
}
}
// Inline all call sites. InlineFunction can still fail (function is recursive, etc)
// but that always leaves the original function in a consistent state
for (int i = 0; i < call_sites.size(); ++i) {
llvm::InlineFunctionInfo info;
if (llvm::InlineFunction(call_sites[i], info)) {
++functions_inlined;
}
}
return functions_inlined;
}
Function* LlvmCodeGen::OptimizeFunctionWithExprs(Function* fn) {
int num_inlined;
do {
// This assumes that all redundant exprs have been registered.
num_inlined = InlineCallSites(fn, false);
} while (num_inlined > 0);
// TODO(skye): fix subexpression elimination
// SubExprElimination subexpr_elim(this);
// subexpr_elim.Run(fn);
return FinalizeFunction(fn);
}
Function* LlvmCodeGen::FinalizeFunction(Function* function) {
function->addFnAttr(llvm::Attribute::AlwaysInline);
if (!VerifyFunction(function)) {
function->eraseFromParent(); // deletes function
return NULL;
}
if (FLAGS_dump_ir) function->dump();
return function;
}
Status LlvmCodeGen::FinalizeModule() {
DCHECK(!is_compiled_);
is_compiled_ = true;
if (FLAGS_unopt_module_dir.size() != 0) {
string path = FLAGS_unopt_module_dir + "/" + id_ + "_unopt.ll";
fstream f(path.c_str(), fstream::out | fstream::trunc);
if (f.fail()) {
LOG(ERROR) << "Could not save IR to: " << path;
} else {
f << GetIR(true);
f.close();
}
}
if (is_corrupt_) return Status("Module is corrupt.");
SCOPED_TIMER(profile_.total_time_counter());
// Don't waste time optimizing module if there are no functions to JIT. This can happen
// if the codegen object is created but no functions are successfully codegen'd.
if (optimizations_enabled_ && !FLAGS_disable_optimization_passes &&
!fns_to_jit_compile_.empty()) {
OptimizeModule();
}
SCOPED_TIMER(compile_timer_);
// JIT compile all codegen'd functions
for (int i = 0; i < fns_to_jit_compile_.size(); ++i) {
*fns_to_jit_compile_[i].second = JitFunction(fns_to_jit_compile_[i].first);
}
if (FLAGS_opt_module_dir.size() != 0) {
string path = FLAGS_opt_module_dir + "/" + id_ + "_opt.ll";
fstream f(path.c_str(), fstream::out | fstream::trunc);
if (f.fail()) {
LOG(ERROR) << "Could not save IR to: " << path;
} else {
f << GetIR(true);
f.close();
}
}
return Status::OK;
}
void LlvmCodeGen::OptimizeModule() {
SCOPED_TIMER(optimization_timer_);
// This pass manager will construct optimizations passes that are "typical" for
// c/c++ programs. We're relying on llvm to pick the best passes for us.
// TODO: we can likely muck with this to get better compile speeds or write
// our own passes. Our subexpression elimination optimization can be rolled into
// a pass.
PassManagerBuilder pass_builder ;
// 2 maps to -O2
// TODO: should we switch to 3? (3 may not produce different IR than 2 while taking
// longer, but we should check)
pass_builder.OptLevel = 2;
// Don't optimize for code size (this corresponds to -O2/-O3)
pass_builder.SizeLevel = 0;
pass_builder.Inliner = createFunctionInliningPass() ;
// Specifying the data layout is necessary for some optimizations (e.g. removing many
// of the loads/stores produced by structs).
const string& data_layout_str = module_->getDataLayout();
DCHECK(!data_layout_str.empty());
// Before running any other optimization passes, run the internalize pass, giving it
// the names of all functions registered by AddFunctionToJit(), followed by the
// global dead code elimination pass. This causes all functions not registered to be
// JIT'd to be marked as internal, and any internal functions that are not used are
// deleted by DCE pass. This greatly decreases compile time by removing unused code.
vector<const char*> exported_fn_names;
for (int i = 0; i < fns_to_jit_compile_.size(); ++i) {
exported_fn_names.push_back(fns_to_jit_compile_[i].first->getName().data());
}
scoped_ptr<PassManager> module_pass_manager(new PassManager());
module_pass_manager->add(new DataLayout(data_layout_str));
module_pass_manager->add(createInternalizePass(exported_fn_names));
module_pass_manager->add(createGlobalDCEPass());
module_pass_manager->run(*module_);
// Create and run function pass manager
scoped_ptr<FunctionPassManager> fn_pass_manager(new FunctionPassManager(module_));
fn_pass_manager->add(new DataLayout(data_layout_str));
pass_builder.populateFunctionPassManager(*fn_pass_manager);
fn_pass_manager->doInitialization();
for (Module::iterator it = module_->begin(), end = module_->end(); it != end ; ++it) {
if (!it->isDeclaration()) fn_pass_manager->run(*it);
}
fn_pass_manager->doFinalization();
// Create and run module pass manager
module_pass_manager.reset(new PassManager());
module_pass_manager->add(new DataLayout(data_layout_str));
pass_builder.populateModulePassManager(*module_pass_manager);
module_pass_manager->run(*module_);
if (FLAGS_print_llvm_ir_instruction_count) {
for (int i = 0; i < fns_to_jit_compile_.size(); ++i) {
InstructionCounter counter;
counter.visit(*fns_to_jit_compile_[i].first);
VLOG(1) << fns_to_jit_compile_[i].first->getName().str();
VLOG(1) << counter.PrintCounters();
}
}
}
void LlvmCodeGen::AddFunctionToJit(Function* fn, void** fn_ptr) {
Type* decimal_val_type = GetType(CodegenAnyVal::LLVM_DECIMALVAL_NAME);
if (fn->getReturnType() == decimal_val_type) {
// Per the x86 calling convention ABI, DecimalVals should be returned via an extra
// first DecimalVal* argument. We generate non-compliant functions that return the
// DecimalVal directly, which we can call from generated code, but not from compiled
// native code. To avoid accidentally calling a non-compliant function from native
// code, call 'function' from an ABI-compliant wrapper.
stringstream name;
name << fn->getName().str() << "ABIWrapper";
LlvmCodeGen::FnPrototype prototype(this, name.str(), void_type_);
// Add return argument
prototype.AddArgument(NamedVariable("result", decimal_val_type->getPointerTo()));
// Add regular arguments
for (Function::arg_iterator arg = fn->arg_begin(); arg != fn->arg_end(); ++arg) {
prototype.AddArgument(NamedVariable(arg->getName(), arg->getType()));
}
LlvmBuilder builder(context());
Value* args[fn->arg_size() + 1];
Function* fn_wrapper = prototype.GeneratePrototype(&builder, &args[0]);
fn_wrapper->addFnAttr(llvm::Attribute::AlwaysInline);
// Mark first argument as sret (not sure if this is necessary but it can't hurt)
fn_wrapper->addAttribute(1, Attribute::StructRet);
// Call 'fn' and store the result in the result argument
Value* result =
builder.CreateCall(fn, ArrayRef<Value*>(&args[1], fn->arg_size()), "result");
builder.CreateStore(result, args[0]);
builder.CreateRetVoid();
fn = FinalizeFunction(fn_wrapper);
DCHECK(fn != NULL);
}
fns_to_jit_compile_.push_back(make_pair(fn, fn_ptr));
}
void* LlvmCodeGen::JitFunction(Function* function) {
if (is_corrupt_) return NULL;
// TODO: log a warning if the jitted function is too big (larger than I cache)
void* jitted_function = execution_engine_->getPointerToFunction(function);
lock_guard<mutex> l(jitted_functions_lock_);
if (jitted_function != NULL) {
jitted_functions_[function] = true;
}
return jitted_function;
}
// Wrapper around printf to make it easier to call from IR
extern "C" void DebugTrace(const char* str) {
printf("LLVM Trace: %s\n", str);
}
void LlvmCodeGen::CodegenDebugTrace(LlvmBuilder* builder, const char* str) {
LOG(ERROR) << "Remove IR codegen debug traces before checking in.";
// Lazily link in debug function to the module
if (debug_trace_fn_ == NULL) {
vector<Type*> args;
args.push_back(ptr_type_);
FunctionType* fn_type = FunctionType::get(void_type_, args, false);
debug_trace_fn_ = Function::Create(fn_type, GlobalValue::ExternalLinkage,
"DebugTrace", module_);
DCHECK(debug_trace_fn_ != NULL);
// DebugTrace shouldn't already exist (llvm mangles function names if there
// are duplicates)
DCHECK(debug_trace_fn_->getName() == "DebugTrace");
debug_trace_fn_->setCallingConv(CallingConv::C);
// Add a mapping to the execution engine so it can link the DebugTrace function
execution_engine_->addGlobalMapping(debug_trace_fn_,
reinterpret_cast<void*>(&DebugTrace));
}
// Make a copy of str into memory owned by this object. This is no guarantee that str is
// still around when the debug printf is executed.
debug_strings_.push_back(str);
str = debug_strings_[debug_strings_.size() - 1].c_str();
// Call the function by turning 'str' into a constant ptr value
Value* str_ptr = CastPtrToLlvmPtr(ptr_type_, const_cast<char*>(str));
vector<Value*> calling_args;
calling_args.push_back(str_ptr);
builder->CreateCall(debug_trace_fn_, calling_args);
}
void LlvmCodeGen::GetFunctions(vector<Function*>* functions) {
Module::iterator fn_iter = module_->begin();
while (fn_iter != module_->end()) {
Function* fn = fn_iter++;
if (!fn->empty()) functions->push_back(fn);
}
}
void LlvmCodeGen::GetSymbols(unordered_set<string>* symbols) {
Module::iterator fn_iter = module_->begin();
while (fn_iter != module_->end()) {
Function* fn = fn_iter++;
if (!fn->empty()) symbols->insert(fn->getName());
}
}
// TODO: cache this function (e.g. all min(int, int) are identical).
// we probably want some more global IR function cache, or, implement this
// in c and precompile it with clang.
// define i32 @Min(i32 %v1, i32 %v2) {
// entry:
// %0 = icmp slt i32 %v1, %v2
// br i1 %0, label %ret_v1, label %ret_v2
//
// ret_v1: ; preds = %entry
// ret i32 %v1
//
// ret_v2: ; preds = %entry
// ret i32 %v2
// }
Function* LlvmCodeGen::CodegenMinMax(const ColumnType& type, bool min) {
LlvmCodeGen::FnPrototype prototype(this, min ? "Min" : "Max", GetType(type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("v1", GetType(type)));
prototype.AddArgument(LlvmCodeGen::NamedVariable("v2", GetType(type)));
Value* params[2];
LlvmBuilder builder(context());
Function* fn = prototype.GeneratePrototype(&builder, ¶ms[0]);
Value* compare = NULL;
switch (type.type) {
case TYPE_NULL:
compare = false_value();
break;
case TYPE_BOOLEAN:
if (min) {
// For min, return x && y
compare = builder.CreateAnd(params[0], params[1]);
} else {
// For max, return x || y
compare = builder.CreateOr(params[0], params[1]);
}
break;
case TYPE_TINYINT:
case TYPE_SMALLINT:
case TYPE_INT:
case TYPE_BIGINT:
if (min) {
compare = builder.CreateICmpSLT(params[0], params[1]);
} else {
compare = builder.CreateICmpSGT(params[0], params[1]);
}
break;
case TYPE_FLOAT:
case TYPE_DOUBLE:
if (min) {
compare = builder.CreateFCmpULT(params[0], params[1]);
} else {
compare = builder.CreateFCmpUGT(params[0], params[1]);
}
break;
default:
DCHECK(false);
}
if (type.type == TYPE_BOOLEAN) {
builder.CreateRet(compare);
} else {
BasicBlock* ret_v1, *ret_v2;
CreateIfElseBlocks(fn, "ret_v1", "ret_v2", &ret_v1, &ret_v2);
builder.CreateCondBr(compare, ret_v1, ret_v2);
builder.SetInsertPoint(ret_v1);
builder.CreateRet(params[0]);
builder.SetInsertPoint(ret_v2);
builder.CreateRet(params[1]);
}
if (!VerifyFunction(fn)) return NULL;
return fn;
}
// Intrinsics are loaded one by one. Some are overloaded (e.g. memcpy) and the types must
// be specified.
// TODO: is there a better way to do this?
Status LlvmCodeGen::LoadIntrinsics() {
// Load memcpy
{
Type* types[] = { ptr_type(), ptr_type(), GetType(TYPE_INT) };
Function* fn = Intrinsic::getDeclaration(module(), Intrinsic::memcpy, types);
if (fn == NULL) {
return Status("Could not find memcpy intrinsic.");
}
llvm_intrinsics_[Intrinsic::memcpy] = fn;
}
// TODO: where is the best place to put this?
struct {
Intrinsic::ID id;
const char* error;
} non_overloaded_intrinsics[] = {
{ Intrinsic::x86_sse42_crc32_32_8, "sse4.2 crc32_u8" },
{ Intrinsic::x86_sse42_crc32_32_16, "sse4.2 crc32_u16" },
{ Intrinsic::x86_sse42_crc32_32_32, "sse4.2 crc32_u32" },
{ Intrinsic::x86_sse42_crc32_64_64, "sse4.2 crc32_u64" },
};
const int num_intrinsics =
sizeof(non_overloaded_intrinsics) / sizeof(non_overloaded_intrinsics[0]);
for (int i = 0; i < num_intrinsics; ++i) {
Intrinsic::ID id = non_overloaded_intrinsics[i].id;
Function* fn = Intrinsic::getDeclaration(module(), id);
if (fn == NULL) {
stringstream ss;
ss << "Could not find " << non_overloaded_intrinsics[i].error << " intrinsic";
return Status(ss.str());
}
llvm_intrinsics_[id] = fn;
}
return Status::OK;
}
void LlvmCodeGen::CodegenMemcpy(LlvmBuilder* builder, Value* dst, Value* src, int size) {
DCHECK_GE(size, 0);
if (size == 0) return;
// Cast src/dst to int8_t*. If they already are, this will get optimized away
DCHECK(PointerType::classof(dst->getType()));
DCHECK(PointerType::classof(src->getType()));
dst = builder->CreateBitCast(dst, ptr_type());
src = builder->CreateBitCast(src, ptr_type());
// Get intrinsic function.
Function* memcpy_fn = llvm_intrinsics_[Intrinsic::memcpy];
DCHECK(memcpy_fn != NULL);
// The fourth argument is the alignment. For non-zero values, the caller
// must guarantee that the src and dst values are aligned to that byte boundary.
// TODO: We should try to take advantage of this since our tuples are well aligned.
Value* args[] = {
dst, src, GetIntConstant(TYPE_INT, size),
GetIntConstant(TYPE_INT, 0),
false_value() // is_volatile.
};
builder->CreateCall(memcpy_fn, args);
}
void LlvmCodeGen::ClearHashFns() {
hash_fns_.clear();
}
// Codegen to compute hash for a particular byte size. Loops are unrolled in this
// process. For the case where num_bytes == 11, we'd do this by calling
// 1. crc64 (for first 8 bytes)
// 2. crc16 (for bytes 9, 10)
// 3. crc8 (for byte 11)
// The resulting IR looks like:
// define i32 @CrcHash11(i8* %data, i32 %len, i32 %seed) {
// entry:
// %0 = zext i32 %seed to i64
// %1 = bitcast i8* %data to i64*
// %2 = getelementptr i64* %1, i32 0
// %3 = load i64* %2
// %4 = call i64 @llvm.x86.sse42.crc32.64.64(i64 %0, i64 %3)
// %5 = trunc i64 %4 to i32
// %6 = getelementptr i8* %data, i32 8
// %7 = bitcast i8* %6 to i16*
// %8 = load i16* %7
// %9 = call i32 @llvm.x86.sse42.crc32.32.16(i32 %5, i16 %8)
// %10 = getelementptr i8* %6, i32 2
// %11 = load i8* %10
// %12 = call i32 @llvm.x86.sse42.crc32.32.8(i32 %9, i8 %11)
// ret i32 %12
// }
Function* LlvmCodeGen::GetHashFunction(int num_bytes) {
if (CpuInfo::IsSupported(CpuInfo::SSE4_2)) {
if (num_bytes == -1) {
// -1 indicates variable length, just return the generic loop based
// hash fn.
return GetFunction(IRFunction::HASH_CRC);
}
map<int, Function*>::iterator cached_fn = hash_fns_.find(num_bytes);
if (cached_fn != hash_fns_.end()) {
return cached_fn->second;
}
// Generate a function to hash these bytes
stringstream ss;
ss << "CrcHash" << num_bytes;
FnPrototype prototype(this, ss.str(), GetType(TYPE_INT));
prototype.AddArgument(LlvmCodeGen::NamedVariable("data", ptr_type()));
prototype.AddArgument(LlvmCodeGen::NamedVariable("len", GetType(TYPE_INT)));
prototype.AddArgument(LlvmCodeGen::NamedVariable("seed", GetType(TYPE_INT)));
Value* args[3];
LlvmBuilder builder(context());
Function* fn = prototype.GeneratePrototype(&builder, &args[0]);
Value* data = args[0];
Value* result = args[2];
Function* crc8_fn = llvm_intrinsics_[Intrinsic::x86_sse42_crc32_32_8];
Function* crc16_fn = llvm_intrinsics_[Intrinsic::x86_sse42_crc32_32_16];
Function* crc32_fn = llvm_intrinsics_[Intrinsic::x86_sse42_crc32_32_32];
Function* crc64_fn = llvm_intrinsics_[Intrinsic::x86_sse42_crc32_64_64];
// Generate the crc instructions starting with the highest number of bytes
if (num_bytes >= 8) {
Value* result_64 = builder.CreateZExt(result, GetType(TYPE_BIGINT));
Value* ptr = builder.CreateBitCast(data, GetPtrType(TYPE_BIGINT));
int i = 0;
while (num_bytes >= 8) {
Value* index[] = { GetIntConstant(TYPE_INT, i++) };
Value* d = builder.CreateLoad(builder.CreateGEP(ptr, index));
result_64 = builder.CreateCall2(crc64_fn, result_64, d);
num_bytes -= 8;
}
result = builder.CreateTrunc(result_64, GetType(TYPE_INT));
Value* index[] = { GetIntConstant(TYPE_INT, i * 8) };
// Update data to past the 8-byte chunks
data = builder.CreateGEP(data, index);
}
if (num_bytes >= 4) {
DCHECK_LT(num_bytes, 8);
Value* ptr = builder.CreateBitCast(data, GetPtrType(TYPE_INT));
Value* d = builder.CreateLoad(ptr);
result = builder.CreateCall2(crc32_fn, result, d);
Value* index[] = { GetIntConstant(TYPE_INT, 4) };
data = builder.CreateGEP(data, index);
num_bytes -= 4;
}
if (num_bytes >= 2) {
DCHECK_LT(num_bytes, 4);
Value* ptr = builder.CreateBitCast(data, GetPtrType(TYPE_SMALLINT));
Value* d = builder.CreateLoad(ptr);
result = builder.CreateCall2(crc16_fn, result, d);
Value* index[] = { GetIntConstant(TYPE_INT, 2) };
data = builder.CreateGEP(data, index);
num_bytes -= 2;
}
if (num_bytes > 0) {
DCHECK_EQ(num_bytes, 1);
Value* d = builder.CreateLoad(data);
result = builder.CreateCall2(crc8_fn, result, d);
--num_bytes;
}
DCHECK_EQ(num_bytes, 0);
Value* shift_16 = GetIntConstant(TYPE_INT, 16);
Value* upper_bits = builder.CreateShl(result, shift_16);
Value* lower_bits = builder.CreateLShr(result, shift_16);
result = builder.CreateOr(upper_bits, lower_bits);
builder.CreateRet(result);
fn = FinalizeFunction(fn);
if (fn != NULL) {
hash_fns_[num_bytes] = fn;
}
return fn;
} else {
return GetMurmurHashFunction(num_bytes);
}
}
static Function* GetLenOptimizedHashFn(
LlvmCodeGen* codegen, IRFunction::Type f, int len) {
Function* fn = codegen->GetFunction(f);
DCHECK(fn != NULL);
if (len != -1) {
// Clone this function since we're going to modify it by replacing the
// length with num_bytes.
fn = codegen->CloneFunction(fn);
Value* len_arg = codegen->GetArgument(fn, 1);
len_arg->replaceAllUsesWith(codegen->GetIntConstant(TYPE_INT, len));
}
return codegen->FinalizeFunction(fn);
}
Function* LlvmCodeGen::GetFnvHashFunction(int len) {
return GetLenOptimizedHashFn(this, IRFunction::HASH_FNV, len);
}
Function* LlvmCodeGen::GetMurmurHashFunction(int len) {
return GetLenOptimizedHashFn(this, IRFunction::HASH_MURMUR, len);
}
void LlvmCodeGen::ReplaceInstWithValue(Instruction* from, Value* to) {
BasicBlock::iterator iter(from);
llvm::ReplaceInstWithValue(from->getParent()->getInstList(), iter, to);
}
Argument* LlvmCodeGen::GetArgument(Function* fn, int i) {
DCHECK_LE(i, fn->arg_size());
Function::arg_iterator iter = fn->arg_begin();
for (int j = 0; j < i; ++j) ++iter;
return iter;
}
}
|
scalingdata/Impala
|
be/src/codegen/llvm-codegen.cc
|
C++
|
apache-2.0
| 39,424
|
/*
* 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.beam.sdk.extensions.sql.impl.interpreter.operator.string;
import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import org.apache.beam.sdk.extensions.sql.impl.interpreter.BeamSqlFnExecutorTestBase;
import org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.BeamSqlExpression;
import org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.BeamSqlPrimitive;
import org.apache.calcite.sql.type.SqlTypeName;
import org.junit.Test;
/** Test of BeamSqlLowerExpression. */
public class BeamSqlLowerExpressionTest extends BeamSqlFnExecutorTestBase {
@Test
public void evaluate() throws Exception {
List<BeamSqlExpression> operands = new ArrayList<>();
operands.add(BeamSqlPrimitive.of(SqlTypeName.VARCHAR, "HELLO"));
assertEquals(
"hello",
new BeamSqlLowerExpression(operands).evaluate(row, null, ImmutableMap.of()).getValue());
}
}
|
tgroh/beam
|
sdks/java/extensions/sql/src/test/java/org/apache/beam/sdk/extensions/sql/impl/interpreter/operator/string/BeamSqlLowerExpressionTest.java
|
Java
|
apache-2.0
| 1,794
|
<!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.5.0_22) on Wed Apr 03 10:04:47 GMT-03:00 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class opennlp.uima.tokenize.AbstractTokenizer (Apache OpenNLP UIMA Annotators 1.5.3 API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class opennlp.uima.tokenize.AbstractTokenizer (Apache OpenNLP UIMA Annotators 1.5.3 API)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= 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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../opennlp/uima/tokenize/AbstractTokenizer.html" title="class in opennlp.uima.tokenize"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </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-all.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
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?opennlp/uima/tokenize/class-use/AbstractTokenizer.html" target="_top"><B>FRAMES</B></A>
<A HREF="AbstractTokenizer.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 ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>opennlp.uima.tokenize.AbstractTokenizer</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../opennlp/uima/tokenize/AbstractTokenizer.html" title="class in opennlp.uima.tokenize">AbstractTokenizer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#opennlp.uima.tokenize"><B>opennlp.uima.tokenize</B></A></TD>
<TD>Package related to finding tokens or word segments. </TD>
</TR>
</TABLE>
<P>
<A NAME="opennlp.uima.tokenize"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../opennlp/uima/tokenize/AbstractTokenizer.html" title="class in opennlp.uima.tokenize">AbstractTokenizer</A> in <A HREF="../../../../opennlp/uima/tokenize/package-summary.html">opennlp.uima.tokenize</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../opennlp/uima/tokenize/AbstractTokenizer.html" title="class in opennlp.uima.tokenize">AbstractTokenizer</A> in <A HREF="../../../../opennlp/uima/tokenize/package-summary.html">opennlp.uima.tokenize</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../opennlp/uima/tokenize/SimpleTokenizer.html" title="class in opennlp.uima.tokenize">SimpleTokenizer</A></B></CODE>
<BR>
OpenNLP Simple Tokenizer annotator.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../opennlp/uima/tokenize/Tokenizer.html" title="class in opennlp.uima.tokenize">Tokenizer</A></B></CODE>
<BR>
OpenNLP Tokenizer annotator.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../opennlp/uima/tokenize/WhitespaceTokenizer.html" title="class in opennlp.uima.tokenize">WhitespaceTokenizer</A></B></CODE>
<BR>
OpenNLP Whitespace Tokenizer annotator.</TD>
</TR>
</TABLE>
<P>
<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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../opennlp/uima/tokenize/AbstractTokenizer.html" title="class in opennlp.uima.tokenize"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </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-all.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
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?opennlp/uima/tokenize/class-use/AbstractTokenizer.html" target="_top"><B>FRAMES</B></A>
<A HREF="AbstractTokenizer.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>
Copyright © 2013 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
|
opener-project/nerc-fr
|
opennlp/docs/apidocs/opennlp-uima/opennlp/uima/tokenize/class-use/AbstractTokenizer.html
|
HTML
|
apache-2.0
| 8,617
|
"""Common functions for Rflink component tests and generic platform tests."""
import asyncio
from unittest.mock import Mock
from homeassistant.bootstrap import async_setup_component
from homeassistant.components.rflink import CONF_RECONNECT_INTERVAL
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF
from tests.common import assert_setup_component
@asyncio.coroutine
def mock_rflink(hass, config, domain, monkeypatch, failures=None):
"""Create mock Rflink asyncio protocol, test component setup."""
transport, protocol = (Mock(), Mock())
@asyncio.coroutine
def send_command_ack(*command):
return True
protocol.send_command_ack = Mock(wraps=send_command_ack)
@asyncio.coroutine
def send_command(*command):
return True
protocol.send_command = Mock(wraps=send_command)
@asyncio.coroutine
def create_rflink_connection(*args, **kwargs):
"""Return mocked transport and protocol."""
# failures can be a list of booleans indicating in which sequence
# creating a connection should success or fail
if failures:
fail = failures.pop()
else:
fail = False
if fail:
raise ConnectionRefusedError
else:
return transport, protocol
mock_create = Mock(wraps=create_rflink_connection)
monkeypatch.setattr(
'rflink.protocol.create_rflink_connection',
mock_create)
# verify instanstiation of component with given config
with assert_setup_component(1, domain):
yield from async_setup_component(hass, domain, config)
# hook into mock config for injecting events
event_callback = mock_create.call_args_list[0][1]['event_callback']
assert event_callback
disconnect_callback = mock_create.call_args_list[
0][1]['disconnect_callback']
return event_callback, mock_create, protocol, disconnect_callback
@asyncio.coroutine
def test_version_banner(hass, monkeypatch):
"""Test sending unknown commands doesn't cause issues."""
# use sensor domain during testing main platform
domain = 'sensor'
config = {
'rflink': {'port': '/dev/ttyABC0', },
domain: {
'platform': 'rflink',
'devices': {
'test': {'name': 'test', 'sensor_type': 'temperature', },
},
},
}
# setup mocking rflink module
event_callback, _, _, _ = yield from mock_rflink(
hass, config, domain, monkeypatch)
event_callback({
'hardware': 'Nodo RadioFrequencyLink',
'firmware': 'RFLink Gateway',
'version': '1.1',
'revision': '45',
})
@asyncio.coroutine
def test_send_no_wait(hass, monkeypatch):
"""Test command sending without ack."""
domain = 'switch'
config = {
'rflink': {
'port': '/dev/ttyABC0',
'wait_for_ack': False,
},
domain: {
'platform': 'rflink',
'devices': {
'protocol_0_0': {
'name': 'test',
'aliasses': ['test_alias_0_0'],
},
},
},
}
# setup mocking rflink module
_, _, protocol, _ = yield from mock_rflink(
hass, config, domain, monkeypatch)
hass.async_add_job(
hass.services.async_call(domain, SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: 'switch.test'}))
yield from hass.async_block_till_done()
assert protocol.send_command.call_args_list[0][0][0] == 'protocol_0_0'
assert protocol.send_command.call_args_list[0][0][1] == 'off'
@asyncio.coroutine
def test_reconnecting_after_disconnect(hass, monkeypatch):
"""An unexpected disconnect should cause a reconnect."""
domain = 'sensor'
config = {
'rflink': {
'port': '/dev/ttyABC0',
CONF_RECONNECT_INTERVAL: 0,
},
domain: {
'platform': 'rflink',
},
}
# setup mocking rflink module
_, mock_create, _, disconnect_callback = yield from mock_rflink(
hass, config, domain, monkeypatch)
assert disconnect_callback, 'disconnect callback not passed to rflink'
# rflink initiated disconnect
disconnect_callback(None)
yield from hass.async_block_till_done()
# we expect 2 call, the initial and reconnect
assert mock_create.call_count == 2
@asyncio.coroutine
def test_reconnecting_after_failure(hass, monkeypatch):
"""A failure to reconnect should be retried."""
domain = 'sensor'
config = {
'rflink': {
'port': '/dev/ttyABC0',
CONF_RECONNECT_INTERVAL: 0,
},
domain: {
'platform': 'rflink',
},
}
# success first time but fail second
failures = [False, True, False]
# setup mocking rflink module
_, mock_create, _, disconnect_callback = yield from mock_rflink(
hass, config, domain, monkeypatch, failures=failures)
# rflink initiated disconnect
disconnect_callback(None)
# wait for reconnects to have happened
yield from hass.async_block_till_done()
yield from hass.async_block_till_done()
# we expect 3 calls, the initial and 2 reconnects
assert mock_create.call_count == 3
@asyncio.coroutine
def test_error_when_not_connected(hass, monkeypatch):
"""Sending command should error when not connected."""
domain = 'switch'
config = {
'rflink': {
'port': '/dev/ttyABC0',
CONF_RECONNECT_INTERVAL: 0,
},
domain: {
'platform': 'rflink',
'devices': {
'protocol_0_0': {
'name': 'test',
'aliasses': ['test_alias_0_0'],
},
},
},
}
# success first time but fail second
failures = [False, True, False]
# setup mocking rflink module
_, mock_create, _, disconnect_callback = yield from mock_rflink(
hass, config, domain, monkeypatch, failures=failures)
assert hass.states.get('rflink.connection_status').state == 'connected'
# rflink initiated disconnect
disconnect_callback(None)
yield from asyncio.sleep(0, loop=hass.loop)
assert hass.states.get('rflink.connection_status').state == 'error'
success = yield from hass.services.async_call(
domain, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: 'switch.test'})
assert not success, 'changing state should not succeed when disconnected'
|
open-homeautomation/home-assistant
|
tests/components/test_rflink.py
|
Python
|
apache-2.0
| 6,534
|
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto
namespace Google\Cloud\Compute\V1\Operation;
use UnexpectedValueException;
/**
* [Output Only] The status of the operation, which can be one of the following: `PENDING`, `RUNNING`, or `DONE`.
*
* Protobuf type <code>google.cloud.compute.v1.Operation.Status</code>
*/
class Status
{
/**
* A value indicating that the enum field is not set.
*
* Generated from protobuf enum <code>UNDEFINED_STATUS = 0;</code>
*/
const UNDEFINED_STATUS = 0;
/**
* Generated from protobuf enum <code>DONE = 2104194;</code>
*/
const DONE = 2104194;
/**
* Generated from protobuf enum <code>PENDING = 35394935;</code>
*/
const PENDING = 35394935;
/**
* Generated from protobuf enum <code>RUNNING = 121282975;</code>
*/
const RUNNING = 121282975;
private static $valueToName = [
self::UNDEFINED_STATUS => 'UNDEFINED_STATUS',
self::DONE => 'DONE',
self::PENDING => 'PENDING',
self::RUNNING => 'RUNNING',
];
public static function name($value)
{
if (!isset(self::$valueToName[$value])) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no name defined for value %s', __CLASS__, $value));
}
return self::$valueToName[$value];
}
public static function value($name)
{
$const = __CLASS__ . '::' . strtoupper($name);
if (!defined($const)) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no value defined for name %s', __CLASS__, $name));
}
return constant($const);
}
}
|
googleapis/google-cloud-php-compute
|
src/V1/Operation/Status.php
|
PHP
|
apache-2.0
| 1,750
|
/*
* Copyright 2010-2015 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/AWSString.h>
namespace Aws
{
namespace EC2
{
namespace Model
{
/*
*/
class AWS_EC2_API CancelBundleTaskRequest : public EC2Request
{
public:
CancelBundleTaskRequest();
Aws::String SerializePayload() const override;
/*
<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 CancelBundleTaskRequest& WithDryRun(bool value) { SetDryRun(value); return *this;}
/*
<p>The ID of the bundle task.</p>
*/
inline const Aws::String& GetBundleId() const{ return m_bundleId; }
/*
<p>The ID of the bundle task.</p>
*/
inline void SetBundleId(const Aws::String& value) { m_bundleIdHasBeenSet = true; m_bundleId = value; }
/*
<p>The ID of the bundle task.</p>
*/
inline void SetBundleId(Aws::String&& value) { m_bundleIdHasBeenSet = true; m_bundleId = value; }
/*
<p>The ID of the bundle task.</p>
*/
inline void SetBundleId(const char* value) { m_bundleIdHasBeenSet = true; m_bundleId.assign(value); }
/*
<p>The ID of the bundle task.</p>
*/
inline CancelBundleTaskRequest& WithBundleId(const Aws::String& value) { SetBundleId(value); return *this;}
/*
<p>The ID of the bundle task.</p>
*/
inline CancelBundleTaskRequest& WithBundleId(Aws::String&& value) { SetBundleId(value); return *this;}
/*
<p>The ID of the bundle task.</p>
*/
inline CancelBundleTaskRequest& WithBundleId(const char* value) { SetBundleId(value); return *this;}
private:
bool m_dryRun;
bool m_dryRunHasBeenSet;
Aws::String m_bundleId;
bool m_bundleIdHasBeenSet;
};
} // namespace Model
} // namespace EC2
} // namespace Aws
|
zeliard/aws-sdk-cpp
|
windows-build/include/aws/ec2/model/CancelBundleTaskRequest.h
|
C
|
apache-2.0
| 3,342
|
/*
* Copyright 2013 JBoss by Red Hat.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.kie.services.impl.bpmn2;
import org.drools.core.xml.ExtensibleXmlParser;
import org.jbpm.bpmn2.core.ItemDefinition;
import org.jbpm.bpmn2.xml.ItemDefinitionHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* This handler collects information about item definitions, which are
* basically BPMN2 elements that alias an external (java) type to an
* internal alias
*/
public class DataServiceItemDefinitionHandler extends ItemDefinitionHandler {
private BPMN2DataServiceSemanticModule module;
private ProcessDescriptionRepository repository;
public DataServiceItemDefinitionHandler(BPMN2DataServiceSemanticModule module) {
this.module = module;
this.repository = module.getRepo();
}
@Override
public Object start(final String uri, final String localName,
final Attributes attrs, final ExtensibleXmlParser parser)
throws SAXException {
ItemDefinition item = (ItemDefinition) super.start(uri, localName, attrs, parser);
String id = item.getId();
String structureRef = item.getStructureRef();
String itemDefinitionId = module.getRepoHelper().getGlobalItemDefinitions().get(id);
if(itemDefinitionId == null) {
module.getRepoHelper().getGlobalItemDefinitions().put(id, structureRef);
// The process id isn't known yet, so we use the thread local process
ProcessDescRepoHelper repoHelper = ProcessDescriptionRepository.LOCAL_PROCESS_REPO_HELPER.get();
if( structureRef.contains(".") ) {
repoHelper.getReferencedClasses().add(structureRef);
} else {
repoHelper.getUnqualifiedClasses().add(structureRef);
}
}
return item;
}
}
|
akoskm/jbpm
|
jbpm-services/jbpm-kie-services/src/main/java/org/jbpm/kie/services/impl/bpmn2/DataServiceItemDefinitionHandler.java
|
Java
|
apache-2.0
| 2,401
|
require 'rails_helper'
describe Api::SortingRulesController do
let!(:sorting_rule) { FactoryGirl.create :sorting_rule, name: 'Some Name' }
let!(:test_sorting_rule) { FactoryGirl.create :sorting_rule, name: 'Test' }
let!(:tagged_sorting_rules) { FactoryGirl.create_list :sorting_rule, 2, tag_ids: [tag.id] }
let!(:categorised_sorting_rules) { FactoryGirl.create_list :sorting_rule, 2, category_id: category.id }
let!(:category) { FactoryGirl.create :category }
let!(:tag) { FactoryGirl.create :tag }
describe 'GET index' do
context 'no filters' do
before { get :index }
it { should respond_with :success }
it 'returns all sorting_rules' do
expect(assigns(:sorting_rules)).to match_array [sorting_rule, test_sorting_rule, tagged_sorting_rules, categorised_sorting_rules].flatten
end
end
context 'filter search query' do
before do
get :index, query: 'test'
end
it { should respond_with :success }
it 'filters sorting rules by search query' do
expect(assigns(:sorting_rules)).to match_array [test_sorting_rule]
end
end
context 'filter with category' do
before do
get :index, category_id: category.id
end
it { should respond_with :success }
it 'filters sorting rules by category_id' do
expect(assigns(:sorting_rules)).to match_array categorised_sorting_rules
end
end
context 'filter with tags' do
before do
get :index, tag_ids: tag.id
end
it { should respond_with :success }
it 'filters sorting rules by tag id' do
expect(assigns(:sorting_rules)).to match_array tagged_sorting_rules
end
end
end
describe 'GET show' do
before { get :show, id: sorting_rule.id }
it { should respond_with :success }
it 'returns the sorting_rule' do
expect(assigns(:sorting_rule)).to eq sorting_rule
end
end
describe 'POST create' do
def valid_request
post :create,
name: 'New Name',
contains: 'Foobar',
category_id: category.id
end
it 'responds with 200' do
valid_request
expect(subject).to respond_with(:success)
end
it 'creates a sorting_rule' do
expect do
valid_request
end.to change(SortingRule, :count).by(1)
end
end
describe 'PUT update' do
def valid_request
put :update,
id: sorting_rule.id,
name: 'Some New Name'
end
it 'responds with 200' do
valid_request
expect(subject).to respond_with(:success)
end
it 'updates the name' do
expect do
valid_request
end.to change { sorting_rule.reload.name }.from('Some Name').to('Some New Name')
end
end
describe 'DELETE destroy' do
def valid_request
delete :destroy,
id: sorting_rule.id
end
it 'responds with 204' do
valid_request
expect(subject).to respond_with(:no_content)
end
it 'deletes the sorting_rule' do
expect do
valid_request
end.to change(SortingRule, :count).by(-1)
end
end
end
|
malclocke/dotledger
|
spec/controllers/api/sorting_rules_controller_spec.rb
|
Ruby
|
apache-2.0
| 3,145
|
/*
Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/C++ is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
MySQL Connectors. There are special exceptions to the terms and
conditions of the GPLv2 as it is applied to this software, see the
FLOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
This program 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; version 2 of the License.
This program 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 this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _SQL_EXCEPTION_H_
#define _SQL_EXCEPTION_H_
#include "build_config.h"
#include <stdexcept>
#include <string>
#include <memory>
namespace sql
{
#define MEMORY_ALLOC_OPERATORS(Class) \
void* operator new(size_t size) throw (std::bad_alloc) { return ::operator new(size); } \
void* operator new(size_t, void*) throw(); \
void* operator new(size_t, const std::nothrow_t&) throw(); \
void* operator new[](size_t) throw (std::bad_alloc); \
void* operator new[](size_t, void*) throw(); \
void* operator new[](size_t, const std::nothrow_t&) throw(); \
void* operator new(size_t N, std::allocator<Class>&);
#ifdef _WIN32
#pragma warning (disable : 4290)
//warning C4290: C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
#pragma warning(push)
#pragma warning(disable: 4275)
#endif
class CPPCONN_PUBLIC_FUNC SQLException : public std::runtime_error
{
#ifdef _WIN32
#pragma warning(pop)
#endif
protected:
const std::string sql_state;
const int errNo;
public:
SQLException(const SQLException& e) : std::runtime_error(e.what()), sql_state(e.sql_state), errNo(e.errNo) {}
SQLException(const std::string& reason, const std::string& SQLState, int vendorCode) :
std::runtime_error(reason),
sql_state(SQLState),
errNo(vendorCode)
{}
SQLException(const std::string& reason, const std::string& SQLState) : std::runtime_error(reason), sql_state(SQLState), errNo(0) {}
SQLException(const std::string& reason) : std::runtime_error(reason), sql_state("HY000"), errNo(0) {}
SQLException() : std::runtime_error(""), sql_state("HY000"), errNo(0) {}
const std::string& getSQLState() const {
return sql_state;
}
const char* getSQLStateCStr() const {
return sql_state.c_str();
}
int getErrorCode() const {
return errNo;
}
virtual ~SQLException() throw() {};
protected:
MEMORY_ALLOC_OPERATORS(SQLException)
};
struct CPPCONN_PUBLIC_FUNC MethodNotImplementedException : public SQLException {
MethodNotImplementedException(const MethodNotImplementedException& e) : SQLException(e.what(), e.sql_state, e.errNo) { }
MethodNotImplementedException(const std::string& reason) : SQLException(reason, "", 0) {}
};
struct CPPCONN_PUBLIC_FUNC InvalidArgumentException : public SQLException {
InvalidArgumentException(const InvalidArgumentException& e) : SQLException(e.what(), e.sql_state, e.errNo) { }
InvalidArgumentException(const std::string& reason) : SQLException(reason, "", 0) {}
};
struct CPPCONN_PUBLIC_FUNC InvalidInstanceException : public SQLException {
InvalidInstanceException(const InvalidInstanceException& e) : SQLException(e.what(), e.sql_state, e.errNo) { }
InvalidInstanceException(const std::string& reason) : SQLException(reason, "", 0) {}
};
struct CPPCONN_PUBLIC_FUNC NonScrollableException : public SQLException {
NonScrollableException(const NonScrollableException& e) : SQLException(e.what(), e.sql_state, e.errNo) { }
NonScrollableException(const std::string& reason) : SQLException(reason, "", 0) {}
};
} /* namespace sql */
#endif /* _SQL_EXCEPTION_H_ */
|
xujb/CC
|
platform/ivr/include/cppconn/exception.h
|
C
|
apache-2.0
| 4,453
|
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.phreak;
public class PhreakNetworkNodeFactoryImpl implements PhreakNetworkNodeFactory {
@Override
public PhreakJoinNode createPhreakJoinNode() {
return new PhreakJoinNode();
}
@Override
public PhreakEvalNode createPhreakEvalNode() {
return new PhreakEvalNode();
}
@Override
public PhreakFromNode createPhreakFromNode() {
return new PhreakFromNode();
}
@Override
public PhreakReactiveFromNode createPhreakReactiveFromNode() {
return new PhreakReactiveFromNode();
}
@Override
public PhreakNotNode createPhreakNotNode() {
return new PhreakNotNode();
}
@Override
public PhreakExistsNode createPhreakExistsNode() {
return new PhreakExistsNode();
}
@Override
public PhreakAccumulateNode createPhreakAccumulateNode() {
return new PhreakAccumulateNode();
}
@Override
public PhreakBranchNode createPhreakBranchNode() {
return new PhreakBranchNode();
}
@Override
public PhreakQueryNode createPhreakQueryNode() {
return new PhreakQueryNode();
}
@Override
public PhreakTimerNode createPhreakTimerNode() {
return new PhreakTimerNode();
}
@Override
public PhreakAsyncSendNode createPhreakAsyncSendNode() {
return new PhreakAsyncSendNode();
}
@Override
public PhreakAsyncReceiveNode createPhreakAsyncReceiveNode() {
return new PhreakAsyncReceiveNode();
}
@Override
public PhreakRuleTerminalNode createPhreakRuleTerminalNode() {
return new PhreakRuleTerminalNode();
}
@Override
public PhreakQueryTerminalNode createPhreakQueryTerminalNode() {
return new PhreakQueryTerminalNode();
}
}
|
lanceleverich/drools
|
drools-core/src/main/java/org/drools/core/phreak/PhreakNetworkNodeFactoryImpl.java
|
Java
|
apache-2.0
| 2,411
|
/* ========================================================================
* Bootstrap: popover.js v3.0.0
* http://twbs.github.com/bootstrap/javascript.html#popovers
* ========================================================================
* Copyright 2012 Twitter, 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.
* ======================================================================== */
+function ($) { "use strict";
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right'
, trigger: 'click'
, content: ''
, template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)
$tip.removeClass('fade top bottom left right in')
$tip.find('.popover-title:empty').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.tip = function () {
if (!this.$tip) this.$tip = $(this.options.template)
return this.$tip
}
// POPOVER PLUGIN DEFINITION
// =========================
var old = $.fn.popover
$.fn.popover = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(window.jQuery);
|
ShavitCohen/bootstrap3-rtl
|
js/popover.js
|
JavaScript
|
apache-2.0
| 3,232
|
/*
* Licensed to DuraSpace under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* DuraSpace 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.fcrepo.camel.audit.triplestore;
/**
* @author acoburn
*/
public final class AuditHeaders {
public static final String EVENT_BASE_URI = "CamelAuditEventBaseUri";
public static final String EVENT_URI = "CamelAuditEventUri";
private AuditHeaders() {
// prevent instantiation
}
}
|
bseeger/fcrepo-camel-toolbox
|
fcrepo-audit-triplestore/src/main/java/org/fcrepo/camel/audit/triplestore/AuditHeaders.java
|
Java
|
apache-2.0
| 1,097
|
/* 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.test.bpmn.gateway;
import java.io.Serializable;
/**
* @author Joram Barrez
*/
public class ExclusiveGatewayTestOrder implements Serializable {
private static final long serialVersionUID = 1L;
private int price;
public ExclusiveGatewayTestOrder(int price) {
this.price = price;
}
public void setPrice(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
public boolean isBasic() {
return price <= 100;
}
public boolean isStandard() {
return price > 100 && price < 250;
}
public boolean isGold() {
return price >= 250;
}
}
|
roberthafner/flowable-engine
|
modules/flowable-engine/src/test/java/org/activiti/engine/test/bpmn/gateway/ExclusiveGatewayTestOrder.java
|
Java
|
apache-2.0
| 1,199
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.model.runtime;
import org.jkiss.dbeaver.Log;
import org.eclipse.core.runtime.IProgressMonitor;
import java.util.ArrayList;
import java.util.List;
/**
* Progress monitor default implementation
*/
public class DefaultProgressMonitor implements DBRProgressMonitor {
private static final Log log = Log.getLog(DefaultProgressMonitor.class);
private IProgressMonitor nestedMonitor;
private List<DBRBlockingObject> blocks = null;
public DefaultProgressMonitor(IProgressMonitor nestedMonitor)
{
this.nestedMonitor = nestedMonitor;
}
@Override
public IProgressMonitor getNestedMonitor()
{
return nestedMonitor;
}
@Override
public void beginTask(String name, int totalWork)
{
nestedMonitor.beginTask(name, totalWork);
}
@Override
public void done()
{
nestedMonitor.done();
}
@Override
public void subTask(String name)
{
nestedMonitor.subTask(name);
}
@Override
public void worked(int work)
{
nestedMonitor.worked(work);
}
@Override
public boolean isCanceled()
{
return nestedMonitor.isCanceled();
}
@Override
public synchronized void startBlock(DBRBlockingObject object, String taskName)
{
if (taskName != null) {
subTask(taskName);
}
if (blocks == null) {
blocks = new ArrayList<>();
}
blocks.add(object);
}
@Override
public synchronized void endBlock()
{
if (blocks == null || blocks.isEmpty()) {
log.warn("End block invoked while no blocking objects are in stack"); //$NON-NLS-1$
return;
}
//if (blocks.size() == 1) {
// this.done();
//}
blocks.remove(blocks.size() - 1);
}
@Override
public synchronized List<DBRBlockingObject> getActiveBlocks()
{
return blocks == null || blocks.isEmpty() ? null : new ArrayList<>(blocks);
}
}
|
AndrewKhitrin/dbeaver
|
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/runtime/DefaultProgressMonitor.java
|
Java
|
apache-2.0
| 2,698
|
/*
* 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.facebook.presto.iceberg;
import com.facebook.presto.spi.connector.ConnectorOutputMetadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import java.util.List;
import static java.util.Objects.requireNonNull;
public class IcebergWrittenPartitions
implements ConnectorOutputMetadata
{
private final List<String> partitionNames;
@JsonCreator
public IcebergWrittenPartitions(@JsonProperty("partitionNames") List<String> partitionNames)
{
this.partitionNames = ImmutableList.copyOf(requireNonNull(partitionNames, "partitionNames is null"));
}
@JsonProperty
public List<String> getInfo()
{
return partitionNames;
}
}
|
facebook/presto
|
presto-iceberg/src/main/java/com/facebook/presto/iceberg/IcebergWrittenPartitions.java
|
Java
|
apache-2.0
| 1,360
|
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title></title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../../lib/jquery.js"></script>
<script type="text/javascript" src="../../../lib/jquery.panzoom.min.js"></script>
<script type="text/javascript" src="../../../lib/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="../../../lib/index.js"></script>
<script type="text/javascript" src="../../../index.js"></script>
<script type="text/javascript" src="../../../lib/scheduler.js"></script>
<script type="text/javascript" src="../../../lib/template.js"></script>
<script type="text/javascript" src="../../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
/* this variable can be used by the JS to determine the path to the root document */
var toRoot = '../../../';
</script>
</head>
<body>
<div id="search">
<span id="doc-title"><span id="doc-version"></span></span>
<span class="close-results"><span class="left"><</span> Back</span>
<div id="textfilter">
<span class="input">
<input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
<i class="clear material-icons"></i>
<i id="search-icon" class="material-icons"></i>
</span>
</div>
</div>
<div id="search-results">
<div id="search-progress">
<div id="progress-fill"></div>
</div>
<div id="results-content">
<div id="entity-results"></div>
<div id="member-results"></div>
</div>
</div>
<div id="content-scroll-container" style="-webkit-overflow-scrolling: touch;">
<div id="content-container" style="-webkit-overflow-scrolling: touch;">
<div id="subpackage-spacer">
<div id="packages">
<h1>Packages</h1>
<ul>
<li name="_root_.root" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="_root_"></a><a id="root:_root_"></a>
<span class="permalink">
<a href="index.html#_root_" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="../../../index.html"><span class="name">root</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../index.html" class="extype" name="_root_">root</a></dd></dl></div>
</li><li name="_root_.net" visbl="pub" class="indented1 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="net"></a><a id="net:net"></a>
<span class="permalink">
<a href="index.html#net" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="For a overview, proceed to the starting point for this document => net.liftmodules.fobo" href="../../index.html"><span class="name">net</span></a>
</span>
<p class="shortcomment cmt">For a overview, proceed to the starting point for this document => <a href="../fobo/index.html" class="extype" name="net.liftmodules.fobo">net.liftmodules.fobo</a></p><div class="fullcomment"><div class="comment cmt"><p>For a overview, proceed to the starting point for this document => <a href="../fobo/index.html" class="extype" name="net.liftmodules.fobo">net.liftmodules.fobo</a></p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../index.html" class="extype" name="_root_">root</a></dd></dl></div>
</li><li name="net.liftmodules" visbl="pub" class="indented2 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="liftmodules"></a><a id="liftmodules:liftmodules"></a>
<span class="permalink">
<a href="../net/index.html#liftmodules" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="For a overview, proceed to the starting point for this document => net.liftmodules.fobo" href="../index.html"><span class="name">liftmodules</span></a>
</span>
<p class="shortcomment cmt">For a overview, proceed to the starting point for this document => <a href="../fobo/index.html" class="extype" name="net.liftmodules.fobo">net.liftmodules.fobo</a></p><div class="fullcomment"><div class="comment cmt"><p>For a overview, proceed to the starting point for this document => <a href="../fobo/index.html" class="extype" name="net.liftmodules.fobo">net.liftmodules.fobo</a></p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../index.html" class="extype" name="net">net</a></dd></dl></div>
</li><li name="net.liftmodules.fobotbapi" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="fobotbapi"></a><a id="fobotbapi:fobotbapi"></a>
<span class="permalink">
<a href="../../net/liftmodules/index.html#fobotbapi" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="This FoBo API module provides FoBo/Lift API components for the Twitter Bootstrap v2.x Toolkit Module, but can also be used as-is, see below for setup information." href="index.html"><span class="name">fobotbapi</span></a>
</span>
<p class="shortcomment cmt">This FoBo API module provides FoBo/Lift API components for the Twitter Bootstrap v2.x Toolkit Module,
but can also be used as-is, see below for setup information.</p><div class="fullcomment"><div class="comment cmt"><h4>FoBo Twitter Bootstrap API Module</h4><p>This FoBo API module provides FoBo/Lift API components for the Twitter Bootstrap v2.x Toolkit Module,
but can also be used as-is, see below for setup information.</p><p>If you are using this module via the FoBo/FoBo artifact module see also <a href="../fobo/index.html" class="extype" name="net.liftmodules.fobo">net.liftmodules.fobo</a> for setup information.</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../index.html" class="extype" name="net.liftmodules">liftmodules</a></dd></dl></div>
</li><li class="current-entities indented3">
<a class="object" href="package$$API$.html" title=""></a>
<a class="trait" href="package$$API.html" title="Initiate FoBo's Bootstrap 3 API in you bootstrap liftweb Boot."></a>
<a href="package$$API.html" title="Initiate FoBo's Bootstrap 3 API in you bootstrap liftweb Boot.">API</a>
</li><li class="current-entities indented3">
<span class="separator"></span>
<a class="object" href="" title="Extends your Lift SiteMap with various common bootstrap menu manipulations such as horizontal and vertical menu dividers and menu labels."></a>
<a href="" title="Extends your Lift SiteMap with various common bootstrap menu manipulations such as horizontal and vertical menu dividers and menu labels.">TBLocInfo</a>
</li>
</ul>
</div>
</div>
<div id="content">
<body class="object value">
<div id="definition">
<div class="big-circle object">o</div>
<p id="owner"><a href="../../index.html" class="extype" name="net">net</a>.<a href="../index.html" class="extype" name="net.liftmodules">liftmodules</a>.<a href="index.html" class="extype" name="net.liftmodules.fobotbapi">fobotbapi</a></p>
<h1>TBLocInfo<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span></h1>
<h3><span class="morelinks"></span></h3>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">object</span>
</span>
<span class="symbol">
<span class="name">TBLocInfo</span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Extends your Lift SiteMap with various common bootstrap menu manipulations such
as horizontal and vertical menu dividers and menu labels.</p><p>This object should be used in conjunction with the TB* menu builder objects in <a href="../fobo/snippet/FoBo/index.html" class="extype" name="net.liftmodules.fobo.snippet.FoBo">net.liftmodules.fobo.snippet.FoBo</a> snippet's.
</p></div><dl class="attributes block"> <div class="block">Example:
<ol><li class="cmt"><p></p><pre> :
<span class="cmt">//add a horizontal menu divider</span>
divider1 >> LocGroup(...) >> FoBoTB.TBLocInfo.Divider,
:
<span class="cmt">//add a vertical menu divider</span>
divider2 >> LocGroup(...) >> FoBoTB.TBLocInfo.DividerVertical,
:</pre></li></ol>
</div></dl><div class="toggleContainer block">
<span class="toggle">
Linear Supertypes
</span>
<div class="superTypes hiddenContent"><a href="http://www.scala-lang.org/api/2.12.6/scala/AnyRef.html#scala.AnyRef" class="extype" name="scala.AnyRef">AnyRef</a>, <a href="http://www.scala-lang.org/api/2.12.6/scala/Any.html#scala.Any" class="extype" name="scala.Any">Any</a></div>
</div></div>
<div id="mbrsel">
<div class="toggle"></div>
<div id="memberfilter">
<i class="material-icons arrow"></i>
<span class="input">
<input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />
</span>
<i class="clear material-icons"></i>
</div>
<div id="filterby">
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By Inheritance</span></li>
</ol>
</div>
<div class="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="net.liftmodules.fobotbapi.TBLocInfo"><span>TBLocInfo</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div class="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show All</span></li>
</ol>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
</div>
<div id="template">
<div id="allMembers">
<div class="values members">
<h3>Value Members</h3>
<ol>
<li name="scala.AnyRef#!=" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a><a id="!=(Any):Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#!=(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/Any.html#scala.Any" class="extype" name="scala.Any">Any</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html###():Int" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Int.html#scala.Int" class="extype" name="scala.Int">Int</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a><a id="==(Any):Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#==(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/Any.html#scala.Any" class="extype" name="scala.Any">Any</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="net.liftmodules.fobotbapi.TBLocInfo#Divider" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="Divider:net.liftweb.sitemap.Loc.LocInfo[String]"></a><a id="Divider:LocInfo[String]"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#Divider:net.liftweb.sitemap.Loc.LocInfo[String]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">Divider</span><span class="result">: <span class="extype" name="net.liftweb.sitemap.Loc.LocInfo">LocInfo</span>[<span class="extype" name="scala.Predef.String">String</span>]</span>
</span>
<p class="shortcomment cmt">Provides a way to specify a horizontal divider for your bootstrap menu in Lift's SiteMap.</p><div class="fullcomment"><div class="comment cmt"><p>Provides a way to specify a horizontal divider for your bootstrap menu in Lift's SiteMap.
</p></div><dl class="attributes block"> <div class="block">Example:
<ol><li class="cmt"><p></p><pre><span class="kw">val</span> index = Menu.i(<span class="lit">"Home"</span>) / <span class="lit">"index"</span>
:
<span class="kw">val</span> about = Menu.i(<span class="lit">"About"</span>) / <span class="lit">"about"</span>
<span class="kw">val</span> divider2 = Menu(<span class="lit">"divider2"</span>) / <span class="lit">"divider2"</span> <span class="cmt">//dummy entry only showing a menu divider</span>
<span class="kw">val</span> navHeader1 = Menu.i(<span class="lit">"navHeader1"</span>) / <span class="lit">"navHeader1"</span> <span class="cmt">//Adds a header (label) to your FoBo.NavList</span>
<span class="kw">def</span> sitemap = SiteMap(
navHeader1 >> LocGroup(<span class="lit">"nl1"</span>) >> FoBoTB.TBLocInfo.NavHeader,
index >> LocGroup(<span class="lit">"top"</span>,<span class="lit">"nl1"</span>,...),
:
ddLabel >> LocGroup(<span class="lit">"top"</span>,...) >> PlaceHolder submenus(
about ,
divider2 >> FoBo.TBLocInfo.Divider,
contact,
feedback
)
)</pre></li></ol>
</div></dl></div>
</li><li name="net.liftmodules.fobotbapi.TBLocInfo#DividerVertical" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="DividerVertical:net.liftweb.sitemap.Loc.LocInfo[String]"></a><a id="DividerVertical:LocInfo[String]"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#DividerVertical:net.liftweb.sitemap.Loc.LocInfo[String]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">DividerVertical</span><span class="result">: <span class="extype" name="net.liftweb.sitemap.Loc.LocInfo">LocInfo</span>[<span class="extype" name="scala.Predef.String">String</span>]</span>
</span>
<p class="shortcomment cmt">Add a vertical divider in your bootstrap menu.</p><div class="fullcomment"><div class="comment cmt"><p>Add a vertical divider in your bootstrap menu.
For a usage example see the Divider val above.
</p></div></div>
</li><li name="net.liftmodules.fobotbapi.TBLocInfo#LinkTargetBlank" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="LinkTargetBlank:net.liftweb.sitemap.Loc.LocInfo[String]"></a><a id="LinkTargetBlank:LocInfo[String]"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#LinkTargetBlank:net.liftweb.sitemap.Loc.LocInfo[String]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">LinkTargetBlank</span><span class="result">: <span class="extype" name="net.liftweb.sitemap.Loc.LocInfo">LocInfo</span>[<span class="extype" name="scala.Predef.String">String</span>]</span>
</span>
<p class="shortcomment cmt">Adds target="_blank" to the link</p><div class="fullcomment"><div class="comment cmt"><p>Adds target="_blank" to the link</p></div><dl class="attributes block"> <dt>Since</dt><dd><p>v1.2</p></dd></dl></div>
</li><li name="net.liftmodules.fobotbapi.TBLocInfo#LinkTargetParent" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="LinkTargetParent:net.liftweb.sitemap.Loc.LocInfo[String]"></a><a id="LinkTargetParent:LocInfo[String]"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#LinkTargetParent:net.liftweb.sitemap.Loc.LocInfo[String]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">LinkTargetParent</span><span class="result">: <span class="extype" name="net.liftweb.sitemap.Loc.LocInfo">LocInfo</span>[<span class="extype" name="scala.Predef.String">String</span>]</span>
</span>
<p class="shortcomment cmt">Adds target="_parent" to the link</p><div class="fullcomment"><div class="comment cmt"><p>Adds target="_parent" to the link</p></div><dl class="attributes block"> <dt>Since</dt><dd><p>v1.2</p></dd></dl></div>
</li><li name="net.liftmodules.fobotbapi.TBLocInfo#LinkTargetSelf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="LinkTargetSelf:net.liftweb.sitemap.Loc.LocInfo[String]"></a><a id="LinkTargetSelf:LocInfo[String]"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#LinkTargetSelf:net.liftweb.sitemap.Loc.LocInfo[String]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">LinkTargetSelf</span><span class="result">: <span class="extype" name="net.liftweb.sitemap.Loc.LocInfo">LocInfo</span>[<span class="extype" name="scala.Predef.String">String</span>]</span>
</span>
<p class="shortcomment cmt">Adds target="_self" to the link</p><div class="fullcomment"><div class="comment cmt"><p>Adds target="_self" to the link</p></div><dl class="attributes block"> <dt>Since</dt><dd><p>v1.2</p></dd></dl></div>
</li><li name="net.liftmodules.fobotbapi.TBLocInfo#LinkTargetTop" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="LinkTargetTop:net.liftweb.sitemap.Loc.LocInfo[String]"></a><a id="LinkTargetTop:LocInfo[String]"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#LinkTargetTop:net.liftweb.sitemap.Loc.LocInfo[String]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">LinkTargetTop</span><span class="result">: <span class="extype" name="net.liftweb.sitemap.Loc.LocInfo">LocInfo</span>[<span class="extype" name="scala.Predef.String">String</span>]</span>
</span>
<p class="shortcomment cmt">Adds target="_top" to the link</p><div class="fullcomment"><div class="comment cmt"><p>Adds target="_top" to the link</p></div><dl class="attributes block"> <dt>Since</dt><dd><p>v1.2</p></dd></dl></div>
</li><li name="net.liftmodules.fobotbapi.TBLocInfo#NavHeader" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="NavHeader:net.liftweb.sitemap.Loc.LocInfo[String]"></a><a id="NavHeader:LocInfo[String]"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#NavHeader:net.liftweb.sitemap.Loc.LocInfo[String]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">NavHeader</span><span class="result">: <span class="extype" name="net.liftweb.sitemap.Loc.LocInfo">LocInfo</span>[<span class="extype" name="scala.Predef.String">String</span>]</span>
</span>
<p class="shortcomment cmt">Add nav header(s) to your bootstrap nav list.</p><div class="fullcomment"><div class="comment cmt"><p>Add nav header(s) to your bootstrap nav list.
For a usage example see the NavHeader val above.
</p></div></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#asInstanceOf[T0]:T0" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a><a id="clone():AnyRef"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#clone():Object" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/AnyRef.html#scala.AnyRef" class="extype" name="scala.AnyRef">AnyRef</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java/lang/index.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a><a id="eq(AnyRef):Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#eq(x$1:AnyRef):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/AnyRef.html#scala.AnyRef" class="extype" name="scala.AnyRef">AnyRef</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a><a id="equals(Any):Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#equals(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/Any.html#scala.Any" class="extype" name="scala.Any">Any</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#finalize():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java/lang/index.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#getClass():Class[_]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#hashCode" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#hashCode():Int" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Int.html#scala.Int" class="extype" name="scala.Int">Int</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#isInstanceOf[T0]:Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a><a id="ne(AnyRef):Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#ne(x$1:AnyRef):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/AnyRef.html#scala.AnyRef" class="extype" name="scala.AnyRef">AnyRef</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#notify():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#notifyAll():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a><a id="synchronized[T0](⇒T0):T0"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#synchronized[T0](x$1:=>T0):T0" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#toString" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#toString():String" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#wait():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a><a id="wait(Long,Int):Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#wait(x$1:Long,x$2:Int):Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/Long.html#scala.Long" class="extype" name="scala.Long">Long</a></span>, <span name="arg1">arg1: <a href="http://www.scala-lang.org/api/2.12.6/scala/Int.html#scala.Int" class="extype" name="scala.Int">Int</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a><a id="wait(Long):Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobotbapi/package$$TBLocInfo$.html#wait(x$1:Long):Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/Long.html#scala.Long" class="extype" name="scala.Long">Long</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li>
</ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="scala.AnyRef">
<h3>Inherited from <a href="http://www.scala-lang.org/api/2.12.6/scala/AnyRef.html#scala.AnyRef" class="extype" name="scala.AnyRef">AnyRef</a></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <a href="http://www.scala-lang.org/api/2.12.6/scala/Any.html#scala.Any" class="extype" name="scala.Any">Any</a></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</div>
</div>
</div>
</body>
</html>
|
karma4u101/FoBo-Demo
|
fobo-lift-template-demo/src/main/webapp/foboapi/older/v2.1/net/liftmodules/fobotbapi/package$$TBLocInfo$.html
|
HTML
|
apache-2.0
| 43,508
|
/* mbed Microcontroller Library
* Copyright (c) 2017-2017 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CORDIO_HCI_DRIVER_H_
#define CORDIO_HCI_DRIVER_H_
#include <stddef.h>
#include <stdint.h>
#include <BLETypes.h>
#include "wsf_buf.h"
#include "CordioHCITransportDriver.h"
namespace ble {
namespace vendor {
namespace cordio {
/**
* Contain description of the memory pool used by the Cordio stack.
*/
struct buf_pool_desc_t {
/**
* Create a new memory pool description
* @param buffer the Buffer used by the memory pool.
* @param pool_desc How the memory is split
*/
template<size_t BufferSize, size_t PoolCount>
buf_pool_desc_t(
uint8_t (&buffer)[BufferSize],
const wsfBufPoolDesc_t (&pool_desc)[PoolCount]
) : buffer_memory(buffer), buffer_size(BufferSize),
pool_description(pool_desc), pool_count(PoolCount)
{
}
uint8_t* buffer_memory; /// Pointer to the buffer memory
size_t buffer_size; /// Size of the buffer
const wsfBufPoolDesc_t* pool_description; /// Pointer to the first element describing the pool
size_t pool_count; /// Number of pools
};
/**
* Base class of the HCI driver use by the BLE port of the Cordio stack.
* This class provide to the stack:
* - The buffer necessary to run BLE API
* - The reset sequence of the BLE module
* - Access to the write function of the underlying HCITransport driver.
*/
class CordioHCIDriver {
// hook for internal tests and passthrough driver
friend class CordioHCIHook;
public:
/**
* Construct a new instance of an HCI driver.
* @param transport_driver The driver used to communicate with the chip.
*/
CordioHCIDriver(CordioHCITransportDriver& transport_driver);
/**
* Driver destructor
*/
virtual ~CordioHCIDriver() { }
/**
* Return the set of memory pool which will be used by the Cordio stack
*/
virtual buf_pool_desc_t get_buffer_pool_description() = 0;
/**
* Initialize the HCI driver.
* This function start by initializing the transport driver then it delegates
* what's remain of the initialization to the function do_initialize.
*/
void initialize();
/**
* Termination of the driver.
* It call in sequence:
* - do_terminate
* - terminate the transport driver.
*/
void terminate();
/**
* Start the reset sequence of the BLE module.
*/
virtual void start_reset_sequence();
/**
* Handle HCI messages received during the reset sequence.
*
* @param msg The HCI message received.
* @note The driver should signal to the stack that the initialization
* sequence is done by calling the function: signal_reset_sequence_done.
*/
virtual void handle_reset_sequence(uint8_t *msg);
/**
* Get the random static address of the controller
*
* @return false if the address has not been set and true otherwise.
*/
virtual bool get_random_static_address(ble::address_t& address);
/**
* Signal to the stack that the reset sequence has been done.
*/
void signal_reset_sequence_done();
/**
* Write data in the transport channel.
*
* @param type The type of packet to transmit. It might be an HCI command
* packet, ACL packet or EVT packet. Depending on the type of transport
* it can prefix the packet itself.
* @param len Number of bytes to transmit.
* @param pData pointer to the data to transmit.
*
* @return The number of bytes which have been transmited.
*/
uint16_t write(uint8_t type, uint16_t len, uint8_t *pData);
/**
* React to host stack inactivity.
*
* The host stack invoke this function when it is inactive. It allows a
* driver to put its controller to sleep if all the conditions are met.
*
* Any call to write signals to the driver that the host stack is active.
*/
virtual void on_host_stack_inactivity();
protected:
/**
* Return a default set of memory pool that the Cordio stack can use.
* This function can be used to implement get_buffer_pool_description().
*/
buf_pool_desc_t get_default_buffer_pool_description();
/**
* Allows the driver to set a random static address. Unlike the HCI command
* this function reports the random static address to the whole BLE system.
* @param random_static_address The random static address to set.
*/
void set_random_static_address(const ble::address_t& random_static_address);
private:
/**
* Initialize the chip.
* The transport is up at that time.
*/
virtual void do_initialize() = 0;
/**
* Terminate the driver
*/
virtual void do_terminate() = 0;
CordioHCITransportDriver& _transport_driver;
};
} // namespace cordio
} // namespace vendor
} // namespace ble
#endif /* CORDIO_HCI_DRIVER_H_ */
|
kjbracey-arm/mbed
|
features/FEATURE_BLE/targets/TARGET_CORDIO/driver/CordioHCIDriver.h
|
C
|
apache-2.0
| 5,513
|
/*
* Copyright 2016-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 es.esky.role.users.domain.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;
import org.springframework.stereotype.Component;
/**
* Validate if a {@code String} is uppercase. Use for {@link Uppercase} interface.
*
* @author Cristian Mateos López
* @since 1.0.0
*/
@Component
public class UppercaseValidator implements ConstraintValidator<Uppercase, String> {
private static final Pattern HAS_UPPERCASE = Pattern.compile("[A-Z]");
/**
* {@inheritDoc}
*/
@Override
public void initialize(Uppercase constraintAnnotation) {
// Not initialization needed.
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return HAS_UPPERCASE.matcher(value).find();
}
}
|
cmateosl/rol-api
|
src/main/java/es/esky/role/users/domain/validator/UppercaseValidator.java
|
Java
|
apache-2.0
| 1,459
|
#ifndef BOOST_MPL_VECTOR_AUX_EMPTY_HPP_INCLUDED
#define BOOST_MPL_VECTOR_AUX_EMPTY_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: empty.hpp,v 1.2 2009/02/16 01:51:06 wdong-pku Exp $
// $Date: 2009/02/16 01:51:06 $
// $Revision: 1.2 $
#include <boost/mpl/empty_fwd.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/vector/aux_/tag.hpp>
#include <boost/mpl/aux_/config/typeof.hpp>
#include <boost/mpl/aux_/config/ctps.hpp>
#include <boost/type_traits/is_same.hpp>
namespace boost { namespace mpl {
#if defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES)
template<>
struct empty_impl< aux::vector_tag >
{
template< typename Vector > struct apply
: is_same<
typename Vector::lower_bound_
, typename Vector::upper_bound_
>
{
};
};
#else
template<>
struct empty_impl< aux::vector_tag<0> >
{
template< typename Vector > struct apply
: true_
{
};
};
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template< long N >
struct empty_impl< aux::vector_tag<N> >
{
template< typename Vector > struct apply
: false_
{
};
};
#endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
#endif // BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES
}}
#endif // BOOST_MPL_VECTOR_AUX_EMPTY_HPP_INCLUDED
|
nihilus/BinClone
|
lshkit/trunk/3rd-party/boost/boost/mpl/vector/aux_/empty.hpp
|
C++
|
apache-2.0
| 1,513
|
function getQueryParamValue(queryString) {
var params = {}, queries, temp, i, l;
// Split into key/value pairs
queryString = queryString.substring(1, queryString.length);
queries = queryString.split("&");
// Convert the array of strings into an object
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
}
/**
* @return An object with named path components
*/
function parsePath(dashboardPath) {
var tokens = dashboardPath.split("/")
var type = tokens[1]
if (type == 'dashboard') {
return {
collection: tokens[2],
metricFunction: tokens[3],
metricViewType: tokens[4],
dimensionViewType: tokens[5],
baselineMillis: tokens[6],
currentMillis: tokens[7]
}
} else if (type == 'metric') {
return {
collection: tokens[2],
metricFunction: tokens[3],
metricViewType: tokens[4],
baselineMillis: tokens[5],
currentMillis: tokens[6]
}
} else if (type == 'dimension') {
return {
collection: tokens[2],
metricFunction: tokens[3],
dimensionViewType: tokens[4],
baselineMillis: tokens[5],
currentMillis: tokens[6]
}
} else {
throw "Invalid path type: " + type
}
}
function parseHashParameters(hashString) {
var params = {}
if (hashString) {
if (hashString.charAt(0) == '#') {
hashString = hashString.substring(1)
}
var keyValuePairs = hashString.split('&')
$.each(keyValuePairs, function(i, pair) {
var tokens = pair.split('=')
var key = decodeURIComponent(tokens[0])
var value = decodeURIComponent(tokens[1])
params[key] = value
})
}
return params
}
function encodeHashParameters(hashParameters) {
var keyValuePairs = []
$.each(hashParameters, function(key, value) {
keyValuePairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
})
return '#' + keyValuePairs.join('&')
}
function setHashParameter(hashString, key, value) {
var params = parseHashParameters(hashString)
params[key] = value
return encodeHashParameters(params)
}
function parseMetricFunction(metricFunction) {
var stack = []
var collector = ""
for (var i = 0; i < metricFunction.length; i++) {
if (metricFunction.charAt(i) == '(') { // open function
var name = collector
collector = ""
stack.push({
name: name,
args: []
})
} else if (metricFunction.charAt(i) == ')') { // close function
if (collector.length > 0) {
stack[stack.length - 1].args.push(collector)
collector = ""
}
var func = stack.pop()
if (stack.length == 0) {
stack.push(func)
} else {
stack[stack.length - 1].args.push(func)
}
} else if (metricFunction.charAt(i) == ',') { // arg
stack[stack.length - 1].args.push(collector)
collector = ""
} else {
collector += metricFunction.charAt(i)
}
}
return stack.pop()
}
function getDashboardPath(path) {
return "/dashboard"
+ "/" + path.collection
+ "/" + path.metricFunction
+ "/" + path.metricViewType
+ "/" + path.dimensionViewType
+ "/" + path.baselineMillis
+ "/" + path.currentMillis
}
function getFlotViewType(metricViewType) {
if (metricViewType == 'INTRA_DAY') {
return 'TIME_SERIES_FULL'
} else if (metricViewType == 'FUNNEL') {
return 'TIME_SERIES_FULL'
} else {
return metricViewType
}
}
/**
* @return A pathname suitable for getting the time series from the parsed path
*/
function getFlotPath(path, options) {
var viewType = getFlotViewType(path.metricViewType)
if (viewType == 'TIME_SERIES_OVERLAY') {
return '/flot'
+ '/' + viewType
+ '/' + path.collection
+ '/' + path.metricFunction
+ '/' + path.baselineMillis
+ '/' + path.currentMillis
+ '/' + options.windowMillis
} else {
return '/flot'
+ '/' + viewType
+ '/' + path.collection
+ '/' + path.metricFunction
+ '/' + path.baselineMillis
+ '/' + path.currentMillis
}
}
function parseDimensionValues(queryString) {
var dimensionValues = {}
if (queryString) {
var query = queryString
if (query.indexOf("?") >= 0) {
query = query.substring(1)
}
var tokens = query.split("&")
$.each(tokens, function(i, token) {
var keyValue = token.split("=")
var key = decodeURIComponent(keyValue[0])
var value = decodeURIComponent(keyValue[1])
dimensionValues[key] = value
})
}
return dimensionValues
}
function encodeDimensionValues(dimensionValues) {
var components = []
$.each(dimensionValues, function(key, value) {
var encodedKey = encodeURIComponent(key)
var encodedValue = encodeURIComponent(value)
components.push(encodedKey + "=" + encodedValue)
})
return "?" + components.join("&")
}
function renderFunnel(container, options) {
var path = parsePath(window.location.pathname)
var endMillis = 0
if (options.mode == 'current') {
endMillis = path.currentMillis
} else {
endMillis = path.baselineMillis
}
path.baselineMillis = endMillis
path.currentMillis = endMillis
var url = getFlotPath(path, options)
if (window.location.search) {
url += window.location.search
if (options.dimension) {
url += '&' + encodeURIComponent(options.dimension) + '=!'
}
} else if (options.dimension) {
url += '?' + encodeURIComponent(options.dimension) + '=!'
}
if (options.legendContainer) {
options.legendContainer.empty()
}
var render = function(data) {
container.css('width', container.width())
container.css('height', '400px')
data.sort(function(a, b) {
return b.data[0][1] - a.data[0][1]
})
// Max value
var max = 0
$.each(data, function(i, datum) {
datum.rawData = datum.data[0][1]
if (datum.rawData > max) {
max = datum.rawData
}
})
// Get ratios to max
$.each(data, function(i, datum) {
datum.ratio = datum.rawData / max
})
// Subtract the next from each
for (var i = 0; i < data.length - 1; i++) {
data[i].data[0][1] -= data[i+1].data[0][1]
}
if(data.length == 1) {
var warning = $('<div></div>', { class: 'uk-alert uk-alert-warning' })
warning.append($('<p></p>', { html: 'A funnel must consist of more than one metric.' }))
container.append(warning)
return;
}
container.plot(data, {
series: {
funnel: {
show: true,
label: {
show: true,
formatter: function(label, slice) {
if (slice.ratio >= 0.999) {
return slice.rawData
}
return slice.rawData + ' (' + (slice.ratio * 100).toFixed(2) + '%)'
}
}
}
},
legend: {
container: options.legendContainer
}
})
}
$.ajax({
url: url,
statusCode: {
404: function() {
container.empty()
var warning = $('<div></div>', { class: 'uk-alert uk-alert-warning' })
warning.append($('<p></p>', { html: 'No data available' }))
container.append(warning)
},
500: function() {
container.empty()
var error = $('<div></div>', { class: 'uk-alert uk-alert-danger' })
error.append($('<p></p>', { html: 'Internal server error' }))
container.append(error)
}
}
}).done(render)
}
/**
* @param container The jQuery object in which to put the time series
* @param tooltip The jQuery object which should contain the hover information
*/
function renderTimeSeries(container, tooltip, options) {
container.empty()
container.html('Loading...')
var path = parsePath(window.location.pathname)
var url = getFlotPath(path, options)
if (!options) {
options = {}
}
if (options.legendContainer) {
options.legendContainer.empty()
}
if (window.location.search) {
url += window.location.search
if (options.dimension) {
url += '&' + encodeURIComponent(options.dimension) + '=!'
}
} else if (options.dimension) {
url += '?' + encodeURIComponent(options.dimension) + '=!'
}
container.css('width', container.width())
tooltip.css('position', 'absolute')
tooltip.css('display', 'none')
options.minTickSize = (path.currentMillis - path.baselineMillis) / 10
var render = function(data) {
container.empty()
if (options.mode == 'own') {
var groups = {}
$.each(data, function(i, datum) {
var label = datum.label
if (label.indexOf('BASELINE_') >= 0) {
label = label.substring('BASELINE_'.length)
} else if (label.indexOf('ANOMALY_') >= 0) {
label = label.substring('ANOMALY_'.length)
}
label = label.substring(0, label.indexOf(' '))
if (!groups[label]) {
groups[label] = []
}
groups[label].push(datum)
})
var groupValues = []
$.each(groups, function(label, values) {
groupValues.push(values)
})
var totalHeight = 0
for (var i = 0; i < groupValues.length; i++) {
var subContainer = $("<div></div>")
var subCanvas = $("<div></div>")
var subLegend = $("<div></div>", { class: 'time-series-legend' })
var optionsCopy = $.extend(true, {}, options)
subContainer.append(subCanvas).append(subLegend)
container.append(subContainer)
subCanvas.css('width', container.width())
subCanvas.css('height', '200px')
optionsCopy.legendContainer = subLegend
plotOne(subCanvas, tooltip, optionsCopy, groupValues[i])
totalHeight += subContainer.height()
}
container.css('height', totalHeight)
} else {
container.css('height', '400px')
plotOne(container, tooltip, options, data)
}
}
$.ajax({
url: url,
statusCode: {
404: function() {
container.empty()
var warning = $('<div></div>', { class: 'uk-alert uk-alert-warning' })
warning.append($('<p></p>', { html: 'No data available' }))
container.append(warning)
},
500: function() {
container.empty()
var error = $('<div></div>', { class: 'uk-alert uk-alert-danger' })
error.append($('<p></p>', { html: 'Internal server error' }))
container.append(error)
}
}
}).done(render)
}
function plotOne(container, tooltip, options, data) {
if (options.filter) {
data = options.filter(data)
}
// make anomalies display as points instead of lines
var dataToPlot = []
for (var i = 0; i < data.length; i++) {
if (data[i].label.indexOf("ANOMALY_") >= 0) {
data[i].lines = { show: false }
data[i].points = {
show: true,
radius: 5,
}
data[i].color = "red"
}
}
container.plot(data, {
legend: {
show: options.legend == null ? true : options.legend,
position: "se",
container: options.legendContainer
},
grid: {
clickable: true,
hoverable: true
},
xaxis: {
tickFormatter: function(millis) {
return moment.utc(millis).tz(jstz().timezone_name).format("YYYY-MM-DD HH:mm")
},
minTickSize: options.minTickSize
}
})
container.bind("plothover", function(event, pos, item) {
if (item) {
var dateString = moment.utc(item.datapoint[0]).tz(jstz().timezone_name).format()
var value = item.datapoint[1]
if (item.series.label.indexOf("ANOMALY_") >= 0) {
var metric = item.series.label.substring('ANOMALY_'.length, item.series.label.indexOf(' '))
tooltip.html(metric + " = " + value + " @ " + dateString + "<hr>"
+ item.series.annotations[item.datapoint[0]].join("<hr>"))
.css({
top: item.pageY + 5,
right: $(window).width() - item.pageX,
'background-color': 'white',
border: '1px solid red',
'z-index': 1000
})
.fadeIn(100)
} else {
tooltip.html(item.series.label + " = " + value + " @ " + dateString)
.css({
top: item.pageY + 5,
right: $(window).width() - item.pageX,
'background-color': '#ffcc00',
border: '1px solid #cc9900',
'z-index': 1000
})
.fadeIn(100)
}
} else {
tooltip.hide()
}
})
if (options.click) {
container.bind("plotclick", options.click)
}
}
/**
* @param rawData The container with raw data
* @return an object with the raw data
*/
function extractHeatMapData(rawData) {
var data = {}
rawData.find('.dimension-view-heat-map').each(function(i, heatMap) {
var heatMapObj = $(heatMap)
var id = heatMapObj.attr('metric').split('.').join('-') + '-' + heatMapObj.attr('dimension').split('.').join('-')
data[id] = {
metric: heatMapObj.attr('metric'),
metricDisplay: heatMapObj.attr('metric-display'),
dimension: heatMapObj.attr('dimension'),
dimensionDisplay: heatMapObj.attr('dimension-display'),
cells: []
}
// Get stats name mapping
var statsNamesMapping = {}
var statsNames = JSON.parse(heatMapObj.attr('stats-names'))
$.each(statsNames, function(i, statsName) {
statsNamesMapping[statsName] = i
})
heatMapObj.find('.dimension-view-heat-map-cell').each(function(j, cell) {
var cellObj = $(cell)
// Get cell stats
try {
var statsList = JSON.parse(cellObj.attr('stats'))
var cellStats = {}
$.each(statsNamesMapping, function(name, idx) {
cellStats[name] = statsList[idx]
})
data[id].cells.push({
value: cellObj.attr('value'),
stats: cellStats
})
} catch (e) {
console.error('Corrupt heat map cell data', cellObj, e)
}
})
})
return data
}
/**
* @param rawData The raw heat map data (XML)
* @param container The container in which to place the rendered heat map
* @param options (sortKey, alphaKey, mainDisplayKey, positiveClass, negativeClass)
*/
function renderHeatMap(rawData, container, options) {
var data = extractHeatMapData(rawData)
container.empty()
// Group
var groups = {}
$.each(data, function(heatMapId, heatMapSpec) {
var cells = heatMapSpec.cells
var tokens = heatMapId.split('-')
var metric = heatMapSpec.metric
var dimension = heatMapSpec.dimension
var groupKey = options.groupBy == 'DIMENSION' ? heatMapSpec.dimensionDisplay : heatMapSpec.metricDisplay
var caption = options.groupBy == 'DIMENSION' ? heatMapSpec.metricDisplay : heatMapSpec.dimensionDisplay // show the other as caption
if (!groups[groupKey]) {
groups[groupKey] = []
}
groups[groupKey].push({
dimension: dimension,
metric: metric,
caption: caption,
cells: cells,
id: heatMapId
})
})
$.each(groups, function(groupId, group) {
var header = $('<h2></h2>', { html: groupId })
container.append(header)
$.each(group, function(i, heatMap) {
var table = $('<table></table>', { class: 'uk-table dimension-view-heat-map-rendered' })
var caption = $('<caption></caption>', { html: heatMap.caption })
var cells = heatMap.cells
var heatMapId = heatMap.id
cells.sort(options.comparator)
// Group cells into rows
var numColumns = 5
var rows = []
var currentRow = []
for (var i = 0; i < cells.length; i++) {
if (options.filter != null && !options.filter(cells[i])) {
continue
}
currentRow.push(cells[i])
if (currentRow.length == numColumns) {
rows.push(currentRow)
currentRow = []
}
}
if (currentRow.length > 0) {
rows.push(currentRow)
}
// Generate table body
var tbody = $("<tbody></tbody>")
$.each(rows, function(i, row) {
var tr = $("<tr></tr>")
$.each(row, function(j, cell) {
var td = $("<td></td>")
td.html(options.display(cell))
td.css('background-color', options.backgroundColor(cell))
td.hover(function() { $(this).css('cursor', 'pointer') })
td.attr('title', $.map(cell.stats, function(val, key) {
if (val !== null && (key === 'baseline_cdf_value'
|| key === 'current_cdf_value'
|| key === 'contribution_difference'
|| key === 'current_ratio'
|| key === 'baseline_ratio'
|| key === 'volume_difference')) {
return key + '=' + val.toFixed(2)
} else {
return key + '=' + val
}
}).join("\n"))
td.attr('dimension', heatMap.dimension);
// Annotate outliers
if (cell.stats['snapshot_category'] == 1) {
td.css('border', '2px solid #580f8b')
}
// Drill-down click handler
td.click(function() {
var name = $(this).attr('dimension')
var value = cell.value
var dimensionValues = parseDimensionValues(window.location.search)
dimensionValues[name] = value
window.location.search = encodeDimensionValues(dimensionValues)
})
tr.append(td)
})
tbody.append(tr)
})
// Append
table.append(caption)
table.append(tbody)
container.append(table)
})
})
}
/** @return A {"size": x, "unit": y} object that best describes @param millis */
function describeMillis(millis) {
var descriptors = [
[2592000000, "MONTHS"],
[604800000, "WEEKS"],
[86400000, "DAYS"],
[3600000, "HOURS"]
]
for (var i = 0; i < descriptors.length; i++) {
if (millis >= descriptors[i][0] && millis % descriptors[i][0] == 0) {
return {
"sizeMillis": descriptors[i][0],
"size": millis / descriptors[i][0],
"unit": descriptors[i][1]
}
}
}
return null
}
function toMillis(size, unit) {
if (unit == 'SECONDS') {
return size * 1000
} else if (unit == 'MINUTES') {
return size * 60 * 1000
} else if (unit == 'HOURS') {
return size * 60 * 60 * 1000
} else if (unit == 'DAYS') {
return size * 24 * 60 * 60 * 1000
} else if (unit == 'WEEKS') {
return size * 7 * 24 * 60 * 60 * 1000
} else if (unit == 'MONTHS') {
return size * 30 * 24 * 60 * 60 * 1000
}
}
function getLocalTimeZone() {
var timeZone = jstz()
var utcOffset = timeZone.utc_offset
var utcOffsetHours = Math.abs(utcOffset) / 60
var utcOffsetMinutes = Math.abs(utcOffset) % 60
var utcOffsetMagnitude = Math.abs(utcOffsetHours)
var formatted = ""
formatted += utcOffset < 0 ? "-" : ""
formatted += utcOffsetMagnitude < 10 ? "0" + utcOffsetMagnitude : utcOffsetMagnitude
formatted += ":"
formatted += utcOffsetMinutes < 10 ? "0" + utcOffsetMinutes : utcOffsetMinutes
formatted += " " + timeZone.timezone_name
return formatted
}
/**
* Get Time Zone
* @function
* @public
* @returns {String} Local timezone from getLocalTimeZone() or hash params
* timezone
*/
function getTimeZone() {
var timeZone = jstz()
if(window.location.hash) {
var params = parseHashParameters(window.location.hash)
if(params.timezone) {
tz = params.timezone.split('-').join('/')
} else {
tz = timeZone.timezone_name
}
} else {
tz = timeZone.timezone_name
}
return tz
}
function updateTableOrder(tableContainer, orderContainer) {
// Get column headers
var currentOrder = $.map(tableContainer.find("thead tr").first().find("th"), function(elt) {
return $.trim(elt.innerHTML)
}).slice(1) // for time column
// Get columns
var columns = {}
for (var i = 0; i < currentOrder.length; i++) {
columns[currentOrder[i]] = []
}
var tableRows = tableContainer.find("tbody tr")
for (var i = 0; i < tableRows.size(); i++) {
var tableCols = $(tableRows[i]).find("td")
for (var j = 0; j < currentOrder.length; j++) {
var colIdx = 1 + j * 3 // n.b. first column time
//columns[j].push({
columns[currentOrder[j]].push({
current: tableCols[colIdx].innerHTML,
baseline: tableCols[colIdx + 1].innerHTML,
ratio: tableCols[colIdx + 2].innerHTML
})
}
}
// Get the desired ordering of metric columns
var nextOrder = $.map(orderContainer.find("li div"), function(elt) {
return $.trim(elt.innerHTML)
})
// Re-write the column headers
tableContainer.find("thead tr").first().find("th").each(function(i, elt) {
if (i > 0) { // first is time column
var metricIndex = i - 1
var currentMetric = currentOrder[metricIndex]
var nextMetric = nextOrder[metricIndex]
$(elt).html(nextMetric)
}
})
// Re-write the columns
for (var i = 0; i < tableRows.size(); i++) {
var tableCols = $(tableRows[i]).find("td")
for (var j = 0; j < currentOrder.length; j++) {
var nextMetric = nextOrder[j]
var column = columns[nextMetric]
// This is relative to the table itself
var colIdx = 1 + j * 3;
$(tableCols[colIdx]).html(column[i].current)
$(tableCols[colIdx + 1]).html(column[i].baseline)
$(tableCols[colIdx + 2]).html(column[i].ratio)
// Set the right class for the value
var ratio = parseFloat(column[i].ratio)
var ratioCell = $(tableCols[colIdx + 2])
ratioCell.removeClass('metric-table-down-cell metric-table-same-cell')
if (ratio < 0) {
ratioCell.addClass('metric-table-down-cell')
} else if (ratio == 0) {
ratioCell.addClass('metric-table-same-cell')
}
}
}
// Set hash parameter
var hashParams = parseHashParameters(window.location.hash)
$.each(nextOrder, function(i, elt) {
hashParams['intraDayOrder_' + i] = elt
})
window.location.hash = encodeHashParameters(hashParams)
}
|
fjy/pinot
|
thirdeye/thirdeye-dashboard/src/main/resources/assets/js/thirdeye.js
|
JavaScript
|
apache-2.0
| 24,905
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
"""Cloud TPU profiler package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from setuptools import setup
_VERSION = '1.7.0'
CONSOLE_SCRIPTS = [
'capture_tpu_profile=cloud_tpu_profiler.main:run_main',
]
setup(
name='cloud_tpu_profiler',
version=_VERSION.replace('-', ''),
description='Trace and profile Cloud TPU performance',
long_description='Tools for capture TPU profile',
url='https://www.tensorflow.org/tfrc/',
author='Google Inc.',
author_email='opensource@google.com',
packages=['cloud_tpu_profiler'],
package_data={
'cloud_tpu_profiler': ['data/*'],
},
entry_points={
'console_scripts': CONSOLE_SCRIPTS,
},
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
license='Apache 2.0',
keywords='tensorflow performance tpu',
)
|
gojira/tensorflow
|
tensorflow/contrib/tpu/profiler/pip_package/setup.py
|
Python
|
apache-2.0
| 2,551
|
/// Copyright (c) 2009 Microsoft Corporation
///
/// 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 Microsoft 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.
ES5Harness.registerTest({
id: "15.2.3.6-3-147",
path: "TestCases/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-147.js",
description: "Object.defineProperty - 'Attributes' is the JSON object that uses Object's [[Get]] method to access the 'value' property (8.10.5 step 5.a)",
test: function testcase() {
var obj = {};
try {
JSON.value = "JSON";
Object.defineProperty(obj, "property", JSON);
return obj.property === "JSON";
} finally {
delete JSON.value;
}
},
precondition: function prereq() {
return fnExists(Object.defineProperty);
}
});
|
hnafar/IronJS
|
Src/Tests/ietestcenter/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-147.js
|
JavaScript
|
apache-2.0
| 2,218
|
<!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
</head>
<body>
<div class="app">
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
|
Jayklutch/HappyLeaf
|
plugins/cz.blocshop.socketsforcordova/src/ios/www/index.html
|
HTML
|
apache-2.0
| 1,950
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.jetbrains.python.documentation.doctest;
import com.google.common.collect.Lists;
import com.intellij.codeInsight.completion.CompletionUtil;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.ResolveResult;
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner;
import com.jetbrains.python.psi.PyQualifiedExpression;
import com.jetbrains.python.psi.impl.references.PyReferenceImpl;
import com.jetbrains.python.psi.resolve.*;
import com.jetbrains.python.psi.types.TypeEvalContext;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* User : ktisha
*/
public class PyDocReference extends PyReferenceImpl {
public PyDocReference(PyQualifiedExpression element, @NotNull PyResolveContext context) {
super(element, context);
}
@Override
public HighlightSeverity getUnresolvedHighlightSeverity(TypeEvalContext context) {
return HighlightSeverity.WARNING;
}
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
ResolveResult[] results = super.multiResolve(incompleteCode);
if (results.length == 0) {
PsiFile file = myElement.getContainingFile();
final InjectedLanguageManager languageManager = InjectedLanguageManager.getInstance(myElement.getProject());
final PsiLanguageInjectionHost host = languageManager.getInjectionHost(myElement);
if (host != null) file = host.getContainingFile();
final String referencedName = myElement.getReferencedName();
if (referencedName == null) return ResolveResult.EMPTY_ARRAY;
if (host != null) {
final List<Pair<PsiElement,TextRange>> files = languageManager.getInjectedPsiFiles(host);
if (files != null) {
for (Pair<PsiElement, TextRange> pair : files) {
ResolveProcessor processor = new ResolveProcessor(referencedName);
PyResolveUtil.scopeCrawlUp(processor, (ScopeOwner)pair.getFirst(), referencedName, pair.getFirst());
final List<RatedResolveResult> resultList = getResultsFromProcessor(referencedName, processor, pair.getFirst(),
pair.getFirst());
if (resultList.size() > 0) {
List<RatedResolveResult> ret = RatedResolveResult.sorted(resultList);
return ret.toArray(new RatedResolveResult[ret.size()]);
}
}
}
}
ResolveProcessor processor = new ResolveProcessor(referencedName);
if (file instanceof ScopeOwner)
PyResolveUtil.scopeCrawlUp(processor, (ScopeOwner)file, referencedName, file);
final List<RatedResolveResult> resultList = getResultsFromProcessor(referencedName, processor, file, file);
if (resultList.size() > 0) {
List<RatedResolveResult> ret = RatedResolveResult.sorted(resultList);
return ret.toArray(new RatedResolveResult[ret.size()]);
}
}
return results;
}
@NotNull
public Object[] getVariants() {
final ArrayList<Object> ret = Lists.newArrayList(super.getVariants());
PsiFile file = myElement.getContainingFile();
final InjectedLanguageManager languageManager = InjectedLanguageManager.getInstance(myElement.getProject());
final PsiLanguageInjectionHost host = languageManager.getInjectionHost(myElement);
if (host != null) file = host.getContainingFile();
final PsiElement originalElement = CompletionUtil.getOriginalElement(myElement);
final PyQualifiedExpression element = originalElement instanceof PyQualifiedExpression ?
(PyQualifiedExpression)originalElement : myElement;
// include our own names
final CompletionVariantsProcessor processor = new CompletionVariantsProcessor(element);
if (file instanceof ScopeOwner)
PyResolveUtil.scopeCrawlUp(processor, (ScopeOwner)file, null, null);
ret.addAll(processor.getResultList());
return ret.toArray();
}
}
|
romankagan/DDBWorkbench
|
python/src/com/jetbrains/python/documentation/doctest/PyDocReference.java
|
Java
|
apache-2.0
| 4,878
|
/*
* Copyright Terracotta, 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 org.terracotta.runnel.metadata;
import org.terracotta.runnel.decoding.ArrayDecoder;
import org.terracotta.runnel.decoding.StructArrayDecoder;
import org.terracotta.runnel.decoding.StructDecoder;
import org.terracotta.runnel.decoding.fields.ArrayField;
import org.terracotta.runnel.decoding.fields.Field;
import org.terracotta.runnel.decoding.fields.StructField;
import org.terracotta.runnel.decoding.fields.ValueField;
import org.terracotta.runnel.utils.ReadBuffer;
/**
* @author Ludovic Orban
*/
public class FieldDecoder {
private final Metadata metadata;
private final ReadBuffer readBuffer;
private int lastIndex = -1;
private int readAheadIndex = -1;
FieldDecoder(Metadata metadata, ReadBuffer readBuffer) {
this.metadata = metadata;
this.readBuffer = readBuffer;
}
public <P> StructArrayDecoder<P> decodeStructArray(String name, P parent) {
ArrayField field = nextField(name, ArrayField.class, StructField.class);
if (field == null) {
return null;
}
return new StructArrayDecoder<P>(((StructField) field.subField()), readBuffer, parent);
}
public <P> StructDecoder<P> decodeStruct(String name, P parent) {
StructField field = nextField(name, StructField.class, null);
if (field == null) {
return null;
}
return new StructDecoder<P>(field, readBuffer, parent);
}
@SuppressWarnings("unchecked")
public <T, P> ArrayDecoder<T, P> decodeValueArray(String name, Class<? extends ValueField<T>> clazz, P parent) {
ArrayField field = nextField(name, ArrayField.class, clazz);
if (field == null) {
return null;
}
return new ArrayDecoder<>((ValueField<T>) field.subField(), readBuffer, parent);
}
public <T> T decodeValue(String name, Class<? extends ValueField<T>> clazz) {
ValueField<T> field = nextField(name, clazz, null);
if (field == null) {
return null;
}
return field.decode(readBuffer);
}
@SuppressWarnings("unchecked")
private <T extends Field, S extends Field> T nextField(String name, Class<T> fieldClazz, Class<S> subFieldClazz) {
Field field = findFieldWithIndex(name, fieldClazz, subFieldClazz);
if (readBuffer.limitReached()) {
return null;
}
int index = readAheadIndex > 0 ? readAheadIndex : readBuffer.getVlqInt();
readAheadIndex = -1;
// skip all fields with a lower index than the requested field's
while (index < field.index()) {
int fieldSize = readBuffer.getVlqInt();
readBuffer.skip(fieldSize);
if (readBuffer.limitReached()) {
return null;
}
index = readBuffer.getVlqInt();
}
if (index > field.index()) {
readAheadIndex = index;
return null;
} else if (index != field.index()) {
return null;
} else {
return (T) field;
}
}
private <T extends Field, S extends Field> Field findFieldWithIndex(String name, Class<T> fieldClazz, Class<S> subFieldClazz) {
Field field = metadata.getFieldByName(name);
if (field == null) {
throw new IllegalArgumentException("No such field : " + name);
}
if (field.index() <= lastIndex) {
throw new IllegalArgumentException("No such field left : '" + name + "'");
}
lastIndex = field.index();
if (field.getClass() != fieldClazz) {
throw new IllegalArgumentException("Invalid type for field '" + name + "', expected : '" + fieldClazz.getSimpleName() + "' but was '" + field.getClass().getSimpleName() + "'");
}
if (subFieldClazz != null) {
ArrayField arrayField = (ArrayField) field;
Field nextSubField = arrayField.subField();
if (!nextSubField.getClass().equals(subFieldClazz)) {
throw new IllegalArgumentException("Invalid subtype for field '" + name + "', expected : '" + subFieldClazz.getSimpleName() + "' but was '" + nextSubField.getClass().getSimpleName() + "'");
}
}
return field;
}
}
|
chrisdennis/terracotta-platform
|
runnel/src/main/java/org/terracotta/runnel/metadata/FieldDecoder.java
|
Java
|
apache-2.0
| 4,506
|
/*!
* ${copyright}
*/
// Provides control sap.ui.ux3.DataSetItem.
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Element', './library'],
function(jQuery, Element, library) {
"use strict";
/**
* Constructor for a new DataSetItem.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* DataSet Item
* @extends sap.ui.core.Element
* @version ${version}
*
* @constructor
* @public
* @deprecated as of version 1.38
* @alias sap.ui.ux3.DataSetItem
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var DataSetItem = Element.extend("sap.ui.ux3.DataSetItem", /** @lends sap.ui.ux3.DataSetItem.prototype */ { metadata : {
library : "sap.ui.ux3",
properties : {
/**
* image
*/
iconSrc : {type : "sap.ui.core.URI", group : "Misc", defaultValue : null},
/**
* title
*/
title : {type : "string", group : "Misc", defaultValue : 'Title'},
/**
* checkable
*/
checkable : {type : "boolean", group : "Misc", defaultValue : true},
/**
* subtitle
*/
subtitle : {type : "string", group : "Misc", defaultValue : 'Subtitle'}
},
aggregations : {
/**
* The template control currently aggregated by this item and managed by the DataSet
*/
_template : {type : "sap.ui.core.Control", multiple : false, visibility : "hidden"}
},
events : {
/**
* Event Fired when Datset item is selected.
*/
selected : {
parameters : {
/**
* Id of the selected Datset item
*/
itemId : {type : "string"}
}
}
}
}});
/**
* Handle onclick event. Fires selected Event.
* @param {sap.ui.base.Event} oEvent click event
* @private
*/
DataSetItem.prototype.onclick = function(oEvent) {
oEvent.stopPropagation();
// determine modifier keys
var bShift = oEvent.shiftKey;
var bCtrl = !!(oEvent.metaKey || oEvent.ctrlKey);
this.fireSelected({
itemId: this.getId(),
shift: bShift,
ctrl: bCtrl
});
};
DataSetItem.prototype.ondblclick = function(oEvent) {
this.onclick(oEvent);
};
return DataSetItem;
}, /* bExport= */ true);
|
SQCLabs/openui5
|
src/sap.ui.ux3/src/sap/ui/ux3/DataSetItem.js
|
JavaScript
|
apache-2.0
| 2,265
|
// Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.SettableFuture;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionExecutionException;
import com.google.devtools.build.lib.actions.ActionLookupData;
import com.google.devtools.build.skyframe.SkyFunction;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* A state machine representing the synchronous or asynchronous execution of an action. This is
* shared between all instances of the same shared action and must therefore be thread-safe. Note
* that only one caller will receive events and output for this action.
*/
final class ActionExecutionState {
/** The owner of this object. Only the owner is allowed to continue work on the state machine. */
private final ActionLookupData actionLookupData;
// Both state and completionFuture may only be read or set when holding the lock for this. The
// state machine for these looks like this:
//
// !state.isDone,completionFuture=null -----> !state.isDone,completionFuture=<value>
// | |
// | | completionFuture.set()
// v v
// state.isDone,completionFuture=null
//
// No other states are legal. In particular, state.isDone,completionFuture=<value> is not a legal
// state.
@GuardedBy("this")
private ActionStepOrResult state;
/**
* A future to represent action completion of the primary action (randomly picked from the set of
* shared actions). This is initially {@code null}, and is only set to a non-null value if this
* turns out to be a shared action, and the primary action is not finished yet (i.e., {@code
* !state.isDone}. It is non-null while the primary action is being executed, at which point the
* thread completing the primary action completes the future, and also sets this field to null.
*
* <p>The reason for this roundabout approach is to avoid memory allocation if this is not a
* shared action, and to release the memory once the action is done.
*
* <p>Skyframe will attempt to cancel this future if the evaluation is interrupted, which violates
* the concurrency assumptions this class makes. Beware!
*/
@GuardedBy("this")
@Nullable
private SettableFuture<Void> completionFuture;
ActionExecutionState(ActionLookupData actionLookupData, ActionStepOrResult state) {
this.actionLookupData = Preconditions.checkNotNull(actionLookupData);
this.state = Preconditions.checkNotNull(state);
}
ActionExecutionValue getResultOrDependOnFuture(
SkyFunction.Environment env,
ActionLookupData actionLookupData,
Action action,
SharedActionCallback sharedActionCallback)
throws ActionExecutionException, InterruptedException {
if (this.actionLookupData.equals(actionLookupData)) {
// This continuation is owned by the Skyframe node executed by the current thread, so we use
// it to run the state machine.
return runStateMachine(env);
}
// This is a shared action, and the executed action is owned by another Skyframe node. If the
// other node is done, we simply return the done value. Otherwise we register a dependency on
// the completionFuture and return null.
ActionExecutionValue result;
synchronized (this) {
if (!state.isDone()) {
if (completionFuture == null) {
completionFuture = SettableFuture.create();
}
// We expect to only call this once per shared action; this method should only be called
// again after the future is completed.
sharedActionCallback.actionStarted();
env.dependOnFuture(completionFuture);
if (!env.valuesMissing()) {
Preconditions.checkState(
completionFuture.isCancelled(), "%s %s", this.actionLookupData, actionLookupData);
// The future is unexpectedly done. This must be because it was registered by another
// thread earlier and was canceled by Skyframe. We are about to be interrupted ourselves,
// but have to do something in the meantime. We can just register a dep with a new future,
// then complete it and return. If for some reason this argument is incorrect, we will be
// restarted immediately and hopefully have a more consistent result.
SettableFuture<Void> dummyFuture = SettableFuture.create();
env.dependOnFuture(dummyFuture);
dummyFuture.set(null);
return null;
}
// No other thread can modify completionFuture until we exit the synchronized block.
Preconditions.checkState(
!completionFuture.isDone(),
"Completion future modified? %s %s %s %s",
this.actionLookupData,
actionLookupData,
action,
completionFuture);
return null;
}
result = state.get();
}
sharedActionCallback.actionCompleted();
return result.transformForSharedAction(action.getOutputs());
}
private ActionExecutionValue runStateMachine(SkyFunction.Environment env)
throws ActionExecutionException, InterruptedException {
ActionStepOrResult original;
synchronized (this) {
original = state;
}
ActionStepOrResult current = original;
// We do the work _outside_ a synchronized block to avoid blocking threads working on shared
// actions that only want to register with the completionFuture.
try {
while (!current.isDone()) {
// Run the state machine for one step; isDone returned false, so this is safe.
current = current.run(env);
// This method guarantees that it either blocks until the action is completed and returns
// a non-null value, or it registers a dependency with Skyframe and returns null; it must
// not return null without registering a dependency, i.e., if {@code !env.valuesMissing()}.
if (env.valuesMissing()) {
return null;
}
}
} finally {
synchronized (this) {
Preconditions.checkState(state == original, "Another thread modified state");
state = current;
if (current.isDone() && completionFuture != null) {
completionFuture.set(null);
completionFuture = null;
}
}
}
// We're done, return the value to the caller (or throw an exception).
return current.get();
}
/** A callback to receive events for shared actions that are not executed. */
public interface SharedActionCallback {
/** Called if the action is shared and the primary action is already executing. */
void actionStarted();
/**
* Called when the primary action is done (on the next call to {@link
* #getResultOrDependOnFuture}.
*/
void actionCompleted();
}
/**
* A state machine where instances of this interface either represent an intermediate state that
* requires more work to be done (possibly waiting for a ListenableFuture to complete) or the
* final result of the executed action (either an ActionExecutionValue or an Exception).
*
* <p>This design allows us to store the current state of the in-progress action execution using a
* single object reference.
*
* <p>Do not implement this interface directly! In order to implement an action step, subclass
* {@link ActionStep}, and implement {@link #run}. In order to represent a result, use {@link
* #of}.
*/
interface ActionStepOrResult {
static ActionStepOrResult of(ActionExecutionValue value) {
return new Finished(value);
}
static ActionStepOrResult of(ActionExecutionException exception) {
return new Exceptional(exception);
}
static ActionStepOrResult of(InterruptedException exception) {
return new Exceptional(exception);
}
/**
* Returns true if and only if the underlying action is complete, i.e., it is legal to call
* {@link #get}. The return value of a single object must not change over time. Instead, call
* {@link ActionStepOrResult#of} to return a final result (or exception).
*/
boolean isDone();
/**
* Returns the next state of the state machine after performing some work towards the end goal
* of executing the action. This must only be called if {@link #isDone} returns false, and must
* only be called by one thread at a time for the same instance.
*/
ActionStepOrResult run(SkyFunction.Environment env) throws InterruptedException;
/**
* Returns the final value of the action or an exception to indicate that the action failed (or
* the process was interrupted). This must only be called if {@link #isDone} returns true.
*/
ActionExecutionValue get() throws ActionExecutionException, InterruptedException;
}
/**
* Abstract implementation of {@link ActionStepOrResult} that declares final implementations for
* {@link #isDone} (to return false) and {@link #get} (tho throw {@link IllegalStateException}).
*
* <p>The framework prevents concurrent calls to {@link #run}, so implementations can keep state
* without having to lock. Note that there may be multiple calls to {@link #run} from different
* threads, as long as they do not overlap in time.
*/
abstract static class ActionStep implements ActionStepOrResult {
@Override
public final boolean isDone() {
return false;
}
@Override
public final ActionExecutionValue get() {
throw new IllegalStateException();
}
}
/**
* Represents a finished action with a specific value. We specifically avoid anonymous inner
* classes to not accidentally retain a reference to the ActionRunner.
*/
private static final class Finished implements ActionStepOrResult {
private final ActionExecutionValue value;
Finished(ActionExecutionValue value) {
this.value = value;
}
@Override
public boolean isDone() {
return true;
}
@Override
public ActionStepOrResult run(SkyFunction.Environment env) {
throw new IllegalStateException();
}
@Override
public ActionExecutionValue get() {
return value;
}
}
/**
* Represents a finished action with an exception. We specifically avoid anonymous inner classes
* to not accidentally retain a reference to the ActionRunner.
*/
private static final class Exceptional implements ActionStepOrResult {
private final Exception e;
Exceptional(ActionExecutionException e) {
this.e = e;
}
Exceptional(InterruptedException e) {
this.e = e;
}
@Override
public boolean isDone() {
return true;
}
@Override
public ActionStepOrResult run(SkyFunction.Environment env) {
throw new IllegalStateException();
}
@Override
public ActionExecutionValue get() throws ActionExecutionException, InterruptedException {
if (e instanceof InterruptedException) {
throw (InterruptedException) e;
}
throw (ActionExecutionException) e;
}
}
}
|
dslomov/bazel
|
src/main/java/com/google/devtools/build/lib/skyframe/ActionExecutionState.java
|
Java
|
apache-2.0
| 11,878
|
object Sessions {
trait Session[This] {
type Dual
type HasDual[D] = Session[This]{type Dual=D}
def run(p: This, dp: Dual): Unit
}
implicit object StopSession extends Session[Stop] {
type Dual = Stop
def run(p: Stop, dp: Stop): Unit = {}
}
implicit def InDual[A, B](implicit sessionDIn: Session[B]) =
new Session[In[A, B]] {
type Dual = Out[A, sessionDIn.Dual]
def run(p: In[A, B], dp: Dual): Unit =
sessionDIn.run(p.func(dp.x), dp.y)
}
implicit def OutDual[A, B](implicit sessionDOut: Session[B]) =
new Session[Out[A, B]] {
type Dual = In[A, sessionDOut.Dual]
def run(p: Out[A, B], dp: Dual): Unit =
sessionDOut.run(p.y, dp.func(p.x))
}
sealed case class Stop()
sealed case class In[-A, +B](func: A => B)
sealed case class Out[+A, +B](x: A, y: B)
def addServer =
In{x: Int =>
In{y: Int => System.out.println("Thinking")
Out(x+y,
Stop())}}
def addClient =
Out(3,
Out(4, { System.out.println("Waiting")
In{z: Int => System.out.println(z)
Stop()}}))
def runSession[S, D: Session[S]#HasDual](p: S, dp: D) =
implicitly[Session[S]#HasDual[D]].run(p, dp)
// def runSession[S, D](p: S, dp: D)(implicit s: Session[S]#HasDual[D]) =
// s.run(p, dp)
//
// def runSession[S, D](p: S, dp: D)(implicit s: Session[S]{type Dual=D}) =
// s.run(p, dp)
// TODO: can we relax the ordering restrictions on dependencies so that we can use
// def runSession[S](p: S, dp: s.Dual)(implicit s: Session[S]) =
// s.run(p, dp)
// to emphasise similarity of type parameters and implicit arguments:
// def runSession[S][val s: Session[S]](p: S, dp: s.Dual) =
// s.run(p, dp)
def myRun = runSession(addServer, addClient)
}
|
lrytz/scala
|
test/files/pos/depmet_implicit_oopsla_session.scala
|
Scala
|
apache-2.0
| 1,764
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/hwpf/hwp/dram_training/mem_pll_setup/cen_mem_pll_setup.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2014 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
// $Id: cen_mem_pll_setup.C,v 1.26 2014/03/19 13:58:05 mfred Exp $
// $Source: /afs/awd/projects/eclipz/KnowledgeBase/.cvsroot/eclipz/chips/centaur/working/procedures/ipl/fapi/cen_mem_pll_setup.C,v $
//------------------------------------------------------------------------------
// *! (C) Copyright International Business Machines Corp. 2012
// *! All Rights Reserved -- Property of IBM
// *! *** ***
//------------------------------------------------------------------------------
// *! TITLE : cen_mem_pll_setup
// *! DESCRIPTION : see additional comments below
// *! OWNER NAME : Mark Fredrickson Email: mfred@us.ibm.com
// *! BACKUP NAME : Mark Bellows Email: bellows@us.ibm.com
// *! SCREEN : pervasive_screen
// #! ADDITIONAL COMMENTS :
//
// The purpose of this procedure is to make sure the Centaur MEM PLL locks.
//
//------------------------------------------------------------------------------
// Don't forget to create CVS comments when you check in your changes!
//------------------------------------------------------------------------------
#include <fapi.H>
#include <cen_scom_addresses.H>
#include <cen_mem_pll_setup.H>
// Constants
const uint64_t DELAY_100NS = 100; // General purpose 100 ns delay for HW mode (2000 sim cycles if simclk - 20ghz)
const uint64_t DELAY_2000SIMCYCLES = 2000; // General purpose 2000 sim cycle delay for sim mode (100 ns if simclk = 20Ghz)
const uint16_t POLL_COUNT_MAX = 50; // Number of times to poll for PLL lock before timing out.
// CFAM FSI STATUS register bit/field definitions
const uint8_t FSI_STATUS_MEM_PLL_LOCK_BIT = 25;
// TP LFIR bit/field definitions
const uint8_t TP_LFIR_ERRORS_FROM_NEST_PLL_LOCK_BIT = 19;
const uint8_t TP_LFIR_ERRORS_FROM_MEM_PLL_LOCK_BIT = 20;
extern "C" {
using namespace fapi;
fapi::ReturnCode cen_mem_pll_setup(const fapi::Target & i_target)
{
// Target is centaur
fapi::ReturnCode rc;
ecmdDataBufferBase cfam_data(32);
uint32_t rc_ecmd = 0;
ecmdDataBufferBase scom_data(64);
uint32_t poll_count = 0;
uint32_t done_polling = 0;
FAPI_INF("********* cen_mem_pll_setup start *********");
do
{
//---------------------------------------
// Poll for PLL lock bit
//---------------------------------------
// Check MEM PLL lock bit (25) in CFAM FSI status register to see if PLL is locked
// Check bit 25 only. Bit 25 is for the MEM PLL. (Bit 24 is the PLL lock for NEST PLL)
FAPI_DBG("Polling on FSI STATUS register bit 25 to see if MEM PLL has locked....\n");
done_polling = 0;
poll_count = 0;
do
{
rc = fapiDelay(DELAY_100NS, DELAY_2000SIMCYCLES); // wait 2000 simcycles (in sim mode) OR 100 nS (in hw mode)
if (rc)
{
FAPI_ERR("Error executing fapiDelay of 100ns or 2000simcycles.");
break;
}
rc = fapiGetCfamRegister( i_target, CFAM_FSI_STATUS_0x00001007, cfam_data);
if (rc)
{
FAPI_ERR("Error reading FSI STATUS Regiter 0x00001007.");
break;
}
if ( cfam_data.isBitSet(FSI_STATUS_MEM_PLL_LOCK_BIT) ) done_polling = 1;
poll_count++;
} while ((done_polling == 0) && (poll_count < POLL_COUNT_MAX)); // Poll until PLL is locked or max count is reached.
if (rc) break; // Go to end of proc if error found inside polling loop.
if ( (poll_count == POLL_COUNT_MAX) && ( done_polling != 1 ) )
{
FAPI_ERR("Centaur MEM PLL failed to lock! Polling timed out after %d loops.",POLL_COUNT_MAX);
ecmdDataBufferBase & CFAM_FSI_STATUS = cfam_data;
const fapi::Target & MEMBUF_CHIP_IN_ERROR = i_target;
FAPI_SET_HWP_ERROR(rc, RC_CEN_MEM_PLL_SETUP_PLL_LOCK_TIMEOUT);
break;
}
else
{
FAPI_INF("Centaur MEM PLL is now locked.");
}
FAPI_DBG("Clearing the FIR PLL lock error bits and unmasking TP LFIR PLL lock error bits ...");
rc_ecmd |= scom_data.flushTo1();
rc_ecmd |= scom_data.clearBit(TP_LFIR_ERRORS_FROM_NEST_PLL_LOCK_BIT);
rc_ecmd |= scom_data.clearBit(TP_LFIR_ERRORS_FROM_MEM_PLL_LOCK_BIT);
if (rc_ecmd)
{
FAPI_ERR("Error 0x%x setting up ecmd data buffer to clear TP LFIR PLL Lock bits.", rc_ecmd);
rc.setEcmdError(rc_ecmd);
break;
}
rc = fapiPutScom(i_target, TP_PERV_LFIR_AND_0x0104000B, scom_data);
if (!rc.ok())
{
FAPI_ERR("Error writing Pervasive LFIR AND Register.");
break;
}
rc = fapiPutScom(i_target, TP_PERV_LFIR_MASK_AND_0x0104000E, scom_data);
if (!rc.ok())
{
FAPI_ERR("Error writing Pervasive LFIR Mask AND Register.");
break;
}
} while(0);
FAPI_INF("********* cen_mem_pll_setup complete *********");
return rc;
}
} //end extern C
/*
*************** Do not edit this area ***************
This section is automatically updated by CVS when you check in this file.
Be sure to create CVS comments when you commit so that they can be included here.
$Log: cen_mem_pll_setup.C,v $
Revision 1.26 2014/03/19 13:58:05 mfred
Update to clear and unmask the PLL lock FIR bits after the PLL locks. SW249390.
Revision 1.25 2013/11/15 16:30:00 mfred
Changes made by Mike Jones for gerrit review, mostly for improved error handling.
Revision 1.24 2013/03/04 17:56:26 mfred
Add some header comments for BACKUP and SCREEN.
Revision 1.23 2012/08/13 17:16:16 mfred
Adding new hwp cen_mem_pll_initf.
Revision 1.22 2012/07/12 21:16:53 mfred
Remove a lot of simulation-only code, use putspys to set the PLL control ring.
Revision 1.21 2012/07/10 14:30:59 mfred
Commented out some lines.
Revision 1.20 2012/07/05 20:06:43 mfred
But MEM PLL into bypass before scanning in new settings.
Revision 1.19 2012/07/02 16:33:31 mfred
Added MEM PLL settings for simulation.
Revision 1.18 2012/06/27 20:34:39 mfred
Updates to use real MEM PLL instead of var osc.
Revision 1.17 2012/06/25 23:37:54 jeshua
Attempt to fix up the mem pll variable oscillators
Revision 1.16 2012/06/14 19:25:13 mfred
Fixing spelling in comment.
Revision 1.15 2012/06/14 19:07:51 mfred
Added more code for setting real PLL control chain. Values are still not final.
Revision 1.14 2012/06/13 20:59:58 mfred
Some updates for using real PLL.cen_mem_pll_setup.C
Revision 1.13 2012/06/07 13:52:23 jmcgill
use independent data buffers for cfam/scom accesses
Revision 1.12 2012/06/06 20:05:03 jmcgill
change FSI GP3/GP4/status register accesses from SCOM->CFAM
Revision 1.11 2012/05/31 18:29:17 mfred
Updates for RC checking and error messages, etc.
Revision 1.10 2012/04/26 20:52:57 mfred
add additional comment
Revision 1.9 2012/04/26 14:35:29 mfred
Some fixes.
Revision 1.8 2012/04/06 15:58:20 mfred
Plugged in real error msgs, removed some unneeded actions.
Revision 1.5 2012/04/03 21:35:57 mfred
Many updates for both sim and lab actions.
Revision 1.4 2012/04/02 15:30:43 mfred
removing prcdUtils.H from this dir.
Revision 1.3 2012/03/30 19:11:06 mfred
removing some obsolete files
Revision 1.1 2012/03/23 20:36:03 mfred
Checking in a shell prototype for cen_mem_pll_setup.
*/
|
shenki/hostboot
|
src/usr/hwpf/hwp/dram_training/mem_pll_setup/cen_mem_pll_setup.C
|
C++
|
apache-2.0
| 9,312
|
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for creating HTTP health checks."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA)
class Create(base_classes.BaseAsyncCreator):
"""Create a HTTP health check to monitor load balanced instances."""
@staticmethod
def Args(parser):
health_checks_utils.AddHttpRelatedCreationArgs(parser)
health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'HTTP')
@property
def service(self):
return self.compute.healthChecks
@property
def method(self):
return 'Insert'
@property
def resource_type(self):
return 'healthChecks'
def CreateRequests(self, args):
"""Returns the request necessary for adding the health check."""
health_check_ref = self.CreateGlobalReference(
args.name, resource_type='healthChecks')
proxy_header = self.messages.HTTPHealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header)
request = self.messages.ComputeHealthChecksInsertRequest(
healthCheck=self.messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=self.messages.HealthCheck.TypeValueValuesEnum.HTTP,
httpHealthCheck=self.messages.HTTPHealthCheck(
host=args.host,
port=args.port,
portName=args.port_name,
requestPath=args.request_path,
proxyHeader=proxy_header),
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold,
),
project=self.project)
return [request]
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(Create):
"""Create a HTTP health check to monitor load balanced instances."""
@staticmethod
def Args(parser):
Create.Args(parser)
health_checks_utils.AddHttpRelatedResponseArg(parser)
def CreateRequests(self, args):
"""Returns the request necessary for adding the health check."""
requests = super(CreateAlpha, self).CreateRequests(args)
requests[0].healthCheck.httpHealthCheck.response = args.response
return requests
Create.detailed_help = {
'brief': ('Create a HTTP health check to monitor load balanced instances'),
'DESCRIPTION': """\
*{command}* is used to create a HTTP health check. HTTP health checks
monitor instances in a load balancer controlled by a target pool. All
arguments to the command are optional except for the name of the health
check. For more information on load balancing, see
[](https://cloud.google.com/compute/docs/load-balancing-and-autoscaling/)
""",
}
|
KaranToor/MA450
|
google-cloud-sdk/lib/surface/compute/health_checks/create/http.py
|
Python
|
apache-2.0
| 3,471
|
# Copyright 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.volume import base
from tempest import exceptions
from tempest import test
class VolumeQuotasNegativeTestJSON(base.BaseVolumeV1AdminTest):
_interface = "json"
force_tenant_isolation = True
@classmethod
@test.safe_setup
def setUpClass(cls):
super(VolumeQuotasNegativeTestJSON, cls).setUpClass()
demo_user = cls.isolated_creds.get_primary_creds()
cls.demo_tenant_id = demo_user.tenant_id
cls.shared_quota_set = {'gigabytes': 3, 'volumes': 1, 'snapshots': 1}
# NOTE(gfidente): no need to restore original quota set
# after the tests as they only work with tenant isolation.
resp, quota_set = cls.quotas_client.update_quota_set(
cls.demo_tenant_id,
**cls.shared_quota_set)
# NOTE(gfidente): no need to delete in tearDown as
# they are created using utility wrapper methods.
cls.volume = cls.create_volume()
cls.snapshot = cls.create_snapshot(cls.volume['id'])
@test.attr(type='negative')
def test_quota_volumes(self):
self.assertRaises(exceptions.OverLimit,
self.volumes_client.create_volume,
size=1)
@test.attr(type='negative')
def test_quota_volume_snapshots(self):
self.assertRaises(exceptions.OverLimit,
self.snapshots_client.create_snapshot,
self.volume['id'])
@test.attr(type='negative')
def test_quota_volume_gigabytes(self):
# NOTE(gfidente): quota set needs to be changed for this test
# or we may be limited by the volumes or snaps quota number, not by
# actual gigs usage; next line ensures shared set is restored.
self.addCleanup(self.quotas_client.update_quota_set,
self.demo_tenant_id,
**self.shared_quota_set)
new_quota_set = {'gigabytes': 2, 'volumes': 2, 'snapshots': 1}
resp, quota_set = self.quotas_client.update_quota_set(
self.demo_tenant_id,
**new_quota_set)
self.assertRaises(exceptions.OverLimit,
self.volumes_client.create_volume,
size=1)
new_quota_set = {'gigabytes': 2, 'volumes': 1, 'snapshots': 2}
resp, quota_set = self.quotas_client.update_quota_set(
self.demo_tenant_id,
**self.shared_quota_set)
self.assertRaises(exceptions.OverLimit,
self.snapshots_client.create_snapshot,
self.volume['id'])
class VolumeQuotasNegativeTestXML(VolumeQuotasNegativeTestJSON):
_interface = "xml"
|
Mirantis/tempest
|
tempest/api/volume/admin/test_volume_quotas_negative.py
|
Python
|
apache-2.0
| 3,331
|
/*
* Copyright 1999-2015 dangdang.com.
* <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
*
* 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.
* </p>
*/
package com.dangdang.ddframe.job.cloud.scheduler.statistics;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 统计元数据.
*
* @author liguangyun
*/
public final class TaskResultMetaData {
private final AtomicInteger successCount;
private final AtomicInteger failedCount;
/**
* 构造函数.
*/
public TaskResultMetaData() {
successCount = new AtomicInteger(0);
failedCount = new AtomicInteger(0);
}
/**
* 增加并获取成功数.
*
* @return 成功数
*/
public int incrementAndGetSuccessCount() {
return successCount.incrementAndGet();
}
/**
* 增加并获取失败数.
*
* @return 失败数
*/
public int incrementAndGetFailedCount() {
return failedCount.incrementAndGet();
}
/**
* 获取成功数.
*
* @return 成功数
*/
public int getSuccessCount() {
return successCount.get();
}
/**
* 获取失败数.
*
* @return 失败数
*/
public int getFailedCount() {
return failedCount.get();
}
/**
* 重置成功数、失败数.
*/
public void reset() {
successCount.set(0);
failedCount.set(0);
}
}
|
Esjob-Cloud-DevOps/elastic-job
|
elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/statistics/TaskResultMetaData.java
|
Java
|
apache-2.0
| 1,919
|
/*
* 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.druid.query.filter;
import org.apache.druid.segment.filter.FilterTestUtils;
import org.apache.druid.testing.InitializedNullHandlingTest;
import org.junit.Assert;
import org.junit.Test;
public class OrDimFilterTest extends InitializedNullHandlingTest
{
@Test
public void testToFilterWithDuplicateFilters()
{
DimFilter dimFilter = DimFilterTestUtils.or(
DimFilterTestUtils.and(
DimFilterTestUtils.selector("col1", "1"),
DimFilterTestUtils.selector("col2", "2")
),
DimFilterTestUtils.and(
// duplicate but different order
DimFilterTestUtils.selector("col2", "2"),
DimFilterTestUtils.selector("col1", "1")
),
DimFilterTestUtils.selector("col3", "3")
);
Filter expected = FilterTestUtils.or(
FilterTestUtils.and(
FilterTestUtils.selector("col1", "1"),
FilterTestUtils.selector("col2", "2")
),
FilterTestUtils.selector("col3", "3")
);
Assert.assertEquals(expected, dimFilter.toFilter());
}
@Test
public void testOptimieShortCircuitWithTrueFilter()
{
DimFilter filter = DimFilterTestUtils.or(
DimFilterTestUtils.selector("col1", "1"),
TrueDimFilter.instance()
);
Assert.assertTrue(filter.optimize() instanceof TrueDimFilter);
}
@Test
public void testOptimizeOringFalseFilters()
{
DimFilter filter = DimFilterTestUtils.or(FalseDimFilter.instance(), FalseDimFilter.instance());
Assert.assertSame(FalseDimFilter.instance(), filter.optimize());
}
@Test
public void testOptimizeOrOfSingleFilterUnwrapOr()
{
DimFilter expected = DimFilterTestUtils.selector("col1", "1");
DimFilter filter = DimFilterTestUtils.or(expected);
Assert.assertEquals(expected, filter.optimize());
}
@Test
public void testOptimizeOrOfMultipleFiltersReturningAsItIs()
{
DimFilter filter = DimFilterTestUtils.or(
DimFilterTestUtils.selector("col1", "1"),
DimFilterTestUtils.selector("col1", "2")
);
Assert.assertEquals(filter, filter.optimize());
}
}
|
pjain1/druid
|
processing/src/test/java/org/apache/druid/query/filter/OrDimFilterTest.java
|
Java
|
apache-2.0
| 2,929
|
/**
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.pricer;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
/**
* Test.
*/
@Test
public class PricingExceptionTest {
public void test_constructor_message() {
PricingException test = new PricingException("Hello");
assertEquals(test.getMessage(), "Hello");
}
public void test_constructor_messageCause() {
IllegalArgumentException cause = new IllegalArgumentException("Under");
PricingException test = new PricingException("Hello", cause);
assertEquals(test.getMessage(), "Hello");
assertEquals(test.getCause(), cause);
}
}
|
jmptrader/Strata
|
modules/pricer/src/test/java/com/opengamma/strata/pricer/PricingExceptionTest.java
|
Java
|
apache-2.0
| 758
|
/*
* 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.easyant.core.descriptor;
import org.apache.easyant.core.ivy.InheritableScope;
import org.apache.ivy.core.module.id.ModuleRevisionId;
/**
* This class is a simple POJO used to store informations on configureProject.
*
*/
public class ConfigureProjectDescriptor implements AdvancedInheritableItem {
private String defaultTarget;
private String basedir;
private InheritableScope inheritScope = InheritableScope.BOTH;
private final ModuleRevisionId sourceModule;
private boolean inheritable = true;
/**
* Default constructor
*/
public ConfigureProjectDescriptor() {
sourceModule = null;
}
/**
* Constructor specifying the source module which was defining the configureproject
*
* @param sourceModule
* a source module
*/
public ConfigureProjectDescriptor(ModuleRevisionId sourceModule) {
this.sourceModule = sourceModule;
}
public String getDefaultTarget() {
return defaultTarget;
}
public void setDefaultTarget(String defaultTarget) {
this.defaultTarget = defaultTarget;
}
public String getBasedir() {
return basedir;
}
public void setBasedir(String basedir) {
this.basedir = basedir;
}
public InheritableScope getInheritScope() {
return inheritScope;
}
public void setInheritScope(InheritableScope inheritScope) {
this.inheritScope = inheritScope;
}
public boolean isInheritable() {
return inheritable;
}
public void setInheritable(boolean inheritable) {
this.inheritable = inheritable;
}
public ModuleRevisionId getSourceModule() {
return sourceModule;
}
}
|
apache/ant-easyant-core
|
src/main/java/org/apache/easyant/core/descriptor/ConfigureProjectDescriptor.java
|
Java
|
apache-2.0
| 2,562
|
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.worker.block;
import alluxio.conf.PropertyKey;
import alluxio.conf.ServerConfiguration;
import alluxio.exception.status.CancelledException;
import alluxio.exception.status.DeadlineExceededException;
import alluxio.exception.status.InternalException;
import alluxio.grpc.BlockMasterWorkerServiceGrpc;
import alluxio.grpc.ConfigProperty;
import alluxio.grpc.LocationBlockIdListEntry;
import alluxio.grpc.RegisterWorkerPOptions;
import alluxio.grpc.RegisterWorkerPRequest;
import alluxio.grpc.RegisterWorkerPResponse;
import alluxio.grpc.StorageList;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
/**
* This class oversees the logic of registering with the master using a stream of
* {@link RegisterWorkerPRequest}.
* The stream lifecycle management lives internal to this instance.
*/
public class RegisterStreamer implements Iterator<RegisterWorkerPRequest> {
private static final Logger LOG = LoggerFactory.getLogger(RegisterStreamer.class);
private static final int MAX_BATCHES_IN_FLIGHT = 2;
private final long mWorkerId;
private final List<String> mStorageTierAliases;
private final Map<String, Long> mTotalBytesOnTiers;
private final Map<String, Long> mUsedBytesOnTiers;
private final RegisterWorkerPOptions mOptions;
private final Map<String, StorageList> mLostStorageMap;
private int mBatchNumber;
private BlockMapIterator mBlockMapIterator;
// For internal flow control and state mgmt
private final CountDownLatch mAckLatch;
private final CountDownLatch mFinishLatch;
private Semaphore mBucket = new Semaphore(MAX_BATCHES_IN_FLIGHT);
private AtomicReference<Throwable> mError = new AtomicReference<>();
private final int mResponseTimeoutMs;
private final int mDeadlineMs;
private final int mCompleteTimeoutMs;
private final BlockMasterWorkerServiceGrpc.BlockMasterWorkerServiceStub mAsyncClient;
private final StreamObserver<RegisterWorkerPResponse> mMasterResponseObserver;
// This cannot be final because it is created on registerWithMaster()
private StreamObserver<RegisterWorkerPRequest> mWorkerRequestObserver;
/**
* Constructor.
*
* @param asyncClient the grpc client
* @param workerId the worker ID
* @param storageTierAliases storage/tier setup from the configuration
* @param totalBytesOnTiers the capacity of each tier
* @param usedBytesOnTiers the current usage of each tier
* @param currentBlocksOnLocation the blocks in each tier/dir
* @param lostStorage the lost storage paths
* @param configList the configuration properties
*/
@VisibleForTesting
public RegisterStreamer(
final BlockMasterWorkerServiceGrpc.BlockMasterWorkerServiceStub asyncClient,
final long workerId, final List<String> storageTierAliases,
final Map<String, Long> totalBytesOnTiers, final Map<String, Long> usedBytesOnTiers,
final Map<BlockStoreLocation, List<Long>> currentBlocksOnLocation,
final Map<String, List<String>> lostStorage,
final List<ConfigProperty> configList) {
this(asyncClient, workerId, storageTierAliases, totalBytesOnTiers, usedBytesOnTiers,
lostStorage, configList, new BlockMapIterator(currentBlocksOnLocation));
}
/**
* Constructor.
*
* @param asyncClient the grpc client
* @param workerId the worker ID
* @param storageTierAliases storage/tier setup from the configuration
* @param totalBytesOnTiers the capacity of each tier
* @param usedBytesOnTiers the current usage of each tier
* @param lostStorage the lost storage paths
* @param configList the configuration properties
* @param blockListIterator an iterator used to iterate the blocks
*/
public RegisterStreamer(
final BlockMasterWorkerServiceGrpc.BlockMasterWorkerServiceStub asyncClient,
final long workerId, final List<String> storageTierAliases,
final Map<String, Long> totalBytesOnTiers, final Map<String, Long> usedBytesOnTiers,
final Map<String, List<String>> lostStorage,
final List<ConfigProperty> configList,
BlockMapIterator blockListIterator) {
mAsyncClient = asyncClient;
mWorkerId = workerId;
mStorageTierAliases = storageTierAliases;
mTotalBytesOnTiers = totalBytesOnTiers;
mUsedBytesOnTiers = usedBytesOnTiers;
mOptions = RegisterWorkerPOptions.newBuilder().addAllConfigs(configList).build();
mLostStorageMap = lostStorage.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> StorageList.newBuilder().addAllStorage(e.getValue()).build()));
mBatchNumber = 0;
mBlockMapIterator = blockListIterator;
mAckLatch = new CountDownLatch(mBlockMapIterator.getBatchCount());
mFinishLatch = new CountDownLatch(1);
mResponseTimeoutMs =
(int) ServerConfiguration.getMs(PropertyKey.WORKER_REGISTER_STREAM_RESPONSE_TIMEOUT);
mDeadlineMs =
(int) ServerConfiguration.getMs(PropertyKey.WORKER_REGISTER_STREAM_DEADLINE);
mCompleteTimeoutMs =
(int) ServerConfiguration.getMs(PropertyKey.WORKER_REGISTER_STREAM_COMPLETE_TIMEOUT);
mMasterResponseObserver = new StreamObserver<RegisterWorkerPResponse>() {
@Override
public void onNext(RegisterWorkerPResponse res) {
LOG.debug("Worker {} - Received ACK {}", mWorkerId, res);
mBucket.release();
mAckLatch.countDown();
}
@Override
public void onError(Throwable t) {
LOG.error("Worker {} - received error from server, marking the stream as closed: ",
mWorkerId, t);
mError.set(t);
mFinishLatch.countDown();
}
@Override
public void onCompleted() {
LOG.info("{} - Complete message received from the server. Closing stream", mWorkerId);
mFinishLatch.countDown();
}
};
}
/**
* Manages the logic of registering with the master in a stream.
*
*/
public void registerWithMaster() throws CancelledException, InternalException,
DeadlineExceededException, InterruptedException {
// onNext() - send the request batches
// onError() - when an error occurs on the worker side, propagate the error status to
// the master side and then close on the worker side, the master will
// handle necessary cleanup on its side
// onCompleted() - complete on the client side when all the batches are sent
// and all ACKs are received
mWorkerRequestObserver = mAsyncClient
.withDeadlineAfter(mDeadlineMs, TimeUnit.MILLISECONDS)
.registerWorkerStream(mMasterResponseObserver);
try {
registerInternal();
} catch (DeadlineExceededException | InterruptedException | CancelledException e) {
LOG.error("Worker {} - Error during the register stream, aborting now.", mWorkerId, e);
// These exceptions are internal to the worker
// Propagate to the master side so it can clean up properly
mWorkerRequestObserver.onError(e);
throw e;
}
// The only exception that is not propagated to the master is InternalException.
// We assume that is from the master so there is no need to send it back again.
}
private void registerInternal() throws InterruptedException, DeadlineExceededException,
CancelledException, InternalException {
int iter = 0;
while (hasNext()) {
// Send a request when the master ACKs the previous one
LOG.debug("Worker {} - Acquiring one token to send the next batch", mWorkerId);
Instant start = Instant.now();
if (!mBucket.tryAcquire(mResponseTimeoutMs, TimeUnit.MILLISECONDS)) {
throw new DeadlineExceededException(
String.format("No response from master for more than %dms during the stream!",
mResponseTimeoutMs));
}
Instant end = Instant.now();
LOG.debug("Worker {} - master ACK received in {}ms, sending the next batch {}",
mWorkerId, Duration.between(start, end).toMillis(), iter);
// Send the request
RegisterWorkerPRequest request = next();
mWorkerRequestObserver.onNext(request);
if (mFinishLatch.getCount() == 0) {
abort();
}
iter++;
}
// If the master side is closed before the client side, there is a problem
if (mFinishLatch.getCount() == 0) {
abort();
}
// Wait for all batches have been ACK-ed by the master before completing the client side
if (!mAckLatch.await(mResponseTimeoutMs * MAX_BATCHES_IN_FLIGHT, TimeUnit.MILLISECONDS)) {
long receivedCount = mBlockMapIterator.getBatchCount() - mAckLatch.getCount();
throw new DeadlineExceededException(
String.format("All batches have been sent to the master but only received %d ACKs!",
receivedCount));
}
LOG.info("Worker {} - All requests have been sent. Completing the client side.", mWorkerId);
mWorkerRequestObserver.onCompleted();
LOG.info("Worker {} - Waiting on the master side to complete", mWorkerId);
if (!mFinishLatch.await(mCompleteTimeoutMs, TimeUnit.MILLISECONDS)) {
throw new DeadlineExceededException(
String.format("All batches have been received by the master but the master failed"
+ " to complete the registration in %dms!", mCompleteTimeoutMs));
}
// If the master failed in completing the request, there will also be an error
if (mError.get() != null) {
Throwable t = mError.get();
LOG.error("Worker {} - Received an error from the master on completion", mWorkerId, t);
throw new InternalException(t);
}
LOG.info("Worker {} - Finished registration with a stream", mWorkerId);
}
private void abort() throws InternalException, CancelledException {
if (mError.get() != null) {
Throwable t = mError.get();
LOG.error("Worker {} - Received an error from the master", mWorkerId, t);
throw new InternalException(t);
} else {
String msg = String.format("Worker %s - The server side has been closed before "
+ "all the batches are sent from the worker!", mWorkerId);
LOG.error(msg);
throw new CancelledException(msg);
}
}
@Override
public boolean hasNext() {
// There will be at least 1 request even if the blocks are empty
return mBlockMapIterator.hasNext() || mBatchNumber == 0;
}
@Override
public RegisterWorkerPRequest next() {
RegisterWorkerPRequest request;
List<LocationBlockIdListEntry> blockBatch;
if (mBatchNumber == 0) {
if (mBlockMapIterator.hasNext()) {
blockBatch = mBlockMapIterator.next();
} else {
blockBatch = Collections.emptyList();
}
// If it is the 1st batch, include metadata
request = RegisterWorkerPRequest.newBuilder()
.setWorkerId(mWorkerId)
.addAllStorageTiers(mStorageTierAliases)
.putAllTotalBytesOnTiers(mTotalBytesOnTiers)
.putAllUsedBytesOnTiers(mUsedBytesOnTiers)
.putAllLostStorage(mLostStorageMap)
.setOptions(mOptions)
.addAllCurrentBlocks(blockBatch)
.build();
} else {
blockBatch = mBlockMapIterator.next();
// Following batches only include the block list
request = RegisterWorkerPRequest.newBuilder()
.setWorkerId(mWorkerId)
.addAllCurrentBlocks(blockBatch)
.build();
}
mBatchNumber++;
return request;
}
}
|
wwjiang007/alluxio
|
core/server/worker/src/main/java/alluxio/worker/block/RegisterStreamer.java
|
Java
|
apache-2.0
| 12,358
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/schemas/Schemas_EXPORTS.h>
#include <aws/schemas/SchemasRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Schemas
{
namespace Model
{
/**
* <p>Updates the registry.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/schemas-2019-12-02/UpdateRegistryRequest">AWS
* API Reference</a></p>
*/
class AWS_SCHEMAS_API UpdateRegistryRequest : public SchemasRequest
{
public:
UpdateRegistryRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "UpdateRegistry"; }
Aws::String SerializePayload() const override;
/**
* <p>The description of the registry to update.</p>
*/
inline const Aws::String& GetDescription() const{ return m_description; }
/**
* <p>The description of the registry to update.</p>
*/
inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }
/**
* <p>The description of the registry to update.</p>
*/
inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }
/**
* <p>The description of the registry to update.</p>
*/
inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }
/**
* <p>The description of the registry to update.</p>
*/
inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }
/**
* <p>The description of the registry to update.</p>
*/
inline UpdateRegistryRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}
/**
* <p>The description of the registry to update.</p>
*/
inline UpdateRegistryRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}
/**
* <p>The description of the registry to update.</p>
*/
inline UpdateRegistryRequest& WithDescription(const char* value) { SetDescription(value); return *this;}
/**
* <p>The name of the registry.</p>
*/
inline const Aws::String& GetRegistryName() const{ return m_registryName; }
/**
* <p>The name of the registry.</p>
*/
inline bool RegistryNameHasBeenSet() const { return m_registryNameHasBeenSet; }
/**
* <p>The name of the registry.</p>
*/
inline void SetRegistryName(const Aws::String& value) { m_registryNameHasBeenSet = true; m_registryName = value; }
/**
* <p>The name of the registry.</p>
*/
inline void SetRegistryName(Aws::String&& value) { m_registryNameHasBeenSet = true; m_registryName = std::move(value); }
/**
* <p>The name of the registry.</p>
*/
inline void SetRegistryName(const char* value) { m_registryNameHasBeenSet = true; m_registryName.assign(value); }
/**
* <p>The name of the registry.</p>
*/
inline UpdateRegistryRequest& WithRegistryName(const Aws::String& value) { SetRegistryName(value); return *this;}
/**
* <p>The name of the registry.</p>
*/
inline UpdateRegistryRequest& WithRegistryName(Aws::String&& value) { SetRegistryName(std::move(value)); return *this;}
/**
* <p>The name of the registry.</p>
*/
inline UpdateRegistryRequest& WithRegistryName(const char* value) { SetRegistryName(value); return *this;}
private:
Aws::String m_description;
bool m_descriptionHasBeenSet;
Aws::String m_registryName;
bool m_registryNameHasBeenSet;
};
} // namespace Model
} // namespace Schemas
} // namespace Aws
|
awslabs/aws-sdk-cpp
|
aws-cpp-sdk-schemas/include/aws/schemas/model/UpdateRegistryRequest.h
|
C
|
apache-2.0
| 4,151
|
.PHONY:all clean
all:ReferenceData.class
ReferenceData.class:ReferenceData.java bloomberg.jks client.p12
javac ReferenceData.java
client.p12:client.crt bloomberg.crt
openssl pkcs12 -export -password pass:secure -in client.crt -CAfile bloomberg.crt -inkey client.key -out client.p12
bloomberg.jks:bloomberg.crt
$(RM) bloomberg.jks
keytool -import -keystore bloomberg.jks -storepass secure2 -trustcacerts -file bloomberg.crt -noprompt
clean:
$(RM) ReferenceData.class client.p12 bloomberg.jks
|
flojdek/blpapi-http
|
examples/java/Makefile
|
Makefile
|
apache-2.0
| 501
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
"""
Utilities with minimum-depends for use in setup.py
"""
import datetime
import os
import re
import subprocess
import sys
from setuptools.command import sdist
def parse_mailmap(mailmap='.mailmap'):
mapping = {}
if os.path.exists(mailmap):
fp = open(mailmap, 'r')
for l in fp:
l = l.strip()
if not l.startswith('#') and ' ' in l:
canonical_email, alias = l.split(' ')
mapping[alias] = canonical_email
return mapping
def canonicalize_emails(changelog, mapping):
"""Takes in a string and an email alias mapping and replaces all
instances of the aliases in the string with their real email.
"""
for alias, email in mapping.iteritems():
changelog = changelog.replace(alias, email)
return changelog
# Get requirements from the first file that exists
def get_reqs_from_files(requirements_files):
reqs_in = []
for requirements_file in requirements_files:
if os.path.exists(requirements_file):
return open(requirements_file, 'r').read().split('\n')
return []
def parse_requirements(requirements_files=['requirements.txt',
'tools/pip-requires']):
requirements = []
for line in get_reqs_from_files(requirements_files):
# For the requirements list, we need to inject only the portion
# after egg= so that distutils knows the package it's looking for
# such as:
# -e git://github.com/openstack/nova/master#egg=nova
if re.match(r'\s*-e\s+', line):
requirements.append(re.sub(r'\s*-e\s+.*#egg=(.*)$', r'\1',
line))
# such as:
# http://github.com/openstack/nova/zipball/master#egg=nova
elif re.match(r'\s*https?:', line):
requirements.append(re.sub(r'\s*https?:.*#egg=(.*)$', r'\1',
line))
# -f lines are for index locations, and don't get used here
elif re.match(r'\s*-f\s+', line):
pass
# argparse is part of the standard library starting with 2.7
# adding it to the requirements list screws distro installs
elif line == 'argparse' and sys.version_info >= (2, 7):
pass
else:
requirements.append(line)
return requirements
def parse_dependency_links(requirements_files=['requirements.txt',
'tools/pip-requires']):
dependency_links = []
# dependency_links inject alternate locations to find packages listed
# in requirements
for line in get_reqs_from_files(requirements_files):
# skip comments and blank lines
if re.match(r'(\s*#)|(\s*$)', line):
continue
# lines with -e or -f need the whole line, minus the flag
if re.match(r'\s*-[ef]\s+', line):
dependency_links.append(re.sub(r'\s*-[ef]\s+', '', line))
# lines that are only urls can go in unmolested
elif re.match(r'\s*https?:', line):
dependency_links.append(line)
return dependency_links
def write_requirements():
venv = os.environ.get('VIRTUAL_ENV', None)
if venv is not None:
with open("requirements.txt", "w") as req_file:
output = subprocess.Popen(["pip", "-E", venv, "freeze", "-l"],
stdout=subprocess.PIPE)
requirements = output.communicate()[0].strip()
req_file.write(requirements)
def _run_shell_command(cmd):
output = subprocess.Popen(["/bin/sh", "-c", cmd],
stdout=subprocess.PIPE)
out = output.communicate()
if len(out) == 0:
return None
if len(out[0].strip()) == 0:
return None
return out[0].strip()
def _get_git_next_version_suffix(branch_name):
datestamp = datetime.datetime.now().strftime('%Y%m%d')
if branch_name == 'milestone-proposed':
revno_prefix = "r"
else:
revno_prefix = ""
_run_shell_command("git fetch origin +refs/meta/*:refs/remotes/meta/*")
milestone_cmd = "git show meta/openstack/release:%s" % branch_name
milestonever = _run_shell_command(milestone_cmd)
if not milestonever:
milestonever = ""
post_version = _get_git_post_version()
revno = post_version.split(".")[-1]
return "%s~%s.%s%s" % (milestonever, datestamp, revno_prefix, revno)
def _get_git_current_tag():
return _run_shell_command("git tag --contains HEAD")
def _get_git_tag_info():
return _run_shell_command("git describe --tags")
def _get_git_post_version():
current_tag = _get_git_current_tag()
if current_tag is not None:
return current_tag
else:
tag_info = _get_git_tag_info()
if tag_info is None:
base_version = "0.0"
cmd = "git --no-pager log --oneline"
out = _run_shell_command(cmd)
revno = len(out.split("\n"))
else:
tag_infos = tag_info.split("-")
base_version = "-".join(tag_infos[:-2])
revno = tag_infos[-2]
return "%s.%s" % (base_version, revno)
def write_git_changelog():
"""Write a changelog based on the git changelog."""
if os.path.isdir('.git'):
git_log_cmd = 'git log --stat'
changelog = _run_shell_command(git_log_cmd)
mailmap = parse_mailmap()
with open("ChangeLog", "w") as changelog_file:
changelog_file.write(canonicalize_emails(changelog, mailmap))
def generate_authors():
"""Create AUTHORS file using git commits."""
jenkins_email = 'jenkins@review.openstack.org'
old_authors = 'AUTHORS.in'
new_authors = 'AUTHORS'
if os.path.isdir('.git'):
# don't include jenkins email address in AUTHORS file
git_log_cmd = ("git log --format='%aN <%aE>' | sort -u | "
"grep -v " + jenkins_email)
changelog = _run_shell_command(git_log_cmd)
mailmap = parse_mailmap()
with open(new_authors, 'w') as new_authors_fh:
new_authors_fh.write(canonicalize_emails(changelog, mailmap))
if os.path.exists(old_authors):
with open(old_authors, "r") as old_authors_fh:
new_authors_fh.write('\n' + old_authors_fh.read())
_rst_template = """%(heading)s
%(underline)s
.. automodule:: %(module)s
:members:
:undoc-members:
:show-inheritance:
"""
def read_versioninfo(project):
"""Read the versioninfo file. If it doesn't exist, we're in a github
zipball, and there's really know way to know what version we really
are, but that should be ok, because the utility of that should be
just about nil if this code path is in use in the first place."""
versioninfo_path = os.path.join(project, 'versioninfo')
if os.path.exists(versioninfo_path):
with open(versioninfo_path, 'r') as vinfo:
version = vinfo.read().strip()
else:
version = "0.0.0"
return version
def write_versioninfo(project, version):
"""Write a simple file containing the version of the package."""
open(os.path.join(project, 'versioninfo'), 'w').write("%s\n" % version)
def get_cmdclass():
"""Return dict of commands to run from setup.py."""
cmdclass = dict()
def _find_modules(arg, dirname, files):
for filename in files:
if filename.endswith('.py') and filename != '__init__.py':
arg["%s.%s" % (dirname.replace('/', '.'),
filename[:-3])] = True
class LocalSDist(sdist.sdist):
"""Builds the ChangeLog and Authors files from VC first."""
def run(self):
write_git_changelog()
generate_authors()
# sdist.sdist is an old style class, can't use super()
sdist.sdist.run(self)
cmdclass['sdist'] = LocalSDist
# If Sphinx is installed on the box running setup.py,
# enable setup.py to build the documentation, otherwise,
# just ignore it
try:
from sphinx.setup_command import BuildDoc
class LocalBuildDoc(BuildDoc):
def generate_autoindex(self):
print "**Autodocumenting from %s" % os.path.abspath(os.curdir)
modules = {}
option_dict = self.distribution.get_option_dict('build_sphinx')
source_dir = os.path.join(option_dict['source_dir'][1], 'api')
if not os.path.exists(source_dir):
os.makedirs(source_dir)
for pkg in self.distribution.packages:
if '.' not in pkg:
os.path.walk(pkg, _find_modules, modules)
module_list = modules.keys()
module_list.sort()
autoindex_filename = os.path.join(source_dir, 'autoindex.rst')
with open(autoindex_filename, 'w') as autoindex:
autoindex.write(""".. toctree::
:maxdepth: 1
""")
for module in module_list:
output_filename = os.path.join(source_dir,
"%s.rst" % module)
heading = "The :mod:`%s` Module" % module
underline = "=" * len(heading)
values = dict(module=module, heading=heading,
underline=underline)
print "Generating %s" % output_filename
with open(output_filename, 'w') as output_file:
output_file.write(_rst_template % values)
autoindex.write(" %s.rst\n" % module)
def run(self):
if not os.getenv('SPHINX_DEBUG'):
self.generate_autoindex()
for builder in ['html', 'man']:
self.builder = builder
self.finalize_options()
self.project = self.distribution.get_name()
self.version = self.distribution.get_version()
self.release = self.distribution.get_version()
BuildDoc.run(self)
cmdclass['build_sphinx'] = LocalBuildDoc
except ImportError:
pass
return cmdclass
def get_git_branchname():
for branch in _run_shell_command("git branch --color=never").split("\n"):
if branch.startswith('*'):
_branch_name = branch.split()[1].strip()
if _branch_name == "(no":
_branch_name = "no-branch"
return _branch_name
def get_pre_version(projectname, base_version):
"""Return a version which is based"""
if os.path.isdir('.git'):
current_tag = _get_git_current_tag()
if current_tag is not None:
version = current_tag
else:
branch_name = os.getenv('BRANCHNAME',
os.getenv('GERRIT_REFNAME',
get_git_branchname()))
version_suffix = _get_git_next_version_suffix(branch_name)
version = "%s~%s" % (base_version, version_suffix)
write_versioninfo(projectname, version)
return version.split('~')[0]
else:
version = read_versioninfo(projectname)
return version.split('~')[0]
def get_post_version(projectname):
"""Return a version which is equal to the tag that's on the current
revision if there is one, or tag plus number of additional revisions
if the current revision has no tag."""
if os.path.isdir('.git'):
version = _get_git_post_version()
write_versioninfo(projectname, version)
return version
return read_versioninfo(projectname)
|
chmouel/python-swiftclient
|
swiftclient/openstack/common/setup.py
|
Python
|
apache-2.0
| 12,438
|
package gov.hhs.onc.dcdt.crypto.keys.impl;
import gov.hhs.onc.dcdt.crypto.CryptographyConfig.GenerateConstraintGroup;
import gov.hhs.onc.dcdt.crypto.CryptographyException;
import gov.hhs.onc.dcdt.crypto.impl.AbstractCryptographyGenerator;
import gov.hhs.onc.dcdt.crypto.keys.KeyAlgorithm;
import gov.hhs.onc.dcdt.crypto.keys.KeyConfig;
import gov.hhs.onc.dcdt.crypto.keys.KeyException;
import gov.hhs.onc.dcdt.crypto.keys.KeyGenerator;
import gov.hhs.onc.dcdt.crypto.keys.KeyInfo;
import gov.hhs.onc.dcdt.crypto.utils.KeyUtils;
import gov.hhs.onc.dcdt.utils.ToolClassUtils;
import gov.hhs.onc.dcdt.utils.ToolStringUtils;
import gov.hhs.onc.dcdt.utils.ToolValidationUtils;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
@Component("keyGenImpl")
public class KeyGeneratorImpl extends AbstractCryptographyGenerator<KeyConfig, KeyInfo> implements KeyGenerator {
private final static Logger LOGGER = LoggerFactory.getLogger(KeyGeneratorImpl.class);
@Resource(name = "secureRandomSha1")
private SecureRandom secureRandom;
@Override
public KeyInfo generateKeys(KeyConfig keyConfig) throws CryptographyException {
BindingResult keyConfigBindingResult = this.validateConfig(keyConfig, GenerateConstraintGroup.class);
if (keyConfigBindingResult.hasErrors()) {
throw new KeyException(String.format("Invalid key configuration (class=%s): %s", ToolClassUtils.getName(keyConfig),
ToolStringUtils.joinDelimit(ToolValidationUtils.mapErrorMessages(this.msgSourceValidation, keyConfigBindingResult).entrySet(), ", ")));
}
KeyAlgorithm keyAlg = keyConfig.getKeyAlgorithm();
// noinspection ConstantConditions
int keySize = keyConfig.getKeySize();
KeyPairGenerator keyPairGen = KeyUtils.getKeyPairGenerator(keyAlg);
keyPairGen.initialize(keySize, this.secureRandom);
KeyInfo keyInfo = new KeyInfoImpl(keyPairGen.generateKeyPair());
// noinspection ConstantConditions
LOGGER.info(String.format("Generated key pair (alg=%s, size=%d).", keyAlg.name(), keySize));
return keyInfo;
}
}
|
mkotelba/dcdt
|
dcdt-core/src/main/java/gov/hhs/onc/dcdt/crypto/keys/impl/KeyGeneratorImpl.java
|
Java
|
apache-2.0
| 2,338
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.