code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/**
* Utility classes for converting between granularities of SI (power-of-ten) and IEC (power-of-two)
* byte units and bit units.
* <p>
* <h3>Example Usage</h3>
* What's the difference in hard drive space between perception and actual?
* <pre><code>
* long perception = BinaryByteUnit.TEBIBYTES.toBytes(2);
* long usable = DecimalByteUnit.TERABYTES.toBytes(2);
* long lost = BinaryByteUnit.BYTES.toGibibytes(perception - usable);
* System.out.println(lost + " GiB lost on a 2TB drive.");
* </code></pre>
* <p>
* Method parameter for specifying a resource size.
* <pre><code>
* public void installDiskCache(long count, ByteUnit unit) {
* long size = unit.toBytes(count);
* // TODO Install disk cache of 'size' bytes.
* }
* </code></pre>
*/
package com.jakewharton.byteunits;
| JakeWharton/byteunits | src/main/java/com/jakewharton/byteunits/package-info.java | Java | apache-2.0 | 799 |
/*
* 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.pig.experimental.logical.relational;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.pig.data.DataType;
import org.apache.pig.impl.util.Pair;
/**
* Schema, from a logical perspective.
*/
public class LogicalSchema {
public static class LogicalFieldSchema {
public String alias;
public byte type;
public long uid;
public LogicalSchema schema;
public LogicalFieldSchema(String alias, LogicalSchema schema, byte type) {
this(alias, schema, type, -1);
}
public LogicalFieldSchema(String alias, LogicalSchema schema, byte type, long uid) {
this.alias = alias;
this.type = type;
this.schema = schema;
this.uid = uid;
}
/**
* Equality is defined as having the same type and either the same schema
* or both null schema. Alias and uid are not checked.
*/
public boolean isEqual(Object other) {
if (other instanceof LogicalFieldSchema) {
LogicalFieldSchema ofs = (LogicalFieldSchema)other;
if (type != ofs.type) return false;
if (schema == null && ofs.schema == null) return true;
if (schema == null) return false;
else return schema.isEqual(ofs.schema);
} else {
return false;
}
}
public String toString() {
if( type == DataType.BAG ) {
if( schema == null ) {
return ( alias + "#" + uid + ":bag{}#" );
}
return ( alias + "#" + uid + ":bag{" + schema.toString() + "}" );
} else if( type == DataType.TUPLE ) {
if( schema == null ) {
return ( alias + "#" + uid + ":tuple{}" );
}
return ( alias + "#" + uid + ":tuple(" + schema.toString() + ")" );
}
return ( alias + "#" + uid + ":" + DataType.findTypeName(type) );
}
}
private List<LogicalFieldSchema> fields;
private Map<String, Pair<Integer, Boolean>> aliases;
public LogicalSchema() {
fields = new ArrayList<LogicalFieldSchema>();
aliases = new HashMap<String, Pair<Integer, Boolean>>();
}
/**
* Add a field to this schema.
* @param field to be added to the schema
*/
public void addField(LogicalFieldSchema field) {
fields.add(field);
if (field.alias != null && !field.alias.equals("")) {
// put the full name of this field into aliases map
// boolean in the pair indicates if this alias is full name
aliases.put(field.alias, new Pair<Integer, Boolean>(fields.size()-1, true));
int index = 0;
// check and put short names into alias map if there is no conflict
while(index != -1) {
index = field.alias.indexOf("::", index);
if (index != -1) {
String a = field.alias.substring(index+2);
if (aliases.containsKey(a)) {
// remove conflict if the conflict is not full name
// we can never remove full name
if (!aliases.get(a).second) {
aliases.remove(a);
}
}else{
// put alias into map and indicate it is a short name
aliases.put(a, new Pair<Integer, Boolean>(fields.size()-1, false));
}
index = index +2;
}
}
}
}
/**
* Fetch a field by alias
* @param alias
* @return field associated with alias, or null if no such field
*/
public LogicalFieldSchema getField(String alias) {
Pair<Integer, Boolean> p = aliases.get(alias);
if (p == null) {
return null;
}
return fields.get(p.first);
}
/**
* Fetch a field by field number
* @param fieldNum field number to fetch
* @return field
*/
public LogicalFieldSchema getField(int fieldNum) {
return fields.get(fieldNum);
}
/**
* Get all fields
* @return list of all fields
*/
public List<LogicalFieldSchema> getFields() {
return fields;
}
/**
* Get the size of the schema.
* @return size
*/
public int size() {
return fields.size();
}
/**
* Two schemas are equal if they are of equal size and their fields
* schemas considered in order are equal.
*/
public boolean isEqual(Object other) {
if (other != null && other instanceof LogicalSchema) {
LogicalSchema os = (LogicalSchema)other;
if (size() != os.size()) return false;
for (int i = 0; i < size(); i++) {
if (!getField(i).isEqual(os.getField(i))) return false;
}
return true;
} else {
return false;
}
}
/**
* Look for the index of the field that contains the specified uid
* @param uid the uid to look for
* @return the index of the field, -1 if not found
*/
public int findField(long uid) {
for(int i=0; i< size(); i++) {
LogicalFieldSchema f = getField(i);
// if this field has the same uid, then return this field
if (f.uid == uid) {
return i;
}
// if this field has a schema, check its schema
if (f.schema != null) {
if (f.schema.findField(uid) != -1) {
return i;
}
}
}
return -1;
}
/**
* Merge two schemas.
* @param s1
* @param s2
* @return a merged schema, or null if the merge fails
*/
public static LogicalSchema merge(LogicalSchema s1, LogicalSchema s2) {
// TODO
return null;
}
public String toString() {
StringBuilder str = new StringBuilder();
for( LogicalFieldSchema field : fields ) {
str.append( field.toString() + "," );
}
if( fields.size() != 0 ) {
str.deleteCharAt( str.length() -1 );
}
return str.toString();
}
}
| hirohanin/pig7hadoop21 | src/org/apache/pig/experimental/logical/relational/LogicalSchema.java | Java | apache-2.0 | 7,432 |
# Polystictus glaucoeffusus Lloyd, 1925 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Mycol. Writ. 7: 1334 (1925)
#### Original name
Polystictus glaucoeffusus Lloyd, 1925
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Polyporaceae/Trametes/Funalia argentea/ Syn. Polystictus glaucoeffusus/README.md | Markdown | apache-2.0 | 250 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Experian.Qas.Prowebintegration {
public partial class RapidAddress {
/// <summary>
/// ButtonNew control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlButton ButtonNew;
/// <summary>
/// ButtonBack control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlButton ButtonBack;
/// <summary>
/// RadioTypedown control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RadioButton RadioTypedown;
/// <summary>
/// RadioSingleline control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RadioButton RadioSingleline;
/// <summary>
/// RadioKeyfinder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RadioButton RadioKeyfinder;
/// <summary>
/// country control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList country;
/// <summary>
/// LabelPrompt control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label LabelPrompt;
/// <summary>
/// searchText control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox searchText;
/// <summary>
/// TableAddress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Table TableAddress;
/// <summary>
/// TableMultiDPCtrl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Table TableMultiDPCtrl;
/// <summary>
/// PlaceholderInfo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder PlaceholderInfo;
/// <summary>
/// LiteralRoute control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal LiteralRoute;
/// <summary>
/// LiteralError control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal LiteralError;
/// <summary>
/// statusData control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableCell statusData;
/// <summary>
/// matchCount control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl matchCount;
/// <summary>
/// infoStatus control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl infoStatus;
}
}
| experiandataquality/proweb | src/Proweb.Webform/RapidAddress.aspx.designer.cs | C# | apache-2.0 | 5,721 |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package contexttip
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"cloud.google.com/go/pubsub"
)
func TestPublishMessage(t *testing.T) {
// TODO: Use testutil to get the project.
projectID = os.Getenv("GOLANG_SAMPLES_PROJECT_ID")
if projectID == "" {
t.Skip("Missing GOLANG_SAMPLES_PROJECT_ID.")
}
ctx := context.Background()
var err error
client, err = pubsub.NewClient(ctx, projectID)
if err != nil {
t.Fatalf("pubsub.NewClient: %v", err)
}
topicName := os.Getenv("FUNCTIONS_TOPIC_NAME")
if topicName == "" {
topicName = "functions-test-topic"
}
topic := client.Topic(topicName)
exists, err := topic.Exists(ctx)
if err != nil {
t.Fatalf("topic(%s).Exists: %v", topicName, err)
}
if !exists {
_, err = client.CreateTopic(context.Background(), topicName)
if err != nil {
t.Fatalf("topic(%s).CreateTopic: %v", topicName, err)
}
}
payload := strings.NewReader(fmt.Sprintf(`{"topic":%q, "message": %q}`, topicName, "my_message"))
rr := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/", payload)
PublishMessage(rr, req)
if rr.Code != http.StatusOK {
t.Errorf("PublishMessage: got response code %v, want %v", rr.Code, http.StatusOK)
}
want := "published"
if got := rr.Body.String(); !strings.Contains(got, want) {
t.Errorf("PublishMessage: got %q, want to contain %q", got, want)
}
}
| GoogleCloudPlatform/golang-samples | functions/tips/contexttip/context_tip_test.go | GO | apache-2.0 | 1,979 |
# BitmapFontImporter
Import bitmap font in Unity generated by Glyph designer or ShoeBox
# Tutorial
http://www.benoitfreslon.com/unity-generate-and-import-a-bitmap-font-with-a-free-tool
| zoeesilcock/BitmapFontImporter | README.md | Markdown | apache-2.0 | 186 |
package grequests
import "testing"
func TestErrorOpenFile(t *testing.T) {
fd, err := FileUploadFromDisk("file", "I am Not A File")
if err == nil {
t.Error("We are not getting an error back from our non existent file: ")
}
if fd != nil {
t.Error("We actually got back a pointer: ", fd)
}
}
| liuzhe0223/grequests | file_upload_test.go | GO | apache-2.0 | 301 |
package com.github.nikolaymakhonin.android_app_example.di.factories;
import android.content.Context;
import android.support.annotation.NonNull;
import com.github.nikolaymakhonin.android_app_example.di.components.AppComponent;
import com.github.nikolaymakhonin.android_app_example.di.components.DaggerAppComponent;
import com.github.nikolaymakhonin.android_app_example.di.components.DaggerServiceComponent;
import com.github.nikolaymakhonin.android_app_example.di.components.ServiceComponent;
import com.github.nikolaymakhonin.common_di.modules.service.ServiceModuleBase;
public final class ComponentsFactory {
public static AppComponent buildAppComponent(@NonNull Context appContext) {
ServiceComponent serviceComponent = buildServiceComponent(appContext);
AppComponent appComponent = DaggerAppComponent.builder()
.serviceComponent(serviceComponent)
.build();
return appComponent;
}
public static ServiceComponent buildServiceComponent(@NonNull Context appContext) {
ServiceComponent serviceComponent = DaggerServiceComponent.builder()
.serviceModuleBase(new ServiceModuleBase(appContext))
.build();
return serviceComponent;
}
}
| NikolayMakhonin/AndroidAppExample | AndroidAppExample/AppExample/src/main/java/com/github/nikolaymakhonin/android_app_example/di/factories/ComponentsFactory.java | Java | apache-2.0 | 1,243 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.objectdiagram.command;
import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.command.CommandExecutionResult;
import net.sourceforge.plantuml.command.SingleLineCommand2;
import net.sourceforge.plantuml.command.regex.IRegex;
import net.sourceforge.plantuml.command.regex.RegexConcat;
import net.sourceforge.plantuml.command.regex.RegexLeaf;
import net.sourceforge.plantuml.command.regex.RegexResult;
import net.sourceforge.plantuml.cucadiagram.IEntity;
import net.sourceforge.plantuml.objectdiagram.AbstractClassOrObjectDiagram;
import net.sourceforge.plantuml.skin.VisibilityModifier;
import net.sourceforge.plantuml.ugraphic.color.NoSuchColorException;
public class CommandAddData extends SingleLineCommand2<AbstractClassOrObjectDiagram> {
public CommandAddData() {
super(getRegexConcat());
}
static IRegex getRegexConcat() {
return RegexConcat.build(CommandAddData.class.getName(), RegexLeaf.start(), //
new RegexLeaf("NAME", "([%pLN_.]+)"), //
RegexLeaf.spaceZeroOrMore(), //
new RegexLeaf(":"), //
RegexLeaf.spaceZeroOrMore(), //
new RegexLeaf("DATA", "(.*)"), RegexLeaf.end()); //
}
@Override
protected CommandExecutionResult executeArg(AbstractClassOrObjectDiagram diagram, LineLocation location,
RegexResult arg) throws NoSuchColorException {
final String name = arg.get("NAME", 0);
final IEntity entity = diagram.getOrCreateLeaf(diagram.buildLeafIdent(name),
diagram.buildCode(name), null, null);
final String field = arg.get("DATA", 0);
if (field.length() > 0 && VisibilityModifier.isVisibilityCharacter(field)) {
diagram.setVisibilityModifierPresent(true);
}
entity.getBodier().addFieldOrMethod(field);
return CommandExecutionResult.ok();
}
}
| talsma-ict/umldoclet | src/plantuml-asl/src/net/sourceforge/plantuml/objectdiagram/command/CommandAddData.java | Java | apache-2.0 | 2,860 |
/**
* 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.xml.security.test.stax.c14n;
import org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_Excl;
import org.junit.Before;
import org.apache.xml.security.stax.ext.stax.XMLSecEvent;
import org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_ExclOmitCommentsTransformer;
import org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_ExclWithCommentsTransformer;
import org.apache.xml.security.test.stax.utils.XMLSecEventAllocator;
import org.apache.xml.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author $Author: coheigea $
* @version $Revision: 1721336 $ $Date: 2015-12-22 10:45:18 +0000 (Tue, 22 Dec 2015) $
*/
public class Canonicalizer20010315ExclusiveTest extends org.junit.Assert {
private XMLInputFactory xmlInputFactory;
@Before
public void setUp() throws Exception {
this.xmlInputFactory = XMLInputFactory.newInstance();
this.xmlInputFactory.setEventAllocator(new XMLSecEventAllocator());
}
@org.junit.Test
public void test221excl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
XMLEventReader xmlSecEventReader = xmlInputFactory.createXMLEventReader(
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/example2_2_1.xml")
);
XMLSecEvent xmlSecEvent = null;
while (xmlSecEventReader.hasNext()) {
xmlSecEvent = (XMLSecEvent) xmlSecEventReader.nextEvent();
if (xmlSecEvent.isStartElement() && xmlSecEvent.asStartElement().getName().equals(new QName("http://example.net", "elem2"))) {
break;
}
}
while (xmlSecEventReader.hasNext()) {
c.transform(xmlSecEvent);
if (xmlSecEvent.isEndElement() && xmlSecEvent.asEndElement().getName().equals(new QName("http://example.net", "elem2"))) {
break;
}
xmlSecEvent = (XMLSecEvent) xmlSecEventReader.nextEvent();
}
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_2_c14nized_exclusive.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void test222excl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
canonicalize(c,
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/example2_2_2.xml"),
new QName("http://example.net", "elem2")
);
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_2_c14nized_exclusive.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void test24excl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
canonicalize(c,
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/example2_4.xml"),
new QName("http://example.net", "elem2")
);
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_4_c14nized.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void testComplexDocexcl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
canonicalize(c,
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/plain-soap-1.1.xml"),
new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body", "env")
);
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/plain-soap-c14nized.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void testNodeSet() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("env");
inclusiveNamespaces.add("ns0");
inclusiveNamespaces.add("xsi");
inclusiveNamespaces.add("wsu");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
/**
* Method test24Aexcl - a testcase for SANTUARIO-263
* "Canonicalizer can't handle dynamical created DOM correctly"
* https://issues.apache.org/jira/browse/SANTUARIO-263
*/
@org.junit.Test
public void test24Aexcl() throws Exception {
Document doc = XMLUtils.createDocumentBuilder(false).newDocument();
Element local = doc.createElementNS("foo:bar", "dsig:local");
Element test = doc.createElementNS("http://example.net", "etsi:test");
Element elem2 = doc.createElementNS("http://example.net", "etsi:elem2");
Element stuff = doc.createElementNS("foo:bar", "dsig:stuff");
elem2.appendChild(stuff);
test.appendChild(elem2);
local.appendChild(test);
doc.appendChild(local);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
t.transform(new DOMSource(doc), streamResult);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
Canonicalizer20010315_ExclWithCommentsTransformer c =
new Canonicalizer20010315_ExclWithCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(stringWriter.toString()), new QName("http://example.net", "elem2"));
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_4_c14nized.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
assertTrue(equals);
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList1() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
{
//exactly the same outcome is expected if #default is not set:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList2() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns=\"http://example.com\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML1 =
"<env:Body"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
final String c14nXML2 =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML1);
}
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML2);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList3() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns=\"\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
{
//exactly the same outcome is expected if #default is not set:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList4() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
{
//exactly the same outcome is expected if #default is not set:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testPropagateDefaultNs1() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs2() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs3() throws Exception {
final String XML =
"<Envelope"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs4() throws Exception {
final String XML =
"<Envelope"
+ " xmlns=\"\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs5() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body xmlns=\"\" wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<ns0:Ping xmlns=\"\" xmlns:ns0=\"http://xmlsoap.org/Ping\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://xmlsoap.org/Ping", "Ping"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
private void canonicalize(
Canonicalizer20010315_Excl c, InputStream inputStream, QName elementName)
throws XMLStreamException {
canonicalize(c, xmlInputFactory.createXMLEventReader(inputStream), elementName);
}
private void canonicalize(
Canonicalizer20010315_Excl c, Reader reader, QName elementName)
throws XMLStreamException {
canonicalize(c, xmlInputFactory.createXMLEventReader(reader), elementName);
}
private void canonicalize(
Canonicalizer20010315_Excl c, XMLEventReader xmlEventReader, QName elementName)
throws XMLStreamException {
XMLSecEvent xmlSecEvent = null;
while (xmlEventReader.hasNext()) {
xmlSecEvent = (XMLSecEvent) xmlEventReader.nextEvent();
if (xmlSecEvent.isStartElement() && xmlSecEvent.asStartElement().getName().equals(elementName)) {
break;
}
}
while (xmlEventReader.hasNext()) {
c.transform(xmlSecEvent);
if (xmlSecEvent.isEndElement() && xmlSecEvent.asEndElement().getName().equals(elementName)) {
break;
}
xmlSecEvent = (XMLSecEvent) xmlEventReader.nextEvent();
}
}
public static byte[] getBytesFromResource(URL resource) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream inputStream = resource.openStream();
try {
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
baos.write(buf, 0, len);
}
return baos.toByteArray();
} finally {
inputStream.close();
}
}
} | Legostaev/xmlsec-gost | src/test/java/org/apache/xml/security/test/stax/c14n/Canonicalizer20010315ExclusiveTest.java | Java | apache-2.0 | 40,733 |
"""Let's Encrypt constants."""
import logging
from acme import challenges
SETUPTOOLS_PLUGINS_ENTRY_POINT = "letsencrypt.plugins"
"""Setuptools entry point group name for plugins."""
CLI_DEFAULTS = dict(
config_files=["/etc/letsencrypt/cli.ini"],
verbose_count=-(logging.WARNING / 10),
server="https://www.letsencrypt-demo.org/acme/new-reg",
rsa_key_size=2048,
rollback_checkpoints=0,
config_dir="/etc/letsencrypt",
work_dir="/var/lib/letsencrypt",
backup_dir="/var/lib/letsencrypt/backups",
key_dir="/etc/letsencrypt/keys",
certs_dir="/etc/letsencrypt/certs",
cert_path="/etc/letsencrypt/certs/cert-letsencrypt.pem",
chain_path="/etc/letsencrypt/certs/chain-letsencrypt.pem",
renewer_config_file="/etc/letsencrypt/renewer.conf",
no_verify_ssl=False,
dvsni_port=challenges.DVSNI.PORT,
)
"""Defaults for CLI flags and `.IConfig` attributes."""
RENEWER_DEFAULTS = dict(
renewer_config_file="/etc/letsencrypt/renewer.conf",
renewal_configs_dir="/etc/letsencrypt/configs",
archive_dir="/etc/letsencrypt/archive",
live_dir="/etc/letsencrypt/live",
renewer_enabled="yes",
renew_before_expiry="30 days",
deploy_before_expiry="20 days",
)
"""Defaults for renewer script."""
EXCLUSIVE_CHALLENGES = frozenset([frozenset([
challenges.DVSNI, challenges.SimpleHTTP])])
"""Mutually exclusive challenges."""
ENHANCEMENTS = ["redirect", "http-header", "ocsp-stapling", "spdy"]
"""List of possible :class:`letsencrypt.interfaces.IInstaller`
enhancements.
List of expected options parameters:
- redirect: None
- http-header: TODO
- ocsp-stapling: TODO
- spdy: TODO
"""
CONFIG_DIRS_MODE = 0o755
"""Directory mode for ``.IConfig.config_dir`` et al."""
TEMP_CHECKPOINT_DIR = "temp_checkpoint"
"""Temporary checkpoint directory (relative to IConfig.work_dir)."""
IN_PROGRESS_DIR = "IN_PROGRESS"
"""Directory used before a permanent checkpoint is finalized (relative to
IConfig.work_dir)."""
CERT_KEY_BACKUP_DIR = "keys-certs"
"""Directory where all certificates and keys are stored (relative to
IConfig.work_dir. Used for easy revocation."""
ACCOUNTS_DIR = "accounts"
"""Directory where all accounts are saved."""
ACCOUNT_KEYS_DIR = "keys"
"""Directory where account keys are saved. Relative to ACCOUNTS_DIR."""
REC_TOKEN_DIR = "recovery_tokens"
"""Directory where all recovery tokens are saved (relative to
IConfig.work_dir)."""
| digideskio/lets-encrypt-preview | letsencrypt/constants.py | Python | apache-2.0 | 2,420 |
/*
* Copyright 2015 OpenCB
*
* 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.opencb.biodata.formats.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractFormatReader<T> {
protected Path path;
protected Logger logger;
protected AbstractFormatReader() {
path = null;
logger = LoggerFactory.getLogger(AbstractFormatReader.class);
// logger.setLevel(Logger.DEBUG_LEVEL);
}
protected AbstractFormatReader(Path f) throws IOException {
Files.exists(f);
this.path = f;
logger = LoggerFactory.getLogger(AbstractFormatReader.class);
// logger.setLevel(Logger.DEBUG_LEVEL);
}
public abstract int size() throws IOException, FileFormatException;
public abstract T read() throws FileFormatException;
public abstract T read(String regexFilter) throws FileFormatException;
public abstract List<T> read(int size) throws FileFormatException;
public abstract List<T> readAll() throws FileFormatException, IOException;
public abstract List<T> readAll(String pattern) throws FileFormatException;
public abstract void close() throws IOException;
}
| kalyanreddyemani/biodata | biodata-formats/src/main/java/org/opencb/biodata/formats/io/AbstractFormatReader.java | Java | apache-2.0 | 1,817 |
<?php
if ( ! function_exists('env') ) {
/**
* 获取一个环境变量的值,支持布尔值,null,empty
*
* @param string $key
* @param mixed $default
* @return mixed
*/
function env($key, $default = null) {
$value = getenv($key);
if ($value === false) return value($default);
return $value;
}
}
if ( ! function_exists('dump') ) {
/**
* 浏览器友好的变量输出
* @param mixed $var 变量
* @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
* @param string $label 标签 默认为空
* @param boolean $strict 是否严谨 默认为true
* @return void|string
*/
function dump($var, $echo=true, $label=null, $strict=true) {
$label = ($label === null) ? '' : rtrim($label) . ' ';
if (!$strict) {
if (ini_get('html_errors')) {
$output = print_r($var, true);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
} else {
$output = $label . print_r($var, true);
}
} else {
ob_start();
var_dump($var);
$output = ob_get_clean();
if (!extension_loaded('xdebug')) {
$output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
}
}
if ($echo) {
echo($output);
return null;
}else
return $output;
}
} | huanguosoft/framework | src/Foundation/helpers.php | PHP | apache-2.0 | 1,615 |
/*
* 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 jp.gihyo.spark.ch05
import java.text.SimpleDateFormat
case class Station(id: Int, name: String, lat: Double, lon: Double,
dockcount: Int, landmark: String, installation: java.sql.Date)
object Station {
def parse(line: String): Station = {
val dateFormat = new SimpleDateFormat("MM/dd/yyy")
val elms = line.split(",")
val id = elms(0).toInt
val name = elms(1)
val lat = elms(2).toDouble
val lon = elms(3).toDouble
val dockcount = elms(4).toInt
val landmark = elms(5)
val parsedInstallation = dateFormat.parse(elms(6))
val installation = new java.sql.Date(parsedInstallation.getTime)
Station(id, name, lat, lon, dockcount, landmark, installation)
}
}
| yu-iskw/gihyo-spark-book-example | src/main/scala/jp/gihyo/spark/ch05/Station.scala | Scala | apache-2.0 | 1,517 |
package org.ovirt.engine.ui.uicommonweb.models.configure.roles_ui;
import java.util.ArrayList;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.ui.uicommonweb.models.ApplicationModeHelper;
import org.ovirt.engine.ui.uicommonweb.models.common.SelectionTreeNodeModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
@SuppressWarnings("unused")
public class RoleTreeView
{
public static ArrayList<SelectionTreeNodeModel> GetRoleTreeView(boolean isReadOnly, boolean isAdmin)
{
RoleNode tree = initTreeView();
ArrayList<ActionGroup> userActionGroups = null;
if (isAdmin == false)
{
userActionGroups = GetUserActionGroups();
}
ArrayList<SelectionTreeNodeModel> roleTreeView = new ArrayList<SelectionTreeNodeModel>();
SelectionTreeNodeModel firstNode = null, secondNode = null, thirdNode = null;
for (RoleNode first : tree.getLeafRoles())
{
firstNode = new SelectionTreeNodeModel();
firstNode.setTitle(first.getName());
firstNode.setDescription(first.getName());
firstNode.setIsChangable(!isReadOnly);
for (RoleNode second : first.getLeafRoles())
{
secondNode = new SelectionTreeNodeModel();
secondNode.setTitle(second.getName());
secondNode.setDescription(second.getName());
secondNode.setIsChangable(!isReadOnly);
secondNode.setTooltip(second.getTooltip());
for (RoleNode third : second.getLeafRoles())
{
thirdNode = new SelectionTreeNodeModel();
thirdNode.setTitle(third.getName());
thirdNode.setDescription(third.getDesc());
thirdNode.setIsSelectedNotificationPrevent(true);
// thirdNode.IsSelected =
// attachedActions.Contains((VdcActionType) Enum.Parse(typeof (VdcActionType), name)); //TODO:
// suppose to be action group
thirdNode.setIsChangable(!isReadOnly);
thirdNode.setIsSelectedNullable(false);
thirdNode.setTooltip(third.getTooltip());
if (!isAdmin)
{
if (userActionGroups.contains(ActionGroup.valueOf(thirdNode.getTitle())))
{
secondNode.getChildren().add(thirdNode);
}
}
else
{
secondNode.getChildren().add(thirdNode);
}
}
if (secondNode.getChildren().size() > 0)
{
firstNode.getChildren().add(secondNode);
}
}
if (firstNode.getChildren().size() > 0)
{
roleTreeView.add(firstNode);
}
}
return roleTreeView;
}
private static ArrayList<ActionGroup> GetUserActionGroups() {
ArrayList<ActionGroup> array = new ArrayList<ActionGroup>();
array.add(ActionGroup.CREATE_VM);
array.add(ActionGroup.DELETE_VM);
array.add(ActionGroup.EDIT_VM_PROPERTIES);
array.add(ActionGroup.VM_BASIC_OPERATIONS);
array.add(ActionGroup.CHANGE_VM_CD);
array.add(ActionGroup.MIGRATE_VM);
array.add(ActionGroup.CONNECT_TO_VM);
array.add(ActionGroup.CONFIGURE_VM_NETWORK);
array.add(ActionGroup.CONFIGURE_VM_STORAGE);
array.add(ActionGroup.MOVE_VM);
array.add(ActionGroup.MANIPULATE_VM_SNAPSHOTS);
array.add(ActionGroup.CREATE_TEMPLATE);
array.add(ActionGroup.EDIT_TEMPLATE_PROPERTIES);
array.add(ActionGroup.DELETE_TEMPLATE);
array.add(ActionGroup.COPY_TEMPLATE);
array.add(ActionGroup.CONFIGURE_TEMPLATE_NETWORK);
array.add(ActionGroup.CREATE_VM_POOL);
array.add(ActionGroup.EDIT_VM_POOL_CONFIGURATION);
array.add(ActionGroup.DELETE_VM_POOL);
array.add(ActionGroup.VM_POOL_BASIC_OPERATIONS);
array.add(ActionGroup.MANIPULATE_PERMISSIONS);
array.add(ActionGroup.CREATE_DISK);
array.add(ActionGroup.ATTACH_DISK);
array.add(ActionGroup.DELETE_DISK);
array.add(ActionGroup.CONFIGURE_DISK_STORAGE);
array.add(ActionGroup.EDIT_DISK_PROPERTIES);
array.add(ActionGroup.LOGIN);
array.add(ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES);
array.add(ActionGroup.PORT_MIRRORING);
return array;
}
private static RoleNode initTreeView()
{
RoleNode tree =
new RoleNode(ConstantsManager.getInstance().getConstants().rootRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance().getConstants().systemRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureSystemRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.MANIPULATE_USERS,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemoveUsersFromTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_PERMISSIONS,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemovePermissionsForUsersOnObjectsInTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_ROLES,
ConstantsManager.getInstance()
.getConstants()
.allowToDefineConfigureRolesInTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.LOGIN,
ConstantsManager.getInstance()
.getConstants()
.allowToLoginToTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_ENGINE,
ConstantsManager.getInstance()
.getConstants()
.allowToGetOrSetSystemConfigurationRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().dataCenterRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureDataCenterRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_STORAGE_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateDataCenterRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_STORAGE_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveDataCenterRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_STORAGE_POOL_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToModifyDataCenterPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_STORAGE_POOL_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureLogicalNetworkPerDataCenterRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().storageDomainRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureStorageDomainRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_STORAGE_DOMAIN,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_STORAGE_DOMAIN,
ConstantsManager.getInstance()
.getConstants()
.allowToDeleteStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_STORAGE_DOMAIN_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToModifyStorageDomainPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_STORAGE_DOMAIN,
ConstantsManager.getInstance()
.getConstants()
.allowToChangeStorageDomainStatusRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().clusterRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureClusterRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_CLUSTER,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateNewClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_CLUSTER,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_CLUSTER_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToEditClusterPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_CLUSTER_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemoveLogicalNetworksForTheClusterRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().glusterRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureVolumesRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_GLUSTER_VOLUME,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateGlusterVolumesRoleTree()),
new RoleNode(ActionGroup.MANIPULATE_GLUSTER_VOLUME,
ConstantsManager.getInstance()
.getConstants()
.allowToManipulateGlusterVolumesRoleTree()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().hostRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureHostRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_HOST,
ConstantsManager.getInstance()
.getConstants()
.allowToAddNewHostToTheClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_HOST,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveExistingHostFromTheClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_HOST_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToEditHostPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPUTLATE_HOST,
ConstantsManager.getInstance()
.getConstants()
.allowToChangeHostStatusRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_HOST_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureHostsNetworkPhysicalInterfacesRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().templateRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.basicOperationsRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.EDIT_TEMPLATE_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowToChangeTemplatePropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_TEMPLATE_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureTemlateNetworkRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatSdOrAboveRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_TEMPLATE,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateNewTemplateRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_TEMPLATE,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveExistingTemplateRoleTreeTooltip()),
new RoleNode(ActionGroup.IMPORT_EXPORT_VM,
ConstantsManager.getInstance()
.getConstants()
.allowImportExportOperationsRoleTreeTooltip()),
new RoleNode(ActionGroup.COPY_TEMPLATE,
ConstantsManager.getInstance()
.getConstants()
.allowToCopyTemplateBetweenStorageDomainsRoleTreeTooltip()) }) }),
new RoleNode(ConstantsManager.getInstance().getConstants().vmRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.basicOperationsRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.VM_BASIC_OPERATIONS,
ConstantsManager.getInstance()
.getConstants()
.allowBasicVmOperationsRoleTreeTooltip()),
new RoleNode(ActionGroup.CHANGE_VM_CD,
ConstantsManager.getInstance()
.getConstants()
.allowToAttachCdToTheVmRoleTreeTooltip()),
new RoleNode(ActionGroup.CONNECT_TO_VM,
ConstantsManager.getInstance()
.getConstants()
.allowViewingTheVmConsoleScreenRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatSdOrAboveRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.EDIT_VM_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowChangeVmPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CREATE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateNewVmsRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveVmsFromTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.IMPORT_EXPORT_VM,
ConstantsManager.getInstance()
.getConstants()
.allowImportExportOperationsRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_VM_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureVMsNetworkRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_VM_STORAGE,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemoveDiskToTheVmRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_VM_SNAPSHOTS,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateDeleteSnapshotsOfTheVmRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.administrationOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatDcOrEqualRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.MOVE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowToMoveVmImageToAnotherStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.MIGRATE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowMigratingVmBetweenHostsInClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowMigratingVmBetweenHostsInClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.PORT_MIRRORING,
ConstantsManager.getInstance()
.getConstants()
.allowVmNetworkPortMirroringRoleTreeTooltip()) }) }),
new RoleNode(ConstantsManager.getInstance().getConstants().vmPoolRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.basicOperationsRoleTree(),
new RoleNode[] { new RoleNode(ActionGroup.VM_POOL_BASIC_OPERATIONS,
ConstantsManager.getInstance()
.getConstants()
.allowToRunPauseStopVmFromVmPoolRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatSdOrAboveRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_VM_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateVmPoolRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_VM_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToDeleteVmPoolRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_VM_POOL_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToChangePropertiesOfTheVmPoolRoleTreeTooltip()) }) }),
new RoleNode(ConstantsManager.getInstance().getConstants().diskRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainingOperationsRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_DISK,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateDiskRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_DISK,
ConstantsManager.getInstance()
.getConstants()
.allowToDeleteDiskRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_DISK_STORAGE,
ConstantsManager.getInstance()
.getConstants()
.allowToMoveDiskToAnotherStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.ATTACH_DISK,
ConstantsManager.getInstance()
.getConstants()
.allowToAttachDiskToVmRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_DISK_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowToChangePropertiesOfTheDiskRoleTreeTooltip()) }) }) });
// nothing to filter
if (!ApplicationModeHelper.getUiMode().equals(ApplicationMode.AllModes)) {
ApplicationModeHelper.filterActionGroupTreeByApplictionMode(tree);
}
return tree;
}
}
| derekhiggins/ovirt-engine | frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/configure/roles_ui/RoleTreeView.java | Java | apache-2.0 | 34,814 |
package com.jpattern.core.command;
import com.jpattern.core.IProvider;
import com.jpattern.core.exception.NullProviderException;
import com.jpattern.logger.ILogger;
import com.jpattern.logger.SystemOutLoggerFactory;
/**
*
* @author Francesco Cina'
*
* 11/set/2011
*/
public abstract class ACommand<T extends IProvider> {
private ICommandExecutor commandExecutor;
private IOnExceptionStrategy onExceptionStrategy;
private T provider;
private ILogger logger = null;
private boolean executed = false;
private boolean rolledback = false;
/**
* This method launch the execution of the command (or chain of commands) using the default
* default Executor and catching every runtime exception.
* This command is the same of:
* exec(provider, true);
* @return the result of the execution
*/
public final ACommandResult exec(T provider) {
return exec(provider, new DefaultCommandExecutor());
}
/**
* This method launch the execution of the command (or chain of commands).
* Every command in the chain will be managed by an ICommandExecutor object.
* This command is the same of:
* exec(commandExecutor, true);
* @param aCommandExecutor the pool in which the command will runs
* @return the result of the execution
*/
public final ACommandResult exec(T provider, ICommandExecutor commandExecutor) {
visit(provider);
return exec( commandExecutor, new CommandResult());
}
/**
* This method launch the rollback of the command execution (or chain of commands) using the default
* default Executor and catching every runtime exception.
* The rollback is effectively performed only if the command has been executed with a positive result, otherwise
* the command is intended as "not executed" then no rollback will be performed.
* This command is the same of:
* rollback(provider, true);
* @return the result of the rollback
*/
public final ACommandResult rollback(T provider) {
return rollback(provider, new DefaultCommandExecutor());
}
/**
* This method launch the rollback of the command execution (or chain of commands) using a custom command executor.
* The rollback is effectively performed only if the command has been executed with a positive result, otherwise
* the command is intended as "not executed" then no rollback will be performed.
* This command is the same of:
* rollback(provider, commandExecutor, true);
* @return the result of the rollback
*/
public final ACommandResult rollback(T provider, ICommandExecutor commandExecutor) {
visit(provider);
return rollback(commandExecutor, new CommandResult());
}
void visit(T provider) {
this.provider = provider;
}
protected final ACommandResult exec(ICommandExecutor commandExecutor, ACommandResult commandResult) {
this.commandExecutor = commandExecutor;
commandResult.setExecutionStart(this);
getCommandExecutor().execute(this, commandResult);
return commandResult;
}
protected final ACommandResult rollback(ICommandExecutor commandExecutor, ACommandResult commandResult) {
this.commandExecutor = commandExecutor;
commandResult.setExecutionStart(this);
getCommandExecutor().rollback(this, commandResult);
return commandResult;
}
protected final ICommandExecutor getCommandExecutor() {
if (commandExecutor==null) {
commandExecutor = new DefaultCommandExecutor();
}
return commandExecutor;
}
protected final T getProvider() {
if (provider==null) {
throw new NullProviderException();
}
return provider;
}
protected final ILogger getLogger() {
if (logger == null) {
if (provider == null) {
logger = new SystemOutLoggerFactory().logger(getClass());
} else {
logger = getProvider().getLoggerService().logger(this.getClass());
}
}
return logger;
}
public void setOnExceptionStrategy(IOnExceptionStrategy onExceptionStrategy) {
this.onExceptionStrategy = onExceptionStrategy;
}
public IOnExceptionStrategy getOnExceptionStrategy() {
if (onExceptionStrategy == null) {
onExceptionStrategy = new CatchOnExceptionStrategy();
}
return onExceptionStrategy;
}
protected final void doExec(ACommandResult commandResult) {
try {
int errorSize = commandResult.getErrorMessages().size();
executed = false;
rolledback = false;
execute(commandResult);
executed = commandResult.getErrorMessages().size() == errorSize;
} catch (RuntimeException e) {
getOnExceptionStrategy().onException(e, getLogger(), commandResult, "RuntimeException thrown");
} finally {
try {
postExecute(commandResult);
} finally {
commandResult.setExecutionEnd(this);
}
}
}
void postExecute(ACommandResult commandResult) {
}
void postRollback(ACommandResult commandResult) {
}
protected final void doRollback(ACommandResult commandResult) {
try {
if (executed && !rolledback) {
rollback(commandResult);
rolledback = true;
}
} catch (RuntimeException e) {
getOnExceptionStrategy().onException(e, getLogger(), commandResult, "RuntimeException thrown while rollbacking");
} finally {
try {
postRollback(commandResult);
} finally {
commandResult.setExecutionEnd(this);
}
}
}
protected abstract void execute(ACommandResult commandResult);
protected abstract void rollback(ACommandResult commandResult);
void setExecuted(boolean executed) {
this.executed = executed;
}
boolean isExecuted() {
return executed;
}
void setRolledback(boolean rolledback) {
this.rolledback = rolledback;
}
boolean isRolledback() {
return rolledback;
}
}
| ufoscout/jpattern | core/src/main/java/com/jpattern/core/command/ACommand.java | Java | apache-2.0 | 5,668 |
#ifndef AXISCOLORSTRUCT_H
#define AXISCOLORSTRUCT_H
struct axisColorStruct
{
public :
double XAxiscolor[3];
double YAxiscolor[3];
double ZAxiscolor[3];
bool complementaryColor;
bool sameColor;
};
#endif // AXISCOLORSTRUCT_H
| laurapascal/ShapePopulationViewer | src/axisColorStruct.h | C | apache-2.0 | 247 |
<?php
namespace App\Http\Controllers\Sadmin;
use App\Http\Controllers\Controller;
use App\Driver;
use App\Customer;
use App\User;
use App\Detail;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use File;
use Mail;
use PDF;
class BillingController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next) {
$user = Auth::user();
$customer_email = Auth::user()->email;
$customer = Customer::where("email", $customer_email)->get();
$this->customer_id = $customer[0]->id;
return $next($request);
});
}
public function index(Request $request)
{
if(Auth::user() == NULL) {
return redirect('sadmin');
}
$customer_email = Auth::user()->email;
$login_user_id = Auth::user()->id;
$s = $request->s;
$billings = Detail::join('drivers', 'details.driver_id', '=', 'drivers.id');
$billings=$billings->select('details.*', 'drivers.user_id');
$billings=$billings->where('drivers.company_id', $this->customer_id);
$billings=$billings->where('details.invoice_created','<>','');
if(isset($s))$billings -> search($s);
$billings=$billings->orderBy('details.created_at','desc')->paginate(10);
return view('sadmin.billing.index', compact('billings','s','customer_email'));
}
public function set_paymentmark(Request $request) {
$id = $request->id;
$detail = Detail::find($id);
$detail->paid_status = 1;
$detail->save();
$result['status'] = 'success';
die(json_encode($result));
}
public function create_invoice($id){
$detail_id = $id;
$detail = Detail::join('contact_lists as c','details.contact_id','c.id')->
select('details.*','c.d_company_name','c.address1','c.city','c.state','c.zipcode')->where('details.id', $detail_id)->get();
$driver = Driver::join('details', 'details.driver_id','=', 'drivers.id')
->join('contact_lists','details.contact_id','contact_lists.id')
->join('users','users.id','drivers.user_id')
->where('details.id',$detail_id)->get();
$driver = $driver[0];
$customer = Customer::find($this->customer_id);
return view('sadmin.billing.invoice_template', compact('detail_id','detail','driver','customer'));
}
public function generate_invoice(Request $request) {
$detail_id = $request['detail_id'];
$activity = $request['activity'];
$amount = $request['sp_rate'];
$charge_array = array();
for($i=0; $i< count($activity); $i++) {
$item['text'] = $activity[$i];
$item['rate'] = $amount[$i];
array_push($charge_array,$item);
}
$invoice_details = $this->arrayToObject($charge_array);
//return response()->json(['add_charge'=>$add_charge[0]->text], $this->successStatus);
$drivers = Driver::join('details', 'details.driver_id','=', 'drivers.id')
->join('contact_lists','details.contact_id','contact_lists.id')
->join('users','users.id','drivers.user_id')
->where('details.id',$detail_id)->get();
// $contact = Detail::where('id', $drivers[0]->contact_id)->get();
$customers = Customer::where('id', $drivers[0]->company_id)->get();
$filename ='Invoice_'. uniqid(). ".pdf" ;
$filepath = public_path('files').'/'.$filename;
// $pdf=PDF::loadView('driver_invoice_pdf',['drivers' => $drivers, 'customers' => $customers, 'invoice_details' => $invoice_details])->setPaper('a4')->save($filepath);
$pdf=PDF::setOptions([
'logOutputFile' => storage_path('logs/log.htm'),
'tempDir' => storage_path('logs/')
])->loadView('driver_invoice_pdf',['drivers' => $drivers, 'customers' => $customers, 'invoice_details' => $invoice_details])->setPaper('a4')->save($filepath);
$filepath_str = asset('/files/'.$filename);
$detail = Detail::findOrFail($detail_id);
$files = $detail->upload;
$names = $detail->filename;
$detail->upload = ($files=="")?$filepath_str:$files.",".$filepath_str ;
$detail->filename = ($names=="")?$filename:$names.",".$filename;
$detail->invoice_created = date("Y-m-d");
$detail->save();
$result['status'] = 'ok';
die(json_encode($result));
}
private function array_to_obj($array, &$obj)
{
foreach ($array as $key => $value)
{
if (is_array($value))
{
$obj->$key = new \stdClass();
$this->array_to_obj($value, $obj->$key);
}
else
{
$obj->$key = $value;
}
}
return $obj;
}
private function arrayToObject($array)
{
$object= new \stdClass();
return $this->array_to_obj($array,$object);
}
public function send_invoice(Request $request){
$detail_id = $request->detail_id;
///////
$from = Auth::user();
$to = $request->to;
$subject = $request->subject;
$content = $request->message;
$attach = json_decode($request->attach);
$message_arr = json_decode($content);
$data = array(
'from' => $from,
'to' => $to,
'subject' => $subject,
'content' => $message_arr,
'attach' => $attach
);
$mail_status = Mail::send('sadmin.invoice.invoice_mail', $data,function($message) use($data){
$message->to($data['to'])->subject($data['subject']);
$message->from($data['from']->email, $data['from']->firstname." " .$data['from']->lastname);
$message->replyTo($data['from']->email, $data['from']->firstname." " .$data['from']->lastname);
foreach($data['attach'] as $filePath){
$message->attach($filePath);
}
});
if(count(Mail::failures()) > 0){
$result['msg'] = 'Failed to send invoice email, please try again.';
$result['status'] = "fail";
}else{
$result['msg'] = 'Sent the invoice email succesfully.';
$result['status'] = "success";
}
die(json_encode($result));
}
/*
public function set_payment(Request $request){
$invoice_id = $request->id;
$invoice = Invoice::find($invoice_id);
if($invoice->send_status == 0){
$result['msg'] = "The invoice is not sent yet.\n Please confirm before.";
$result['status']="fail";
}else{
$invoice->paid_status=1;
if($invoice->save()){
$result['status']="success";
}else{
$result['status']="fail";
$result['msg'] = "Failed the save.";
}
}
die(json_encode($result));
}
//invoice delete
public function destroy($id)
{
$invoice_detail = Invoice_detail::where('inv_id','=',$id)->get();
foreach ($invoice_detail as $recode) {
$recode -> delete();
}
$invoice_special = Invoice_special::where('inv_id',$id)->get();
foreach ($invoice_special as $recode) {
$recode -> delete();
}
$invoice = Invoice::find($id);
$invoice->delete();
// return redirect('admin/invoice');
return back();
}
*/
}
| widedeveloper/laravel-transport | app/Http/Controllers/Sadmin/BillingController.php | PHP | apache-2.0 | 8,073 |
var child_process = require('child_process'),
fs = require('fs'),
path = require('path');
module.exports = function(context) {
var IOS_DEPLOYMENT_TARGET = '8.0',
SWIFT_VERSION = '3.0',
COMMENT_KEY = /_comment$/,
CORDOVA_VERSION = process.env.CORDOVA_VERSION;
run();
function run() {
var cordova_util = context.requireCordovaModule('cordova-lib/src/cordova/util'),
ConfigParser = CORDOVA_VERSION >= 6.0
? context.requireCordovaModule('cordova-common').ConfigParser
: context.requireCordovaModule('cordova-lib/src/configparser/ConfigParser'),
projectRoot = cordova_util.isCordova(),
platform_ios,
xml = cordova_util.projectConfig(projectRoot),
cfg = new ConfigParser(xml),
projectName = cfg.name(),
iosPlatformPath = path.join(projectRoot, 'platforms', 'ios'),
iosProjectFilesPath = path.join(iosPlatformPath, projectName),
xcconfigPath = path.join(iosPlatformPath, 'cordova', 'build.xcconfig'),
xcconfigContent,
projectFile,
xcodeProject,
bridgingHeaderPath;
if(CORDOVA_VERSION < 7.0) {
platform_ios = CORDOVA_VERSION < 5.0
? context.requireCordovaModule('cordova-lib/src/plugman/platforms')['ios']
: context.requireCordovaModule('cordova-lib/src/plugman/platforms/ios')
projectFile = platform_ios.parseProjectFile(iosPlatformPath);
} else {
var project_files = context.requireCordovaModule('glob').sync(path.join(iosPlatformPath, '*.xcodeproj', 'project.pbxproj'));
if (project_files.length === 0) {
throw new Error('Can\'t found xcode project file');
}
var pbxPath = project_files[0];
var xcodeproj = context.requireCordovaModule('xcode').project(pbxPath);
xcodeproj.parseSync();
projectFile = {
'xcode': xcodeproj,
write: function () {
var fs = context.requireCordovaModule('fs');
var frameworks_file = path.join(iosPlatformPath, 'frameworks.json');
var frameworks = {};
try {
frameworks = context.requireCordovaModule(frameworks_file);
console.log(JSON.stringify(frameworks));
} catch(e) {}
fs.writeFileSync(pbxPath, xcodeproj.writeSync());
fs.writeFileSync(frameworks_file, JSON.stringify(this.frameworks, null, 4));
}
};
}
xcodeProject = projectFile.xcode;
if (fs.existsSync(xcconfigPath)) {
xcconfigContent = fs.readFileSync(xcconfigPath, 'utf-8');
}
bridgingHeaderPath = getBridgingHeader(projectName, xcconfigContent, xcodeProject);
if(bridgingHeaderPath) {
bridgingHeaderPath = path.join(iosPlatformPath, bridgingHeaderPath);
} else {
bridgingHeaderPath = createBridgingHeader(xcodeProject, projectName, iosProjectFilesPath);
}
getExistingBridgingHeaders(iosProjectFilesPath, function (headers) {
importBridgingHeaders(bridgingHeaderPath, headers);
var configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection()),
config, buildSettings;
for (config in configurations) {
buildSettings = configurations[config].buildSettings;
buildSettings['IPHONEOS_DEPLOYMENT_TARGET'] = IOS_DEPLOYMENT_TARGET;
buildSettings['SWIFT_VERSION'] = SWIFT_VERSION;
buildSettings['EMBEDDED_CONTENT_CONTAINS_SWIFT'] = "YES";
buildSettings['LD_RUNPATH_SEARCH_PATHS'] = '"@executable_path/Frameworks"';
}
console.log('IOS project now has deployment target set as:[' + IOS_DEPLOYMENT_TARGET + '] ...');
console.log('IOS project option EMBEDDED_CONTENT_CONTAINS_SWIFT set as:[YES] ...');
console.log('IOS project swift_objc Bridging-Header set to:[' + bridgingHeaderPath + '] ...');
console.log('IOS project Runpath Search Paths set to: @executable_path/Frameworks ...');
projectFile.write();
});
}
function getBridgingHeader(projectName, xcconfigContent, xcodeProject) {
var configurations,
config,
buildSettings,
bridgingHeader;
if (xcconfigContent) {
var regex = /^SWIFT_OBJC_BRIDGING_HEADER *=(.*)$/m,
match = xcconfigContent.match(regex);
if (match) {
bridgingHeader = match[1];
bridgingHeader = bridgingHeader
.replace("$(PROJECT_DIR)/", "")
.replace("$(PROJECT_NAME)", projectName)
.trim();
return bridgingHeader;
}
}
configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection());
for (config in configurations) {
buildSettings = configurations[config].buildSettings;
bridgingHeader = buildSettings['SWIFT_OBJC_BRIDGING_HEADER'];
if (bridgingHeader) {
return unquote(bridgingHeader);
}
}
}
function createBridgingHeader(xcodeProject, projectName, xcodeProjectRootPath) {
var newBHPath = path.join(xcodeProjectRootPath, "Plugins", "Bridging-Header.h"),
content = ["//",
"// Use this file to import your target's public headers that you would like to expose to Swift.",
"//",
"#import <Cordova/CDV.h>"]
//fs.openSync(newBHPath, 'w');
console.log('Creating new Bridging-Header.h at path: ', newBHPath);
fs.writeFileSync(newBHPath, content.join("\n"), { encoding: 'utf-8', flag: 'w' });
xcodeProject.addHeaderFile("Bridging-Header.h");
setBridgingHeader(xcodeProject, path.join(projectName, "Plugins", "Bridging-Header.h"));
return newBHPath;
}
function setBridgingHeader(xcodeProject, headerPath) {
var configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection()),
config, buildSettings, bridgingHeader;
for (config in configurations) {
buildSettings = configurations[config].buildSettings;
buildSettings['SWIFT_OBJC_BRIDGING_HEADER'] = '"' + headerPath + '"';
}
}
function getExistingBridgingHeaders(xcodeProjectRootPath, callback) {
var searchPath = path.join(xcodeProjectRootPath, 'Plugins');
child_process.exec('find . -name "*Bridging-Header*.h"', { cwd: searchPath }, function (error, stdout, stderr) {
var headers = stdout.toString().split('\n').map(function (filePath) {
return path.basename(filePath);
});
callback(headers);
});
}
function importBridgingHeaders(mainBridgingHeader, headers) {
var content = fs.readFileSync(mainBridgingHeader, 'utf-8'),
mainHeaderName = path.basename(mainBridgingHeader);
headers.forEach(function (header) {
if(header !== mainHeaderName && content.indexOf(header) < 0) {
if (content.charAt(content.length - 1) != '\n') {
content += "\n";
}
content += "#import \""+header+"\"\n"
console.log('Importing ' + header + ' into main bridging-header at: ' + mainBridgingHeader);
}
});
fs.writeFileSync(mainBridgingHeader, content, 'utf-8');
}
function nonComments(obj) {
var keys = Object.keys(obj),
newObj = {},
i = 0;
for (i; i < keys.length; i++) {
if (!COMMENT_KEY.test(keys[i])) {
newObj[keys[i]] = obj[keys[i]];
}
}
return newObj;
}
function unquote(str) {
if (str) return str.replace(/^"(.*)"$/, "$1");
}
} | pmwisdom/cordova-background-geolocation-services | hooks/add_swift_support.js | JavaScript | apache-2.0 | 8,172 |
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.hash;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Output stream decorator that hashes data written to the stream.
* Inspired by the Google Guava project.
*/
public final class HashingOutputStream extends FilterOutputStream {
private final Hasher hasher;
public HashingOutputStream(HashFunction hashFunction, OutputStream out) {
super(checkNotNull(out));
this.hasher = checkNotNull(hashFunction.newHasher());
}
@Override
public void write(int b) throws IOException {
hasher.putByte((byte) b);
out.write(b);
}
@Override
public void write(byte[] bytes, int off, int len) throws IOException {
hasher.putBytes(bytes, off, len);
out.write(bytes, off, len);
}
public HashCode hash() {
return hasher.hash();
}
@Override
public void close() throws IOException {
out.close();
}
}
| gstevey/gradle | subprojects/base-services/src/main/java/org/gradle/internal/hash/HashingOutputStream.java | Java | apache-2.0 | 1,665 |
/*
* Copyright (c) 2014 Spotify AB.
*
* 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.spotify.helios.agent;
import com.spotify.docker.client.ContainerNotFoundException;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.DockerException;
import com.spotify.docker.client.messages.ContainerInfo;
import com.spotify.helios.common.descriptors.Goal;
import com.spotify.helios.common.descriptors.Job;
import com.spotify.helios.servicescommon.DefaultReactor;
import com.spotify.helios.servicescommon.Reactor;
import com.spotify.helios.servicescommon.statistics.MetricsContext;
import com.spotify.helios.servicescommon.statistics.SupervisorMetrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InterruptedIOException;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.spotify.helios.common.descriptors.TaskStatus.State.STOPPED;
import static com.spotify.helios.common.descriptors.TaskStatus.State.STOPPING;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Supervises docker containers for a single job.
*/
public class Supervisor {
public interface Listener {
void stateChanged(Supervisor supervisor);
}
private static final Logger log = LoggerFactory.getLogger(Supervisor.class);
private final DockerClient docker;
private final Job job;
private final RestartPolicy restartPolicy;
private final SupervisorMetrics metrics;
private final Reactor reactor;
private final Listener listener;
private final TaskRunnerFactory runnerFactory;
private final StatusUpdater statusUpdater;
private final TaskMonitor monitor;
private final Sleeper sleeper;
private volatile Goal goal;
private volatile String containerId;
private volatile TaskRunner runner;
private volatile Command currentCommand;
private volatile Command performedCommand;
public Supervisor(final Builder builder) {
this.job = checkNotNull(builder.job, "job");
this.docker = checkNotNull(builder.dockerClient, "docker");
this.restartPolicy = checkNotNull(builder.restartPolicy, "restartPolicy");
this.metrics = checkNotNull(builder.metrics, "metrics");
this.listener = checkNotNull(builder.listener, "listener");
this.currentCommand = new Nop();
this.containerId = builder.existingContainerId;
this.runnerFactory = checkNotNull(builder.runnerFactory, "runnerFactory");
this.statusUpdater = checkNotNull(builder.statusUpdater, "statusUpdater");
this.monitor = checkNotNull(builder.monitor, "monitor");
this.reactor = new DefaultReactor("supervisor-" + job.getId(), new Update(),
SECONDS.toMillis(30));
this.reactor.startAsync();
statusUpdater.setContainerId(containerId);
this.sleeper = builder.sleeper;
}
public void setGoal(final Goal goal) {
if (this.goal == goal) {
return;
}
log.debug("Supervisor {}: setting goal: {}", job.getId(), goal);
this.goal = goal;
statusUpdater.setGoal(goal);
switch (goal) {
case START:
currentCommand = new Start();
reactor.signal();
metrics.supervisorStarted();
break;
case STOP:
case UNDEPLOY:
currentCommand = new Stop();
reactor.signal();
metrics.supervisorStopped();
break;
}
}
/**
* Close this supervisor. The actual container is left as-is.
*/
public void close() {
reactor.stopAsync();
if (runner != null) {
runner.stopAsync();
}
metrics.supervisorClosed();
monitor.close();
}
/**
* Wait for supervisor to stop after closing it.
*/
public void join() {
reactor.awaitTerminated();
if (runner != null) {
// Stop the runner again in case it was rewritten by the reactor before it terminated.
runner.stopAsync();
runner.awaitTerminated();
}
}
/**
* Check if the current command is start.
* @return True if current command is start, otherwise false.
*/
public boolean isStarting() {
return currentCommand instanceof Start;
}
/**
* Check if the current command is stop.
* @return True if current command is stop, otherwise false.
*/
public boolean isStopping() {
return currentCommand instanceof Stop;
}
/**
* Check whether the last start/stop command is done.
* @return True if last start/stop command is done, otherwise false.
*/
public boolean isDone() {
return currentCommand == performedCommand;
}
/**
* Get the current container id
* @return The container id.
*/
public String containerId() {
return containerId;
}
private class Update implements Reactor.Callback {
@Override
public void run(final boolean timeout) throws InterruptedException {
final Command command = currentCommand;
final boolean done = performedCommand == command;
log.debug("Supervisor {}: update: performedCommand={}, command={}, done={}",
job.getId(), performedCommand, command, done);
command.perform(done);
if (!done) {
performedCommand = command;
fireStateChanged();
}
}
}
private void fireStateChanged() {
log.debug("Supervisor {}: state changed", job.getId());
try {
listener.stateChanged(this);
} catch (Exception e) {
log.error("Listener threw exception", e);
}
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private Builder() {
}
private Job job;
private String existingContainerId;
private DockerClient dockerClient;
private RestartPolicy restartPolicy;
private SupervisorMetrics metrics;
private Listener listener = new NopListener();
private TaskRunnerFactory runnerFactory;
private StatusUpdater statusUpdater;
private TaskMonitor monitor;
private Sleeper sleeper = new ThreadSleeper();
public Builder setJob(final Job job) {
this.job = job;
return this;
}
public Builder setExistingContainerId(final String existingContainerId) {
this.existingContainerId = existingContainerId;
return this;
}
public Builder setRestartPolicy(final RestartPolicy restartPolicy) {
this.restartPolicy = restartPolicy;
return this;
}
public Builder setDockerClient(final DockerClient dockerClient) {
this.dockerClient = dockerClient;
return this;
}
public Builder setMetrics(SupervisorMetrics metrics) {
this.metrics = metrics;
return this;
}
public Builder setListener(final Listener listener) {
this.listener = listener;
return this;
}
public Builder setRunnerFactory(final TaskRunnerFactory runnerFactory) {
this.runnerFactory = runnerFactory;
return this;
}
public Builder setStatusUpdater(final StatusUpdater statusUpdater) {
this.statusUpdater = statusUpdater;
return this;
}
public Builder setMonitor(final TaskMonitor monitor) {
this.monitor = monitor;
return this;
}
public Builder setSleeper(final Sleeper sleeper) {
this.sleeper = sleeper;
return this;
}
public Supervisor build() {
return new Supervisor(this);
}
private class NopListener implements Listener {
@Override
public void stateChanged(final Supervisor supervisor) {
}
}
}
private interface Command {
/**
* Perform the command. Although this is declared to throw InterruptedException, this will only
* happen when the supervisor is being shut down. During normal operations, the operation will
* be allowed to run until it's done.
* @param done Flag indicating if operation is done.
* @throws InterruptedException If thread is interrupted.
*/
void perform(final boolean done) throws InterruptedException;
}
/**
* Starts a container and attempts to keep it up indefinitely, restarting it when it exits.
*/
private class Start implements Command {
@Override
public void perform(final boolean done) throws InterruptedException {
if (runner == null) {
// There's no active runner, start it to bring up the container.
startAfter(0);
return;
}
if (runner.isRunning()) {
// There's an active runner, brought up by this or another Start command previously.
return;
}
// Check if the runner exited normally or threw an exception
final Result<Integer> result = runner.result();
if (!result.isSuccess()) {
// Runner threw an exception, inspect it.
final Throwable t = result.getException();
if (t instanceof InterruptedException || t instanceof InterruptedIOException) {
// We're probably shutting down, remove the runner and bail.
log.debug("task runner interrupted");
runner = null;
reactor.signal();
return;
} else if (t instanceof DockerException) {
log.error("docker error", t);
} else {
log.error("task runner threw exception", t);
}
}
// Restart the task
startAfter(restartPolicy.delay(monitor.throttle()));
}
private void startAfter(final long delay) {
log.debug("starting job (delay={}): {}", delay, job);
runner = runnerFactory.create(delay, containerId, new TaskListener());
runner.startAsync();
runner.resultFuture().addListener(reactor.signalRunnable(), directExecutor());
}
}
/**
* Stops a container, making sure that the runner spawned by {@link Start} is stopped and the
* container is not running.
*/
private class Stop implements Command {
@Override
public void perform(final boolean done) throws InterruptedException {
if (done) {
return;
}
final Integer gracePeriod = job.getGracePeriod();
if (gracePeriod != null && gracePeriod > 0) {
log.info("Unregistering from service discovery for {} seconds before stopping",
gracePeriod);
statusUpdater.setState(STOPPING);
statusUpdater.update();
if (runner.unregister()) {
log.info("Unregistered. Now sleeping for {} seconds.", gracePeriod);
sleeper.sleep(TimeUnit.MILLISECONDS.convert(gracePeriod, TimeUnit.SECONDS));
}
}
log.info("stopping job: {}", job);
// Stop the runner
if (runner != null) {
runner.stop();
runner = null;
}
final RetryScheduler retryScheduler = BoundedRandomExponentialBackoff.newBuilder()
.setMinIntervalMillis(SECONDS.toMillis(1))
.setMaxIntervalMillis(SECONDS.toMillis(30))
.build().newScheduler();
// Kill the container after stopping the runner
while (!containerNotRunning()) {
killContainer();
Thread.sleep(retryScheduler.nextMillis());
}
statusUpdater.setState(STOPPED);
statusUpdater.setContainerError(containerError());
statusUpdater.update();
}
private void killContainer() throws InterruptedException {
if (containerId == null) {
return;
}
try {
docker.killContainer(containerId);
} catch (DockerException e) {
log.error("failed to kill container {}", containerId, e);
}
}
private boolean containerNotRunning()
throws InterruptedException {
if (containerId == null) {
return true;
}
final ContainerInfo containerInfo;
try {
containerInfo = docker.inspectContainer(containerId);
} catch (ContainerNotFoundException e) {
return true;
} catch (DockerException e) {
log.error("failed to query container {}", containerId, e);
return false;
}
return !containerInfo.state().running();
}
private String containerError() throws InterruptedException {
if (containerId == null) {
return null;
}
final ContainerInfo containerInfo;
try {
containerInfo = docker.inspectContainer(containerId);
} catch (ContainerNotFoundException e) {
return null;
} catch (DockerException e) {
log.error("failed to query container {}", containerId, e);
return null;
}
return containerInfo.state().error();
}
}
private static class Nop implements Command {
@Override
public void perform(final boolean done) {
}
}
@Override
public String toString() {
return "Supervisor{" +
"job=" + job +
", currentCommand=" + currentCommand +
", performedCommand=" + performedCommand +
'}';
}
private class TaskListener extends TaskRunner.NopListener {
private MetricsContext pullContext;
@Override
public void failed(final Throwable t, final String containerError) {
metrics.containersThrewException();
}
@Override
public void pulling() {
pullContext = metrics.containerPull();
}
@Override
public void pullFailed() {
if (pullContext != null) {
pullContext.failure();
}
}
@Override
public void pulled() {
if (pullContext != null) {
pullContext.success();
}
}
@Override
public void created(final String createdContainerId) {
containerId = createdContainerId;
}
}
}
| gtonic/helios | helios-services/src/main/java/com/spotify/helios/agent/Supervisor.java | Java | apache-2.0 | 14,062 |
package de.saxsys.mvvmfx.examples.contacts.model;
public class Subdivision {
private final String name;
private final String abbr;
private final Country country;
public Subdivision(String name, String abbr, Country country) {
this.name = name;
this.abbr = abbr;
this.country = country;
}
public String getName() {
return name;
}
public String getAbbr() {
return abbr;
}
public Country getCountry() {
return country;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Subdivision that = (Subdivision) o;
if (!abbr.equals(that.abbr)) {
return false;
}
if (!country.equals(that.country)) {
return false;
}
if (!name.equals(that.name)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + abbr.hashCode();
result = 31 * result + country.hashCode();
return result;
}
}
| sialcasa/mvvmFX | examples/contacts-example/src/main/java/de/saxsys/mvvmfx/examples/contacts/model/Subdivision.java | Java | apache-2.0 | 1,010 |
package http
import (
bm "go-common/library/net/http/blademaster"
)
func debugCache(c *bm.Context) {
opt := new(struct {
Keys string `form:"keys" validate:"required"`
})
if err := c.Bind(opt); err != nil {
return
}
c.JSONMap(srv.DebugCache(opt.Keys), nil)
}
| LQJJ/demo | 126-go-common-master/app/job/main/aegis/server/http/debug.go | GO | apache-2.0 | 270 |
-- MySQL dump 10.13 Distrib 5.1.61, for redhat-linux-gnu (x86_64)
--
-- Host: mysql-eg-devel-1.ebi.ac.uk Database: test_escherichia_coli_core
-- ------------------------------------------------------
-- Server version 5.5.36-log
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `analysis_description`
--
DROP TABLE IF EXISTS `analysis_description`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analysis_description` (
`analysis_id` smallint(5) unsigned NOT NULL,
`description` text,
`display_label` varchar(255) NOT NULL,
`displayable` tinyint(1) NOT NULL DEFAULT '1',
`web_data` text,
UNIQUE KEY `analysis_idx` (`analysis_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2014-05-23 13:47:08
| EnsemblGenomes/eg-rest | t/test-genome-DBs/escherichia_coli/core/analysis_description.sql | SQL | apache-2.0 | 1,586 |
# Poneramoeba Lühe, 1909 GENUS
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
Schr. Ges. Königsb. , 49, 421.
#### Original name
null
### Remarks
null | mdoering/backbone | life/Protozoa/Sarcomastigophora/Zoomastigophora/Acanthoecidae/Poneramoeba/README.md | Markdown | apache-2.0 | 214 |
package com.twitter.io
import java.io.IOException
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class BufInputStreamTest extends FunSuite {
private[this] val fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n"
private[this] val fileBuf = Buf.ByteArray(fileString.getBytes)
test("Constructor") {
val is = new BufInputStream(fileBuf)
assert(is.available() == fileString.length())
}
test("available") {
val is = new BufInputStream(fileBuf)
assert(is.available() == fileString.length(), "Returned incorrect number of available bytes")
}
test("close") {
val is = new BufInputStream(fileBuf)
val i = is.read()
assert(i != -1)
try {
is.close()
} catch { case e: IOException =>
fail("Test 1: Failed to close the input stream.")
}
try {
val j = is.read()
assert(j != -1)
} catch { case e: Exception =>
fail("Test 2: Should be able to read from closed stream.")
}
}
test("markI") {
val is = new BufInputStream(fileBuf)
// Test for method void java.io.ByteArrayInputStream.mark(int)
val array1 = new Array[Byte](100)
val array2 = new Array[Byte](100)
try {
is.skip(3000)
is.mark(1000)
is.read(array1, 0, array1.length)
is.reset()
is.read(array2, 0, array2.length)
is.reset()
val s1 = new String(array1, 0, array1.length)
val s2 = new String(array2, 0, array2.length)
assert(s1.equals(s2), "Failed to mark correct position")
} catch { case e: Exception =>
fail("Exception during mark test")
}
}
test("markSupported") {
val is = new BufInputStream(fileBuf)
assert(is.markSupported(), "markSupported returned incorrect value")
}
test("read one") {
val is = new BufInputStream(fileBuf)
val c = is.read()
is.reset()
assert(c == fileString.charAt(0), "read returned incorrect char %s %s".format(c, fileString.charAt(0)))
}
test("read") {
val is = new BufInputStream(fileBuf)
val array = new Array[Byte](20)
is.skip(50)
is.mark(100)
is.read(array, 0, array.length)
val s1 = new String(array, 0, array.length)
val s2 = fileString.substring(50, 70)
assert(s1.equals(s2), "Failed to read correct data.")
}
test("read into null array") {
val is = new BufInputStream(fileBuf)
intercept[NullPointerException] {
is.read(null, 0, 1)
fail("NullPointerException expected.")
}
}
test("read into offset < 0") {
val is = new BufInputStream(fileBuf)
val array = new Array[Byte](20)
intercept[IndexOutOfBoundsException] {
is.read(array , -1, 1)
fail("IndexOutOfBoundsException expected.")
}
}
test("read negative len bytes") {
val is = new BufInputStream(fileBuf)
val array = new Array[Byte](20)
intercept[IllegalArgumentException] {
is.read(array , 1, -1)
fail("IllegalArgumentException expected.")
}
}
test("read beyond end of array") {
val is = new BufInputStream(fileBuf)
val array = new Array[Byte](20)
intercept[IndexOutOfBoundsException] {
is.read(array, 1, array.length)
fail("IndexOutOfBoundsException expected.")
}
intercept[IndexOutOfBoundsException] {
is.read(array, array.length, array.length)
fail("IndexOutOfBoundsException expected.")
}
}
test("reset") {
val is = new BufInputStream(fileBuf)
// Test for method void java.io.ByteArrayInputStream.reset()
val array1 = new Array[Byte](10)
val array2 = new Array[Byte](10)
is.mark(200)
is.read(array1, 0, 10)
is.reset()
is.read(array2, 0, 10)
is.reset()
val s1 = new String(array1, 0, array1.length)
val s2 = new String(array2, 0, array2.length)
assert(s1.equals(s2), "Reset failed")
}
test("skip") {
val is = new BufInputStream(fileBuf)
val array1 = new Array[Byte](10)
is.skip(100)
is.read(array1, 0, array1.length)
val s1 = new String(array1, 0, array1.length)
val s2 = fileString.substring(100, 110)
assert(s1.equals(s2), "Failed to skip to correct position")
}
test("read len=0 from non-empty stream should return 0") {
val is = new BufInputStream(fileBuf)
val array = new Array[Byte](1)
assert(is.read(array, 0, 0) == 0)
}
test("read len >= 0 from exhausted stream should return -1") {
val is = new BufInputStream(fileBuf)
val array = new Array[Byte](10000)
val c = is.read(array, 0, array.length)
assert(c == fileBuf.length, "Stream should have been exhausted")
assert(is.read(array, c, 0) == -1, "Stream should have repored exhaustion")
assert(is.read(array, c, array.length - c) == -1, "Stream should have repored exhaustion")
}
}
| n054/util | util-core/src/test/scala/com/twitter/io/BufInputStreamTest.scala | Scala | apache-2.0 | 4,959 |
package fr.jmini.asciidoctorj.testcases;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.asciidoctor.AttributesBuilder;
import org.asciidoctor.OptionsBuilder;
import org.asciidoctor.ast.Block;
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.Title;
public class ShowTitleTrueTestCase implements AdocTestCase {
public static final String ASCIIDOC = "" +
"= My page\n" +
"\n" +
"Some text\n" +
"";
@Override
public String getAdocInput() {
return ASCIIDOC;
}
@Override
public Map<String, Object> getInputOptions() {
AttributesBuilder attributesBuilder = AttributesBuilder.attributes()
.showTitle(true);
return OptionsBuilder.options()
.attributes(attributesBuilder)
.asMap();
}
// tag::expected-html[]
public static final String EXPECTED_HTML = "" +
"<h1>My page</h1>\n" +
"<div class=\"paragraph\">\n" +
"<p>Some text</p>\n" +
"</div>";
// end::expected-html[]
@Override
public String getHtmlOutput() {
return EXPECTED_HTML;
}
@Override
// tag::assert-code[]
public void checkAst(Document astDocument) {
Document document1 = astDocument;
assertThat(document1.getId()).isNull();
assertThat(document1.getNodeName()).isEqualTo("document");
assertThat(document1.getParent()).isNull();
assertThat(document1.getContext()).isEqualTo("document");
assertThat(document1.getDocument()).isSameAs(document1);
assertThat(document1.isInline()).isFalse();
assertThat(document1.isBlock()).isTrue();
assertThat(document1.getAttributes()).containsEntry("doctitle", "My page")
.containsEntry("doctype", "article")
.containsEntry("example-caption", "Example")
.containsEntry("figure-caption", "Figure")
.containsEntry("filetype", "html")
.containsEntry("notitle", "")
.containsEntry("prewrap", "")
.containsEntry("showtitle", true)
.containsEntry("table-caption", "Table");
assertThat(document1.getRoles()).isNullOrEmpty();
assertThat(document1.isReftext()).isFalse();
assertThat(document1.getReftext()).isNull();
assertThat(document1.getCaption()).isNull();
assertThat(document1.getTitle()).isNull();
assertThat(document1.getStyle()).isNull();
assertThat(document1.getLevel()).isEqualTo(0);
assertThat(document1.getContentModel()).isEqualTo("compound");
assertThat(document1.getSourceLocation()).isNull();
assertThat(document1.getSubstitutions()).isNullOrEmpty();
assertThat(document1.getBlocks()).hasSize(1);
Block block1 = (Block) document1.getBlocks()
.get(0);
assertThat(block1.getId()).isNull();
assertThat(block1.getNodeName()).isEqualTo("paragraph");
assertThat(block1.getParent()).isSameAs(document1);
assertThat(block1.getContext()).isEqualTo("paragraph");
assertThat(block1.getDocument()).isSameAs(document1);
assertThat(block1.isInline()).isFalse();
assertThat(block1.isBlock()).isTrue();
assertThat(block1.getAttributes()).isNullOrEmpty();
assertThat(block1.getRoles()).isNullOrEmpty();
assertThat(block1.isReftext()).isFalse();
assertThat(block1.getReftext()).isNull();
assertThat(block1.getCaption()).isNull();
assertThat(block1.getTitle()).isNull();
assertThat(block1.getStyle()).isNull();
assertThat(block1.getLevel()).isEqualTo(0);
assertThat(block1.getContentModel()).isEqualTo("simple");
assertThat(block1.getSourceLocation()).isNull();
assertThat(block1.getSubstitutions()).containsExactly("specialcharacters", "quotes", "attributes", "replacements", "macros", "post_replacements");
assertThat(block1.getBlocks()).isNullOrEmpty();
assertThat(block1.getLines()).containsExactly("Some text");
assertThat(block1.getSource()).isEqualTo("Some text");
Title title1 = document1.getStructuredDoctitle();
assertThat(title1.getMain()).isEqualTo("My page");
assertThat(title1.getSubtitle()).isNull();
assertThat(title1.getCombined()).isEqualTo("My page");
assertThat(title1.isSanitized()).isFalse();
assertThat(document1.getDoctitle()).isEqualTo("My page");
assertThat(document1.getOptions()).containsEntry("header_footer", false);
}
// end::assert-code[]
@Override
// tag::mock-code[]
public Document createMock() {
Document mockDocument1 = mock(Document.class);
when(mockDocument1.getId()).thenReturn(null);
when(mockDocument1.getNodeName()).thenReturn("document");
when(mockDocument1.getParent()).thenReturn(null);
when(mockDocument1.getContext()).thenReturn("document");
when(mockDocument1.getDocument()).thenReturn(mockDocument1);
when(mockDocument1.isInline()).thenReturn(false);
when(mockDocument1.isBlock()).thenReturn(true);
Map<String, Object> map1 = new HashMap<>();
map1.put("doctitle", "My page");
map1.put("doctype", "article");
map1.put("example-caption", "Example");
map1.put("figure-caption", "Figure");
map1.put("filetype", "html");
map1.put("notitle", "");
map1.put("prewrap", "");
map1.put("showtitle", true);
map1.put("table-caption", "Table");
when(mockDocument1.getAttributes()).thenReturn(map1);
when(mockDocument1.getRoles()).thenReturn(Collections.emptyList());
when(mockDocument1.isReftext()).thenReturn(false);
when(mockDocument1.getReftext()).thenReturn(null);
when(mockDocument1.getCaption()).thenReturn(null);
when(mockDocument1.getTitle()).thenReturn(null);
when(mockDocument1.getStyle()).thenReturn(null);
when(mockDocument1.getLevel()).thenReturn(0);
when(mockDocument1.getContentModel()).thenReturn("compound");
when(mockDocument1.getSourceLocation()).thenReturn(null);
when(mockDocument1.getSubstitutions()).thenReturn(Collections.emptyList());
Block mockBlock1 = mock(Block.class);
when(mockBlock1.getId()).thenReturn(null);
when(mockBlock1.getNodeName()).thenReturn("paragraph");
when(mockBlock1.getParent()).thenReturn(mockDocument1);
when(mockBlock1.getContext()).thenReturn("paragraph");
when(mockBlock1.getDocument()).thenReturn(mockDocument1);
when(mockBlock1.isInline()).thenReturn(false);
when(mockBlock1.isBlock()).thenReturn(true);
when(mockBlock1.getAttributes()).thenReturn(Collections.emptyMap());
when(mockBlock1.getRoles()).thenReturn(Collections.emptyList());
when(mockBlock1.isReftext()).thenReturn(false);
when(mockBlock1.getReftext()).thenReturn(null);
when(mockBlock1.getCaption()).thenReturn(null);
when(mockBlock1.getTitle()).thenReturn(null);
when(mockBlock1.getStyle()).thenReturn(null);
when(mockBlock1.getLevel()).thenReturn(0);
when(mockBlock1.getContentModel()).thenReturn("simple");
when(mockBlock1.getSourceLocation()).thenReturn(null);
when(mockBlock1.getSubstitutions()).thenReturn(Arrays.asList("specialcharacters", "quotes", "attributes", "replacements", "macros", "post_replacements"));
when(mockBlock1.getBlocks()).thenReturn(Collections.emptyList());
when(mockBlock1.getLines()).thenReturn(Collections.singletonList("Some text"));
when(mockBlock1.getSource()).thenReturn("Some text");
when(mockDocument1.getBlocks()).thenReturn(Collections.singletonList(mockBlock1));
Title mockTitle1 = mock(Title.class);
when(mockTitle1.getMain()).thenReturn("My page");
when(mockTitle1.getSubtitle()).thenReturn(null);
when(mockTitle1.getCombined()).thenReturn("My page");
when(mockTitle1.isSanitized()).thenReturn(false);
when(mockDocument1.getStructuredDoctitle()).thenReturn(mockTitle1);
when(mockDocument1.getDoctitle()).thenReturn("My page");
Map<Object, Object> map2 = new HashMap<>();
map2.put("attributes", "{\"showtitle\"=>true}");
map2.put("header_footer", false);
when(mockDocument1.getOptions()).thenReturn(map2);
return mockDocument1;
}
// end::mock-code[]
} | jmini/asciidoctorj-experiments | test-cases/adoc-test-cases/src/main/java/fr/jmini/asciidoctorj/testcases/ShowTitleTrueTestCase.java | Java | apache-2.0 | 8,764 |
package fr.sii.ogham.sms.message;
import fr.sii.ogham.core.util.EqualsBuilder;
import fr.sii.ogham.core.util.HashCodeBuilder;
/**
* Represents a phone number. It wraps a simple string. The aim is to abstracts
* the concept and to be able to provide other fields latter if needed.
*
* @author Aurélien Baudet
*
*/
public class PhoneNumber {
/**
* The phone number as string
*/
private String number;
/**
* Initialize the phone number with the provided number.
*
* @param number
* the phone number
*/
public PhoneNumber(String number) {
super();
this.number = number;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Override
public String toString() {
return number;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(number).hashCode();
}
@Override
public boolean equals(Object obj) {
return new EqualsBuilder(this, obj).appendFields("number").isEqual();
}
}
| groupe-sii/ogham | ogham-core/src/main/java/fr/sii/ogham/sms/message/PhoneNumber.java | Java | apache-2.0 | 1,017 |
# Vagrant Kafka Lab
------
**Prerequistes:** Vagrant (2.0.1), Virtual Box (5.2.0) and Ansible (2.4.1.0)
## Web UIs
- Grafana: [http://kafka-1:3000](http://kafka-1:3000)
- Prometheus-UI: [http://kafka-1:9090](http://kafka-1:9090)
## Installation
```bash
git clone https://github.com/ineedcode/vagrant-kafka-lab
cd vagrant-kafka-lab
vagrant plugin install vagrant-hostmanager
vagrant up
```
##### Grafana Konfiguration
access to Grafana and use the default credentials with `admin:admin`. Add Dashboard with Prometheus as source, the source is available at `localhost:9000.
Upload the Kafka Dashboard which is included in the doc folder: [Grafana-Kafka-Dashboard](doc/Grafana-Kafka-Dashboard-v1.json)
## Components
In the following you'll find list of components that has been used and with some general settings.
| IP | Hostname | Description | Settings |
|--------------|----------|-------------------------------------|----------|
| 192.168.10.2 | kafka-1 | ZK, Kafka Broker, Prometheus | 2GB RAM |
| 192.168.10.3 | kafka-2 | ZK, Kafka Broker | 1GB RAM |
| 192.168.10.4 | kafka-3 | ZK, Kafka Broker | 1GB RAM |
# Ansible
```bash
ansible all -i ansible/inventories/vbox/hosts -m ping -o
ansible-playbook ansible/cluster.yml --tags "new-kafka-config"
```
## Usage
##### Use pre build commands to interact with Kafka
The `script` folder has been added to the PATH therefore you can use the shell scripts from your cli of the virtual machines.
```bash
vagrant ssh kafka-1
list-topics.sh #lists all topics
```
### Versions
Following versions are used in this lab
- Kafka is using 0.11.0.2 ([change it here](ansible/roles/kafka/defaults/main.yml))
- Zookeeper is using 3.4.10 ([change it here](ansible/roles/zookeeper/defaults/main.yml))
- Promeutheus is using 1.7.1 ([change it here](ansible/roles/promeutheus/defaults/main.yml))
- Grafana is using 4.3.2 ([change it here](ansible/roles/promeutheus/defaults/main.yml)) | iNeedCode/vagrant-kafka-lab | Readme.md | Markdown | apache-2.0 | 2,024 |
package org.fastnate.generator.converter;
import java.time.Duration;
import org.fastnate.generator.context.GeneratorContext;
import org.fastnate.generator.statements.ColumnExpression;
import org.fastnate.generator.statements.PrimitiveColumnExpression;
/**
* Converts a {@link Duration} to an SQL expression.
*
* @author Tobias Liefke
*/
public class DurationConverter implements ValueConverter<Duration> {
@Override
public ColumnExpression getExpression(final Duration value, final GeneratorContext context) {
return PrimitiveColumnExpression.create(value.toNanos(), context.getDialect());
}
@Override
public ColumnExpression getExpression(final String defaultValue, final GeneratorContext context) {
return getExpression(Duration.parse(defaultValue), context);
}
}
| liefke/org.fastnate | fastnate-generator/src/main/java/org/fastnate/generator/converter/DurationConverter.java | Java | apache-2.0 | 786 |
module AssemblyAndServiceOperationsMixin
# Commands used from new dtk client
def check_if_instance_running(node_address, port, path)
endpoint = node_address + ":" + port
response = request_response(path, {}, 'get', endpoint);
response.code == 200
end
def get_node_by_name(service_instance_name, node_name)
nodes_response = send_request("/rest/api/v1/services/#{service_instance_name}/nodes", {}, 'get')
nodes = nodes_response['data']
if nodes.empty?
puts "No nodes found";
return false
end
selected_node_arr = nodes.select { |node| node['display_name'] == node_name } if nodes
if selected_node_arr.empty? || selected_node_arr.length > 1
puts "Expected only one node, but found: #{selected_node_arr}"
return false
end
node = selected_node_arr.first
puts "Found requested node: #{node}"
node
end
def verify_service_instance_nodes_terminated(service_instance_name)
require 'aws-sdk-ec2'
puts "Verify service instance nodes have been terminated", "-----------------------------------------------------"
nodes_terminated = true
ec2 = Aws::EC2::Client.new(region: 'us-east-1')
ec2_instance = ec2.describe_instances(filters:[{ name: 'tag:Name', values: ["*" + service_instance_name + "*"] }])
ec2_instance.reservations.each do |status|
puts "Instance details: #{status}"
if status.instances.first.state.name == "running"
nodes_terminated = false
puts "Service instance: #{service_instance_name} nodes have not been terminated"
end
end
puts ""
puts "Service instance: #{service_instance_name} nodes have been terminated" if nodes_terminated
nodes_terminated
end
def check_if_service_instance_exists(service_instance_name)
puts "Check if service instance exists", "-----------------------------------"
service_instance_exists = false
service_instances_list = send_request("/rest/api/v1/services/list", {}, 'get')
ap service_instances_list
if service_instances_list['status'] == 'ok' && !service_instances_list['data'].empty?
service_instances_list['data'].each do |instance|
if instance['display_name'] == service_instance_name
puts "Service instance: #{service_instance_name} found!"
service_instance_exists = true
end
end
else
puts "Service instance #{service_instance_name} is not found!"
end
puts "Service instance #{service_instance_name} is not found!" unless service_instance_exists
puts ""
service_instance_exists
end
def check_if_node_exists_in_service_instance(service_instance_name, node_name)
puts "Check if node exists in service instance", "---------------------------------------"
node_exists = false
nodes_list = send_request("/rest/api/v1/services/#{service_instance_name}/nodes", {}, 'get')
ap nodes_list
if nodes_list['status'] == 'ok' && !nodes_list['data'].empty?
nodes_list['data'].each do |node|
if node['display_name'] == node_name
puts "Node: #{node_name} found!"
node_exists = true
end
end
else
puts "Node #{node_name} is not found in #{service_instance_name}"
end
puts "Node #{node_name} is not found in #{service_instance_name}" unless node_exists
puts ""
node_exists
end
def check_if_node_group_exists_in_service_instance(service_instance_name, node_group_name, cardinality)
puts "Check if node group exists in service instance", "-------------------------------------------"
node_group_exist = false
nodes_list = send_request("/rest/api/v1/services/#{service_instance_name}/nodes", {}, 'get')
ap nodes_list
if nodes_list['status'] == 'ok' && !nodes_list['data'].empty?
node_group_members = []
nodes_list['data'].each do |node|
if node['display_name'].include? node_group_name + ":" # indicator it is node group member
node_group_members << node['display_name']
end
end
if node_group_members.size == cardinality
puts "Node group #{node_group_name} is found in #{service_instance_name}"
node_group_exist = true
end
else
puts "Node group #{node_group_name} is not found in #{service_instance_name}"
end
puts "Node group #{node_group_name} is not found in #{service_instance_name}" unless node_group_exist
puts ""
node_group_exist
end
def check_if_component_exists_in_service_instance(service_instance_name, component_name)
puts "Check if component exists in service instance", "-----------------------------------------"
component_exists = false
components_list = send_request("/rest/api/v1/services/#{service_instance_name}/components", {}, 'get')
ap components_list
if components_list['status'] == 'ok' && !components_list['data'].empty?
components_list['data'].each do |cmp|
if cmp['display_name'] == component_name
puts "Component: #{component_name} found!"
component_exists = true
end
end
else
puts "Component #{component_name} is not found in #{service_instance_name}"
end
puts "Component #{component_name} is not found in #{service_instance_name}" unless component_exists
puts ""
component_exists
end
def check_if_action_exists_in_service_instance(service_instance_name, action_to_check)
puts "Check if action exists in service instance", "------------------------------------------"
action_exists = false
list_of_actions = send_request("/rest/api/v1/services/#{service_instance_name}/actions", {}, 'get')
ap list_of_actions
if list_of_actions['status'] == 'ok' && !list_of_actions['data'].empty?
list_of_actions['data'].each do |action|
if action['display_name'] == action_to_check
puts "Action: #{action_to_check} found!"
action_exists = true
end
end
else
puts "Action #{action_to_check} is not found in #{service_instance_name}"
end
puts "Action #{action_to_check} is not found in #{service_instance_name}" unless action_exists
puts ""
action_exists
end
def check_if_attributes_exists_in_service_instance(service_instance_name, attributes_to_check)
puts "Check if attributes exist and are correct in service instance", "---------------------------------------------------"
attributes_exist = false
attributes_list = send_request("/rest/api/v1/services/#{service_instance_name}/attributes?all&format=yaml", {}, 'get')
puts "Attributes to check:"
ap attributes_to_check
puts ""
puts "Attributes on service instance:"
ap attributes_list
puts ""
if attributes_list['status'] == 'ok' && !attributes_list['data'].empty?
attributes_exist_and_values_correct = []
attributes_list['data'].each do |attr|
if (attributes_to_check.keys.include? attr['name']) && (attributes_to_check.values.include? attr['value'])
attributes_exist_and_values_correct << true
end
end
if (attributes_exist_and_values_correct.count == attributes_to_check.count) && (!attributes_exist_and_values_correct.include? false)
puts "All attributes: #{attributes_to_check} are verified and exist on service instance"
attributes_exist = true
else
puts "Some attributes are missing or they don't have expected values on service instance"
end
else
puts "Attributes #{attributes_to_check} are not found in #{service_instance_name}"
end
puts ""
attributes_exist
end
def check_task_status(service_instance_name)
puts "Check task status", "----------------"
service_converged = { pass: false, error: nil }
end_loop = false
count = 0
max_num_of_retries = 80
while (count < max_num_of_retries)
sleep 10
count += 1
task_status_response = send_request("/rest/api/v1/services/#{service_instance_name}/task_status", {}, 'get')
if task_status_response['status'] == 'ok'
if task_status_response['data'].first['status'] == 'succeeded'
puts "Service was converged successfully!"
service_converged[:pass] = true
break
elsif task_status_response['data'].first['status'] == 'failed'
puts 'Service was not converged successfully!'
ap task_status_response['data']
service_converged[:error] = task_status_response['data']
break
end
else
ap task_status_response['data']
service_converged[:error] = task_status_response['data']
puts "Service was not converged successfully!"
break
end
end
puts ''
service_converged
end
def check_task_status_with_breakpoint(service_instance_name, subtask_name_with_breakpoint)
puts "Check task status with breakpoint", "---------------------------------"
debug_passed = false
end_loop = false
count = 0
max_num_of_retries = 30
while (count < max_num_of_retries)
sleep 10
count += 1
task_status_response = send_request("/rest/api/v1/services/#{service_instance_name}/task_status", {}, 'get')
ap task_status_response
if task_status_response['status'] == 'ok'
if task_status_response['data'].first['status'] == 'debugging'
subtask = task_status_response['data'].select { |subtask| subtask['type'].include? subtask_name_with_breakpoint }.first
debug_command = subtask['info']['message'].match(/(byebug -R.+)'/)[1]
debug_execution = `echo c | #{debug_command}`
puts debug_execution
if debug_execution.include? "Connected"
debug_passed = true
break
else
debug_passed = false
break
end
end
else
ap task_status_response['data']
puts "Service was not converged successfully! Debug cannot proceed"
break
end
end
puts ''
debug_passed
end
def check_delete_task_status(service_instance_name)
puts "Check delete task status", "------------------------"
service_deleted = { pass: false, error: nil }
end_loop = false
count = 0
max_num_of_retries = 50
while (count < max_num_of_retries)
sleep 10
count += 1
task_status_response = send_request("/rest/api/v1/services/#{service_instance_name}/task_status", {}, 'get')
if task_status_response['status'] == 'ok'
if task_status_response['data'].first['status'] == 'succeeded'
puts "Service was deleted successfully!"
service_deleted[:pass] = true
break
elsif task_status_response['data'].first['status'] == 'failed'
puts 'Service was not deleted successfully!'
ap task_status_response['data']
service_deleted[:error] = task_status_response['data']
break
end
else
ap task_status_response
if task_status_response['errors'].first['message'] == "No context with the name '#{service_instance_name}' exists"
puts "Service was deleted successfully!"
service_deleted[:pass] = true
else
puts "Service was not deleted successfully!"
service_deleted[:error] = task_status_response['data']
end
break
end
end
puts ''
service_deleted
end
def stage_service_instance(service_instance_name, context = nil)
#Get list of assemblies, extract selected assembly, stage service and return its id
puts "Stage service:", "--------------"
service_id = nil
extract_id_regex = /id: (\d+)/
assembly_list = send_request('/rest/assembly/list', {:subtype=>'template'})
puts "List of avaliable assemblies: "
pretty_print_JSON(assembly_list)
test_template = assembly_list['data'].select { |x| x['display_name'] == @assembly }.first
if (!test_template.nil?)
puts "Assembly #{@assembly} found!"
assembly_id = test_template['id']
puts "Assembly id: #{assembly_id}"
if @is_context
stage_service_response = send_request('/rest/assembly/stage', {:assembly_id=>assembly_id, :name=>@service_name, :service_module_name => service_instance_name, :is_context => @is_context})
else
unless context
stage_service_response = send_request('/rest/assembly/stage', {:assembly_id=>assembly_id, :name=>@service_name, :service_module_name => service_instance_name})
else
stage_service_response = send_request('/rest/assembly/stage', {:assembly_id=>assembly_id, :name=>@service_name, :service_module_name => service_instance_name, :context_id=>context})
end
end
pretty_print_JSON(stage_service_response)
if (stage_service_response['data'].include? "name: #{@service_name}")
puts "Stage of #{@service_name} assembly completed successfully!"
service_id_match = stage_service_response['data'].match(extract_id_regex)
self.service_id = service_id_match[1].to_i
puts "Service id for a staged service: #{self.service_id}"
else
puts "Stage service didnt pass!"
end
else
puts "Assembly #{@service_name} not found!"
end
puts ""
end
# Commands used from old dtk client
def stage_service(context = nil)
#Get list of assemblies, extract selected assembly, stage service and return its id
puts "Stage service:", "--------------"
service_id = nil
extract_id_regex = /id: (\d+)/
assembly_list = send_request('/rest/assembly/list', {:subtype=>'template'})
puts "List of avaliable assemblies: "
pretty_print_JSON(assembly_list)
test_template = assembly_list['data'].select { |x| x['display_name'] == @assembly }.first
if (!test_template.nil?)
puts "Assembly #{@assembly} found!"
assembly_id = test_template['id']
puts "Assembly id: #{assembly_id}"
if @is_context
stage_service_response = send_request('/rest/assembly/stage', {:assembly_id=>assembly_id, :name=>@service_name, :is_context => @is_context})
else
unless context
stage_service_response = send_request('/rest/assembly/stage', {:assembly_id=>assembly_id, :name=>@service_name})
else
stage_service_response = send_request('/rest/assembly/stage', {:assembly_id=>assembly_id, :name=>@service_name, :context_id=>context})
end
end
pretty_print_JSON(stage_service_response)
if (stage_service_response['data'].include? "name: #{@service_name}")
puts "Stage of #{@service_name} assembly completed successfully!"
service_id_match = stage_service_response['data'].match(extract_id_regex)
self.service_id = service_id_match[1].to_i
puts "Service id for a staged service: #{self.service_id}"
else
puts "Stage service didnt pass!"
end
else
puts "Assembly #{@service_name} not found!"
end
puts ""
end
def get_components_versions(service_id)
puts "Get all component versions from service:", "-----------------------------"
components_list = send_request('/rest/assembly/info_about', {:assembly_id=>service_id, :node_id => nil, :component_id => nil, :subtype=>'instance', :about=>'components'})
components_list = components_list['data'].map! { |c| c['version'] }
puts ""
return components_list
end
def get_default_context_service
puts "Get default context service instance id:", "---------------------------------------"
service_id = nil
default_context_service_response = send_request('/rest/assembly/get_default_context', {})
if default_context_service_response['status'] == 'ok'
puts "Default context service instance succesfully found."
service_id = default_context_service_response['data']['id']
else
puts "Default context service was not succesfully found."
end
puts ''
service_id
end
def stage_service_with_namespace(namespace)
#Get list of assemblies, extract selected assembly, stage service and return its id
puts "Stage service:", "--------------"
service_id = nil
extract_id_regex = /id: (\d+)/
assembly_list = send_request('/rest/assembly/list', {:subtype=>'template'})
puts "List of avaliable assemblies: "
pretty_print_JSON(assembly_list)
test_template = assembly_list['data'].select { |x| x['display_name'] == @assembly && x['namespace'] == namespace }.first
if (!test_template.nil?)
puts "Assembly #{@assembly} from namespace #{namespace} found!"
assembly_id = test_template['id']
puts "Assembly id: #{assembly_id}"
stage_service_response = send_request('/rest/assembly/stage', {:assembly_id=>assembly_id, :name=>@service_name})
pretty_print_JSON(stage_service_response)
if (stage_service_response['data'].include? "name: #{@service_name}")
puts "Stage of #{@service_name} assembly completed successfully!"
service_id_match = stage_service_response['data'].match(extract_id_regex)
self.service_id = service_id_match[1].to_i
puts "Service id for a staged service: #{self.service_id}"
else
puts "Stage service didnt pass!"
end
else
puts "Assembly #{@service_name} not found!"
end
puts ""
end
def check_service_info(service_id, info_to_check)
puts "Show service info:", "------------------"
info_exist = false
service_info_response = send_request('/rest/assembly/info', {:assembly_id=>service_id, :subtype=>:instance})
pretty_print_JSON(service_info_response)
if service_info_response['data'].include? info_to_check
puts "#{info_to_check} exists in info output!"
info_exist = true
else
puts "#{info_to_check} does not exist in info output!"
end
puts ""
return info_exist
end
def rename_service(service_id, new_service_name)
puts "Rename service:", "---------------"
service_renamed = false
service_list = send_request('/rest/assembly/list', {:detail_level=>'nodes', :subtype=>'instance'})
service_name = service_list['data'].select { |x| x['id'] == service_id }
if service_name.any?
puts "Old service name is: #{service_name}. Proceed with renaming it to #{new_service_name}..."
rename_status = send_request('/rest/assembly/rename', {:assembly_id=>service_id, :assembly_name=>service_name, :new_assembly_name=>new_service_name})
if rename_status['status'] == 'ok'
puts "Service #{service_name} renamed to #{new_service_name} successfully!"
service_renamed = true
else
puts "Service #{service_name} was not renamed to #{new_service_name} successfully!"
end
else
puts "Service with id #{service_id} does not exist!"
end
puts ""
return service_renamed
end
def create_attribute(service_id, attribute_name)
#Create attribute
puts "Create attribute:", "-----------------"
attributes_created = false
create_attribute_response = send_request('/rest/assembly/set_attributes', {:assembly_id=>service_id, :create=>true, :pattern=>attribute_name})
puts "List of service attributes:"
service_attributes = send_request('/rest/assembly/info_about', {:about=>'attributes', :filter=>nil, :subtype=>'instance', :assembly_id=>service_id})
pretty_print_JSON(service_attributes)
extract_attribute = service_attributes['data'].select { |x| x['display_name'].include? attribute_name }.first['display_name']
if (extract_attribute == attribute_name)
puts "Creating #{attribute_name} attribute completed successfully!"
attributes_created = true
end
puts ""
return attributes_created
end
def check_if_attribute_exists(service_id, attribute_name)
puts "Check if attribute exists:", "--------------------------"
attribute_exists = false
puts "List of service attributes:"
service_attributes = send_request('/rest/assembly/info_about', {:about=>'attributes', :filter=>nil, :subtype=>'instance', :assembly_id=>service_id})
pretty_print_JSON(service_attributes)
extract_attribute = service_attributes['data'].select { |x| x['display_name'].include? attribute_name }.first['display_name']
if (extract_attribute == attribute_name)
puts "#{attribute_name} attribute exists!"
attribute_exists = true
else
puts "#{attribute_name} attribute does not exist!"
end
puts ""
return attribute_exists
end
def link_attributes(service_id, source_attribute, context_attribute)
puts "Link attributes:", "----------------"
attributes_linked = false
link_attributes_response = send_request('/rest/assembly/add_ad_hoc_attribute_links', {:assembly_id=>service_id, :context_attribute_term=>context_attribute, :source_attribute_term=>"$#{source_attribute}"})
pretty_print_JSON(link_attributes_response)
if link_attributes_response['status'] == 'ok'
puts "Link between #{source_attribute} attribute and #{context_attribute} attribute is established!"
attributes_linked = true
else
puts "Link between #{source_attribute} attribute and #{context_attribute} attribute is not established!"
end
puts ""
return attributes_linked
end
def get_service_id_by_name(service_name)
puts "Get service instance id by its name", "-----------------------------------"
service_list = send_request('/rest/assembly/list', {:detail_level=>'nodes', :subtype=>'instance'})
puts "List of all services and its content:"
service_instance = nil
filtered_services = service_list['data'].select { |x| x['display_name'] == service_name }
if filtered_services.length == 1
puts "Service instance with name #{service_name} exists: "
pretty_print_JSON(filtered_services)
service_instance = filtered_services[0]
elsif filtered_services.length.zero?
puts "Service instance with name #{service_name} does not exist."
else
puts "Multiple service instances with name #{service_name} exist."
end
end
def check_if_service_exists(service_id)
#Get list of existing services and check if staged service exists
puts "Check if service exists:", "------------------------"
service_exists = false
service_list = send_request('/rest/assembly/list', {:detail_level=>'nodes', :subtype=>'instance'})
puts "List of all services and its content:"
pretty_print_JSON(service_list)
test_service = service_list['data'].select { |x| x['id'] == service_id }
puts "Service with id #{service_id}: "
pretty_print_JSON(test_service)
if (test_service.any?)
extract_service_id = test_service.first['id']
execution_status = test_service.first['execution_status']
if ((extract_service_id == service_id) && (execution_status == 'staged'))
puts "Service with id #{service_id} exists!"
service_exists = true
end
else
puts "Service with id #{service_id} does not exist!"
end
puts ""
return service_exists
end
def list_specific_success_service(service_name)
puts "List success services:", "------------------------"
service_list = send_request('/rest/assembly/list', {:subtype=>'instance', :detail_level => 'nodes'})
success_services = service_list['data'].select { |x| x['display_name'] == service_name && x['execution_status'] == 'succeeded' }
pretty_print_JSON(success_services)
return success_services
end
def list_matched_success_service(service_name)
puts "List success services:", "------------------------"
service_list = send_request('/rest/assembly/list', {:subtype=>'instance', :detail_level => 'nodes'})
success_services = service_list['data'].select { |x| (x['display_name'].include? service_name) && (x['execution_status'] == 'succeeded') }
pretty_print_JSON(success_services)
return success_services
end
def list_specific_failed_service(service_name)
puts "List failed services:", "-------------------------"
service_list = send_request('/rest/assembly/list', {:subtype=>'instance', :detail_level => 'nodes'})
failed_services = service_list['data'].select { |x| x['display_name'] == service_name && x['execution_status'] == 'failed' }
pretty_print_JSON(failed_services)
return failed_services
end
def list_matched_failed_service(service_name)
puts "List failed services:", "-------------------------"
service_list = send_request('/rest/assembly/list', {:subtype=>'instance', :detail_level => 'nodes'})
failed_services = service_list['data'].select { |x| (x['display_name'].include? service_name) && (x['execution_status'] == 'failed') }
pretty_print_JSON(failed_services)
return failed_services
end
def check_service_status(service_id, status_to_check)
#Get list of services and check if service exists and its status
puts "Check service status:", "---------------------"
service_exists = false
end_loop = false
count = 0
max_num_of_retries = 50
while (end_loop == false)
sleep 5
count += 1
service_list = send_request('/rest/assembly/list', {:subtype=>'instance'})
service = service_list['data'].select { |x| x['id'] == service_id }.first
if (!service.nil?)
test_service = send_request('/rest/assembly/info', {:assembly_id=>service_id,:subtype=>:instance})
op_status = test_service['data']['op_status']
extract_service_id = service['id']
if ((extract_service_id == service_id) && (op_status == status_to_check))
puts "Service with id #{extract_service_id} has current op status: #{status_to_check}"
service_exists = true
end_loop = true
else
puts "Service with id #{extract_service_id} still does not have current op status: #{status_to_check}"
end
else
puts "Service with id #{service_id} not found in list"
end_loop = true
end
if (count > max_num_of_retries)
puts "Max number of retries reached..."
end_loop = true
end
end
puts ""
return service_exists
end
def set_attribute(service_id, attribute_name, attribute_value)
#Set attribute on particular service
puts "Set attribute:", "--------------"
is_attributes_set = false
service_attributes = send_request('/rest/assembly/info_about', {:about=>'attributes', :filter=>nil, :subtype=>'instance', :assembly_id=>service_id})
attribute_id = service_attributes['data'].select { |x| x['display_name'].include? attribute_name }
if attribute_id.empty?
set_attribute_value_response = send_request('/rest/assembly/set_attributes', {:assembly_id=>service_id, :value=>attribute_value, :pattern=>attribute_name})
if set_attribute_value_response['status'] == 'ok'
puts "Setting of attribute #{attribute_name} completed successfully!"
is_attributes_set = true
end
else
set_attribute_value_response = send_request('/rest/assembly/set_attributes', {:assembly_id=>service_id, :value=>attribute_value, :pattern=>attribute_id.first['id']})
service_attributes = send_request('/rest/assembly/info_about', {:about=>'attributes', :filter=>nil, :subtype=>'instance', :assembly_id=>service_id})
extract_attribute_value = service_attributes['data'].select { |x| x['value'] == attribute_value }.first['value']
if extract_attribute_value != nil
puts "Setting of attribute #{attribute_name} completed successfully!"
is_attributes_set = true
end
end
puts ""
return is_attributes_set
end
def set_attribute_on_service_level_component(service_id, attribute_name, attribute_value)
#Set attribute on particular service
puts "Set attribute:", "--------------"
is_attributes_set = false
#Get attribute id for which value will be set
service_attributes = send_request('/rest/assembly/info_about', {:about=>'attributes', :filter=>nil, :subtype=>'instance', :assembly_id=>service_id})
attribute_id = service_attributes['data'].select { |x| x['display_name'].include? attribute_name }.first['id']
#Set attribute value for given attribute id
set_attribute_value_response = send_request('/rest/assembly/set_attributes', {:assembly_id=>service_id, :value=>attribute_value, :pattern=>attribute_id})
service_attributes = send_request('/rest/assembly/info_about', {:about=>'attributes', :filter=>nil, :subtype=>'instance', :assembly_id=>service_id})
extract_attribute_value = attribute_id = service_attributes['data'].select { |x| x['display_name'].include? attribute_name }.first['value']
if extract_attribute_value == attribute_value
puts "Setting of attribute #{attribute_name} completed successfully!"
is_attributes_set = true
end
puts ""
return is_attributes_set
end
def get_attribute_value(service_id, node_name, component_name, attribute_name)
puts "Get attribute value by name:", "----------------------------"
puts "List of service attributes:"
service_attributes = send_request('/rest/assembly/info_about', {:assembly_id=>service_id, :filter=>nil, :about=>'attributes', :subtype=>'instance'})
pretty_print_JSON(service_attributes)
attributes = service_attributes['data'].select { |x| x['display_name'] == "#{node_name}/#{component_name}/#{attribute_name}" }.first
if !attributes.nil?
attribute_value = service_attributes['data'].select { |x| x['display_name'] == "#{node_name}/#{component_name}/#{attribute_name}" }.first['value']
puts "Attribute value is: #{attribute_value}"
else
puts "Some of the input parameters is incorrect or missing. Node name: #{node_name}, Component name: #{component_name}, Attribute name: #{attribute_name}"
end
puts ""
return attribute_value
end
# new client
def check_component_depedency(service_instance_name, source_component, dependency_component, type)
puts "Check component dependency:", "---------------------------"
dependency_found = false
puts "List service components with dependencies:"
components_list = send_request("/rest/api/v1/services/#{service_instance_name}/component_links", {}, 'get')
component = components_list['data'].select { |x| x['base_component'] == source_component}
if (!component.nil?)
puts "Component #{source_component} exists. Check its dependencies..."
component.each do |deps|
if (deps['dependent_component'] == dependency_component) && (deps['type'] == type)
dependency_found = true
puts "Component #{source_component} has expected dependency component #{dependency_component} with type #{type}"
else
puts "Component #{source_component} does not have expected dependency component #{dependency_component} with type #{type}"
end
end
else
puts "Component #{source_component} does not exist and therefore it does not have any dependencies"
end
puts ""
return dependency_found
end
def converge_service(service_id, max_num_of_retries=15)
puts "Converge service:", "-----------------"
service_converged = false
puts "Converge process for service with id #{service_id} started!"
find_violations = send_request('/rest/assembly/find_violations', {'assembly_id' => service_id})
create_task_response = send_request('/rest/assembly/create_task', {'assembly_id' => service_id})
if (@error_message == "")
task_id = create_task_response['data']['task_id']
puts "Task id: #{task_id}"
task_execute_response = send_request('/rest/task/execute', {'task_id' => task_id})
end_loop = false
count = 0
task_status = 'executing'
while ((task_status.include? 'executing') && (end_loop == false))
sleep 20
count += 1
response_task_status = send_request('/rest/assembly/task_status', {'assembly_id'=> service_id})
status = response_task_status['data'].first['status']
unless status.nil?
if (status.include? 'succeeded')
service_converged = true
puts "Task execution status: #{status}"
puts "Converge process finished successfully!"
end_loop = true
elsif (status.include? 'failed')
puts "Error details on subtasks:"
ap response_task_status['data']
response_task_status['data'].each do |error_message|
unless error_message['errors'].nil?
puts error_message['errors']['message']
puts error_message['errors']['type']
end
end
puts "Task execution status: #{status}"
puts "Converge process was not finished successfully! Some tasks failed!"
end_loop = true
end
puts "Task execution status: #{status}"
end
if (count > max_num_of_retries)
puts "Max number of retries reached..."
puts "Converge process was not finished successfully!"
end_loop = true
end
end
else
puts "Service was not converged successfully!"
end
puts ""
return service_converged
end
def stop_running_service(service_id)
puts "Stop running service:", "---------------------"
service_stopped = false
stop_service_response = send_request('/rest/assembly/stop', {:assembly_id => service_id})
if (stop_service_response['status'] == "ok")
puts "Service stopped successfully!"
service_stopped = true
else
puts "Service was not stopped successfully!"
end
puts ""
return service_stopped
end
def create_assembly_from_service(service_id, service_module_name, assembly_name, namespace=nil)
puts "Create assembly from service:", "-----------------------------"
assembly_created = false
create_assembly_response = send_request('/rest/assembly/promote_to_template', {:service_module_name=>service_module_name, :mode=>:create, :assembly_id=>service_id, :assembly_template_name=>assembly_name, :namespace=>namespace})
if (create_assembly_response['status'] == 'ok')
puts "Assembly #{assembly_name} created in service module #{service_module_name}"
assembly_created = true
else
puts "Assembly #{assembly_name} was not created in service module #{service_module_name}"
end
puts ""
return assembly_created
end
def netstats_check(service_id, port)
puts "Netstats check:", "---------------"
netstats_check = false
end_loop = false
count = 0
max_num_of_retries = 15
while (end_loop == false)
sleep 10
count += 1
if (count > max_num_of_retries)
puts "Max number of retries for getting netstats reached..."
end_loop = true
end
response = send_request('/rest/assembly/initiate_get_netstats', {:node_id=>nil, :assembly_id=>service_id})
pretty_print_JSON(response)
action_results_id = response['data']['action_results_id']
5.downto(1) do |i|
sleep 1
response = send_request('/rest/assembly/get_action_results', {:disable_post_processing=>false, :return_only_if_complete=>true, :action_results_id=>action_results_id, :sort_key=>"port"})
puts "Netstats check:"
pretty_print_JSON(response)
if response['data']['is_complete']
port_to_check = response['data']['results'].select { |x| x['port'] == port}.first
if (!port_to_check.nil?)
puts "Netstats check completed! Port #{port} available!"
netstats_check = true
end_loop = true
break
else
puts "Netstats check completed! Port #{port} is not available!"
netstats_check = false
break
end
end
end
end
puts ""
return netstats_check
end
def start_running_service(service_id)
puts "Start service:", "--------------"
service_started = false
response = send_request('/rest/assembly/start', {:assembly_id => service_id, :node_pattern=>nil})
pretty_print_JSON(response)
task_id = response['data']['task_id']
response = send_request('/rest/task/execute', {:task_id=>task_id})
if (response['status'] == 'ok')
end_loop = false
count = 0
max_num_of_retries = 30
while (end_loop == false)
sleep 10
count += 1
response = send_request('/rest/assembly/info_about', {:assembly_id => service_id, :subtype => 'instance', :about => 'tasks'})
puts "Start instance check:"
status = response['data'].select { |x| x['status'] == 'executing'}.first
pretty_print_JSON(status)
if (count > max_num_of_retries)
puts "Max number of retries for starting instance reached..."
end_loop = true
elsif (status.nil?)
puts "Instance started!"
service_started = true
end_loop = true
end
end
else
puts "Start instance is not completed successfully!"
end
puts ""
return service_started
end
def add_component_by_name_to_service_node(service_id, node_name, component_name)
puts "Add component to service:", "--------------------------"
component_added = false
service_nodes = send_request('/rest/assembly/info_about', {:assembly_id=>service_id, :filter=>nil, :about=>'nodes', :subtype=>'instance'})
if (service_nodes['data'].select { |x| x['display_name'] == node_name }.first)
puts "Node #{node_name} exists in service. Get node id..."
node_id = service_nodes['data'].select { |x| x['display_name'] == node_name }.first['id']
component_add_response = send_request('/rest/assembly/add_component', {:node_id=>node_id, :component_template_id=>component_name.split(":").last, :assembly_id=>service_id, :namespace=>component_name.split(":").first})
if (component_add_response['status'] == 'ok')
puts "Component #{component_name} added to service!"
component_added = true
end
else
component_add_response = send_request('/rest/assembly/add_component', {:node_id=>nil, :component_template_id=>component_name.split(":").last, :assembly_id=>service_id, :namespace=>component_name.split(":").first})
if (component_add_response['status'] == 'ok')
puts "Component #{component_name} added to service!"
component_added = true
end
end
puts ""
return component_added
end
def delete_and_destroy_service(service_id)
puts "Delete and destroy service:", "---------------------------"
service_deleted = false
delete_service_response = send_request('/rest/assembly/delete', {:assembly_id=>service_id})
if (delete_service_response['status'] == "ok")
puts "Service deleted successfully!"
service_deleted = true
else
puts "Service was not deleted successfully!"
end
puts ""
return service_deleted
end
def delete_task_status(service_id, component_to_delete, delete_type, check_component_in_task_status=true)
service_deleted = false
end_loop = false
count = 0
max_num_of_retries = 50
task_status = 'executing'
while ((task_status.include? 'executing') && (end_loop == false))
sleep 2
count += 1
response_task_status = send_request('/rest/assembly/task_status', {'assembly_id'=> service_id})
delete_status = response_task_status['data'].first['status']
if !delete_status.nil?
if check_component_in_task_status
component_delete_status = response_task_status['data'].select { |x| x['type'].include? component_to_delete }.first['status']
else
# case when performing delete action on staged service
component_delete_status = 'succeeded'
end
if (delete_status.include? "succeeded") && (component_delete_status.include? "succeeded")
service_deleted = true
task_status = delete_status
puts "Task execution status: #{delete_status}"
puts "#{delete_type} finished successfully!"
end_loop = true
end
if (delete_status.include? 'failed')
puts "Error details:"
ap response_task_status['data']
response_task_status['data'].each do |error_message|
unless error_message['errors'].nil?
puts error_message['errors']['message']
puts error_message['errors']['type']
end
end
puts "Task execution status: #{delete_status}"
puts "#{delete_type} with workflow did not finish successfully!"
task_status = delete_status
end_loop = true
end
puts "Task execution status: #{delete_status}"
else
if delete_type == 'delete_service'
# This is set to true only in case when we delete service instance
# Reason: we cannot get task status details on instance that does not exist anymore
service_deleted = true
break
end
end
if (count > max_num_of_retries)
puts "Max number of retries reached..."
puts "#{delete_type} with workflow did not finish successfully!"
break
end
end
service_deleted
end
def delete_service_with_workflow(service_id, component_to_delete, check_component_in_task_status)
puts "Delete and destroy service with workflow:", "-----------------------------------------"
service_deleted_successfully = false
delete_service_response = send_request('/rest/assembly/delete_using_workflow', {:assembly_id=>service_id, :subtype => :instance})
if delete_service_response['status'] == 'ok'
service_deleted_successfully = delete_task_status(service_id, component_to_delete, 'delete_service', check_component_in_task_status)
puts "Service was deleted successfully!"
else
puts "Service was not deleted successfully!"
end
puts ""
return service_deleted_successfully
end
def delete_node_with_workflow(service_id, node_name, component_to_delete, check_component_in_task_status)
puts "Delete node with workflow:", "----------------------------------"
node_deleted_successfully = false
delete_node_response = send_request('/rest/assembly/delete_node_using_workflow', {:assembly_id=>service_id, :subtype => :instance, :node_id => node_name})
if delete_node_response['status'] == 'ok'
node_deleted_successfully = delete_task_status(service_id, component_to_delete, 'delete_node', check_component_in_task_status)
puts "Node: #{node_name} was deleted successfully!"
else
puts "Node: #{node_name} was not deleted successfully!"
end
puts ""
return node_deleted_successfully
end
def delete_component_with_workflow(service_id, node_name, component_to_delete, check_component_in_task_status)
puts "Delete component with workflow:", "---------------------------------------"
component_deleted_successfully = false
delete_component_response = send_request('/rest/assembly/delete_component_using_workflow', {:assembly_id=>service_id, :task_action => "#{component_to_delete}.delete", :task_params => { "node" => node_name }, :component_id => component_to_delete, :noop_if_no_action => nil, :cmp_full_name => "#{node_name}/#{component_to_delete}", :node_id => node_name })
if delete_component_response['status'] == 'ok'
component_deleted_successfully = delete_task_status(service_id, component_to_delete, 'delete_component', check_component_in_task_status)
puts "Component: #{component_to_delete} was deleted successfully!"
else
puts "Component: #{component_to_delete} was not deleted successfully!"
end
puts ""
return component_deleted_successfully
end
def delete_context(context_name)
puts "Delete context:", "-----------------"
context_deleted = false
delete_context_service_response = send_request('/rest/assembly/delete', {:assembly_id=>context_name})
if (delete_context_service_response['status'] == "ok")
puts "context service deleted successfully!"
context_deleted = true
else
puts "context service was not deleted successfully!"
end
puts ""
return context_deleted
end
def push_assembly_updates(service_id, service_module)
puts "Push assembly updates:", "---------------------"
assembly_updated = false
response = send_request('/rest/assembly/promote_to_template', {:assembly_id=>service_id, :mode => 'update', :use_module_namespace => true })
pretty_print_JSON(response)
if response['status'] == 'ok' && response['data']['full_module_name'] == service_module
assembly_updated = true
end
puts ""
return assembly_updated
end
def push_component_module_updates_without_changes(service_id, component_module)
puts "Push component module updates:", "-------------------------------"
response = send_request('/rest/assembly/promote_module_updates', {:assembly_id=>service_id, :module_name => component_module, :module_type => "component_module" })
return response
end
def get_nodes(service_id)
puts "Get all nodes from service:", "-----------------------------"
nodes_list = send_request('/rest/assembly/info_about', {:assembly_id=>service_id, :node_id => nil, :component_id => nil, :subtype=>'instance', :about=>'nodes'})
nodes_list = nodes_list['data'].map! { |c| c['display_name'] }
pretty_print_JSON(nodes_list)
puts ""
return nodes_list
end
def get_components(service_id)
puts "Get all components from service:", "-----------------------------"
components_list = send_request('/rest/assembly/info_about', {:assembly_id=>service_id, :node_id => nil, :component_id => nil, :subtype=>'instance', :about=>'components'})
components_list = components_list['data'].map! { |c| c['display_name'] }
puts ""
return components_list
end
def get_cardinality(service_id, node_name)
puts "Get cardinality from service:", "-----------------------------"
cardinality = send_request('/rest/assembly/info_about', {:assembly_id=>service_id, :node_id => nil, :component_id => nil, :subtype=>'instance', :about=>'attributes', :format=>'yaml'})
content = YAML.load(cardinality['data'])
puts content
attributes = (content["nodes"]["#{node_name}/"]||{})['attributes']||{}
puts ""
return attributes['cardinality'] && attributes['cardinality'].to_i
end
def get_workflow_info(service_id)
puts "Get workflow info:", "----------------------"
workflow_info = send_request('/rest/assembly/info_about_task', {:assembly_id=>service_id, :subtype => 'instance'})
content = YAML.load(workflow_info['data'])
puts content
puts ""
return content
end
def grant_access(service_id, system_user, rsa_pub_name, ssh_key)
puts "Grant access:", "-----------------"
response = send_request('/rest/assembly/initiate_ssh_pub_access', {:agent_action => :grant_access, :assembly_id=>service_id, :system_user => system_user, :rsa_pub_name => rsa_pub_name, :rsa_pub_key => ssh_key})
pretty_print_JSON(response)
puts ""
return response
end
def revoke_access(service_id, system_user, rsa_pub_name, ssh_key)
puts "Revoke access:", "-----------------"
resp = send_request('/rest/assembly/initiate_ssh_pub_access', {:agent_action => :revoke_access, :assembly_id=>service_id, :system_user => system_user, :rsa_pub_name => rsa_pub_name, :rsa_pub_key => ssh_key})
pretty_print_JSON(resp)
response = nil
if resp['status'] != 'notok'
response = send_request('/rest/assembly/get_action_results', {:action_results_id => resp['data']['action_results_id'], :return_only_if_complete => true, :disable_post_processing => true})
puts response
else
response = resp
end
puts ""
return response
end
def list_services_by_property(key, value)
# Get list of existing workspace service instances in a specific context
puts "List service instances with #{value} value for #{key} property:", "----------------------------------------------------------------------------------"
service_instance_list = send_request('/rest/assembly/list', {:detail_level=>'nodes', :subtype=>'instance', :include_namespaces => true})
filtered_services = nil
if service_instance_list['status'] == 'ok'
filtered_services = service_instance_list['data'].select{ |x| x[key].include? value }
if filtered_services.length.zero?
puts "No service instances with #{value} value for #{key} property been found."
filtered_services = nil
else
puts "#{filtered_services.length} service instances with #{value} value for #{key} property found: "
end
else
puts "Could not get service instance list."
end
puts ''
filtered_services
end
def list_ssh_access(service_id, system_user, rsa_pub_name, nodes)
puts "List ssh access:", "---------------------"
sleep 5
response = send_request('/rest/assembly/list_ssh_access', {:assembly_id=>service_id})
pretty_print_JSON(response)
list = response['data'].select { |x| x['attributes']['linux_user'] == system_user && x['attributes']['key_name'] == rsa_pub_name && (nodes.include? x['node_name']) }
puts ""
return list.map! { |x| x['attributes']['key_name']}
end
def get_task_action_output(service_id, action_id)
puts "Get task action output:", "------------------------"
response = send_request('/rest/assembly/task_action_detail', {:assembly_id=>service_id, :message_id=>action_id})
pretty_print_JSON(response)
runs = {}
if response['status'] == "ok"
output = response['data']
output.gsub!("=","") if response['data'].include? "="
runs = output.split(/\n \n\n|\n\n\n|\n\n/)
else
puts "Task action details were not retrieved successfully!"
end
puts ""
return runs
end
def verify_flags(service_id, component_module_name, update_flag, update_saved_flag)
puts "Verify update and update saved flags:", "---------------------------------"
flags_verified = false
response = send_request('/rest/assembly/info_about', {:assembly_id=>service_id, :subtype=>:instance, :about=>'modules', :detail_to_include=>[:version_info]})
pretty_print_JSON(response)
component_module_details = response['data'].select { |x| x['display_name'] == component_module_name }.first
if !component_module_details.nil?
puts "Component module found! Check flags..."
pretty_print_JSON(component_module_details)
unless component_module_details.key?('local_copy') || component_module_details.key?('update_saved')
puts "Flags dont not exist in the output"
end
if component_module_details['local_copy'] == update_flag && component_module_details['update_saved'] == update_saved_flag
puts "Update and update saved flags match the comparison"
flags_verified = true
else
puts "Update and update saved flags does not match the comparison"
end
else
puts "Component module was not found!"
end
puts ""
flags_verified
end
end | dtk/dtk-server | test/functional/rspec/lib/mixins/assembly_and_service_operations_mixin.rb | Ruby | apache-2.0 | 51,221 |
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using DNTProfiler.Common.JsonToolkit;
using DNTProfiler.Common.Models;
using DNTProfiler.Common.Mvvm;
using DNTProfiler.Infrastructure.Core;
using DNTProfiler.Infrastructure.ScriptDomVisitors;
using DNTProfiler.Infrastructure.ViewModels;
using DNTProfiler.PluginsBase;
namespace DNTProfiler.InCorrectNullComparisons.ViewModels
{
public class MainViewModel : MainViewModelBase
{
private readonly CallbacksManagerBase _callbacksManager;
public MainViewModel(ProfilerPluginBase pluginContext)
: base(pluginContext)
{
if (Designer.IsInDesignModeStatic)
return;
setActions();
setGuiModel();
_callbacksManager = new CallbacksManagerBase(PluginContext, GuiModelData);
setEvenets();
}
private void Commands_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (Command command in e.NewItems)
{
var visitor = new NullComparisonVisitor();
foreach (var parameter in command.Parameters.Where(parameter => parameter.Value == "null"))
{
visitor.NullVariableNames.Add(parameter.Name);
}
_callbacksManager.RunAnalysisVisitorOnCommand(visitor, command);
}
break;
}
}
private void GuiModelData_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "SelectedApplicationIdentity":
_callbacksManager.ShowSelectedApplicationIdentityLocalCommands();
break;
case "SelectedExecutedCommand":
_callbacksManager.ShowSelectedCommandRelatedStackTraces();
break;
}
}
private void setActions()
{
PluginContext.Reset = () =>
{
ResetAll();
};
PluginContext.GetResults = () =>
{
return GuiModelData.RelatedCommands.ToFormattedJson();
};
}
private void setEvenets()
{
PluginContext.ProfilerData.Commands.CollectionChanged += Commands_CollectionChanged;
}
private void setGuiModel()
{
GuiModelData.PropertyChanged += GuiModelData_PropertyChanged;
}
}
} | VahidN/DNTProfiler | Plugins/DNTProfiler.InCorrectNullComparisons/ViewModels/MainViewModel.cs | C# | apache-2.0 | 2,745 |
/*!
* Bootstrap v3.3.6 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
html {
font-family: sans-serif;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%
}
body {
margin: 0
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block
}
audio,
canvas,
progress,
video {
display: inline-block;
vertical-align: baseline
}
audio:not([controls]) {
display: none;
height: 0
}
[hidden],
template {
display: none
}
a {
background-color: transparent
}
a:active,
a:hover {
outline: 0
}
abbr[title] {
border-bottom: 1px dotted
}
b,
strong {
font-weight: 700
}
dfn {
font-style: italic
}
h1 {
margin: .67em 0;
font-size: 2em
}
mark {
color: #000;
background: #ff0
}
small {
font-size: 80%
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline
}
sup {
top: -.5em
}
sub {
bottom: -.25em
}
img {
border: 0
}
svg:not(:root) {
overflow: hidden
}
figure {
margin: 1em 40px
}
hr {
height: 0;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box
}
pre {
overflow: auto
}
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em
}
button,
input,
optgroup,
select,
textarea {
margin: 0;
font: inherit;
color: inherit
}
button {
overflow: visible
}
button,
select {
text-transform: none
}
button,
html input[type=button],
input[type=reset],
input[type=submit] {
-webkit-appearance: button;
cursor: pointer
}
button[disabled],
html input[disabled] {
cursor: default
}
button::-moz-focus-inner,
input::-moz-focus-inner {
padding: 0;
border: 0
}
input {
line-height: normal
}
input[type=checkbox],
input[type=radio] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
height: auto
}
input[type=search] {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
-webkit-appearance: textfield
}
input[type=search]::-webkit-search-cancel-button,
input[type=search]::-webkit-search-decoration {
-webkit-appearance: none
}
fieldset {
padding: .35em .625em .75em;
margin: 0 2px;
border: 1px solid silver
}
legend {
padding: 0;
border: 0
}
textarea {
overflow: auto
}
optgroup {
font-weight: 700
}
table {
border-spacing: 0;
border-collapse: collapse
}
td,
th {
padding: 0
}
/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
@media print {
*,
:after,
:before {
color: #000!important;
text-shadow: none!important;
background: 0 0!important;
-webkit-box-shadow: none!important;
box-shadow: none!important
}
a,
a:visited {
text-decoration: underline
}
a[href]:after {
content: " (" attr(href) ")"
}
abbr[title]:after {
content: " (" attr(title) ")"
}
a[href^="javascript:"]:after,
a[href^="#"]:after {
content: ""
}
blockquote,
pre {
border: 1px solid #999;
page-break-inside: avoid
}
thead {
display: table-header-group
}
img,
tr {
page-break-inside: avoid
}
img {
max-width: 100%!important
}
h2,
h3,
p {
orphans: 3;
widows: 3
}
h2,
h3 {
page-break-after: avoid
}
.navbar {
display: none
}
.btn>.caret,
.dropup>.btn>.caret {
border-top-color: #000!important
}
.label {
border: 1px solid #000
}
.table {
border-collapse: collapse!important
}
.table td,
.table th {
background-color: #fff!important
}
.table-bordered td,
.table-bordered th {
border: 1px solid #ddd!important
}
}
@font-face {
font-family: 'Glyphicons Halflings';
src: url(../fonts/glyphicons-halflings-regular.eot);
src: url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'), url(../fonts/glyphicons-halflings-regular.woff2) format('woff2'), url(../fonts/glyphicons-halflings-regular.woff) format('woff'), url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'), url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')
}
.glyphicon {
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: 400;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale
}
.glyphicon-asterisk:before {
content: "\002a"
}
.glyphicon-plus:before {
content: "\002b"
}
.glyphicon-eur:before,
.glyphicon-euro:before {
content: "\20ac"
}
.glyphicon-minus:before {
content: "\2212"
}
.glyphicon-cloud:before {
content: "\2601"
}
.glyphicon-envelope:before {
content: "\2709"
}
.glyphicon-pencil:before {
content: "\270f"
}
.glyphicon-glass:before {
content: "\e001"
}
.glyphicon-music:before {
content: "\e002"
}
.glyphicon-search:before {
content: "\e003"
}
.glyphicon-heart:before {
content: "\e005"
}
.glyphicon-star:before {
content: "\e006"
}
.glyphicon-star-empty:before {
content: "\e007"
}
.glyphicon-user:before {
content: "\e008"
}
.glyphicon-film:before {
content: "\e009"
}
.glyphicon-th-large:before {
content: "\e010"
}
.glyphicon-th:before {
content: "\e011"
}
.glyphicon-th-list:before {
content: "\e012"
}
.glyphicon-ok:before {
content: "\e013"
}
.glyphicon-remove:before {
content: "\e014"
}
.glyphicon-zoom-in:before {
content: "\e015"
}
.glyphicon-zoom-out:before {
content: "\e016"
}
.glyphicon-off:before {
content: "\e017"
}
.glyphicon-signal:before {
content: "\e018"
}
.glyphicon-cog:before {
content: "\e019"
}
.glyphicon-trash:before {
content: "\e020"
}
.glyphicon-home:before {
content: "\e021"
}
.glyphicon-file:before {
content: "\e022"
}
.glyphicon-time:before {
content: "\e023"
}
.glyphicon-road:before {
content: "\e024"
}
.glyphicon-download-alt:before {
content: "\e025"
}
.glyphicon-download:before {
content: "\e026"
}
.glyphicon-upload:before {
content: "\e027"
}
.glyphicon-inbox:before {
content: "\e028"
}
.glyphicon-play-circle:before {
content: "\e029"
}
.glyphicon-repeat:before {
content: "\e030"
}
.glyphicon-refresh:before {
content: "\e031"
}
.glyphicon-list-alt:before {
content: "\e032"
}
.glyphicon-lock:before {
content: "\e033"
}
.glyphicon-flag:before {
content: "\e034"
}
.glyphicon-headphones:before {
content: "\e035"
}
.glyphicon-volume-off:before {
content: "\e036"
}
.glyphicon-volume-down:before {
content: "\e037"
}
.glyphicon-volume-up:before {
content: "\e038"
}
.glyphicon-qrcode:before {
content: "\e039"
}
.glyphicon-barcode:before {
content: "\e040"
}
.glyphicon-tag:before {
content: "\e041"
}
.glyphicon-tags:before {
content: "\e042"
}
.glyphicon-book:before {
content: "\e043"
}
.glyphicon-bookmark:before {
content: "\e044"
}
.glyphicon-print:before {
content: "\e045"
}
.glyphicon-camera:before {
content: "\e046"
}
.glyphicon-font:before {
content: "\e047"
}
.glyphicon-bold:before {
content: "\e048"
}
.glyphicon-italic:before {
content: "\e049"
}
.glyphicon-text-height:before {
content: "\e050"
}
.glyphicon-text-width:before {
content: "\e051"
}
.glyphicon-align-left:before {
content: "\e052"
}
.glyphicon-align-center:before {
content: "\e053"
}
.glyphicon-align-right:before {
content: "\e054"
}
.glyphicon-align-justify:before {
content: "\e055"
}
.glyphicon-list:before {
content: "\e056"
}
.glyphicon-indent-left:before {
content: "\e057"
}
.glyphicon-indent-right:before {
content: "\e058"
}
.glyphicon-facetime-video:before {
content: "\e059"
}
.glyphicon-picture:before {
content: "\e060"
}
.glyphicon-map-marker:before {
content: "\e062"
}
.glyphicon-adjust:before {
content: "\e063"
}
.glyphicon-tint:before {
content: "\e064"
}
.glyphicon-edit:before {
content: "\e065"
}
.glyphicon-share:before {
content: "\e066"
}
.glyphicon-check:before {
content: "\e067"
}
.glyphicon-move:before {
content: "\e068"
}
.glyphicon-step-backward:before {
content: "\e069"
}
.glyphicon-fast-backward:before {
content: "\e070"
}
.glyphicon-backward:before {
content: "\e071"
}
.glyphicon-play:before {
content: "\e072"
}
.glyphicon-pause:before {
content: "\e073"
}
.glyphicon-stop:before {
content: "\e074"
}
.glyphicon-forward:before {
content: "\e075"
}
.glyphicon-fast-forward:before {
content: "\e076"
}
.glyphicon-step-forward:before {
content: "\e077"
}
.glyphicon-eject:before {
content: "\e078"
}
.glyphicon-chevron-left:before {
content: "\e079"
}
.glyphicon-chevron-right:before {
content: "\e080"
}
.glyphicon-plus-sign:before {
content: "\e081"
}
.glyphicon-minus-sign:before {
content: "\e082"
}
.glyphicon-remove-sign:before {
content: "\e083"
}
.glyphicon-ok-sign:before {
content: "\e084"
}
.glyphicon-question-sign:before {
content: "\e085"
}
.glyphicon-info-sign:before {
content: "\e086"
}
.glyphicon-screenshot:before {
content: "\e087"
}
.glyphicon-remove-circle:before {
content: "\e088"
}
.glyphicon-ok-circle:before {
content: "\e089"
}
.glyphicon-ban-circle:before {
content: "\e090"
}
.glyphicon-arrow-left:before {
content: "\e091"
}
.glyphicon-arrow-right:before {
content: "\e092"
}
.glyphicon-arrow-up:before {
content: "\e093"
}
.glyphicon-arrow-down:before {
content: "\e094"
}
.glyphicon-share-alt:before {
content: "\e095"
}
.glyphicon-resize-full:before {
content: "\e096"
}
.glyphicon-resize-small:before {
content: "\e097"
}
.glyphicon-exclamation-sign:before {
content: "\e101"
}
.glyphicon-gift:before {
content: "\e102"
}
.glyphicon-leaf:before {
content: "\e103"
}
.glyphicon-fire:before {
content: "\e104"
}
.glyphicon-eye-open:before {
content: "\e105"
}
.glyphicon-eye-close:before {
content: "\e106"
}
.glyphicon-warning-sign:before {
content: "\e107"
}
.glyphicon-plane:before {
content: "\e108"
}
.glyphicon-calendar:before {
content: "\e109"
}
.glyphicon-random:before {
content: "\e110"
}
.glyphicon-comment:before {
content: "\e111"
}
.glyphicon-magnet:before {
content: "\e112"
}
.glyphicon-chevron-up:before {
content: "\e113"
}
.glyphicon-chevron-down:before {
content: "\e114"
}
.glyphicon-retweet:before {
content: "\e115"
}
.glyphicon-shopping-cart:before {
content: "\e116"
}
.glyphicon-folder-close:before {
content: "\e117"
}
.glyphicon-folder-open:before {
content: "\e118"
}
.glyphicon-resize-vertical:before {
content: "\e119"
}
.glyphicon-resize-horizontal:before {
content: "\e120"
}
.glyphicon-hdd:before {
content: "\e121"
}
.glyphicon-bullhorn:before {
content: "\e122"
}
.glyphicon-bell:before {
content: "\e123"
}
.glyphicon-certificate:before {
content: "\e124"
}
.glyphicon-thumbs-up:before {
content: "\e125"
}
.glyphicon-thumbs-down:before {
content: "\e126"
}
.glyphicon-hand-right:before {
content: "\e127"
}
.glyphicon-hand-left:before {
content: "\e128"
}
.glyphicon-hand-up:before {
content: "\e129"
}
.glyphicon-hand-down:before {
content: "\e130"
}
.glyphicon-circle-arrow-right:before {
content: "\e131"
}
.glyphicon-circle-arrow-left:before {
content: "\e132"
}
.glyphicon-circle-arrow-up:before {
content: "\e133"
}
.glyphicon-circle-arrow-down:before {
content: "\e134"
}
.glyphicon-globe:before {
content: "\e135"
}
.glyphicon-wrench:before {
content: "\e136"
}
.glyphicon-tasks:before {
content: "\e137"
}
.glyphicon-filter:before {
content: "\e138"
}
.glyphicon-briefcase:before {
content: "\e139"
}
.glyphicon-fullscreen:before {
content: "\e140"
}
.glyphicon-dashboard:before {
content: "\e141"
}
.glyphicon-paperclip:before {
content: "\e142"
}
.glyphicon-heart-empty:before {
content: "\e143"
}
.glyphicon-link:before {
content: "\e144"
}
.glyphicon-phone:before {
content: "\e145"
}
.glyphicon-pushpin:before {
content: "\e146"
}
.glyphicon-usd:before {
content: "\e148"
}
.glyphicon-gbp:before {
content: "\e149"
}
.glyphicon-sort:before {
content: "\e150"
}
.glyphicon-sort-by-alphabet:before {
content: "\e151"
}
.glyphicon-sort-by-alphabet-alt:before {
content: "\e152"
}
.glyphicon-sort-by-order:before {
content: "\e153"
}
.glyphicon-sort-by-order-alt:before {
content: "\e154"
}
.glyphicon-sort-by-attributes:before {
content: "\e155"
}
.glyphicon-sort-by-attributes-alt:before {
content: "\e156"
}
.glyphicon-unchecked:before {
content: "\e157"
}
.glyphicon-expand:before {
content: "\e158"
}
.glyphicon-collapse-down:before {
content: "\e159"
}
.glyphicon-collapse-up:before {
content: "\e160"
}
.glyphicon-log-in:before {
content: "\e161"
}
.glyphicon-flash:before {
content: "\e162"
}
.glyphicon-log-out:before {
content: "\e163"
}
.glyphicon-new-window:before {
content: "\e164"
}
.glyphicon-record:before {
content: "\e165"
}
.glyphicon-save:before {
content: "\e166"
}
.glyphicon-open:before {
content: "\e167"
}
.glyphicon-saved:before {
content: "\e168"
}
.glyphicon-import:before {
content: "\e169"
}
.glyphicon-export:before {
content: "\e170"
}
.glyphicon-send:before {
content: "\e171"
}
.glyphicon-floppy-disk:before {
content: "\e172"
}
.glyphicon-floppy-saved:before {
content: "\e173"
}
.glyphicon-floppy-remove:before {
content: "\e174"
}
.glyphicon-floppy-save:before {
content: "\e175"
}
.glyphicon-floppy-open:before {
content: "\e176"
}
.glyphicon-credit-card:before {
content: "\e177"
}
.glyphicon-transfer:before {
content: "\e178"
}
.glyphicon-cutlery:before {
content: "\e179"
}
.glyphicon-header:before {
content: "\e180"
}
.glyphicon-compressed:before {
content: "\e181"
}
.glyphicon-earphone:before {
content: "\e182"
}
.glyphicon-phone-alt:before {
content: "\e183"
}
.glyphicon-tower:before {
content: "\e184"
}
.glyphicon-stats:before {
content: "\e185"
}
.glyphicon-sd-video:before {
content: "\e186"
}
.glyphicon-hd-video:before {
content: "\e187"
}
.glyphicon-subtitles:before {
content: "\e188"
}
.glyphicon-sound-stereo:before {
content: "\e189"
}
.glyphicon-sound-dolby:before {
content: "\e190"
}
.glyphicon-sound-5-1:before {
content: "\e191"
}
.glyphicon-sound-6-1:before {
content: "\e192"
}
.glyphicon-sound-7-1:before {
content: "\e193"
}
.glyphicon-copyright-mark:before {
content: "\e194"
}
.glyphicon-registration-mark:before {
content: "\e195"
}
.glyphicon-cloud-download:before {
content: "\e197"
}
.glyphicon-cloud-upload:before {
content: "\e198"
}
.glyphicon-tree-conifer:before {
content: "\e199"
}
.glyphicon-tree-deciduous:before {
content: "\e200"
}
.glyphicon-cd:before {
content: "\e201"
}
.glyphicon-save-file:before {
content: "\e202"
}
.glyphicon-open-file:before {
content: "\e203"
}
.glyphicon-level-up:before {
content: "\e204"
}
.glyphicon-copy:before {
content: "\e205"
}
.glyphicon-paste:before {
content: "\e206"
}
.glyphicon-alert:before {
content: "\e209"
}
.glyphicon-equalizer:before {
content: "\e210"
}
.glyphicon-king:before {
content: "\e211"
}
.glyphicon-queen:before {
content: "\e212"
}
.glyphicon-pawn:before {
content: "\e213"
}
.glyphicon-bishop:before {
content: "\e214"
}
.glyphicon-knight:before {
content: "\e215"
}
.glyphicon-baby-formula:before {
content: "\e216"
}
.glyphicon-tent:before {
content: "\26fa"
}
.glyphicon-blackboard:before {
content: "\e218"
}
.glyphicon-bed:before {
content: "\e219"
}
.glyphicon-apple:before {
content: "\f8ff"
}
.glyphicon-erase:before {
content: "\e221"
}
.glyphicon-hourglass:before {
content: "\231b"
}
.glyphicon-lamp:before {
content: "\e223"
}
.glyphicon-duplicate:before {
content: "\e224"
}
.glyphicon-piggy-bank:before {
content: "\e225"
}
.glyphicon-scissors:before {
content: "\e226"
}
.glyphicon-bitcoin:before {
content: "\e227"
}
.glyphicon-btc:before {
content: "\e227"
}
.glyphicon-xbt:before {
content: "\e227"
}
.glyphicon-yen:before {
content: "\00a5"
}
.glyphicon-jpy:before {
content: "\00a5"
}
.glyphicon-ruble:before {
content: "\20bd"
}
.glyphicon-rub:before {
content: "\20bd"
}
.glyphicon-scale:before {
content: "\e230"
}
.glyphicon-ice-lolly:before {
content: "\e231"
}
.glyphicon-ice-lolly-tasted:before {
content: "\e232"
}
.glyphicon-education:before {
content: "\e233"
}
.glyphicon-option-horizontal:before {
content: "\e234"
}
.glyphicon-option-vertical:before {
content: "\e235"
}
.glyphicon-menu-hamburger:before {
content: "\e236"
}
.glyphicon-modal-window:before {
content: "\e237"
}
.glyphicon-oil:before {
content: "\e238"
}
.glyphicon-grain:before {
content: "\e239"
}
.glyphicon-sunglasses:before {
content: "\e240"
}
.glyphicon-text-size:before {
content: "\e241"
}
.glyphicon-text-color:before {
content: "\e242"
}
.glyphicon-text-background:before {
content: "\e243"
}
.glyphicon-object-align-top:before {
content: "\e244"
}
.glyphicon-object-align-bottom:before {
content: "\e245"
}
.glyphicon-object-align-horizontal:before {
content: "\e246"
}
.glyphicon-object-align-left:before {
content: "\e247"
}
.glyphicon-object-align-vertical:before {
content: "\e248"
}
.glyphicon-object-align-right:before {
content: "\e249"
}
.glyphicon-triangle-right:before {
content: "\e250"
}
.glyphicon-triangle-left:before {
content: "\e251"
}
.glyphicon-triangle-bottom:before {
content: "\e252"
}
.glyphicon-triangle-top:before {
content: "\e253"
}
.glyphicon-console:before {
content: "\e254"
}
.glyphicon-superscript:before {
content: "\e255"
}
.glyphicon-subscript:before {
content: "\e256"
}
.glyphicon-menu-left:before {
content: "\e257"
}
.glyphicon-menu-right:before {
content: "\e258"
}
.glyphicon-menu-down:before {
content: "\e259"
}
.glyphicon-menu-up:before {
content: "\e260"
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box
}
:after,
:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box
}
html {
font-size: 10px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0)
}
body {
/* font-family: "Arimo", "Segoe UI", Helvetica, Arial, sans-serif;
*/ font-family: "Roboto", "Open Sans", Helvetica, Arial, sans-serif;
font-size: 15px;
line-height: 1.42857143;
color: #000000;
background-color: #fff
}
button,
input,
select,
textarea {
font-family: inherit;
font-size: inherit;
line-height: inherit
}
a {
color: #337ab7;
text-decoration: none
}
a:focus,
a:hover {
color: #23527c;
text-decoration: underline
}
a:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px
}
figure {
margin: 0
}
img {
vertical-align: middle
}
.carousel-inner>.item>a>img,
.carousel-inner>.item>img,
.img-responsive,
.thumbnail a>img,
.thumbnail>img {
display: block;
max-width: 100%;
height: auto
}
.img-rounded {
border-radius: 6px
}
.img-thumbnail {
display: inline-block;
max-width: 100%;
height: auto;
padding: 4px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: all .2s ease-in-out;
-o-transition: all .2s ease-in-out;
transition: all .2s ease-in-out
}
.img-circle {
border-radius: 50%
}
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eee
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0
}
.sr-only-focusable:active,
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto
}
[role=button] {
cursor: pointer
}
.h1,
.h2,
.h3,
.h4,
.h5,
.h6,
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: inherit;
font-weight: 500;
line-height: 1;
color: inherit
}
.h1 .small,
.h1 small,
.h2 .small,
.h2 small,
.h3 .small,
.h3 small,
.h4 .small,
.h4 small,
.h5 .small,
.h5 small,
.h6 .small,
.h6 small,
h1 .small,
h1 small,
h2 .small,
h2 small,
h3 .small,
h3 small,
h4 .small,
h4 small,
h5 .small,
h5 small,
h6 .small,
h6 small {
font-weight: 400;
line-height: 1;
color: #777
}
.h1,
.h2,
.h3,
h1,
h2,
h3 {
margin-top: 20px;
margin-bottom: 10px
}
.h1 .small,
.h1 small,
.h2 .small,
.h2 small,
.h3 .small,
.h3 small,
h1 .small,
h1 small,
h2 .small,
h2 small,
h3 .small,
h3 small {
font-size: 65%
}
.h4,
.h5,
.h6,
h4,
h5,
h6 {
margin-top: 10px;
margin-bottom: 10px
}
.h4 .small,
.h4 small,
.h5 .small,
.h5 small,
.h6 .small,
.h6 small,
h4 .small,
h4 small,
h5 .small,
h5 small,
h6 .small,
h6 small {
font-size: 75%
}
.h1,
h1 {
font-size: 36px
}
.h2,
h2 {
font-size: 30px
}
.h3,
h3 {
font-size: 24px
}
.h4,
h4 {
font-size: 18px
}
.h5,
h5 {
font-size: 14px
}
.h6,
h6 {
font-size: 12px
}
p {
margin: 0 0 10px
}
.lead {
margin-bottom: 20px;
font-size: 16px;
font-weight: 300;
line-height: 1.4
}
@media (min-width:768px) {
.lead {
font-size: 21px
}
}
.small,
small {
font-size: 85%
}
.mark,
mark {
padding: .2em;
background-color: #fcf8e3
}
.text-left {
text-align: left
}
.text-right {
text-align: right
}
.text-center {
text-align: center
}
.text-justify {
text-align: justify
}
.text-nowrap {
white-space: nowrap
}
.text-lowercase {
text-transform: lowercase
}
.text-uppercase {
text-transform: uppercase
}
.text-capitalize {
text-transform: capitalize
}
.text-muted {
color: #777
}
.text-primary {
color: #337ab7
}
a.text-primary:focus,
a.text-primary:hover {
color: #286090
}
.text-success {
color: #3c763d
}
a.text-success:focus,
a.text-success:hover {
color: #2b542c
}
.text-info {
color: #31708f
}
a.text-info:focus,
a.text-info:hover {
color: #245269
}
.text-warning {
color: #8a6d3b
}
a.text-warning:focus,
a.text-warning:hover {
color: #66512c
}
.text-danger {
color: #a94442
}
a.text-danger:focus,
a.text-danger:hover {
color: #843534
}
.bg-primary {
color: #fff;
background-color: #337ab7
}
a.bg-primary:focus,
a.bg-primary:hover {
background-color: #286090
}
.bg-success {
background-color: #dff0d8
}
a.bg-success:focus,
a.bg-success:hover {
background-color: #c1e2b3
}
.bg-info {
background-color: #d9edf7
}
a.bg-info:focus,
a.bg-info:hover {
background-color: #afd9ee
}
.bg-warning {
background-color: #fcf8e3
}
a.bg-warning:focus,
a.bg-warning:hover {
background-color: #f7ecb5
}
.bg-danger {
background-color: #f2dede
}
a.bg-danger:focus,
a.bg-danger:hover {
background-color: #e4b9b9
}
.page-header {
padding-bottom: 9px;
margin: 40px 0 20px;
border-bottom: 1px solid #eee
}
ol,
ul {
margin-top: 0;
margin-bottom: 10px
}
ol ol,
ol ul,
ul ol,
ul ul {
margin-bottom: 0
}
.list-unstyled {
padding-left: 0;
list-style: none
}
.list-inline {
padding-left: 0;
margin-left: -5px;
list-style: none
}
.list-inline>li {
display: inline-block;
padding-right: 5px;
padding-left: 5px
}
dl {
margin-top: 0;
margin-bottom: 20px
}
dd,
dt {
line-height: 1.42857143
}
dt {
font-weight: 700
}
dd {
margin-left: 0
}
@media (min-width:768px) {
.dl-horizontal dt {
float: left;
width: 160px;
overflow: hidden;
clear: left;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap
}
.dl-horizontal dd {
margin-left: 180px
}
}
abbr[data-original-title],
abbr[title] {
cursor: help;
border-bottom: 1px dotted #777
}
.initialism {
font-size: 90%;
text-transform: uppercase
}
blockquote {
padding: 10px 20px;
margin: 0 0 20px;
font-size: 17.5px;
border-left: 5px solid #eee
}
blockquote ol:last-child,
blockquote p:last-child,
blockquote ul:last-child {
margin-bottom: 0
}
blockquote .small,
blockquote footer,
blockquote small {
display: block;
font-size: 80%;
line-height: 1.42857143;
color: #777
}
blockquote .small:before,
blockquote footer:before,
blockquote small:before {
content: '\2014 \00A0'
}
.blockquote-reverse,
blockquote.pull-right {
padding-right: 15px;
padding-left: 0;
text-align: right;
border-right: 5px solid #eee;
border-left: 0
}
.blockquote-reverse .small:before,
.blockquote-reverse footer:before,
.blockquote-reverse small:before,
blockquote.pull-right .small:before,
blockquote.pull-right footer:before,
blockquote.pull-right small:before {
content: ''
}
.blockquote-reverse .small:after,
.blockquote-reverse footer:after,
.blockquote-reverse small:after,
blockquote.pull-right .small:after,
blockquote.pull-right footer:after,
blockquote.pull-right small:after {
content: '\00A0 \2014'
}
address {
margin-bottom: 20px;
font-style: normal;
line-height: 1.42857143
}
code,
kbd,
pre,
samp {
font-family: Menlo, Monaco, Consolas, "Courier New", monospace
}
code {
padding: 2px 4px;
font-size: 90%;
color: #c7254e;
background-color: #f9f2f4;
border-radius: 4px
}
kbd {
padding: 2px 4px;
font-size: 90%;
color: #fff;
background-color: #333;
border-radius: 3px;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25)
}
kbd kbd {
padding: 0;
font-size: 100%;
font-weight: 700;
-webkit-box-shadow: none;
box-shadow: none
}
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
line-height: 1.42857143;
color: #333;
word-break: break-all;
word-wrap: break-word;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px
}
pre code {
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre-wrap;
background-color: transparent;
border-radius: 0
}
.pre-scrollable {
max-height: 340px;
overflow-y: scroll
}
.container {
padding-right: 30px;
padding-left: 30px;
margin-right: auto;
margin-left: auto
}
@media (min-width:768px) {
.container {
/* width: 750px*/
/* padding-top: 30px;
padding-bottom: 30px*/
}
}
@media (min-width:992px) {
.container {
width: 970px
}
}
@media (min-width:1200px) {
.container {
/* margin-top:30px;
margin-bottom:30px;*/
width: 100%;
max-width: auto
}
}
.container-fluid {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto
}
.row {
margin-right: -15px;
margin-left: -15px
}
.col-lg-1,
.col-lg-10,
.col-lg-11,
.col-lg-12,
.col-lg-2,
.col-lg-3,
.col-lg-4,
.col-lg-5,
.col-lg-6,
.col-lg-7,
.col-lg-8,
.col-lg-9,
.col-md-1,
.col-md-10,
.col-md-11,
.col-md-12,
.col-md-2,
.col-md-3,
.col-md-4,
.col-md-5,
.col-md-6,
.col-md-7,
.col-md-8,
.col-md-9,
.col-sm-1,
.col-sm-10,
.col-sm-11,
.col-sm-12,
.col-sm-2,
.col-sm-3,
.col-sm-4,
.col-sm-5,
.col-sm-6,
.col-sm-7,
.col-sm-8,
.col-sm-9,
.col-xs-1,
.col-xs-10,
.col-xs-11,
.col-xs-12,
.col-xs-2,
.col-xs-3,
.col-xs-4,
.col-xs-5,
.col-xs-6,
.col-xs-7,
.col-xs-8,
.col-xs-9 {
position: relative;
min-height: 1px;
padding-right: 15px;
padding-left: 15px
}
.col-xs-1,
.col-xs-10,
.col-xs-11,
.col-xs-12,
.col-xs-2,
.col-xs-3,
.col-xs-4,
.col-xs-5,
.col-xs-6,
.col-xs-7,
.col-xs-8,
.col-xs-9 {
float: left
}
.col-xs-12 {
width: 100%
}
.col-xs-11 {
width: 91.66666667%
}
.col-xs-10 {
width: 83.33333333%
}
.col-xs-9 {
width: 75%
}
.col-xs-8 {
width: 66.66666667%
}
.col-xs-7 {
width: 58.33333333%
}
.col-xs-6 {
width: 50%
}
.col-xs-5 {
width: 41.66666667%
}
.col-xs-4 {
width: 33.33333333%
}
.col-xs-3 {
width: 25%
}
.col-xs-2 {
width: 16.66666667%
}
.col-xs-1 {
width: 8.33333333%
}
.col-xs-pull-12 {
right: 100%
}
.col-xs-pull-11 {
right: 91.66666667%
}
.col-xs-pull-10 {
right: 83.33333333%
}
.col-xs-pull-9 {
right: 75%
}
.col-xs-pull-8 {
right: 66.66666667%
}
.col-xs-pull-7 {
right: 58.33333333%
}
.col-xs-pull-6 {
right: 50%
}
.col-xs-pull-5 {
right: 41.66666667%
}
.col-xs-pull-4 {
right: 33.33333333%
}
.col-xs-pull-3 {
right: 25%
}
.col-xs-pull-2 {
right: 16.66666667%
}
.col-xs-pull-1 {
right: 8.33333333%
}
.col-xs-pull-0 {
right: auto
}
.col-xs-push-12 {
left: 100%
}
.col-xs-push-11 {
left: 91.66666667%
}
.col-xs-push-10 {
left: 83.33333333%
}
.col-xs-push-9 {
left: 75%
}
.col-xs-push-8 {
left: 66.66666667%
}
.col-xs-push-7 {
left: 58.33333333%
}
.col-xs-push-6 {
left: 50%
}
.col-xs-push-5 {
left: 41.66666667%
}
.col-xs-push-4 {
left: 33.33333333%
}
.col-xs-push-3 {
left: 25%
}
.col-xs-push-2 {
left: 16.66666667%
}
.col-xs-push-1 {
left: 8.33333333%
}
.col-xs-push-0 {
left: auto
}
.col-xs-offset-12 {
margin-left: 100%
}
.col-xs-offset-11 {
margin-left: 91.66666667%
}
.col-xs-offset-10 {
margin-left: 83.33333333%
}
.col-xs-offset-9 {
margin-left: 75%
}
.col-xs-offset-8 {
margin-left: 66.66666667%
}
.col-xs-offset-7 {
margin-left: 58.33333333%
}
.col-xs-offset-6 {
margin-left: 50%
}
.col-xs-offset-5 {
margin-left: 41.66666667%
}
.col-xs-offset-4 {
margin-left: 33.33333333%
}
.col-xs-offset-3 {
margin-left: 25%
}
.col-xs-offset-2 {
margin-left: 16.66666667%
}
.col-xs-offset-1 {
margin-left: 8.33333333%
}
.col-xs-offset-0 {
margin-left: 0
}
@media (min-width:768px) {
.col-sm-1,
.col-sm-10,
.col-sm-11,
.col-sm-12,
.col-sm-2,
.col-sm-3,
.col-sm-4,
.col-sm-5,
.col-sm-6,
.col-sm-7,
.col-sm-8,
.col-sm-9 {
float: left
}
.col-sm-12 {
width: 100%
}
.col-sm-11 {
width: 91.66666667%
}
.col-sm-10 {
width: 83.33333333%
}
.col-sm-9 {
width: 75%
}
.col-sm-8 {
width: 66.66666667%
}
.col-sm-7 {
width: 58.33333333%
}
.col-sm-6 {
width: 50%
}
.col-sm-5 {
width: 41.66666667%
}
.col-sm-4 {
width: 33.33333333%
}
.col-sm-3 {
width: 25%
}
.col-sm-2 {
width: 16.66666667%
}
.col-sm-1 {
width: 8.33333333%
}
.col-sm-pull-12 {
right: 100%
}
.col-sm-pull-11 {
right: 91.66666667%
}
.col-sm-pull-10 {
right: 83.33333333%
}
.col-sm-pull-9 {
right: 75%
}
.col-sm-pull-8 {
right: 66.66666667%
}
.col-sm-pull-7 {
right: 58.33333333%
}
.col-sm-pull-6 {
right: 50%
}
.col-sm-pull-5 {
right: 41.66666667%
}
.col-sm-pull-4 {
right: 33.33333333%
}
.col-sm-pull-3 {
right: 25%
}
.col-sm-pull-2 {
right: 16.66666667%
}
.col-sm-pull-1 {
right: 8.33333333%
}
.col-sm-pull-0 {
right: auto
}
.col-sm-push-12 {
left: 100%
}
.col-sm-push-11 {
left: 91.66666667%
}
.col-sm-push-10 {
left: 83.33333333%
}
.col-sm-push-9 {
left: 75%
}
.col-sm-push-8 {
left: 66.66666667%
}
.col-sm-push-7 {
left: 58.33333333%
}
.col-sm-push-6 {
left: 50%
}
.col-sm-push-5 {
left: 41.66666667%
}
.col-sm-push-4 {
left: 33.33333333%
}
.col-sm-push-3 {
left: 25%
}
.col-sm-push-2 {
left: 16.66666667%
}
.col-sm-push-1 {
left: 8.33333333%
}
.col-sm-push-0 {
left: auto
}
.col-sm-offset-12 {
margin-left: 100%
}
.col-sm-offset-11 {
margin-left: 91.66666667%
}
.col-sm-offset-10 {
margin-left: 83.33333333%
}
.col-sm-offset-9 {
margin-left: 75%
}
.col-sm-offset-8 {
margin-left: 66.66666667%
}
.col-sm-offset-7 {
margin-left: 58.33333333%
}
.col-sm-offset-6 {
margin-left: 50%
}
.col-sm-offset-5 {
margin-left: 41.66666667%
}
.col-sm-offset-4 {
margin-left: 33.33333333%
}
.col-sm-offset-3 {
margin-left: 25%
}
.col-sm-offset-2 {
margin-left: 16.66666667%
}
.col-sm-offset-1 {
margin-left: 8.33333333%
}
.col-sm-offset-0 {
margin-left: 0
}
}
@media (min-width:992px) {
.col-md-1,
.col-md-10,
.col-md-11,
.col-md-12,
.col-md-2,
.col-md-3,
.col-md-4,
.col-md-5,
.col-md-6,
.col-md-7,
.col-md-8,
.col-md-9 {
float: left
}
.col-md-12 {
width: 100%
}
.col-md-11 {
width: 91.66666667%
}
.col-md-10 {
width: 83.33333333%
}
.col-md-9 {
width: 75%
}
.col-md-8 {
width: 66.66666667%
}
.col-md-7 {
width: 58.33333333%
}
.col-md-6 {
width: 50%
}
.col-md-5 {
width: 41.66666667%
}
.col-md-4 {
width: 33.33333333%
}
.col-md-3 {
width: 25%
}
.col-md-2 {
width: 16.66666667%
}
.col-md-1 {
width: 8.33333333%
}
.col-md-pull-12 {
right: 100%
}
.col-md-pull-11 {
right: 91.66666667%
}
.col-md-pull-10 {
right: 83.33333333%
}
.col-md-pull-9 {
right: 75%
}
.col-md-pull-8 {
right: 66.66666667%
}
.col-md-pull-7 {
right: 58.33333333%
}
.col-md-pull-6 {
right: 50%
}
.col-md-pull-5 {
right: 41.66666667%
}
.col-md-pull-4 {
right: 33.33333333%
}
.col-md-pull-3 {
right: 25%
}
.col-md-pull-2 {
right: 16.66666667%
}
.col-md-pull-1 {
right: 8.33333333%
}
.col-md-pull-0 {
right: auto
}
.col-md-push-12 {
left: 100%
}
.col-md-push-11 {
left: 91.66666667%
}
.col-md-push-10 {
left: 83.33333333%
}
.col-md-push-9 {
left: 75%
}
.col-md-push-8 {
left: 66.66666667%
}
.col-md-push-7 {
left: 58.33333333%
}
.col-md-push-6 {
left: 50%
}
.col-md-push-5 {
left: 41.66666667%
}
.col-md-push-4 {
left: 33.33333333%
}
.col-md-push-3 {
left: 25%
}
.col-md-push-2 {
left: 16.66666667%
}
.col-md-push-1 {
left: 8.33333333%
}
.col-md-push-0 {
left: auto
}
.col-md-offset-12 {
margin-left: 100%
}
.col-md-offset-11 {
margin-left: 91.66666667%
}
.col-md-offset-10 {
margin-left: 83.33333333%
}
.col-md-offset-9 {
margin-left: 75%
}
.col-md-offset-8 {
margin-left: 66.66666667%
}
.col-md-offset-7 {
margin-left: 58.33333333%
}
.col-md-offset-6 {
margin-left: 50%
}
.col-md-offset-5 {
margin-left: 41.66666667%
}
.col-md-offset-4 {
margin-left: 33.33333333%
}
.col-md-offset-3 {
margin-left: 25%
}
.col-md-offset-2 {
margin-left: 16.66666667%
}
.col-md-offset-1 {
margin-left: 8.33333333%
}
.col-md-offset-0 {
margin-left: 0
}
}
@media (min-width:1200px) {
.col-lg-1,
.col-lg-10,
.col-lg-11,
.col-lg-12,
.col-lg-2,
.col-lg-3,
.col-lg-4,
.col-lg-5,
.col-lg-6,
.col-lg-7,
.col-lg-8,
.col-lg-9 {
float: left
}
.col-lg-12 {
width: 100%
}
.col-lg-11 {
width: 91.66666667%
}
.col-lg-10 {
width: 83.33333333%
}
.col-lg-9 {
width: 75%
}
.col-lg-8 {
width: 66.66666667%
}
.col-lg-7 {
width: 58.33333333%
}
.col-lg-6 {
width: 50%
}
.col-lg-5 {
width: 41.66666667%
}
.col-lg-4 {
width: 33.33333333%
}
.col-lg-3 {
width: 25%
}
.col-lg-2 {
width: 16.66666667%
}
.col-lg-1 {
width: 8.33333333%
}
.col-lg-pull-12 {
right: 100%
}
.col-lg-pull-11 {
right: 91.66666667%
}
.col-lg-pull-10 {
right: 83.33333333%
}
.col-lg-pull-9 {
right: 75%
}
.col-lg-pull-8 {
right: 66.66666667%
}
.col-lg-pull-7 {
right: 58.33333333%
}
.col-lg-pull-6 {
right: 50%
}
.col-lg-pull-5 {
right: 41.66666667%
}
.col-lg-pull-4 {
right: 33.33333333%
}
.col-lg-pull-3 {
right: 25%
}
.col-lg-pull-2 {
right: 16.66666667%
}
.col-lg-pull-1 {
right: 8.33333333%
}
.col-lg-pull-0 {
right: auto
}
.col-lg-push-12 {
left: 100%
}
.col-lg-push-11 {
left: 91.66666667%
}
.col-lg-push-10 {
left: 83.33333333%
}
.col-lg-push-9 {
left: 75%
}
.col-lg-push-8 {
left: 66.66666667%
}
.col-lg-push-7 {
left: 58.33333333%
}
.col-lg-push-6 {
left: 50%
}
.col-lg-push-5 {
left: 41.66666667%
}
.col-lg-push-4 {
left: 33.33333333%
}
.col-lg-push-3 {
left: 25%
}
.col-lg-push-2 {
left: 16.66666667%
}
.col-lg-push-1 {
left: 8.33333333%
}
.col-lg-push-0 {
left: auto
}
.col-lg-offset-12 {
margin-left: 100%
}
.col-lg-offset-11 {
margin-left: 91.66666667%
}
.col-lg-offset-10 {
margin-left: 83.33333333%
}
.col-lg-offset-9 {
margin-left: 75%
}
.col-lg-offset-8 {
margin-left: 66.66666667%
}
.col-lg-offset-7 {
margin-left: 58.33333333%
}
.col-lg-offset-6 {
margin-left: 50%
}
.col-lg-offset-5 {
margin-left: 41.66666667%
}
.col-lg-offset-4 {
margin-left: 33.33333333%
}
.col-lg-offset-3 {
margin-left: 25%
}
.col-lg-offset-2 {
margin-left: 16.66666667%
}
.col-lg-offset-1 {
margin-left: 8.33333333%
}
.col-lg-offset-0 {
margin-left: 0
}
}
table {
background-color: transparent
}
caption {
padding-top: 8px;
padding-bottom: 8px;
color: #777;
text-align: left
}
th {
text-align: left
}
.table {
width: 100%;
max-width: 100%;
margin-bottom: 20px
}
.table>tbody>tr>td,
.table>tbody>tr>th,
.table>tfoot>tr>td,
.table>tfoot>tr>th,
.table>thead>tr>td,
.table>thead>tr>th {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #ddd
}
.table>thead>tr>th {
vertical-align: bottom;
border-bottom: 2px solid #ddd
}
.table>caption+thead>tr:first-child>td,
.table>caption+thead>tr:first-child>th,
.table>colgroup+thead>tr:first-child>td,
.table>colgroup+thead>tr:first-child>th,
.table>thead:first-child>tr:first-child>td,
.table>thead:first-child>tr:first-child>th {
border-top: 0
}
.table>tbody+tbody {
border-top: 2px solid #ddd
}
.table .table {
background-color: #fff
}
.table-condensed>tbody>tr>td,
.table-condensed>tbody>tr>th,
.table-condensed>tfoot>tr>td,
.table-condensed>tfoot>tr>th,
.table-condensed>thead>tr>td,
.table-condensed>thead>tr>th {
padding: 5px
}
.table-bordered {
border: 1px solid #ddd
}
.table-bordered>tbody>tr>td,
.table-bordered>tbody>tr>th,
.table-bordered>tfoot>tr>td,
.table-bordered>tfoot>tr>th,
.table-bordered>thead>tr>td,
.table-bordered>thead>tr>th {
border: 1px solid #ddd
}
.table-bordered>thead>tr>td,
.table-bordered>thead>tr>th {
border-bottom-width: 2px
}
.table-striped>tbody>tr:nth-of-type(odd) {
background-color: #f9f9f9
}
.table-hover>tbody>tr:hover {
background-color: #f5f5f5
}
table col[class*=col-] {
position: static;
display: table-column;
float: none
}
table td[class*=col-],
table th[class*=col-] {
position: static;
display: table-cell;
float: none
}
.table>tbody>tr.active>td,
.table>tbody>tr.active>th,
.table>tbody>tr>td.active,
.table>tbody>tr>th.active,
.table>tfoot>tr.active>td,
.table>tfoot>tr.active>th,
.table>tfoot>tr>td.active,
.table>tfoot>tr>th.active,
.table>thead>tr.active>td,
.table>thead>tr.active>th,
.table>thead>tr>td.active,
.table>thead>tr>th.active {
background-color: #f5f5f5
}
.table-hover>tbody>tr.active:hover>td,
.table-hover>tbody>tr.active:hover>th,
.table-hover>tbody>tr:hover>.active,
.table-hover>tbody>tr>td.active:hover,
.table-hover>tbody>tr>th.active:hover {
background-color: #e8e8e8
}
.table>tbody>tr.success>td,
.table>tbody>tr.success>th,
.table>tbody>tr>td.success,
.table>tbody>tr>th.success,
.table>tfoot>tr.success>td,
.table>tfoot>tr.success>th,
.table>tfoot>tr>td.success,
.table>tfoot>tr>th.success,
.table>thead>tr.success>td,
.table>thead>tr.success>th,
.table>thead>tr>td.success,
.table>thead>tr>th.success {
background-color: #dff0d8
}
.table-hover>tbody>tr.success:hover>td,
.table-hover>tbody>tr.success:hover>th,
.table-hover>tbody>tr:hover>.success,
.table-hover>tbody>tr>td.success:hover,
.table-hover>tbody>tr>th.success:hover {
background-color: #d0e9c6
}
.table>tbody>tr.info>td,
.table>tbody>tr.info>th,
.table>tbody>tr>td.info,
.table>tbody>tr>th.info,
.table>tfoot>tr.info>td,
.table>tfoot>tr.info>th,
.table>tfoot>tr>td.info,
.table>tfoot>tr>th.info,
.table>thead>tr.info>td,
.table>thead>tr.info>th,
.table>thead>tr>td.info,
.table>thead>tr>th.info {
background-color: #d9edf7
}
.table-hover>tbody>tr.info:hover>td,
.table-hover>tbody>tr.info:hover>th,
.table-hover>tbody>tr:hover>.info,
.table-hover>tbody>tr>td.info:hover,
.table-hover>tbody>tr>th.info:hover {
background-color: #c4e3f3
}
.table>tbody>tr.warning>td,
.table>tbody>tr.warning>th,
.table>tbody>tr>td.warning,
.table>tbody>tr>th.warning,
.table>tfoot>tr.warning>td,
.table>tfoot>tr.warning>th,
.table>tfoot>tr>td.warning,
.table>tfoot>tr>th.warning,
.table>thead>tr.warning>td,
.table>thead>tr.warning>th,
.table>thead>tr>td.warning,
.table>thead>tr>th.warning {
background-color: #fcf8e3
}
.table-hover>tbody>tr.warning:hover>td,
.table-hover>tbody>tr.warning:hover>th,
.table-hover>tbody>tr:hover>.warning,
.table-hover>tbody>tr>td.warning:hover,
.table-hover>tbody>tr>th.warning:hover {
background-color: #faf2cc
}
.table>tbody>tr.danger>td,
.table>tbody>tr.danger>th,
.table>tbody>tr>td.danger,
.table>tbody>tr>th.danger,
.table>tfoot>tr.danger>td,
.table>tfoot>tr.danger>th,
.table>tfoot>tr>td.danger,
.table>tfoot>tr>th.danger,
.table>thead>tr.danger>td,
.table>thead>tr.danger>th,
.table>thead>tr>td.danger,
.table>thead>tr>th.danger {
background-color: #f2dede
}
.table-hover>tbody>tr.danger:hover>td,
.table-hover>tbody>tr.danger:hover>th,
.table-hover>tbody>tr:hover>.danger,
.table-hover>tbody>tr>td.danger:hover,
.table-hover>tbody>tr>th.danger:hover {
background-color: #ebcccc
}
.table-responsive {
min-height: .01%;
overflow-x: auto
}
@media screen and (max-width:767px) {
.table-responsive {
width: 100%;
margin-bottom: 15px;
overflow-y: hidden;
-ms-overflow-style: -ms-autohiding-scrollbar;
border: 1px solid #ddd
}
.table-responsive>.table {
margin-bottom: 0
}
.table-responsive>.table>tbody>tr>td,
.table-responsive>.table>tbody>tr>th,
.table-responsive>.table>tfoot>tr>td,
.table-responsive>.table>tfoot>tr>th,
.table-responsive>.table>thead>tr>td,
.table-responsive>.table>thead>tr>th {
white-space: nowrap
}
.table-responsive>.table-bordered {
border: 0
}
.table-responsive>.table-bordered>tbody>tr>td:first-child,
.table-responsive>.table-bordered>tbody>tr>th:first-child,
.table-responsive>.table-bordered>tfoot>tr>td:first-child,
.table-responsive>.table-bordered>tfoot>tr>th:first-child,
.table-responsive>.table-bordered>thead>tr>td:first-child,
.table-responsive>.table-bordered>thead>tr>th:first-child {
border-left: 0
}
.table-responsive>.table-bordered>tbody>tr>td:last-child,
.table-responsive>.table-bordered>tbody>tr>th:last-child,
.table-responsive>.table-bordered>tfoot>tr>td:last-child,
.table-responsive>.table-bordered>tfoot>tr>th:last-child,
.table-responsive>.table-bordered>thead>tr>td:last-child,
.table-responsive>.table-bordered>thead>tr>th:last-child {
border-right: 0
}
.table-responsive>.table-bordered>tbody>tr:last-child>td,
.table-responsive>.table-bordered>tbody>tr:last-child>th,
.table-responsive>.table-bordered>tfoot>tr:last-child>td,
.table-responsive>.table-bordered>tfoot>tr:last-child>th {
border-bottom: 0
}
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0
}
legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 20px;
font-size: 21px;
line-height: inherit;
color: #333;
border: 0;
border-bottom: 1px solid #e5e5e5
}
label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
font-weight: 700
}
input[type=search] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box
}
input[type=checkbox],
input[type=radio] {
margin: 4px 0 0;
margin-top: 1px\9;
line-height: normal
}
input[type=file] {
display: block
}
input[type=range] {
display: block;
width: 100%
}
select[multiple],
select[size] {
height: auto
}
input[type=file]:focus,
input[type=checkbox]:focus,
input[type=radio]:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px
}
output {
display: block;
padding-top: 7px;
font-size: 14px;
line-height: 1.42857143;
color: #555
}
.form-control {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, .6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, .6)
}
.form-control::-moz-placeholder {
color: #999;
opacity: 1
}
.form-control:-ms-input-placeholder {
color: #999
}
.form-control::-webkit-input-placeholder {
color: #999
}
.form-control::-ms-expand {
background-color: transparent;
border: 0
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
background-color: #eee;
opacity: 1
}
.form-control[disabled],
fieldset[disabled] .form-control {
cursor: not-allowed
}
textarea.form-control {
height: auto
}
input[type=search] {
-webkit-appearance: none
}
@media screen and (-webkit-min-device-pixel-ratio:0) {
input[type=date].form-control,
input[type=time].form-control,
input[type=datetime-local].form-control,
input[type=month].form-control {
line-height: 34px
}
.input-group-sm input[type=date],
.input-group-sm input[type=time],
.input-group-sm input[type=datetime-local],
.input-group-sm input[type=month],
input[type=date].input-sm,
input[type=time].input-sm,
input[type=datetime-local].input-sm,
input[type=month].input-sm {
line-height: 30px
}
.input-group-lg input[type=date],
.input-group-lg input[type=time],
.input-group-lg input[type=datetime-local],
.input-group-lg input[type=month],
input[type=date].input-lg,
input[type=time].input-lg,
input[type=datetime-local].input-lg,
input[type=month].input-lg {
line-height: 46px
}
}
.form-group {
margin-bottom: 15px
}
.checkbox,
.radio {
position: relative;
display: block;
margin-top: 10px;
margin-bottom: 10px
}
.checkbox label,
.radio label {
min-height: 20px;
padding-left: 20px;
margin-bottom: 0;
font-weight: 400;
cursor: pointer
}
.checkbox input[type=checkbox],
.checkbox-inline input[type=checkbox],
.radio input[type=radio],
.radio-inline input[type=radio] {
position: absolute;
margin-top: 4px\9;
margin-left: -20px
}
.checkbox+.checkbox,
.radio+.radio {
margin-top: -5px
}
.checkbox-inline,
.radio-inline {
position: relative;
display: inline-block;
padding-left: 20px;
margin-bottom: 0;
font-weight: 400;
vertical-align: middle;
cursor: pointer
}
.checkbox-inline+.checkbox-inline,
.radio-inline+.radio-inline {
margin-top: 0;
margin-left: 10px
}
fieldset[disabled] input[type=checkbox],
fieldset[disabled] input[type=radio],
input[type=checkbox].disabled,
input[type=checkbox][disabled],
input[type=radio].disabled,
input[type=radio][disabled] {
cursor: not-allowed
}
.checkbox-inline.disabled,
.radio-inline.disabled,
fieldset[disabled] .checkbox-inline,
fieldset[disabled] .radio-inline {
cursor: not-allowed
}
.checkbox.disabled label,
.radio.disabled label,
fieldset[disabled] .checkbox label,
fieldset[disabled] .radio label {
cursor: not-allowed
}
.form-control-static {
min-height: 34px;
padding-top: 7px;
padding-bottom: 7px;
margin-bottom: 0
}
.form-control-static.input-lg,
.form-control-static.input-sm {
padding-right: 0;
padding-left: 0
}
.input-sm {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px
}
select.input-sm {
height: 30px;
line-height: 30px
}
select[multiple].input-sm,
textarea.input-sm {
height: auto
}
.form-group-sm .form-control {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px
}
.form-group-sm select.form-control {
height: 30px;
line-height: 30px
}
.form-group-sm select[multiple].form-control,
.form-group-sm textarea.form-control {
height: auto
}
.form-group-sm .form-control-static {
height: 30px;
min-height: 32px;
padding: 6px 10px;
font-size: 12px;
line-height: 1.5
}
.input-lg {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px
}
select.input-lg {
height: 46px;
line-height: 46px
}
select[multiple].input-lg,
textarea.input-lg {
height: auto
}
.form-group-lg .form-control {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px
}
.form-group-lg select.form-control {
height: 46px;
line-height: 46px
}
.form-group-lg select[multiple].form-control,
.form-group-lg textarea.form-control {
height: auto
}
.form-group-lg .form-control-static {
height: 46px;
min-height: 38px;
padding: 11px 16px;
font-size: 18px;
line-height: 1.3333333
}
.has-feedback {
position: relative
}
.has-feedback .form-control {
padding-right: 42.5px
}
.form-control-feedback {
position: absolute;
top: 0;
right: 0;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
pointer-events: none
}
.form-group-lg .form-control+.form-control-feedback,
.input-group-lg+.form-control-feedback,
.input-lg+.form-control-feedback {
width: 46px;
height: 46px;
line-height: 46px
}
.form-group-sm .form-control+.form-control-feedback,
.input-group-sm+.form-control-feedback,
.input-sm+.form-control-feedback {
width: 30px;
height: 30px;
line-height: 30px
}
.has-success .checkbox,
.has-success .checkbox-inline,
.has-success .control-label,
.has-success .help-block,
.has-success .radio,
.has-success .radio-inline,
.has-success.checkbox label,
.has-success.checkbox-inline label,
.has-success.radio label,
.has-success.radio-inline label {
color: #3c763d
}
.has-success .form-control {
border-color: #3c763d;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075)
}
.has-success .form-control:focus {
border-color: #2b542c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168
}
.has-success .input-group-addon {
color: #3c763d;
background-color: #dff0d8;
border-color: #3c763d
}
.has-success .form-control-feedback {
color: #3c763d
}
.has-warning .checkbox,
.has-warning .checkbox-inline,
.has-warning .control-label,
.has-warning .help-block,
.has-warning .radio,
.has-warning .radio-inline,
.has-warning.checkbox label,
.has-warning.checkbox-inline label,
.has-warning.radio label,
.has-warning.radio-inline label {
color: #8a6d3b
}
.has-warning .form-control {
border-color: #8a6d3b;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075)
}
.has-warning .form-control:focus {
border-color: #66512c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b
}
.has-warning .input-group-addon {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #8a6d3b
}
.has-warning .form-control-feedback {
color: #8a6d3b
}
.has-error .checkbox,
.has-error .checkbox-inline,
.has-error .control-label,
.has-error .help-block,
.has-error .radio,
.has-error .radio-inline,
.has-error.checkbox label,
.has-error.checkbox-inline label,
.has-error.radio label,
.has-error.radio-inline label {
color: #a94442
}
.has-error .form-control {
border-color: #a94442;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075)
}
.has-error .form-control:focus {
border-color: #843534;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483
}
.has-error .input-group-addon {
color: #a94442;
background-color: #f2dede;
border-color: #a94442
}
.has-error .form-control-feedback {
color: #a94442
}
.has-feedback label~.form-control-feedback {
top: 25px
}
.has-feedback label.sr-only~.form-control-feedback {
top: 0
}
.help-block {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #737373
}
@media (min-width:768px) {
.form-inline .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle
}
.form-inline .form-control {
display: inline-block;
width: auto;
vertical-align: middle
}
.form-inline .form-control-static {
display: inline-block
}
.form-inline .input-group {
display: inline-table;
vertical-align: middle
}
.form-inline .input-group .form-control,
.form-inline .input-group .input-group-addon,
.form-inline .input-group .input-group-btn {
width: auto
}
.form-inline .input-group>.form-control {
width: 100%
}
.form-inline .control-label {
margin-bottom: 0;
vertical-align: middle
}
.form-inline .checkbox,
.form-inline .radio {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle
}
.form-inline .checkbox label,
.form-inline .radio label {
padding-left: 0
}
.form-inline .checkbox input[type=checkbox],
.form-inline .radio input[type=radio] {
position: relative;
margin-left: 0
}
.form-inline .has-feedback .form-control-feedback {
top: 0
}
}
.form-horizontal .checkbox,
.form-horizontal .checkbox-inline,
.form-horizontal .radio,
.form-horizontal .radio-inline {
padding-top: 7px;
margin-top: 0;
margin-bottom: 0
}
.form-horizontal .checkbox,
.form-horizontal .radio {
min-height: 27px
}
.form-horizontal .form-group {
margin-right: -15px;
margin-left: -15px
}
@media (min-width:768px) {
.form-horizontal .control-label {
padding-top: 7px;
margin-bottom: 0;
text-align: right
}
}
.form-horizontal .has-feedback .form-control-feedback {
right: 15px
}
@media (min-width:768px) {
.form-horizontal .form-group-lg .control-label {
padding-top: 11px;
font-size: 18px
}
}
@media (min-width:768px) {
.form-horizontal .form-group-sm .control-label {
padding-top: 6px;
font-size: 12px
}
}
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: 400;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px
}
.btn.active.focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn:active:focus,
.btn:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px
}
.btn.focus,
.btn:focus,
.btn:hover {
color: #333;
text-decoration: none
}
.btn.active,
.btn:active {
background-image: none;
outline: 0;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125)
}
.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
cursor: not-allowed;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
opacity: .65
}
a.btn.disabled,
fieldset[disabled] a.btn {
pointer-events: none
}
.btn-default {
color: #333;
background-color: #fff;
border-color: #ccc
}
.btn-default.focus,
.btn-default:focus {
color: #333;
background-color: #e6e6e6;
border-color: #8c8c8c
}
.btn-default:hover {
color: #333;
background-color: #e6e6e6;
border-color: #adadad
}
.btn-default.active,
.btn-default:active,
.open>.dropdown-toggle.btn-default {
color: #333;
background-color: #e6e6e6;
border-color: #adadad
}
.btn-default.active.focus,
.btn-default.active:focus,
.btn-default.active:hover,
.btn-default:active.focus,
.btn-default:active:focus,
.btn-default:active:hover,
.open>.dropdown-toggle.btn-default.focus,
.open>.dropdown-toggle.btn-default:focus,
.open>.dropdown-toggle.btn-default:hover {
color: #333;
background-color: #d4d4d4;
border-color: #8c8c8c
}
.btn-default.active,
.btn-default:active,
.open>.dropdown-toggle.btn-default {
background-image: none
}
.btn-default.disabled.focus,
.btn-default.disabled:focus,
.btn-default.disabled:hover,
.btn-default[disabled].focus,
.btn-default[disabled]:focus,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default.focus,
fieldset[disabled] .btn-default:focus,
fieldset[disabled] .btn-default:hover {
background-color: #fff;
border-color: #ccc
}
.btn-default .badge {
color: #fff;
background-color: #333
}
.btn-primary {
color: #fff;
background-color: #337ab7;
border-color: #2e6da4
}
.btn-primary.focus,
.btn-primary:focus {
color: #fff;
background-color: #286090;
border-color: #122b40
}
.btn-primary:hover {
color: #fff;
background-color: #286090;
border-color: #204d74
}
.btn-primary.active,
.btn-primary:active,
.open>.dropdown-toggle.btn-primary {
color: #fff;
background-color: #286090;
border-color: #204d74
}
.btn-primary.active.focus,
.btn-primary.active:focus,
.btn-primary.active:hover,
.btn-primary:active.focus,
.btn-primary:active:focus,
.btn-primary:active:hover,
.open>.dropdown-toggle.btn-primary.focus,
.open>.dropdown-toggle.btn-primary:focus,
.open>.dropdown-toggle.btn-primary:hover {
color: #fff;
background-color: #204d74;
border-color: #122b40
}
.btn-primary.active,
.btn-primary:active,
.open>.dropdown-toggle.btn-primary {
background-image: none
}
.btn-primary.disabled.focus,
.btn-primary.disabled:focus,
.btn-primary.disabled:hover,
.btn-primary[disabled].focus,
.btn-primary[disabled]:focus,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary.focus,
fieldset[disabled] .btn-primary:focus,
fieldset[disabled] .btn-primary:hover {
background-color: #337ab7;
border-color: #2e6da4
}
.btn-primary .badge {
color: #337ab7;
background-color: #fff
}
.btn-success {
color: #fff;
background-color: #5cb85c;
border-color: #4cae4c
}
.btn-success.focus,
.btn-success:focus {
color: #fff;
background-color: #449d44;
border-color: #255625
}
.btn-success:hover {
color: #fff;
background-color: #449d44;
border-color: #398439
}
.btn-success.active,
.btn-success:active,
.open>.dropdown-toggle.btn-success {
color: #fff;
background-color: #449d44;
border-color: #398439
}
.btn-success.active.focus,
.btn-success.active:focus,
.btn-success.active:hover,
.btn-success:active.focus,
.btn-success:active:focus,
.btn-success:active:hover,
.open>.dropdown-toggle.btn-success.focus,
.open>.dropdown-toggle.btn-success:focus,
.open>.dropdown-toggle.btn-success:hover {
color: #fff;
background-color: #398439;
border-color: #255625
}
.btn-success.active,
.btn-success:active,
.open>.dropdown-toggle.btn-success {
background-image: none
}
.btn-success.disabled.focus,
.btn-success.disabled:focus,
.btn-success.disabled:hover,
.btn-success[disabled].focus,
.btn-success[disabled]:focus,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success.focus,
fieldset[disabled] .btn-success:focus,
fieldset[disabled] .btn-success:hover {
background-color: #5cb85c;
border-color: #4cae4c
}
.btn-success .badge {
color: #5cb85c;
background-color: #fff
}
.btn-info {
color: #fff;
background-color: #5bc0de;
border-color: #46b8da
}
.btn-info.focus,
.btn-info:focus {
color: #fff;
background-color: #31b0d5;
border-color: #1b6d85
}
.btn-info:hover {
color: #fff;
background-color: #31b0d5;
border-color: #269abc
}
.btn-info.active,
.btn-info:active,
.open>.dropdown-toggle.btn-info {
color: #fff;
background-color: #31b0d5;
border-color: #269abc
}
.btn-info.active.focus,
.btn-info.active:focus,
.btn-info.active:hover,
.btn-info:active.focus,
.btn-info:active:focus,
.btn-info:active:hover,
.open>.dropdown-toggle.btn-info.focus,
.open>.dropdown-toggle.btn-info:focus,
.open>.dropdown-toggle.btn-info:hover {
color: #fff;
background-color: #269abc;
border-color: #1b6d85
}
.btn-info.active,
.btn-info:active,
.open>.dropdown-toggle.btn-info {
background-image: none
}
.btn-info.disabled.focus,
.btn-info.disabled:focus,
.btn-info.disabled:hover,
.btn-info[disabled].focus,
.btn-info[disabled]:focus,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info.focus,
fieldset[disabled] .btn-info:focus,
fieldset[disabled] .btn-info:hover {
background-color: #5bc0de;
border-color: #46b8da
}
.btn-info .badge {
color: #5bc0de;
background-color: #fff
}
.btn-warning {
color: #fff;
background-color: #f0ad4e;
border-color: #eea236
}
.btn-warning.focus,
.btn-warning:focus {
color: #fff;
background-color: #ec971f;
border-color: #985f0d
}
.btn-warning:hover {
color: #fff;
background-color: #ec971f;
border-color: #d58512
}
.btn-warning.active,
.btn-warning:active,
.open>.dropdown-toggle.btn-warning {
color: #fff;
background-color: #ec971f;
border-color: #d58512
}
.btn-warning.active.focus,
.btn-warning.active:focus,
.btn-warning.active:hover,
.btn-warning:active.focus,
.btn-warning:active:focus,
.btn-warning:active:hover,
.open>.dropdown-toggle.btn-warning.focus,
.open>.dropdown-toggle.btn-warning:focus,
.open>.dropdown-toggle.btn-warning:hover {
color: #fff;
background-color: #d58512;
border-color: #985f0d
}
.btn-warning.active,
.btn-warning:active,
.open>.dropdown-toggle.btn-warning {
background-image: none
}
.btn-warning.disabled.focus,
.btn-warning.disabled:focus,
.btn-warning.disabled:hover,
.btn-warning[disabled].focus,
.btn-warning[disabled]:focus,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning.focus,
fieldset[disabled] .btn-warning:focus,
fieldset[disabled] .btn-warning:hover {
background-color: #f0ad4e;
border-color: #eea236
}
.btn-warning .badge {
color: #f0ad4e;
background-color: #fff
}
.btn-danger {
color: #fff;
background-color: #d9534f;
border-color: #d43f3a
}
.btn-danger.focus,
.btn-danger:focus {
color: #fff;
background-color: #c9302c;
border-color: #761c19
}
.btn-danger:hover {
color: #fff;
background-color: #c9302c;
border-color: #ac2925
}
.btn-danger.active,
.btn-danger:active,
.open>.dropdown-toggle.btn-danger {
color: #fff;
background-color: #c9302c;
border-color: #ac2925
}
.btn-danger.active.focus,
.btn-danger.active:focus,
.btn-danger.active:hover,
.btn-danger:active.focus,
.btn-danger:active:focus,
.btn-danger:active:hover,
.open>.dropdown-toggle.btn-danger.focus,
.open>.dropdown-toggle.btn-danger:focus,
.open>.dropdown-toggle.btn-danger:hover {
color: #fff;
background-color: #ac2925;
border-color: #761c19
}
.btn-danger.active,
.btn-danger:active,
.open>.dropdown-toggle.btn-danger {
background-image: none
}
.btn-danger.disabled.focus,
.btn-danger.disabled:focus,
.btn-danger.disabled:hover,
.btn-danger[disabled].focus,
.btn-danger[disabled]:focus,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger.focus,
fieldset[disabled] .btn-danger:focus,
fieldset[disabled] .btn-danger:hover {
background-color: #d9534f;
border-color: #d43f3a
}
.btn-danger .badge {
color: #d9534f;
background-color: #fff
}
.btn-link {
font-weight: 400;
color: #337ab7;
border-radius: 0
}
.btn-link,
.btn-link.active,
.btn-link:active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none
}
.btn-link,
.btn-link:active,
.btn-link:focus,
.btn-link:hover {
border-color: transparent
}
.btn-link:focus,
.btn-link:hover {
color: #23527c;
text-decoration: underline;
background-color: transparent
}
.btn-link[disabled]:focus,
.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:focus,
fieldset[disabled] .btn-link:hover {
color: #777;
text-decoration: none
}
.btn-group-lg>.btn,
.btn-lg {
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px
}
.btn-group-sm>.btn,
.btn-sm {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px
}
.btn-group-xs>.btn,
.btn-xs {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px
}
.btn-block {
display: block;
width: 100%
}
.btn-block+.btn-block {
margin-top: 5px
}
input[type=button].btn-block,
input[type=reset].btn-block,
input[type=submit].btn-block {
width: 100%
}
.fade {
opacity: 0;
-webkit-transition: opacity .15s linear;
-o-transition: opacity .15s linear;
transition: opacity .15s linear
}
.fade.in {
opacity: 1
}
.collapse {
display: none
}
.collapse.in {
display: block
}
tr.collapse.in {
display: table-row
}
tbody.collapse.in {
display: table-row-group
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
-webkit-transition-timing-function: ease;
-o-transition-timing-function: ease;
transition-timing-function: ease;
-webkit-transition-duration: .35s;
-o-transition-duration: .35s;
transition-duration: .35s;
-webkit-transition-property: height, visibility;
-o-transition-property: height, visibility;
transition-property: height, visibility
}
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: 4px dashed;
border-top: 4px solid\9;
border-right: 4px solid transparent;
border-left: 4px solid transparent
}
.dropdown,
.dropup {
position: relative
}
.dropdown-toggle:focus {
outline: 0
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
font-size: 14px;
text-align: left;
list-style: none;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
box-shadow: 0 6px 12px rgba(0, 0, 0, .175)
}
.dropdown-menu.pull-right {
right: 0;
left: auto
}
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5
}
.dropdown-menu>li>a {
display: block;
padding: 3px 20px;
clear: both;
font-weight: 400;
line-height: 1.42857143;
color: #333;
white-space: nowrap
}
.dropdown-menu>li>a:focus,
.dropdown-menu>li>a:hover {
color: #262626;
text-decoration: none;
background-color: #f5f5f5
}
.dropdown-menu>.active>a,
.dropdown-menu>.active>a:focus,
.dropdown-menu>.active>a:hover {
color: #fff;
text-decoration: none;
background-color: #337ab7;
outline: 0
}
.dropdown-menu>.disabled>a,
.dropdown-menu>.disabled>a:focus,
.dropdown-menu>.disabled>a:hover {
color: #777
}
.dropdown-menu>.disabled>a:focus,
.dropdown-menu>.disabled>a:hover {
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
background-image: none;
filter: progid: DXImageTransform.Microsoft.gradient(enabled=false)
}
.open>.dropdown-menu {
display: block
}
.open>a {
outline: 0
}
.dropdown-menu-right {
right: 0;
left: auto
}
.dropdown-menu-left {
right: auto;
left: 0
}
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: 12px;
line-height: 1.42857143;
color: #777;
white-space: nowrap
}
.dropdown-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 990
}
.pull-right>.dropdown-menu {
right: 0;
left: auto
}
.dropup .caret,
.navbar-fixed-bottom .dropdown .caret {
content: "";
border-top: 0;
border-bottom: 4px dashed;
border-bottom: 4px solid\9
}
.dropup .dropdown-menu,
.navbar-fixed-bottom .dropdown .dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 2px
}
@media (min-width:768px) {
.navbar-right .dropdown-menu {
right: 0;
left: auto
}
.navbar-right .dropdown-menu-left {
right: auto;
left: 0
}
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle
}
.btn-group-vertical>.btn,
.btn-group>.btn {
position: relative;
float: left
}
.btn-group-vertical>.btn.active,
.btn-group-vertical>.btn:active,
.btn-group-vertical>.btn:focus,
.btn-group-vertical>.btn:hover,
.btn-group>.btn.active,
.btn-group>.btn:active,
.btn-group>.btn:focus,
.btn-group>.btn:hover {
z-index: 2
}
.btn-group .btn+.btn,
.btn-group .btn+.btn-group,
.btn-group .btn-group+.btn,
.btn-group .btn-group+.btn-group {
margin-left: -1px
}
.btn-toolbar {
margin-left: -5px
}
.btn-toolbar .btn,
.btn-toolbar .btn-group,
.btn-toolbar .input-group {
float: left
}
.btn-toolbar>.btn,
.btn-toolbar>.btn-group,
.btn-toolbar>.input-group {
margin-left: 5px
}
.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
border-radius: 0
}
.btn-group>.btn:first-child {
margin-left: 0
}
.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle) {
border-top-right-radius: 0;
border-bottom-right-radius: 0
}
.btn-group>.btn:last-child:not(:first-child),
.btn-group>.dropdown-toggle:not(:first-child) {
border-top-left-radius: 0;
border-bottom-left-radius: 0
}
.btn-group>.btn-group {
float: left
}
.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn {
border-radius: 0
}
.btn-group>.btn-group:first-child:not(:last-child)>.btn:last-child,
.btn-group>.btn-group:first-child:not(:last-child)>.dropdown-toggle {
border-top-right-radius: 0;
border-bottom-right-radius: 0
}
.btn-group>.btn-group:last-child:not(:first-child)>.btn:first-child {
border-top-left-radius: 0;
border-bottom-left-radius: 0
}
.btn-group .dropdown-toggle:active,
.btn-group.open .dropdown-toggle {
outline: 0
}
.btn-group>.btn+.dropdown-toggle {
padding-right: 8px;
padding-left: 8px
}
.btn-group>.btn-lg+.dropdown-toggle {
padding-right: 12px;
padding-left: 12px
}
.btn-group.open .dropdown-toggle {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125)
}
.btn-group.open .dropdown-toggle.btn-link {
-webkit-box-shadow: none;
box-shadow: none
}
.btn .caret {
margin-left: 0
}
.btn-lg .caret {
border-width: 5px 5px 0;
border-bottom-width: 0
}
.dropup .btn-lg .caret {
border-width: 0 5px 5px
}
.btn-group-vertical>.btn,
.btn-group-vertical>.btn-group,
.btn-group-vertical>.btn-group>.btn {
display: block;
float: none;
width: 100%;
max-width: 100%
}
.btn-group-vertical>.btn-group>.btn {
float: none
}
.btn-group-vertical>.btn+.btn,
.btn-group-vertical>.btn+.btn-group,
.btn-group-vertical>.btn-group+.btn,
.btn-group-vertical>.btn-group+.btn-group {
margin-top: -1px;
margin-left: 0
}
.btn-group-vertical>.btn:not(:first-child):not(:last-child) {
border-radius: 0
}
.btn-group-vertical>.btn:first-child:not(:last-child) {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0
}
.btn-group-vertical>.btn:last-child:not(:first-child) {
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px
}
.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn {
border-radius: 0
}
.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,
.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0
}
.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child {
border-top-left-radius: 0;
border-top-right-radius: 0
}
.btn-group-justified {
display: table;
width: 100%;
table-layout: fixed;
border-collapse: separate
}
.btn-group-justified>.btn,
.btn-group-justified>.btn-group {
display: table-cell;
float: none;
width: 1%
}
.btn-group-justified>.btn-group .btn {
width: 100%
}
.btn-group-justified>.btn-group .dropdown-menu {
left: auto
}
[data-toggle=buttons]>.btn input[type=checkbox],
[data-toggle=buttons]>.btn input[type=radio],
[data-toggle=buttons]>.btn-group>.btn input[type=checkbox],
[data-toggle=buttons]>.btn-group>.btn input[type=radio] {
position: absolute;
clip: rect(0, 0, 0, 0);
pointer-events: none
}
.input-group {
position: relative;
display: table;
border-collapse: separate
}
.input-group[class*=col-] {
float: none;
padding-right: 0;
padding-left: 0
}
.input-group .form-control {
position: relative;
z-index: 2;
float: left;
width: 100%;
margin-bottom: 0
}
.input-group .form-control:focus {
z-index: 3
}
.input-group-lg>.form-control,
.input-group-lg>.input-group-addon,
.input-group-lg>.input-group-btn>.btn {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px
}
select.input-group-lg>.form-control,
select.input-group-lg>.input-group-addon,
select.input-group-lg>.input-group-btn>.btn {
height: 46px;
line-height: 46px
}
select[multiple].input-group-lg>.form-control,
select[multiple].input-group-lg>.input-group-addon,
select[multiple].input-group-lg>.input-group-btn>.btn,
textarea.input-group-lg>.form-control,
textarea.input-group-lg>.input-group-addon,
textarea.input-group-lg>.input-group-btn>.btn {
height: auto
}
.input-group-sm>.form-control,
.input-group-sm>.input-group-addon,
.input-group-sm>.input-group-btn>.btn {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px
}
select.input-group-sm>.form-control,
select.input-group-sm>.input-group-addon,
select.input-group-sm>.input-group-btn>.btn {
height: 30px;
line-height: 30px
}
select[multiple].input-group-sm>.form-control,
select[multiple].input-group-sm>.input-group-addon,
select[multiple].input-group-sm>.input-group-btn>.btn,
textarea.input-group-sm>.form-control,
textarea.input-group-sm>.input-group-addon,
textarea.input-group-sm>.input-group-btn>.btn {
height: auto
}
.input-group .form-control,
.input-group-addon,
.input-group-btn {
display: table-cell
}
.input-group .form-control:not(:first-child):not(:last-child),
.input-group-addon:not(:first-child):not(:last-child),
.input-group-btn:not(:first-child):not(:last-child) {
border-radius: 0
}
.input-group-addon,
.input-group-btn {
width: 1%;
white-space: nowrap;
vertical-align: middle
}
.input-group-addon {
padding: 6px 12px;
font-size: 14px;
font-weight: 400;
line-height: 1;
color: #555;
text-align: center;
background-color: #eee;
border: 1px solid #ccc;
border-radius: 4px
}
.input-group-addon.input-sm {
padding: 5px 10px;
font-size: 12px;
border-radius: 3px
}
.input-group-addon.input-lg {
padding: 10px 16px;
font-size: 18px;
border-radius: 6px
}
.input-group-addon input[type=checkbox],
.input-group-addon input[type=radio] {
margin-top: 0
}
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child>.btn,
.input-group-btn:first-child>.btn-group>.btn,
.input-group-btn:first-child>.dropdown-toggle,
.input-group-btn:last-child>.btn-group:not(:last-child)>.btn,
.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle) {
border-top-right-radius: 0;
border-bottom-right-radius: 0
}
.input-group-addon:first-child {
border-right: 0
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:first-child>.btn-group:not(:first-child)>.btn,
.input-group-btn:first-child>.btn:not(:first-child),
.input-group-btn:last-child>.btn,
.input-group-btn:last-child>.btn-group>.btn,
.input-group-btn:last-child>.dropdown-toggle {
border-top-left-radius: 0;
border-bottom-left-radius: 0
}
.input-group-addon:last-child {
border-left: 0
}
.input-group-btn {
position: relative;
font-size: 0;
white-space: nowrap
}
.input-group-btn>.btn {
position: relative
}
.input-group-btn>.btn+.btn {
margin-left: -1px
}
.input-group-btn>.btn:active,
.input-group-btn>.btn:focus,
.input-group-btn>.btn:hover {
z-index: 2
}
.input-group-btn:first-child>.btn,
.input-group-btn:first-child>.btn-group {
margin-right: -1px
}
.input-group-btn:last-child>.btn,
.input-group-btn:last-child>.btn-group {
z-index: 2;
margin-left: -1px
}
.nav {
padding-left: 0;
margin-bottom: 0;
list-style: none
}
.nav>li {
position: relative;
display: block
}
.nav>li>a {
position: relative;
display: block;
padding: 10px 15px
}
.nav>li>a:focus,
.nav>li>a:hover {
text-decoration: none;
background-color: #eee
}
.nav>li.disabled>a {
color: #777
}
.nav>li.disabled>a:focus,
.nav>li.disabled>a:hover {
color: #777;
text-decoration: none;
cursor: not-allowed;
background-color: transparent
}
.nav .open>a,
.nav .open>a:focus,
.nav .open>a:hover {
background-color: #eee;
border-color: #337ab7
}
.nav .nav-divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5
}
.nav>li>a>img {
max-width: none
}
.nav-tabs {
border-bottom: 1px solid #ddd
}
.nav-tabs>li {
float: left;
margin-bottom: -1px
}
.nav-tabs>li>a {
margin-right: 2px;
line-height: 1.42857143;
border: 1px solid transparent;
border-radius: 4px 4px 0 0
}
.nav-tabs>li>a:hover {
border-color: #eee #eee #ddd
}
.nav-tabs>li.active>a,
.nav-tabs>li.active>a:focus,
.nav-tabs>li.active>a:hover {
color: #555;
cursor: default;
background-color: #fff;
border: 1px solid #ddd;
border-bottom-color: transparent
}
.nav-tabs.nav-justified {
width: 100%;
border-bottom: 0
}
.nav-tabs.nav-justified>li {
float: none
}
.nav-tabs.nav-justified>li>a {
margin-bottom: 5px;
text-align: center
}
.nav-tabs.nav-justified>.dropdown .dropdown-menu {
top: auto;
left: auto
}
@media (min-width:768px) {
.nav-tabs.nav-justified>li {
display: table-cell;
width: 1%
}
.nav-tabs.nav-justified>li>a {
margin-bottom: 0
}
}
.nav-tabs.nav-justified>li>a {
margin-right: 0;
border-radius: 4px
}
.nav-tabs.nav-justified>.active>a,
.nav-tabs.nav-justified>.active>a:focus,
.nav-tabs.nav-justified>.active>a:hover {
border: 1px solid #ddd
}
@media (min-width:768px) {
.nav-tabs.nav-justified>li>a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0
}
.nav-tabs.nav-justified>.active>a,
.nav-tabs.nav-justified>.active>a:focus,
.nav-tabs.nav-justified>.active>a:hover {
border-bottom-color: #fff
}
}
.nav-pills>li {
float: left
}
.nav-pills>li>a {
border-radius: 4px
}
.nav-pills>li+li {
margin-left: 2px
}
.nav-pills>li.active>a,
.nav-pills>li.active>a:focus,
.nav-pills>li.active>a:hover {
color: #fff;
background-color: #337ab7
}
.nav-stacked>li {
float: none
}
.nav-stacked>li+li {
margin-top: 2px;
margin-left: 0
}
.nav-justified {
width: 100%
}
.nav-justified>li {
float: none
}
.nav-justified>li>a {
margin-bottom: 5px;
text-align: center
}
.nav-justified>.dropdown .dropdown-menu {
top: auto;
left: auto
}
@media (min-width:768px) {
.nav-justified>li {
display: table-cell;
width: 1%
}
.nav-justified>li>a {
margin-bottom: 0
}
}
.nav-tabs-justified {
border-bottom: 0
}
.nav-tabs-justified>li>a {
margin-right: 0;
border-radius: 4px
}
.nav-tabs-justified>.active>a,
.nav-tabs-justified>.active>a:focus,
.nav-tabs-justified>.active>a:hover {
border: 1px solid #ddd
}
@media (min-width:768px) {
.nav-tabs-justified>li>a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0
}
.nav-tabs-justified>.active>a,
.nav-tabs-justified>.active>a:focus,
.nav-tabs-justified>.active>a:hover {
border-bottom-color: #fff
}
}
.tab-content>.tab-pane {
display: none
}
.tab-content>.active {
display: block
}
.nav-tabs .dropdown-menu {
margin-top: -1px;
border-top-left-radius: 0;
border-top-right-radius: 0
}
.navbar {
position: relative;
min-height: 50px;
margin-bottom: 20px;
border: 1px solid transparent
}
@media (min-width:768px) {
.navbar {
border-radius: 4px
}
}
@media (min-width:768px) {
.navbar-header {
float: left
}
}
.navbar-collapse {
padding-right: 15px;
padding-left: 15px;
overflow-x: visible;
-webkit-overflow-scrolling: touch;
border-top: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1)
}
.navbar-collapse.in {
overflow-y: auto
}
@media (min-width:768px) {
.navbar-collapse {
width: auto;
border-top: 0;
-webkit-box-shadow: none;
box-shadow: none
}
.navbar-collapse.collapse {
display: block!important;
height: auto!important;
padding-bottom: 0;
overflow: visible!important
}
.navbar-collapse.in {
overflow-y: visible
}
.navbar-fixed-bottom .navbar-collapse,
.navbar-fixed-top .navbar-collapse,
.navbar-static-top .navbar-collapse {
padding-right: 0;
padding-left: 0
}
}
.navbar-fixed-bottom .navbar-collapse,
.navbar-fixed-top .navbar-collapse {
max-height: 340px
}
@media (max-device-width:480px) and (orientation:landscape) {
.navbar-fixed-bottom .navbar-collapse,
.navbar-fixed-top .navbar-collapse {
max-height: 200px
}
}
.container-fluid>.navbar-collapse,
.container-fluid>.navbar-header,
.container>.navbar-collapse,
.container>.navbar-header {
margin-right: -15px;
margin-left: -15px
}
@media (min-width:768px) {
.container-fluid>.navbar-collapse,
.container-fluid>.navbar-header,
.container>.navbar-collapse,
.container>.navbar-header {
margin-right: 0;
margin-left: 0
}
}
.navbar-static-top {
z-index: 1000;
border-width: 0 0 1px
}
@media (min-width:768px) {
.navbar-static-top {
border-radius: 0
}
}
.navbar-fixed-bottom,
.navbar-fixed-top {
position: fixed;
right: 0;
left: 0;
z-index: 1030
}
@media (min-width:768px) {
.navbar-fixed-bottom,
.navbar-fixed-top {
border-radius: 0
}
}
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px
}
.navbar-fixed-bottom {
bottom: 0;
margin-bottom: 0;
border-width: 1px 0 0
}
.navbar-brand {
float: left;
height: 50px;
padding: 15px 15px;
font-size: 18px;
line-height: 20px
}
.navbar-brand:focus,
.navbar-brand:hover {
text-decoration: none
}
.navbar-brand>img {
display: block
}
@media (min-width:768px) {
.navbar>.container .navbar-brand,
.navbar>.container-fluid .navbar-brand {
margin-left: -15px
}
}
.navbar-toggle {
position: relative;
float: right;
padding: 9px 10px;
margin-top: 8px;
margin-right: 15px;
margin-bottom: 8px;
background-color: transparent;
background-image: none;
border: 1px solid transparent;
border-radius: 4px
}
.navbar-toggle:focus {
outline: 0
}
.navbar-toggle .icon-bar {
display: block;
width: 22px;
height: 2px;
border-radius: 1px
}
.navbar-toggle .icon-bar+.icon-bar {
margin-top: 4px
}
@media (min-width:768px) {
.navbar-toggle {
display: none
}
}
.navbar-nav {
margin: 7.5px -15px
}
.navbar-nav>li>a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 20px
}
@media (max-width:767px) {
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
-webkit-box-shadow: none;
box-shadow: none
}
.navbar-nav .open .dropdown-menu .dropdown-header,
.navbar-nav .open .dropdown-menu>li>a {
padding: 5px 15px 5px 25px
}
.navbar-nav .open .dropdown-menu>li>a {
line-height: 20px
}
.navbar-nav .open .dropdown-menu>li>a:focus,
.navbar-nav .open .dropdown-menu>li>a:hover {
background-image: none
}
}
@media (min-width:768px) {
.navbar-nav {
float: left;
margin: 0
}
.navbar-nav>li {
float: left
}
.navbar-nav>li>a {
padding-top: 15px;
padding-bottom: 15px
}
}
.navbar-form {
padding: 10px 15px;
margin-top: 8px;
margin-right: -15px;
margin-bottom: 8px;
margin-left: -15px;
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1)
}
@media (min-width:768px) {
.navbar-form .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle
}
.navbar-form .form-control {
display: inline-block;
width: auto;
vertical-align: middle
}
.navbar-form .form-control-static {
display: inline-block
}
.navbar-form .input-group {
display: inline-table;
vertical-align: middle
}
.navbar-form .input-group .form-control,
.navbar-form .input-group .input-group-addon,
.navbar-form .input-group .input-group-btn {
width: auto
}
.navbar-form .input-group>.form-control {
width: 100%
}
.navbar-form .control-label {
margin-bottom: 0;
vertical-align: middle
}
.navbar-form .checkbox,
.navbar-form .radio {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle
}
.navbar-form .checkbox label,
.navbar-form .radio label {
padding-left: 0
}
.navbar-form .checkbox input[type=checkbox],
.navbar-form .radio input[type=radio] {
position: relative;
margin-left: 0
}
.navbar-form .has-feedback .form-control-feedback {
top: 0
}
}
@media (max-width:767px) {
.navbar-form .form-group {
margin-bottom: 5px
}
.navbar-form .form-group:last-child {
margin-bottom: 0
}
}
@media (min-width:768px) {
.navbar-form {
width: auto;
padding-top: 0;
padding-bottom: 0;
margin-right: 0;
margin-left: 0;
border: 0;
-webkit-box-shadow: none;
box-shadow: none
}
}
.navbar-nav>li>.dropdown-menu {
margin-top: 0;
border-top-left-radius: 0;
border-top-right-radius: 0
}
.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu {
margin-bottom: 0;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0
}
.navbar-btn {
margin-top: 8px;
margin-bottom: 8px
}
.navbar-btn.btn-sm {
margin-top: 10px;
margin-bottom: 10px
}
.navbar-btn.btn-xs {
margin-top: 14px;
margin-bottom: 14px
}
.navbar-text {
margin-top: 15px;
margin-bottom: 15px
}
@media (min-width:768px) {
.navbar-text {
float: left;
margin-right: 15px;
margin-left: 15px
}
}
@media (min-width:768px) {
.navbar-left {
float: left!important
}
.navbar-right {
float: right!important;
margin-right: -15px
}
.navbar-right~.navbar-right {
margin-right: 0
}
}
.navbar-default {
background-color: #f8f8f8;
/* border-color: #e7e7e7*/
}
.navbar-default .navbar-brand {
color: #777
}
.navbar-default .navbar-brand:focus,
.navbar-default .navbar-brand:hover {
color: #5e5e5e;
background-color: transparent
}
.navbar-default .navbar-text {
color: #777
}
.navbar-default .navbar-nav>li>a {
color: #777
}
.navbar-default .navbar-nav>li>a:focus,
.navbar-default .navbar-nav>li>a:hover {
color: #333;
background-color: transparent
}
.navbar-default .navbar-nav>.active>a,
.navbar-default .navbar-nav>.active>a:focus,
.navbar-default .navbar-nav>.active>a:hover {
color: #555;
/*background-color: #e7e7e7*/
}
.navbar-default .navbar-nav>.disabled>a,
.navbar-default .navbar-nav>.disabled>a:focus,
.navbar-default .navbar-nav>.disabled>a:hover {
color: #ccc;
background-color: transparent
}
.navbar-default .navbar-toggle {
border-color: #ddd
}
.navbar-default .navbar-toggle:focus,
.navbar-default .navbar-toggle:hover {
background-color: #ddd
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #888
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: #e7e7e7
}
.navbar-default .navbar-nav>.open>a,
.navbar-default .navbar-nav>.open>a:focus,
.navbar-default .navbar-nav>.open>a:hover {
color: #555;
/*background-color: #e7e7e7*/
}
@media (max-width:767px) {
.navbar-default .navbar-nav .open .dropdown-menu>li>a {
color: #777
}
.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,
.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover {
color: #333;
background-color: transparent
}
.navbar-default .navbar-nav .open .dropdown-menu>.active>a,
.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,
.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover {
color: #555;
/*background-color: #e7e7e7*/
}
.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,
.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,
.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover {
color: #ccc;
background-color: transparent
}
}
.navbar-default .navbar-link {
color: #777
}
.navbar-default .navbar-link:hover {
color: #333
}
.navbar-default .btn-link {
color: #777
}
.navbar-default .btn-link:focus,
.navbar-default .btn-link:hover {
color: #333
}
.navbar-default .btn-link[disabled]:focus,
.navbar-default .btn-link[disabled]:hover,
fieldset[disabled] .navbar-default .btn-link:focus,
fieldset[disabled] .navbar-default .btn-link:hover {
color: #ccc
}
.navbar-inverse {
background-color: #222;
border-color: #080808
}
.navbar-inverse .navbar-brand {
color: #9d9d9d
}
.navbar-inverse .navbar-brand:focus,
.navbar-inverse .navbar-brand:hover {
color: #fff;
background-color: transparent
}
.navbar-inverse .navbar-text {
color: #9d9d9d
}
.navbar-inverse .navbar-nav>li>a {
color: #9d9d9d
}
.navbar-inverse .navbar-nav>li>a:focus,
.navbar-inverse .navbar-nav>li>a:hover {
color: #fff;
background-color: transparent
}
.navbar-inverse .navbar-nav>.active>a,
.navbar-inverse .navbar-nav>.active>a:focus,
.navbar-inverse .navbar-nav>.active>a:hover {
color: #fff;
background-color: #080808
}
.navbar-inverse .navbar-nav>.disabled>a,
.navbar-inverse .navbar-nav>.disabled>a:focus,
.navbar-inverse .navbar-nav>.disabled>a:hover {
color: #444;
background-color: transparent
}
.navbar-inverse .navbar-toggle {
border-color: #333
}
.navbar-inverse .navbar-toggle:focus,
.navbar-inverse .navbar-toggle:hover {
background-color: #333
}
.navbar-inverse .navbar-toggle .icon-bar {
background-color: #fff
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
border-color: #101010
}
.navbar-inverse .navbar-nav>.open>a,
.navbar-inverse .navbar-nav>.open>a:focus,
.navbar-inverse .navbar-nav>.open>a:hover {
color: #fff;
background-color: #080808
}
@media (max-width:767px) {
.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header {
border-color: #080808
}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
background-color: #080808
}
.navbar-inverse .navbar-nav .open .dropdown-menu>li>a {
color: #9d9d9d
}
.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,
.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover {
color: #fff;
background-color: transparent
}
.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,
.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,
.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover {
color: #fff;
background-color: #080808
}
.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,
.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,
.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover {
color: #444;
background-color: transparent
}
}
.navbar-inverse .navbar-link {
color: #9d9d9d
}
.navbar-inverse .navbar-link:hover {
color: #fff
}
.navbar-inverse .btn-link {
color: #9d9d9d
}
.navbar-inverse .btn-link:focus,
.navbar-inverse .btn-link:hover {
color: #fff
}
.navbar-inverse .btn-link[disabled]:focus,
.navbar-inverse .btn-link[disabled]:hover,
fieldset[disabled] .navbar-inverse .btn-link:focus,
fieldset[disabled] .navbar-inverse .btn-link:hover {
color: #444
}
.breadcrumb {
padding: 8px 15px;
margin-bottom: 20px;
list-style: none;
background-color: #f5f5f5;
border-radius: 4px
}
.breadcrumb>li {
display: inline-block
}
.breadcrumb>li+li:before {
padding: 0 5px;
color: #ccc;
content: "/\00a0"
}
.breadcrumb>.active {
color: #777
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 20px 0;
border-radius: 4px
}
.pagination>li {
display: inline
}
.pagination>li>a,
.pagination>li>span {
position: relative;
float: left;
padding: 6px 12px;
margin-left: -1px;
line-height: 1.42857143;
color: #337ab7;
text-decoration: none;
background-color: #fff;
border: 1px solid #ddd
}
.pagination>li:first-child>a,
.pagination>li:first-child>span {
margin-left: 0;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px
}
.pagination>li:last-child>a,
.pagination>li:last-child>span {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px
}
.pagination>li>a:focus,
.pagination>li>a:hover,
.pagination>li>span:focus,
.pagination>li>span:hover {
z-index: 2;
color: #23527c;
background-color: #eee;
border-color: #ddd
}
.pagination>.active>a,
.pagination>.active>a:focus,
.pagination>.active>a:hover,
.pagination>.active>span,
.pagination>.active>span:focus,
.pagination>.active>span:hover {
z-index: 3;
color: #fff;
cursor: default;
background-color: #337ab7;
border-color: #337ab7
}
.pagination>.disabled>a,
.pagination>.disabled>a:focus,
.pagination>.disabled>a:hover,
.pagination>.disabled>span,
.pagination>.disabled>span:focus,
.pagination>.disabled>span:hover {
color: #777;
cursor: not-allowed;
background-color: #fff;
border-color: #ddd
}
.pagination-lg>li>a,
.pagination-lg>li>span {
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333
}
.pagination-lg>li:first-child>a,
.pagination-lg>li:first-child>span {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px
}
.pagination-lg>li:last-child>a,
.pagination-lg>li:last-child>span {
border-top-right-radius: 6px;
border-bottom-right-radius: 6px
}
.pagination-sm>li>a,
.pagination-sm>li>span {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5
}
.pagination-sm>li:first-child>a,
.pagination-sm>li:first-child>span {
border-top-left-radius: 3px;
border-bottom-left-radius: 3px
}
.pagination-sm>li:last-child>a,
.pagination-sm>li:last-child>span {
border-top-right-radius: 3px;
border-bottom-right-radius: 3px
}
.pager {
padding-left: 0;
margin: 20px 0;
text-align: center;
list-style: none
}
.pager li {
display: inline
}
.pager li>a,
.pager li>span {
display: inline-block;
padding: 5px 14px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 15px
}
.pager li>a:focus,
.pager li>a:hover {
text-decoration: none;
background-color: #eee
}
.pager .next>a,
.pager .next>span {
float: right
}
.pager .previous>a,
.pager .previous>span {
float: left
}
.pager .disabled>a,
.pager .disabled>a:focus,
.pager .disabled>a:hover,
.pager .disabled>span {
color: #777;
cursor: not-allowed;
background-color: #fff
}
.label {
display: inline;
padding: .2em .6em .3em;
font-size: 75%;
font-weight: 700;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em
}
a.label:focus,
a.label:hover {
color: #fff;
text-decoration: none;
cursor: pointer
}
.label:empty {
display: none
}
.btn .label {
position: relative;
top: -1px
}
.label-default {
background-color: #777
}
.label-default[href]:focus,
.label-default[href]:hover {
background-color: #5e5e5e
}
.label-primary {
background-color: #337ab7
}
.label-primary[href]:focus,
.label-primary[href]:hover {
background-color: #286090
}
.label-success {
background-color: #5cb85c
}
.label-success[href]:focus,
.label-success[href]:hover {
background-color: #449d44
}
.label-info {
background-color: #5bc0de
}
.label-info[href]:focus,
.label-info[href]:hover {
background-color: #31b0d5
}
.label-warning {
background-color: #f0ad4e
}
.label-warning[href]:focus,
.label-warning[href]:hover {
background-color: #ec971f
}
.label-danger {
background-color: #d9534f
}
.label-danger[href]:focus,
.label-danger[href]:hover {
background-color: #c9302c
}
.badge {
display: inline-block;
min-width: 10px;
padding: 3px 7px;
font-size: 12px;
font-weight: 700;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: middle;
background-color: #777;
border-radius: 10px
}
.badge:empty {
display: none
}
.btn .badge {
position: relative;
top: -1px
}
.btn-group-xs>.btn .badge,
.btn-xs .badge {
top: 0;
padding: 1px 5px
}
a.badge:focus,
a.badge:hover {
color: #fff;
text-decoration: none;
cursor: pointer
}
.list-group-item.active>.badge,
.nav-pills>.active>a>.badge {
color: #337ab7;
background-color: #fff
}
.list-group-item>.badge {
float: right
}
.list-group-item>.badge+.badge {
margin-right: 5px
}
.nav-pills>li>a>.badge {
margin-left: 3px
}
.jumbotron {
padding-top: 30px;
padding-bottom: 30px;
margin-bottom: 30px;
color: inherit;
background-color: #eee
}
.jumbotron .h1,
.jumbotron h1 {
color: inherit
}
.jumbotron p {
margin-bottom: 15px;
font-size: 21px;
font-weight: 200
}
.jumbotron>hr {
border-top-color: #d5d5d5
}
.container .jumbotron,
.container-fluid .jumbotron {
padding-right: 15px;
padding-left: 15px;
border-radius: 6px
}
.jumbotron .container {
max-width: 100%
}
@media screen and (min-width:768px) {
.jumbotron {
padding-top: 48px;
padding-bottom: 48px
}
.container .jumbotron,
.container-fluid .jumbotron {
padding-right: 60px;
padding-left: 60px
}
.jumbotron .h1,
.jumbotron h1 {
font-size: 63px
}
}
.thumbnail {
display: block;
padding: 4px;
margin-bottom: 20px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: border .2s ease-in-out;
-o-transition: border .2s ease-in-out;
transition: border .2s ease-in-out
}
.thumbnail a>img,
.thumbnail>img {
margin-right: auto;
margin-left: auto
}
a.thumbnail.active,
a.thumbnail:focus,
a.thumbnail:hover {
border-color: #337ab7
}
.thumbnail .caption {
padding: 9px;
color: #333
}
.alert {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px
}
.alert h4 {
margin-top: 0;
color: inherit
}
.alert .alert-link {
font-weight: 700
}
.alert>p,
.alert>ul {
margin-bottom: 0
}
.alert>p+p {
margin-top: 5px
}
.alert-dismissable,
.alert-dismissible {
padding-right: 35px
}
.alert-dismissable .close,
.alert-dismissible .close {
position: relative;
top: -2px;
right: -21px;
color: inherit
}
.alert-success {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6
}
.alert-success hr {
border-top-color: #c9e2b3
}
.alert-success .alert-link {
color: #2b542c
}
.alert-info {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1
}
.alert-info hr {
border-top-color: #a6e1ec
}
.alert-info .alert-link {
color: #245269
}
.alert-warning {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc
}
.alert-warning hr {
border-top-color: #f7e1b5
}
.alert-warning .alert-link {
color: #66512c
}
.alert-danger {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1
}
.alert-danger hr {
border-top-color: #e4b9c0
}
.alert-danger .alert-link {
color: #843534
}
@-webkit-keyframes progress-bar-stripes {
from {
background-position: 40px 0
}
to {
background-position: 0 0
}
}
@-o-keyframes progress-bar-stripes {
from {
background-position: 40px 0
}
to {
background-position: 0 0
}
}
@keyframes progress-bar-stripes {
from {
background-position: 40px 0
}
to {
background-position: 0 0
}
}
.progress {
height: 20px;
margin-bottom: 20px;
overflow: hidden;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1)
}
.progress-bar {
float: left;
width: 0;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #337ab7;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
-webkit-transition: width .6s ease;
-o-transition: width .6s ease;
transition: width .6s ease
}
.progress-bar-striped,
.progress-striped .progress-bar {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
-webkit-background-size: 40px 40px;
background-size: 40px 40px
}
.progress-bar.active,
.progress.active .progress-bar {
-webkit-animation: progress-bar-stripes 2s linear infinite;
-o-animation: progress-bar-stripes 2s linear infinite;
animation: progress-bar-stripes 2s linear infinite
}
.progress-bar-success {
background-color: #5cb85c
}
.progress-striped .progress-bar-success {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent)
}
.progress-bar-info {
background-color: #5bc0de
}
.progress-striped .progress-bar-info {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent)
}
.progress-bar-warning {
background-color: #f0ad4e
}
.progress-striped .progress-bar-warning {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent)
}
.progress-bar-danger {
background-color: #d9534f
}
.progress-striped .progress-bar-danger {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent)
}
.media {
margin-top: 15px
}
.media:first-child {
margin-top: 0
}
.media,
.media-body {
overflow: hidden;
zoom: 1
}
.media-body {
width: 10000px
}
.media-object {
display: block
}
.media-object.img-thumbnail {
max-width: none
}
.media-right,
.media>.pull-right {
padding-left: 10px
}
.media-left,
.media>.pull-left {
padding-right: 10px
}
.media-body,
.media-left,
.media-right {
display: table-cell;
vertical-align: top
}
.media-middle {
vertical-align: middle
}
.media-bottom {
vertical-align: bottom
}
.media-heading {
margin-top: 0;
margin-bottom: 5px
}
.media-list {
padding-left: 0;
list-style: none
}
.list-group {
padding-left: 0;
margin-bottom: 20px
}
.list-group-item {
position: relative;
display: block;
padding: 10px 15px;
margin-bottom: -1px;
background-color: #fff;
border: 1px solid #ddd
}
.list-group-item:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px
}
.list-group-item:last-child {
margin-bottom: 0;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px
}
a.list-group-item,
button.list-group-item {
color: #555
}
a.list-group-item .list-group-item-heading,
button.list-group-item .list-group-item-heading {
color: #333
}
a.list-group-item:focus,
a.list-group-item:hover,
button.list-group-item:focus,
button.list-group-item:hover {
color: #555;
text-decoration: none;
background-color: #f5f5f5
}
button.list-group-item {
width: 100%;
text-align: left
}
.list-group-item.disabled,
.list-group-item.disabled:focus,
.list-group-item.disabled:hover {
color: #777;
cursor: not-allowed;
background-color: #eee
}
.list-group-item.disabled .list-group-item-heading,
.list-group-item.disabled:focus .list-group-item-heading,
.list-group-item.disabled:hover .list-group-item-heading {
color: inherit
}
.list-group-item.disabled .list-group-item-text,
.list-group-item.disabled:focus .list-group-item-text,
.list-group-item.disabled:hover .list-group-item-text {
color: #777
}
.list-group-item.active,
.list-group-item.active:focus,
.list-group-item.active:hover {
z-index: 2;
color: #fff;
background-color: #337ab7;
border-color: #337ab7
}
.list-group-item.active .list-group-item-heading,
.list-group-item.active .list-group-item-heading>.small,
.list-group-item.active .list-group-item-heading>small,
.list-group-item.active:focus .list-group-item-heading,
.list-group-item.active:focus .list-group-item-heading>.small,
.list-group-item.active:focus .list-group-item-heading>small,
.list-group-item.active:hover .list-group-item-heading,
.list-group-item.active:hover .list-group-item-heading>.small,
.list-group-item.active:hover .list-group-item-heading>small {
color: inherit
}
.list-group-item.active .list-group-item-text,
.list-group-item.active:focus .list-group-item-text,
.list-group-item.active:hover .list-group-item-text {
color: #c7ddef
}
.list-group-item-success {
color: #3c763d;
background-color: #dff0d8
}
a.list-group-item-success,
button.list-group-item-success {
color: #3c763d
}
a.list-group-item-success .list-group-item-heading,
button.list-group-item-success .list-group-item-heading {
color: inherit
}
a.list-group-item-success:focus,
a.list-group-item-success:hover,
button.list-group-item-success:focus,
button.list-group-item-success:hover {
color: #3c763d;
background-color: #d0e9c6
}
a.list-group-item-success.active,
a.list-group-item-success.active:focus,
a.list-group-item-success.active:hover,
button.list-group-item-success.active,
button.list-group-item-success.active:focus,
button.list-group-item-success.active:hover {
color: #fff;
background-color: #3c763d;
border-color: #3c763d
}
.list-group-item-info {
color: #31708f;
background-color: #d9edf7
}
a.list-group-item-info,
button.list-group-item-info {
color: #31708f
}
a.list-group-item-info .list-group-item-heading,
button.list-group-item-info .list-group-item-heading {
color: inherit
}
a.list-group-item-info:focus,
a.list-group-item-info:hover,
button.list-group-item-info:focus,
button.list-group-item-info:hover {
color: #31708f;
background-color: #c4e3f3
}
a.list-group-item-info.active,
a.list-group-item-info.active:focus,
a.list-group-item-info.active:hover,
button.list-group-item-info.active,
button.list-group-item-info.active:focus,
button.list-group-item-info.active:hover {
color: #fff;
background-color: #31708f;
border-color: #31708f
}
.list-group-item-warning {
color: #8a6d3b;
background-color: #fcf8e3
}
a.list-group-item-warning,
button.list-group-item-warning {
color: #8a6d3b
}
a.list-group-item-warning .list-group-item-heading,
button.list-group-item-warning .list-group-item-heading {
color: inherit
}
a.list-group-item-warning:focus,
a.list-group-item-warning:hover,
button.list-group-item-warning:focus,
button.list-group-item-warning:hover {
color: #8a6d3b;
background-color: #faf2cc
}
a.list-group-item-warning.active,
a.list-group-item-warning.active:focus,
a.list-group-item-warning.active:hover,
button.list-group-item-warning.active,
button.list-group-item-warning.active:focus,
button.list-group-item-warning.active:hover {
color: #fff;
background-color: #8a6d3b;
border-color: #8a6d3b
}
.list-group-item-danger {
color: #a94442;
background-color: #f2dede
}
a.list-group-item-danger,
button.list-group-item-danger {
color: #a94442
}
a.list-group-item-danger .list-group-item-heading,
button.list-group-item-danger .list-group-item-heading {
color: inherit
}
a.list-group-item-danger:focus,
a.list-group-item-danger:hover,
button.list-group-item-danger:focus,
button.list-group-item-danger:hover {
color: #a94442;
background-color: #ebcccc
}
a.list-group-item-danger.active,
a.list-group-item-danger.active:focus,
a.list-group-item-danger.active:hover,
button.list-group-item-danger.active,
button.list-group-item-danger.active:focus,
button.list-group-item-danger.active:hover {
color: #fff;
background-color: #a94442;
border-color: #a94442
}
.list-group-item-heading {
margin-top: 0;
margin-bottom: 5px
}
.list-group-item-text {
margin-bottom: 0;
line-height: 1.3
}
.panel {
margin-bottom: 20px;
background-color: #fff;
border: 1px solid transparent;
border-radius: 4px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: 0 1px 1px rgba(0, 0, 0, .05)
}
.panel-body {
padding: 15px
}
.panel-heading {
padding: 10px 15px;
border-bottom: 1px solid transparent;
border-top-left-radius: 3px;
border-top-right-radius: 3px
}
.panel-heading>.dropdown .dropdown-toggle {
color: inherit
}
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: 16px;
color: inherit
}
.panel-title>.small,
.panel-title>.small>a,
.panel-title>a,
.panel-title>small,
.panel-title>small>a {
color: inherit
}
.panel-footer {
padding: 10px 15px;
background-color: #f5f5f5;
border-top: 1px solid #ddd;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px
}
.panel>.list-group,
.panel>.panel-collapse>.list-group {
margin-bottom: 0
}
.panel>.list-group .list-group-item,
.panel>.panel-collapse>.list-group .list-group-item {
border-width: 1px 0;
border-radius: 0
}
.panel>.list-group:first-child .list-group-item:first-child,
.panel>.panel-collapse>.list-group:first-child .list-group-item:first-child {
border-top: 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px
}
.panel>.list-group:last-child .list-group-item:last-child,
.panel>.panel-collapse>.list-group:last-child .list-group-item:last-child {
border-bottom: 0;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px
}
.panel>.panel-heading+.panel-collapse>.list-group .list-group-item:first-child {
border-top-left-radius: 0;
border-top-right-radius: 0
}
.panel-heading+.list-group .list-group-item:first-child {
border-top-width: 0
}
.list-group+.panel-footer {
border-top-width: 0
}
.panel>.panel-collapse>.table,
.panel>.table,
.panel>.table-responsive>.table {
margin-bottom: 0
}
.panel>.panel-collapse>.table caption,
.panel>.table caption,
.panel>.table-responsive>.table caption {
padding-right: 15px;
padding-left: 15px
}
.panel>.table-responsive:first-child>.table:first-child,
.panel>.table:first-child {
border-top-left-radius: 3px;
border-top-right-radius: 3px
}
.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,
.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,
.panel>.table:first-child>tbody:first-child>tr:first-child,
.panel>.table:first-child>thead:first-child>tr:first-child {
border-top-left-radius: 3px;
border-top-right-radius: 3px
}
.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,
.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,
.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,
.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,
.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,
.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,
.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,
.panel>.table:first-child>thead:first-child>tr:first-child th:first-child {
border-top-left-radius: 3px
}
.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,
.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,
.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,
.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,
.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,
.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,
.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,
.panel>.table:first-child>thead:first-child>tr:first-child th:last-child {
border-top-right-radius: 3px
}
.panel>.table-responsive:last-child>.table:last-child,
.panel>.table:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px
}
.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,
.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,
.panel>.table:last-child>tbody:last-child>tr:last-child,
.panel>.table:last-child>tfoot:last-child>tr:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px
}
.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,
.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,
.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,
.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,
.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,
.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,
.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,
.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child {
border-bottom-left-radius: 3px
}
.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,
.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,
.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,
.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,
.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,
.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,
.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,
.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child {
border-bottom-right-radius: 3px
}
.panel>.panel-body+.table,
.panel>.panel-body+.table-responsive,
.panel>.table+.panel-body,
.panel>.table-responsive+.panel-body {
border-top: 1px solid #ddd
}
.panel>.table>tbody:first-child>tr:first-child td,
.panel>.table>tbody:first-child>tr:first-child th {
border-top: 0
}
.panel>.table-bordered,
.panel>.table-responsive>.table-bordered {
border: 0
}
.panel>.table-bordered>tbody>tr>td:first-child,
.panel>.table-bordered>tbody>tr>th:first-child,
.panel>.table-bordered>tfoot>tr>td:first-child,
.panel>.table-bordered>tfoot>tr>th:first-child,
.panel>.table-bordered>thead>tr>td:first-child,
.panel>.table-bordered>thead>tr>th:first-child,
.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,
.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,
.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,
.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,
.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,
.panel>.table-responsive>.table-bordered>thead>tr>th:first-child {
border-left: 0
}
.panel>.table-bordered>tbody>tr>td:last-child,
.panel>.table-bordered>tbody>tr>th:last-child,
.panel>.table-bordered>tfoot>tr>td:last-child,
.panel>.table-bordered>tfoot>tr>th:last-child,
.panel>.table-bordered>thead>tr>td:last-child,
.panel>.table-bordered>thead>tr>th:last-child,
.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,
.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,
.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,
.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,
.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,
.panel>.table-responsive>.table-bordered>thead>tr>th:last-child {
border-right: 0
}
.panel>.table-bordered>tbody>tr:first-child>td,
.panel>.table-bordered>tbody>tr:first-child>th,
.panel>.table-bordered>thead>tr:first-child>td,
.panel>.table-bordered>thead>tr:first-child>th,
.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,
.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,
.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,
.panel>.table-responsive>.table-bordered>thead>tr:first-child>th {
border-bottom: 0
}
.panel>.table-bordered>tbody>tr:last-child>td,
.panel>.table-bordered>tbody>tr:last-child>th,
.panel>.table-bordered>tfoot>tr:last-child>td,
.panel>.table-bordered>tfoot>tr:last-child>th,
.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,
.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,
.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,
.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th {
border-bottom: 0
}
.panel>.table-responsive {
margin-bottom: 0;
border: 0
}
.panel-group {
margin-bottom: 20px
}
.panel-group .panel {
margin-bottom: 0;
border-radius: 4px
}
.panel-group .panel+.panel {
margin-top: 5px
}
.panel-group .panel-heading {
border-bottom: 0
}
.panel-group .panel-heading+.panel-collapse>.list-group,
.panel-group .panel-heading+.panel-collapse>.panel-body {
border-top: 1px solid #ddd
}
.panel-group .panel-footer {
border-top: 0
}
.panel-group .panel-footer+.panel-collapse .panel-body {
border-bottom: 1px solid #ddd
}
.panel-default {
border-color: #ddd
}
.panel-default>.panel-heading {
color: #333;
background-color: #f5f5f5;
border-color: #ddd
}
.panel-default>.panel-heading+.panel-collapse>.panel-body {
border-top-color: #ddd
}
.panel-default>.panel-heading .badge {
color: #f5f5f5;
background-color: #333
}
.panel-default>.panel-footer+.panel-collapse>.panel-body {
border-bottom-color: #ddd
}
.panel-primary {
border-color: #337ab7
}
.panel-primary>.panel-heading {
color: #fff;
background-color: #337ab7;
border-color: #337ab7
}
.panel-primary>.panel-heading+.panel-collapse>.panel-body {
border-top-color: #337ab7
}
.panel-primary>.panel-heading .badge {
color: #337ab7;
background-color: #fff
}
.panel-primary>.panel-footer+.panel-collapse>.panel-body {
border-bottom-color: #337ab7
}
.panel-success {
border-color: #d6e9c6
}
.panel-success>.panel-heading {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6
}
.panel-success>.panel-heading+.panel-collapse>.panel-body {
border-top-color: #d6e9c6
}
.panel-success>.panel-heading .badge {
color: #dff0d8;
background-color: #3c763d
}
.panel-success>.panel-footer+.panel-collapse>.panel-body {
border-bottom-color: #d6e9c6
}
.panel-info {
border-color: #bce8f1
}
.panel-info>.panel-heading {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1
}
.panel-info>.panel-heading+.panel-collapse>.panel-body {
border-top-color: #bce8f1
}
.panel-info>.panel-heading .badge {
color: #d9edf7;
background-color: #31708f
}
.panel-info>.panel-footer+.panel-collapse>.panel-body {
border-bottom-color: #bce8f1
}
.panel-warning {
border-color: #faebcc
}
.panel-warning>.panel-heading {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc
}
.panel-warning>.panel-heading+.panel-collapse>.panel-body {
border-top-color: #faebcc
}
.panel-warning>.panel-heading .badge {
color: #fcf8e3;
background-color: #8a6d3b
}
.panel-warning>.panel-footer+.panel-collapse>.panel-body {
border-bottom-color: #faebcc
}
.panel-danger {
border-color: #ebccd1
}
.panel-danger>.panel-heading {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1
}
.panel-danger>.panel-heading+.panel-collapse>.panel-body {
border-top-color: #ebccd1
}
.panel-danger>.panel-heading .badge {
color: #f2dede;
background-color: #a94442
}
.panel-danger>.panel-footer+.panel-collapse>.panel-body {
border-bottom-color: #ebccd1
}
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden
}
.embed-responsive .embed-responsive-item,
.embed-responsive embed,
.embed-responsive iframe,
.embed-responsive object,
.embed-responsive video {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
border: 0
}
.embed-responsive-16by9 {
padding-bottom: 56.25%
}
.embed-responsive-4by3 {
padding-bottom: 75%
}
.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05)
}
.well blockquote {
border-color: #ddd;
border-color: rgba(0, 0, 0, .15)
}
.well-lg {
padding: 24px;
border-radius: 6px
}
.well-sm {
padding: 9px;
border-radius: 3px
}
.close {
float: right;
font-size: 21px;
font-weight: 700;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
filter: alpha(opacity=20);
opacity: .2
}
.close:focus,
.close:hover {
color: #000;
text-decoration: none;
cursor: pointer;
filter: alpha(opacity=50);
opacity: .5
}
button.close {
-webkit-appearance: none;
padding: 0;
cursor: pointer;
background: 0 0;
border: 0
}
.modal-open {
overflow: hidden
}
.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1050;
display: none;
overflow: hidden;
-webkit-overflow-scrolling: touch;
outline: 0
}
.modal.fade .modal-dialog {
-webkit-transition: -webkit-transform .3s ease-out;
-o-transition: -o-transform .3s ease-out;
transition: transform .3s ease-out;
-webkit-transform: translate(0, -25%);
-ms-transform: translate(0, -25%);
-o-transform: translate(0, -25%);
transform: translate(0, -25%)
}
.modal.in .modal-dialog {
-webkit-transform: translate(0, 0);
-ms-transform: translate(0, 0);
-o-transform: translate(0, 0);
transform: translate(0, 0)
}
.modal-open .modal {
overflow-x: hidden;
overflow-y: auto
}
.modal-dialog {
position: relative;
width: auto;
margin: 10px
}
.modal-content {
position: relative;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #999;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
outline: 0;
-webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
box-shadow: 0 3px 9px rgba(0, 0, 0, .5)
}
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1040;
background-color: #000
}
.modal-backdrop.fade {
filter: alpha(opacity=0);
opacity: 0
}
.modal-backdrop.in {
filter: alpha(opacity=50);
opacity: .5
}
.modal-header {
padding: 15px;
border-bottom: 1px solid #e5e5e5
}
.modal-header .close {
margin-top: -2px
}
.modal-title {
margin: 0;
line-height: 1.42857143
}
.modal-body {
position: relative;
padding: 15px
}
.modal-footer {
padding: 15px;
text-align: right;
border-top: 1px solid #e5e5e5
}
.modal-footer .btn+.btn {
margin-bottom: 0;
margin-left: 5px
}
.modal-footer .btn-group .btn+.btn {
margin-left: -1px
}
.modal-footer .btn-block+.btn-block {
margin-left: 0
}
.modal-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll
}
@media (min-width:768px) {
.modal-dialog {
width: 600px;
margin: 30px auto
}
.modal-content {
-webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
box-shadow: 0 5px 15px rgba(0, 0, 0, .5)
}
.modal-sm {
width: 300px
}
}
@media (min-width:992px) {
.modal-lg {
width: 900px
}
}
.tooltip {
position: absolute;
z-index: 1070;
display: block;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-weight: 400;
line-height: 1.42857143;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
letter-spacing: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
white-space: normal;
filter: alpha(opacity=0);
opacity: 0;
line-break: auto
}
.tooltip.in {
filter: alpha(opacity=90);
opacity: .9
}
.tooltip.top {
padding: 5px 0;
margin-top: -3px
}
.tooltip.right {
padding: 0 5px;
margin-left: 3px
}
.tooltip.bottom {
padding: 5px 0;
margin-top: 3px
}
.tooltip.left {
padding: 0 5px;
margin-left: -3px
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #fff;
text-align: center;
background-color: #000;
border-radius: 4px
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-width: 5px 5px 0;
border-top-color: #000
}
.tooltip.top-left .tooltip-arrow {
right: 5px;
bottom: 0;
margin-bottom: -5px;
border-width: 5px 5px 0;
border-top-color: #000
}
.tooltip.top-right .tooltip-arrow {
bottom: 0;
left: 5px;
margin-bottom: -5px;
border-width: 5px 5px 0;
border-top-color: #000
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-width: 5px 5px 5px 0;
border-right-color: #000
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-width: 5px 0 5px 5px;
border-left-color: #000
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000
}
.tooltip.bottom-left .tooltip-arrow {
top: 0;
right: 5px;
margin-top: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000
}
.tooltip.bottom-right .tooltip-arrow {
top: 0;
left: 5px;
margin-top: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1060;
display: none;
max-width: 276px;
padding: 1px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 1.42857143;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
letter-spacing: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
white-space: normal;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
line-break: auto
}
.popover.top {
margin-top: -10px
}
.popover.right {
margin-left: 10px
}
.popover.bottom {
margin-top: 10px
}
.popover.left {
margin-left: -10px
}
.popover-title {
padding: 8px 14px;
margin: 0;
font-size: 14px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
border-radius: 5px 5px 0 0
}
.popover-content {
padding: 9px 14px
}
.popover>.arrow,
.popover>.arrow:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid
}
.popover>.arrow {
border-width: 11px
}
.popover>.arrow:after {
content: "";
border-width: 10px
}
.popover.top>.arrow {
bottom: -11px;
left: 50%;
margin-left: -11px;
border-top-color: #999;
border-top-color: rgba(0, 0, 0, .25);
border-bottom-width: 0
}
.popover.top>.arrow:after {
bottom: 1px;
margin-left: -10px;
content: " ";
border-top-color: #fff;
border-bottom-width: 0
}
.popover.right>.arrow {
top: 50%;
left: -11px;
margin-top: -11px;
border-right-color: #999;
border-right-color: rgba(0, 0, 0, .25);
border-left-width: 0
}
.popover.right>.arrow:after {
bottom: -10px;
left: 1px;
content: " ";
border-right-color: #fff;
border-left-width: 0
}
.popover.bottom>.arrow {
top: -11px;
left: 50%;
margin-left: -11px;
border-top-width: 0;
border-bottom-color: #999;
border-bottom-color: rgba(0, 0, 0, .25)
}
.popover.bottom>.arrow:after {
top: 1px;
margin-left: -10px;
content: " ";
border-top-width: 0;
border-bottom-color: #fff
}
.popover.left>.arrow {
top: 50%;
right: -11px;
margin-top: -11px;
border-right-width: 0;
border-left-color: #999;
border-left-color: rgba(0, 0, 0, .25)
}
.popover.left>.arrow:after {
right: 1px;
bottom: -10px;
content: " ";
border-right-width: 0;
border-left-color: #fff
}
.carousel {
position: relative
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden
}
.carousel-inner>.item {
position: relative;
display: none;
-webkit-transition: .6s ease-in-out left;
-o-transition: .6s ease-in-out left;
transition: .6s ease-in-out left
}
.carousel-inner>.item>a>img,
.carousel-inner>.item>img {
line-height: 1
}
@media all and (transform-3d),
(-webkit-transform-3d) {
.carousel-inner>.item {
-webkit-transition: -webkit-transform .6s ease-in-out;
-o-transition: -o-transform .6s ease-in-out;
transition: transform .6s ease-in-out;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-perspective: 1000px;
perspective: 1000px
}
.carousel-inner>.item.active.right,
.carousel-inner>.item.next {
left: 0;
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0)
}
.carousel-inner>.item.active.left,
.carousel-inner>.item.prev {
left: 0;
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0)
}
.carousel-inner>.item.active,
.carousel-inner>.item.next.left,
.carousel-inner>.item.prev.right {
left: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0)
}
}
.carousel-inner>.active,
.carousel-inner>.next,
.carousel-inner>.prev {
display: block
}
.carousel-inner>.active {
left: 0
}
.carousel-inner>.next,
.carousel-inner>.prev {
position: absolute;
top: 0;
width: 100%
}
.carousel-inner>.next {
left: 100%
}
.carousel-inner>.prev {
left: -100%
}
.carousel-inner>.next.left,
.carousel-inner>.prev.right {
left: 0
}
.carousel-inner>.active.left {
left: -100%
}
.carousel-inner>.active.right {
left: 100%
}
.carousel-control {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 15%;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
background-color: rgba(0, 0, 0, 0);
filter: alpha(opacity=50);
opacity: .5
}
.carousel-control.left {
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0, rgba(0, 0, 0, .0001) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0, rgba(0, 0, 0, .0001) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0, rgba(0, 0, 0, .0001) 100%);
filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
background-repeat: repeat-x
}
.carousel-control.right {
right: 0;
left: auto;
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0, rgba(0, 0, 0, .5) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0, rgba(0, 0, 0, .5) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0, rgba(0, 0, 0, .5) 100%);
filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
background-repeat: repeat-x
}
.carousel-control:focus,
.carousel-control:hover {
color: #fff;
text-decoration: none;
filter: alpha(opacity=90);
outline: 0;
opacity: .9
}
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next,
.carousel-control .icon-prev {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
margin-top: -10px
}
.carousel-control .glyphicon-chevron-left,
.carousel-control .icon-prev {
left: 50%;
margin-left: -10px
}
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next {
right: 50%;
margin-right: -10px
}
.carousel-control .icon-next,
.carousel-control .icon-prev {
width: 20px;
height: 20px;
font-family: serif;
line-height: 1
}
.carousel-control .icon-prev:before {
content: '\2039'
}
.carousel-control .icon-next:before {
content: '\203a'
}
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 15;
width: 60%;
padding-left: 0;
margin-left: -30%;
text-align: center;
list-style: none
}
.carousel-indicators li {
display: inline-block;
width: 10px;
height: 10px;
margin: 1px;
text-indent: -999px;
cursor: pointer;
background-color: #000\9;
background-color: rgba(0, 0, 0, 0);
border: 1px solid #fff;
border-radius: 10px
}
.carousel-indicators .active {
width: 12px;
height: 12px;
margin: 0;
background-color: #fff
}
.carousel-caption {
position: absolute;
right: 15%;
bottom: 20px;
left: 15%;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6)
}
.carousel-caption .btn {
text-shadow: none
}
@media screen and (min-width:768px) {
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next,
.carousel-control .icon-prev {
width: 30px;
height: 30px;
margin-top: -10px;
font-size: 30px
}
.carousel-control .glyphicon-chevron-left,
.carousel-control .icon-prev {
margin-left: -10px
}
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next {
margin-right: -10px
}
.carousel-caption {
right: 20%;
left: 20%;
padding-bottom: 30px
}
.carousel-indicators {
bottom: 20px
}
}
.btn-group-vertical>.btn-group:after,
.btn-group-vertical>.btn-group:before,
.btn-toolbar:after,
.btn-toolbar:before,
.clearfix:after,
.clearfix:before,
.container-fluid:after,
.container-fluid:before,
.container:after,
.container:before,
.dl-horizontal dd:after,
.dl-horizontal dd:before,
.form-horizontal .form-group:after,
.form-horizontal .form-group:before,
.modal-footer:after,
.modal-footer:before,
.modal-header:after,
.modal-header:before,
.nav:after,
.nav:before,
.navbar-collapse:after,
.navbar-collapse:before,
.navbar-header:after,
.navbar-header:before,
.navbar:after,
.navbar:before,
.pager:after,
.pager:before,
.panel-body:after,
.panel-body:before,
.row:after,
.row:before {
display: table;
content: " "
}
.btn-group-vertical>.btn-group:after,
.btn-toolbar:after,
.clearfix:after,
.container-fluid:after,
.container:after,
.dl-horizontal dd:after,
.form-horizontal .form-group:after,
.modal-footer:after,
.modal-header:after,
.nav:after,
.navbar-collapse:after,
.navbar-header:after,
.navbar:after,
.pager:after,
.panel-body:after,
.row:after {
clear: both
}
.center-block {
display: block;
margin-right: auto;
margin-left: auto
}
.pull-right {
float: right!important
}
.pull-left {
float: left!important
}
.hide {
display: none!important
}
.show {
display: block!important
}
.invisible {
visibility: hidden
}
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0
}
.hidden {
display: none!important
}
.affix {
position: fixed
}
@-ms-viewport {
width: device-width
}
.visible-lg,
.visible-md,
.visible-sm,
.visible-xs {
display: none!important
}
.visible-lg-block,
.visible-lg-inline,
.visible-lg-inline-block,
.visible-md-block,
.visible-md-inline,
.visible-md-inline-block,
.visible-sm-block,
.visible-sm-inline,
.visible-sm-inline-block,
.visible-xs-block,
.visible-xs-inline,
.visible-xs-inline-block {
display: none!important
}
@media (max-width:767px) {
.visible-xs {
display: block!important
}
table.visible-xs {
display: table!important
}
tr.visible-xs {
display: table-row!important
}
td.visible-xs,
th.visible-xs {
display: table-cell!important
}
}
@media (max-width:767px) {
.visible-xs-block {
display: block!important
}
}
@media (max-width:767px) {
.visible-xs-inline {
display: inline!important
}
}
@media (max-width:767px) {
.visible-xs-inline-block {
display: inline-block!important
}
}
@media (min-width:768px) and (max-width:991px) {
.visible-sm {
display: block!important
}
table.visible-sm {
display: table!important
}
tr.visible-sm {
display: table-row!important
}
td.visible-sm,
th.visible-sm {
display: table-cell!important
}
}
@media (min-width:768px) and (max-width:991px) {
.visible-sm-block {
display: block!important
}
}
@media (min-width:768px) and (max-width:991px) {
.visible-sm-inline {
display: inline!important
}
}
@media (min-width:768px) and (max-width:991px) {
.visible-sm-inline-block {
display: inline-block!important
}
}
@media (min-width:992px) and (max-width:1199px) {
.visible-md {
display: block!important
}
table.visible-md {
display: table!important
}
tr.visible-md {
display: table-row!important
}
td.visible-md,
th.visible-md {
display: table-cell!important
}
}
@media (min-width:992px) and (max-width:1199px) {
.visible-md-block {
display: block!important
}
}
@media (min-width:992px) and (max-width:1199px) {
.visible-md-inline {
display: inline!important
}
}
@media (min-width:992px) and (max-width:1199px) {
.visible-md-inline-block {
display: inline-block!important
}
}
@media (min-width:1200px) {
.visible-lg {
display: block!important
}
table.visible-lg {
display: table!important
}
tr.visible-lg {
display: table-row!important
}
td.visible-lg,
th.visible-lg {
display: table-cell!important
}
}
@media (min-width:1200px) {
.visible-lg-block {
display: block!important
}
}
@media (min-width:1200px) {
.visible-lg-inline {
display: inline!important
}
}
@media (min-width:1200px) {
.visible-lg-inline-block {
display: inline-block!important
}
}
@media (max-width:767px) {
.hidden-xs {
display: none!important
}
}
@media (min-width:768px) and (max-width:991px) {
.hidden-sm {
display: none!important
}
}
@media (min-width:992px) and (max-width:1199px) {
.hidden-md {
display: none!important
}
}
@media (min-width:1200px) {
.hidden-lg {
display: none!important
}
}
.visible-print {
display: none!important
}
@media print {
.visible-print {
display: block!important
}
table.visible-print {
display: table!important
}
tr.visible-print {
display: table-row!important
}
td.visible-print,
th.visible-print {
display: table-cell!important
}
}
.visible-print-block {
display: none!important
}
@media print {
.visible-print-block {
display: block!important
}
}
.visible-print-inline {
display: none!important
}
@media print {
.visible-print-inline {
display: inline!important
}
}
.visible-print-inline-block {
display: none!important
}
@media print {
.visible-print-inline-block {
display: inline-block!important
}
}
@media print {
.hidden-print {
display: none!important
}
}
/*# sourceMappingURL=bootstrap.min.css.map */ | angelfu528/angelfu528.github.io | css/bootstrap.min.css | CSS | apache-2.0 | 150,056 |
//
// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.8-b130911.1802
// Vedere <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine.
// Generato il: 2014.10.23 alle 11:27:04 AM CEST
//
package org.cumulus.certificate.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Classe Java per HistoryStateType complex type.
*
* <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe.
*
* <pre>
* <complexType name="HistoryStateType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="stateId" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="refersToStateId" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HistoryStateType")
public class HistoryStateType {
@XmlAttribute(name = "stateId", required = true)
protected String stateId;
@XmlAttribute(name = "refersToStateId", required = true)
protected String refersToStateId;
/**
* Recupera il valore della proprietà stateId.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStateId() {
return stateId;
}
/**
* Imposta il valore della proprietà stateId.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStateId(String value) {
this.stateId = value;
}
/**
* Recupera il valore della proprietà refersToStateId.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRefersToStateId() {
return refersToStateId;
}
/**
* Imposta il valore della proprietà refersToStateId.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRefersToStateId(String value) {
this.refersToStateId = value;
}
}
| fgaudenzi/testManager | testManager/XMLRepository/CertificationModel/org/cumulus/certificate/model/HistoryStateType.java | Java | apache-2.0 | 2,497 |
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2013 EMC Corp.
//
// @filename:
// CMDIdCast.cpp
//
// @doc:
// Implementation of mdids for cast functions
//---------------------------------------------------------------------------
#include "naucrates/md/CMDIdCast.h"
#include "naucrates/dxl/xml/CXMLSerializer.h"
using namespace gpos;
using namespace gpmd;
//---------------------------------------------------------------------------
// @function:
// CMDIdCast::CMDIdCast
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CMDIdCast::CMDIdCast
(
CMDIdGPDB *pmdidSrc,
CMDIdGPDB *pmdidDest
)
:
m_pmdidSrc(pmdidSrc),
m_pmdidDest(pmdidDest),
m_str(m_wszBuffer, GPOS_ARRAY_SIZE(m_wszBuffer))
{
GPOS_ASSERT(pmdidSrc->FValid());
GPOS_ASSERT(pmdidDest->FValid());
// serialize mdid into static string
Serialize();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdCast::~CMDIdCast
//
// @doc:
// Dtor
//
//---------------------------------------------------------------------------
CMDIdCast::~CMDIdCast()
{
m_pmdidSrc->Release();
m_pmdidDest->Release();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdCast::Serialize
//
// @doc:
// Serialize mdid into static string
//
//---------------------------------------------------------------------------
void
CMDIdCast::Serialize()
{
// serialize mdid as SystemType.mdidSrc.mdidDest
m_str.AppendFormat
(
GPOS_WSZ_LIT("%d.%d.%d.%d;%d.%d.%d"),
Emdidt(),
m_pmdidSrc->OidObjectId(),
m_pmdidSrc->UlVersionMajor(),
m_pmdidSrc->UlVersionMinor(),
m_pmdidDest->OidObjectId(),
m_pmdidDest->UlVersionMajor(),
m_pmdidDest->UlVersionMinor()
);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdCast::Wsz
//
// @doc:
// Returns the string representation of the mdid
//
//---------------------------------------------------------------------------
const WCHAR *
CMDIdCast::Wsz() const
{
return m_str.Wsz();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdCast::PmdidSrc
//
// @doc:
// Returns the source type id
//
//---------------------------------------------------------------------------
IMDId *
CMDIdCast::PmdidSrc() const
{
return m_pmdidSrc;
}
//---------------------------------------------------------------------------
// @function:
// CMDIdCast::PmdidDest
//
// @doc:
// Returns the destination type id
//
//---------------------------------------------------------------------------
IMDId *
CMDIdCast::PmdidDest() const
{
return m_pmdidDest;
}
//---------------------------------------------------------------------------
// @function:
// CMDIdCast::FEquals
//
// @doc:
// Checks if the mdids are equal
//
//---------------------------------------------------------------------------
BOOL
CMDIdCast::FEquals
(
const IMDId *pmdid
)
const
{
if (NULL == pmdid || EmdidCastFunc != pmdid->Emdidt())
{
return false;
}
const CMDIdCast *pmdidCastFunc = CMDIdCast::PmdidConvert(pmdid);
return m_pmdidSrc->FEquals(pmdidCastFunc->PmdidSrc()) &&
m_pmdidDest->FEquals(pmdidCastFunc->PmdidDest());
}
//---------------------------------------------------------------------------
// @function:
// CMDIdCast::Serialize
//
// @doc:
// Serializes the mdid as the value of the given attribute
//
//---------------------------------------------------------------------------
void
CMDIdCast::Serialize
(
CXMLSerializer * pxmlser,
const CWStringConst *pstrAttribute
)
const
{
pxmlser->AddAttribute(pstrAttribute, &m_str);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdCast::OsPrint
//
// @doc:
// Debug print of the id in the provided stream
//
//---------------------------------------------------------------------------
IOstream &
CMDIdCast::OsPrint
(
IOstream &os
)
const
{
os << "(" << m_str.Wsz() << ")";
return os;
}
// EOF
| PengJi/gporca-comments | libnaucrates/src/md/CMDIdCast.cpp | C++ | apache-2.0 | 4,157 |
/*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.serverhealth;
import com.thoughtworks.go.config.CruiseConfig;
import com.thoughtworks.go.config.CruiseConfigProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class ServerHealthService implements ApplicationContextAware {
private static final Logger LOG = LoggerFactory.getLogger(ServerHealthService.class);
private HashMap<ServerHealthState, Set<String>> pipelinesWithErrors;
private Map<HealthStateType, ServerHealthState> serverHealth;
private ApplicationContext applicationContext;
public ServerHealthService() {
this.serverHealth = new ConcurrentHashMap<>();
this.pipelinesWithErrors = new HashMap<>();
}
public void removeByScope(HealthStateScope scope) {
for (HealthStateType healthStateType : entryKeys()) {
if (healthStateType.isSameScope(scope)) {
serverHealth.remove(healthStateType);
}
}
}
private Set<HealthStateType> entryKeys() {
return new HashSet<>(serverHealth.keySet());
}
public List<ServerHealthState> filterByScope(HealthStateScope scope) {
List<ServerHealthState> filtered = new ArrayList<>();
for (Map.Entry<HealthStateType, ServerHealthState> entry : sortedEntries()) {
HealthStateType type = entry.getKey();
if (type.isSameScope(scope)) {
filtered.add(entry.getValue());
}
}
return filtered;
}
public HealthStateType update(ServerHealthState serverHealthState) {
HealthStateType type = serverHealthState.getType();
if (serverHealthState.getLogLevel() == HealthStateLevel.OK) {
if (serverHealth.containsKey(type)) {
serverHealth.remove(type);
}
return null;
} else {
serverHealth.put(type, serverHealthState);
return type;
}
}
// called from spring timer
public synchronized void onTimer() {
CruiseConfig currentConfig = applicationContext.getBean(CruiseConfigProvider.class).getCurrentConfig();
purgeStaleHealthMessages(currentConfig);
LOG.debug("Recomputing material to pipeline mappings.");
HashMap<ServerHealthState, Set<String>> erroredPipelines = new HashMap<>();
for (Map.Entry<HealthStateType, ServerHealthState> entry : serverHealth.entrySet()) {
erroredPipelines.put(entry.getValue(), entry.getValue().getPipelineNames(currentConfig));
}
pipelinesWithErrors = erroredPipelines;
LOG.debug("Done recomputing material to pipeline mappings.");
}
public Set<String> getPipelinesWithErrors(ServerHealthState serverHealthState) {
return pipelinesWithErrors.get(serverHealthState);
}
void purgeStaleHealthMessages(CruiseConfig cruiseConfig) {
removeMessagesForElementsNoLongerInConfig(cruiseConfig);
removeExpiredMessages();
}
@Deprecated(forRemoval = true) // Remove once we get rid of SpringJUnitTestRunner
public void removeAllLogs() {
serverHealth.clear();
}
private void removeMessagesForElementsNoLongerInConfig(CruiseConfig cruiseConfig) {
for (HealthStateType type : entryKeys()) {
if (type.isRemovedFromConfig(cruiseConfig)) {
this.removeByScope(type);
}
}
}
private void removeExpiredMessages() {
for (Map.Entry<HealthStateType, ServerHealthState> entry : new HashSet<>(serverHealth.entrySet())) {
ServerHealthState value = entry.getValue();
if (value.hasExpired()) {
serverHealth.remove(entry.getKey());
}
}
}
private void removeByScope(HealthStateType type) {
removeByScope(type.getScope());
}
public ServerHealthStates logs() {
ArrayList<ServerHealthState> logs = new ArrayList<>();
for (Map.Entry<HealthStateType, ServerHealthState> entry : sortedEntries()) {
logs.add(entry.getValue());
}
return new ServerHealthStates(logs);
}
private List<Map.Entry<HealthStateType, ServerHealthState>> sortedEntries() {
List<Map.Entry<HealthStateType, ServerHealthState>> entries = new ArrayList<>(serverHealth.entrySet());
entries.sort(Comparator.comparing(Map.Entry::getKey));
return entries;
}
public String getLogsAsText() {
StringBuilder text = new StringBuilder();
for (ServerHealthState state : logs()) {
text.append(state.getDescription());
text.append("\n\t");
text.append(state.getMessage());
text.append("\n");
}
return text.toString();
}
public boolean containsError(HealthStateType type, HealthStateLevel level) {
ServerHealthStates allLogs = logs();
for (ServerHealthState log : allLogs) {
if (log.getType().equals(type) && log.getLogLevel() == level) {
return true;
}
}
return false;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| GaneshSPatil/gocd | common/src/main/java/com/thoughtworks/go/serverhealth/ServerHealthService.java | Java | apache-2.0 | 6,153 |
package gov.ic.geoint.spreadsheet;
/**
*
*/
public interface ICell extends Hashable {
/**
*
* @return
*/
public int getColumnNum();
/**
*
* @return
*/
public int getRowNum();
/**
*
* @return
*/
public String getValue();
}
| GEOINT/spreadsheetDiff | src/main/java/gov/ic/geoint/spreadsheet/ICell.java | Java | apache-2.0 | 298 |
package sdk.chat.demo.examples.api;
import io.reactivex.functions.Consumer;
import sdk.guru.common.DisposableMap;
public class BaseExample implements Consumer<Throwable> {
// Add the disposables to a map so you can dispose of them all at one time
protected DisposableMap dm = new DisposableMap();
@Override
public void accept(Throwable throwable) throws Exception {
// Handle exception
}
}
| chat-sdk/chat-sdk-android | chat-sdk-demo/src/main/java/sdk/chat/demo/examples/api/BaseExample.java | Java | apache-2.0 | 423 |
//Copyright (c) 2014 by Disy Informationssysteme GmbH
package net.disy.eenvplus.tfes.core.api.query;
// NOT_PUBLISHED
public interface ISuggestionQuery extends ISourceQuery {
String getKeyword();
}
| eENVplus/tf-exploitation-server | TF_Exploitation_Server_core/src/main/java/net/disy/eenvplus/tfes/core/api/query/ISuggestionQuery.java | Java | apache-2.0 | 201 |
////////////////////////////////////////////////////////////////////////////
// Module : script_value_container_impl.h
// Created : 16.07.2004
// Modified : 16.07.2004
// Author : Dmitriy Iassenev
// Description : Script value container
////////////////////////////////////////////////////////////////////////////
#pragma once
#include "object_broker.h"
#ifdef XRSE_FACTORY_EXPORTS
#include "script_value.h"
#endif
IC CScriptValueContainer::~CScriptValueContainer() { clear(); }
IC void CScriptValueContainer::add(CScriptValue* new_value) {
#ifdef XRSE_FACTORY_EXPORTS
CScriptValue* value = 0;
xr_vector<CScriptValue*>::const_iterator I = m_values.begin();
xr_vector<CScriptValue*>::const_iterator E = m_values.end();
for (; I != E; ++I)
if (!xr_strcmp((*I)->name(), new_value->name())) {
value = *I;
break;
}
if (value)
return;
m_values.push_back(new_value);
#endif
}
IC void CScriptValueContainer::assign() {
#ifdef XRSE_FACTORY_EXPORTS
xr_vector<CScriptValue*>::iterator I = m_values.begin();
xr_vector<CScriptValue*>::iterator E = m_values.end();
for (; I != E; ++I)
(*I)->assign();
#endif
}
IC void CScriptValueContainer::clear() { delete_data(m_values); }
| Im-dex/xray-162 | code/engine/xrServerEntities/script_value_container_impl.h | C | apache-2.0 | 1,268 |
package com.jwetherell.algorithms.data_structures.interfaces;
/**
* A tree can be defined recursively (locally) as a collection of nodes (starting at a root node),
* where each node is a data structure consisting of a value, together with a list of nodes (the "children"),
* with the constraints that no node is duplicated. A tree can be defined abstractly as a whole (globally)
* as an ordered tree, with a value assigned to each node.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)">Tree (Wikipedia)</a>
* <br>
* @author Justin Wetherell <[email protected]>
*/
public interface ITree<T> {
/**
* Add value to the tree. Tree can contain multiple equal values.
*
* @param value to add to the tree.
* @return True if successfully added to tree.
*/
public boolean add(T value);
/**
* Remove first occurrence of value in the tree.
*
* @param value to remove from the tree.
* @return T value removed from tree.
*/
public T remove(T value);
/**
* Clear the entire stack.
*/
public void clear();
/**
* Does the tree contain the value.
*
* @param value to locate in the tree.
* @return True if tree contains value.
*/
public boolean contains(T value);
/**
* Get number of nodes in the tree.
*
* @return Number of nodes in the tree.
*/
public int size();
/**
* Validate the tree according to the invariants.
*
* @return True if the tree is valid.
*/
public boolean validate();
/**
* Get Tree as a Java compatible Collection
*
* @return Java compatible Collection
*/
public java.util.Collection<T> toCollection();
}
| phishman3579/java-algorithms-implementation | src/com/jwetherell/algorithms/data_structures/interfaces/ITree.java | Java | apache-2.0 | 1,766 |
/*
* Copyright 2014, The Sporting Exchange Limited
* Copyright 2014, Simon Matić Langford
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.exemel.disco.transport.jetty;
import uk.co.exemel.disco.DiscoVersion;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.junit.Test;
import java.util.Collections;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
/**
* Unit tests for {@link uk.co.exemel.disco.transport.jetty.CrossOriginHandler}
*/
public class CrossOriginHandlerTest {
@Test
public void testHandlerSetsServerHeaderInTheResponse() throws Exception {
final CrossOriginHandler victim = new CrossOriginHandler("betfair.com", "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", "");
final MockJettyRequest req = mock(MockJettyRequest.class);
final MockJettyResponse res = mock(MockJettyResponse.class);
victim.handle("/", req, req, res);
verify(res, times(1)).setHeader(eq("Server"), eq("Disco 2 - " + DiscoVersion.getVersion()));
}
@Test
public void testHandlerMarksRequestAsHandledByDefault() throws Exception {
final CrossOriginHandler victim = new CrossOriginHandler("betfair.com", "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", "");
final MockJettyRequest req = mock(MockJettyRequest.class);
final MockJettyResponse res = mock(MockJettyResponse.class);
victim.handle("/", req, req, res);
verify(req, times(1)).setHandled(eq(true));
verify(req, times(1)).setHandled(eq(false));
}
@Test
public void testHandlerUnmarksRequestAsHandledIfFilterContinuesTheChainExplicitDomain() throws Exception {
testHandlesCrossOriginRequest("betfair.com", true);
}
@Test
public void testHandlerUnmarksRequestAsHandledIfFilterContinuesTheChainAllDomains() throws Exception {
testHandlesCrossOriginRequest("*", true);
}
@Test
public void testHandlerUnmarksRequestAsHandledIfFilterContinuesTheChainNoDomains() throws Exception {
testHandlesCrossOriginRequest("", false);
}
private void testHandlesCrossOriginRequest(String domains, boolean wantHandled) throws Exception {
final CrossOriginHandler victim = new CrossOriginHandler(domains, "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", "");
final MockJettyRequest req = mock(MockJettyRequest.class);
final MockJettyResponse res = mock(MockJettyResponse.class);
when(req.getMethod()).thenReturn("OPTIONS");
when(req.getHeader("Origin")).thenReturn("betfair.com");
when(req.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER)).thenReturn("PUT");
when(req.getHeaders("Connection")).thenReturn(Collections.<String>emptyEnumeration());
victim.handle("/", req, req, res);
// this is always called
verify(req, times(1)).setHandled(eq(true));
if (wantHandled) {
verify(req, never()).setHandled(eq(false));
}
else {
verify(req, times(1)).setHandled(eq(false));
}
}
}
| eswdd/disco | disco-framework/jetty-transport/src/test/java/uk/co/exemel/disco/transport/jetty/CrossOriginHandlerTest.java | Java | apache-2.0 | 3,706 |
package org.nd4j.linalg.indexing;
import com.google.common.base.Function;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.nd4j.linalg.BaseNd4jTest;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.accum.MatchCondition;
import org.nd4j.linalg.api.ops.impl.transforms.comparison.CompareAndReplace;
import org.nd4j.linalg.api.ops.impl.transforms.comparison.CompareAndSet;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import org.nd4j.linalg.indexing.conditions.AbsValueGreaterThan;
import org.nd4j.linalg.indexing.conditions.Condition;
import org.nd4j.linalg.indexing.conditions.Conditions;
import org.nd4j.linalg.indexing.functions.Value;
import java.util.Arrays;
import static org.junit.Assert.*;
/**
* @author [email protected]
*/
@RunWith(Parameterized.class)
public class BooleanIndexingTest extends BaseNd4jTest {
public BooleanIndexingTest(Nd4jBackend backend) {
super(backend);
}
/*
1D array checks
*/
@Test
public void testAnd1() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.and(array, Conditions.greaterThan(0.5f)));
}
@Test
public void testAnd2() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.and(array, Conditions.lessThan(6.0f)));
}
@Test
public void testAnd3() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertFalse(BooleanIndexing.and(array, Conditions.lessThan(5.0f)));
}
@Test
public void testAnd4() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertFalse(BooleanIndexing.and(array, Conditions.greaterThan(4.0f)));
}
@Test
public void testAnd5() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f, 1e-5f, 1e-5f});
assertTrue(BooleanIndexing.and(array, Conditions.greaterThanOrEqual(1e-5f)));
}
@Test
public void testAnd6() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f, 1e-5f, 1e-5f});
assertFalse(BooleanIndexing.and(array, Conditions.lessThan(1e-5f)));
}
@Test
public void testAnd7() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f, 1e-5f, 1e-5f});
assertTrue(BooleanIndexing.and(array, Conditions.equals(1e-5f)));
}
@Test
public void testOr1() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.or(array, Conditions.greaterThan(3.0f)));
}
@Test
public void testOr2() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.or(array, Conditions.lessThan(3.0f)));
}
@Test
public void testOr3() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertFalse(BooleanIndexing.or(array, Conditions.greaterThan(6.0f)));
}
@Test
public void testApplyWhere1() throws Exception {
INDArray array = Nd4j.create(new float[] {-1f, -1f, -1f, -1f, -1f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(Nd4j.EPS_THRESHOLD), new Value(Nd4j.EPS_THRESHOLD));
//System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
assertTrue(BooleanIndexing.and(array, Conditions.equals(Nd4j.EPS_THRESHOLD)));
}
@Test
public void testApplyWhere2() throws Exception {
INDArray array = Nd4j.create(new float[] {0f, 0f, 0f, 0f, 0f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(1.0f), new Value(1.0f));
assertTrue(BooleanIndexing.and(array, Conditions.equals(1.0f)));
}
@Test
public void testApplyWhere3() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-18f, 1e-18f, 1e-18f, 1e-18f, 1e-18f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(1e-12f), new Value(1e-12f));
//System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
assertTrue(BooleanIndexing.and(array, Conditions.equals(1e-12f)));
}
@Test
public void testApplyWhere4() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-18f, Float.NaN, 1e-18f, 1e-18f, 1e-18f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(1e-12f), new Value(1e-12f));
//System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
BooleanIndexing.applyWhere(array, Conditions.isNan(), new Value(1e-16f));
System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
assertFalse(BooleanIndexing.or(array, Conditions.isNan()));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1e-12f)));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1e-16f)));
}
/*
2D array checks
*/
@Test
public void test2dAnd1() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
assertTrue(BooleanIndexing.and(array, Conditions.equals(0f)));
}
@Test
public void test2dAnd2() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
array.slice(4).putScalar(2, 1e-5f);
System.out.println(array);
assertFalse(BooleanIndexing.and(array, Conditions.equals(0f)));
}
@Test
public void test2dAnd3() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
array.slice(4).putScalar(2, 1e-5f);
assertFalse(BooleanIndexing.and(array, Conditions.greaterThan(0f)));
}
@Test
public void test2dAnd4() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
array.slice(4).putScalar(2, 1e-5f);
assertTrue(BooleanIndexing.or(array, Conditions.greaterThan(1e-6f)));
}
@Test
public void test2dApplyWhere1() throws Exception {
INDArray array = Nd4j.ones(4, 4);
array.slice(3).putScalar(2, 1e-5f);
//System.out.println("Array before: " + Arrays.toString(array.data().asFloat()));
BooleanIndexing.applyWhere(array, Conditions.lessThan(1e-4f), new Value(1e-12f));
//System.out.println("Array after 1: " + Arrays.toString(array.data().asFloat()));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1e-12f)));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1.0f)));
assertFalse(BooleanIndexing.and(array, Conditions.equals(1e-12f)));
}
/**
* This test fails, because it highlights current mechanics on SpecifiedIndex stuff.
* Internally there's
*
* @throws Exception
*/
@Test
public void testSliceAssign1() throws Exception {
INDArray array = Nd4j.zeros(4, 4);
INDArray patch = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f});
INDArray slice = array.slice(1);
int[] idx = new int[] {0, 1, 3};
INDArrayIndex[] range = new INDArrayIndex[] {new SpecifiedIndex(idx)};
INDArray subarray = slice.get(range);
System.out.println("Subarray: " + Arrays.toString(subarray.data().asFloat()) + " isView: " + subarray.isView());
slice.put(range, patch);
System.out.println("Array after being patched: " + Arrays.toString(array.data().asFloat()));
assertFalse(BooleanIndexing.and(array, Conditions.equals(0f)));
}
@Test
public void testConditionalAssign1() throws Exception {
INDArray array1 = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7});
INDArray array2 = Nd4j.create(new double[] {7, 6, 5, 4, 3, 2, 1});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 3, 2, 1});
BooleanIndexing.replaceWhere(array1, array2, Conditions.greaterThan(4));
assertEquals(comp, array1);
}
@Test
public void testCaSTransform1() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(array, 3, Conditions.equals(0)));
assertEquals(comp, array);
}
@Test
public void testCaSTransform2() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {3, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(array, 3.0, Conditions.lessThan(2)));
assertEquals(comp, array);
}
@Test
public void testCaSPairwiseTransform1() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(array, comp, Conditions.lessThan(5)));
assertEquals(comp, array);
}
@Test
public void testCaRPairwiseTransform1() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(array, comp, Conditions.lessThan(1)));
assertEquals(comp, array);
}
@Test
public void testCaSPairwiseTransform2() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 0, 5});
INDArray comp = Nd4j.create(new double[] {2, 4, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(x, y, Conditions.epsNotEquals(0.0)));
assertEquals(comp, x);
}
@Test
public void testCaRPairwiseTransform2() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 4, 5});
INDArray comp = Nd4j.create(new double[] {2, 4, 0, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(x, y, Conditions.epsNotEquals(0.0)));
assertEquals(comp, x);
}
@Test
public void testCaSPairwiseTransform3() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 4, 5});
INDArray comp = Nd4j.create(new double[] {2, 4, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(x, y, Conditions.lessThan(4)));
assertEquals(comp, x);
}
@Test
public void testCaRPairwiseTransform3() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 4, 5});
INDArray comp = Nd4j.create(new double[] {2, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(x, y, Conditions.lessThan(2)));
assertEquals(comp, x);
}
@Test
public void testMatchConditionAllDimensions1() throws Exception {
INDArray array = Nd4j.create(new double[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
int val = (int) Nd4j.getExecutioner().exec(new MatchCondition(array, Conditions.lessThan(5)), Integer.MAX_VALUE)
.getDouble(0);
assertEquals(5, val);
}
@Test
public void testMatchConditionAllDimensions2() throws Exception {
INDArray array = Nd4j.create(new double[] {0, 1, 2, 3, Double.NaN, 5, 6, 7, 8, 9});
int val = (int) Nd4j.getExecutioner().exec(new MatchCondition(array, Conditions.isNan()), Integer.MAX_VALUE)
.getDouble(0);
assertEquals(1, val);
}
@Test
public void testMatchConditionAllDimensions3() throws Exception {
INDArray array = Nd4j.create(new double[] {0, 1, 2, 3, Double.NEGATIVE_INFINITY, 5, 6, 7, 8, 9});
int val = (int) Nd4j.getExecutioner()
.exec(new MatchCondition(array, Conditions.isInfinite()), Integer.MAX_VALUE).getDouble(0);
assertEquals(1, val);
}
@Test
public void testAbsValueGreaterThan() {
final double threshold = 2;
Condition absValueCondition = new AbsValueGreaterThan(threshold);
Function<Number, Number> clipFn = new Function<Number, Number>() {
@Override
public Number apply(Number number) {
System.out.println("Number: " + number.doubleValue());
return (number.doubleValue() > threshold ? threshold : -threshold);
}
};
Nd4j.getRandom().setSeed(12345);
INDArray orig = Nd4j.rand(1, 20).muli(6).subi(3); //Random numbers: -3 to 3
INDArray exp = orig.dup();
INDArray after = orig.dup();
for (int i = 0; i < exp.length(); i++) {
double d = exp.getDouble(i);
if (d > threshold) {
exp.putScalar(i, threshold);
} else if (d < -threshold) {
exp.putScalar(i, -threshold);
}
}
BooleanIndexing.applyWhere(after, absValueCondition, clipFn);
System.out.println(orig);
System.out.println(exp);
System.out.println(after);
assertEquals(exp, after);
}
@Test
public void testMatchConditionAlongDimension1() throws Exception {
INDArray array = Nd4j.ones(3, 10);
array.getRow(2).assign(0.0);
boolean result[] = BooleanIndexing.and(array, Conditions.equals(0.0), 1);
boolean comp[] = new boolean[] {false, false, true};
System.out.println("Result: " + Arrays.toString(result));
assertArrayEquals(comp, result);
}
@Test
public void testMatchConditionAlongDimension2() throws Exception {
INDArray array = Nd4j.ones(3, 10);
array.getRow(2).assign(0.0).putScalar(0, 1.0);
System.out.println("Array: " + array);
boolean result[] = BooleanIndexing.or(array, Conditions.lessThan(0.9), 1);
boolean comp[] = new boolean[] {false, false, true};
System.out.println("Result: " + Arrays.toString(result));
assertArrayEquals(comp, result);
}
@Test
public void testMatchConditionAlongDimension3() throws Exception {
INDArray array = Nd4j.ones(3, 10);
array.getRow(2).assign(0.0).putScalar(0, 1.0);
boolean result[] = BooleanIndexing.and(array, Conditions.lessThan(0.0), 1);
boolean comp[] = new boolean[] {false, false, false};
System.out.println("Result: " + Arrays.toString(result));
assertArrayEquals(comp, result);
}
@Test
public void testConditionalUpdate() {
INDArray arr = Nd4j.linspace(-2, 2, 5);
INDArray ones = Nd4j.ones(5);
INDArray exp = Nd4j.create(new double[] {1, 1, 0, 1, 1});
Nd4j.getExecutioner().exec(new CompareAndSet(ones, arr, ones, Conditions.equals(0.0)));
assertEquals(exp, ones);
}
@Test
public void testFirstIndex1() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
INDArray result = BooleanIndexing.firstIndex(arr, Conditions.greaterThanOrEqual(3));
assertEquals(2, result.getDouble(0), 0.0);
}
@Test
public void testFirstIndex2() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
INDArray result = BooleanIndexing.firstIndex(arr, Conditions.lessThan(3));
assertEquals(0, result.getDouble(0), 0.0);
}
@Test
public void testLastIndex1() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
INDArray result = BooleanIndexing.lastIndex(arr, Conditions.greaterThanOrEqual(3));
assertEquals(8, result.getDouble(0), 0.0);
}
@Test
public void testFirstIndex2D() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 0, 1, 3, 7, 8, 9}).reshape('c', 3, 3);
INDArray result = BooleanIndexing.firstIndex(arr, Conditions.greaterThanOrEqual(2), 1);
INDArray exp = Nd4j.create(new double[] {1, 2, 0});
assertEquals(exp, result);
}
@Test
public void testLastIndex2D() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 0, 1, 3, 7, 8, 0}).reshape('c', 3, 3);
INDArray result = BooleanIndexing.lastIndex(arr, Conditions.greaterThanOrEqual(2), 1);
INDArray exp = Nd4j.create(new double[] {2, 2, 1});
assertEquals(exp, result);
}
@Test
public void testEpsEquals1() throws Exception {
INDArray array = Nd4j.create(new double[]{-1, -1, -1e-8, 1e-8, 1, 1});
MatchCondition condition = new MatchCondition(array, Conditions.epsEquals(0.0));
int numZeroes = Nd4j.getExecutioner().exec(condition, Integer.MAX_VALUE).getInt(0);
assertEquals(2, numZeroes);
}
@Override
public char ordering() {
return 'c';
}
}
| huitseeker/nd4j | nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/indexing/BooleanIndexingTest.java | Java | apache-2.0 | 17,052 |
# coding: utf-8
#
# Copyright 2018 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.
"""Tests for methods in the action registry."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
from core.domain import action_registry
from core.tests import test_utils
class ActionRegistryUnitTests(test_utils.GenericTestBase):
"""Test for the action registry."""
def test_action_registry(self):
"""Do some sanity checks on the action registry."""
self.assertEqual(
len(action_registry.Registry.get_all_actions()), 3)
| prasanna08/oppia | core/domain/action_registry_test.py | Python | apache-2.0 | 1,192 |
package com.xiaojinzi.component.error;
public class ServiceRepeatCreateException extends RuntimeException {
public ServiceRepeatCreateException() {
}
public ServiceRepeatCreateException(String message) {
super(message);
}
public ServiceRepeatCreateException(String message, Throwable cause) {
super(message, cause);
}
public ServiceRepeatCreateException(Throwable cause) {
super(cause);
}
}
| xiaojinzi123/Component | ComponentImpl/src/main/java/com/xiaojinzi/component/error/ServiceRepeatCreateException.java | Java | apache-2.0 | 453 |
#/bin/bash
set -x
#wget --user [email protected] --password New=1baby --no-check-certificate -c -r -np -k -L -p \
wget -c -r -np -k -L -p \
http://rchgsa.ibm.com/projects/e/emsol/ccs/build/driver/osee-liberty/rhel7.1/openstack/latest-bld/
| linzhaolover/myansible | remote/liberty.sh | Shell | apache-2.0 | 254 |
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Conversion from AST representation of types to the ty.rs
//! representation. The main routine here is `ast_ty_to_ty()`: each use
//! is parameterized by an instance of `AstConv` and a `RegionScope`.
//!
//! The parameterization of `ast_ty_to_ty()` is because it behaves
//! somewhat differently during the collect and check phases,
//! particularly with respect to looking up the types of top-level
//! items. In the collect phase, the crate context is used as the
//! `AstConv` instance; in this phase, the `get_item_type_scheme()`
//! function triggers a recursive call to `type_scheme_of_item()`
//! (note that `ast_ty_to_ty()` will detect recursive types and report
//! an error). In the check phase, when the FnCtxt is used as the
//! `AstConv`, `get_item_type_scheme()` just looks up the item type in
//! `tcx.tcache` (using `ty::lookup_item_type`).
//!
//! The `RegionScope` trait controls what happens when the user does
//! not specify a region in some location where a region is required
//! (e.g., if the user writes `&Foo` as a type rather than `&'a Foo`).
//! See the `rscope` module for more details.
//!
//! Unlike the `AstConv` trait, the region scope can change as we descend
//! the type. This is to accommodate the fact that (a) fn types are binding
//! scopes and (b) the default region may change. To understand case (a),
//! consider something like:
//!
//! type foo = { x: &a.int, y: |&a.int| }
//!
//! The type of `x` is an error because there is no region `a` in scope.
//! In the type of `y`, however, region `a` is considered a bound region
//! as it does not already appear in scope.
//!
//! Case (b) says that if you have a type:
//! type foo<'a> = ...;
//! type bar = fn(&foo, &a.foo)
//! The fully expanded version of type bar is:
//! type bar = fn(&'foo &, &a.foo<'a>)
//! Note that the self region for the `foo` defaulted to `&` in the first
//! case but `&a` in the second. Basically, defaults that appear inside
//! an rptr (`&r.T`) use the region `r` that appears in the rptr.
use middle::astconv_util::{prim_ty_to_ty, check_path_args, NO_TPS, NO_REGIONS};
use middle::const_eval;
use middle::def;
use middle::resolve_lifetime as rl;
use middle::privacy::{AllPublic, LastMod};
use middle::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs};
use middle::traits;
use middle::ty::{self, RegionEscape, Ty};
use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope, ExplicitRscope,
ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope};
use util::common::{ErrorReported, FN_OUTPUT_NAME};
use util::nodemap::FnvHashSet;
use util::ppaux::{self, Repr, UserString};
use std::iter::repeat;
use std::rc::Rc;
use std::slice;
use syntax::{abi, ast, ast_util};
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::print::pprust;
pub trait AstConv<'tcx> {
fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
/// Identify the type scheme for an item with a type, like a type
/// alias, fn, or struct. This allows you to figure out the set of
/// type parameters defined on the item.
fn get_item_type_scheme(&self, span: Span, id: ast::DefId)
-> Result<ty::TypeScheme<'tcx>, ErrorReported>;
/// Returns the `TraitDef` for a given trait. This allows you to
/// figure out the set of type parameters defined on the trait.
fn get_trait_def(&self, span: Span, id: ast::DefId)
-> Result<Rc<ty::TraitDef<'tcx>>, ErrorReported>;
/// Ensure that the super-predicates for the trait with the given
/// id are available and also for the transitive set of
/// super-predicates.
fn ensure_super_predicates(&self, span: Span, id: ast::DefId)
-> Result<(), ErrorReported>;
/// Returns the set of bounds in scope for the type parameter with
/// the given id.
fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
-> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
/// Returns true if the trait with id `trait_def_id` defines an
/// associated type with the name `name`.
fn trait_defines_associated_type_named(&self, trait_def_id: ast::DefId, name: ast::Name)
-> bool;
/// Return an (optional) substitution to convert bound type parameters that
/// are in scope into free ones. This function should only return Some
/// within a fn body.
/// See ParameterEnvironment::free_substs for more information.
fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
None
}
/// What type should we use when a type is omitted?
fn ty_infer(&self, span: Span) -> Ty<'tcx>;
/// Projecting an associated type from a (potentially)
/// higher-ranked trait reference is more complicated, because of
/// the possibility of late-bound regions appearing in the
/// associated type binding. This is not legal in function
/// signatures for that reason. In a function body, we can always
/// handle it because we can use inference variables to remove the
/// late-bound regions.
fn projected_ty_from_poly_trait_ref(&self,
span: Span,
poly_trait_ref: ty::PolyTraitRef<'tcx>,
item_name: ast::Name)
-> Ty<'tcx>
{
if ty::binds_late_bound_regions(self.tcx(), &poly_trait_ref) {
span_err!(self.tcx().sess, span, E0212,
"cannot extract an associated type from a higher-ranked trait bound \
in this context");
self.tcx().types.err
} else {
// no late-bound regions, we can just ignore the binder
self.projected_ty(span, poly_trait_ref.0.clone(), item_name)
}
}
/// Project an associated type from a non-higher-ranked trait reference.
/// This is fairly straightforward and can be accommodated in any context.
fn projected_ty(&self,
span: Span,
_trait_ref: Rc<ty::TraitRef<'tcx>>,
_item_name: ast::Name)
-> Ty<'tcx>;
}
pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &ast::Lifetime)
-> ty::Region {
let r = match tcx.named_region_map.get(&lifetime.id) {
None => {
// should have been recorded by the `resolve_lifetime` pass
tcx.sess.span_bug(lifetime.span, "unresolved lifetime");
}
Some(&rl::DefStaticRegion) => {
ty::ReStatic
}
Some(&rl::DefLateBoundRegion(debruijn, id)) => {
ty::ReLateBound(debruijn, ty::BrNamed(ast_util::local_def(id), lifetime.name))
}
Some(&rl::DefEarlyBoundRegion(space, index, id)) => {
ty::ReEarlyBound(id, space, index, lifetime.name)
}
Some(&rl::DefFreeRegion(scope, id)) => {
ty::ReFree(ty::FreeRegion {
scope: scope,
bound_region: ty::BrNamed(ast_util::local_def(id),
lifetime.name)
})
}
};
debug!("ast_region_to_region(lifetime={} id={}) yields {}",
lifetime.repr(tcx),
lifetime.id,
r.repr(tcx));
r
}
pub fn opt_ast_region_to_region<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
default_span: Span,
opt_lifetime: &Option<ast::Lifetime>) -> ty::Region
{
let r = match *opt_lifetime {
Some(ref lifetime) => {
ast_region_to_region(this.tcx(), lifetime)
}
None => {
match rscope.anon_regions(default_span, 1) {
Err(v) => {
debug!("optional region in illegal location");
span_err!(this.tcx().sess, default_span, E0106,
"missing lifetime specifier");
match v {
Some(v) => {
let mut m = String::new();
let len = v.len();
for (i, (name, n)) in v.into_iter().enumerate() {
let help_name = if name.is_empty() {
format!("argument {}", i + 1)
} else {
format!("`{}`", name)
};
m.push_str(&(if n == 1 {
help_name
} else {
format!("one of {}'s {} elided lifetimes", help_name, n)
})[..]);
if len == 2 && i == 0 {
m.push_str(" or ");
} else if i + 2 == len {
m.push_str(", or ");
} else if i + 1 != len {
m.push_str(", ");
}
}
if len == 1 {
fileline_help!(this.tcx().sess, default_span,
"this function's return type contains a borrowed value, but \
the signature does not say which {} it is borrowed from",
m);
} else if len == 0 {
fileline_help!(this.tcx().sess, default_span,
"this function's return type contains a borrowed value, but \
there is no value for it to be borrowed from");
fileline_help!(this.tcx().sess, default_span,
"consider giving it a 'static lifetime");
} else {
fileline_help!(this.tcx().sess, default_span,
"this function's return type contains a borrowed value, but \
the signature does not say whether it is borrowed from {}",
m);
}
}
None => {},
}
ty::ReStatic
}
Ok(rs) => rs[0],
}
}
};
debug!("opt_ast_region_to_region(opt_lifetime={}) yields {}",
opt_lifetime.repr(this.tcx()),
r.repr(this.tcx()));
r
}
/// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
/// returns an appropriate set of substitutions for this particular reference to `I`.
pub fn ast_path_substs_for_ty<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
param_mode: PathParamMode,
decl_generics: &ty::Generics<'tcx>,
item_segment: &ast::PathSegment)
-> Substs<'tcx>
{
let tcx = this.tcx();
// ast_path_substs() is only called to convert paths that are
// known to refer to traits, types, or structs. In these cases,
// all type parameters defined for the item being referenced will
// be in the TypeSpace or SelfSpace.
//
// Note: in the case of traits, the self parameter is also
// defined, but we don't currently create a `type_param_def` for
// `Self` because it is implicit.
assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
assert!(decl_generics.types.all(|d| d.space != FnSpace));
let (regions, types, assoc_bindings) = match item_segment.parameters {
ast::AngleBracketedParameters(ref data) => {
convert_angle_bracketed_parameters(this, rscope, span, decl_generics, data)
}
ast::ParenthesizedParameters(ref data) => {
span_err!(tcx.sess, span, E0214,
"parenthesized parameters may only be used with a trait");
convert_parenthesized_parameters(this, rscope, span, decl_generics, data)
}
};
prohibit_projections(this.tcx(), &assoc_bindings);
create_substs_for_ast_path(this,
span,
param_mode,
decl_generics,
None,
types,
regions)
}
#[derive(PartialEq, Eq)]
pub enum PathParamMode {
// Any path in a type context.
Explicit,
// The `module::Type` in `module::Type::method` in an expression.
Optional
}
fn create_region_substs<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
decl_generics: &ty::Generics<'tcx>,
regions_provided: Vec<ty::Region>)
-> Substs<'tcx>
{
let tcx = this.tcx();
// If the type is parameterized by the this region, then replace this
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
let expected_num_region_params = decl_generics.regions.len(TypeSpace);
let supplied_num_region_params = regions_provided.len();
let regions = if expected_num_region_params == supplied_num_region_params {
regions_provided
} else {
let anon_regions =
rscope.anon_regions(span, expected_num_region_params);
if supplied_num_region_params != 0 || anon_regions.is_err() {
report_lifetime_number_error(tcx, span,
supplied_num_region_params,
expected_num_region_params);
}
match anon_regions {
Ok(anon_regions) => anon_regions,
Err(_) => (0..expected_num_region_params).map(|_| ty::ReStatic).collect()
}
};
Substs::new_type(vec![], regions)
}
/// Given the type/region arguments provided to some path (along with
/// an implicit Self, if this is a trait reference) returns the complete
/// set of substitutions. This may involve applying defaulted type parameters.
///
/// Note that the type listing given here is *exactly* what the user provided.
///
/// The `region_substs` should be the result of `create_region_substs`
/// -- that is, a substitution with no types but the correct number of
/// regions.
fn create_substs_for_ast_path<'tcx>(
this: &AstConv<'tcx>,
span: Span,
param_mode: PathParamMode,
decl_generics: &ty::Generics<'tcx>,
self_ty: Option<Ty<'tcx>>,
types_provided: Vec<Ty<'tcx>>,
region_substs: Substs<'tcx>)
-> Substs<'tcx>
{
let tcx = this.tcx();
debug!("create_substs_for_ast_path(decl_generics={}, self_ty={}, \
types_provided={}, region_substs={}",
decl_generics.repr(tcx), self_ty.repr(tcx), types_provided.repr(tcx),
region_substs.repr(tcx));
assert_eq!(region_substs.regions().len(TypeSpace), decl_generics.regions.len(TypeSpace));
assert!(region_substs.types.is_empty());
// Convert the type parameters supplied by the user.
let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
let formal_ty_param_count = ty_param_defs.len();
let required_ty_param_count = ty_param_defs.iter()
.take_while(|x| x.default.is_none())
.count();
// Fill with `ty_infer` if no params were specified, as long as
// they were optional (e.g. paths inside expressions).
let mut type_substs = if param_mode == PathParamMode::Optional &&
types_provided.is_empty() {
(0..formal_ty_param_count).map(|_| this.ty_infer(span)).collect()
} else {
types_provided
};
let supplied_ty_param_count = type_substs.len();
check_type_argument_count(this.tcx(), span, supplied_ty_param_count,
required_ty_param_count, formal_ty_param_count);
if supplied_ty_param_count < required_ty_param_count {
while type_substs.len() < required_ty_param_count {
type_substs.push(tcx.types.err);
}
} else if supplied_ty_param_count > formal_ty_param_count {
type_substs.truncate(formal_ty_param_count);
}
assert!(type_substs.len() >= required_ty_param_count &&
type_substs.len() <= formal_ty_param_count);
let mut substs = region_substs;
substs.types.extend(TypeSpace, type_substs.into_iter());
match self_ty {
None => {
// If no self-type is provided, it's still possible that
// one was declared, because this could be an object type.
}
Some(ty) => {
// If a self-type is provided, one should have been
// "declared" (in other words, this should be a
// trait-ref).
assert!(decl_generics.types.get_self().is_some());
substs.types.push(SelfSpace, ty);
}
}
let actual_supplied_ty_param_count = substs.types.len(TypeSpace);
for param in &ty_param_defs[actual_supplied_ty_param_count..] {
if let Some(default) = param.default {
// If we are converting an object type, then the
// `Self` parameter is unknown. However, some of the
// other type parameters may reference `Self` in their
// defaults. This will lead to an ICE if we are not
// careful!
if self_ty.is_none() && ty::type_has_self(default) {
tcx.sess.span_err(
span,
&format!("the type parameter `{}` must be explicitly specified \
in an object type because its default value `{}` references \
the type `Self`",
param.name.user_string(tcx),
default.user_string(tcx)));
substs.types.push(TypeSpace, tcx.types.err);
} else {
// This is a default type parameter.
let default = default.subst_spanned(tcx,
&substs,
Some(span));
substs.types.push(TypeSpace, default);
}
} else {
tcx.sess.span_bug(span, "extra parameter without default");
}
}
substs
}
struct ConvertedBinding<'tcx> {
item_name: ast::Name,
ty: Ty<'tcx>,
span: Span,
}
fn convert_angle_bracketed_parameters<'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
decl_generics: &ty::Generics<'tcx>,
data: &ast::AngleBracketedParameterData)
-> (Substs<'tcx>,
Vec<Ty<'tcx>>,
Vec<ConvertedBinding<'tcx>>)
{
let regions: Vec<_> =
data.lifetimes.iter()
.map(|l| ast_region_to_region(this.tcx(), l))
.collect();
let region_substs =
create_region_substs(this, rscope, span, decl_generics, regions);
let types: Vec<_> =
data.types.iter()
.enumerate()
.map(|(i,t)| ast_ty_arg_to_ty(this, rscope, decl_generics,
i, ®ion_substs, t))
.collect();
let assoc_bindings: Vec<_> =
data.bindings.iter()
.map(|b| ConvertedBinding { item_name: b.ident.name,
ty: ast_ty_to_ty(this, rscope, &*b.ty),
span: b.span })
.collect();
(region_substs, types, assoc_bindings)
}
/// Returns the appropriate lifetime to use for any output lifetimes
/// (if one exists) and a vector of the (pattern, number of lifetimes)
/// corresponding to each input type/pattern.
fn find_implied_output_region(input_tys: &[Ty], input_pats: Vec<String>)
-> (Option<ty::Region>, Vec<(String, usize)>)
{
let mut lifetimes_for_params: Vec<(String, usize)> = Vec::new();
let mut possible_implied_output_region = None;
for (input_type, input_pat) in input_tys.iter().zip(input_pats.into_iter()) {
let mut accumulator = Vec::new();
ty::accumulate_lifetimes_in_type(&mut accumulator, *input_type);
if accumulator.len() == 1 {
// there's a chance that the unique lifetime of this
// iteration will be the appropriate lifetime for output
// parameters, so lets store it.
possible_implied_output_region = Some(accumulator[0])
}
lifetimes_for_params.push((input_pat, accumulator.len()));
}
let implied_output_region =
if lifetimes_for_params.iter().map(|&(_, n)| n).sum::<usize>() == 1 {
assert!(possible_implied_output_region.is_some());
possible_implied_output_region
} else {
None
};
(implied_output_region, lifetimes_for_params)
}
fn convert_ty_with_lifetime_elision<'tcx>(this: &AstConv<'tcx>,
implied_output_region: Option<ty::Region>,
param_lifetimes: Vec<(String, usize)>,
ty: &ast::Ty)
-> Ty<'tcx>
{
match implied_output_region {
Some(implied_output_region) => {
let rb = ElidableRscope::new(implied_output_region);
ast_ty_to_ty(this, &rb, ty)
}
None => {
// All regions must be explicitly specified in the output
// if the lifetime elision rules do not apply. This saves
// the user from potentially-confusing errors.
let rb = UnelidableRscope::new(param_lifetimes);
ast_ty_to_ty(this, &rb, ty)
}
}
}
fn convert_parenthesized_parameters<'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
decl_generics: &ty::Generics<'tcx>,
data: &ast::ParenthesizedParameterData)
-> (Substs<'tcx>,
Vec<Ty<'tcx>>,
Vec<ConvertedBinding<'tcx>>)
{
let region_substs =
create_region_substs(this, rscope, span, decl_generics, Vec::new());
let binding_rscope = BindingRscope::new();
let inputs =
data.inputs.iter()
.map(|a_t| ast_ty_arg_to_ty(this, &binding_rscope, decl_generics,
0, ®ion_substs, a_t))
.collect::<Vec<Ty<'tcx>>>();
let input_params: Vec<_> = repeat(String::new()).take(inputs.len()).collect();
let (implied_output_region,
params_lifetimes) = find_implied_output_region(&*inputs, input_params);
let input_ty = ty::mk_tup(this.tcx(), inputs);
let (output, output_span) = match data.output {
Some(ref output_ty) => {
(convert_ty_with_lifetime_elision(this,
implied_output_region,
params_lifetimes,
&**output_ty),
output_ty.span)
}
None => {
(ty::mk_nil(this.tcx()), data.span)
}
};
let output_binding = ConvertedBinding {
item_name: token::intern(FN_OUTPUT_NAME),
ty: output,
span: output_span
};
(region_substs, vec![input_ty], vec![output_binding])
}
pub fn instantiate_poly_trait_ref<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
ast_trait_ref: &ast::PolyTraitRef,
self_ty: Option<Ty<'tcx>>,
poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
-> ty::PolyTraitRef<'tcx>
{
let trait_ref = &ast_trait_ref.trait_ref;
let trait_def_id = trait_def_id(this, trait_ref);
ast_path_to_poly_trait_ref(this,
rscope,
trait_ref.path.span,
PathParamMode::Explicit,
trait_def_id,
self_ty,
trait_ref.path.segments.last().unwrap(),
poly_projections)
}
/// Instantiates the path for the given trait reference, assuming that it's
/// bound to a valid trait type. Returns the def_id for the defining trait.
/// Fails if the type is a type other than a trait type.
///
/// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
/// are disallowed. Otherwise, they are pushed onto the vector given.
pub fn instantiate_mono_trait_ref<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
trait_ref: &ast::TraitRef,
self_ty: Option<Ty<'tcx>>)
-> Rc<ty::TraitRef<'tcx>>
{
let trait_def_id = trait_def_id(this, trait_ref);
ast_path_to_mono_trait_ref(this,
rscope,
trait_ref.path.span,
PathParamMode::Explicit,
trait_def_id,
self_ty,
trait_ref.path.segments.last().unwrap())
}
fn trait_def_id<'tcx>(this: &AstConv<'tcx>, trait_ref: &ast::TraitRef) -> ast::DefId {
let path = &trait_ref.path;
match ::lookup_full_def(this.tcx(), path.span, trait_ref.ref_id) {
def::DefTrait(trait_def_id) => trait_def_id,
_ => {
span_fatal!(this.tcx().sess, path.span, E0245, "`{}` is not a trait",
path.user_string(this.tcx()));
}
}
}
fn object_path_to_poly_trait_ref<'a,'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
param_mode: PathParamMode,
trait_def_id: ast::DefId,
trait_segment: &ast::PathSegment,
mut projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
-> ty::PolyTraitRef<'tcx>
{
ast_path_to_poly_trait_ref(this,
rscope,
span,
param_mode,
trait_def_id,
None,
trait_segment,
projections)
}
fn ast_path_to_poly_trait_ref<'a,'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
param_mode: PathParamMode,
trait_def_id: ast::DefId,
self_ty: Option<Ty<'tcx>>,
trait_segment: &ast::PathSegment,
poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
-> ty::PolyTraitRef<'tcx>
{
// The trait reference introduces a binding level here, so
// we need to shift the `rscope`. It'd be nice if we could
// do away with this rscope stuff and work this knowledge
// into resolve_lifetimes, as we do with non-omitted
// lifetimes. Oh well, not there yet.
let shifted_rscope = &ShiftedRscope::new(rscope);
let (substs, assoc_bindings) =
create_substs_for_ast_trait_ref(this,
shifted_rscope,
span,
param_mode,
trait_def_id,
self_ty,
trait_segment);
let poly_trait_ref = ty::Binder(Rc::new(ty::TraitRef::new(trait_def_id, substs)));
{
let converted_bindings =
assoc_bindings
.iter()
.filter_map(|binding| {
// specify type to assert that error was already reported in Err case:
let predicate: Result<_, ErrorReported> =
ast_type_binding_to_poly_projection_predicate(this,
poly_trait_ref.clone(),
self_ty,
binding);
predicate.ok() // ok to ignore Err() because ErrorReported (see above)
});
poly_projections.extend(converted_bindings);
}
poly_trait_ref
}
fn ast_path_to_mono_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
param_mode: PathParamMode,
trait_def_id: ast::DefId,
self_ty: Option<Ty<'tcx>>,
trait_segment: &ast::PathSegment)
-> Rc<ty::TraitRef<'tcx>>
{
let (substs, assoc_bindings) =
create_substs_for_ast_trait_ref(this,
rscope,
span,
param_mode,
trait_def_id,
self_ty,
trait_segment);
prohibit_projections(this.tcx(), &assoc_bindings);
Rc::new(ty::TraitRef::new(trait_def_id, substs))
}
fn create_substs_for_ast_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
param_mode: PathParamMode,
trait_def_id: ast::DefId,
self_ty: Option<Ty<'tcx>>,
trait_segment: &ast::PathSegment)
-> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
{
debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
trait_segment);
let trait_def = match this.get_trait_def(span, trait_def_id) {
Ok(trait_def) => trait_def,
Err(ErrorReported) => {
// No convenient way to recover from a cycle here. Just bail. Sorry!
this.tcx().sess.abort_if_errors();
this.tcx().sess.bug("ErrorReported returned, but no errors reports?")
}
};
let (regions, types, assoc_bindings) = match trait_segment.parameters {
ast::AngleBracketedParameters(ref data) => {
// For now, require that parenthetical notation be used
// only with `Fn()` etc.
if !this.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
span_err!(this.tcx().sess, span, E0215,
"angle-bracket notation is not stable when \
used with the `Fn` family of traits, use parentheses");
fileline_help!(this.tcx().sess, span,
"add `#![feature(unboxed_closures)]` to \
the crate attributes to enable");
}
convert_angle_bracketed_parameters(this, rscope, span, &trait_def.generics, data)
}
ast::ParenthesizedParameters(ref data) => {
// For now, require that parenthetical notation be used
// only with `Fn()` etc.
if !this.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
span_err!(this.tcx().sess, span, E0216,
"parenthetical notation is only stable when \
used with the `Fn` family of traits");
fileline_help!(this.tcx().sess, span,
"add `#![feature(unboxed_closures)]` to \
the crate attributes to enable");
}
convert_parenthesized_parameters(this, rscope, span, &trait_def.generics, data)
}
};
let substs = create_substs_for_ast_path(this,
span,
param_mode,
&trait_def.generics,
self_ty,
types,
regions);
(this.tcx().mk_substs(substs), assoc_bindings)
}
fn ast_type_binding_to_poly_projection_predicate<'tcx>(
this: &AstConv<'tcx>,
mut trait_ref: ty::PolyTraitRef<'tcx>,
self_ty: Option<Ty<'tcx>>,
binding: &ConvertedBinding<'tcx>)
-> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
{
let tcx = this.tcx();
// Given something like `U : SomeTrait<T=X>`, we want to produce a
// predicate like `<U as SomeTrait>::T = X`. This is somewhat
// subtle in the event that `T` is defined in a supertrait of
// `SomeTrait`, because in that case we need to upcast.
//
// That is, consider this case:
//
// ```
// trait SubTrait : SuperTrait<int> { }
// trait SuperTrait<A> { type T; }
//
// ... B : SubTrait<T=foo> ...
// ```
//
// We want to produce `<B as SuperTrait<int>>::T == foo`.
// Simple case: X is defined in the current trait.
if this.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
return Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------+
projection_ty: ty::ProjectionTy { // |
trait_ref: trait_ref.skip_binder().clone(), // Binder moved here --+
item_name: binding.item_name,
},
ty: binding.ty,
}));
}
// Otherwise, we have to walk through the supertraits to find
// those that do. This is complicated by the fact that, for an
// object type, the `Self` type is not present in the
// substitutions (after all, it's being constructed right now),
// but the `supertraits` iterator really wants one. To handle
// this, we currently insert a dummy type and then remove it
// later. Yuck.
let dummy_self_ty = ty::mk_infer(tcx, ty::FreshTy(0));
if self_ty.is_none() { // if converting for an object type
let mut dummy_substs = trait_ref.skip_binder().substs.clone(); // binder moved here -+
assert!(dummy_substs.self_ty().is_none()); // |
dummy_substs.types.push(SelfSpace, dummy_self_ty); // |
trait_ref = ty::Binder(Rc::new(ty::TraitRef::new(trait_ref.def_id(), // <------------+
tcx.mk_substs(dummy_substs))));
}
try!(this.ensure_super_predicates(binding.span, trait_ref.def_id()));
let mut candidates: Vec<ty::PolyTraitRef> =
traits::supertraits(tcx, trait_ref.clone())
.filter(|r| this.trait_defines_associated_type_named(r.def_id(), binding.item_name))
.collect();
// If converting for an object type, then remove the dummy-ty from `Self` now.
// Yuckety yuck.
if self_ty.is_none() {
for candidate in &mut candidates {
let mut dummy_substs = candidate.0.substs.clone();
assert!(dummy_substs.self_ty() == Some(dummy_self_ty));
dummy_substs.types.pop(SelfSpace);
*candidate = ty::Binder(Rc::new(ty::TraitRef::new(candidate.def_id(),
tcx.mk_substs(dummy_substs))));
}
}
let candidate = try!(one_bound_for_assoc_type(tcx,
candidates,
&trait_ref.user_string(tcx),
&token::get_name(binding.item_name),
binding.span));
Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------------+
projection_ty: ty::ProjectionTy { // |
trait_ref: candidate.skip_binder().clone(), // binder is moved up here --+
item_name: binding.item_name,
},
ty: binding.ty,
}))
}
fn ast_path_to_ty<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
param_mode: PathParamMode,
did: ast::DefId,
item_segment: &ast::PathSegment)
-> Ty<'tcx>
{
let tcx = this.tcx();
let (generics, decl_ty) = match this.get_item_type_scheme(span, did) {
Ok(ty::TypeScheme { generics, ty: decl_ty }) => {
(generics, decl_ty)
}
Err(ErrorReported) => {
return tcx.types.err;
}
};
let substs = ast_path_substs_for_ty(this,
rscope,
span,
param_mode,
&generics,
item_segment);
// FIXME(#12938): This is a hack until we have full support for DST.
if Some(did) == this.tcx().lang_items.owned_box() {
assert_eq!(substs.types.len(TypeSpace), 1);
return ty::mk_uniq(this.tcx(), *substs.types.get(TypeSpace, 0));
}
decl_ty.subst(this.tcx(), &substs)
}
type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
ty: &ast::Ty,
bounds: &[ast::TyParamBound])
-> Result<TraitAndProjections<'tcx>, ErrorReported>
{
/*!
* In a type like `Foo + Send`, we want to wait to collect the
* full set of bounds before we make the object type, because we
* need them to infer a region bound. (For example, if we tried
* made a type from just `Foo`, then it wouldn't be enough to
* infer a 'static bound, and hence the user would get an error.)
* So this function is used when we're dealing with a sum type to
* convert the LHS. It only accepts a type that refers to a trait
* name, and reports an error otherwise.
*/
match ty.node {
ast::TyPath(None, ref path) => {
let def = match this.tcx().def_map.borrow().get(&ty.id) {
Some(&def::PathResolution { base_def, depth: 0, .. }) => Some(base_def),
_ => None
};
match def {
Some(def::DefTrait(trait_def_id)) => {
let mut projection_bounds = Vec::new();
let trait_ref = object_path_to_poly_trait_ref(this,
rscope,
path.span,
PathParamMode::Explicit,
trait_def_id,
path.segments.last().unwrap(),
&mut projection_bounds);
Ok((trait_ref, projection_bounds))
}
_ => {
span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
Err(ErrorReported)
}
}
}
_ => {
span_err!(this.tcx().sess, ty.span, E0178,
"expected a path on the left-hand side of `+`, not `{}`",
pprust::ty_to_string(ty));
match ty.node {
ast::TyRptr(None, ref mut_ty) => {
fileline_help!(this.tcx().sess, ty.span,
"perhaps you meant `&{}({} +{})`? (per RFC 438)",
ppaux::mutability_to_string(mut_ty.mutbl),
pprust::ty_to_string(&*mut_ty.ty),
pprust::bounds_to_string(bounds));
}
ast::TyRptr(Some(ref lt), ref mut_ty) => {
fileline_help!(this.tcx().sess, ty.span,
"perhaps you meant `&{} {}({} +{})`? (per RFC 438)",
pprust::lifetime_to_string(lt),
ppaux::mutability_to_string(mut_ty.mutbl),
pprust::ty_to_string(&*mut_ty.ty),
pprust::bounds_to_string(bounds));
}
_ => {
fileline_help!(this.tcx().sess, ty.span,
"perhaps you forgot parentheses? (per RFC 438)");
}
}
Err(ErrorReported)
}
}
}
fn trait_ref_to_object_type<'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
trait_ref: ty::PolyTraitRef<'tcx>,
projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
bounds: &[ast::TyParamBound])
-> Ty<'tcx>
{
let existential_bounds = conv_existential_bounds(this,
rscope,
span,
trait_ref.clone(),
projection_bounds,
bounds);
let result = make_object_type(this, span, trait_ref, existential_bounds);
debug!("trait_ref_to_object_type: result={}",
result.repr(this.tcx()));
result
}
fn make_object_type<'tcx>(this: &AstConv<'tcx>,
span: Span,
principal: ty::PolyTraitRef<'tcx>,
bounds: ty::ExistentialBounds<'tcx>)
-> Ty<'tcx> {
let tcx = this.tcx();
let object = ty::TyTrait {
principal: principal,
bounds: bounds
};
let object_trait_ref =
object.principal_trait_ref_with_self_ty(tcx, tcx.types.err);
// ensure the super predicates and stop if we encountered an error
if this.ensure_super_predicates(span, object.principal_def_id()).is_err() {
return tcx.types.err;
}
let mut associated_types: FnvHashSet<(ast::DefId, ast::Name)> =
traits::supertraits(tcx, object_trait_ref)
.flat_map(|tr| {
let trait_def = ty::lookup_trait_def(tcx, tr.def_id());
trait_def.associated_type_names
.clone()
.into_iter()
.map(move |associated_type_name| (tr.def_id(), associated_type_name))
})
.collect();
for projection_bound in &object.bounds.projection_bounds {
let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
projection_bound.0.projection_ty.item_name);
associated_types.remove(&pair);
}
for (trait_def_id, name) in associated_types {
span_err!(tcx.sess, span, E0191,
"the value of the associated type `{}` (from the trait `{}`) must be specified",
name.user_string(tcx),
ty::item_path_str(tcx, trait_def_id));
}
ty::mk_trait(tcx, object.principal, object.bounds)
}
fn report_ambiguous_associated_type(tcx: &ty::ctxt,
span: Span,
type_str: &str,
trait_str: &str,
name: &str) {
span_err!(tcx.sess, span, E0223,
"ambiguous associated type; specify the type using the syntax \
`<{} as {}>::{}`",
type_str, trait_str, name);
}
// Search for a bound on a type parameter which includes the associated item
// given by assoc_name. ty_param_node_id is the node id for the type parameter
// (which might be `Self`, but only if it is the `Self` of a trait, not an
// impl). This function will fail if there are no suitable bounds or there is
// any ambiguity.
fn find_bound_for_assoc_item<'tcx>(this: &AstConv<'tcx>,
ty_param_node_id: ast::NodeId,
assoc_name: ast::Name,
span: Span)
-> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
{
let tcx = this.tcx();
let bounds = match this.get_type_parameter_bounds(span, ty_param_node_id) {
Ok(v) => v,
Err(ErrorReported) => {
return Err(ErrorReported);
}
};
// Ensure the super predicates and stop if we encountered an error.
if bounds.iter().any(|b| this.ensure_super_predicates(span, b.def_id()).is_err()) {
return Err(ErrorReported);
}
// Check that there is exactly one way to find an associated type with the
// correct name.
let suitable_bounds: Vec<_> =
traits::transitive_bounds(tcx, &bounds)
.filter(|b| this.trait_defines_associated_type_named(b.def_id(), assoc_name))
.collect();
let ty_param_name = tcx.type_parameter_def(ty_param_node_id).name;
one_bound_for_assoc_type(tcx,
suitable_bounds,
&token::get_name(ty_param_name),
&token::get_name(assoc_name),
span)
}
// Checks that bounds contains exactly one element and reports appropriate
// errors otherwise.
fn one_bound_for_assoc_type<'tcx>(tcx: &ty::ctxt<'tcx>,
bounds: Vec<ty::PolyTraitRef<'tcx>>,
ty_param_name: &str,
assoc_name: &str,
span: Span)
-> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
{
if bounds.len() == 0 {
span_err!(tcx.sess, span, E0220,
"associated type `{}` not found for `{}`",
assoc_name,
ty_param_name);
return Err(ErrorReported);
}
if bounds.len() > 1 {
span_err!(tcx.sess, span, E0221,
"ambiguous associated type `{}` in bounds of `{}`",
assoc_name,
ty_param_name);
for bound in &bounds {
span_note!(tcx.sess, span,
"associated type `{}` could derive from `{}`",
ty_param_name,
bound.user_string(tcx));
}
}
Ok(bounds[0].clone())
}
// Create a type from a a path to an associated type.
// For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
// and item_segment is the path segment for D. We return a type and a def for
// the whole path.
// Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
// parameter or Self.
fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>,
span: Span,
ty: Ty<'tcx>,
ty_path_def: def::Def,
item_segment: &ast::PathSegment)
-> (Ty<'tcx>, def::Def)
{
let tcx = this.tcx();
let assoc_name = item_segment.identifier.name;
debug!("associated_path_def_to_ty: {}::{}", ty.repr(tcx), token::get_name(assoc_name));
check_path_args(tcx, slice::ref_slice(item_segment), NO_TPS | NO_REGIONS);
// Find the type of the associated item, and the trait where the associated
// item is declared.
let bound = match (&ty.sty, ty_path_def) {
(_, def::DefSelfTy(Some(trait_did), Some((impl_id, _)))) => {
// `Self` in an impl of a trait - we have a concrete self type and a
// trait reference.
match tcx.map.expect_item(impl_id).node {
ast::ItemImpl(_, _, _, Some(ref trait_ref), _, _) => {
if this.ensure_super_predicates(span, trait_did).is_err() {
return (tcx.types.err, ty_path_def);
}
let trait_segment = &trait_ref.path.segments.last().unwrap();
let trait_ref = ast_path_to_mono_trait_ref(this,
&ExplicitRscope,
span,
PathParamMode::Explicit,
trait_did,
Some(ty),
trait_segment);
let candidates: Vec<ty::PolyTraitRef> =
traits::supertraits(tcx, ty::Binder(trait_ref.clone()))
.filter(|r| this.trait_defines_associated_type_named(r.def_id(),
assoc_name))
.collect();
match one_bound_for_assoc_type(tcx,
candidates,
"Self",
&token::get_name(assoc_name),
span) {
Ok(bound) => bound,
Err(ErrorReported) => return (tcx.types.err, ty_path_def),
}
}
_ => unreachable!()
}
}
(&ty::ty_param(_), def::DefTyParam(..)) |
(&ty::ty_param(_), def::DefSelfTy(Some(_), None)) => {
// A type parameter or Self, we need to find the associated item from
// a bound.
let ty_param_node_id = ty_path_def.local_node_id();
match find_bound_for_assoc_item(this, ty_param_node_id, assoc_name, span) {
Ok(bound) => bound,
Err(ErrorReported) => return (tcx.types.err, ty_path_def),
}
}
_ => {
report_ambiguous_associated_type(tcx,
span,
&ty.user_string(tcx),
"Trait",
&token::get_name(assoc_name));
return (tcx.types.err, ty_path_def);
}
};
let trait_did = bound.0.def_id;
let ty = this.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
let item_did = if trait_did.krate == ast::LOCAL_CRATE {
// `ty::trait_items` used below requires information generated
// by type collection, which may be in progress at this point.
match tcx.map.expect_item(trait_did.node).node {
ast::ItemTrait(_, _, _, ref trait_items) => {
let item = trait_items.iter()
.find(|i| i.ident.name == assoc_name)
.expect("missing associated type");
ast_util::local_def(item.id)
}
_ => unreachable!()
}
} else {
let trait_items = ty::trait_items(tcx, trait_did);
let item = trait_items.iter().find(|i| i.name() == assoc_name);
item.expect("missing associated type").def_id()
};
(ty, def::DefAssociatedTy(trait_did, item_did))
}
fn qpath_to_ty<'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
param_mode: PathParamMode,
opt_self_ty: Option<Ty<'tcx>>,
trait_def_id: ast::DefId,
trait_segment: &ast::PathSegment,
item_segment: &ast::PathSegment)
-> Ty<'tcx>
{
let tcx = this.tcx();
check_path_args(tcx, slice::ref_slice(item_segment), NO_TPS | NO_REGIONS);
let self_ty = if let Some(ty) = opt_self_ty {
ty
} else {
let path_str = ty::item_path_str(tcx, trait_def_id);
report_ambiguous_associated_type(tcx,
span,
"Type",
&path_str,
&token::get_ident(item_segment.identifier));
return tcx.types.err;
};
debug!("qpath_to_ty: self_type={}", self_ty.repr(tcx));
let trait_ref = ast_path_to_mono_trait_ref(this,
rscope,
span,
param_mode,
trait_def_id,
Some(self_ty),
trait_segment);
debug!("qpath_to_ty: trait_ref={}", trait_ref.repr(tcx));
this.projected_ty(span, trait_ref, item_segment.identifier.name)
}
/// Convert a type supplied as value for a type argument from AST into our
/// our internal representation. This is the same as `ast_ty_to_ty` but that
/// it applies the object lifetime default.
///
/// # Parameters
///
/// * `this`, `rscope`: the surrounding context
/// * `decl_generics`: the generics of the struct/enum/trait declaration being
/// referenced
/// * `index`: the index of the type parameter being instantiated from the list
/// (we assume it is in the `TypeSpace`)
/// * `region_substs`: a partial substitution consisting of
/// only the region type parameters being supplied to this type.
/// * `ast_ty`: the ast representation of the type being supplied
pub fn ast_ty_arg_to_ty<'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
decl_generics: &ty::Generics<'tcx>,
index: usize,
region_substs: &Substs<'tcx>,
ast_ty: &ast::Ty)
-> Ty<'tcx>
{
let tcx = this.tcx();
if let Some(def) = decl_generics.types.opt_get(TypeSpace, index) {
let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
ast_ty_to_ty(this, rscope1, ast_ty)
} else {
ast_ty_to_ty(this, rscope, ast_ty)
}
}
// Check the base def in a PathResolution and convert it to a Ty. If there are
// associated types in the PathResolution, these will need to be seperately
// resolved.
fn base_def_to_ty<'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
param_mode: PathParamMode,
def: &def::Def,
opt_self_ty: Option<Ty<'tcx>>,
base_segments: &[ast::PathSegment])
-> Ty<'tcx> {
let tcx = this.tcx();
match *def {
def::DefTrait(trait_def_id) => {
// N.B. this case overlaps somewhat with
// TyObjectSum, see that fn for details
let mut projection_bounds = Vec::new();
let trait_ref = object_path_to_poly_trait_ref(this,
rscope,
span,
param_mode,
trait_def_id,
base_segments.last().unwrap(),
&mut projection_bounds);
check_path_args(tcx, base_segments.init(), NO_TPS | NO_REGIONS);
trait_ref_to_object_type(this,
rscope,
span,
trait_ref,
projection_bounds,
&[])
}
def::DefTy(did, _) | def::DefStruct(did) => {
check_path_args(tcx, base_segments.init(), NO_TPS | NO_REGIONS);
ast_path_to_ty(this,
rscope,
span,
param_mode,
did,
base_segments.last().unwrap())
}
def::DefTyParam(space, index, _, name) => {
check_path_args(tcx, base_segments, NO_TPS | NO_REGIONS);
ty::mk_param(tcx, space, index, name)
}
def::DefSelfTy(_, Some((_, self_ty_id))) => {
// Self in impl (we know the concrete type).
check_path_args(tcx, base_segments, NO_TPS | NO_REGIONS);
if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&self_ty_id) {
ty
} else {
tcx.sess.span_bug(span, "self type has not been fully resolved")
}
}
def::DefSelfTy(Some(_), None) => {
// Self in trait.
check_path_args(tcx, base_segments, NO_TPS | NO_REGIONS);
ty::mk_self_type(tcx)
}
def::DefAssociatedTy(trait_did, _) => {
check_path_args(tcx, &base_segments[..base_segments.len()-2], NO_TPS | NO_REGIONS);
qpath_to_ty(this,
rscope,
span,
param_mode,
opt_self_ty,
trait_did,
&base_segments[base_segments.len()-2],
base_segments.last().unwrap())
}
def::DefMod(id) => {
// Used as sentinel by callers to indicate the `<T>::A::B::C` form.
// FIXME(#22519) This part of the resolution logic should be
// avoided entirely for that form, once we stop needed a Def
// for `associated_path_def_to_ty`.
// Fixing this will also let use resolve <Self>::Foo the same way we
// resolve Self::Foo, at the moment we can't resolve the former because
// we don't have the trait information around, which is just sad.
if !base_segments.is_empty() {
span_err!(tcx.sess,
span,
E0247,
"found module name used as a type: {}",
tcx.map.node_to_string(id.node));
return this.tcx().types.err;
}
opt_self_ty.expect("missing T in <T>::a::b::c")
}
def::DefPrimTy(prim_ty) => {
prim_ty_to_ty(tcx, base_segments, prim_ty)
}
_ => {
span_err!(tcx.sess, span, E0248,
"found value name used as a type: {:?}", *def);
return this.tcx().types.err;
}
}
}
// Note that both base_segments and assoc_segments may be empty, although not at
// the same time.
pub fn finish_resolving_def_to_ty<'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
param_mode: PathParamMode,
def: &def::Def,
opt_self_ty: Option<Ty<'tcx>>,
base_segments: &[ast::PathSegment],
assoc_segments: &[ast::PathSegment])
-> Ty<'tcx> {
let mut ty = base_def_to_ty(this,
rscope,
span,
param_mode,
def,
opt_self_ty,
base_segments);
let mut def = *def;
// If any associated type segments remain, attempt to resolve them.
for segment in assoc_segments {
if ty.sty == ty::ty_err {
break;
}
// This is pretty bad (it will fail except for T::A and Self::A).
let (a_ty, a_def) = associated_path_def_to_ty(this,
span,
ty,
def,
segment);
ty = a_ty;
def = a_def;
}
ty
}
/// Parses the programmer's textual representation of a type into our
/// internal notion of a type.
pub fn ast_ty_to_ty<'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
ast_ty: &ast::Ty)
-> Ty<'tcx>
{
debug!("ast_ty_to_ty(ast_ty={})",
ast_ty.repr(this.tcx()));
let tcx = this.tcx();
if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&ast_ty.id) {
return ty;
}
let typ = match ast_ty.node {
ast::TyVec(ref ty) => {
ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty), None)
}
ast::TyObjectSum(ref ty, ref bounds) => {
match ast_ty_to_trait_ref(this, rscope, &**ty, bounds) {
Ok((trait_ref, projection_bounds)) => {
trait_ref_to_object_type(this,
rscope,
ast_ty.span,
trait_ref,
projection_bounds,
bounds)
}
Err(ErrorReported) => {
this.tcx().types.err
}
}
}
ast::TyPtr(ref mt) => {
ty::mk_ptr(tcx, ty::mt {
ty: ast_ty_to_ty(this, rscope, &*mt.ty),
mutbl: mt.mutbl
})
}
ast::TyRptr(ref region, ref mt) => {
let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
debug!("ty_rptr r={}", r.repr(this.tcx()));
let rscope1 =
&ObjectLifetimeDefaultRscope::new(
rscope,
Some(ty::ObjectLifetimeDefault::Specific(r)));
let t = ast_ty_to_ty(this, rscope1, &*mt.ty);
ty::mk_rptr(tcx, tcx.mk_region(r), ty::mt {ty: t, mutbl: mt.mutbl})
}
ast::TyTup(ref fields) => {
let flds = fields.iter()
.map(|t| ast_ty_to_ty(this, rscope, &**t))
.collect();
ty::mk_tup(tcx, flds)
}
ast::TyParen(ref typ) => ast_ty_to_ty(this, rscope, &**typ),
ast::TyBareFn(ref bf) => {
if bf.decl.variadic && bf.abi != abi::C {
span_err!(tcx.sess, ast_ty.span, E0222,
"variadic function must have C calling convention");
}
let bare_fn = ty_of_bare_fn(this, bf.unsafety, bf.abi, &*bf.decl);
ty::mk_bare_fn(tcx, None, tcx.mk_bare_fn(bare_fn))
}
ast::TyPolyTraitRef(ref bounds) => {
conv_ty_poly_trait_ref(this, rscope, ast_ty.span, bounds)
}
ast::TyPath(ref maybe_qself, ref path) => {
let path_res = if let Some(&d) = tcx.def_map.borrow().get(&ast_ty.id) {
d
} else if let Some(ast::QSelf { position: 0, .. }) = *maybe_qself {
// Create some fake resolution that can't possibly be a type.
def::PathResolution {
base_def: def::DefMod(ast_util::local_def(ast::CRATE_NODE_ID)),
last_private: LastMod(AllPublic),
depth: path.segments.len()
}
} else {
tcx.sess.span_bug(ast_ty.span,
&format!("unbound path {}", ast_ty.repr(tcx)))
};
let def = path_res.base_def;
let base_ty_end = path.segments.len() - path_res.depth;
let opt_self_ty = maybe_qself.as_ref().map(|qself| {
ast_ty_to_ty(this, rscope, &qself.ty)
});
let ty = finish_resolving_def_to_ty(this,
rscope,
ast_ty.span,
PathParamMode::Explicit,
&def,
opt_self_ty,
&path.segments[..base_ty_end],
&path.segments[base_ty_end..]);
if path_res.depth != 0 && ty.sty != ty::ty_err {
// Write back the new resolution.
tcx.def_map.borrow_mut().insert(ast_ty.id, def::PathResolution {
base_def: def,
last_private: path_res.last_private,
depth: 0
});
}
ty
}
ast::TyFixedLengthVec(ref ty, ref e) => {
match const_eval::eval_const_expr_partial(tcx, &**e, Some(tcx.types.usize)) {
Ok(r) => {
match r {
const_eval::const_int(i) =>
ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty),
Some(i as usize)),
const_eval::const_uint(i) =>
ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty),
Some(i as usize)),
_ => {
span_err!(tcx.sess, ast_ty.span, E0249,
"expected constant expr for array length");
this.tcx().types.err
}
}
}
Err(ref r) => {
let subspan =
ast_ty.span.lo <= r.span.lo && r.span.hi <= ast_ty.span.hi;
span_err!(tcx.sess, r.span, E0250,
"array length constant evaluation error: {}",
r.description());
if !subspan {
span_note!(tcx.sess, ast_ty.span, "for array length here")
}
this.tcx().types.err
}
}
}
ast::TyTypeof(ref _e) => {
tcx.sess.span_bug(ast_ty.span, "typeof is reserved but unimplemented");
}
ast::TyInfer => {
// TyInfer also appears as the type of arguments or return
// values in a ExprClosure, or as
// the type of local variables. Both of these cases are
// handled specially and will not descend into this routine.
this.ty_infer(ast_ty.span)
}
};
tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, typ);
return typ;
}
pub fn ty_of_arg<'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
a: &ast::Arg,
expected_ty: Option<Ty<'tcx>>)
-> Ty<'tcx>
{
match a.ty.node {
ast::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
ast::TyInfer => this.ty_infer(a.ty.span),
_ => ast_ty_to_ty(this, rscope, &*a.ty),
}
}
struct SelfInfo<'a, 'tcx> {
untransformed_self_ty: Ty<'tcx>,
explicit_self: &'a ast::ExplicitSelf,
}
pub fn ty_of_method<'tcx>(this: &AstConv<'tcx>,
sig: &ast::MethodSig,
untransformed_self_ty: Ty<'tcx>)
-> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
let self_info = Some(SelfInfo {
untransformed_self_ty: untransformed_self_ty,
explicit_self: &sig.explicit_self,
});
let (bare_fn_ty, optional_explicit_self_category) =
ty_of_method_or_bare_fn(this,
sig.unsafety,
sig.abi,
self_info,
&sig.decl);
(bare_fn_ty, optional_explicit_self_category.unwrap())
}
pub fn ty_of_bare_fn<'tcx>(this: &AstConv<'tcx>, unsafety: ast::Unsafety, abi: abi::Abi,
decl: &ast::FnDecl) -> ty::BareFnTy<'tcx> {
let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, unsafety, abi, None, decl);
bare_fn_ty
}
fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>,
unsafety: ast::Unsafety,
abi: abi::Abi,
opt_self_info: Option<SelfInfo<'a, 'tcx>>,
decl: &ast::FnDecl)
-> (ty::BareFnTy<'tcx>, Option<ty::ExplicitSelfCategory>)
{
debug!("ty_of_method_or_bare_fn");
// New region names that appear inside of the arguments of the function
// declaration are bound to that function type.
let rb = rscope::BindingRscope::new();
// `implied_output_region` is the region that will be assumed for any
// region parameters in the return type. In accordance with the rules for
// lifetime elision, we can determine it in two ways. First (determined
// here), if self is by-reference, then the implied output region is the
// region of the self parameter.
let mut explicit_self_category_result = None;
let (self_ty, mut implied_output_region) = match opt_self_info {
None => (None, None),
Some(self_info) => {
// This type comes from an impl or trait; no late-bound
// regions should be present.
assert!(!self_info.untransformed_self_ty.has_escaping_regions());
// Figure out and record the explicit self category.
let explicit_self_category =
determine_explicit_self_category(this, &rb, &self_info);
explicit_self_category_result = Some(explicit_self_category);
match explicit_self_category {
ty::StaticExplicitSelfCategory => {
(None, None)
}
ty::ByValueExplicitSelfCategory => {
(Some(self_info.untransformed_self_ty), None)
}
ty::ByReferenceExplicitSelfCategory(region, mutability) => {
(Some(ty::mk_rptr(this.tcx(),
this.tcx().mk_region(region),
ty::mt {
ty: self_info.untransformed_self_ty,
mutbl: mutability
})),
Some(region))
}
ty::ByBoxExplicitSelfCategory => {
(Some(ty::mk_uniq(this.tcx(), self_info.untransformed_self_ty)), None)
}
}
}
};
// HACK(eddyb) replace the fake self type in the AST with the actual type.
let input_params = if self_ty.is_some() {
&decl.inputs[1..]
} else {
&decl.inputs[..]
};
let input_tys = input_params.iter().map(|a| ty_of_arg(this, &rb, a, None));
let input_pats: Vec<String> = input_params.iter()
.map(|a| pprust::pat_to_string(&*a.pat))
.collect();
let self_and_input_tys: Vec<Ty> =
self_ty.into_iter().chain(input_tys).collect();
// Second, if there was exactly one lifetime (either a substitution or a
// reference) in the arguments, then any anonymous regions in the output
// have that lifetime.
let lifetimes_for_params = if implied_output_region.is_none() {
let input_tys = if self_ty.is_some() {
// Skip the first argument if `self` is present.
&self_and_input_tys[1..]
} else {
&self_and_input_tys[..]
};
let (ior, lfp) = find_implied_output_region(input_tys, input_pats);
implied_output_region = ior;
lfp
} else {
vec![]
};
let output_ty = match decl.output {
ast::Return(ref output) if output.node == ast::TyInfer =>
ty::FnConverging(this.ty_infer(output.span)),
ast::Return(ref output) =>
ty::FnConverging(convert_ty_with_lifetime_elision(this,
implied_output_region,
lifetimes_for_params,
&**output)),
ast::DefaultReturn(..) => ty::FnConverging(ty::mk_nil(this.tcx())),
ast::NoReturn(..) => ty::FnDiverging
};
(ty::BareFnTy {
unsafety: unsafety,
abi: abi,
sig: ty::Binder(ty::FnSig {
inputs: self_and_input_tys,
output: output_ty,
variadic: decl.variadic
}),
}, explicit_self_category_result)
}
fn determine_explicit_self_category<'a, 'tcx>(this: &AstConv<'tcx>,
rscope: &RegionScope,
self_info: &SelfInfo<'a, 'tcx>)
-> ty::ExplicitSelfCategory
{
return match self_info.explicit_self.node {
ast::SelfStatic => ty::StaticExplicitSelfCategory,
ast::SelfValue(_) => ty::ByValueExplicitSelfCategory,
ast::SelfRegion(ref lifetime, mutability, _) => {
let region =
opt_ast_region_to_region(this,
rscope,
self_info.explicit_self.span,
lifetime);
ty::ByReferenceExplicitSelfCategory(region, mutability)
}
ast::SelfExplicit(ref ast_type, _) => {
let explicit_type = ast_ty_to_ty(this, rscope, &**ast_type);
// We wish to (for now) categorize an explicit self
// declaration like `self: SomeType` into either `self`,
// `&self`, `&mut self`, or `Box<self>`. We do this here
// by some simple pattern matching. A more precise check
// is done later in `check_method_self_type()`.
//
// Examples:
//
// ```
// impl Foo for &T {
// // Legal declarations:
// fn method1(self: &&T); // ByReferenceExplicitSelfCategory
// fn method2(self: &T); // ByValueExplicitSelfCategory
// fn method3(self: Box<&T>); // ByBoxExplicitSelfCategory
//
// // Invalid cases will be caught later by `check_method_self_type`:
// fn method_err1(self: &mut T); // ByReferenceExplicitSelfCategory
// }
// ```
//
// To do the check we just count the number of "modifiers"
// on each type and compare them. If they are the same or
// the impl has more, we call it "by value". Otherwise, we
// look at the outermost modifier on the method decl and
// call it by-ref, by-box as appropriate. For method1, for
// example, the impl type has one modifier, but the method
// type has two, so we end up with
// ByReferenceExplicitSelfCategory.
let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
let method_modifiers = count_modifiers(explicit_type);
debug!("determine_explicit_self_category(self_info.untransformed_self_ty={} \
explicit_type={} \
modifiers=({},{})",
self_info.untransformed_self_ty.repr(this.tcx()),
explicit_type.repr(this.tcx()),
impl_modifiers,
method_modifiers);
if impl_modifiers >= method_modifiers {
ty::ByValueExplicitSelfCategory
} else {
match explicit_type.sty {
ty::ty_rptr(r, mt) => ty::ByReferenceExplicitSelfCategory(*r, mt.mutbl),
ty::ty_uniq(_) => ty::ByBoxExplicitSelfCategory,
_ => ty::ByValueExplicitSelfCategory,
}
}
}
};
fn count_modifiers(ty: Ty) -> usize {
match ty.sty {
ty::ty_rptr(_, mt) => count_modifiers(mt.ty) + 1,
ty::ty_uniq(t) => count_modifiers(t) + 1,
_ => 0,
}
}
}
pub fn ty_of_closure<'tcx>(
this: &AstConv<'tcx>,
unsafety: ast::Unsafety,
decl: &ast::FnDecl,
abi: abi::Abi,
expected_sig: Option<ty::FnSig<'tcx>>)
-> ty::ClosureTy<'tcx>
{
debug!("ty_of_closure(expected_sig={})",
expected_sig.repr(this.tcx()));
// new region names that appear inside of the fn decl are bound to
// that function type
let rb = rscope::BindingRscope::new();
let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
// no guarantee that the correct number of expected args
// were supplied
if i < e.inputs.len() {
Some(e.inputs[i])
} else {
None
}
});
ty_of_arg(this, &rb, a, expected_arg_ty)
}).collect();
let expected_ret_ty = expected_sig.map(|e| e.output);
let is_infer = match decl.output {
ast::Return(ref output) if output.node == ast::TyInfer => true,
ast::DefaultReturn(..) => true,
_ => false
};
let output_ty = match decl.output {
_ if is_infer && expected_ret_ty.is_some() =>
expected_ret_ty.unwrap(),
_ if is_infer =>
ty::FnConverging(this.ty_infer(decl.output.span())),
ast::Return(ref output) =>
ty::FnConverging(ast_ty_to_ty(this, &rb, &**output)),
ast::DefaultReturn(..) => unreachable!(),
ast::NoReturn(..) => ty::FnDiverging
};
debug!("ty_of_closure: input_tys={}", input_tys.repr(this.tcx()));
debug!("ty_of_closure: output_ty={}", output_ty.repr(this.tcx()));
ty::ClosureTy {
unsafety: unsafety,
abi: abi,
sig: ty::Binder(ty::FnSig {inputs: input_tys,
output: output_ty,
variadic: decl.variadic}),
}
}
/// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
/// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
/// for closures. Eventually this should all be normalized, I think, so that there is no "main
/// trait ref" and instead we just have a flat list of bounds as the existential type.
fn conv_existential_bounds<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
principal_trait_ref: ty::PolyTraitRef<'tcx>,
projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
ast_bounds: &[ast::TyParamBound])
-> ty::ExistentialBounds<'tcx>
{
let partitioned_bounds =
partition_bounds(this.tcx(), span, ast_bounds);
conv_existential_bounds_from_partitioned_bounds(
this, rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
}
fn conv_ty_poly_trait_ref<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
ast_bounds: &[ast::TyParamBound])
-> Ty<'tcx>
{
let mut partitioned_bounds = partition_bounds(this.tcx(), span, &ast_bounds[..]);
let mut projection_bounds = Vec::new();
let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
let trait_bound = partitioned_bounds.trait_bounds.remove(0);
instantiate_poly_trait_ref(this,
rscope,
trait_bound,
None,
&mut projection_bounds)
} else {
span_err!(this.tcx().sess, span, E0224,
"at least one non-builtin trait is required for an object type");
return this.tcx().types.err;
};
let bounds =
conv_existential_bounds_from_partitioned_bounds(this,
rscope,
span,
main_trait_bound.clone(),
projection_bounds,
partitioned_bounds);
make_object_type(this, span, main_trait_bound, bounds)
}
pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
principal_trait_ref: ty::PolyTraitRef<'tcx>,
mut projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
partitioned_bounds: PartitionedBounds)
-> ty::ExistentialBounds<'tcx>
{
let PartitionedBounds { builtin_bounds,
trait_bounds,
region_bounds } =
partitioned_bounds;
if !trait_bounds.is_empty() {
let b = &trait_bounds[0];
span_err!(this.tcx().sess, b.trait_ref.path.span, E0225,
"only the builtin traits can be used as closure or object bounds");
}
let region_bound = compute_object_lifetime_bound(this,
rscope,
span,
®ion_bounds,
principal_trait_ref,
builtin_bounds);
ty::sort_bounds_list(&mut projection_bounds);
ty::ExistentialBounds {
region_bound: region_bound,
builtin_bounds: builtin_bounds,
projection_bounds: projection_bounds,
}
}
/// Given the bounds on an object, determines what single region bound
/// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
/// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
/// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
fn compute_object_lifetime_bound<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
explicit_region_bounds: &[&ast::Lifetime],
principal_trait_ref: ty::PolyTraitRef<'tcx>,
builtin_bounds: ty::BuiltinBounds)
-> ty::Region
{
let tcx = this.tcx();
debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
principal_trait_ref={}, builtin_bounds={})",
explicit_region_bounds,
principal_trait_ref.repr(tcx),
builtin_bounds.repr(tcx));
if explicit_region_bounds.len() > 1 {
span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
"only a single explicit lifetime bound is permitted");
}
if explicit_region_bounds.len() != 0 {
// Explicitly specified region bound. Use that.
let r = explicit_region_bounds[0];
return ast_region_to_region(tcx, r);
}
if let Err(ErrorReported) = this.ensure_super_predicates(span,principal_trait_ref.def_id()) {
return ty::ReStatic;
}
// No explicit region bound specified. Therefore, examine trait
// bounds and see if we can derive region bounds from those.
let derived_region_bounds =
object_region_bounds(tcx, &principal_trait_ref, builtin_bounds);
// If there are no derived region bounds, then report back that we
// can find no region bound.
if derived_region_bounds.len() == 0 {
match rscope.object_lifetime_default(span) {
Some(r) => { return r; }
None => {
span_err!(this.tcx().sess, span, E0228,
"the lifetime bound for this object type cannot be deduced \
from context; please supply an explicit bound");
return ty::ReStatic;
}
}
}
// If any of the derived region bounds are 'static, that is always
// the best choice.
if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
return ty::ReStatic;
}
// Determine whether there is exactly one unique region in the set
// of derived region bounds. If so, use that. Otherwise, report an
// error.
let r = derived_region_bounds[0];
if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
span_err!(tcx.sess, span, E0227,
"ambiguous lifetime bound, explicit lifetime bound required");
}
return r;
}
/// Given an object type like `SomeTrait+Send`, computes the lifetime
/// bounds that must hold on the elided self type. These are derived
/// from the declarations of `SomeTrait`, `Send`, and friends -- if
/// they declare `trait SomeTrait : 'static`, for example, then
/// `'static` would appear in the list. The hard work is done by
/// `ty::required_region_bounds`, see that for more information.
pub fn object_region_bounds<'tcx>(
tcx: &ty::ctxt<'tcx>,
principal: &ty::PolyTraitRef<'tcx>,
others: ty::BuiltinBounds)
-> Vec<ty::Region>
{
// Since we don't actually *know* the self type for an object,
// this "open(err)" serves as a kind of dummy standin -- basically
// a skolemized type.
let open_ty = ty::mk_infer(tcx, ty::FreshTy(0));
// Note that we preserve the overall binding levels here.
assert!(!open_ty.has_escaping_regions());
let substs = tcx.mk_substs(principal.0.substs.with_self_ty(open_ty));
let trait_refs = vec!(ty::Binder(Rc::new(ty::TraitRef::new(principal.0.def_id, substs))));
let param_bounds = ty::ParamBounds {
region_bounds: Vec::new(),
builtin_bounds: others,
trait_bounds: trait_refs,
projection_bounds: Vec::new(), // not relevant to computing region bounds
};
let predicates = ty::predicates(tcx, open_ty, ¶m_bounds);
ty::required_region_bounds(tcx, open_ty, predicates)
}
pub struct PartitionedBounds<'a> {
pub builtin_bounds: ty::BuiltinBounds,
pub trait_bounds: Vec<&'a ast::PolyTraitRef>,
pub region_bounds: Vec<&'a ast::Lifetime>,
}
/// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
/// general trait bounds, and region bounds.
pub fn partition_bounds<'a>(tcx: &ty::ctxt,
_span: Span,
ast_bounds: &'a [ast::TyParamBound])
-> PartitionedBounds<'a>
{
let mut builtin_bounds = ty::empty_builtin_bounds();
let mut region_bounds = Vec::new();
let mut trait_bounds = Vec::new();
for ast_bound in ast_bounds {
match *ast_bound {
ast::TraitTyParamBound(ref b, ast::TraitBoundModifier::None) => {
match ::lookup_full_def(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
def::DefTrait(trait_did) => {
if ty::try_add_builtin_trait(tcx,
trait_did,
&mut builtin_bounds) {
let segments = &b.trait_ref.path.segments;
let parameters = &segments[segments.len() - 1].parameters;
if parameters.types().len() > 0 {
check_type_argument_count(tcx, b.trait_ref.path.span,
parameters.types().len(), 0, 0);
}
if parameters.lifetimes().len() > 0 {
report_lifetime_number_error(tcx, b.trait_ref.path.span,
parameters.lifetimes().len(), 0);
}
continue; // success
}
}
_ => {
// Not a trait? that's an error, but it'll get
// reported later.
}
}
trait_bounds.push(b);
}
ast::TraitTyParamBound(_, ast::TraitBoundModifier::Maybe) => {}
ast::RegionTyParamBound(ref l) => {
region_bounds.push(l);
}
}
}
PartitionedBounds {
builtin_bounds: builtin_bounds,
trait_bounds: trait_bounds,
region_bounds: region_bounds,
}
}
fn prohibit_projections<'tcx>(tcx: &ty::ctxt<'tcx>,
bindings: &[ConvertedBinding<'tcx>])
{
for binding in bindings.iter().take(1) {
span_err!(tcx.sess, binding.span, E0229,
"associated type bindings are not allowed here");
}
}
fn check_type_argument_count(tcx: &ty::ctxt, span: Span, supplied: usize,
required: usize, accepted: usize) {
if supplied < required {
let expected = if required < accepted {
"expected at least"
} else {
"expected"
};
span_err!(tcx.sess, span, E0243,
"wrong number of type arguments: {} {}, found {}",
expected, required, supplied);
} else if supplied > accepted {
let expected = if required < accepted {
"expected at most"
} else {
"expected"
};
span_err!(tcx.sess, span, E0244,
"wrong number of type arguments: {} {}, found {}",
expected,
accepted,
supplied);
}
}
fn report_lifetime_number_error(tcx: &ty::ctxt, span: Span, number: usize, expected: usize) {
span_err!(tcx.sess, span, E0107,
"wrong number of lifetime parameters: expected {}, found {}",
expected, number);
}
| ruud-v-a/rust | src/librustc_typeck/astconv.rs | Rust | apache-2.0 | 91,859 |
package de.uniulm.omi.cloudiator.sword.multicloud.service;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;
import de.uniulm.omi.cloudiator.sword.domain.Cloud;
import de.uniulm.omi.cloudiator.sword.domain.Pricing;
import de.uniulm.omi.cloudiator.sword.multicloud.pricing.PricingSupplierFactory;
import de.uniulm.omi.cloudiator.sword.service.PricingService;
import java.util.*;
import static com.google.common.base.Preconditions.checkNotNull;
public class MultiCloudPricingService implements PricingService {
private final CloudRegistry cloudRegistry;
@Inject
private PricingSupplierFactory pricingSupplierFactory;
@Inject
public MultiCloudPricingService(CloudRegistry cloudRegistry) {
this.cloudRegistry = checkNotNull(cloudRegistry, "cloudRegistry is null");
}
@Override
public Iterable<Pricing> listPricing() {
/*final ImmutableSet.Builder<Pricing> builder = ImmutableSet.builder();
Optional<Cloud> awsCloud = cloudRegistry.list().stream().filter(cloud -> cloud.api().providerName().equals("aws-ec2")).findFirst();
if(awsCloud.isPresent()) {
Supplier<Set<Pricing>> awsPricingSupplier = pricingSupplierFactory.createAWSPricingSupplier(awsCloud.get().credential());
builder.addAll(awsPricingSupplier.get());
}
return builder.build();*/
final ImmutableSet.Builder<Pricing> builder = ImmutableSet.builder();
cloudRegistry
.list()
.stream()
.filter(cloud -> cloud.api().providerName().equals("aws-ec2"))
.findFirst()
.ifPresent(cloud -> builder.addAll(pricingSupplierFactory.createAWSPricingSupplier(cloud.credential()).get()));
return builder.build();
}
}
| cloudiator/sword | multicloud/src/main/java/de/uniulm/omi/cloudiator/sword/multicloud/service/MultiCloudPricingService.java | Java | apache-2.0 | 1,844 |
<!--
Generated template for the PicturePage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<div class="adjust-horizontal inline">
<button class="inline-right" (click)="closeModal()" ion-button clear> Cerrar</button>
</div>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-slides *ngIf="fileList && fileList.length>0" pager="true" zoom="true">
<ion-slide *ngFor="let file of fileList">
<img [src]="ext+'/containers/'+file.container+'/download/'+file.name" alt="">
</ion-slide>
</ion-slides>
</ion-content>
| luispalacios270/frontend-cleanApp | src/pages/picture/picture.html | HTML | apache-2.0 | 657 |
<!-- This file is machine generated: DO NOT EDIT! -->
# Sparse Tensors
Note: Functions taking `Tensor` arguments can also take anything accepted by
[`tf.convert_to_tensor`](framework.md#convert_to_tensor).
[TOC]
## Sparse Tensor Representation
TensorFlow supports a `SparseTensor` representation for data that is sparse
in multiple dimensions. Contrast this representation with `IndexedSlices`,
which is efficient for representing tensors that are sparse in their first
dimension, and dense along all other dimensions.
- - -
### `class tf.SparseTensor` {#SparseTensor}
Represents a sparse tensor.
TensorFlow represents a sparse tensor as three separate dense tensors:
`indices`, `values`, and `shape`. In Python, the three tensors are
collected into a `SparseTensor` class for ease of use. If you have separate
`indices`, `values`, and `shape` tensors, wrap them in a `SparseTensor`
object before passing to the ops below.
Concretely, the sparse tensor `SparseTensor(indices, values, shape)` is
* `indices`: A 2-D int64 tensor of shape `[N, ndims]`.
* `values`: A 1-D tensor of any type and shape `[N]`.
* `shape`: A 1-D int64 tensor of shape `[ndims]`.
where `N` and `ndims` are the number of values, and number of dimensions in
the `SparseTensor` respectively.
The corresponding dense tensor satisfies
```python
dense.shape = shape
dense[tuple(indices[i])] = values[i]
```
By convention, `indices` should be sorted in row-major order (or equivalently
lexicographic order on the tuples `indices[i]`). This is not enforced when
`SparseTensor` objects are constructed, but most ops assume correct ordering.
If the ordering of sparse tensor `st` is wrong, a fixed version can be
obtained by calling `tf.sparse_reorder(st)`.
Example: The sparse tensor
```python
SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], shape=[3, 4])
```
represents the dense tensor
```python
[[1, 0, 0, 0]
[0, 0, 2, 0]
[0, 0, 0, 0]]
```
- - -
#### `tf.SparseTensor.__init__(indices, values, shape)` {#SparseTensor.__init__}
Creates a `SparseTensor`.
##### Args:
* <b>`indices`</b>: A 2-D int64 tensor of shape `[N, ndims]`.
* <b>`values`</b>: A 1-D tensor of any type and shape `[N]`.
* <b>`shape`</b>: A 1-D int64 tensor of shape `[ndims]`.
##### Returns:
A `SparseTensor`
- - -
#### `tf.SparseTensor.indices` {#SparseTensor.indices}
The indices of non-zero values in the represented dense tensor.
##### Returns:
A 2-D Tensor of int64 with shape `[N, ndims]`, where `N` is the
number of non-zero values in the tensor, and `ndims` is the rank.
- - -
#### `tf.SparseTensor.values` {#SparseTensor.values}
The non-zero values in the represented dense tensor.
##### Returns:
A 1-D Tensor of any data type.
- - -
#### `tf.SparseTensor.shape` {#SparseTensor.shape}
A 1-D Tensor of int64 representing the shape of the dense tensor.
- - -
#### `tf.SparseTensor.dtype` {#SparseTensor.dtype}
The `DType` of elements in this tensor.
- - -
#### `tf.SparseTensor.op` {#SparseTensor.op}
The `Operation` that produces `values` as an output.
- - -
#### `tf.SparseTensor.graph` {#SparseTensor.graph}
The `Graph` that contains the index, value, and shape tensors.
#### Other Methods
- - -
#### `tf.SparseTensor.eval(feed_dict=None, session=None)` {#SparseTensor.eval}
Evaluates this sparse tensor in a `Session`.
Calling this method will execute all preceding operations that
produce the inputs needed for the operation that produces this
tensor.
*N.B.* Before invoking `SparseTensor.eval()`, its graph must have been
launched in a session, and either a default session must be
available, or `session` must be specified explicitly.
##### Args:
* <b>`feed_dict`</b>: A dictionary that maps `Tensor` objects to feed values.
See [`Session.run()`](../../api_docs/python/client.md#Session.run) for a
description of the valid feed values.
* <b>`session`</b>: (Optional.) The `Session` to be used to evaluate this sparse
tensor. If none, the default session will be used.
##### Returns:
A `SparseTensorValue` object.
- - -
#### `tf.SparseTensor.from_value(cls, sparse_tensor_value)` {#SparseTensor.from_value}
- - -
### `class tf.SparseTensorValue` {#SparseTensorValue}
SparseTensorValue(indices, values, shape)
- - -
#### `tf.SparseTensorValue.indices` {#SparseTensorValue.indices}
Alias for field number 0
- - -
#### `tf.SparseTensorValue.shape` {#SparseTensorValue.shape}
Alias for field number 2
- - -
#### `tf.SparseTensorValue.values` {#SparseTensorValue.values}
Alias for field number 1
## Conversion
- - -
### `tf.sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value=0, validate_indices=True, name=None)` {#sparse_to_dense}
Converts a sparse representation into a dense tensor.
Builds an array `dense` with shape `output_shape` such that
```python
# If sparse_indices is scalar
dense[i] = (i == sparse_indices ? sparse_values : default_value)
# If sparse_indices is a vector, then for each i
dense[sparse_indices[i]] = sparse_values[i]
# If sparse_indices is an n by d matrix, then for each i in [0, n)
dense[sparse_indices[i][0], ..., sparse_indices[i][d-1]] = sparse_values[i]
```
All other values in `dense` are set to `default_value`. If `sparse_values`
is a scalar, all sparse indices are set to this single value.
Indices should be sorted in lexicographic order, and indices must not
contain any repeats. If `validate_indices` is True, these properties
are checked during execution.
##### Args:
* <b>`sparse_indices`</b>: A 0-D, 1-D, or 2-D `Tensor` of type `int32` or `int64`.
`sparse_indices[i]` contains the complete index where `sparse_values[i]`
will be placed.
* <b>`output_shape`</b>: A 1-D `Tensor` of the same type as `sparse_indices`. Shape
of the dense output tensor.
* <b>`sparse_values`</b>: A 0-D or 1-D `Tensor`. Values corresponding to each row of
`sparse_indices`, or a scalar value to be used for all sparse indices.
* <b>`default_value`</b>: A 0-D `Tensor` of the same type as `sparse_values`. Value
to set for indices not specified in `sparse_indices`. Defaults to zero.
* <b>`validate_indices`</b>: A boolean value. If True, indices are checked to make
sure they are sorted in lexicographic order and that there are no repeats.
* <b>`name`</b>: A name for the operation (optional).
##### Returns:
Dense `Tensor` of shape `output_shape`. Has the same type as
`sparse_values`.
- - -
### `tf.sparse_tensor_to_dense(sp_input, default_value=0, validate_indices=True, name=None)` {#sparse_tensor_to_dense}
Converts a `SparseTensor` into a dense tensor.
This op is a convenience wrapper around `sparse_to_dense` for `SparseTensor`s.
For example, if `sp_input` has shape `[3, 5]` and non-empty string values:
[0, 1]: a
[0, 3]: b
[2, 0]: c
and `default_value` is `x`, then the output will be a dense `[3, 5]`
string tensor with values:
[[x a x b x]
[x x x x x]
[c x x x x]]
Indices must be without repeats. This is only
tested if validate_indices is True.
##### Args:
* <b>`sp_input`</b>: The input `SparseTensor`.
* <b>`default_value`</b>: Scalar value to set for indices not specified in
`sp_input`. Defaults to zero.
* <b>`validate_indices`</b>: A boolean value. If `True`, indices are checked to make
sure they are sorted in lexicographic order and that there are no repeats.
* <b>`name`</b>: A name prefix for the returned tensors (optional).
##### Returns:
A dense tensor with shape `sp_input.shape` and values specified by
the non-empty values in `sp_input`. Indices not in `sp_input` are assigned
`default_value`.
##### Raises:
* <b>`TypeError`</b>: If `sp_input` is not a `SparseTensor`.
- - -
### `tf.sparse_to_indicator(sp_input, vocab_size, name=None)` {#sparse_to_indicator}
Converts a `SparseTensor` of ids into a dense bool indicator tensor.
The last dimension of `sp_input.indices` is discarded and replaced with
the values of `sp_input`. If `sp_input.shape = [D0, D1, ..., Dn, K]`, then
`output.shape = [D0, D1, ..., Dn, vocab_size]`, where
output[d_0, d_1, ..., d_n, sp_input[d_0, d_1, ..., d_n, k]] = True
and False elsewhere in `output`.
For example, if `sp_input.shape = [2, 3, 4]` with non-empty values:
[0, 0, 0]: 0
[0, 1, 0]: 10
[1, 0, 3]: 103
[1, 1, 2]: 150
[1, 1, 3]: 149
[1, 1, 4]: 150
[1, 2, 1]: 121
and `vocab_size = 200`, then the output will be a `[2, 3, 200]` dense bool
tensor with False everywhere except at positions
(0, 0, 0), (0, 1, 10), (1, 0, 103), (1, 1, 149), (1, 1, 150),
(1, 2, 121).
Note that repeats are allowed in the input SparseTensor.
This op is useful for converting `SparseTensor`s into dense formats for
compatibility with ops that expect dense tensors.
The input `SparseTensor` must be in row-major order.
##### Args:
* <b>`sp_input`</b>: A `SparseTensor` with `values` property of type `int32` or
`int64`.
* <b>`vocab_size`</b>: A scalar int64 Tensor (or Python int) containing the new size
of the last dimension, `all(0 <= sp_input.values < vocab_size)`.
* <b>`name`</b>: A name prefix for the returned tensors (optional)
##### Returns:
A dense bool indicator tensor representing the indices with specified value.
##### Raises:
* <b>`TypeError`</b>: If `sp_input` is not a `SparseTensor`.
- - -
### `tf.sparse_merge(sp_ids, sp_values, vocab_size, name=None)` {#sparse_merge}
Combines a batch of feature ids and values into a single `SparseTensor`.
The most common use case for this function occurs when feature ids and
their corresponding values are stored in `Example` protos on disk.
`parse_example` will return a batch of ids and a batch of values, and this
function joins them into a single logical `SparseTensor` for use in
functions such as `sparse_tensor_dense_matmul`, `sparse_to_dense`, etc.
The `SparseTensor` returned by this function has the following properties:
- `indices` is equivalent to `sp_ids.indices` with the last
dimension discarded and replaced with `sp_ids.values`.
- `values` is simply `sp_values.values`.
- If `sp_ids.shape = [D0, D1, ..., Dn, K]`, then
`output.shape = [D0, D1, ..., Dn, vocab_size]`.
For example, consider the following feature vectors:
vector1 = [-3, 0, 0, 0, 0, 0]
vector2 = [ 0, 1, 0, 4, 1, 0]
vector3 = [ 5, 0, 0, 9, 0, 0]
These might be stored sparsely in the following Example protos by storing
only the feature ids (column number if the vectors are treated as a matrix)
of the non-zero elements and the corresponding values:
examples = [Example(features={
"ids": Feature(int64_list=Int64List(value=[0])),
"values": Feature(float_list=FloatList(value=[-3]))}),
Example(features={
"ids": Feature(int64_list=Int64List(value=[1, 4, 3])),
"values": Feature(float_list=FloatList(value=[1, 1, 4]))}),
Example(features={
"ids": Feature(int64_list=Int64List(value=[0, 3])),
"values": Feature(float_list=FloatList(value=[5, 9]))})]
The result of calling parse_example on these examples will produce a
dictionary with entries for "ids" and "values". Passing those two objects
to this function along with vocab_size=6, will produce a `SparseTensor` that
sparsely represents all three instances. Namely, the `indices` property will
contain the coordinates of the non-zero entries in the feature matrix (the
first dimension is the row number in the matrix, i.e., the index within the
batch, and the second dimension is the column number, i.e., the feature id);
`values` will contain the actual values. `shape` will be the shape of the
original matrix, i.e., (3, 6). For our example above, the output will be
equal to:
SparseTensor(indices=[[0, 0], [1, 1], [1, 3], [1, 4], [2, 0], [2, 3]],
values=[-3, 1, 4, 1, 5, 9],
shape=[3, 6])
##### Args:
* <b>`sp_ids`</b>: A `SparseTensor` with `values` property of type `int32`
or `int64`.
* <b>`sp_values`</b>: A`SparseTensor` of any type.
* <b>`vocab_size`</b>: A scalar `int64` Tensor (or Python int) containing the new size
of the last dimension, `all(0 <= sp_ids.values < vocab_size)`.
* <b>`name`</b>: A name prefix for the returned tensors (optional)
##### Returns:
A `SparseTensor` compactly representing a batch of feature ids and values,
useful for passing to functions that expect such a `SparseTensor`.
##### Raises:
* <b>`TypeError`</b>: If `sp_ids` or `sp_values` are not a `SparseTensor`.
## Manipulation
- - -
### `tf.sparse_concat(concat_dim, sp_inputs, name=None, expand_nonconcat_dim=False)` {#sparse_concat}
Concatenates a list of `SparseTensor` along the specified dimension.
Concatenation is with respect to the dense versions of each sparse input.
It is assumed that each inputs is a `SparseTensor` whose elements are ordered
along increasing dimension number.
If expand_nonconcat_dim is False, all inputs' shapes must match, except for
the concat dimension. If expand_nonconcat_dim is True, then inputs' shapes are
allowd to vary among all inputs.
The `indices`, `values`, and `shapes` lists must have the same length.
If expand_nonconcat_dim is False, then the output shape is identical to the
inputs', except along the concat dimension, where it is the sum of the inputs'
sizes along that dimension.
If expand_nonconcat_dim is True, then the output shape along the non-concat
dimensions will be expand to be the largest among all inputs, and it is the
sum of the inputs sizes along the concat dimension.
The output elements will be resorted to preserve the sort order along
increasing dimension number.
This op runs in `O(M log M)` time, where `M` is the total number of non-empty
values across all inputs. This is due to the need for an internal sort in
order to concatenate efficiently across an arbitrary dimension.
For example, if `concat_dim = 1` and the inputs are
sp_inputs[0]: shape = [2, 3]
[0, 2]: "a"
[1, 0]: "b"
[1, 1]: "c"
sp_inputs[1]: shape = [2, 4]
[0, 1]: "d"
[0, 2]: "e"
then the output will be
shape = [2, 7]
[0, 2]: "a"
[0, 4]: "d"
[0, 5]: "e"
[1, 0]: "b"
[1, 1]: "c"
Graphically this is equivalent to doing
[ a] concat [ d e ] = [ a d e ]
[b c ] [ ] [b c ]
Another example, if 'concat_dim = 1' and the inputs are
sp_inputs[0]: shape = [3, 3]
[0, 2]: "a"
[1, 0]: "b"
[2, 1]: "c"
sp_inputs[1]: shape = [2, 4]
[0, 1]: "d"
[0, 2]: "e"
if expand_nonconcat_dim = False, this will result in an error. But if
expand_nonconcat_dim = True, this will result in:
shape = [3, 7]
[0, 2]: "a"
[0, 4]: "d"
[0, 5]: "e"
[1, 0]: "b"
[2, 1]: "c"
Graphically this is equivalent to doing
[ a] concat [ d e ] = [ a d e ]
[b ] [ ] [b ]
[ c ] [ c ]
##### Args:
* <b>`concat_dim`</b>: Dimension to concatenate along.
* <b>`sp_inputs`</b>: List of `SparseTensor` to concatenate.
* <b>`name`</b>: A name prefix for the returned tensors (optional).
* <b>`expand_nonconcat_dim`</b>: Whether to allow the expansion in the non-concat
dimensions. Defaulted to False.
##### Returns:
A `SparseTensor` with the concatenated output.
##### Raises:
* <b>`TypeError`</b>: If `sp_inputs` is not a list of `SparseTensor`.
- - -
### `tf.sparse_reorder(sp_input, name=None)` {#sparse_reorder}
Reorders a `SparseTensor` into the canonical, row-major ordering.
Note that by convention, all sparse ops preserve the canonical ordering
along increasing dimension number. The only time ordering can be violated
is during manual manipulation of the indices and values to add entries.
Reordering does not affect the shape of the `SparseTensor`.
For example, if `sp_input` has shape `[4, 5]` and `indices` / `values`:
[0, 3]: b
[0, 1]: a
[3, 1]: d
[2, 0]: c
then the output will be a `SparseTensor` of shape `[4, 5]` and
`indices` / `values`:
[0, 1]: a
[0, 3]: b
[2, 0]: c
[3, 1]: d
##### Args:
* <b>`sp_input`</b>: The input `SparseTensor`.
* <b>`name`</b>: A name prefix for the returned tensors (optional)
##### Returns:
A `SparseTensor` with the same shape and non-empty values, but in
canonical ordering.
##### Raises:
* <b>`TypeError`</b>: If `sp_input` is not a `SparseTensor`.
- - -
### `tf.sparse_reshape(sp_input, shape, name=None)` {#sparse_reshape}
Reshapes a `SparseTensor` to represent values in a new dense shape.
This operation has the same semantics as `reshape` on the represented dense
tensor. The indices of non-empty values in `sp_input` are recomputed based
on the new dense shape, and a new `SparseTensor` is returned containing the
new indices and new shape. The order of non-empty values in `sp_input` is
unchanged.
If one component of `shape` is the special value -1, the size of that
dimension is computed so that the total dense size remains constant. At
most one component of `shape` can be -1. The number of dense elements
implied by `shape` must be the same as the number of dense elements
originally represented by `sp_input`.
For example, if `sp_input` has shape `[2, 3, 6]` and `indices` / `values`:
[0, 0, 0]: a
[0, 0, 1]: b
[0, 1, 0]: c
[1, 0, 0]: d
[1, 2, 3]: e
and `shape` is `[9, -1]`, then the output will be a `SparseTensor` of
shape `[9, 4]` and `indices` / `values`:
[0, 0]: a
[0, 1]: b
[1, 2]: c
[4, 2]: d
[8, 1]: e
##### Args:
* <b>`sp_input`</b>: The input `SparseTensor`.
* <b>`shape`</b>: A 1-D (vector) int64 `Tensor` specifying the new dense shape of the
represented `SparseTensor`.
* <b>`name`</b>: A name prefix for the returned tensors (optional)
##### Returns:
A `SparseTensor` with the same non-empty values but with indices calculated
by the new dense shape.
##### Raises:
* <b>`TypeError`</b>: If `sp_input` is not a `SparseTensor`.
- - -
### `tf.sparse_split(split_dim, num_split, sp_input, name=None)` {#sparse_split}
Split a `SparseTensor` into `num_split` tensors along `split_dim`.
If the `sp_input.shape[split_dim]` is not an integer multiple of `num_split`
each slice starting from 0:`shape[split_dim] % num_split` gets extra one
dimension. For example, if `split_dim = 1` and `num_split = 2` and the
input is:
input_tensor = shape = [2, 7]
[ a d e ]
[b c ]
Graphically the output tensors are:
output_tensor[0] =
[ a ]
[b c ]
output_tensor[1] =
[ d e ]
[ ]
##### Args:
* <b>`split_dim`</b>: A 0-D `int32` `Tensor`. The dimension along which to split.
* <b>`num_split`</b>: A Python integer. The number of ways to split.
* <b>`sp_input`</b>: The `SparseTensor` to split.
* <b>`name`</b>: A name for the operation (optional).
##### Returns:
`num_split` `SparseTensor` objects resulting from splitting `value`.
##### Raises:
* <b>`TypeError`</b>: If `sp_input` is not a `SparseTensor`.
- - -
### `tf.sparse_retain(sp_input, to_retain)` {#sparse_retain}
Retains specified non-empty values within a `SparseTensor`.
For example, if `sp_input` has shape `[4, 5]` and 4 non-empty string values:
[0, 1]: a
[0, 3]: b
[2, 0]: c
[3, 1]: d
and `to_retain = [True, False, False, True]`, then the output will
be a `SparseTensor` of shape `[4, 5]` with 2 non-empty values:
[0, 1]: a
[3, 1]: d
##### Args:
* <b>`sp_input`</b>: The input `SparseTensor` with `N` non-empty elements.
* <b>`to_retain`</b>: A bool vector of length `N` with `M` true values.
##### Returns:
A `SparseTensor` with the same shape as the input and `M` non-empty
elements corresponding to the true positions in `to_retain`.
##### Raises:
* <b>`TypeError`</b>: If `sp_input` is not a `SparseTensor`.
- - -
### `tf.sparse_reset_shape(sp_input, new_shape=None)` {#sparse_reset_shape}
Resets the shape of a `SparseTensor` with indices and values unchanged.
If `new_shape` is None, returns a copy of `sp_input` with its shape reset
to the tight bounding box of `sp_input`.
If `new_shape` is provided, then it must be larger or equal in all dimensions
compared to the shape of `sp_input`. When this condition is met, the returned
SparseTensor will have its shape reset to `new_shape` and its indices and
values unchanged from that of `sp_input.`
For example:
Consider a `sp_input` with shape [2, 3, 5]:
[0, 0, 1]: a
[0, 1, 0]: b
[0, 2, 2]: c
[1, 0, 3]: d
- It is an error to set `new_shape` as [3, 7] since this represents a
rank-2 tensor while `sp_input` is rank-3. This is either a ValueError
during graph construction (if both shapes are known) or an OpError during
run time.
- Setting `new_shape` as [2, 3, 6] will be fine as this shape is larger or
eqaul in every dimension compared to the original shape [2, 3, 5].
- On the other hand, setting new_shape as [2, 3, 4] is also an error: The
third dimension is smaller than the original shape [2, 3, 5] (and an
`InvalidArgumentError` will be raised).
- If `new_shape` is None, the returned SparseTensor will have a shape
[2, 3, 4], which is the tight bounding box of `sp_input`.
##### Args:
* <b>`sp_input`</b>: The input `SparseTensor`.
* <b>`new_shape`</b>: None or a vector representing the new shape for the returned
`SpraseTensor`.
##### Returns:
A `SparseTensor` indices and values unchanged from `input_sp`. Its shape is
`new_shape` if that is set. Otherwise it is the tight bounding box of
`input_sp`
##### Raises:
* <b>`TypeError`</b>: If `sp_input` is not a `SparseTensor`.
* <b>`ValueError`</b>: If `new_shape` represents a tensor with a different rank from
that of `sp_input` (if shapes are known when graph is constructed).
* <b>`OpError`</b>:
- If `new_shape` has dimension sizes that are too small.
- If shapes are not known during graph construction time, and during run
time it is found out that the ranks do not match.
- - -
### `tf.sparse_fill_empty_rows(sp_input, default_value, name=None)` {#sparse_fill_empty_rows}
Fills empty rows in the input 2-D `SparseTensor` with a default value.
This op adds entries with the specified `default_value` at index
`[row, 0]` for any row in the input that does not already have a value.
For example, suppose `sp_input` has shape `[5, 6]` and non-empty values:
[0, 1]: a
[0, 3]: b
[2, 0]: c
[3, 1]: d
Rows 1 and 4 are empty, so the output will be of shape `[5, 6]` with values:
[0, 1]: a
[0, 3]: b
[1, 0]: default_value
[2, 0]: c
[3, 1]: d
[4, 0]: default_value
Note that the input may have empty columns at the end, with no effect on
this op.
The output `SparseTensor` will be in row-major order and will have the
same shape as the input.
This op also returns an indicator vector such that
empty_row_indicator[i] = True iff row i was an empty row.
##### Args:
* <b>`sp_input`</b>: A `SparseTensor` with shape `[N, M]`.
* <b>`default_value`</b>: The value to fill for empty rows, with the same type as
`sp_input.`
* <b>`name`</b>: A name prefix for the returned tensors (optional)
##### Returns:
* <b>`sp_ordered_output`</b>: A `SparseTensor` with shape `[N, M]`, and with all empty
rows filled in with `default_value`.
* <b>`empty_row_indicator`</b>: A bool vector of length `N` indicating whether each
input row was empty.
##### Raises:
* <b>`TypeError`</b>: If `sp_input` is not a `SparseTensor`.
## Reduction
- - -
### `tf.sparse_reduce_sum(sp_input, reduction_axes=None, keep_dims=False)` {#sparse_reduce_sum}
Computes the sum of elements across dimensions of a SparseTensor.
This Op takes a SparseTensor and is the sparse counterpart to
`tf.reduce_sum()`. In particular, this Op also returns a dense `Tensor`
instead of a sparse one.
Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless
`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in
`reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained
with length 1.
If `reduction_axes` has no entries, all dimensions are reduced, and a tensor
with a single element is returned. Additionally, the axes can be negative,
similar to the indexing rules in Python.
For example:
```python
# 'x' represents [[1, ?, 1]
# [?, 1, ?]]
# where ? is implictly-zero.
tf.sparse_reduce_sum(x) ==> 3
tf.sparse_reduce_sum(x, 0) ==> [1, 1, 1]
tf.sparse_reduce_sum(x, 1) ==> [2, 1] # Can also use -1 as the axis.
tf.sparse_reduce_sum(x, 1, keep_dims=True) ==> [[2], [1]]
tf.sparse_reduce_sum(x, [0, 1]) ==> 3
```
##### Args:
* <b>`sp_input`</b>: The SparseTensor to reduce. Should have numeric type.
* <b>`reduction_axes`</b>: The dimensions to reduce; list or scalar. If `None` (the
default), reduces all dimensions.
* <b>`keep_dims`</b>: If true, retain reduced dimensions with length 1.
##### Returns:
The reduced Tensor.
## Math Operations
- - -
### `tf.sparse_add(a, b, thresh=0)` {#sparse_add}
Adds two tensors, at least one of each is a `SparseTensor`.
If one `SparseTensor` and one `Tensor` are passed in, returns a `Tensor`. If
both arguments are `SparseTensor`s, this returns a `SparseTensor`. The order
of arguments does not matter. Use vanilla `tf.add()` for adding two dense
`Tensor`s.
The indices of any input `SparseTensor` are assumed ordered in standard
lexicographic order. If this is not the case, before this step run
`SparseReorder` to restore index ordering.
If both arguments are sparse, we perform "clipping" as follows. By default,
if two values sum to zero at some index, the output `SparseTensor` would still
include that particular location in its index, storing a zero in the
corresponding value slot. To override this, callers can specify `thresh`,
indicating that if the sum has a magnitude strictly smaller than `thresh`, its
corresponding value and index would then not be included. In particular,
`thresh == 0.0` (default) means everything is kept and actual thresholding
happens only for a positive value.
For example, suppose the logical sum of two sparse operands is (densified):
[ 2]
[.1 0]
[ 6 -.2]
Then,
- thresh == 0 (the default): all 5 index/value pairs will be returned.
- thresh == 0.11: only .1 and 0 will vanish, and the remaining three
index/value pairs will be returned.
- thresh == 0.21: .1, 0, and -.2 will vanish.
##### Args:
* <b>`a`</b>: The first operand; `SparseTensor` or `Tensor`.
* <b>`b`</b>: The second operand; `SparseTensor` or `Tensor`. At least one operand
must be sparse.
* <b>`thresh`</b>: A 0-D `Tensor`. The magnitude threshold that determines if an
output value/index pair takes space. Its dtype should match that of the
values if they are real; if the latter are complex64/complex128, then the
dtype should be float32/float64, correspondingly.
##### Returns:
A `SparseTensor` or a `Tensor`, representing the sum.
##### Raises:
* <b>`TypeError`</b>: If both `a` and `b` are `Tensor`s. Use `tf.add()` instead.
- - -
### `tf.sparse_softmax(sp_input, name=None)` {#sparse_softmax}
Applies softmax to a batched N-D `SparseTensor`.
The inputs represent an N-D SparseTensor with logical shape `[..., B, C]`
(where `N >= 2`), and with indices sorted in the canonical lexicographic
order.
This op is equivalent to applying the normal `tf.nn.softmax()` to each
innermost logical submatrix with shape `[B, C]`, but with the catch that *the
implicitly zero elements do not participate*. Specifically, the algorithm is
equivalent to:
(1) Applies `tf.nn.softmax()` to a densified view of each innermost
submatrix with shape `[B, C]`, along the size-C dimension;
(2) Masks out the original implicitly-zero locations;
(3) Renormalizes the remaining elements.
Hence, the `SparseTensor` result has exactly the same non-zero indices and
shape.
Example:
```python
# First batch:
# [? e.]
# [1. ? ]
# Second batch:
# [e ? ]
# [e e ]
shape = [2, 2, 2] # 3-D SparseTensor
values = np.asarray([[[0., np.e], [1., 0.]], [[np.e, 0.], [np.e, np.e]]])
indices = np.vstack(np.where(values)).astype(np.int64).T
result = tf.sparse_softmax(tf.SparseTensor(indices, values, shape))
# ...returning a 3-D SparseTensor, equivalent to:
# [? 1.] [1 ?]
# [1. ? ] and [.5 .5]
# where ? means implicitly zero.
```
##### Args:
* <b>`sp_input`</b>: N-D `SparseTensor`, where `N >= 2`.
* <b>`name`</b>: optional name of the operation.
##### Returns:
* <b>`output`</b>: N-D `SparseTensor` representing the results.
- - -
### `tf.sparse_tensor_dense_matmul(sp_a, b, adjoint_a=False, adjoint_b=False, name=None)` {#sparse_tensor_dense_matmul}
Multiply SparseTensor (of rank 2) "A" by dense matrix "B".
No validity checking is performed on the indices of A. However, the following
input format is recommended for optimal behavior:
if adjoint_a == false:
A should be sorted in lexicographically increasing order. Use
sparse_reorder if you're not sure.
if adjoint_a == true:
A should be sorted in order of increasing dimension 1 (i.e., "column major"
order instead of "row major" order).
Deciding when to use sparse_tensor_dense_matmul vs. matmul(sp_a=True):
There are a number of questions to ask in the decision process, including:
* Will the SparseTensor A fit in memory if densified?
* Is the column count of the product large (>> 1)?
* Is the density of A larger than approximately 15%?
If the answer to several of these questions is yes, consider
converting the SparseTensor to a dense one and using tf.matmul with sp_a=True.
This operation tends to perform well when A is more sparse, if the column size
of the product is small (e.g. matrix-vector multiplication), if sp_a.shape
takes on large values.
Below is a rough speed comparison between sparse_tensor_dense_matmul,
labelled 'sparse', and matmul(sp_a=True), labelled 'dense'. For purposes of
the comparison, the time spent converting from a SparseTensor to a dense
Tensor is not included, so it is overly conservative with respect to
the time ratio.
Benchmark system:
CPU: Intel Ivybridge with HyperThreading (6 cores) dL1:32KB dL2:256KB dL3:12MB
GPU: NVidia Tesla k40c
Compiled with:
-c opt --config=cuda --copt=-mavx
```tensorflow/python/sparse_tensor_dense_matmul_op_test --benchmarks
A sparse [m, k] with % nonzero values between 1% and 80%
B dense [k, n]
% nnz n gpu m k dt(dense) dt(sparse) dt(sparse)/dt(dense)
0.01 1 True 100 100 0.000221166 0.00010154 0.459112
0.01 1 True 100 1000 0.00033858 0.000109275 0.322745
0.01 1 True 1000 100 0.000310557 9.85661e-05 0.317385
0.01 1 True 1000 1000 0.0008721 0.000100875 0.115669
0.01 1 False 100 100 0.000208085 0.000107603 0.51711
0.01 1 False 100 1000 0.000327112 9.51118e-05 0.290762
0.01 1 False 1000 100 0.000308222 0.00010345 0.335635
0.01 1 False 1000 1000 0.000865721 0.000101397 0.117124
0.01 10 True 100 100 0.000218522 0.000105537 0.482958
0.01 10 True 100 1000 0.000340882 0.000111641 0.327506
0.01 10 True 1000 100 0.000315472 0.000117376 0.372064
0.01 10 True 1000 1000 0.000905493 0.000123263 0.136128
0.01 10 False 100 100 0.000221529 9.82571e-05 0.44354
0.01 10 False 100 1000 0.000330552 0.000112615 0.340687
0.01 10 False 1000 100 0.000341277 0.000114097 0.334324
0.01 10 False 1000 1000 0.000819944 0.000120982 0.147549
0.01 25 True 100 100 0.000207806 0.000105977 0.509981
0.01 25 True 100 1000 0.000322879 0.00012921 0.400181
0.01 25 True 1000 100 0.00038262 0.000141583 0.370035
0.01 25 True 1000 1000 0.000865438 0.000202083 0.233504
0.01 25 False 100 100 0.000209401 0.000104696 0.499979
0.01 25 False 100 1000 0.000321161 0.000130737 0.407076
0.01 25 False 1000 100 0.000377012 0.000136801 0.362856
0.01 25 False 1000 1000 0.000861125 0.00020272 0.235413
0.2 1 True 100 100 0.000206952 9.69219e-05 0.46833
0.2 1 True 100 1000 0.000348674 0.000147475 0.422959
0.2 1 True 1000 100 0.000336908 0.00010122 0.300439
0.2 1 True 1000 1000 0.001022 0.000203274 0.198898
0.2 1 False 100 100 0.000207532 9.5412e-05 0.459746
0.2 1 False 100 1000 0.000356127 0.000146824 0.41228
0.2 1 False 1000 100 0.000322664 0.000100918 0.312764
0.2 1 False 1000 1000 0.000998987 0.000203442 0.203648
0.2 10 True 100 100 0.000211692 0.000109903 0.519165
0.2 10 True 100 1000 0.000372819 0.000164321 0.440753
0.2 10 True 1000 100 0.000338651 0.000144806 0.427596
0.2 10 True 1000 1000 0.00108312 0.000758876 0.70064
0.2 10 False 100 100 0.000215727 0.000110502 0.512231
0.2 10 False 100 1000 0.000375419 0.0001613 0.429653
0.2 10 False 1000 100 0.000336999 0.000145628 0.432132
0.2 10 False 1000 1000 0.00110502 0.000762043 0.689618
0.2 25 True 100 100 0.000218705 0.000129913 0.594009
0.2 25 True 100 1000 0.000394794 0.00029428 0.745402
0.2 25 True 1000 100 0.000404483 0.0002693 0.665788
0.2 25 True 1000 1000 0.0012002 0.00194494 1.62052
0.2 25 False 100 100 0.000221494 0.0001306 0.589632
0.2 25 False 100 1000 0.000396436 0.000297204 0.74969
0.2 25 False 1000 100 0.000409346 0.000270068 0.659754
0.2 25 False 1000 1000 0.00121051 0.00193737 1.60046
0.5 1 True 100 100 0.000214981 9.82111e-05 0.456836
0.5 1 True 100 1000 0.000415328 0.000223073 0.537101
0.5 1 True 1000 100 0.000358324 0.00011269 0.314492
0.5 1 True 1000 1000 0.00137612 0.000437401 0.317851
0.5 1 False 100 100 0.000224196 0.000101423 0.452386
0.5 1 False 100 1000 0.000400987 0.000223286 0.556841
0.5 1 False 1000 100 0.000368825 0.00011224 0.304318
0.5 1 False 1000 1000 0.00136036 0.000429369 0.31563
0.5 10 True 100 100 0.000222125 0.000112308 0.505608
0.5 10 True 100 1000 0.000461088 0.00032357 0.701753
0.5 10 True 1000 100 0.000394624 0.000225497 0.571422
0.5 10 True 1000 1000 0.00158027 0.00190898 1.20801
0.5 10 False 100 100 0.000232083 0.000114978 0.495418
0.5 10 False 100 1000 0.000454574 0.000324632 0.714146
0.5 10 False 1000 100 0.000379097 0.000227768 0.600817
0.5 10 False 1000 1000 0.00160292 0.00190168 1.18638
0.5 25 True 100 100 0.00023429 0.000151703 0.647501
0.5 25 True 100 1000 0.000497462 0.000598873 1.20386
0.5 25 True 1000 100 0.000460778 0.000557038 1.20891
0.5 25 True 1000 1000 0.00170036 0.00467336 2.74845
0.5 25 False 100 100 0.000228981 0.000155334 0.678371
0.5 25 False 100 1000 0.000496139 0.000620789 1.25124
0.5 25 False 1000 100 0.00045473 0.000551528 1.21287
0.5 25 False 1000 1000 0.00171793 0.00467152 2.71927
0.8 1 True 100 100 0.000222037 0.000105301 0.47425
0.8 1 True 100 1000 0.000410804 0.000329327 0.801664
0.8 1 True 1000 100 0.000349735 0.000131225 0.375212
0.8 1 True 1000 1000 0.00139219 0.000677065 0.48633
0.8 1 False 100 100 0.000214079 0.000107486 0.502085
0.8 1 False 100 1000 0.000413746 0.000323244 0.781261
0.8 1 False 1000 100 0.000348983 0.000131983 0.378193
0.8 1 False 1000 1000 0.00136296 0.000685325 0.50282
0.8 10 True 100 100 0.000229159 0.00011825 0.516017
0.8 10 True 100 1000 0.000498845 0.000532618 1.0677
0.8 10 True 1000 100 0.000383126 0.00029935 0.781336
0.8 10 True 1000 1000 0.00162866 0.00307312 1.88689
0.8 10 False 100 100 0.000230783 0.000124958 0.541452
0.8 10 False 100 1000 0.000493393 0.000550654 1.11606
0.8 10 False 1000 100 0.000377167 0.000298581 0.791642
0.8 10 False 1000 1000 0.00165795 0.00305103 1.84024
0.8 25 True 100 100 0.000233496 0.000175241 0.75051
0.8 25 True 100 1000 0.00055654 0.00102658 1.84458
0.8 25 True 1000 100 0.000463814 0.000783267 1.68875
0.8 25 True 1000 1000 0.00186905 0.00755344 4.04132
0.8 25 False 100 100 0.000240243 0.000175047 0.728625
0.8 25 False 100 1000 0.000578102 0.00104499 1.80763
0.8 25 False 1000 100 0.000485113 0.000776849 1.60138
0.8 25 False 1000 1000 0.00211448 0.00752736 3.55992
```
##### Args:
* <b>`sp_a`</b>: SparseTensor A, of rank 2.
* <b>`b`</b>: A dense Matrix with the same dtype as sp_a.
* <b>`adjoint_a`</b>: Use the adjoint of A in the matrix multiply. If A is complex,
this is transpose(conj(A)). Otherwise it's transpose(A).
* <b>`adjoint_b`</b>: Use the adjoint of B in the matrix multiply. If B is complex,
this is transpose(conj(B)). Otherwise it's transpose(B).
* <b>`name`</b>: A name prefix for the returned tensors (optional)
##### Returns:
A dense matrix (pseudo-code in dense np.matrix notation):
A = A.H if adjoint_a else A
B = B.H if adjoint_b else B
return A*B
- - -
### `tf.sparse_maximum(sp_a, sp_b, name=None)` {#sparse_maximum}
Returns the element-wise max of two SparseTensors.
Assumes the two SparseTensors have the same shape, i.e., no broadcasting.
Example:
```python
sp_zero = ops.SparseTensor([[0]], [0], [7])
sp_one = ops.SparseTensor([[1]], [1], [7])
res = tf.sparse_maximum(sp_zero, sp_one).eval()
# "res" should be equal to SparseTensor([[0], [1]], [0, 1], [7]).
```
##### Args:
* <b>`sp_a`</b>: a `SparseTensor` operand whose dtype is real, and indices
lexicographically ordered.
* <b>`sp_b`</b>: the other `SparseTensor` operand with the same requirements (and the
same shape).
* <b>`name`</b>: optional name of the operation.
##### Returns:
* <b>`output`</b>: the output SparseTensor.
- - -
### `tf.sparse_minimum(sp_a, sp_b, name=None)` {#sparse_minimum}
Returns the element-wise min of two SparseTensors.
Assumes the two SparseTensors have the same shape, i.e., no broadcasting.
Example:
```python
sp_zero = ops.SparseTensor([[0]], [0], [7])
sp_one = ops.SparseTensor([[1]], [1], [7])
res = tf.sparse_minimum(sp_zero, sp_one).eval()
# "res" should be equal to SparseTensor([[0], [1]], [0, 0], [7]).
```
##### Args:
* <b>`sp_a`</b>: a `SparseTensor` operand whose dtype is real, and indices
lexicographically ordered.
* <b>`sp_b`</b>: the other `SparseTensor` operand with the same requirements (and the
same shape).
* <b>`name`</b>: optional name of the operation.
##### Returns:
* <b>`output`</b>: the output SparseTensor.
| HaebinShin/tensorflow | tensorflow/g3doc/api_docs/python/sparse_ops.md | Markdown | apache-2.0 | 40,708 |
/*
* Copyright 2011-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.transform;
import java.lang.reflect.Constructor;
import com.amazonaws.AmazonServiceException;
public abstract class AbstractErrorUnmarshaller<T> implements Unmarshaller<AmazonServiceException, T> {
/**
* The type of AmazonServiceException that will be instantiated. Subclasses
* specialized for a specific type of exception can control this through the
* protected constructor.
*/
protected final Class<? extends AmazonServiceException> exceptionClass;
/**
* Constructs a new error unmarshaller that will unmarshall error responses
* into AmazonServiceException objects.
*/
public AbstractErrorUnmarshaller() {
this(AmazonServiceException.class);
}
/**
* Constructs a new error unmarshaller that will unmarshall error responses
* into objects of the specified class, extending AmazonServiceException.
*
* @param exceptionClass
* The subclass of AmazonServiceException which will be
* instantiated and populated by this class.
*/
public AbstractErrorUnmarshaller(Class<? extends AmazonServiceException> exceptionClass) {
this.exceptionClass = exceptionClass;
}
/**
* Constructs a new exception object of the type specified in this class's
* constructor and sets the specified error message.
*
* @param message
* The error message to set in the new exception object.
*
* @return A new exception object of the type specified in this class's
* constructor and sets the specified error message.
*
* @throws Exception
* If there are any problems using reflection to invoke the
* exception class's constructor.
*/
protected AmazonServiceException newException(String message) throws Exception {
Constructor<? extends AmazonServiceException> constructor = exceptionClass.getConstructor(String.class);
return constructor.newInstance(message);
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/transform/AbstractErrorUnmarshaller.java | Java | apache-2.0 | 2,633 |
package com.icfcc.cache.support;
import com.icfcc.cache.Cache;
import java.util.Collection;
/**
* Simple cache manager working against a given collection of caches.
* Useful for testing or simple caching declarations.
*
* @author Costin Leau
* @since 3.1
*/
public class SimpleCacheManager extends AbstractCacheManager {
private Collection<? extends Cache> caches;
/**
* Specify the collection of Cache instances to use for this CacheManager.
*/
public void setCaches(Collection<? extends Cache> caches) {
this.caches = caches;
}
@Override
protected Collection<? extends Cache> loadCaches() {
return this.caches;
}
} | Gitpiece/spring-cache-project | spring-cache/src/main/java/com/icfcc/cache/support/SimpleCacheManager.java | Java | apache-2.0 | 684 |
---
title: Floating IPs
redirect_from: latest/usage/openstack/floating-ips
canonical_url: 'https://docs.projectcalico.org/v2.6/usage/openstack/floating-ips'
---
networking-calico includes beta support for floating IPs. Currently this
requires running {{site.prodname}} as a Neutron core plugin (i.e. `core_plugin =
calico`) instead of as an ML2 mechanism driver.
> **Note**: We would like it to work as an ML2 mechanism driver too—patches
> and/or advice welcome!
{: .alert .alert-info}
To set up a floating IP, you need the same pattern of Neutron data model
objects as you do for Neutron in general, which means:
- a tenant network, with an instance attached to it, that will be the target of
the floating IP
- a Neutron router, with the tenant network connected to it
- a provider network with `router:external True` that is set as the
router's gateway (e.g. with `neutron router-gateway-set`), and with a
subnet with a CIDR that floating IPs will be allocated from
- a floating IP, allocated from the provider network subnet, that maps onto the
instance attached to the tenant network.
For example:
# Create tenant network and subnet
neutron net-create --shared calico
neutron subnet-create --gateway 10.65.0.1 --enable-dhcp --ip-version 4 --name calico-v4 calico 10.65.0.0/24
# Boot a VM on that network, and find its Neutron port ID.
nova boot [...]
neutron port-list
# Create external network and subnet - this is where floating
# IPs will be allocated from.
neutron net-create public --router:external True
neutron subnet-create public 172.16.1.0/24
# Create a router connecting the tenant and external networks.
neutron router-create router1
neutron router-interface-add router1 <tenant-subnet-id>
neutron router-gateway-set router1 public
# Create a floating IP and associate it with the target VM.
neutron floatingip-create public
neutron floatingip-associate <floatingip-id> <target-VM-port-id>
Then the {{site.prodname}} agents will arrange that the floating IP is routed to the
instance's compute host, and then DNAT'd to the instance's fixed IP address:
core@compute-node01:~$ ip r
default via 10.240.0.1 dev eth0
10.65.0.13 dev tap9a7e0868-da scope link
10.65.0.14 via 192.168.8.4 dev l2tpeth8-3 proto bird
10.65.0.23 via 192.168.8.4 dev l2tpeth8-3 proto bird
10.240.0.1 dev eth0 scope link
172.16.1.3 dev tap9a7e0868-da scope link
192.168.8.0/24 dev l2tpeth8-3 proto kernel scope link src 192.168.8.3
192.168.122.0/24 dev virbr0 proto kernel scope link src 192.168.122.1
core@compute-node01:~$ sudo iptables -L -n -v -t nat
[...]
Chain felix-FIP-DNAT (2 references)
pkts bytes target prot opt in out source destination
0 0 DNAT all -- * * 0.0.0.0/0 172.16.1.3 to:10.65.0.13
Chain felix-FIP-SNAT (1 references)
pkts bytes target prot opt in out source destination
0 0 SNAT all -- * * 10.65.0.13 10.65.0.13 to:172.16.1.3
Chain felix-OUTPUT (1 references)
pkts bytes target prot opt in out source destination
1 60 felix-FIP-DNAT all -- * * 0.0.0.0/0 0.0.0.0/0
Chain felix-POSTROUTING (1 references)
pkts bytes target prot opt in out source destination
1 60 felix-FIP-SNAT all -- * * 0.0.0.0/0 0.0.0.0/0
Chain felix-PREROUTING (1 references)
pkts bytes target prot opt in out source destination
0 0 felix-FIP-DNAT all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 DNAT tcp -- * * 0.0.0.0/0 169.254.169.254 tcp dpt:80 to:127.0.0.1:8775
[...]
| tomdee/calico | v3.2/usage/openstack/floating-ips.md | Markdown | apache-2.0 | 3,931 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2016 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# 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.
'''
This submodule contains helper functions for parsing and printing the
contents of describe hashes for various DNAnexus entities (projects,
containers, dataobjects, apps, and jobs).
'''
from __future__ import print_function, unicode_literals, division, absolute_import
import datetime, time, json, math, sys, copy
import locale
import subprocess
from collections import defaultdict
import dxpy
from .printing import (RED, GREEN, BLUE, YELLOW, WHITE, BOLD, UNDERLINE, ENDC, DELIMITER, get_delimiter, fill)
from ..compat import basestring, USING_PYTHON2
def JOB_STATES(state):
if state == 'failed':
return BOLD() + RED() + state + ENDC()
elif state == 'done':
return BOLD() + GREEN() + state + ENDC()
elif state in ['running', 'in_progress']:
return GREEN() + state + ENDC()
elif state == 'partially_failed':
return RED() + state + ENDC()
else:
return YELLOW() + state + ENDC()
def DATA_STATES(state):
if state == 'open':
return YELLOW() + state + ENDC()
elif state == 'closing':
return YELLOW() + state + ENDC()
elif state == 'closed':
return GREEN() + state + ENDC()
else:
return state
SIZE_LEVEL = ['bytes', 'KB', 'MB', 'GB', 'TB']
def get_size_str(size):
"""
Formats a byte size as a string.
The returned string is no more than 9 characters long.
"""
if size is None:
return "0 " + SIZE_LEVEL[0]
if size == 0:
magnitude = 0
level = 0
else:
magnitude = math.floor(math.log(size, 10))
level = int(min(math.floor(magnitude // 3), 4))
return ('%d' if level == 0 else '%.2f') % (float(size) / 2**(level*10)) + ' ' + SIZE_LEVEL[level]
def parse_typespec(thing):
if isinstance(thing, basestring):
return thing
elif '$and' in thing:
return '(' + ' AND '.join(map(parse_typespec, thing['$and'])) + ')'
elif '$or' in thing:
return '(' + ' OR '.join(map(parse_typespec, thing['$or'])) + ')'
else:
return 'Type spec could not be parsed'
def get_io_desc(parameter, include_class=True, show_opt=True, app_help_version=False):
# For interactive help, format array:CLASS inputs as:
# -iNAME=CLASS [-iNAME=... [...]] # If input is required (needs >=1 inputs)
# [-iNAME=CLASS [...]] # If input is optional (needs >=0 inputs
if app_help_version and parameter["class"].startswith("array"):
scalar_parameter = parameter.copy()
# Munge the parameter dict (strip off "array:" to turn it into a
# scalar) and recurse
scalar_parameter["class"] = scalar_parameter["class"][6:]
if "default" in parameter or parameter.get("optional"):
return "[" + get_io_desc(scalar_parameter, include_class=include_class, show_opt=False, app_help_version=app_help_version) + " [-i%s=... [...]]]" % (parameter["name"],)
else:
return get_io_desc(scalar_parameter, include_class=include_class, show_opt=False, app_help_version=app_help_version) + " [-i%s=... [...]]" % (parameter["name"],)
desc = ""
is_optional = False
if show_opt:
if "default" in parameter or parameter.get("optional"):
is_optional = True
desc += "["
desc += ('-i' if app_help_version else '') + parameter["name"]
include_parens = include_class or 'type' in parameter or 'default' in parameter
if include_parens:
desc += ("=" if app_help_version else " ") + "("
is_first = True
if include_class:
desc += parameter["class"]
is_first = False
if "type" in parameter:
if not is_first:
desc += ", "
else:
is_first = False
desc += "type " + parse_typespec(parameter["type"])
if "default" in parameter:
if not is_first:
desc += ', '
desc += 'default=' + json.dumps(parameter['default'])
if include_parens:
desc += ")"
if show_opt and is_optional:
desc += "]"
return desc
def get_io_spec(spec, skip_fields=None):
if spec is None:
return 'null'
if skip_fields is None:
skip_fields = []
filtered_spec = [param for param in spec if param["name"] not in skip_fields]
groups = defaultdict(list)
for param in filtered_spec:
groups[param.get('group')].append(param)
list_of_params = []
for param in groups.get(None, []):
list_of_params.append(get_io_desc(param))
for group in groups:
if group is None:
continue
list_of_params.append("{g}:".format(g=group))
for param in groups[group]:
list_of_params.append(" "+get_io_desc(param))
if len(skip_fields) > 0:
list_of_params.append("<advanced inputs hidden; use --verbose to see more>")
if len(list_of_params) == 0:
return '-'
if get_delimiter() is not None:
return ('\n' + get_delimiter()).join(list_of_params)
else:
return ('\n' + ' '*16).join([fill(param,
subsequent_indent=' '*18,
width_adjustment=-18) for param in list_of_params])
def is_job_ref(thing, reftype=dict):
'''
:param thing: something that might be a job-based object reference hash
:param reftype: type that a job-based object reference would be (default is dict)
'''
return isinstance(thing, reftype) and \
((len(thing) == 2 and \
isinstance(thing.get('field'), basestring) and \
isinstance(thing.get('job'), basestring)) or \
(len(thing) == 1 and \
isinstance(thing.get('$dnanexus_link'), reftype) and \
isinstance(thing['$dnanexus_link'].get('field'), basestring) and \
isinstance(thing['$dnanexus_link'].get('job'), basestring)))
def get_job_from_jbor(thing):
'''
:returns: Job ID from a JBOR
Assumes :func:`is_job_ref` evaluates to True
'''
if '$dnanexus_link' in thing:
return thing['$dnanexus_link']['job']
else:
return thing['job']
def get_field_from_jbor(thing):
'''
:returns: Output field name from a JBOR
Assumes :func:`is_job_ref` evaluates to True
'''
if '$dnanexus_link' in thing:
return thing['$dnanexus_link']['field']
else:
return thing['field']
def get_index_from_jbor(thing):
'''
:returns: Array index of the JBOR if applicable; None otherwise
Assumes :func:`is_job_ref` evaluates to True
'''
if '$dnanexus_link' in thing:
return thing['$dnanexus_link'].get('index')
else:
return None
def is_metadata_ref(thing, reftype=dict):
return isinstance(thing, reftype) and \
len(thing) == 1 and \
isinstance(thing.get('$dnanexus_link'), reftype) and \
isinstance(thing['$dnanexus_link'].get('metadata'), basestring)
def jbor_to_str(val):
ans = get_job_from_jbor(val) + ':' + get_field_from_jbor(val)
index = get_index_from_jbor(val)
if index is not None:
ans += "." + str(index)
return ans
def io_val_to_str(val):
if is_job_ref(val):
# Job-based object references
return jbor_to_str(val)
elif isinstance(val, dict) and '$dnanexus_link' in val:
# DNAnexus link
if isinstance(val['$dnanexus_link'], basestring):
# simple link
return val['$dnanexus_link']
elif 'project' in val['$dnanexus_link'] and 'id' in val['$dnanexus_link']:
return val['$dnanexus_link']['project'] + ':' + val['$dnanexus_link']['id']
else:
return json.dumps(val)
elif isinstance(val, list):
if len(val) == 0:
return '[]'
else:
return '[ ' + ', '.join([io_val_to_str(item) for item in val]) + ' ]'
elif isinstance(val, dict):
return '{ ' + ', '.join([key + ': ' + io_val_to_str(value) for key, value in val.items()]) + ' }'
else:
return json.dumps(val)
def job_output_to_str(job_output, prefix='\n', title="Output: ", title_len=None):
if len(job_output) == 0:
return prefix + title + "-"
else:
if title_len is None:
title_len = len(title)
return prefix + title + (prefix+' '*title_len).join([fill(key + ' = ' + io_val_to_str(value),
subsequent_indent=' '*9,
break_long_words=False) for key, value in job_output.items()])
def get_io_field(io_hash, defaults=None, delim='=', highlight_fields=()):
def highlight_value(key, value):
if key in highlight_fields:
return YELLOW() + value + ENDC()
else:
return value
if defaults is None:
defaults = {}
if io_hash is None:
return '-'
if len(io_hash) == 0 and len(defaults) == 0:
return '-'
if get_delimiter() is not None:
return ('\n' + get_delimiter()).join([(key + delim + highlight_value(key, io_val_to_str(value))) for key, value in io_hash.items()] +
[('[' + key + delim + io_val_to_str(value) + ']') for key, value in defaults.items()])
else:
lines = [fill(key + ' ' + delim + ' ' + highlight_value(key, io_val_to_str(value)),
initial_indent=' ' * FIELD_NAME_WIDTH,
subsequent_indent=' ' * (FIELD_NAME_WIDTH + 1),
break_long_words=False)
for key, value in io_hash.items()]
lines.extend([fill('[' + key + ' ' + delim + ' ' + io_val_to_str(value) + ']',
initial_indent=' ' * FIELD_NAME_WIDTH,
subsequent_indent=' ' * (FIELD_NAME_WIDTH + 1),
break_long_words=False)
for key, value in defaults.items()])
return '\n'.join(lines)[FIELD_NAME_WIDTH:]
def get_resolved_jbors(resolved_thing, orig_thing, resolved_jbors):
if resolved_thing == orig_thing:
return
if is_job_ref(orig_thing):
jbor_str = jbor_to_str(orig_thing)
if jbor_str not in resolved_jbors:
try:
from dxpy.api import job_describe
job_output = job_describe(get_job_from_jbor(orig_thing)).get('output')
if job_output is not None:
field_value = job_output.get(get_field_from_jbor(orig_thing))
jbor_index = get_index_from_jbor(orig_thing)
if jbor_index is not None:
if isinstance(field_value, list):
resolved_jbors[jbor_str] = field_value[jbor_index]
else:
resolved_jbors[jbor_str] = field_value
except:
# Just don't report any resolved JBORs if there are
# any problems
pass
elif isinstance(orig_thing, list):
for i in range(len(orig_thing)):
get_resolved_jbors(resolved_thing[i], orig_thing[i], resolved_jbors)
elif isinstance(orig_thing, dict) and '$dnanexus_link' not in orig_thing:
for key in orig_thing:
get_resolved_jbors(resolved_thing[key], orig_thing[key], resolved_jbors)
def render_bundleddepends(thing):
from ..bindings.search import find_one_data_object
from ..exceptions import DXError
bundles = []
for item in thing:
bundle_asset_record = dxpy.DXFile(item["id"]["$dnanexus_link"]).get_properties().get("AssetBundle")
asset = None
if bundle_asset_record:
asset = dxpy.DXRecord(bundle_asset_record)
if asset:
try:
bundles.append(asset.describe().get("name") + " (" + asset.get_id() + ")")
except DXError:
asset = None
if not asset:
bundles.append(item["name"] + " (" + item["id"]["$dnanexus_link"] + ")")
return bundles
def render_execdepends(thing):
rendered = []
for item in thing:
dep = copy.copy(item)
dep.setdefault('package_manager', 'apt')
dep['version'] = ' = '+dep['version'] if 'version' in dep else ''
rendered.append("{package_manager}: {name}{version}".format(**dep))
return rendered
def render_stage(title, stage, as_stage_of=None):
lines_to_print = []
if stage['name'] is not None:
lines_to_print.append((title, "{name} ({id})".format(name=stage['name'], id=stage['id'])))
else:
lines_to_print.append((title, stage['id']))
lines_to_print.append((' Executable', stage['executable'] + \
(" (" + RED() + "inaccessible" + ENDC() + ")" \
if stage.get('accessible') is False else "")))
if 'execution' in stage:
is_cached_result = as_stage_of is not None and 'parentAnalysis' in stage['execution'] and \
stage['execution']['parentAnalysis'] != as_stage_of
execution_id_str = stage['execution']['id']
if is_cached_result:
execution_id_str = "[" + execution_id_str + "]"
if 'state' in stage['execution']:
lines_to_print.append((' Execution', execution_id_str + ' (' + JOB_STATES(stage['execution']['state']) + ')'))
else:
lines_to_print.append((' Execution', execution_id_str))
if is_cached_result:
lines_to_print.append((' Cached from', stage['execution']['parentAnalysis']))
for line in lines_to_print:
print_field(line[0], line[1])
def render_short_timestamp(timestamp):
return str(datetime.datetime.fromtimestamp(timestamp//1000))
def render_timestamp(timestamp):
return datetime.datetime.fromtimestamp(timestamp//1000).ctime()
FIELD_NAME_WIDTH = 22
def print_field(label, value):
if get_delimiter() is not None:
sys.stdout.write(label + get_delimiter() + value + '\n')
else:
sys.stdout.write(
label + " " * (FIELD_NAME_WIDTH-len(label)) + fill(value,
subsequent_indent=' '*FIELD_NAME_WIDTH,
width_adjustment=-FIELD_NAME_WIDTH) +
'\n')
def print_nofill_field(label, value):
sys.stdout.write(label + DELIMITER(" " * (FIELD_NAME_WIDTH - len(label))) + value + '\n')
def print_list_field(label, values):
print_field(label, ('-' if len(values) == 0 else DELIMITER(', ').join(values)))
def print_json_field(label, json_value):
print_field(label, json.dumps(json_value, ensure_ascii=False))
def print_project_desc(desc, verbose=False):
recognized_fields = [
'id', 'class', 'name', 'summary', 'description', 'protected', 'restricted', 'created', 'modified',
'dataUsage', 'sponsoredDataUsage', 'tags', 'level', 'folders', 'objects', 'permissions', 'properties',
'appCaches', 'billTo', 'version', 'createdBy', 'totalSponsoredEgressBytes', 'consumedSponsoredEgressBytes',
'containsPHI', 'databaseUIViewOnly', 'region', 'storageCost', 'pendingTransfer','atSpendingLimit',
# Following are app container-specific
'destroyAt', 'project', 'type', 'app', 'appName'
]
# Basic metadata
print_field("ID", desc["id"])
print_field("Class", desc["class"])
if "name" in desc:
print_field("Name", desc["name"])
if 'summary' in desc:
print_field("Summary", desc["summary"])
if 'description' in desc and (verbose or 'summary' not in desc):
print_field("Description", desc['description'])
if 'version' in desc and verbose:
print_field("Version", str(desc['version']))
# Ownership and permissions
if 'billTo' in desc:
print_field("Billed to", desc['billTo'][5 if desc['billTo'].startswith('user-') else 0:])
if 'pendingTransfer' in desc and (verbose or desc['pendingTransfer'] is not None):
print_json_field('Pending transfer to', desc['pendingTransfer'])
if "level" in desc:
print_field("Access level", desc["level"])
if 'region' in desc:
print_field('Region', desc['region'])
# Project settings
if 'protected' in desc:
print_json_field("Protected", desc["protected"])
if 'restricted' in desc:
print_json_field("Restricted", desc["restricted"])
if 'containsPHI' in desc:
print_json_field('Contains PHI', desc['containsPHI'])
if 'databaseUIViewOnly' in desc and desc['databaseUIViewOnly']:
print_json_field('Database UI View Only', desc['databaseUIViewOnly'])
# Usage
print_field("Created", render_timestamp(desc['created']))
if 'createdBy' in desc:
print_field("Created by", desc['createdBy']['user'][desc['createdBy']['user'].find('-') + 1:])
print_field("Last modified", render_timestamp(desc['modified']))
print_field("Data usage", ('%.2f' % desc["dataUsage"]) + ' GB')
if 'sponsoredDataUsage' in desc:
print_field("Sponsored data", ('%.2f' % desc["sponsoredDataUsage"]) + ' GB')
if 'storageCost' in desc:
print_field("Storage cost", "$%.3f/month" % desc["storageCost"])
if 'totalSponsoredEgressBytes' in desc or 'consumedSponsoredEgressBytes' in desc:
total_egress_str = '%.2f GB' % (desc['totalSponsoredEgressBytes'] / 1073741824.,) \
if 'totalSponsoredEgressBytes' in desc else '??'
consumed_egress_str = '%.2f GB' % (desc['consumedSponsoredEgressBytes'] / 1073741824.,) \
if 'consumedSponsoredEgressBytes' in desc else '??'
print_field('Sponsored egress',
('%s used of %s total' % (consumed_egress_str, total_egress_str)))
if 'atSpendingLimit' in desc:
print_json_field("At spending limit?", desc['atSpendingLimit'])
# Misc metadata
if "objects" in desc:
print_field("# Files", str(desc["objects"]))
if "folders" in desc:
print_list_field("Folders", desc["folders"])
if "permissions" in desc:
print_list_field(
"Permissions",
[key[5 if key.startswith('user-') else 0:] + ':' + value for key, value in desc["permissions"].items()]
)
if 'tags' in desc:
print_list_field("Tags", desc["tags"])
if "properties" in desc:
print_list_field("Properties", [key + '=' + value for key, value in desc["properties"].items()])
if "appCaches" in desc:
print_json_field("App caches", desc["appCaches"])
# Container-specific
if 'type' in desc:
print_field("Container type", desc["type"])
if 'project' in desc:
print_field("Associated project", desc["project"])
if 'destroyAt' in desc:
print_field("To be destroyed", render_timestamp(desc['modified']))
if 'app' in desc:
print_field("Associated App ID", desc["app"])
if 'appName' in desc:
print_field("Associated App", desc["appName"])
for field in desc:
if field not in recognized_fields:
print_json_field(field, desc[field])
def get_advanced_inputs(desc, verbose):
details = desc.get("details")
if not verbose and isinstance(details, dict):
return details.get("advancedInputs", [])
return []
def print_app_desc(desc, verbose=False):
recognized_fields = ['id', 'class', 'name', 'version', 'aliases', 'createdBy', 'created', 'modified', 'deleted', 'published', 'title', 'subtitle', 'description', 'categories', 'access', 'dxapi', 'inputSpec', 'outputSpec', 'runSpec', 'resources', 'billTo', 'installed', 'openSource', 'summary', 'applet', 'installs', 'billing', 'details', 'developerNotes',
'authorizedUsers']
print_field("ID", desc["id"])
print_field("Class", desc["class"])
if 'billTo' in desc:
print_field("Billed to", desc['billTo'][5 if desc['billTo'].startswith('user-') else 0:])
print_field("Name", desc["name"])
print_field("Version", desc["version"])
print_list_field("Aliases", desc["aliases"])
print_field("Created by", desc["createdBy"][5 if desc['createdBy'].startswith('user-') else 0:])
print_field("Created", render_timestamp(desc['created']))
print_field("Last modified", render_timestamp(desc['modified']))
print_field("Created from", desc["applet"])
print_json_field('Installed', desc['installed'])
print_json_field('Open source', desc['openSource'])
print_json_field('Deleted', desc['deleted'])
if not desc['deleted']:
advanced_inputs = []
details = desc["details"]
if isinstance(details, dict) and "advancedInputs" in details:
if not verbose:
advanced_inputs = details["advancedInputs"]
del details["advancedInputs"]
if 'published' not in desc or desc["published"] < 0:
print_field("Published", "-")
else:
print_field("Published", render_timestamp(desc['published']))
if "title" in desc and desc['title'] is not None:
print_field("Title", desc["title"])
if "subtitle" in desc and desc['subtitle'] is not None:
print_field("Subtitle", desc["subtitle"])
if 'summary' in desc and desc['summary'] is not None:
print_field("Summary", desc['summary'])
print_list_field("Categories", desc["categories"])
if 'details' in desc:
print_json_field("Details", desc["details"])
print_json_field("Access", desc["access"])
print_field("API version", desc["dxapi"])
if 'inputSpec' in desc:
print_nofill_field("Input Spec", get_io_spec(desc["inputSpec"], skip_fields=advanced_inputs))
print_nofill_field("Output Spec", get_io_spec(desc["outputSpec"]))
print_field("Interpreter", desc["runSpec"]["interpreter"])
if "resources" in desc["runSpec"]:
print_json_field("Resources", desc["runSpec"]["resources"])
if "bundledDepends" in desc["runSpec"]:
print_list_field("bundledDepends", render_bundleddepends(desc["runSpec"]["bundledDepends"]))
if "execDepends" in desc["runSpec"]:
print_list_field("execDepends", render_execdepends(desc["runSpec"]["execDepends"]))
if "systemRequirements" in desc['runSpec']:
print_json_field('Sys Requirements', desc['runSpec']['systemRequirements'])
if 'resources' in desc:
print_field("Resources", desc['resources'])
if 'installs' in desc:
print_field('# Installs', str(desc['installs']))
if 'authorizedUsers' in desc:
print_list_field('AuthorizedUsers', desc["authorizedUsers"])
for field in desc:
if field not in recognized_fields:
print_json_field(field, desc[field])
def print_globalworkflow_desc(desc, verbose=False):
recognized_fields = ['id', 'class', 'name', 'version', 'aliases', 'createdBy', 'created',
'modified', 'deleted', 'published', 'title', 'description',
'categories', 'dxapi', 'billTo', 'summary', 'billing', 'developerNotes',
'authorizedUsers', 'regionalOptions']
is_locked_workflow = False
print_field("ID", desc["id"])
print_field("Class", desc["class"])
if 'billTo' in desc:
print_field("Billed to", desc['billTo'][5 if desc['billTo'].startswith('user-') else 0:])
print_field("Name", desc["name"])
print_field("Version", desc["version"])
print_list_field("Aliases", desc["aliases"])
print_field("Created by", desc["createdBy"][5 if desc['createdBy'].startswith('user-') else 0:])
print_field("Created", render_timestamp(desc['created']))
print_field("Last modified", render_timestamp(desc['modified']))
# print_json_field('Open source', desc['openSource'])
print_json_field('Deleted', desc.get('deleted', False))
if not desc.get('deleted', False):
if 'published' not in desc or desc["published"] < 0:
print_field("Published", "-")
else:
print_field("Published", render_timestamp(desc['published']))
if "title" in desc and desc['title'] is not None:
print_field("Title", desc["title"])
if "subtitle" in desc and desc['subtitle'] is not None:
print_field("Subtitle", desc["subtitle"])
if 'summary' in desc and desc['summary'] is not None:
print_field("Summary", desc['summary'])
print_list_field("Categories", desc["categories"])
if 'details' in desc:
print_json_field("Details", desc["details"])
print_field("API version", desc["dxapi"])
# Additionally, print inputs, outputs, stages of the underlying workflow
# from the region of the current workspace
current_project = dxpy.WORKSPACE_ID
if current_project:
region = dxpy.api.project_describe(current_project, input_params={"fields": {"region": True}})["region"]
if region and region in desc['regionalOptions']:
workflow_desc = desc['regionalOptions'][region]['workflowDescribe']
print_field("Workflow region", region)
if 'id' in workflow_desc:
print_field("Workflow ID", workflow_desc['id'])
if workflow_desc.get('inputSpec') is not None and workflow_desc.get('inputs') is None:
print_nofill_field("Input Spec", get_io_spec(workflow_desc['inputSpec'], skip_fields=get_advanced_inputs(workflow_desc, verbose)))
if workflow_desc.get('outputSpec') is not None and workflow_desc.get('outputs') is None:
print_nofill_field("Output Spec", get_io_spec(workflow_desc['outputSpec']))
if workflow_desc.get('inputs') is not None:
is_locked_workflow = True
print_nofill_field("Workflow Inputs", get_io_spec(workflow_desc['inputs']))
if workflow_desc.get('outputs') is not None:
print_nofill_field("Workflow Outputs", get_io_spec(workflow_desc['outputs']))
if 'stages' in workflow_desc:
for i, stage in enumerate(workflow_desc["stages"]):
render_stage("Stage " + str(i), stage)
if 'authorizedUsers' in desc:
print_list_field('AuthorizedUsers', desc["authorizedUsers"])
if is_locked_workflow:
print_locked_workflow_note()
for field in desc:
if field not in recognized_fields:
print_json_field(field, desc[field])
def get_col_str(col_desc):
return col_desc['name'] + DELIMITER(" (") + col_desc['type'] + DELIMITER(")")
def print_data_obj_desc(desc, verbose=False):
recognized_fields = ['id', 'class', 'project', 'folder', 'name', 'properties', 'tags', 'types', 'hidden', 'details', 'links', 'created', 'modified', 'state', 'title', 'subtitle', 'description', 'inputSpec', 'outputSpec', 'runSpec', 'summary', 'dxapi', 'access', 'createdBy', 'summary', 'sponsored', 'developerNotes',
'stages', 'inputs', 'outputs', 'latestAnalysis', 'editVersion', 'outputFolder', 'initializedFrom', 'temporary']
is_locked_workflow = False
print_field("ID", desc["id"])
print_field("Class", desc["class"])
if 'project' in desc:
print_field("Project", desc['project'])
if 'folder' in desc:
print_field("Folder", desc["folder"])
print_field("Name", desc["name"])
if 'state' in desc:
print_field("State", DATA_STATES(desc['state']))
if 'hidden' in desc:
print_field("Visibility", ("hidden" if desc["hidden"] else "visible"))
if 'types' in desc:
print_list_field("Types", desc['types'])
if 'properties' in desc:
print_list_field("Properties", ['='.join([k, v]) for k, v in desc['properties'].items()])
if 'tags' in desc:
print_list_field("Tags", desc['tags'])
if verbose and 'details' in desc:
print_json_field("Details", desc["details"])
if 'links' in desc:
print_list_field("Outgoing links", desc['links'])
print_field("Created", render_timestamp(desc['created']))
if 'createdBy' in desc:
print_field("Created by", desc['createdBy']['user'][5:])
if 'job' in desc["createdBy"]:
print_field(" via the job", desc['createdBy']['job'])
if verbose and 'executable' in desc['createdBy']:
print_field(" running", desc['createdBy']['executable'])
print_field("Last modified", render_timestamp(desc['modified']))
if "editVersion" in desc:
print_field("Edit Version", str(desc['editVersion']))
if "title" in desc:
print_field("Title", desc["title"])
if "subtitle" in desc:
print_field("Subtitle", desc["subtitle"])
if 'summary' in desc:
print_field("Summary", desc['summary'])
if 'description' in desc and verbose:
print_field("Description", desc["description"])
if 'outputFolder' in desc:
print_field("Output Folder", desc["outputFolder"] if desc["outputFolder"] is not None else "-")
if 'access' in desc:
print_json_field("Access", desc["access"])
if 'dxapi' in desc:
print_field("API version", desc["dxapi"])
# In case of a workflow: do not display "Input/Output Specs" that show stages IO
# when the workflow has workflow-level input/output fields defined.
if desc.get('inputSpec') is not None and desc.get('inputs') is None:
print_nofill_field("Input Spec", get_io_spec(desc['inputSpec'], skip_fields=get_advanced_inputs(desc, verbose)))
if desc.get('outputSpec') is not None and desc.get('outputs') is None:
print_nofill_field("Output Spec", get_io_spec(desc['outputSpec']))
if desc.get('inputs') is not None:
is_locked_workflow = True
print_nofill_field("Workflow Inputs", get_io_spec(desc['inputs']))
if desc.get('outputs') is not None:
print_nofill_field("Workflow Outputs", get_io_spec(desc['outputs']))
if 'runSpec' in desc:
print_field("Interpreter", desc["runSpec"]["interpreter"])
if "resources" in desc['runSpec']:
print_json_field("Resources", desc["runSpec"]["resources"])
if "bundledDepends" in desc["runSpec"]:
print_list_field("bundledDepends", render_bundleddepends(desc["runSpec"]["bundledDepends"]))
if "execDepends" in desc["runSpec"]:
print_list_field("execDepends", render_execdepends(desc["runSpec"]["execDepends"]))
if "systemRequirements" in desc['runSpec']:
print_json_field('Sys Requirements', desc['runSpec']['systemRequirements'])
if 'stages' in desc:
for i, stage in enumerate(desc["stages"]):
render_stage("Stage " + str(i), stage)
if 'initializedFrom' in desc:
print_field("initializedFrom", desc["initializedFrom"]["id"])
if 'latestAnalysis' in desc and desc['latestAnalysis'] is not None:
print_field("Last execution", desc["latestAnalysis"]["id"])
print_field(" run at", render_timestamp(desc["latestAnalysis"]["created"]))
print_field(" state", JOB_STATES(desc["latestAnalysis"]["state"]))
for field in desc:
if field in recognized_fields:
continue
else:
if field == "media":
print_field("Media type", desc['media'])
elif field == "size":
if desc["class"] == "file":
sponsored_str = ""
if 'sponsored' in desc and desc['sponsored']:
sponsored_str = DELIMITER(", ") + "sponsored by DNAnexus"
print_field("Size", get_size_str(desc['size']) + sponsored_str)
else:
print_field("Size", str(desc['size']))
elif field == "length":
print_field("Length", str(desc['length']))
elif field == "columns":
if len(desc['columns']) > 0:
coldescs = "Columns" + DELIMITER(" " *(16-len("Columns"))) + get_col_str(desc["columns"][0])
for column in desc["columns"][1:]:
coldescs += '\n' + DELIMITER(" "*16) + get_col_str(column)
print(coldescs)
else:
print_list_field("Columns", desc['columns'])
else: # Unhandled prettifying
print_json_field(field, desc[field])
if is_locked_workflow:
print_locked_workflow_note()
def printable_ssh_host_key(ssh_host_key):
try:
keygen = subprocess.Popen(["ssh-keygen", "-lf", "/dev/stdin"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
if USING_PYTHON2:
(stdout, stderr) = keygen.communicate(ssh_host_key)
else:
(stdout, stderr) = keygen.communicate(ssh_host_key.encode())
except:
return ssh_host_key.strip()
else:
if not USING_PYTHON2:
stdout = stdout.decode()
return stdout.replace(" no comment", "").strip()
def print_execution_desc(desc):
recognized_fields = ['id', 'class', 'project', 'workspace', 'region',
'app', 'applet', 'executable', 'workflow',
'state',
'rootExecution', 'parentAnalysis', 'parentJob', 'originJob', 'analysis', 'stage',
'function', 'runInput', 'originalInput', 'input', 'output', 'folder', 'launchedBy', 'created',
'modified', 'failureReason', 'failureMessage', 'stdout', 'stderr', 'waitingOnChildren',
'dependsOn', 'resources', 'projectCache', 'details', 'tags', 'properties',
'name', 'instanceType', 'systemRequirements', 'executableName', 'failureFrom', 'billTo',
'startedRunning', 'stoppedRunning', 'stateTransitions',
'delayWorkspaceDestruction', 'stages', 'totalPrice', 'isFree', 'invoiceMetadata',
'priority', 'sshHostKey']
print_field("ID", desc["id"])
print_field("Class", desc["class"])
if "name" in desc and desc['name'] is not None:
print_field("Job name", desc['name'])
if "executableName" in desc and desc['executableName'] is not None:
print_field("Executable name", desc['executableName'])
print_field("Project context", desc["project"])
if 'region' in desc:
print_field("Region", desc["region"])
if 'billTo' in desc:
print_field("Billed to", desc['billTo'][5 if desc['billTo'].startswith('user-') else 0:])
if 'workspace' in desc:
print_field("Workspace", desc["workspace"])
if 'projectCache' in desc:
print_field('Cache workspace', desc['projectCache'])
print_field('Resources', desc['resources'])
if "app" in desc:
print_field("App", desc["app"])
elif desc.get("executable", "").startswith("globalworkflow"):
print_field("Workflow", desc["executable"])
elif "applet" in desc:
print_field("Applet", desc["applet"])
elif "workflow" in desc:
print_field("Workflow", desc["workflow"]["id"])
if "instanceType" in desc and desc['instanceType'] is not None:
print_field("Instance Type", desc["instanceType"])
if "priority" in desc:
print_field("Priority", desc["priority"])
print_field("State", JOB_STATES(desc["state"]))
if "rootExecution" in desc:
print_field("Root execution", desc["rootExecution"])
if "originJob" in desc:
if desc["originJob"] is None:
print_field("Origin job", "-")
else:
print_field("Origin job", desc["originJob"])
if desc["parentJob"] is None:
print_field("Parent job", "-")
else:
print_field("Parent job", desc["parentJob"])
if "parentAnalysis" in desc:
if desc["parentAnalysis"] is not None:
print_field("Parent analysis", desc["parentAnalysis"])
if "analysis" in desc and desc["analysis"] is not None:
print_field("Analysis", desc["analysis"])
print_field("Stage", desc["stage"])
if "stages" in desc:
for i, (stage, analysis_stage) in enumerate(zip(desc["workflow"]["stages"], desc["stages"])):
stage['execution'] = analysis_stage['execution']
render_stage("Stage " + str(i), stage, as_stage_of=desc["id"])
if "function" in desc:
print_field("Function", desc["function"])
if 'runInput' in desc:
default_fields = {k: v for k, v in desc["originalInput"].items() if k not in desc["runInput"]}
print_nofill_field("Input", get_io_field(desc["runInput"], defaults=default_fields))
else:
print_nofill_field("Input", get_io_field(desc["originalInput"]))
resolved_jbors = {}
input_with_jbors = desc.get('runInput', desc['originalInput'])
for k in desc["input"]:
if k in input_with_jbors and desc["input"][k] != input_with_jbors[k]:
get_resolved_jbors(desc["input"][k], input_with_jbors[k], resolved_jbors)
if len(resolved_jbors) != 0:
print_nofill_field("Resolved JBORs", get_io_field(resolved_jbors, delim=(GREEN() + '=>' + ENDC())))
print_nofill_field("Output", get_io_field(desc["output"]))
if 'folder' in desc:
print_field('Output folder', desc['folder'])
print_field("Launched by", desc["launchedBy"][5:])
print_field("Created", render_timestamp(desc['created']))
if 'startedRunning' in desc:
if 'stoppedRunning' in desc:
print_field("Started running", render_timestamp(desc['startedRunning']))
else:
print_field("Started running", "{t} (running for {rt})".format(t=render_timestamp(desc['startedRunning']),
rt=datetime.timedelta(seconds=int(time.time())-desc['startedRunning']//1000)))
if 'stoppedRunning' in desc:
print_field("Stopped running", "{t} (Runtime: {rt})".format(
t=render_timestamp(desc['stoppedRunning']),
rt=datetime.timedelta(seconds=(desc['stoppedRunning']-desc['startedRunning'])//1000)))
if desc.get('class') == 'analysis' and 'stateTransitions' in desc and desc['stateTransitions']:
# Display finishing time of the analysis if available
if desc['stateTransitions'][-1]['newState'] in ['done', 'failed', 'terminated']:
print_field("Finished", "{t} (Wall-clock time: {wt})".format(
t=render_timestamp(desc['stateTransitions'][-1]['setAt']),
wt=datetime.timedelta(seconds=(desc['stateTransitions'][-1]['setAt']-desc['created'])//1000)))
print_field("Last modified", render_timestamp(desc['modified']))
if 'waitingOnChildren' in desc:
print_list_field('Pending subjobs', desc['waitingOnChildren'])
if 'dependsOn' in desc:
print_list_field('Depends on', desc['dependsOn'])
if "failureReason" in desc:
print_field("Failure reason", desc["failureReason"])
if "failureMessage" in desc:
print_field("Failure message", desc["failureMessage"])
if "failureFrom" in desc and desc['failureFrom'] is not None and desc['failureFrom']['id'] != desc['id']:
print_field("Failure is from", desc['failureFrom']['id'])
if 'systemRequirements' in desc:
print_json_field("Sys Requirements", desc['systemRequirements'])
if "tags" in desc:
print_list_field("Tags", desc["tags"])
if "properties" in desc:
print_list_field("Properties", [key + '=' + value for key, value in desc["properties"].items()])
if "details" in desc and "clonedFrom" in desc["details"]:
cloned_hash = desc["details"]["clonedFrom"]
if "id" in cloned_hash:
print_field("Re-run of", cloned_hash["id"])
print_field(" named", cloned_hash["name"])
same_executable = cloned_hash["executable"] == desc.get("applet", desc.get("app", ""))
print_field(" using", ("" if same_executable else YELLOW()) + \
cloned_hash["executable"] + \
(" (same)" if same_executable else ENDC()))
same_project = cloned_hash["project"] == desc["project"]
same_folder = cloned_hash["folder"] == desc["folder"] or not same_project
print_field(" output folder", ("" if same_project else YELLOW()) + \
cloned_hash["project"] + \
("" if same_project else ENDC()) + ":" + \
("" if same_folder else YELLOW()) + \
cloned_hash["folder"] + \
(" (same)" if (same_project and same_folder) else "" if same_folder else ENDC()))
different_inputs = []
for item in cloned_hash["runInput"]:
if cloned_hash["runInput"][item] != desc["runInput"][item]:
different_inputs.append(item)
print_nofill_field(" input", get_io_field(cloned_hash["runInput"], highlight_fields=different_inputs))
cloned_sys_reqs = cloned_hash.get("systemRequirements")
if isinstance(cloned_sys_reqs, dict):
if cloned_sys_reqs == desc.get('systemRequirements'):
print_nofill_field(" sys reqs", json.dumps(cloned_sys_reqs) + ' (same)')
else:
print_nofill_field(" sys reqs", YELLOW() + json.dumps(cloned_sys_reqs) + ENDC())
if not desc.get('isFree') and desc.get('totalPrice') is not None:
print_field('Total Price', format_currency(desc['totalPrice'], meta=desc['currency']))
if desc.get('invoiceMetadata'):
print_json_field("Invoice Metadata", desc['invoiceMetadata'])
if desc.get('sshHostKey'):
print_nofill_field("SSH Host Key", printable_ssh_host_key(desc['sshHostKey']))
for field in desc:
if field not in recognized_fields:
print_json_field(field, desc[field])
def locale_from_currency_code(dx_code):
"""
This is a (temporary) hardcoded mapping between currency_list.json in nucleus and standard
locale string useful for further formatting
:param dx_code: An id of nucleus/commons/pricing_models/currency_list.json collection
:return: standardised locale, eg 'en_US'; None when no mapping found
"""
currency_locale_map = {0: 'en_US', 1: 'en_GB'}
return currency_locale_map[dx_code] if dx_code in currency_locale_map else None
def format_currency_from_meta(value, meta):
"""
Formats currency value into properly decorated currency string based on provided currency metadata.
Please note that this is very basic solution missing some of the localisation features (such as
negative symbol position and type.
Better option is to use 'locale' module to reflect currency string decorations more accurately.
See 'format_currency'
:param value:
:param meta:
:return:
"""
prefix = '-' if value < 0 else '' # .. TODO: some locales position neg symbol elsewhere, missing meta
prefix += meta['symbol'] if meta['symbolPosition'] == 'left' else ''
suffix = ' %s' % meta["symbol"] if meta['symbolPosition'] == 'right' else ''
# .. TODO: take the group and decimal separators from meta into account (US & UK are the same, so far we're safe)
formatted_value = '{:,.2f}'.format(abs(value))
return prefix + formatted_value + suffix
def format_currency(value, meta, currency_locale=None):
"""
Formats currency value into properly decorated currency string based on either locale (preferred)
or if that is not available then currency metadata. Until locale is provided from the server
a crude mapping between `currency.dxCode` and a locale string is used instead (eg 0: 'en_US')
:param value: amount
:param meta: server metadata (`currency`)
:return: formatted currency string
"""
try:
if currency_locale is None:
currency_locale = locale_from_currency_code(meta['dxCode'])
if currency_locale is None:
return format_currency_from_meta(value, meta)
else:
locale.setlocale(locale.LC_ALL, currency_locale)
return locale.currency(value, grouping=True)
except locale.Error:
# .. locale is probably not available -> fallback to format manually
return format_currency_from_meta(value, meta)
def print_user_desc(desc):
print_field("ID", desc["id"])
print_field("Name", desc["first"] + " " + ((desc["middle"] + " ") if desc["middle"] != '' else '') + desc["last"])
if "email" in desc:
print_field("Email", desc["email"])
bill_to_label = "Default bill to"
if "billTo" in desc:
print_field(bill_to_label, desc["billTo"])
if "appsInstalled" in desc:
print_list_field("Apps installed", desc["appsInstalled"])
def print_generic_desc(desc):
for field in desc:
print_json_field(field, desc[field])
def print_desc(desc, verbose=False):
'''
:param desc: The describe hash of a DNAnexus entity
:type desc: dict
Depending on the class of the entity, this method will print a
formatted and human-readable string containing the data in *desc*.
'''
if desc['class'] in ['project', 'workspace', 'container']:
print_project_desc(desc, verbose=verbose)
elif desc['class'] == 'app':
print_app_desc(desc, verbose=verbose)
elif desc['class'] == 'globalworkflow':
print_globalworkflow_desc(desc, verbose=verbose)
elif desc['class'] in ['job', 'analysis']:
print_execution_desc(desc)
elif desc['class'] == 'user':
print_user_desc(desc)
elif desc['class'] in ['org', 'team']:
print_generic_desc(desc)
else:
print_data_obj_desc(desc, verbose=verbose)
def get_ls_desc(desc, print_id=False):
addendum = ' : ' + desc['id'] if print_id is True else ''
if desc['class'] in ['applet', 'workflow']:
return BOLD() + GREEN() + desc['name'] + ENDC() + addendum
else:
return desc['name'] + addendum
def print_ls_desc(desc, **kwargs):
print(get_ls_desc(desc, **kwargs))
def get_ls_l_header():
return (BOLD() +
'State' + DELIMITER(' ') +
'Last modified' + DELIMITER(' ') +
'Size' + DELIMITER(' ') +
'Name' + DELIMITER(' (') +
'ID' + DELIMITER(')') +
ENDC())
def print_ls_l_header():
print(get_ls_l_header())
def get_ls_l_desc_fields():
return {
'id': True,
'class': True,
'folder': True,
'length': True,
'modified': True,
'name': True,
'project': True,
'size': True,
'state': True
}
def get_ls_l_desc(desc, include_folder=False, include_project=False):
"""
desc must have at least all the fields given by get_ls_l_desc_fields.
"""
# If you make this method consume an additional field, you must add it to
# get_ls_l_desc_fields above.
if 'state' in desc:
state_len = len(desc['state'])
if desc['state'] != 'closed':
state_str = YELLOW() + desc['state'] + ENDC()
else:
state_str = GREEN() + desc['state'] + ENDC()
else:
state_str = ''
state_len = 0
name_str = ''
if include_folder:
name_str += desc['folder'] + ('/' if desc['folder'] != '/' else '')
name_str += desc['name']
if desc['class'] in ['applet', 'workflow']:
name_str = BOLD() + GREEN() + name_str + ENDC()
size_str = ''
if 'size' in desc and desc['class'] == 'file':
size_str = get_size_str(desc['size'])
elif 'length' in desc:
size_str = str(desc['length']) + ' rows'
size_padding = ' ' * max(0, 9 - len(size_str))
return (state_str +
DELIMITER(' '*(8 - state_len)) + render_short_timestamp(desc['modified']) +
DELIMITER(' ') + size_str +
DELIMITER(size_padding + ' ') + name_str +
DELIMITER(' (') + ((desc['project'] + DELIMITER(':')) if include_project else '') + desc['id'] +
DELIMITER(')'))
def print_ls_l_desc(desc, **kwargs):
print(get_ls_l_desc(desc, **kwargs))
def get_find_executions_string(desc, has_children, single_result=False, show_outputs=True,
is_cached_result=False):
'''
:param desc: hash of execution's describe output
:param has_children: whether the execution has children to be printed
:param single_result: whether the execution is displayed as a single result or as part of an execution tree
:param is_cached_result: whether the execution should be formatted as a cached result
'''
is_not_subjob = desc['parentJob'] is None or desc['class'] == 'analysis' or single_result
result = ("* " if is_not_subjob and get_delimiter() is None else "")
canonical_execution_name = desc['executableName']
if desc['class'] == 'job':
canonical_execution_name += ":" + desc['function']
execution_name = desc.get('name', '<no name>')
# Format the name of the execution
if is_cached_result:
result += BOLD() + "[" + ENDC()
result += BOLD() + BLUE()
if desc['class'] == 'analysis':
result += UNDERLINE()
result += execution_name + ENDC()
if execution_name != canonical_execution_name and execution_name+":main" != canonical_execution_name:
result += ' (' + canonical_execution_name + ')'
if is_cached_result:
result += BOLD() + "]" + ENDC()
# Format state
result += DELIMITER(' (') + JOB_STATES(desc['state']) + DELIMITER(') ') + desc['id']
# Add unicode pipe to child if necessary
result += DELIMITER('\n' + (u'│ ' if is_not_subjob and has_children else (" " if is_not_subjob else "")))
result += desc['launchedBy'][5:] + DELIMITER(' ')
result += render_short_timestamp(desc['created'])
cached_and_runtime_strs = []
if is_cached_result:
cached_and_runtime_strs.append(YELLOW() + "cached" + ENDC())
if desc['class'] == 'job':
# Only print runtime if it ever started running
if desc.get('startedRunning'):
if desc['state'] in ['done', 'failed', 'terminated', 'waiting_on_output']:
runtime = datetime.timedelta(seconds=int(desc['stoppedRunning']-desc['startedRunning'])//1000)
cached_and_runtime_strs.append("runtime " + str(runtime))
elif desc['state'] == 'running':
seconds_running = max(int(time.time()-desc['startedRunning']//1000), 0)
msg = "running for {rt}".format(rt=datetime.timedelta(seconds=seconds_running))
cached_and_runtime_strs.append(msg)
if cached_and_runtime_strs:
result += " (" + ", ".join(cached_and_runtime_strs) + ")"
if show_outputs:
prefix = DELIMITER('\n' + (u'│ ' if is_not_subjob and has_children else (" " if is_not_subjob else "")))
if desc.get("output") != None:
result += job_output_to_str(desc['output'], prefix=prefix)
elif desc['state'] == 'failed' and 'failureReason' in desc:
result += prefix + BOLD() + desc['failureReason'] + ENDC() + ": " + fill(desc.get('failureMessage', ''),
subsequent_indent=prefix.lstrip('\n'))
return result
def print_locked_workflow_note():
print_field('Note',
'This workflow has an explicit input specification (i.e. it is locked), and as such stage inputs cannot be modified at run-time.')
| dnanexus/dx-toolkit | src/python/dxpy/utils/describe.py | Python | apache-2.0 | 52,416 |
package fr.fablabmars.model;
import java.util.ArrayList;
import fr.fablabmars.observer.Observable;
import fr.fablabmars.observer.Observer;
/**
* Observable contenant le menu courant.
*
* @author Guillaume Perouffe
* @see Observable
*/
public class CardMenu implements Observable {
/**
* Liste des observateurs de cet observable.
*/
private ArrayList<Observer> listObserver = new ArrayList<Observer>();
/**
* Indice du menu courant
*/
private int panel;
/**
* Constructeur de l'observable
* <p>
* On initialise le menu sur le 'panel' par défaut,
* d'indice 0.
* </p>
*
* @see CardMenu#panel
*/
public CardMenu(){
panel = 0;
}
/**
* Change le panneau courant et notifie les observateurs.
*
* @param panel
* Indice du nouveau menu.
*
* @see CardMenu#panel
* @see Observable#notifyObservers()
*/
public void setPanel(int panel){
this.panel = panel;
notifyObservers();
}
@Override
public void addObserver(Observer obs) {
listObserver.add(obs);
}
@Override
public void removeObserver(Observer obs) {
listObserver.remove(obs);
}
@Override
public void notifyObservers() {
for(Observer obs:listObserver){
obs.update(this);
}
}
/**
* Retourne le menu courant
*
* @return Menu courant
*
* @see CardMenu#panel
*/
@Override
public int getState(){
return panel;
}
}
| gperouffe/FabLabUsers | src/fr/fablabmars/model/CardMenu.java | Java | apache-2.0 | 1,473 |
package ru.job4j.collections.tree;
/**
* Бинарное дерево .
*
* @author Hincu Andrei ([email protected]) by 20.10.17;
* @version $Id$
* @since 0.1
* @param <E> тип данных.
*/
public class BinaryTree<E extends Comparable<E>> extends Tree<E> {
/**
* Корень дерева.
*/
private Node<E> node;
/**
* Размер дерева.
*/
private int size;
/**
* Узел дерева.
* @param <E> значение.
*/
private class Node<E> {
/**
* Значение.
*/
private E value;
/**
* левый сын.
*/
private Node<E> left;
/**
* правый сын.
*/
private Node<E> right;
/**
* Конструктор.
* @param value значение узла.
*/
private Node(E value) {
this.value = value;
}
}
/**
* Добавляем новый элемент или корень дерева.
* @param e значение.
*/
public void add(E e) {
if (node == null) {
node = new Node<>(e);
size++;
} else {
addNewElement(e, node);
}
}
/**
* Метод для поиска места вставки.
* @param e значение.
* @param n текуший узел дерева.
*/
private void addNewElement(E e, Node<E> n) {
if (e.compareTo(n.value) < 0) {
if (n.left == null) {
n.left = new Node<>(e);
size++;
} else {
addNewElement(e, n.left);
}
} else if (e.compareTo(n.value) > 0) {
if (n.right == null) {
n.right = new Node<>(e);
size++;
} else {
addNewElement(e, n.right);
}
}
}
/**
* геттер.
* @return размер дерева.
*/
public int getSize() {
return size;
}
}
| andreiHi/hincuA | chapter_005/src/main/java/ru/job4j/collections/tree/BinaryTree.java | Java | apache-2.0 | 2,101 |
<?php include_once('procedures.php'); ?>
<?php include("top.php"); ?>
<script src="./js/visualRound.js"></script>
<style>
#bottomBar {
position: fixed;
left: 0px;
bottom: 0px;
width: 100%;
height: 40px;
background-color: #EEE;
border-top-width: 1px;
border-top-color: #999;
border-top-style: solid;
overflow: hidden;
z-index: 100;
}
#bottomBarText {
position: relative;
left: 20px;
top: 5px;
font-size: 20px;
color: black;
opacity: 1.0;
}
.bottom_gray_text {
position: relative;
top: 9px;
font-size: 15px;
color: gray;
opacity: 1.0;
}
.footer {
margin-bottom: 50px;
}
.button {
background-color: #9999FF;
cursor: pointer;
}
.left {
float: left;
}
.right {
float:right;
}
.pointer {
cursor: pointer;
}
.timer {
top: 12px;
}
#bottomBarTextOld {
left: 40px;
}
#bottomCounter {
right: 10px;
}
#timersEditor {
right: 5px;
}
</style>
<div class = "container content">
</div>
<div id = "dataContainer" class = "container content">
<?php
$roundId = intval($_GET['round']);
$roundData = getRoundData($roundId);
?>
<div class = "centeredText">
<h2>Раунд "<?php echo $roundData['name']; ?>" игры "<?php echo $roundData['gameName']; ?>" от <?php echo $roundData['date']; ?></h2>
</div>
<h3>Результаты раунда</h3>
<table class = "table table-bordered">
<tr align = center>
<td>Пользователь</td>
<td>Счет</td>
</tr>
<?php
$result = getUsersRoundScoresNoSort($roundId);
$i = -1;
foreach ($result as $row)
{
$i++;
?>
<tr class="tableRow" title="<?php echo $i; ?>" id="r<?php echo $row['id']; ?>" align = "center">
<td>
<?php
echo $row['name'];
?></td>
<td id="c<?php echo $row['id']; ?>"><?php echo 0; ?></td>
</tr>
<?php
}
?>
</table>
<br>
</div>
<script>
round = <?php echo $roundId; ?>;
startVisualization();
</script>
<div id="bottomBar">
<button id="pause" class="btn btn-info left" onClick="pause();">Начать</button>
<button class="btn btn-info left" onClick="step();">Далее</button>
<p id="bottomBarText" class="left"></p>
<p id="bottomBarTextOld" class="bottom_gray_text left"></p>
<p id="timersEditor" class="glyphicon glyphicon-time pointer timer right" onClick="showTimersDialog();"></p>
<p id="bottomCounter" class="bottom_gray_text right"></p>
</div>
<?php include("bottom.php"); ?> | Dovgalyuk/AIBattle | site/visualRound.php | PHP | apache-2.0 | 2,942 |
# coding=utf-8
# Copyright 2018 The Tensor2Tensor 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.
"""ByteNet tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensor2tensor.data_generators import problem_hparams
from tensor2tensor.models import bytenet
import tensorflow as tf
class ByteNetTest(tf.test.TestCase):
def testByteNet(self):
vocab_size = 9
x = np.random.random_integers(1, high=vocab_size - 1, size=(3, 5, 1, 1))
y = np.random.random_integers(1, high=vocab_size - 1, size=(3, 6, 1, 1))
hparams = bytenet.bytenet_base()
p_hparams = problem_hparams.test_problem_hparams(vocab_size, vocab_size)
with self.test_session() as session:
features = {
"inputs": tf.constant(x, dtype=tf.int32),
"targets": tf.constant(y, dtype=tf.int32),
}
model = bytenet.ByteNet(
hparams, tf.estimator.ModeKeys.TRAIN, p_hparams)
logits, _ = model(features)
session.run(tf.global_variables_initializer())
res = session.run(logits)
self.assertEqual(res.shape, (3, 50, 1, 1, vocab_size))
if __name__ == "__main__":
tf.test.main()
| vthorsteinsson/tensor2tensor | tensor2tensor/models/bytenet_test.py | Python | apache-2.0 | 1,719 |
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "bt.h"
#include "bta_api.h"
#include "esp_gap_ble_api.h"
#include "esp_gatts_api.h"
#include "esp_bt_defs.h"
#include "esp_bt_main.h"
#include "esp_bt_main.h"
#include "gatts_table_creat_demo.h"
#define GATTS_TABLE_TAG "GATTS_TABLE_DEMO"
#define HEART_PROFILE_NUM 1
#define HEART_PROFILE_APP_IDX 0
#define ESP_HEART_RATE_APP_ID 0x55
#define SAMPLE_DEVICE_NAME "ESP_HEART_RATE"
#define SAMPLE_MANUFACTURER_DATA_LEN 17
#define HEART_RATE_SVC_INST_ID 0
#define GATTS_DEMO_CHAR_VAL_LEN_MAX 0x40
uint8_t char1_str[] ={0x11,0x22,0x33};
uint16_t heart_rate_handle_table[HRS_IDX_NB];
esp_attr_value_t gatts_demo_char1_val =
{
.attr_max_len = GATTS_DEMO_CHAR_VAL_LEN_MAX,
.attr_len = sizeof(char1_str),
.attr_value = char1_str,
};
static uint8_t heart_rate_service_uuid[16] = {
/* LSB <--------------------------------------------------------------------------------> MSB */
//first uuid, 16bit, [12],[13] is the value
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x18, 0x0D, 0x00, 0x00,
};
static esp_ble_adv_data_t heart_rate_adv_config = {
.set_scan_rsp = false,
.include_name = true,
.include_txpower = true,
.min_interval = 0x20,
.max_interval = 0x40,
.appearance = 0x00,
.manufacturer_len = 0, //TEST_MANUFACTURER_DATA_LEN,
.p_manufacturer_data = NULL, //&test_manufacturer[0],
.service_data_len = 0,
.p_service_data = NULL,
.service_uuid_len = 32,
.p_service_uuid = heart_rate_service_uuid,
.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
};
static esp_ble_adv_params_t heart_rate_adv_params = {
.adv_int_min = 0x20,
.adv_int_max = 0x40,
.adv_type = ADV_TYPE_IND,
.own_addr_type = BLE_ADDR_TYPE_PUBLIC,
//.peer_addr =
//.peer_addr_type =
.channel_map = ADV_CHNL_ALL,
.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
};
struct gatts_profile_inst {
esp_gatts_cb_t gatts_cb;
uint16_t gatts_if;
uint16_t app_id;
uint16_t conn_id;
uint16_t service_handle;
esp_gatt_srvc_id_t service_id;
uint16_t char_handle;
esp_bt_uuid_t char_uuid;
esp_gatt_perm_t perm;
esp_gatt_char_prop_t property;
uint16_t descr_handle;
esp_bt_uuid_t descr_uuid;
};
static void gatts_profile_event_handler(esp_gatts_cb_event_t event,
esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
/* One gatt-based profile one app_id and one gatts_if, this array will store the gatts_if returned by ESP_GATTS_REG_EVT */
static struct gatts_profile_inst heart_rate_profile_tab[HEART_PROFILE_NUM] = {
[HEART_PROFILE_APP_IDX] = {
.gatts_cb = gatts_profile_event_handler,
.gatts_if = ESP_GATT_IF_NONE, /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
},
};
/*
* HTPT PROFILE ATTRIBUTES
****************************************************************************************
*/
/*
* Heart Rate PROFILE ATTRIBUTES
****************************************************************************************
*/
/// Heart Rate Sensor Service
static const uint16_t heart_rate_svc = ESP_GATT_UUID_HEART_RATE_SVC;
#define CHAR_DECLARATION_SIZE (sizeof(uint8_t))
static const uint16_t primary_service_uuid = ESP_GATT_UUID_PRI_SERVICE;
static const uint16_t character_declaration_uuid = ESP_GATT_UUID_CHAR_DECLARE;
static const uint16_t character_client_config_uuid = ESP_GATT_UUID_CHAR_CLIENT_CONFIG;
static const uint8_t char_prop_notify = ESP_GATT_CHAR_PROP_BIT_NOTIFY;
static const uint8_t char_prop_read = ESP_GATT_CHAR_PROP_BIT_READ;
static const uint8_t char_prop_read_write = ESP_GATT_CHAR_PROP_BIT_WRITE|ESP_GATT_CHAR_PROP_BIT_READ;
/// Heart Rate Sensor Service - Heart Rate Measurement Characteristic, notify
static const uint16_t heart_rate_meas_uuid = ESP_GATT_HEART_RATE_MEAS;
static const uint8_t heart_measurement_ccc[2] ={ 0x00, 0x00};
/// Heart Rate Sensor Service -Body Sensor Location characteristic, read
static const uint16_t body_sensor_location_uuid = ESP_GATT_BODY_SENSOR_LOCATION;
static const uint8_t body_sensor_loc_val[1] = {0x00};
/// Heart Rate Sensor Service - Heart Rate Control Point characteristic, write&read
static const uint16_t heart_rate_ctrl_point = ESP_GATT_HEART_RATE_CNTL_POINT;
static const uint8_t heart_ctrl_point[1] = {0x00};
/// Full HRS Database Description - Used to add attributes into the database
static const esp_gatts_attr_db_t heart_rate_gatt_db[HRS_IDX_NB] =
{
// Heart Rate Service Declaration
[HRS_IDX_SVC] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&primary_service_uuid, ESP_GATT_PERM_READ,
sizeof(uint16_t), sizeof(heart_rate_svc), (uint8_t *)&heart_rate_svc}},
// Heart Rate Measurement Characteristic Declaration
[HRS_IDX_HR_MEAS_CHAR] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
CHAR_DECLARATION_SIZE,CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_notify}},
// Heart Rate Measurement Characteristic Value
[HRS_IDX_HR_MEAS_VAL] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&heart_rate_meas_uuid, ESP_GATT_PERM_READ,
HRPS_HT_MEAS_MAX_LEN,0, NULL}},
// Heart Rate Measurement Characteristic - Client Characteristic Configuration Descriptor
[HRS_IDX_HR_MEAS_NTF_CFG] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ|ESP_GATT_PERM_WRITE,
sizeof(uint16_t),sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},
// Body Sensor Location Characteristic Declaration
[HRS_IDX_BOBY_SENSOR_LOC_CHAR] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
CHAR_DECLARATION_SIZE,CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read}},
// Body Sensor Location Characteristic Value
[HRS_IDX_BOBY_SENSOR_LOC_VAL] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&body_sensor_location_uuid, ESP_GATT_PERM_READ,
sizeof(uint8_t), sizeof(body_sensor_loc_val), (uint8_t *)body_sensor_loc_val}},
// Heart Rate Control Point Characteristic Declaration
[HRS_IDX_HR_CTNL_PT_CHAR] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
CHAR_DECLARATION_SIZE,CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read_write}},
// Heart Rate Control Point Characteristic Value
[HRS_IDX_HR_CTNL_PT_VAL] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&heart_rate_ctrl_point, ESP_GATT_PERM_WRITE|ESP_GATT_PERM_READ,
sizeof(uint8_t), sizeof(heart_ctrl_point), (uint8_t *)heart_ctrl_point}},
};
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
ESP_LOGE(GATTS_TABLE_TAG, "GAP_EVT, event %d\n", event);
switch (event) {
case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT:
esp_ble_gap_start_advertising(&heart_rate_adv_params);
break;
case ESP_GAP_BLE_ADV_START_COMPLETE_EVT:
//advertising start complete event to indicate advertising start successfully or failed
if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) {
ESP_LOGE(GATTS_TABLE_TAG, "Advertising start failed\n");
}
break;
default:
break;
}
}
static void gatts_profile_event_handler(esp_gatts_cb_event_t event,
esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
{
ESP_LOGE(GATTS_TABLE_TAG, "event = %x\n",event);
switch (event) {
case ESP_GATTS_REG_EVT:
ESP_LOGI(GATTS_TABLE_TAG, "%s %d\n", __func__, __LINE__);
esp_ble_gap_set_device_name(SAMPLE_DEVICE_NAME);
ESP_LOGI(GATTS_TABLE_TAG, "%s %d\n", __func__, __LINE__);
esp_ble_gap_config_adv_data(&heart_rate_adv_config);
ESP_LOGI(GATTS_TABLE_TAG, "%s %d\n", __func__, __LINE__);
esp_ble_gatts_create_attr_tab(heart_rate_gatt_db, gatts_if,
HRS_IDX_NB, HEART_RATE_SVC_INST_ID);
break;
case ESP_GATTS_READ_EVT:
break;
case ESP_GATTS_WRITE_EVT:
break;
case ESP_GATTS_EXEC_WRITE_EVT:
break;
case ESP_GATTS_MTU_EVT:
break;
case ESP_GATTS_CONF_EVT:
break;
case ESP_GATTS_UNREG_EVT:
break;
case ESP_GATTS_DELETE_EVT:
break;
case ESP_GATTS_START_EVT:
break;
case ESP_GATTS_STOP_EVT:
break;
case ESP_GATTS_CONNECT_EVT:
break;
case ESP_GATTS_DISCONNECT_EVT:
break;
case ESP_GATTS_OPEN_EVT:
break;
case ESP_GATTS_CANCEL_OPEN_EVT:
break;
case ESP_GATTS_CLOSE_EVT:
break;
case ESP_GATTS_LISTEN_EVT:
break;
case ESP_GATTS_CONGEST_EVT:
break;
case ESP_GATTS_CREAT_ATTR_TAB_EVT:{
ESP_LOGE(GATTS_TABLE_TAG, "The number handle =%x\n",param->add_attr_tab.num_handle);
if(param->add_attr_tab.num_handle == HRS_IDX_NB){
memcpy(heart_rate_handle_table, param->add_attr_tab.handles,
sizeof(heart_rate_handle_table));
esp_ble_gatts_start_service(heart_rate_handle_table[HRS_IDX_SVC]);
}
break;
}
default:
break;
}
}
static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
esp_ble_gatts_cb_param_t *param)
{
ESP_LOGI(GATTS_TABLE_TAG, "EVT %d, gatts if %d\n", event, gatts_if);
/* If event is register event, store the gatts_if for each profile */
if (event == ESP_GATTS_REG_EVT) {
if (param->reg.status == ESP_GATT_OK) {
heart_rate_profile_tab[HEART_PROFILE_APP_IDX].gatts_if = gatts_if;
} else {
ESP_LOGI(GATTS_TABLE_TAG, "Reg app failed, app_id %04x, status %d\n",
param->reg.app_id,
param->reg.status);
return;
}
}
do {
int idx;
for (idx = 0; idx < HEART_PROFILE_NUM; idx++) {
if (gatts_if == ESP_GATT_IF_NONE || /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */
gatts_if == heart_rate_profile_tab[idx].gatts_if) {
if (heart_rate_profile_tab[idx].gatts_cb) {
heart_rate_profile_tab[idx].gatts_cb(event, gatts_if, param);
}
}
}
} while (0);
}
void app_main()
{
esp_err_t ret;
esp_bt_controller_init();
ret = esp_bt_controller_enable(ESP_BT_MODE_BTDM);
if (ret) {
ESP_LOGE(GATTS_TABLE_TAG, "%s enable controller failed\n", __func__);
return;
}
ESP_LOGI(GATTS_TABLE_TAG, "%s init bluetooth\n", __func__);
ret = esp_bluedroid_init();
if (ret) {
ESP_LOGE(GATTS_TABLE_TAG, "%s init bluetooth failed\n", __func__);
return;
}
ret = esp_bluedroid_enable();
if (ret) {
ESP_LOGE(GATTS_TABLE_TAG, "%s enable bluetooth failed\n", __func__);
return;
}
esp_ble_gatts_register_callback(gatts_event_handler);
esp_ble_gap_register_callback(gap_event_handler);
esp_ble_gatts_app_register(ESP_HEART_RATE_APP_ID);
return;
}
| wmpluto/esp-idf | examples/bluetooth/gatt_server_service_table/main/gatts_table_creat_demo.c | C | apache-2.0 | 12,057 |
/**
* 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.pinot.core.startree.v2.store;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.List;
import java.util.Map;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.pinot.common.segment.ReadMode;
import org.apache.pinot.core.segment.index.column.ColumnIndexContainer;
import org.apache.pinot.core.segment.index.metadata.SegmentMetadataImpl;
import org.apache.pinot.core.segment.memory.PinotDataBuffer;
import org.apache.pinot.core.startree.v2.StarTreeV2;
import org.apache.pinot.core.startree.v2.StarTreeV2Constants;
import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexKey;
import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexValue;
/**
* The {@code StarTreeIndexContainer} class contains the indexes for multiple star-trees.
*/
public class StarTreeIndexContainer implements Closeable {
private final PinotDataBuffer _dataBuffer;
private final List<StarTreeV2> _starTrees;
public StarTreeIndexContainer(File segmentDirectory, SegmentMetadataImpl segmentMetadata,
Map<String, ColumnIndexContainer> indexContainerMap, ReadMode readMode)
throws ConfigurationException, IOException {
File indexFile = new File(segmentDirectory, StarTreeV2Constants.INDEX_FILE_NAME);
if (readMode == ReadMode.heap) {
_dataBuffer = PinotDataBuffer
.loadFile(indexFile, 0, indexFile.length(), ByteOrder.LITTLE_ENDIAN, "Star-tree V2 data buffer");
} else {
_dataBuffer = PinotDataBuffer
.mapFile(indexFile, true, 0, indexFile.length(), ByteOrder.LITTLE_ENDIAN, "Star-tree V2 data buffer");
}
File indexMapFile = new File(segmentDirectory, StarTreeV2Constants.INDEX_MAP_FILE_NAME);
List<Map<IndexKey, IndexValue>> indexMapList =
StarTreeIndexMapUtils.loadFromFile(indexMapFile, segmentMetadata.getStarTreeV2MetadataList().size());
_starTrees = StarTreeLoaderUtils.loadStarTreeV2(_dataBuffer, indexMapList, segmentMetadata, indexContainerMap);
}
public List<StarTreeV2> getStarTrees() {
return _starTrees;
}
@Override
public void close()
throws IOException {
_dataBuffer.close();
}
}
| linkedin/pinot | pinot-core/src/main/java/org/apache/pinot/core/startree/v2/store/StarTreeIndexContainer.java | Java | apache-2.0 | 3,059 |
/*
Copyright 2010-2011 Zhengmao HU (James)
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 net.sf.jabb.util.text;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Given a text string to be tested, and list of matching strings, find out which matching string the
* text string starts with.<br>
* 给定一个待检查的文本字符串,以及一批开头匹配字符串,看看待检查的文本字符串以哪个匹配字符串开头。
* <p>
* The matching is case sensitive.
* If one matching string starts with another,
* and the text string starts with them, then the longer one will be considered to be matched.
* <p>
* 匹配时对大小写敏感。如果匹配字符串之间互相饱含,则匹配其中最长的。
*
* <p>
* If the matching need to be checked upon number segments (start number ~ end number) represented
* as strings, {@link #expandNumberMatchingRange(Map, String, String, Object)} method can be used to
* expand number segments to heading number strings.
* <p>
* 如果需要对代表数字号码(开始号码~结束号码)的字符串进行匹配,可使用
* {@link #expandNumberMatchingRange(Map, String, String, Object)} 方法
* 将号码段字符串(一个开始号码,一个结束号码)转换为号码头字符串。
*
* @author Zhengmao HU (James)
*
*/
public class StringStartWithMatcher extends StartWithMatcher {
private static final long serialVersionUID = -2501231925022032723L;
/**
* Create a new instance according to heading strings and their corresponding attachment objects.<br>
* 根据开头匹配字符串、开头匹配字符串所对应的附件对象,创建一个新的实例。
* <p>
* When initializing internal data structure, choose to consume more memory for better matching speed.
* <p>
* 在创建内部数据结构的时候,选择占用更多内存,而换取速度上的提升。
*
* @param headingDefinitions Key is the heading string, Value is its associated attachment object.
* When the heading string is matched, the attachment object will be returned
* as identifier.<p>
* Key是匹配字符串,Value是附件对象。
* 当进行匹配检查的时候,返回附件对象来标识哪一个匹配字符串被匹配上了。
*/
public StringStartWithMatcher(Map<String, ? extends Object> headingDefinitions) {
super(normalizeMatchingDefinitions(headingDefinitions));
}
/**
* Create a new instance according to heading strings and their corresponding attachment objects.<br>
* 根据开头匹配字符串、开头匹配字符串所对应的附件对象,创建一个新的实例。
*
* @param headingDefinitions Key是匹配字符串,Value是附件对象。
* 当进行匹配检查的时候,返回附件对象来标识哪一个匹配字符串被匹配上了。
* <p>
* Key is the heading string, Value is its associated attachment object.
* When the heading string is matched, the attachment object will be returned
* as identifier.
* @param moreSpaceForSpeed 是否占用更多内存,而换取速度上的提升。
* <p>Whether or not to consume
* more memory for better matching speed.
*/
public StringStartWithMatcher(Map<String, ? extends Object> headingDefinitions, boolean moreSpaceForSpeed) {
super(normalizeMatchingDefinitions(headingDefinitions), moreSpaceForSpeed);
}
/**
* Create a copy, the copy will have exactly the same matching
* definitions as the original copy.<br>
* 创建一个副本,这个副本与原先的对象具有完全相同匹配方式。
*
* @param toBeCopied 原本。<br>The original copy.
*/
public StringStartWithMatcher(StringStartWithMatcher toBeCopied) {
super(toBeCopied);
}
/**
* Normalize matching definitions according to requirements of {@link StartWithMatcher}.<br>
* 根据{@link StartWithMatcher}的需要来规范化匹配条件定义。
*
* @param headingDefinitions Key是匹配字符串,Value是附件对象。
* 当进行匹配检查的时候,返回附件对象来标识哪一个匹配字符串被匹配上了。
* <p>
* Key is the heading string, Value is its associated attachment object.
* When the heading string is matched, the attachment object will be returned
* as identifier.
* @return {@link StartWithMatcher}所需的匹配条件定义。
* <br>Matching definitions for usage of {@link StartWithMatcher}.
*/
static protected List<MatchingDefinition> normalizeMatchingDefinitions(Map<String, ? extends Object> headingDefinitions){
// exactMatchExample自动设置为与regularExpression相同
List<MatchingDefinition> l = new ArrayList<MatchingDefinition>(headingDefinitions.size());
for (Map.Entry<String, ? extends Object> e: headingDefinitions.entrySet()){
MatchingDefinition c = new MatchingDefinition();
c.setRegularExpression(escapeForRegExp(e.getKey()));
c.setAttachment(e.getValue());
c.setExactMatchExample(e.getKey());
l.add(c);
}
return l;
}
/**
* Expand number segments (such as 138000~138999 or 138000~138029) into number headings
* (such as 138 or {13800,13801,13802}).<br>
* 把号码段(类似:138000~138999或138000~138029)展开成号码头(类似:138或13800,13801,13802)。
*
* @param headingDefinitions 可用来对{@link StringStartWithMatcher}进行初始化的展开后的匹配条件
* 会被放到这个Map里。
* <br> Equivalent heading definitions that could be used to
* create instance of {@link StringStartWithMatcher} will be put into this Map.
* @param start 起始号码 <br> first/starting number
* @param end 结束号码 <br> last/ending number
* @param attachment 匹配附件<br>attachment to identify that the segment matches a string
*/
public static <T> void expandNumberMatchingRange(Map<String, T> headingDefinitions, String start, String end, T attachment){
int firstDiff; //第一个不相同字符的位置
int lastDiff; //末尾0:9对应段开始的位置
// 先强行保证起始号码与结束号码长度相同
if (start.length() > end.length()){
StringBuilder sb = new StringBuilder(end);
while (start.length() > sb.length()){
sb.append("9");
}
end = sb.toString();
} else if (end.length() > start.length()){
StringBuilder sb = new StringBuilder(start);
while (end.length() > sb.length()){
sb.append("0");
}
start = sb.toString();
}
// 然后寻找第一个不相同字符的位置
for (firstDiff = 0; firstDiff < start.length(); firstDiff++){
if (start.charAt(firstDiff) != end.charAt(firstDiff)){
break;
}
}
// 再寻找末尾0:9对应段开始的位置
for (lastDiff = start.length() - 1; lastDiff >= 0; lastDiff--){
if (start.charAt(lastDiff) != '0' || end.charAt(lastDiff) != '9'){
break;
}
}
lastDiff++;
if (firstDiff == lastDiff){ // 则表示可合并为一条
headingDefinitions.put(start.substring(0, firstDiff), attachment);
} else { // 则表示要扩展为多条
int j = Integer.parseInt(start.substring(firstDiff, lastDiff));
int k = Integer.parseInt(end.substring(firstDiff, lastDiff));
String head = start.substring(0, firstDiff);
String f = "%" + (lastDiff-firstDiff) + "d";
StringBuilder sb = new StringBuilder();
for (int i = j; i <= k; i++){
sb.setLength(0);
sb.append(head);
sb.append(String.format(f, i));
headingDefinitions.put(sb.toString(), attachment);
}
}
}
}
| james-hu/jabb-core | src/main/java/net/sf/jabb/util/text/StringStartWithMatcher.java | Java | apache-2.0 | 8,259 |
# -*- coding: utf-8 -*-
"""
Linguistic and other taggers.
Tagging each token in a sentence with supplementary information,
such as its part-of-speech (POS) tag, and named entity (NE) tag.
"""
__all__ = [
"PerceptronTagger",
"pos_tag",
"pos_tag_sents",
"tag_provinces",
"chunk_parse",
"NER",
]
from pythainlp.tag.locations import tag_provinces
from pythainlp.tag.pos_tag import pos_tag, pos_tag_sents
from pythainlp.tag._tag_perceptron import PerceptronTagger
from pythainlp.tag.chunk import chunk_parse
from pythainlp.tag.named_entity import NER
| PyThaiNLP/pythainlp | pythainlp/tag/__init__.py | Python | apache-2.0 | 573 |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMAR3 {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct MAR {
bits: u32,
}
impl MAR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _MAW<'a> {
w: &'a mut W,
}
impl<'a> _MAW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u32) -> &'a mut W {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&self) -> MAR {
let bits = {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u32
};
MAR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&mut self) -> _MAW {
_MAW { w: self }
}
}
| pollen/stm32f0 | stm32f0x2/src/dma1/cmar3/mod.rs | Rust | apache-2.0 | 2,556 |
<?php
namespace Topxia\WebBundle\Listener;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale)
{
if ($defaultLocale == 'en') {
$defaultLocale = 'en_US'; //兼容原来的配置
}
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
$locale = $request->getSession()->get('_locale', $request->cookies->get('_last_logout_locale') ?: $this->defaultLocale);
$request->setLocale($locale);
}
public static function getSubscribedEvents()
{
return array(
// must be registered after the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 15))
);
}
}
| 18826252059/im | src/Topxia/WebBundle/Listener/LocaleListener.php | PHP | apache-2.0 | 1,115 |
<?php
namespace BankId\Merchant\Library\Schemas\saml\metadata;
/**
* Class representing Extensions
*/
class Extensions extends ExtensionsType
{
}
| notarynodes/idintt | hackathon-module/idintt-php-module/library/Schemas/saml/metadata/Extensions.php | PHP | apache-2.0 | 166 |
package com.dexvis.simple.transform;
import javafx.scene.web.HTMLEditor;
import org.simpleframework.xml.transform.Transform;
public class HTMLEditorTransform implements Transform<HTMLEditor>
{
public HTMLEditor read(String value) throws Exception
{
HTMLEditor editor = new HTMLEditor();
editor.setHtmlText(value);
return editor;
}
@Override
public String write(HTMLEditor value) throws Exception
{
return value.getHtmlText();
}
}
| PatMartin/Dex | src/com/dexvis/simple/transform/HTMLEditorTransform.java | Java | apache-2.0 | 485 |
package ecologylab.bigsemantics.service.crawler;
import java.io.IOException;
/**
* A general framework for crawling resources.
*
* @author quyin
*/
public interface ResourceCrawler<T>
{
/**
* Queue a resource with the given URI.
*
* @param uri
*/
void queue(String uri);
/**
* If the crawler has more resources to crawl.
*
* @return true if there are still resources to crawl.
*/
boolean hasNext();
/**
* Retrieve the next resource.
*
* @return The next crawled resource.
* @throws IOException
* If the resource cannot be accessed.
*/
T next() throws IOException;
/**
* Expand a given resource.
*
* @param resource
*/
void expand(T resource);
/**
* @return The number of resources queued.
*/
int countQueued();
/**
* @return The number of resources that are to be crawled.
*/
int countWaiting();
/**
* @return The number of resources that have been accessed.
*/
int countAccessed();
/**
* @return The number of resources that have been accessed successfully.
*/
int countSuccess();
/**
* @return The number of resources that have been accessed unsuccessfully.
*/
int countFailure();
} | ecologylab/BigSemanticsService | BasicCrawler/src/ecologylab/bigsemantics/service/crawler/ResourceCrawler.java | Java | apache-2.0 | 1,304 |
package net.sf.anpr.rcp.widget;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class JCanvasPanel extends JLabel {
private static final long serialVersionUID = 1L;
private Rectangle focusArea=new Rectangle();
private BufferedImage image;
public JCanvasPanel() {
super();
this.setVerticalAlignment(SwingConstants.TOP);
this.setHorizontalAlignment(SwingConstants.LEFT);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(focusArea==null) return ;
if (focusArea.width >= 0 && focusArea.height >= 0) {
Color c = g.getColor();
g.setColor(Color.RED);
g.drawRect(focusArea.x, focusArea.y, focusArea.width, focusArea.height);
g.setColor(c);
}
g.dispose();
}
protected void setImage(BufferedImage image){
this.image=image;
this.setIcon(new ImageIcon(image));
}
public void setFocusArea(Rectangle focusArea) {
this.focusArea = focusArea;
}
protected BufferedImage getImage() {
return image;
}
}
| alexmao86/swing-rcp | src/main/java/net/sf/anpr/rcp/widget/JCanvasPanel.java | Java | apache-2.0 | 1,173 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 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.
"""
Common Policy Engine Implementation
Policies can be expressed in one of two forms: A list of lists, or a
string written in the new policy language.
In the list-of-lists representation, each check inside the innermost
list is combined as with an "and" conjunction--for that check to pass,
all the specified checks must pass. These innermost lists are then
combined as with an "or" conjunction. This is the original way of
expressing policies, but there now exists a new way: the policy
language.
In the policy language, each check is specified the same way as in the
list-of-lists representation: a simple "a:b" pair that is matched to
the correct code to perform that check. However, conjunction
operators are available, allowing for more expressiveness in crafting
policies.
As an example, take the following rule, expressed in the list-of-lists
representation::
[["role:admin"], ["project_id:%(project_id)s", "role:projectadmin"]]
In the policy language, this becomes::
role:admin or (project_id:%(project_id)s and role:projectadmin)
The policy language also has the "not" operator, allowing a richer
policy rule::
project_id:%(project_id)s and not role:dunce
Finally, two special policy checks should be mentioned; the policy
check "@" will always accept an access, and the policy check "!" will
always reject an access. (Note that if a rule is either the empty
list ("[]") or the empty string, this is equivalent to the "@" policy
check.) Of these, the "!" policy check is probably the most useful,
as it allows particular rules to be explicitly disabled.
"""
import abc
import re
import urllib
import urllib2
from oslo.config import cfg
import six
from kwstandby.openstack.common import fileutils
from kwstandby.openstack.common.gettextutils import _
from kwstandby.openstack.common import jsonutils
from kwstandby.openstack.common import log as logging
policy_opts = [
cfg.StrOpt('policy_file',
default='policy.json',
help=_('JSON file containing policy')),
cfg.StrOpt('policy_default_rule',
default='default',
help=_('Rule enforced when requested rule is not found')),
]
CONF = cfg.CONF
CONF.register_opts(policy_opts)
LOG = logging.getLogger(__name__)
_checks = {}
class PolicyNotAuthorized(Exception):
def __init__(self, rule):
msg = _("Policy doesn't allow %s to be performed.") % rule
super(PolicyNotAuthorized, self).__init__(msg)
class Rules(dict):
"""A store for rules. Handles the default_rule setting directly."""
@classmethod
def load_json(cls, data, default_rule=None):
"""Allow loading of JSON rule data."""
# Suck in the JSON data and parse the rules
rules = dict((k, parse_rule(v)) for k, v in
jsonutils.loads(data).items())
return cls(rules, default_rule)
def __init__(self, rules=None, default_rule=None):
"""Initialize the Rules store."""
super(Rules, self).__init__(rules or {})
self.default_rule = default_rule
def __missing__(self, key):
"""Implements the default rule handling."""
# If the default rule isn't actually defined, do something
# reasonably intelligent
if not self.default_rule or self.default_rule not in self:
raise KeyError(key)
return self[self.default_rule]
def __str__(self):
"""Dumps a string representation of the rules."""
# Start by building the canonical strings for the rules
out_rules = {}
for key, value in self.items():
# Use empty string for singleton TrueCheck instances
if isinstance(value, TrueCheck):
out_rules[key] = ''
else:
out_rules[key] = str(value)
# Dump a pretty-printed JSON representation
return jsonutils.dumps(out_rules, indent=4)
class Enforcer(object):
"""Responsible for loading and enforcing rules.
:param policy_file: Custom policy file to use, if none is
specified, `CONF.policy_file` will be
used.
:param rules: Default dictionary / Rules to use. It will be
considered just in the first instantiation. If
`load_rules(True)`, `clear()` or `set_rules(True)`
is called this will be overwritten.
:param default_rule: Default rule to use, CONF.default_rule will
be used if none is specified.
"""
def __init__(self, policy_file=None, rules=None, default_rule=None):
self.rules = Rules(rules)
self.default_rule = default_rule or CONF.policy_default_rule
self.policy_path = None
self.policy_file = policy_file or CONF.policy_file
def set_rules(self, rules, overwrite=True):
"""Create a new Rules object based on the provided dict of rules.
:param rules: New rules to use. It should be an instance of dict.
:param overwrite: Whether to overwrite current rules or update them
with the new rules.
"""
if not isinstance(rules, dict):
raise TypeError(_("Rules must be an instance of dict or Rules, "
"got %s instead") % type(rules))
if overwrite:
self.rules = Rules(rules)
else:
self.update(rules)
def clear(self):
"""Clears Enforcer rules, policy's cache and policy's path."""
self.set_rules({})
self.policy_path = None
def load_rules(self, force_reload=False):
"""Loads policy_path's rules.
Policy file is cached and will be reloaded if modified.
:param force_reload: Whether to overwrite current rules.
"""
if not self.policy_path:
self.policy_path = self._get_policy_path()
reloaded, data = fileutils.read_cached_file(self.policy_path,
force_reload=force_reload)
if reloaded:
rules = Rules.load_json(data, self.default_rule)
self.set_rules(rules)
LOG.debug(_("Rules successfully reloaded"))
def _get_policy_path(self):
"""Locate the policy json data file.
:param policy_file: Custom policy file to locate.
:returns: The policy path
:raises: ConfigFilesNotFoundError if the file couldn't
be located.
"""
policy_file = CONF.find_file(self.policy_file)
if policy_file:
return policy_file
raise cfg.ConfigFilesNotFoundError(path=CONF.policy_file)
def enforce(self, rule, target, creds, do_raise=False,
exc=None, *args, **kwargs):
"""Checks authorization of a rule against the target and credentials.
:param rule: A string or BaseCheck instance specifying the rule
to evaluate.
:param target: As much information about the object being operated
on as possible, as a dictionary.
:param creds: As much information about the user performing the
action as possible, as a dictionary.
:param do_raise: Whether to raise an exception or not if check
fails.
:param exc: Class of the exception to raise if the check fails.
Any remaining arguments passed to check() (both
positional and keyword arguments) will be passed to
the exception class. If not specified, PolicyNotAuthorized
will be used.
:return: Returns False if the policy does not allow the action and
exc is not provided; otherwise, returns a value that
evaluates to True. Note: for rules using the "case"
expression, this True value will be the specified string
from the expression.
"""
# NOTE(flaper87): Not logging target or creds to avoid
# potential security issues.
LOG.debug(_("Rule %s will be now enforced") % rule)
self.load_rules()
# Allow the rule to be a Check tree
if isinstance(rule, BaseCheck):
result = rule(target, creds, self)
elif not self.rules:
# No rules to reference means we're going to fail closed
result = False
else:
try:
# Evaluate the rule
result = self.rules[rule](target, creds, self)
except KeyError:
LOG.debug(_("Rule [%s] doesn't exist") % rule)
# If the rule doesn't exist, fail closed
result = False
# If it is False, raise the exception if requested
if do_raise and not result:
if exc:
raise exc(*args, **kwargs)
raise PolicyNotAuthorized(rule)
return result
class BaseCheck(object):
"""Abstract base class for Check classes."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __str__(self):
"""String representation of the Check tree rooted at this node."""
pass
@abc.abstractmethod
def __call__(self, target, cred):
"""Triggers if instance of the class is called.
Performs the check. Returns False to reject the access or a
true value (not necessary True) to accept the access.
"""
pass
class FalseCheck(BaseCheck):
"""A policy check that always returns False (disallow)."""
def __str__(self):
"""Return a string representation of this check."""
return "!"
def __call__(self, target, cred):
"""Check the policy."""
return False
class TrueCheck(BaseCheck):
"""A policy check that always returns True (allow)."""
def __str__(self):
"""Return a string representation of this check."""
return "@"
def __call__(self, target, cred):
"""Check the policy."""
return True
class Check(BaseCheck):
"""A base class to allow for user-defined policy checks."""
def __init__(self, kind, match):
"""Initiates Check instance.
:param kind: The kind of the check, i.e., the field before the
':'.
:param match: The match of the check, i.e., the field after
the ':'.
"""
self.kind = kind
self.match = match
def __str__(self):
"""Return a string representation of this check."""
return "%s:%s" % (self.kind, self.match)
class NotCheck(BaseCheck):
"""Implements the "not" logical operator.
A policy check that inverts the result of another policy check.
"""
def __init__(self, rule):
"""Initialize the 'not' check.
:param rule: The rule to negate. Must be a Check.
"""
self.rule = rule
def __str__(self):
"""Return a string representation of this check."""
return "not %s" % self.rule
def __call__(self, target, cred):
"""Check the policy.
Returns the logical inverse of the wrapped check.
"""
return not self.rule(target, cred)
class AndCheck(BaseCheck):
"""Implements the "and" logical operator.
A policy check that requires that a list of other checks all return True.
"""
def __init__(self, rules):
"""Initialize the 'and' check.
:param rules: A list of rules that will be tested.
"""
self.rules = rules
def __str__(self):
"""Return a string representation of this check."""
return "(%s)" % ' and '.join(str(r) for r in self.rules)
def __call__(self, target, cred):
"""Check the policy.
Requires that all rules accept in order to return True.
"""
for rule in self.rules:
if not rule(target, cred):
return False
return True
def add_check(self, rule):
"""Adds rule to be tested.
Allows addition of another rule to the list of rules that will
be tested. Returns the AndCheck object for convenience.
"""
self.rules.append(rule)
return self
class OrCheck(BaseCheck):
"""Implements the "or" operator.
A policy check that requires that at least one of a list of other
checks returns True.
"""
def __init__(self, rules):
"""Initialize the 'or' check.
:param rules: A list of rules that will be tested.
"""
self.rules = rules
def __str__(self):
"""Return a string representation of this check."""
return "(%s)" % ' or '.join(str(r) for r in self.rules)
def __call__(self, target, cred):
"""Check the policy.
Requires that at least one rule accept in order to return True.
"""
for rule in self.rules:
if rule(target, cred):
return True
return False
def add_check(self, rule):
"""Adds rule to be tested.
Allows addition of another rule to the list of rules that will
be tested. Returns the OrCheck object for convenience.
"""
self.rules.append(rule)
return self
def _parse_check(rule):
"""Parse a single base check rule into an appropriate Check object."""
# Handle the special checks
if rule == '!':
return FalseCheck()
elif rule == '@':
return TrueCheck()
try:
kind, match = rule.split(':', 1)
except Exception:
LOG.exception(_("Failed to understand rule %s") % rule)
# If the rule is invalid, we'll fail closed
return FalseCheck()
# Find what implements the check
if kind in _checks:
return _checks[kind](kind, match)
elif None in _checks:
return _checks[None](kind, match)
else:
LOG.error(_("No handler for matches of kind %s") % kind)
return FalseCheck()
def _parse_list_rule(rule):
"""Translates the old list-of-lists syntax into a tree of Check objects.
Provided for backwards compatibility.
"""
# Empty rule defaults to True
if not rule:
return TrueCheck()
# Outer list is joined by "or"; inner list by "and"
or_list = []
for inner_rule in rule:
# Elide empty inner lists
if not inner_rule:
continue
# Handle bare strings
if isinstance(inner_rule, basestring):
inner_rule = [inner_rule]
# Parse the inner rules into Check objects
and_list = [_parse_check(r) for r in inner_rule]
# Append the appropriate check to the or_list
if len(and_list) == 1:
or_list.append(and_list[0])
else:
or_list.append(AndCheck(and_list))
# If we have only one check, omit the "or"
if not or_list:
return FalseCheck()
elif len(or_list) == 1:
return or_list[0]
return OrCheck(or_list)
# Used for tokenizing the policy language
_tokenize_re = re.compile(r'\s+')
def _parse_tokenize(rule):
"""Tokenizer for the policy language.
Most of the single-character tokens are specified in the
_tokenize_re; however, parentheses need to be handled specially,
because they can appear inside a check string. Thankfully, those
parentheses that appear inside a check string can never occur at
the very beginning or end ("%(variable)s" is the correct syntax).
"""
for tok in _tokenize_re.split(rule):
# Skip empty tokens
if not tok or tok.isspace():
continue
# Handle leading parens on the token
clean = tok.lstrip('(')
for i in range(len(tok) - len(clean)):
yield '(', '('
# If it was only parentheses, continue
if not clean:
continue
else:
tok = clean
# Handle trailing parens on the token
clean = tok.rstrip(')')
trail = len(tok) - len(clean)
# Yield the cleaned token
lowered = clean.lower()
if lowered in ('and', 'or', 'not'):
# Special tokens
yield lowered, clean
elif clean:
# Not a special token, but not composed solely of ')'
if len(tok) >= 2 and ((tok[0], tok[-1]) in
[('"', '"'), ("'", "'")]):
# It's a quoted string
yield 'string', tok[1:-1]
else:
yield 'check', _parse_check(clean)
# Yield the trailing parens
for i in range(trail):
yield ')', ')'
class ParseStateMeta(type):
"""Metaclass for the ParseState class.
Facilitates identifying reduction methods.
"""
def __new__(mcs, name, bases, cls_dict):
"""Create the class.
Injects the 'reducers' list, a list of tuples matching token sequences
to the names of the corresponding reduction methods.
"""
reducers = []
for key, value in cls_dict.items():
if not hasattr(value, 'reducers'):
continue
for reduction in value.reducers:
reducers.append((reduction, key))
cls_dict['reducers'] = reducers
return super(ParseStateMeta, mcs).__new__(mcs, name, bases, cls_dict)
def reducer(*tokens):
"""Decorator for reduction methods.
Arguments are a sequence of tokens, in order, which should trigger running
this reduction method.
"""
def decorator(func):
# Make sure we have a list of reducer sequences
if not hasattr(func, 'reducers'):
func.reducers = []
# Add the tokens to the list of reducer sequences
func.reducers.append(list(tokens))
return func
return decorator
class ParseState(object):
"""Implement the core of parsing the policy language.
Uses a greedy reduction algorithm to reduce a sequence of tokens into
a single terminal, the value of which will be the root of the Check tree.
Note: error reporting is rather lacking. The best we can get with
this parser formulation is an overall "parse failed" error.
Fortunately, the policy language is simple enough that this
shouldn't be that big a problem.
"""
__metaclass__ = ParseStateMeta
def __init__(self):
"""Initialize the ParseState."""
self.tokens = []
self.values = []
def reduce(self):
"""Perform a greedy reduction of the token stream.
If a reducer method matches, it will be executed, then the
reduce() method will be called recursively to search for any more
possible reductions.
"""
for reduction, methname in self.reducers:
if (len(self.tokens) >= len(reduction) and
self.tokens[-len(reduction):] == reduction):
# Get the reduction method
meth = getattr(self, methname)
# Reduce the token stream
results = meth(*self.values[-len(reduction):])
# Update the tokens and values
self.tokens[-len(reduction):] = [r[0] for r in results]
self.values[-len(reduction):] = [r[1] for r in results]
# Check for any more reductions
return self.reduce()
def shift(self, tok, value):
"""Adds one more token to the state. Calls reduce()."""
self.tokens.append(tok)
self.values.append(value)
# Do a greedy reduce...
self.reduce()
@property
def result(self):
"""Obtain the final result of the parse.
Raises ValueError if the parse failed to reduce to a single result.
"""
if len(self.values) != 1:
raise ValueError("Could not parse rule")
return self.values[0]
@reducer('(', 'check', ')')
@reducer('(', 'and_expr', ')')
@reducer('(', 'or_expr', ')')
def _wrap_check(self, _p1, check, _p2):
"""Turn parenthesized expressions into a 'check' token."""
return [('check', check)]
@reducer('check', 'and', 'check')
def _make_and_expr(self, check1, _and, check2):
"""Create an 'and_expr'.
Join two checks by the 'and' operator.
"""
return [('and_expr', AndCheck([check1, check2]))]
@reducer('and_expr', 'and', 'check')
def _extend_and_expr(self, and_expr, _and, check):
"""Extend an 'and_expr' by adding one more check."""
return [('and_expr', and_expr.add_check(check))]
@reducer('check', 'or', 'check')
def _make_or_expr(self, check1, _or, check2):
"""Create an 'or_expr'.
Join two checks by the 'or' operator.
"""
return [('or_expr', OrCheck([check1, check2]))]
@reducer('or_expr', 'or', 'check')
def _extend_or_expr(self, or_expr, _or, check):
"""Extend an 'or_expr' by adding one more check."""
return [('or_expr', or_expr.add_check(check))]
@reducer('not', 'check')
def _make_not_expr(self, _not, check):
"""Invert the result of another check."""
return [('check', NotCheck(check))]
def _parse_text_rule(rule):
"""Parses policy to the tree.
Translates a policy written in the policy language into a tree of
Check objects.
"""
# Empty rule means always accept
if not rule:
return TrueCheck()
# Parse the token stream
state = ParseState()
for tok, value in _parse_tokenize(rule):
state.shift(tok, value)
try:
return state.result
except ValueError:
# Couldn't parse the rule
LOG.exception(_("Failed to understand rule %(rule)r") % locals())
# Fail closed
return FalseCheck()
def parse_rule(rule):
"""Parses a policy rule into a tree of Check objects."""
# If the rule is a string, it's in the policy language
if isinstance(rule, basestring):
return _parse_text_rule(rule)
return _parse_list_rule(rule)
def register(name, func=None):
"""Register a function or Check class as a policy check.
:param name: Gives the name of the check type, e.g., 'rule',
'role', etc. If name is None, a default check type
will be registered.
:param func: If given, provides the function or class to register.
If not given, returns a function taking one argument
to specify the function or class to register,
allowing use as a decorator.
"""
# Perform the actual decoration by registering the function or
# class. Returns the function or class for compliance with the
# decorator interface.
def decorator(func):
_checks[name] = func
return func
# If the function or class is given, do the registration
if func:
return decorator(func)
return decorator
@register("rule")
class RuleCheck(Check):
def __call__(self, target, creds, enforcer):
"""Recursively checks credentials based on the defined rules."""
try:
return enforcer.rules[self.match](target, creds, enforcer)
except KeyError:
# We don't have any matching rule; fail closed
return False
@register("role")
class RoleCheck(Check):
def __call__(self, target, creds, enforcer):
"""Check that there is a matching role in the cred dict."""
return self.match.lower() in [x.lower() for x in creds['roles']]
@register('http')
class HttpCheck(Check):
def __call__(self, target, creds, enforcer):
"""Check http: rules by calling to a remote server.
This example implementation simply verifies that the response
is exactly 'True'.
"""
url = ('http:' + self.match) % target
data = {'target': jsonutils.dumps(target),
'credentials': jsonutils.dumps(creds)}
post_data = urllib.urlencode(data)
f = urllib2.urlopen(url, post_data)
return f.read() == "True"
@register(None)
class GenericCheck(Check):
def __call__(self, target, creds, enforcer):
"""Check an individual match.
Matches look like:
tenant:%(tenant_id)s
role:compute:admin
"""
# TODO(termie): do dict inspection via dot syntax
match = self.match % target
if self.kind in creds:
return match == six.text_type(creds[self.kind])
return False
| frossigneux/kwstandby | kwstandby/openstack/common/policy.py | Python | apache-2.0 | 25,233 |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2022 DBeaver Corp and others
*
* 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.ui.app.standalone.about;
import org.eclipse.jface.action.IAction;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionDelegate;
public class AboutBoxAction extends ActionDelegate
{
private IWorkbenchWindow window;
public AboutBoxAction(IWorkbenchWindow window) {
this.window = window;
}
@Override
public void run(IAction action)
{
// new AboutDialog(window.getShell()).open();
AboutBoxDialog dialog = new AboutBoxDialog(window.getShell());
dialog.open();
}
} | dbeaver/dbeaver | plugins/org.jkiss.dbeaver.ui.app.standalone/src/org/jkiss/dbeaver/ui/app/standalone/about/AboutBoxAction.java | Java | apache-2.0 | 1,230 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="es">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Thu Apr 10 11:52:58 CEST 2014 -->
<title>State</title>
<meta name="date" content="2014-04-10">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="State";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../JSHOP2/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-all.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../JSHOP2/SolverThread.html" title="class in JSHOP2"><span class="strong">Prev Class</span></a></li>
<li><a href="../JSHOP2/StdLib.html" title="class in JSHOP2"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?JSHOP2/State.html" target="_top">Frames</a></li>
<li><a href="State.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">JSHOP2</div>
<h2 title="Class State" class="title">Class State</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>JSHOP2.State</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">State</span>
extends java.lang.Object</pre>
<div class="block">This class is used to represent the current state of the world.</div>
<dl><dt><span class="strong">Version:</span></dt>
<dd>1.0.3</dd>
<dt><span class="strong">Author:</span></dt>
<dd>Okhtay Ilghami, <a href="http://www.cs.umd.edu/~okhtay">http://www.cs.umd.edu/~okhtay</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>private java.util.Vector<<a href="../JSHOP2/Term.html" title="class in JSHOP2">Term</a>>[]</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#atoms">atoms</a></strong></code>
<div class="block">The atoms in the current state of the world as an array of
<code>Vector</code>s.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>private <a href="../JSHOP2/Axiom.html" title="class in JSHOP2">Axiom</a>[][]</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#axioms">axioms</a></strong></code>
<div class="block">The axioms in the domain description as a two-dimensional array.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>private java.util.Vector<<a href="../JSHOP2/NumberedPredicate.html" title="class in JSHOP2">NumberedPredicate</a>>[]</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#protections">protections</a></strong></code>
<div class="block">The protections in the current state of the world as an array of
<code>Vector</code>s.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../JSHOP2/State.html#State(int, JSHOP2.Axiom[][])">State</a></strong>(int size,
<a href="../JSHOP2/Axiom.html" title="class in JSHOP2">Axiom</a>[][] axiomsIn)</code>
<div class="block">To initialize the state of the world.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#add(JSHOP2.Predicate)">add</a></strong>(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p)</code>
<div class="block">To add a predicate to the current state of the world.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#addProtection(JSHOP2.Predicate)">addProtection</a></strong>(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p)</code>
<div class="block">To protect a given predicate in the current state of the world.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#clear()">clear</a></strong>()</code>
<div class="block">To empty the world state.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#del(JSHOP2.Predicate)">del</a></strong>(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p)</code>
<div class="block">To delete a predicate from the current state of the world.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#delProtection(JSHOP2.Predicate)">delProtection</a></strong>(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p)</code>
<div class="block">To unprotect a given predicate.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.ArrayList<java.lang.String></code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#getState()">getState</a></strong>()</code>
<div class="block">Returns an ArrayList of strings that represents the state.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#isProtected(JSHOP2.Predicate)">isProtected</a></strong>(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p)</code>
<div class="block">To check if a predicate is protected.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../JSHOP2/MyIterator.html" title="class in JSHOP2">MyIterator</a></code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#iterator(int)">iterator</a></strong>(int head)</code>
<div class="block">To initialize and return the appropriate iterator when looking
for ways to satisfy a given predicate.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../JSHOP2/Term.html" title="class in JSHOP2">Term</a>[]</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#nextBinding(JSHOP2.Predicate, JSHOP2.MyIterator)">nextBinding</a></strong>(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p,
<a href="../JSHOP2/MyIterator.html" title="class in JSHOP2">MyIterator</a> me)</code>
<div class="block">This function returns the bindings that can satisfy a given precondition
one-by-one.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#print()">print</a></strong>()</code>
<div class="block">This function is used to print the current state of the world.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../JSHOP2/State.html#undo(java.util.Vector[])">undo</a></strong>(java.util.Vector[] delAdd)</code>
<div class="block">This function is used, in case of a backtrack, to undo the changes that
were made to the current state of the world because of the backtracked
decision.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="atoms">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>atoms</h4>
<pre>private java.util.Vector<<a href="../JSHOP2/Term.html" title="class in JSHOP2">Term</a>>[] atoms</pre>
<div class="block">The atoms in the current state of the world as an array of
<code>Vector</code>s. The array is indexed by the possible heads (i.e.,
the constant symbol that comes first) of the possible predicates.</div>
</li>
</ul>
<a name="axioms">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>axioms</h4>
<pre>private <a href="../JSHOP2/Axiom.html" title="class in JSHOP2">Axiom</a>[][] axioms</pre>
<div class="block">The axioms in the domain description as a two-dimensional array. The
array is indexed first by the head of the predicates each axiom can prove
and second by the axioms themselves.</div>
</li>
</ul>
<a name="protections">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>protections</h4>
<pre>private java.util.Vector<<a href="../JSHOP2/NumberedPredicate.html" title="class in JSHOP2">NumberedPredicate</a>>[] protections</pre>
<div class="block">The protections in the current state of the world as an array of
<code>Vector</code>s. The array is indexed by the heads of protected
predicates.</div>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="State(int, JSHOP2.Axiom[][])">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>State</h4>
<pre>public State(int size,
<a href="../JSHOP2/Axiom.html" title="class in JSHOP2">Axiom</a>[][] axiomsIn)</pre>
<div class="block">To initialize the state of the world.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>size</code> - the number of possible heads of predicates (i.e., the number of
constant symbols that can come first in a predicate).</dd><dd><code>axiomsIn</code> - the axioms in the domain description as a two-dimensional array.
The array is indexed first by the head of the predicates each
axiom can prove and second by the axioms themselves.</dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="add(JSHOP2.Predicate)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>add</h4>
<pre>public boolean add(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p)</pre>
<div class="block">To add a predicate to the current state of the world.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>p</code> - the predicate to be added.</dd>
<dt><span class="strong">Returns:</span></dt><dd><code>true</code> if the predicate was added (i.e., it was not
already in the current state of the world), <code>false</code>
otherwise.</dd></dl>
</li>
</ul>
<a name="addProtection(JSHOP2.Predicate)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addProtection</h4>
<pre>public boolean addProtection(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p)</pre>
<div class="block">To protect a given predicate in the current state of the world.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>p</code> - the predicate to be protected.</dd>
<dt><span class="strong">Returns:</span></dt><dd>this function always returns <code>true</code>.</dd></dl>
</li>
</ul>
<a name="clear()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clear</h4>
<pre>public void clear()</pre>
<div class="block">To empty the world state.</div>
</li>
</ul>
<a name="del(JSHOP2.Predicate)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>del</h4>
<pre>public int del(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p)</pre>
<div class="block">To delete a predicate from the current state of the world.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>p</code> - the predicate to be deleted.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the index of the predicate that was deleted in the
<code>Vector</code> if the predicate was deleted (i.e., it
existed in the current state of the world), -1 otherwise. This
index is used in case of a backtrack to undo this deletion by
inserting the deleted predicate right back where it used to be.</dd></dl>
</li>
</ul>
<a name="delProtection(JSHOP2.Predicate)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>delProtection</h4>
<pre>public boolean delProtection(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p)</pre>
<div class="block">To unprotect a given predicate.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>p</code> - the predicate to be unprotected.</dd>
<dt><span class="strong">Returns:</span></dt><dd><code>true</code> if the protected is unprotected successfully,
<code>false</code> otherwise (i.e., when the predicate was not
protected before).</dd></dl>
</li>
</ul>
<a name="isProtected(JSHOP2.Predicate)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isProtected</h4>
<pre>public boolean isProtected(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p)</pre>
<div class="block">To check if a predicate is protected.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>p</code> - the predicate to be checked.</dd>
<dt><span class="strong">Returns:</span></dt><dd><code>true</code> if the predicate is protected,
<code>false</code> otherwise.</dd></dl>
</li>
</ul>
<a name="iterator(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>iterator</h4>
<pre>public <a href="../JSHOP2/MyIterator.html" title="class in JSHOP2">MyIterator</a> iterator(int head)</pre>
<div class="block">To initialize and return the appropriate iterator when looking
for ways to satisfy a given predicate.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>head</code> - the index of the constant symbol that is the head of the
predicate (i.e., that comes first in the predicate).</dd>
<dt><span class="strong">Returns:</span></dt><dd>the iterator to be used to find the satisfiers for this
predicate.</dd></dl>
</li>
</ul>
<a name="nextBinding(JSHOP2.Predicate, JSHOP2.MyIterator)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>nextBinding</h4>
<pre>public <a href="../JSHOP2/Term.html" title="class in JSHOP2">Term</a>[] nextBinding(<a href="../JSHOP2/Predicate.html" title="class in JSHOP2">Predicate</a> p,
<a href="../JSHOP2/MyIterator.html" title="class in JSHOP2">MyIterator</a> me)</pre>
<div class="block">This function returns the bindings that can satisfy a given precondition
one-by-one.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>p</code> - the predicate to be satisfied.</dd><dd><code>me</code> - the iterator that keeps track of where we are with the satisfiers
so that the next time this function is called, we can take off
where we stopped last time.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the next binding as an array of terms indexed by the indeices of
the variable symbols in the given predicate.</dd></dl>
</li>
</ul>
<a name="print()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>print</h4>
<pre>public void print()</pre>
<div class="block">This function is used to print the current state of the world.</div>
</li>
</ul>
<a name="getState()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getState</h4>
<pre>public java.util.ArrayList<java.lang.String> getState()</pre>
<div class="block">Returns an ArrayList of strings that represents the state. Used
in conjunction with JSHOP2GUI
(Added 5/28/06)</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>- An ArrayList<String> representing the state</dd></dl>
</li>
</ul>
<a name="undo(java.util.Vector[])">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>undo</h4>
<pre>public void undo(java.util.Vector[] delAdd)</pre>
<div class="block">This function is used, in case of a backtrack, to undo the changes that
were made to the current state of the world because of the backtracked
decision.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>delAdd</code> - a 4-member array of type <code>Vector</code>. These four
members are the deleted atoms, the added atoms, the deleted
protections and the added protections respectively.</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../JSHOP2/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-all.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../JSHOP2/SolverThread.html" title="class in JSHOP2"><span class="strong">Prev Class</span></a></li>
<li><a href="../JSHOP2/StdLib.html" title="class in JSHOP2"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?JSHOP2/State.html" target="_top">Frames</a></li>
<li><a href="State.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| jormunmor/doctorado | JSHOP2/doc/JSHOP2/State.html | HTML | apache-2.0 | 22,009 |
using SolrNetLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using SolrNetLight.Facet;
namespace SolrNetLight
{
[DataContract]
public class SolrResponse<T>
{
[DataMember(Name="response")]
public SolrResponseBase<T> Response { get; set; }
[DataMember(Name = "facet_counts")]
public FacetCounts Facets { get; set; }
}
}
| SolrNetLight/SolrNetLight | SolrNetLight/SolrResponse.cs | C# | apache-2.0 | 453 |
package com.action.design.pattern.chain;
/**
* 创建不同类型的记录器。赋予它们不同的错误级别,并在每个记录器中设置下一个记录器。每个记录器中的下一个记录器代表的是链的一部分。
* Created by wuyunfeng on 2017/6/15.
*/
public class ChainPatternDemo {
private static AbstractLogger getChainOfLoggers() {
AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);
AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG);
AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO);
errorLogger.setNextLogger(fileLogger);
fileLogger.setNextLogger(consoleLogger);
return errorLogger;
}
public static void main(String[] args) {
AbstractLogger loggerChain = getChainOfLoggers();
loggerChain.logMessage(AbstractLogger.INFO, "This is an information.");
loggerChain.logMessage(AbstractLogger.DEBUG,
"This is an debug level information.");
loggerChain.logMessage(AbstractLogger.ERROR,
"This is an error information.");
}
}
| pearpai/java_action | src/main/java/com/action/design/pattern/chain/ChainPatternDemo.java | Java | apache-2.0 | 1,140 |
/*
* Copyright (c) 2021, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.descriptor;
import boofcv.struct.feature.TupleDesc_B;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("ResultOfMethodCallIgnored") @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2)
@Measurement(iterations = 5)
@State(Scope.Benchmark)
@Fork(value = 1)
public class BenchmarkDescriptorDistance {
static int NUM_FEATURES = 10000;
List<TupleDesc_B> binaryA = new ArrayList<>();
List<TupleDesc_B> binaryB = new ArrayList<>();
HammingTable16 table = new HammingTable16();
@Setup public void setup() {
Random rand = new Random(234234);
binaryA = new ArrayList<>();
binaryB = new ArrayList<>();
for (int i = 0; i < NUM_FEATURES; i++) {
binaryA.add(randomFeature(rand));
binaryB.add(randomFeature(rand));
}
}
@Benchmark public void hammingTable() {
for (int i = 0; i < binaryA.size(); i++) {
tableScore(binaryA.get(i), binaryB.get(i));
}
}
private int tableScore( TupleDesc_B a, TupleDesc_B b ) {
int score = 0;
for (int i = 0; i < a.data.length; i++) {
int dataA = a.data[i];
int dataB = b.data[i];
score += table.lookup((short)dataA, (short)dataB);
score += table.lookup((short)(dataA >> 16), (short)(dataB >> 16));
}
return score;
}
@Benchmark public void equationOld() {
for (int i = 0; i < binaryA.size(); i++) {
ExperimentalDescriptorDistance.hamming(binaryA.get(i), binaryB.get(i));
}
}
@Benchmark public void equation() {
for (int i = 0; i < binaryA.size(); i++) {
DescriptorDistance.hamming(binaryA.get(i), binaryB.get(i));
}
}
private TupleDesc_B randomFeature( Random rand ) {
TupleDesc_B feat = new TupleDesc_B(512);
for (int j = 0; j < feat.data.length; j++) {
feat.data[j] = rand.nextInt();
}
return feat;
}
public static void main( String[] args ) throws RunnerException {
Options opt = new OptionsBuilder()
.include(BenchmarkDescriptorDistance.class.getSimpleName())
.warmupTime(TimeValue.seconds(1))
.measurementTime(TimeValue.seconds(1))
.build();
new Runner(opt).run();
}
}
| lessthanoptimal/BoofCV | main/boofcv-feature/src/benchmark/java/boofcv/alg/descriptor/BenchmarkDescriptorDistance.java | Java | apache-2.0 | 3,105 |
package adamin90.com.wpp.model.mostsearch;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
@Generated("org.jsonschema2pojo")
public class MostSearchData {
@SerializedName("data")
@Expose
private List<Datum> data = new ArrayList<Datum>();
@SerializedName("code")
@Expose
private Integer code;
/**
*
* @return
* The data
*/
public List<Datum> getData() {
return data;
}
/**
*
* @param data
* The data
*/
public void setData(List<Datum> data) {
this.data = data;
}
/**
*
* @return
* The code
*/
public Integer getCode() {
return code;
}
/**
*
* @param code
* The code
*/
public void setCode(Integer code) {
this.code = code;
}
}
| adamin1990/MaterialWpp | wpp/app/src/main/java/adamin90/com/wpp/model/mostsearch/MostSearchData.java | Java | apache-2.0 | 971 |
<html dir="LTR">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<title>ConfigFileExtension Property</title>
<xml>
</xml>
<link rel="stylesheet" type="text/css" href="MSDN.css" />
</head>
<body id="bodyID" class="dtBODY">
<div id="nsbanner">
<div id="bannerrow1">
<table class="bannerparthead" cellspacing="0">
<tr id="hdr">
<td class="runninghead">Apache log4net SDK Documentation - Microsoft .NET Framework 4.0</td>
<td class="product">
</td>
</tr>
</table>
</div>
<div id="TitleRow">
<h1 class="dtH1">XmlConfiguratorAttribute.ConfigFileExtension Property</h1>
</div>
</div>
<div id="nstext">
<p> Gets or sets the extension of the configuration file. </p>
<div class="syntax">
<span class="lang">[Visual Basic]</span>
<br />Public Property ConfigFileExtension As <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemStringClassTopic.htm">String</a></div>
<div class="syntax">
<span class="lang">[C#]</span>
<br />public <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemStringClassTopic.htm">string</a> ConfigFileExtension {get; set;}</div>
<p>
</p>
<h4 class="dtH4">Property Value</h4>
<p> The extension of the configuration file. </p>
<h4 class="dtH4">Remarks</h4>
<p> If specified this is the extension for the configuration file. The path to the config file is built by using the <b>application base</b> directory (<a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemAppDomainClassBaseDirectoryTopic.htm">BaseDirectory</a>), the <b>assembly file name</b> and the config file extension. </p>
<p> If the <b>ConfigFileExtension</b> is set to <code>MyExt</code> then possible config file names would be: <code>MyConsoleApp.exe.MyExt</code> or <code>MyClassLibrary.dll.MyExt</code>. </p>
<p> The <a href="log4net.Config.XmlConfiguratorAttribute.ConfigFile.html">ConfigFile</a> takes priority over the <b>ConfigFileExtension</b>. </p>
<h4 class="dtH4">See Also</h4><p><a href="log4net.Config.XmlConfiguratorAttribute.html">XmlConfiguratorAttribute Class</a> | <a href="log4net.Config.html">log4net.Config Namespace</a></p><object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"><param name="Keyword" value="ConfigFileExtension property"></param><param name="Keyword" value="ConfigFileExtension property, XmlConfiguratorAttribute class"></param><param name="Keyword" value="XmlConfiguratorAttribute.ConfigFileExtension property"></param></object><hr /><div id="footer"><a href='http://logging.apache.org/log4net/'>Copyright 2004-2013 The Apache Software Foundation.</a><br></br>Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.</div></div>
</body>
</html> | gersonkurz/manualisator | manualisator/log4net-1.2.13/doc/release/sdk/log4net.Config.XmlConfiguratorAttribute.ConfigFileExtension.html | HTML | apache-2.0 | 3,146 |
var activeElements = [];
var sleepElements = [];
var promises = [];
$.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/assetdatabases/D0EgxEhIf8KUieOFdFcX1IWQZ8qIGYDdE0m5aJCwNb4x_gSlVQSVRFUjAwMVxQSUZJVE5FU1M/elements", {
type : 'GET',
headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
success: function(results){
for (var i = 0; i < results.Items.length; i++) {
var item = results.Items[i];
getSubElements(item);
}
}
}).done(function(){
$.when.apply($,promises).done(function(){
spinner.stop(target);
var blackout = document.getElementById('blackout');
$('#blackout').css('opacity', '0');
$('#blackout').css('width', '0%');
$('#blackout').css('height', '0%');
});
});
var getSubElements = function(personElement){
promises.push($.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + personElement.WebId + "/elements", {
type : 'GET',
headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
success: function(results){
for (var i = 0; i < results.Items.length; i++) {
var innerItem = results.Items[i];
if (innerItem.TemplateName == "Fitbit Activity Template") {
getFitbitActivityAttributes({
Person : personElement.Name,
Child : "Fitbit Activity",
ChildWebId : innerItem.WebId
});
} else if (innerItem.TemplateName == "Fitbit Sleep Template") {
getFitbitSleepAttributes({
Person : personElement.Name,
Child : "Fitbit Sleep",
ChildWebId : innerItem.WebId
});
}
}}}));
}
var getFitbitActivityAttributes = function(object) {
promises.push($.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + object.ChildWebId + "/attributes",{
type : 'GET',
headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
success: function(results){
object.Attributes = [];
activeElements.push(object);
for (var i = 0; i < results.Items.length; i++) {
var attribute = results.Items[i];
object.Attributes.push({
Attribute : attribute.Name,
AttributeWebId : attribute.WebId
});
};
}
}));
}
var getFitbitSleepAttributes = function(object) {
promises.push($.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + object.ChildWebId + "/attributes",{
type : 'GET',
headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
success: function(results){
object.Attributes = [];
sleepElements.push(object);
for (var i = 0; i < results.Items.length; i++) {
var attribute = results.Items[i];
object.Attributes.push({
Attribute : attribute.Name,
AttributeWebId : attribute.WebId
});
};
}
}));
}
| dstcontrols/UnhandledException | customJS/piWebAPI.js | JavaScript | apache-2.0 | 2,755 |
import { Seq, Set as ISet } from 'immutable';
import { atom, unwrap } from '../derivable';
import { equals } from './equals';
describe('util/equals', () => {
it('should check equality of primitives', () => {
expect(equals(NaN, NaN)).toBe(true);
expect(equals(4, 2 + 2)).toBe(true);
expect(equals(0, 0)).toBe(true);
expect(equals('abcd', 'ab' + 'cd')).toBe(true);
});
it('should check identity on ordinary object', () => {
expect(equals({}, {})).toBe(false);
expect(equals([], [])).toBe(false);
const arr: never[] = [];
const obj = {};
expect(equals(arr, arr)).toBe(true);
expect(equals(obj, obj)).toBe(true);
});
it('should check equality on immutable objects', () => {
const seq = Seq.Indexed.of(1, 2, 3);
const set = ISet.of(1, 2, 3);
expect(equals(seq, set)).toBe(false);
expect(equals(seq.toSetSeq(), set)).toBe(true);
expect(equals(seq, [1, 2, 3])).toBe(false);
});
it('should check the equality of derivables', () => {
const a = atom('foo');
const b = atom('foo');
const notA = atom('bar');
const aDerivable = a.derive(v => v.toUpperCase());
const bDerivable = b.derive(v => v.toUpperCase());
const withObj1 = atom({ hello: 'world' });
const withObj2 = atom({ hello: 'world' });
expect(equals(a, a)).toBe(true);
expect(equals(b, b)).toBe(true);
expect(equals(a, notA)).toBe(false);
expect(equals(a, b)).toBe(false);
expect(equals(aDerivable, bDerivable)).toBe(false);
expect(equals(withObj1, withObj1)).toBe(true);
expect(equals(withObj1, withObj2)).toBe(false);
});
it('should test for reference equality, not derivable value equality', () => {
const personA = { name$: atom('Sherlock') };
const personB = { name$: atom('Sherlock') };
const person$ = atom(personA);
const nameOfPerson$ = person$.derive(p => p.name$).derive(unwrap).autoCache();
expect(nameOfPerson$.get()).toBe('Sherlock');
person$.set(personB);
expect(nameOfPerson$.get()).toBe('Sherlock');
personB.name$.set('Moriarty');
expect(nameOfPerson$.get()).toBe('Moriarty');
});
});
| politie/sherlock | src/utils/equals.test.ts | TypeScript | apache-2.0 | 2,307 |
<!DOCTYPE html>
<html>
<head>
<title id="titre"></title>
<meta charset="UTF-8"/>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="../../dist/jsRealB.js"></script>
<!-- to ease debugging we load each file separately -/->
<script src="../../data/lexicon-fr.js"></script>
<script src="../../data/rule-fr.js"></script>
<script src="../../data/lexicon-en.js"></script>
<script src="../../data/rule-en.js"></script>
<script src="../../build/Utils.js"></script>
<script src="../../build/Constituent.js"></script>
<script src="../../build/Phrase.js"></script>
<script src="../../build/Terminal.js"></script>
<script src="../../build/Date.js"></script>
<script src="../../build/Number.js"></script>
<script src="../../build/Warnings.js"></script>
<!-/- end of separate loading -->
<script>
var max=4;
function kmsAPied(n){
return NP(NO(n).dOpt({nat:true}),N('kilomètre'),
PP(P("à"),NP(N("pied"))));
}
function ligne(l){
return $("<div/>").css("text-align","center").text(l.toString());
}
function refrain(){
var s1=S(NP(D("le"),N("peinture"),
PP(P("à"),D("le"),N("huile"))).a(","),
S(Pro("ce"), VP(V("être").t("p"),Adv("bien"),A("difficile"))));
var s2=S('mais',
Pro("ce"),
VP(V("être").t("p"),
AP("bien plus",A("beau"),
SP(Pro("que"),
NP(D("le"),N("peinture"),
PP(P("à"),D("le"),N("eau")) ) ) )
)
);
return $("<p/>").append(ligne(s1)).append(ligne(s2));
}
function generer() {
loadFr();
var $body=$("body");
var m1=S(kmsAPied(1));
$("#titre").text(m1);
var h1=$("<h1/>").css("text-align","center").text(m1)
$body.append(h1);
var use=V("user").t("p");
var s1=S(Pro("ça"),use);
var s2=S(s1,NP(D("le"),N("soulier").n("p")));
for(var i=1;i<=max;i++){
var kmap=kmsAPied(i).a(",");
var $lignes=$("<b/>").append("<p/>");
$lignes.append(ligne(S(kmap,s1,s1))).append(ligne(S(kmap,s2)));
$body.append($lignes);
$body.append(refrain());
};
$body.append(ligne("..."));
};
$(document).ready(function() {
generer();
});
</script>
</head>
<body>
</body>
</html> | rali-udem/JSrealB | demos/KilometresAPied/index.html | HTML | apache-2.0 | 2,786 |
# Config
For each project a list of branches can be configured, to which submits should not be allowed, until a merge commit has been merged.
| selevt/gerrit-merge-nosubmit | src/main/resources/Documentation/config.md | Markdown | apache-2.0 | 143 |
// Generated from /POI/java/org/apache/poi/hpsf/VariantBool.java
#pragma once
#include <fwd-POI.hpp>
#include <org/apache/poi/hpsf/fwd-POI.hpp>
#include <org/apache/poi/util/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct default_init_tag;
class poi::hpsf::VariantBool
: public virtual ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
static ::poi::util::POILogger* LOG_;
public: /* package */
static constexpr int32_t SIZE { int32_t(2) };
private:
bool _value { };
protected:
void ctor();
public: /* package */
virtual void read(::poi::util::LittleEndianByteArrayInputStream* lei);
virtual bool getValue();
virtual void setValue(bool value);
// Generated
VariantBool();
protected:
VariantBool(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
static void clinit();
private:
static ::poi::util::POILogger*& LOG();
virtual ::java::lang::Class* getClass0();
};
| pebble2015/cpoi | src/org/apache/poi/hpsf/VariantBool.hpp | C++ | apache-2.0 | 992 |
package com.hangon.saying.viewPager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.example.fd.ourapplication.R;
import com.hangon.common.Constants;
import com.hangon.common.MyApplication;
import com.hangon.common.ViewHolder;
import com.hangon.common.VolleyBitmapCache;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2016/5/31.
*/
public class GradAdapter extends BaseAdapter implements AbsListView.OnScrollListener {
Context context;
List list = new ArrayList();
private static ImageLoader mImageLoader; // imageLoader对象,用来初始化NetworkImageView
/**
* 记录每个子项的高度。
*/
private int mItemHeight = 0;
GradAdapter(Context context, List list) {
this.context = context;
this.list = list;
mImageLoader = new ImageLoader(MyApplication.queues, new VolleyBitmapCache()); // 初始化一个loader对象,可以进行自定义配置
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
ViewGradHolder gradHolder;
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
gradHolder = new ViewGradHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.carlife_grade_content, null);
gradHolder.img = (ImageView) convertView.findViewById(R.id.item_grida_image);
convertView.setTag(gradHolder);
} else {
gradHolder = (ViewGradHolder) convertView.getTag();
}
NetworkImageView networkImageView = (NetworkImageView) gradHolder.img;
// 设置默认的图片
networkImageView.setDefaultImageResId(R.drawable.default_photo);
// 设置图片加载失败后显示的图片
networkImageView.setErrorImageResId(R.drawable.error_photo);
if (list.get(position) != null && !list.get(position).equals("")) {
//getImag(list.get(position).toString());
// 开始加载网络图片
networkImageView.setImageUrl(Constants.LOAD_SAYING_IMG_URL + list.get(position), mImageLoader);
}
return convertView;
}
class ViewGradHolder {
ImageView img;
}
private void getImag(String path) {
String url = Constants.LOAD_SAYING_IMG_URL + path;
ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
gradHolder.img.setImageBitmap(bitmap);
}
}, 0, 0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(context, "说说图片加载失败", Toast.LENGTH_SHORT).show();
}
});
MyApplication.getHttpQueues().add(request);
}
/**
* 设置item子项的高度。
*/
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
notifyDataSetChanged();
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// 仅当GridView静止时才去下载图片,GridView滑动时取消所有正在下载的任务
if (scrollState == SCROLL_STATE_IDLE) {
// loadBitmaps(mFirstVisibleItem, mVisibleItemCount);
} else {
// cancelAllTasks();
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
}
| TangZuopeng/OurApplication | app/src/main/java/com/hangon/saying/viewPager/GradAdapter.java | Java | apache-2.0 | 4,468 |
/*
* MaiKe Labs (2016 - 2026)
*
* Written by Jack Tan <[email protected]>
*
* Connect VCC of the SSD1306 OLED to 3.3V
* Connect GND to Ground
* Connect SCL to i2c clock - GPIO21
* Connect SDA to i2c data - GPIO22
* Connect DC to GND (The scanned i2c address is 0x3C)
*
*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE); // I2C / TWI
void draw(void)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr(0, 22, "Hello World!");
}
void ssd1306_task(void *pvParameter)
{
// assign default color value
if (u8g.getMode() == U8G_MODE_R3G3B2) {
u8g.setColorIndex(255); // white
} else if (u8g.getMode() == U8G_MODE_GRAY2BIT) {
u8g.setColorIndex(3); // max intensity
} else if (u8g.getMode() == U8G_MODE_BW) {
u8g.setColorIndex(1); // pixel on
} else if (u8g.getMode() == U8G_MODE_HICOLOR) {
u8g.setHiColorByRGB(255, 255, 255);
}
while(1) {
// picture loop
u8g.firstPage();
do {
draw();
} while (u8g.nextPage());
draw();
vTaskDelay(1000 / portTICK_RATE_MS);
}
}
extern "C" void app_main()
{
nvs_flash_init();
printf("Welcome to Noduino!\r\n");
printf("Start to test SSD1306 OLED!\r\n");
xTaskCreate(&ssd1306_task, "ssd1306_task", 2048, NULL, 5, NULL);
}
| icamgo/esp-idf | examples/10_ssd1306_hello/main/main.cpp | C++ | apache-2.0 | 1,359 |
<table border="1" id="table1" style="border-collapse: collapse">
<tr>
<td height="25" align="center"><span style="font-size: 16px">三国</span></td>
<td height="25" align="center"><span style="font-size: 16px">公元245年</span></td>
<td height="25" align="center"><span style="font-size: 16px">乙丑</span></td>
<td height="25px" align="center"><span style="font-size: 16px">正始六年</span></td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>历史纪事</b> </td>
<td>
<div>吴太子和与鲁王霸不睦
初,吴帝孙权使吴太子和与弟鲁王霸同宫居隹,礼秩相同,群臣多以为不妥。权乃令二人分宫,二子因而有隙。鲁王霸曲意结交当时名士,杨竺、全寄、吴安、孙奇等均为其党。于是由二宫僚属、侍御、宾客起,分为两党,延至大臣。权闻之,以需专心精学为由,禁断二子宾客往来。全公主(孙鲁班、全琮妻)与太子和母王夫人有隙,亦数次谮毁太子,太子宠益衰。陆逊上疏,认为太子为正统,鲁王为藩臣,当使有别。权不悦。太常顾谭亦上疏陈嫡庶之别,于是鲁王与谭有隙。芍陂(今安徽泰县南)战后,全琮(全寄父)子端、绪与顾弟承及子休争功,谮毁二人于孙权,权徙谭、承、休于交州,又追赐休死,吴赤乌八年(245)初,太子太傅吾粲请使鲁王出镇夏口(今湖北武汉),令杨竺等不得在京师,并数次与陆逊通消息;鲁王与杨竺共谮之,权怒,收粲下狱,诛。孙权又数次遣中使责问陆逊,吴赤乌八年二月,陆逊愤恨而卒。
马茂谋杀孙权不遂
吴赤乌八年(245)七月,吴将马茂与兼符节令朱贞、无难督虞钦、牙门将朱志等合谋,欲乘孙权与公卿诸将入苑射猎,权在苑中,而众臣在门外未入时,朱贞持节宣诏,尽收众臣,而由马茂入苑击权,分据宫中及石头坞,遣人报魏。事泄,均被族诛。马茂原为魏钟离(今安徽凤阳东北)长,叛降吴,为吴征西将军,领九江太守、外部督,封侯,领兵千人。
吴凿破岗渎
吴赤乌八年(245)八月,遣校尉陈勋率屯田兵及作士三万人,凿破岗渎,开通从句容(今江苏),以南向东至云阳(今江苏丹阳)西城的河道,使航路可从建业直通吴会。并开市以会商旅。
魏诏学者课试王郎《易传》
魏正始六年(245)十二月初五(辛亥),诏以故司徒王郎所作《易传》课试学者。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>文化纪事</b> </td>
<td>
<div>缪袭卒
缪袭(186——245)字熙伯,东海兰陵(今山东苍山兰陵镇)人。曾任职御史大夫府,官至尚书,光禄勋。历仕魏四世,有才学,多所著述。魏改汉乐府十二曲为魏鼓吹曲,由袭作词,为操、丕、睿颂功德;诗作以《挽歌》较著名,另存《喜霁赋》、《青龙赋》等文数篇。原有集五卷,均佚。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>杂谭逸事</b> </td>
<td>
<div>陆逊卒
陆逊(183——245),本名议,字伯言,吴郡吴(今江苏苏州)人。世为江东大族,孙策婿。初为孙权幕府,后累迁为右部督,攻丹杨山越,得精兵数万人,汉建安二十四年(219),与吕蒙定袭取荆州之计,擒杀关羽。吴黄武元年(222),陆逊为大都督,率兵五万西拒刘备,坚守七八个月不战,等蜀军疲,乃顺风放火,取得夷陵之战的胜利。领荆州牧,封江陵侯。吴黄武七年,又大破魏大司马曹休于石亭(今安徽怀宁、桐城间)。吴蜀连和,孙权每与蜀书,常先交陆逊,有所不安,便令改定。吴黄龙元年(229)拜上大将军、右都护。同年,孙权迁都建业,使逊留武昌,辅太子登。吴赤乌七年(244)代顾雍为丞相。仍留驻武昌。时吴太子和与鲁王霸争位,逊数上疏陈嫡庶之分,权不听。逊外甥顾谭、顾承、姚信亦以亲附太子遭流放。逊卒后,孙权以杨竺所白陆逊二十事一一问陆逊子抗,抗事事条答,权意乃稍解。
赵俨卒
赵俨(171——245),字伯然,颍川阳翟(今河南禹县)人。东汉末避乱荆州。建安二年(197),投曹操,为司空掾属主簿。从曹操征荆州。建安二十四年,以议郎与徐晃至樊城助曹仁拒关羽。曹丕即位,俨为侍中,领河东(今山西夏县东北)太守。曹休拒孙权,以俨为军师,曹睿即位,进封都乡侯,齐王曹芳即位,以俨都督雍、凉诸军事。魏正始四年(243)老病求还,六年,迁司空。卒谥穆侯。赵俨与同郡辛毗、陈群、杜袭齐名,号为辛、陈、杜、赵。
蒋琬卒
蜀延熙八年(一说为延熙九年,245——246)十一月,大司马蒋碗卒。蜀帝刘禅自摄国事。蒋琬(?——245),字公琰,零陵湘乡人。以荆州书佐随刘备入蜀,除广都(今四川成都东南,一说今四川双流)长。刘备偶至广都,见蒋琬不理公事,时又酒醉,大怒,欲罪之。诸葛亮认为蒋琬为社稷之器、非百里之才,为琬求请。刘备堍亮,但免蒋琬官而已。不久,又除什邡(今四川)令。刘备称汉中王,琬入为尚书郎。蜀建兴元年(223),琬为丞相东曹掾,迁为参军。八年,为长史,加抚军将军。诸葛亮数次北代,琬常足兵足食以相供给。亮卒,以琬为尚书令,加行都护,假节,领益州牧,迁大将军,录尚书事,封字阳亭侯。蜀延熙二年(239),加为大司马。卒谥恭侯。
董允卒
蜀延熙八年(一说为延熙九年,245——246),蜀守尚书令董允卒。董允(?——245),字休昭,南郡枝江(今湖北)人。刘备立太子,允为太子舍人,徙太子洗马。后主刘祥即位,迁黄门侍郎。诸葛亮将北伐,驻汉中,虑后主年轻,是非不别,上疏请以允任宫省事。迁侍中,领虎贲中郎将,统令宿亲兵。董允事事防制,匡正后主。后主常欲采择宫女,允以为古时天子后妃之数不过十二,今后宫嫔、嫱已具,不宜增加,终不听。后主畏怕之。及后主渐长,宠宦人黄皓,允常正色语后主,并多次责问黄皓,皓畏允,不敢为非。终允之世,皓位不过黄门丞。蜀延熙六年(243),加辅国将军,七年,以侍中守尚书令,为大将军费祎副贰。卒后,黄皓渐操弄权柄,终至灭国。蜀人无不追思允。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>注释</b></td>
<td>
<div>延熙八年 赤乌八年</div></td>
</tr>
</table>
</td>
</tr>
<tr>
</tr></table>
| ilearninging/xxhis | all/1172.html | HTML | apache-2.0 | 7,126 |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
# Documentation: https://github.com/hunspell/hyphen/blob/21127cc8493a68d4fe9adbb71377b469b4f2b550/doc/tb87nemeth.pdf
module TwitterCldr
module Shared
class Hyphenator
class UnsupportedLocaleError < StandardError; end
BASE_RESOURCE_PATH = %w(shared hyphenation).freeze
DEFAULT_LEFT_HYPHEN_MIN = 2
DEFAULT_RIGHT_HYPHEN_MIN = 2
DEFAULT_NO_HYPHEN = "-'’".freeze
class << self
def get(locale)
locale = find_supported_locale(locale)
unless locale
raise UnsupportedLocaleError,
"'#{locale}' is not a supported hyphenation locale"
end
cache[locale] ||= begin
resource = resource_for(locale)
new(resource[:rules], locale, resource[:options])
end
end
def supported_locale?(locale)
!!find_supported_locale(locale)
end
def supported_locales
@supported_locales ||= begin
absolute_resource_path = TwitterCldr.absolute_resource_path(
File.join(BASE_RESOURCE_PATH)
)
files = Dir.glob(File.join(absolute_resource_path, '*.yml'))
files.map { |f| File.basename(f).chomp('.yml') }
end
end
private
def find_supported_locale(locale)
maximized_locale = Locale.parse(locale.to_s).maximize
maximized_locale.permutations('-').find do |locale_candidate|
TwitterCldr.resource_exists?(
*BASE_RESOURCE_PATH, locale_candidate
)
end
end
def cache
@cache ||= {}
end
def resource_for(locale)
TwitterCldr.get_resource(*BASE_RESOURCE_PATH, locale)
end
end
attr_reader :rules, :locale, :options, :trie
def initialize(rules, locale, options)
@rules = rules
@locale = locale
@options = options
@trie = build_trie_from(rules)
end
# 0x00AD is a soft hyphen
def hyphenate(text, hyphen = "\u00AD")
each_chunk(text).to_a.join(hyphen)
end
def each_chunk(text)
if block_given?
last_pos = 0
each_position(text) do |pos|
yield text[last_pos...pos].tap { last_pos = pos }
end
if last_pos < text.size
yield text[last_pos..text.size]
end
else
to_enum(__method__, text)
end
end
def each_position(text)
if block_given?
text = ".#{text}."
break_weights = break_weights_for(text)
left = left_hyphen_min
right = text.size - right_hyphen_min - 2
(left...right).each do |idx|
yield idx if break_weights[idx].odd?
end
else
to_enum(__method__, text)
end
end
private
def break_weights_for(text)
break_weights = Array.new(text.size - 1, 0)
text.each_char.with_index do |char, idx|
subtrie = trie.root
counter = idx
while subtrie
subtrie = subtrie.child(text[counter])
counter += 1
if subtrie && subtrie.has_value?
update_break_weights(subtrie.value, break_weights, idx)
end
end
end
remove_illegal_hyphens(break_weights, text)
end
def update_break_weights(pattern, break_weights, start_idx)
pattern_idx = 0
pattern.each_char do |segment|
if segment =~ /\d/
int_seg = segment.to_i
idx = (start_idx + pattern_idx) - 1
break if idx >= break_weights.size
break_weights[idx] = if break_weights[idx] > int_seg
break_weights[idx]
else
int_seg
end
else
pattern_idx += 1
end
end
end
def remove_illegal_hyphens(break_weights, text)
break_weights.map.with_index do |break_weight, idx|
next break_weight if idx.zero?
next 0 if no_hyphen.include?(text[idx - 1])
break_weight
end
end
def left_hyphen_min
@left_hyphen_min ||=
options.fetch(:lefthyphenmin, DEFAULT_LEFT_HYPHEN_MIN).to_i
end
def right_hyphen_min
@right_hyphen_min ||=
options.fetch(:righthyphenmin, DEFAULT_RIGHT_HYPHEN_MIN).to_i
end
def no_hyphen
@no_hyphen ||= options.fetch(:nohyphen, DEFAULT_NO_HYPHEN)
end
def build_trie_from(rules)
TwitterCldr::Utils::Trie.new.tap do |trie|
rules.each do |rule|
trie.add(rule.gsub(/\d/, '').each_char, rule)
end
end
end
end
end
end
| twitter/twitter-cldr-rb | lib/twitter_cldr/shared/hyphenator.rb | Ruby | apache-2.0 | 4,872 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/mediaconvert/model/DashIsoGroupSettings.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace MediaConvert
{
namespace Model
{
DashIsoGroupSettings::DashIsoGroupSettings() :
m_additionalManifestsHasBeenSet(false),
m_audioChannelConfigSchemeIdUri(DashIsoGroupAudioChannelConfigSchemeIdUri::NOT_SET),
m_audioChannelConfigSchemeIdUriHasBeenSet(false),
m_baseUrlHasBeenSet(false),
m_destinationHasBeenSet(false),
m_destinationSettingsHasBeenSet(false),
m_encryptionHasBeenSet(false),
m_fragmentLength(0),
m_fragmentLengthHasBeenSet(false),
m_hbbtvCompliance(DashIsoHbbtvCompliance::NOT_SET),
m_hbbtvComplianceHasBeenSet(false),
m_imageBasedTrickPlay(DashIsoImageBasedTrickPlay::NOT_SET),
m_imageBasedTrickPlayHasBeenSet(false),
m_imageBasedTrickPlaySettingsHasBeenSet(false),
m_minBufferTime(0),
m_minBufferTimeHasBeenSet(false),
m_minFinalSegmentLength(0.0),
m_minFinalSegmentLengthHasBeenSet(false),
m_mpdProfile(DashIsoMpdProfile::NOT_SET),
m_mpdProfileHasBeenSet(false),
m_ptsOffsetHandlingForBFrames(DashIsoPtsOffsetHandlingForBFrames::NOT_SET),
m_ptsOffsetHandlingForBFramesHasBeenSet(false),
m_segmentControl(DashIsoSegmentControl::NOT_SET),
m_segmentControlHasBeenSet(false),
m_segmentLength(0),
m_segmentLengthHasBeenSet(false),
m_segmentLengthControl(DashIsoSegmentLengthControl::NOT_SET),
m_segmentLengthControlHasBeenSet(false),
m_writeSegmentTimelineInRepresentation(DashIsoWriteSegmentTimelineInRepresentation::NOT_SET),
m_writeSegmentTimelineInRepresentationHasBeenSet(false)
{
}
DashIsoGroupSettings::DashIsoGroupSettings(JsonView jsonValue) :
m_additionalManifestsHasBeenSet(false),
m_audioChannelConfigSchemeIdUri(DashIsoGroupAudioChannelConfigSchemeIdUri::NOT_SET),
m_audioChannelConfigSchemeIdUriHasBeenSet(false),
m_baseUrlHasBeenSet(false),
m_destinationHasBeenSet(false),
m_destinationSettingsHasBeenSet(false),
m_encryptionHasBeenSet(false),
m_fragmentLength(0),
m_fragmentLengthHasBeenSet(false),
m_hbbtvCompliance(DashIsoHbbtvCompliance::NOT_SET),
m_hbbtvComplianceHasBeenSet(false),
m_imageBasedTrickPlay(DashIsoImageBasedTrickPlay::NOT_SET),
m_imageBasedTrickPlayHasBeenSet(false),
m_imageBasedTrickPlaySettingsHasBeenSet(false),
m_minBufferTime(0),
m_minBufferTimeHasBeenSet(false),
m_minFinalSegmentLength(0.0),
m_minFinalSegmentLengthHasBeenSet(false),
m_mpdProfile(DashIsoMpdProfile::NOT_SET),
m_mpdProfileHasBeenSet(false),
m_ptsOffsetHandlingForBFrames(DashIsoPtsOffsetHandlingForBFrames::NOT_SET),
m_ptsOffsetHandlingForBFramesHasBeenSet(false),
m_segmentControl(DashIsoSegmentControl::NOT_SET),
m_segmentControlHasBeenSet(false),
m_segmentLength(0),
m_segmentLengthHasBeenSet(false),
m_segmentLengthControl(DashIsoSegmentLengthControl::NOT_SET),
m_segmentLengthControlHasBeenSet(false),
m_writeSegmentTimelineInRepresentation(DashIsoWriteSegmentTimelineInRepresentation::NOT_SET),
m_writeSegmentTimelineInRepresentationHasBeenSet(false)
{
*this = jsonValue;
}
DashIsoGroupSettings& DashIsoGroupSettings::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("additionalManifests"))
{
Array<JsonView> additionalManifestsJsonList = jsonValue.GetArray("additionalManifests");
for(unsigned additionalManifestsIndex = 0; additionalManifestsIndex < additionalManifestsJsonList.GetLength(); ++additionalManifestsIndex)
{
m_additionalManifests.push_back(additionalManifestsJsonList[additionalManifestsIndex].AsObject());
}
m_additionalManifestsHasBeenSet = true;
}
if(jsonValue.ValueExists("audioChannelConfigSchemeIdUri"))
{
m_audioChannelConfigSchemeIdUri = DashIsoGroupAudioChannelConfigSchemeIdUriMapper::GetDashIsoGroupAudioChannelConfigSchemeIdUriForName(jsonValue.GetString("audioChannelConfigSchemeIdUri"));
m_audioChannelConfigSchemeIdUriHasBeenSet = true;
}
if(jsonValue.ValueExists("baseUrl"))
{
m_baseUrl = jsonValue.GetString("baseUrl");
m_baseUrlHasBeenSet = true;
}
if(jsonValue.ValueExists("destination"))
{
m_destination = jsonValue.GetString("destination");
m_destinationHasBeenSet = true;
}
if(jsonValue.ValueExists("destinationSettings"))
{
m_destinationSettings = jsonValue.GetObject("destinationSettings");
m_destinationSettingsHasBeenSet = true;
}
if(jsonValue.ValueExists("encryption"))
{
m_encryption = jsonValue.GetObject("encryption");
m_encryptionHasBeenSet = true;
}
if(jsonValue.ValueExists("fragmentLength"))
{
m_fragmentLength = jsonValue.GetInteger("fragmentLength");
m_fragmentLengthHasBeenSet = true;
}
if(jsonValue.ValueExists("hbbtvCompliance"))
{
m_hbbtvCompliance = DashIsoHbbtvComplianceMapper::GetDashIsoHbbtvComplianceForName(jsonValue.GetString("hbbtvCompliance"));
m_hbbtvComplianceHasBeenSet = true;
}
if(jsonValue.ValueExists("imageBasedTrickPlay"))
{
m_imageBasedTrickPlay = DashIsoImageBasedTrickPlayMapper::GetDashIsoImageBasedTrickPlayForName(jsonValue.GetString("imageBasedTrickPlay"));
m_imageBasedTrickPlayHasBeenSet = true;
}
if(jsonValue.ValueExists("imageBasedTrickPlaySettings"))
{
m_imageBasedTrickPlaySettings = jsonValue.GetObject("imageBasedTrickPlaySettings");
m_imageBasedTrickPlaySettingsHasBeenSet = true;
}
if(jsonValue.ValueExists("minBufferTime"))
{
m_minBufferTime = jsonValue.GetInteger("minBufferTime");
m_minBufferTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("minFinalSegmentLength"))
{
m_minFinalSegmentLength = jsonValue.GetDouble("minFinalSegmentLength");
m_minFinalSegmentLengthHasBeenSet = true;
}
if(jsonValue.ValueExists("mpdProfile"))
{
m_mpdProfile = DashIsoMpdProfileMapper::GetDashIsoMpdProfileForName(jsonValue.GetString("mpdProfile"));
m_mpdProfileHasBeenSet = true;
}
if(jsonValue.ValueExists("ptsOffsetHandlingForBFrames"))
{
m_ptsOffsetHandlingForBFrames = DashIsoPtsOffsetHandlingForBFramesMapper::GetDashIsoPtsOffsetHandlingForBFramesForName(jsonValue.GetString("ptsOffsetHandlingForBFrames"));
m_ptsOffsetHandlingForBFramesHasBeenSet = true;
}
if(jsonValue.ValueExists("segmentControl"))
{
m_segmentControl = DashIsoSegmentControlMapper::GetDashIsoSegmentControlForName(jsonValue.GetString("segmentControl"));
m_segmentControlHasBeenSet = true;
}
if(jsonValue.ValueExists("segmentLength"))
{
m_segmentLength = jsonValue.GetInteger("segmentLength");
m_segmentLengthHasBeenSet = true;
}
if(jsonValue.ValueExists("segmentLengthControl"))
{
m_segmentLengthControl = DashIsoSegmentLengthControlMapper::GetDashIsoSegmentLengthControlForName(jsonValue.GetString("segmentLengthControl"));
m_segmentLengthControlHasBeenSet = true;
}
if(jsonValue.ValueExists("writeSegmentTimelineInRepresentation"))
{
m_writeSegmentTimelineInRepresentation = DashIsoWriteSegmentTimelineInRepresentationMapper::GetDashIsoWriteSegmentTimelineInRepresentationForName(jsonValue.GetString("writeSegmentTimelineInRepresentation"));
m_writeSegmentTimelineInRepresentationHasBeenSet = true;
}
return *this;
}
JsonValue DashIsoGroupSettings::Jsonize() const
{
JsonValue payload;
if(m_additionalManifestsHasBeenSet)
{
Array<JsonValue> additionalManifestsJsonList(m_additionalManifests.size());
for(unsigned additionalManifestsIndex = 0; additionalManifestsIndex < additionalManifestsJsonList.GetLength(); ++additionalManifestsIndex)
{
additionalManifestsJsonList[additionalManifestsIndex].AsObject(m_additionalManifests[additionalManifestsIndex].Jsonize());
}
payload.WithArray("additionalManifests", std::move(additionalManifestsJsonList));
}
if(m_audioChannelConfigSchemeIdUriHasBeenSet)
{
payload.WithString("audioChannelConfigSchemeIdUri", DashIsoGroupAudioChannelConfigSchemeIdUriMapper::GetNameForDashIsoGroupAudioChannelConfigSchemeIdUri(m_audioChannelConfigSchemeIdUri));
}
if(m_baseUrlHasBeenSet)
{
payload.WithString("baseUrl", m_baseUrl);
}
if(m_destinationHasBeenSet)
{
payload.WithString("destination", m_destination);
}
if(m_destinationSettingsHasBeenSet)
{
payload.WithObject("destinationSettings", m_destinationSettings.Jsonize());
}
if(m_encryptionHasBeenSet)
{
payload.WithObject("encryption", m_encryption.Jsonize());
}
if(m_fragmentLengthHasBeenSet)
{
payload.WithInteger("fragmentLength", m_fragmentLength);
}
if(m_hbbtvComplianceHasBeenSet)
{
payload.WithString("hbbtvCompliance", DashIsoHbbtvComplianceMapper::GetNameForDashIsoHbbtvCompliance(m_hbbtvCompliance));
}
if(m_imageBasedTrickPlayHasBeenSet)
{
payload.WithString("imageBasedTrickPlay", DashIsoImageBasedTrickPlayMapper::GetNameForDashIsoImageBasedTrickPlay(m_imageBasedTrickPlay));
}
if(m_imageBasedTrickPlaySettingsHasBeenSet)
{
payload.WithObject("imageBasedTrickPlaySettings", m_imageBasedTrickPlaySettings.Jsonize());
}
if(m_minBufferTimeHasBeenSet)
{
payload.WithInteger("minBufferTime", m_minBufferTime);
}
if(m_minFinalSegmentLengthHasBeenSet)
{
payload.WithDouble("minFinalSegmentLength", m_minFinalSegmentLength);
}
if(m_mpdProfileHasBeenSet)
{
payload.WithString("mpdProfile", DashIsoMpdProfileMapper::GetNameForDashIsoMpdProfile(m_mpdProfile));
}
if(m_ptsOffsetHandlingForBFramesHasBeenSet)
{
payload.WithString("ptsOffsetHandlingForBFrames", DashIsoPtsOffsetHandlingForBFramesMapper::GetNameForDashIsoPtsOffsetHandlingForBFrames(m_ptsOffsetHandlingForBFrames));
}
if(m_segmentControlHasBeenSet)
{
payload.WithString("segmentControl", DashIsoSegmentControlMapper::GetNameForDashIsoSegmentControl(m_segmentControl));
}
if(m_segmentLengthHasBeenSet)
{
payload.WithInteger("segmentLength", m_segmentLength);
}
if(m_segmentLengthControlHasBeenSet)
{
payload.WithString("segmentLengthControl", DashIsoSegmentLengthControlMapper::GetNameForDashIsoSegmentLengthControl(m_segmentLengthControl));
}
if(m_writeSegmentTimelineInRepresentationHasBeenSet)
{
payload.WithString("writeSegmentTimelineInRepresentation", DashIsoWriteSegmentTimelineInRepresentationMapper::GetNameForDashIsoWriteSegmentTimelineInRepresentation(m_writeSegmentTimelineInRepresentation));
}
return payload;
}
} // namespace Model
} // namespace MediaConvert
} // namespace Aws
| aws/aws-sdk-cpp | aws-cpp-sdk-mediaconvert/source/model/DashIsoGroupSettings.cpp | C++ | apache-2.0 | 10,732 |
/**
* Copyright 2013 Agustín Miura <"[email protected]">
*
* 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 ar.com.imperium.common.security;
import org.springframework.stereotype.Component;
@Component("dummyHashService")
public class DummyHashServiceImpl implements IHashService
{
@Override
public String hashString(String input) throws Exception
{
return input;
}
}
| agustinmiura/imperium | src/main/java/ar/com/imperium/common/security/DummyHashServiceImpl.java | Java | apache-2.0 | 925 |
(function(jQuery) {
"use strict";
var control = Echo.Control.manifest("Echo.Tests.Controls.TestControl");
if (Echo.Control.isDefined(control)) return;
control.init = function() {
if (!Echo.Variables) {
Echo.Variables = {};
}
Echo.Variables.TestControl = "production";
this.ready();
};
control.config = {};
control.templates.main = "";
Echo.Control.create(control);
})(Echo.jQuery);
| EchoAppsTeam/js-sdk | tests/fixtures/resources/loader/scripts.prod.js | JavaScript | apache-2.0 | 395 |
<?php
namespace DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIREncounter;
/*!
* This class was generated with the PHPFHIR library (https://github.com/dcarbone/php-fhir) using
* class definitions from HL7 FHIR (https://www.hl7.org/fhir/)
*
* Class creation date: December 26th, 2019 15:44+0000
*
* PHPFHIR Copyright:
*
* Copyright 2016-2019 Daniel Carbone ([email protected])
*
* 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.
*
*
* FHIR Copyright Notice:
*
* Copyright (c) 2011+, HL7, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of HL7 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 HOLDER 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.
*
*
* Generated on Fri, Nov 1, 2019 09:29+1100 for FHIR v4.0.1
*
* Note: the schemas & schematrons do not contain all of the rules about what makes resources
* valid. Implementers will still need to be familiar with the content of the specification and with
* any profiles that apply to the resources in order to make a conformant implementation.
*
*/
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRPositiveInt;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference;
use DCarbone\PHPFHIRGenerated\R4\PHPFHIRConstants;
use DCarbone\PHPFHIRGenerated\R4\PHPFHIRTypeInterface;
/**
* An interaction between a patient and healthcare provider(s) for the purpose of
* providing healthcare service(s) or assessing the health status of a patient.
*
* Class FHIREncounterDiagnosis
* @package \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIREncounter
*/
class FHIREncounterDiagnosis extends FHIRBackboneElement
{
// name of FHIR type this class describes
const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_ENCOUNTER_DOT_DIAGNOSIS;
const FIELD_CONDITION = 'condition';
const FIELD_RANK = 'rank';
const FIELD_RANK_EXT = '_rank';
const FIELD_USE = 'use';
/** @var string */
private $_xmlns = 'http://hl7.org/fhir';
/**
* A reference from one resource to another.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Reason the encounter takes place, as specified using information from another
* resource. For admissions, this is the admission diagnosis. The indication will
* typically be a Condition (with other resources referenced in the
* evidence.detail), or a Procedure.
*
* @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference
*/
protected $condition = null;
/**
* An integer with a value that is positive (e.g. >0)
* If the element is present, it must have either a \@value, an \@id referenced from
* the Narrative, or extensions
*
* Ranking of the diagnosis (for each role type).
*
* @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRPositiveInt
*/
protected $rank = null;
/**
* A concept that may be defined by a formal reference to a terminology or ontology
* or may be provided by text.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Role that this diagnosis has within the encounter (e.g. admission, billing,
* discharge …).
*
* @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept
*/
protected $use = null;
/**
* Validation map for fields in type Encounter.Diagnosis
* @var array
*/
private static $_validationRules = [ ];
/**
* FHIREncounterDiagnosis Constructor
* @param null|array $data
*/
public function __construct($data = null)
{
if (null === $data || [] === $data) {
return;
}
if (!is_array($data)) {
throw new \InvalidArgumentException(sprintf(
'FHIREncounterDiagnosis::_construct - $data expected to be null or array, %s seen',
gettype($data)
));
}
parent::__construct($data);
if (isset($data[self::FIELD_CONDITION])) {
if ($data[self::FIELD_CONDITION] instanceof FHIRReference) {
$this->setCondition($data[self::FIELD_CONDITION]);
} else {
$this->setCondition(new FHIRReference($data[self::FIELD_CONDITION]));
}
}
if (isset($data[self::FIELD_RANK]) || isset($data[self::FIELD_RANK_EXT])) {
if (isset($data[self::FIELD_RANK])) {
$value = $data[self::FIELD_RANK];
} else {
$value = null;
}
if (isset($data[self::FIELD_RANK_EXT]) && is_array($data[self::FIELD_RANK_EXT])) {
$ext = $data[self::FIELD_RANK_EXT];
} else {
$ext = [];
}
if (null !== $value) {
if ($value instanceof FHIRPositiveInt) {
$this->setRank($value);
} else if (is_array($value)) {
$this->setRank(new FHIRPositiveInt(array_merge($ext, $value)));
} else {
$this->setRank(new FHIRPositiveInt([FHIRPositiveInt::FIELD_VALUE => $value] + $ext));
}
} else if ([] !== $ext) {
$this->setRank(new FHIRPositiveInt($ext));
}
}
if (isset($data[self::FIELD_USE])) {
if ($data[self::FIELD_USE] instanceof FHIRCodeableConcept) {
$this->setUse($data[self::FIELD_USE]);
} else {
$this->setUse(new FHIRCodeableConcept($data[self::FIELD_USE]));
}
}
}
/**
* @return string
*/
public function _getFHIRTypeName()
{
return self::FHIR_TYPE_NAME;
}
/**
* @return string
*/
public function _getFHIRXMLElementDefinition()
{
$xmlns = $this->_getFHIRXMLNamespace();
if (null !== $xmlns) {
$xmlns = " xmlns=\"{$xmlns}\"";
}
return "<EncounterDiagnosis{$xmlns}></EncounterDiagnosis>";
}
/**
* A reference from one resource to another.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Reason the encounter takes place, as specified using information from another
* resource. For admissions, this is the admission diagnosis. The indication will
* typically be a Condition (with other resources referenced in the
* evidence.detail), or a Procedure.
*
* @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference
*/
public function getCondition()
{
return $this->condition;
}
/**
* A reference from one resource to another.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Reason the encounter takes place, as specified using information from another
* resource. For admissions, this is the admission diagnosis. The indication will
* typically be a Condition (with other resources referenced in the
* evidence.detail), or a Procedure.
*
* @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference $condition
* @return static
*/
public function setCondition(FHIRReference $condition = null)
{
$this->condition = $condition;
return $this;
}
/**
* An integer with a value that is positive (e.g. >0)
* If the element is present, it must have either a \@value, an \@id referenced from
* the Narrative, or extensions
*
* Ranking of the diagnosis (for each role type).
*
* @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRPositiveInt
*/
public function getRank()
{
return $this->rank;
}
/**
* An integer with a value that is positive (e.g. >0)
* If the element is present, it must have either a \@value, an \@id referenced from
* the Narrative, or extensions
*
* Ranking of the diagnosis (for each role type).
*
* @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRPositiveInt $rank
* @return static
*/
public function setRank($rank = null)
{
if (null === $rank) {
$this->rank = null;
return $this;
}
if ($rank instanceof FHIRPositiveInt) {
$this->rank = $rank;
return $this;
}
$this->rank = new FHIRPositiveInt($rank);
return $this;
}
/**
* A concept that may be defined by a formal reference to a terminology or ontology
* or may be provided by text.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Role that this diagnosis has within the encounter (e.g. admission, billing,
* discharge …).
*
* @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept
*/
public function getUse()
{
return $this->use;
}
/**
* A concept that may be defined by a formal reference to a terminology or ontology
* or may be provided by text.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Role that this diagnosis has within the encounter (e.g. admission, billing,
* discharge …).
*
* @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept $use
* @return static
*/
public function setUse(FHIRCodeableConcept $use = null)
{
$this->use = $use;
return $this;
}
/**
* Returns the validation rules that this type's fields must comply with to be considered "valid"
* The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]]
*
* @return array
*/
public function _getValidationRules()
{
return self::$_validationRules;
}
/**
* Validates that this type conforms to the specifications set forth for it by FHIR. An empty array must be seen as
* passing.
*
* @return array
*/
public function _getValidationErrors()
{
$errs = parent::_getValidationErrors();
$validationRules = $this->_getValidationRules();
if (null !== ($v = $this->getCondition())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_CONDITION] = $fieldErrs;
}
}
if (null !== ($v = $this->getRank())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_RANK] = $fieldErrs;
}
}
if (null !== ($v = $this->getUse())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_USE] = $fieldErrs;
}
}
if (isset($validationRules[self::FIELD_CONDITION])) {
$v = $this->getCondition();
foreach($validationRules[self::FIELD_CONDITION] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ENCOUNTER_DOT_DIAGNOSIS, self::FIELD_CONDITION, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_CONDITION])) {
$errs[self::FIELD_CONDITION] = [];
}
$errs[self::FIELD_CONDITION][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_RANK])) {
$v = $this->getRank();
foreach($validationRules[self::FIELD_RANK] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ENCOUNTER_DOT_DIAGNOSIS, self::FIELD_RANK, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_RANK])) {
$errs[self::FIELD_RANK] = [];
}
$errs[self::FIELD_RANK][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_USE])) {
$v = $this->getUse();
foreach($validationRules[self::FIELD_USE] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ENCOUNTER_DOT_DIAGNOSIS, self::FIELD_USE, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_USE])) {
$errs[self::FIELD_USE] = [];
}
$errs[self::FIELD_USE][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_MODIFIER_EXTENSION])) {
$v = $this->getModifierExtension();
foreach($validationRules[self::FIELD_MODIFIER_EXTENSION] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BACKBONE_ELEMENT, self::FIELD_MODIFIER_EXTENSION, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_MODIFIER_EXTENSION])) {
$errs[self::FIELD_MODIFIER_EXTENSION] = [];
}
$errs[self::FIELD_MODIFIER_EXTENSION][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_EXTENSION])) {
$v = $this->getExtension();
foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_EXTENSION, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_EXTENSION])) {
$errs[self::FIELD_EXTENSION] = [];
}
$errs[self::FIELD_EXTENSION][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_ID])) {
$v = $this->getId();
foreach($validationRules[self::FIELD_ID] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_ID, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_ID])) {
$errs[self::FIELD_ID] = [];
}
$errs[self::FIELD_ID][$rule] = $err;
}
}
}
return $errs;
}
/**
* @param \SimpleXMLElement|string|null $sxe
* @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIREncounter\FHIREncounterDiagnosis $type
* @param null|int $libxmlOpts
* @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIREncounter\FHIREncounterDiagnosis
*/
public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
return null;
}
if (is_string($sxe)) {
libxml_use_internal_errors(true);
$sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false);
if ($sxe === false) {
throw new \DomainException(sprintf('FHIREncounterDiagnosis::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors()))));
}
libxml_use_internal_errors(false);
}
if (!($sxe instanceof \SimpleXMLElement)) {
throw new \InvalidArgumentException(sprintf('FHIREncounterDiagnosis::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe)));
}
if (null === $type) {
$type = new FHIREncounterDiagnosis;
} elseif (!is_object($type) || !($type instanceof FHIREncounterDiagnosis)) {
throw new \RuntimeException(sprintf(
'FHIREncounterDiagnosis::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIREncounter\FHIREncounterDiagnosis or null, %s seen.',
is_object($type) ? get_class($type) : gettype($type)
));
}
FHIRBackboneElement::xmlUnserialize($sxe, $type);
$xmlNamespaces = $sxe->getDocNamespaces(false, false);
if ([] !== $xmlNamespaces) {
$ns = reset($xmlNamespaces);
if (false !== $ns && '' !== $ns) {
$type->_xmlns = $ns;
}
}
$attributes = $sxe->attributes();
$children = $sxe->children();
if (isset($children->condition)) {
$type->setCondition(FHIRReference::xmlUnserialize($children->condition));
}
if (isset($children->rank)) {
$type->setRank(FHIRPositiveInt::xmlUnserialize($children->rank));
}
if (isset($attributes->rank)) {
$pt = $type->getRank();
if (null !== $pt) {
$pt->setValue((string)$attributes->rank);
} else {
$type->setRank((string)$attributes->rank);
}
}
if (isset($children->use)) {
$type->setUse(FHIRCodeableConcept::xmlUnserialize($children->use));
}
return $type;
}
/**
* @param null|\SimpleXMLElement $sxe
* @param null|int $libxmlOpts
* @return \SimpleXMLElement
*/
public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
$sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false);
}
parent::xmlSerialize($sxe);
if (null !== ($v = $this->getCondition())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_CONDITION, null, $v->_getFHIRXMLNamespace()));
}
if (null !== ($v = $this->getRank())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_RANK, null, $v->_getFHIRXMLNamespace()));
}
if (null !== ($v = $this->getUse())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_USE, null, $v->_getFHIRXMLNamespace()));
}
return $sxe;
}
/**
* @return array
*/
public function jsonSerialize()
{
$a = parent::jsonSerialize();
if (null !== ($v = $this->getCondition())) {
$a[self::FIELD_CONDITION] = $v;
}
if (null !== ($v = $this->getRank())) {
$a[self::FIELD_RANK] = $v->getValue();
$enc = $v->jsonSerialize();
$cnt = count($enc);
if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRPositiveInt::FIELD_VALUE, $enc)))) {
unset($enc[FHIRPositiveInt::FIELD_VALUE]);
$a[self::FIELD_RANK_EXT] = $enc;
}
}
if (null !== ($v = $this->getUse())) {
$a[self::FIELD_USE] = $v;
}
if ([] !== ($vs = $this->_getFHIRComments())) {
$a[PHPFHIRConstants::JSON_FIELD_FHIR_COMMENTS] = $vs;
}
return $a;
}
/**
* @return string
*/
public function __toString()
{
return self::FHIR_TYPE_NAME;
}
} | dcarbone/php-fhir-generated | src/DCarbone/PHPFHIRGenerated/R4/FHIRElement/FHIRBackboneElement/FHIREncounter/FHIREncounterDiagnosis.php | PHP | apache-2.0 | 21,748 |
/*
Copyright 2015 The Kubernetes 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.
*/
// If you make changes to this file, you should also make the corresponding change in ReplicaSet.
package replication
import (
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/api"
client "k8s.io/kubernetes/pkg/client/unversioned"
)
// updateReplicaCount attempts to update the Status.Replicas of the given controller, with a single GET/PUT retry.
func updateReplicaCount(rcClient client.ReplicationControllerInterface, controller api.ReplicationController, numReplicas int) (updateErr error) {
// This is the steady state. It happens when the rc doesn't have any expectations, since
// we do a periodic relist every 30s. If the generations differ but the replicas are
// the same, a caller might've resized to the same replica count.
if controller.Status.Replicas == numReplicas &&
controller.Generation == controller.Status.ObservedGeneration {
return nil
}
// Save the generation number we acted on, otherwise we might wrongfully indicate
// that we've seen a spec update when we retry.
// TODO: This can clobber an update if we allow multiple agents to write to the
// same status.
generation := controller.Generation
var getErr error
for i, rc := 0, &controller; ; i++ {
glog.V(4).Infof("Updating replica count for rc: %v, %d->%d (need %d), sequence No: %v->%v",
controller.Name, controller.Status.Replicas, numReplicas, controller.Spec.Replicas, controller.Status.ObservedGeneration, generation)
rc.Status = api.ReplicationControllerStatus{Replicas: numReplicas, ObservedGeneration: generation}
_, updateErr = rcClient.UpdateStatus(rc)
if updateErr == nil || i >= statusUpdateRetries {
return updateErr
}
// Update the controller with the latest resource version for the next poll
if rc, getErr = rcClient.Get(controller.Name); getErr != nil {
// If the GET fails we can't trust status.Replicas anymore. This error
// is bound to be more interesting than the update failure.
return getErr
}
}
}
// OverlappingControllers sorts a list of controllers by creation timestamp, using their names as a tie breaker.
type OverlappingControllers []api.ReplicationController
func (o OverlappingControllers) Len() int { return len(o) }
func (o OverlappingControllers) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func (o OverlappingControllers) Less(i, j int) bool {
if o[i].CreationTimestamp.Equal(o[j].CreationTimestamp) {
return o[i].Name < o[j].Name
}
return o[i].CreationTimestamp.Before(o[j].CreationTimestamp)
}
| WIZARD-CXY/kubernetes | pkg/controller/replication/replication_controller_utils.go | GO | apache-2.0 | 3,070 |
package com.sadc.game.gameobject.trackobject;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.sadc.game.GameConstants;
import com.sadc.game.gameobject.GameUtils;
import com.sadc.game.gameobject.Player;
/**
* @author f536985 (Tom Farello)
*/
public class Wall extends TrackObject {
public Wall(float distance, float angle) {
setActive(true);
setDistance(distance);
setAngle(angle);
setWidth(22);
setTexture(new Texture("brickWall.png"));
}
@Override
public void update(float delta, Player player) {
if (collide(player)) {
player.crash();
setActive(false);
}
}
@Override
public void draw(float delta, float playerDistance, SpriteBatch spriteBatch) {
float drawDistance = (float)Math.pow(2 , playerDistance - (getDistance()));
GameUtils.setColorByDrawDistance(drawDistance, spriteBatch);
spriteBatch.draw(getTexture(), GameConstants.SCREEN_WIDTH / 2 - 50, 15,
50, GameConstants.SCREEN_HEIGHT / 2 - 15, 100, 70, drawDistance, drawDistance, getAngle(), 0, 0, 100, 70, false, false);
}
}
| jlturner85/libgdx-gradle-template | core/src/main/java/com/sadc/game/gameobject/trackobject/Wall.java | Java | apache-2.0 | 1,196 |
<!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_111) on Wed Feb 22 09:55:43 CET 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.togglz.slack (Togglz 2.4.0.Final API)</title>
<meta name="date" content="2017-02-22">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../org/togglz/slack/package-summary.html" target="classFrame">org.togglz.slack</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="SlackStateRepository.html" title="class in org.togglz.slack" target="classFrame">SlackStateRepository</a></li>
</ul>
</div>
</body>
</html>
| togglz/togglz-site | apidocs/2.4.0.Final/org/togglz/slack/package-frame.html | HTML | apache-2.0 | 904 |
class JobApplicationsController < ApplicationController
after_action :verify_authorized
after_action :verify_policy_scoped, only: [:index]
before_action :require_login
before_action :set_job_application, only: [:show, :edit, :update, :destroy, :followup]
# GET /posting/1/job_application
# GET /posting/1/job_application.json
# def index
# @posting = Posting.unscoped.find(params[:posting_id])
# authorize @posting, :show?
# @job_applications = JobApplication.all
# end
# GET /posting/1/job_application
# GET /posting/1/job_application.json
def show
end
# GET /posting/1/job_application/new
def new
@job_application = JobApplication.new
authorize @job_application
end
# GET /posting/1/job_application/edit
def edit
end
# POST /posting/1/job_application
# POST /posting/1/job_application.json
def create
@job_application = JobApplication.new(job_application_params)
@job_application.posting = Posting.unscoped.find(params[:posting_id])
authorize @job_application
authorize @job_application.posting, :update?
respond_to do |format|
if @job_application.save
# TODO: Is this line still needed?
@job_application_is_new = true
format.html {
redirect_to @job_application.posting,
notice: 'Job application was successfully created.'
}
format.json { render action: 'show', status: :created }
else
format.html { render action: 'new' }
format.json {
render json: @job_application.errors,
status: :unprocessable_entity
}
end
end
end
# PATCH/PUT /posting/1/job_application/followup.json
def followup
respond_to do |format|
if @job_application.update(followup: Time.now)
format.json { render action: 'show' }
else
format.json {
render json: @job_application.errors,
status: :unprocessable_entity
}
end
end
end
# PATCH/PUT /posting/1/job_application
# PATCH/PUT /posting/1/job_application.json
def update
respond_to do |format|
if @job_application.update(job_application_params)
format.html { redirect_to @job_application.posting, notice: 'Changes saved!' }
format.json { render action: 'show', notice: 'Changes saved!' }
else
format.html { render action: 'edit' }
format.json {
render json: @job_application.errors,
status: :unprocessable_entity
}
end
end
end
# DELETE /posting/1/job_application
# DELETE /posting/1/job_application.json
def destroy
@job_application.destroy
respond_to do |format|
format.html { redirect_to @job_application.posting }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_job_application
@job_application = Posting.unscoped.find(params[:posting_id]).job_application
authorize @job_application
end
# Never trust parameters from the scary internet, only allow the white list through.
def job_application_params
params.require(:job_application).permit(:date_sent, :cover_letter, :posting_id)
end
end
| sarahmonster/suitor | app/controllers/job_applications_controller.rb | Ruby | apache-2.0 | 3,255 |
<!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_08) on Wed Jan 10 16:02:59 PST 2007 -->
<TITLE>
Uses of Interface org.apache.hadoop.mapred.JobSubmissionProtocol (Hadoop 0.10.1 API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Interface org.apache.hadoop.mapred.JobSubmissionProtocol (Hadoop 0.10.1 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="../../../../../org/apache/hadoop/mapred/JobSubmissionProtocol.html" title="interface in org.apache.hadoop.mapred"><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?org/apache/hadoop/mapred//class-useJobSubmissionProtocol.html" target="_top"><B>FRAMES</B></A>
<A HREF="JobSubmissionProtocol.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 Interface<br>org.apache.hadoop.mapred.JobSubmissionProtocol</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="../../../../../org/apache/hadoop/mapred/JobSubmissionProtocol.html" title="interface in org.apache.hadoop.mapred">JobSubmissionProtocol</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.mapred"><B>org.apache.hadoop.mapred</B></A></TD>
<TD>A system for scalable, fault-tolerant, distributed computation over
large data collections. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.mapred"><!-- --></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="../../../../../org/apache/hadoop/mapred/JobSubmissionProtocol.html" title="interface in org.apache.hadoop.mapred">JobSubmissionProtocol</A> in <A HREF="../../../../../org/apache/hadoop/mapred/package-summary.html">org.apache.hadoop.mapred</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">Classes in <A HREF="../../../../../org/apache/hadoop/mapred/package-summary.html">org.apache.hadoop.mapred</A> that implement <A HREF="../../../../../org/apache/hadoop/mapred/JobSubmissionProtocol.html" title="interface in org.apache.hadoop.mapred">JobSubmissionProtocol</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="../../../../../org/apache/hadoop/mapred/JobTracker.html" title="class in org.apache.hadoop.mapred">JobTracker</A></B></CODE>
<BR>
JobTracker is the central location for submitting and
tracking MR jobs in a network environment.</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="../../../../../org/apache/hadoop/mapred/JobSubmissionProtocol.html" title="interface in org.apache.hadoop.mapred"><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?org/apache/hadoop/mapred//class-useJobSubmissionProtocol.html" target="_top"><B>FRAMES</B></A>
<A HREF="JobSubmissionProtocol.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 © 2006 The Apache Software Foundation
</BODY>
</HTML>
| moreus/hadoop | hadoop-0.10.1/docs/api/org/apache/hadoop/mapred/class-use/JobSubmissionProtocol.html | HTML | apache-2.0 | 7,980 |
package dx.exec
import dx.api.{DxApi, DxFile}
import dx.core.io.ExecLinkInfo
import dx.core.languages.wdl.{TypeSerialization, WdlVarLinksConverter}
import spray.json._
import wdlTools.eval.WdlValues
import wdlTools.types.WdlTypes
case class WfFragInput(blockPath: Vector[Int],
env: Map[String, (WdlTypes.T, WdlValues.V)],
execLinkInfo: Map[String, ExecLinkInfo])
case class WfFragInputOutput(typeAliases: Map[String, WdlTypes.T],
wdlVarLinksConverter: WdlVarLinksConverter,
dxApi: DxApi) {
private def revTransformVarName(varName: String): String = {
varName.replaceAll("___", "\\.")
}
private def loadWorkflowMetaInfo(
metaInfo: Map[String, JsValue]
): (Map[String, ExecLinkInfo], Vector[Int], Map[String, WdlTypes.T]) = {
// meta information used for running workflow fragments
val execLinkInfo: Map[String, ExecLinkInfo] = metaInfo.get("execLinkInfo") match {
case None => Map.empty
case Some(JsObject(fields)) =>
fields.map {
case (key, ali) =>
key -> ExecLinkInfo.readJson(dxApi, ali, typeAliases)
}
case other => throw new Exception(s"Bad value ${other}")
}
val blockPath: Vector[Int] = metaInfo.get("blockPath") match {
case None => Vector.empty
case Some(JsArray(arr)) =>
arr.map {
case JsNumber(n) => n.toInt
case _ => throw new Exception("Bad value ${arr}")
}
case other => throw new Exception(s"Bad value ${other}")
}
val fqnDictTypes: Map[String, WdlTypes.T] = metaInfo.get("fqnDictTypes") match {
case Some(JsObject(fields)) =>
fields.map {
case (key, JsString(value)) =>
// Transform back to a fully qualified name with dots
val orgKeyName = revTransformVarName(key)
val wdlType = TypeSerialization(typeAliases).fromString(value)
orgKeyName -> wdlType
case other => throw new Exception(s"Bad value ${other}")
}
case other => throw new Exception(s"Bad value ${other}")
}
(execLinkInfo, blockPath, fqnDictTypes)
}
// 1. Convert the inputs to WDL values
// 2. Setup an environment to evaluate the sub-block. This should
// look to the WDL code as if all previous code had been evaluated.
def loadInputs(inputs: JsValue, metaInfo: JsValue): WfFragInput = {
val regularFields: Map[String, JsValue] = inputs.asJsObject.fields
.filter { case (fieldName, _) => !fieldName.endsWith(WdlVarLinksConverter.FLAT_FILES_SUFFIX) }
// Extract the meta information needed to setup the closure for the subblock
val (execLinkInfo, blockPath, fqnDictTypes) = loadWorkflowMetaInfo(metaInfo.asJsObject.fields)
// What remains are inputs from other stages. Convert from JSON to WDL values
val env: Map[String, (WdlTypes.T, WdlValues.V)] = regularFields.map {
case (name, jsValue) =>
val fqn = revTransformVarName(name)
val wdlType = fqnDictTypes.get(fqn) match {
case None =>
throw new Exception(s"Did not find variable ${fqn} (${name}) in the block environment")
case Some(x) => x
}
val value = wdlVarLinksConverter.unpackJobInput(fqn, wdlType, jsValue)
fqn -> (wdlType, value)
}
WfFragInput(blockPath, env, execLinkInfo)
}
// find all the dx:files that are referenced from the inputs
def findRefDxFiles(inputs: JsValue, metaInfo: JsValue): Vector[DxFile] = {
val regularFields: Map[String, JsValue] = inputs.asJsObject.fields
.filter { case (fieldName, _) => !fieldName.endsWith(WdlVarLinksConverter.FLAT_FILES_SUFFIX) }
val (_, _, fqnDictTypes) = loadWorkflowMetaInfo(metaInfo.asJsObject.fields)
// Convert from JSON to WDL values
regularFields
.map {
case (name, jsValue) =>
val fqn = revTransformVarName(name)
if (!fqnDictTypes.contains(fqn)) {
throw new Exception(
s"Did not find variable ${fqn} (${name}) in the block environment"
)
}
dxApi.findFiles(jsValue)
}
.toVector
.flatten
}
}
| dnanexus-rnd/dxWDL | src/main/scala/dx/exec/WfFragInputOutput.scala | Scala | apache-2.0 | 4,231 |
/*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.sql.functions.coll;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This operator can work as aggregate or inline. If only one argument is passed than aggregates,
* otherwise executes, and returns, the SYMMETRIC DIFFERENCE between the collections received as
* parameters. Works also with no collection values.
*
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*/
public class OSQLFunctionSymmetricDifference extends OSQLFunctionMultiValueAbstract<Set<Object>> {
public static final String NAME = "symmetricDifference";
private Set<Object> rejected;
public OSQLFunctionSymmetricDifference() {
super(NAME, 1, -1);
}
private static void addItemToResult(Object o, Set<Object> accepted, Set<Object> rejected) {
if (!accepted.contains(o) && !rejected.contains(o)) {
accepted.add(o);
} else {
accepted.remove(o);
rejected.add(o);
}
}
private static void addItemsToResult(
Collection<Object> co, Set<Object> accepted, Set<Object> rejected) {
for (Object o : co) {
addItemToResult(o, accepted, rejected);
}
}
@SuppressWarnings("unchecked")
public Object execute(
Object iThis,
OIdentifiable iCurrentRecord,
Object iCurrentResult,
final Object[] iParams,
OCommandContext iContext) {
if (iParams[0] == null) return null;
Object value = iParams[0];
if (iParams.length == 1) {
// AGGREGATION MODE (STATEFUL)
if (context == null) {
context = new HashSet<Object>();
rejected = new HashSet<Object>();
}
if (value instanceof Collection<?>) {
addItemsToResult((Collection<Object>) value, context, rejected);
} else {
addItemToResult(value, context, rejected);
}
return null;
} else {
// IN-LINE MODE (STATELESS)
final Set<Object> result = new HashSet<Object>();
final Set<Object> rejected = new HashSet<Object>();
for (Object iParameter : iParams) {
if (iParameter instanceof Collection<?>) {
addItemsToResult((Collection<Object>) iParameter, result, rejected);
} else {
addItemToResult(iParameter, result, rejected);
}
}
return result;
}
}
@Override
public Set<Object> getResult() {
if (returnDistributedResult()) {
final Map<String, Object> doc = new HashMap<String, Object>();
doc.put("result", context);
doc.put("rejected", rejected);
return Collections.<Object>singleton(doc);
} else {
return super.getResult();
}
}
public String getSyntax() {
return "difference(<field>*)";
}
@Override
public Object mergeDistributedResult(List<Object> resultsToMerge) {
if (returnDistributedResult()) {
final Set<Object> result = new HashSet<Object>();
final Set<Object> rejected = new HashSet<Object>();
for (Object item : resultsToMerge) {
rejected.addAll(unwrap(item, "rejected"));
}
for (Object item : resultsToMerge) {
addItemsToResult(unwrap(item, "result"), result, rejected);
}
return result;
}
if (!resultsToMerge.isEmpty()) return resultsToMerge.get(0);
return null;
}
@SuppressWarnings("unchecked")
private Set<Object> unwrap(Object obj, String field) {
final Set<Object> objAsSet = (Set<Object>) obj;
final Map<String, Object> objAsMap = (Map<String, Object>) objAsSet.iterator().next();
final Set<Object> objAsField = (Set<Object>) objAsMap.get(field);
return objAsField;
}
}
| orientechnologies/orientdb | core/src/main/java/com/orientechnologies/orient/core/sql/functions/coll/OSQLFunctionSymmetricDifference.java | Java | apache-2.0 | 4,574 |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.simpleemail.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* An empty element returned on a successful request.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetReceiptRulePosition" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetReceiptRulePositionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* 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("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SetReceiptRulePositionResult == false)
return false;
SetReceiptRulePositionResult other = (SetReceiptRulePositionResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public SetReceiptRulePositionResult clone() {
try {
return (SetReceiptRulePositionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| dagnir/aws-sdk-java | aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/SetReceiptRulePositionResult.java | Java | apache-2.0 | 2,365 |
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.daisy.pipeline.client.PipelineClient;
import org.daisy.pipeline.webservice.jaxb.job.Job;
import org.daisy.pipeline.webservice.jaxb.job.JobStatus;
import org.daisy.pipeline.webservice.jaxb.job.Messages;
import org.daisy.pipeline.webservice.jaxb.request.Callback;
import org.daisy.pipeline.webservice.jaxb.request.CallbackType;
import org.daisy.pipeline.webservice.jaxb.request.Input;
import org.daisy.pipeline.webservice.jaxb.request.Item;
import org.daisy.pipeline.webservice.jaxb.request.JobRequest;
import org.daisy.pipeline.webservice.jaxb.request.ObjectFactory;
import org.daisy.pipeline.webservice.jaxb.request.Script;
import org.daisy.pipeline.webservice.jaxb.request.Priority;
import org.junit.Assert;
import org.junit.Test;
public class TestPushNotifications extends Base {
private static final PipelineClient client = newClient(TestClientJobs.CREDS_DEF.clientId, TestClientJobs.CREDS_DEF.secret);
@Override
protected PipelineClient client() {
return client;
}
@Override
protected Properties systemProperties() {
Properties p = super.systemProperties();
// client authentication is required for push notifications
p.setProperty("org.daisy.pipeline.ws.authentication", "true");
p.setProperty("org.daisy.pipeline.ws.authentication.key", TestClientJobs.CREDS_DEF.clientId);
p.setProperty("org.daisy.pipeline.ws.authentication.secret", TestClientJobs.CREDS_DEF.secret);
return p;
}
@Test
public void testPushNotifications() throws Exception {
AbstractCallback testStatusAndMessages = new AbstractCallback() {
JobStatus lastStatus = null;
BigDecimal lastProgress = BigDecimal.ZERO;
Iterator<BigDecimal> mustSee = stream(".25", ".375", ".5", ".55", ".675", ".8", ".9").map(d -> new BigDecimal(d)).iterator();
BigDecimal mustSeeNext = mustSee.next();
List<BigDecimal> seen = new ArrayList<BigDecimal>();
@Override
void handleStatus(JobStatus status) {
lastStatus = status;
}
@Override
void handleMessages(Messages messages) {
BigDecimal progress = messages.getProgress();
if (progress.compareTo(lastProgress) != 0) {
Assert.assertTrue("Progress must be monotonic non-decreasing", progress.compareTo(lastProgress) >= 0);
if (mustSeeNext != null) {
if (progress.compareTo(mustSeeNext) == 0) {
seen.clear();
mustSeeNext = mustSee.hasNext() ? mustSee.next() : null;
} else {
seen.add(progress);
Assert.assertTrue("Expected " + mustSeeNext + " but got " + seen, progress.compareTo(mustSeeNext) < 0);
}
}
lastProgress = progress;
}
}
@Override
void finalTest() {
Assert.assertEquals(JobStatus.SUCCESS, lastStatus);
Assert.assertTrue("Expected " + mustSeeNext + " but got " + seen, mustSeeNext == null);
}
};
HttpServer server; {
server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/notify", testStatusAndMessages);
server.setExecutor(null);
server.start();
}
try {
JobRequest req; {
ObjectFactory oFactory = new ObjectFactory();
req = oFactory.createJobRequest();
Script script = oFactory.createScript(); {
Optional<String> href = getScriptHref("mock-messages-script");
Assert.assertTrue(href.isPresent());
script.setHref(href.get());
}
req.getScriptOrNicenameOrPriority().add(script);
Input input = oFactory.createInput(); {
Item source = oFactory.createItem();
source.setValue(getResource("hello.xml").toURI().toString());
input.getItem().add(source);
input.setName("source");
}
req.getScriptOrNicenameOrPriority().add(input);
req.getScriptOrNicenameOrPriority().add(oFactory.createNicename("NICE_NAME"));
req.getScriptOrNicenameOrPriority().add(oFactory.createPriority(Priority.LOW));
Callback callback = oFactory.createCallback(); {
callback.setType(CallbackType.MESSAGES);
callback.setHref("http://localhost:8080/notify");
callback.setFrequency("1");
}
req.getScriptOrNicenameOrPriority().add(callback);
callback = oFactory.createCallback(); {
callback.setType(CallbackType.STATUS);
callback.setHref("http://localhost:8080/notify");
callback.setFrequency("1");
}
req.getScriptOrNicenameOrPriority().add(callback);
}
Job job = client().sendJob(req);
deleteAfterTest(job);
waitForStatus(JobStatus.SUCCESS, job, 10000);
// wait until all updates have been pushed
Thread.sleep(1000);
testStatusAndMessages.finalTest();
} finally {
server.stop(1);
}
}
public static abstract class AbstractCallback implements HttpHandler {
abstract void handleStatus(JobStatus status);
abstract void handleMessages(Messages messages);
abstract void finalTest();
@Override
public void handle(HttpExchange t) throws IOException {
Job job; {
try {
job = (Job)JAXBContext.newInstance(Job.class).createUnmarshaller().unmarshal(t.getRequestBody());
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
handleStatus(job.getStatus());
Optional<Messages> messages = getMessages(job);
if (messages.isPresent())
handleMessages(messages.get());
String response = "got it";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static Optional<Messages> getMessages(Job job) {
return Optional.fromNullable(
Iterables.getOnlyElement(
Iterables.filter(
job.getNicenameOrBatchIdOrScript(),
Messages.class),
null));
}
static <T> Stream<T> stream(T... array) {
return Arrays.<T>stream(array);
}
}
| daisy/pipeline-issues | framework/webservice/src/test/java/TestPushNotifications.java | Java | apache-2.0 | 6,214 |
// <copyright file="KeyEvent.cs" company="WebDriver Committers">
// Copyright 2015 Software Freedom Conservancy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
namespace Selenium.Internal.SeleniumEmulation
{
/// <summary>
/// Defines the command for the keyEvent keyword.
/// </summary>
internal class KeyEvent : SeleneseCommand
{
private ElementFinder finder;
private KeyState keyState;
private string eventName;
/// <summary>
/// Initializes a new instance of the <see cref="KeyEvent"/> class.
/// </summary>
/// <param name="elementFinder">An <see cref="ElementFinder"/> used to find the element on which to execute the command.</param>
/// <param name="state">A <see cref="KeyState"/> object defining the state of modifier keys.</param>
/// <param name="eventName">The name of the event to send.</param>
public KeyEvent(ElementFinder elementFinder, KeyState state, string eventName)
{
this.finder = elementFinder;
this.keyState = state;
this.eventName = eventName;
}
/// <summary>
/// Handles the command.
/// </summary>
/// <param name="driver">The driver used to execute the command.</param>
/// <param name="locator">The first parameter to the command.</param>
/// <param name="value">The second parameter to the command.</param>
/// <returns>The result of the command.</returns>
protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value)
{
object[] parameters = new object[]
{
value,
this.keyState.ControlKeyDown,
this.keyState.AltKeyDown,
this.keyState.ShiftKeyDown,
this.keyState.MetaKeyDown
};
JavaScriptLibrary.CallEmbeddedSelenium(driver, this.eventName, this.finder.FindElement(driver, locator), parameters);
return null;
}
}
}
| soundcloud/selenium | dotnet/src/webdriverbackedselenium/Internal/SeleniumEmulation/KeyEvent.cs | C# | apache-2.0 | 2,688 |
/*
* Copyright 2012-2016 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 jetbrains.jetpad.base.edt;
public class BufferingEdtManager extends RunningEdtManager {
public BufferingEdtManager() {
super();
}
public BufferingEdtManager(String name) {
super(name);
}
@Override
protected void doSchedule(Runnable r) {
addTaskToQueue(r);
}
@Override
public String toString() {
return "BufferingEdtManager@" + Integer.toHexString(hashCode()) +
("".equals(getName()) ? "" : " (" + getName()+ ")");
}
} | timzam/jetpad-mapper | util/base/src/test/java/jetbrains/jetpad/base/edt/BufferingEdtManager.java | Java | apache-2.0 | 1,075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.