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
var Alloy = require("alloy"), _ = Alloy._, Backbone = Alloy.Backbone; Alloy.Globals.steps = 0; Alloy.Globals.capacity = 0; Alloy.Globals.basketImage = ""; Alloy.Globals.fruitCount = 0; Alloy.createController("index");
jhenziz/Fruit-Basket
Resources/app.js
JavaScript
apache-2.0
222
/** * <copyright> * </copyright> * * $Id$ */ package de.hub.specificmodels.tests.testsourcemodel.impl; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.impl.EPackageImpl; import de.hub.specificmodels.tests.testsourcemodel.ClassWithListFeatures; import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass1; import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass2; import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass3; import de.hub.specificmodels.tests.testsourcemodel.RootClass; import de.hub.specificmodels.tests.testsourcemodel.TestSourceModelFactory; import de.hub.specificmodels.tests.testsourcemodel.TestSourceModelPackage; /** * <!-- begin-user-doc --> * An implementation of the model <b>Package</b>. * <!-- end-user-doc --> * @generated */ public class TestSourceModelPackageImpl extends EPackageImpl implements TestSourceModelPackage { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass rootClassEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass classWithListFeaturesEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass listFeatureElementClass1EClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass listFeatureElementClass2EClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass listFeatureElementClass3EClass = null; /** * Creates an instance of the model <b>Package</b>, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * <p>Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.emf.ecore.EPackage.Registry * @see de.hub.specificmodels.tests.testsourcemodel.TestSourceModelPackage#eNS_URI * @see #init() * @generated */ private TestSourceModelPackageImpl() { super(eNS_URI, TestSourceModelFactory.eINSTANCE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends. * * <p>This method is used to initialize {@link TestSourceModelPackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static TestSourceModelPackage init() { if (isInited) return (TestSourceModelPackage)EPackage.Registry.INSTANCE.getEPackage(TestSourceModelPackage.eNS_URI); // Obtain or create and register package TestSourceModelPackageImpl theTestSourceModelPackage = (TestSourceModelPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof TestSourceModelPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new TestSourceModelPackageImpl()); isInited = true; // Create package meta-data objects theTestSourceModelPackage.createPackageContents(); // Initialize created meta-data theTestSourceModelPackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theTestSourceModelPackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(TestSourceModelPackage.eNS_URI, theTestSourceModelPackage); return theTestSourceModelPackage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getRootClass() { return rootClassEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getRootClass_AnAttribute1() { return (EAttribute)rootClassEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getRootClass_NormalReference() { return (EReference)rootClassEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getRootClass_Any() { return (EAttribute)rootClassEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getRootClass_NonManyReference() { return (EReference)rootClassEClass.getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getClassWithListFeatures() { return classWithListFeaturesEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getClassWithListFeatures_ListFeature1() { return (EReference)classWithListFeaturesEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getClassWithListFeatures_ListFeature2() { return (EReference)classWithListFeaturesEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getClassWithListFeatures_AnAttribute1() { return (EAttribute)classWithListFeaturesEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getListFeatureElementClass1() { return listFeatureElementClass1EClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getListFeatureElementClass1_Name() { return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getListFeatureElementClass1_ListFeature3() { return (EReference)listFeatureElementClass1EClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getListFeatureElementClass1_AnAttributeOfFeatureClass1() { return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getListFeatureElementClass1_Any() { return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getListFeatureElementClass2() { return listFeatureElementClass2EClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getListFeatureElementClass2_Name() { return (EAttribute)listFeatureElementClass2EClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getListFeatureElementClass2_AnAttributeOfFeatureClass2() { return (EAttribute)listFeatureElementClass2EClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getListFeatureElementClass3() { return listFeatureElementClass3EClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getListFeatureElementClass3_Name() { return (EAttribute)listFeatureElementClass3EClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getListFeatureElementClass3_AnAttributeOfFeatureClass3() { return (EAttribute)listFeatureElementClass3EClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TestSourceModelFactory getTestSourceModelFactory() { return (TestSourceModelFactory)getEFactoryInstance(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features rootClassEClass = createEClass(ROOT_CLASS); createEAttribute(rootClassEClass, ROOT_CLASS__AN_ATTRIBUTE1); createEReference(rootClassEClass, ROOT_CLASS__NORMAL_REFERENCE); createEAttribute(rootClassEClass, ROOT_CLASS__ANY); createEReference(rootClassEClass, ROOT_CLASS__NON_MANY_REFERENCE); classWithListFeaturesEClass = createEClass(CLASS_WITH_LIST_FEATURES); createEReference(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__LIST_FEATURE1); createEReference(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__LIST_FEATURE2); createEAttribute(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__AN_ATTRIBUTE1); listFeatureElementClass1EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS1); createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__NAME); createEReference(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__LIST_FEATURE3); createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__AN_ATTRIBUTE_OF_FEATURE_CLASS1); createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__ANY); listFeatureElementClass2EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS2); createEAttribute(listFeatureElementClass2EClass, LIST_FEATURE_ELEMENT_CLASS2__NAME); createEAttribute(listFeatureElementClass2EClass, LIST_FEATURE_ELEMENT_CLASS2__AN_ATTRIBUTE_OF_FEATURE_CLASS2); listFeatureElementClass3EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS3); createEAttribute(listFeatureElementClass3EClass, LIST_FEATURE_ELEMENT_CLASS3__NAME); createEAttribute(listFeatureElementClass3EClass, LIST_FEATURE_ELEMENT_CLASS3__AN_ATTRIBUTE_OF_FEATURE_CLASS3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(rootClassEClass, RootClass.class, "RootClass", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getRootClass_AnAttribute1(), ecorePackage.getEString(), "anAttribute1", null, 0, 1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getRootClass_NormalReference(), this.getClassWithListFeatures(), null, "normalReference", null, 0, -1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getRootClass_Any(), ecorePackage.getEFeatureMapEntry(), "any", null, 0, -1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getRootClass_NonManyReference(), this.getClassWithListFeatures(), null, "nonManyReference", null, 0, 1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(classWithListFeaturesEClass, ClassWithListFeatures.class, "ClassWithListFeatures", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getClassWithListFeatures_ListFeature1(), this.getListFeatureElementClass1(), null, "listFeature1", null, 0, -1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getClassWithListFeatures_ListFeature2(), this.getListFeatureElementClass2(), null, "listFeature2", null, 0, -1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getClassWithListFeatures_AnAttribute1(), ecorePackage.getEInt(), "anAttribute1", null, 0, 1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(listFeatureElementClass1EClass, ListFeatureElementClass1.class, "ListFeatureElementClass1", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getListFeatureElementClass1_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getListFeatureElementClass1_ListFeature3(), this.getListFeatureElementClass3(), null, "listFeature3", null, 0, -1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getListFeatureElementClass1_AnAttributeOfFeatureClass1(), ecorePackage.getEString(), "anAttributeOfFeatureClass1", null, 0, 1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getListFeatureElementClass1_Any(), ecorePackage.getEFeatureMapEntry(), "any", null, 0, -1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(listFeatureElementClass2EClass, ListFeatureElementClass2.class, "ListFeatureElementClass2", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getListFeatureElementClass2_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass2.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getListFeatureElementClass2_AnAttributeOfFeatureClass2(), ecorePackage.getEString(), "anAttributeOfFeatureClass2", null, 0, 1, ListFeatureElementClass2.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(listFeatureElementClass3EClass, ListFeatureElementClass3.class, "ListFeatureElementClass3", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getListFeatureElementClass3_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass3.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getListFeatureElementClass3_AnAttributeOfFeatureClass3(), ecorePackage.getEString(), "anAttributeOfFeatureClass3", null, 0, 1, ListFeatureElementClass3.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); // Create annotations // http:///org/eclipse/emf/ecore/util/ExtendedMetaData createExtendedMetaDataAnnotations(); } /** * Initializes the annotations for <b>http:///org/eclipse/emf/ecore/util/ExtendedMetaData</b>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void createExtendedMetaDataAnnotations() { String source = "http:///org/eclipse/emf/ecore/util/ExtendedMetaData"; addAnnotation (getRootClass_Any(), source, new String[] { "kind", "elementWildcard", "name", ":1", "processing", "lax", "wildcards", "##any" }); addAnnotation (getListFeatureElementClass1_Any(), source, new String[] { "kind", "elementWildcard", "name", ":1", "processing", "lax", "wildcards", "##any" }); } } //TestSourceModelPackageImpl
markus1978/clickwatch
util/de.hub.specificmodels.test/src-gen/de/hub/specificmodels/tests/testsourcemodel/impl/TestSourceModelPackageImpl.java
Java
apache-2.0
16,757
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.typeCook.deductive.util; import com.intellij.psi.*; import com.intellij.refactoring.typeCook.Settings; import com.intellij.refactoring.typeCook.Util; import java.util.HashSet; /** * @author db */ public class VictimCollector extends Visitor { final HashSet<PsiElement> myVictims = new HashSet<PsiElement>(); final PsiElement[] myElements; final Settings mySettings; public VictimCollector(final PsiElement[] elements, final Settings settings) { myElements = elements; mySettings = settings; } private void testNAdd(final PsiElement element, final PsiType t) { if (Util.isRaw(t, mySettings)) { if (element instanceof PsiNewExpression && t.getCanonicalText().equals("java.lang.Object")){ return; } myVictims.add(element); } } @Override public void visitLocalVariable(final PsiLocalVariable variable) { testNAdd(variable, variable.getType()); super.visitLocalVariable(variable); } @Override public void visitForeachStatement(final PsiForeachStatement statement) { super.visitForeachStatement(statement); final PsiParameter parameter = statement.getIterationParameter(); testNAdd(parameter, parameter.getType()); } @Override public void visitField(final PsiField field) { testNAdd(field, field.getType()); super.visitField(field); } @Override public void visitMethod(final PsiMethod method) { final PsiParameter[] parms = method.getParameterList().getParameters(); for (PsiParameter parm : parms) { testNAdd(parm, parm.getType()); } if (Util.isRaw(method.getReturnType(), mySettings)) { myVictims.add(method); } final PsiCodeBlock body = method.getBody(); if (body != null) { body.accept(this); } } @Override public void visitNewExpression(final PsiNewExpression expression) { if (expression.getClassReference() != null) { testNAdd(expression, expression.getType()); } super.visitNewExpression(expression); } @Override public void visitTypeCastExpression (final PsiTypeCastExpression cast){ final PsiTypeElement typeElement = cast.getCastType(); if (typeElement != null) { testNAdd(cast, typeElement.getType()); } super.visitTypeCastExpression(cast); } @Override public void visitReferenceExpression(final PsiReferenceExpression expression) { } @Override public void visitFile(PsiFile file) { if (file instanceof PsiJavaFile) { super.visitFile(file); } } public HashSet<PsiElement> getVictims() { for (PsiElement element : myElements) { element.accept(this); } return myVictims; } }
joewalnes/idea-community
java/java-impl/src/com/intellij/refactoring/typeCook/deductive/util/VictimCollector.java
Java
apache-2.0
3,283
// Generated from /POI/java/org/apache/poi/hssf/usermodel/HSSFName.java #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <org/apache/poi/hssf/record/fwd-POI.hpp> #include <org/apache/poi/hssf/usermodel/fwd-POI.hpp> #include <org/apache/poi/ss/formula/ptg/fwd-POI.hpp> #include <java/lang/Object.hpp> #include <org/apache/poi/ss/usermodel/Name.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace poi { namespace ss { namespace formula { namespace ptg { typedef ::SubArray< ::poi::ss::formula::ptg::Ptg, ::java::lang::ObjectArray > PtgArray; } // ptg } // formula } // ss } // poi struct default_init_tag; class poi::hssf::usermodel::HSSFName final : public virtual ::java::lang::Object , public ::poi::ss::usermodel::Name { public: typedef ::java::lang::Object super; private: HSSFWorkbook* _book { }; ::poi::hssf::record::NameRecord* _definedNameRec { }; ::poi::hssf::record::NameCommentRecord* _commentRec { }; protected: void ctor(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name); void ctor(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name, ::poi::hssf::record::NameCommentRecord* comment); public: ::java::lang::String* getSheetName() override; ::java::lang::String* getNameName() override; void setNameName(::java::lang::String* nameName) override; private: static void validateName(::java::lang::String* name); public: void setRefersToFormula(::java::lang::String* formulaText) override; ::java::lang::String* getRefersToFormula() override; public: /* package */ void setNameDefinition(::poi::ss::formula::ptg::PtgArray* ptgs); public: bool isDeleted() override; bool isFunctionName() override; ::java::lang::String* toString() override; void setSheetIndex(int32_t index) override; int32_t getSheetIndex() override; ::java::lang::String* getComment() override; void setComment(::java::lang::String* comment) override; void setFunction(bool value) override; // Generated public: /* package */ HSSFName(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name); HSSFName(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name, ::poi::hssf::record::NameCommentRecord* comment); protected: HSSFName(const ::default_init_tag&); public: static ::java::lang::Class *class_(); private: virtual ::java::lang::Class* getClass0(); };
pebble2015/cpoi
src/org/apache/poi/hssf/usermodel/HSSFName.hpp
C++
apache-2.0
2,520
Ext.namespace("Ext.haode"); Ext.haode.Control = function(args){ Ext.apply(this, args); this.init(); }; Ext.haode.Control.prototype = { userName : '', version : '', app_name : '', copyright : '', viewport : null, cn : 1, init : function() { this.viewport = this.getViewport(); }, getViewport : function() { var viewport; if (this.viewport) { viewport = this.viewport; } else { var centerPanel = this.getCenterPanel(); viewport = new Ext.Viewport({ layout: 'fit', items: [centerPanel] }); } return viewport; }, getCenterPanel : function() { var panel; if (this.viewport) { panel = this.getViewport().items[0]; } else { var n = new Ext.Button({ id : 'tsb', text : '发放任务', align : 'right', width : 80, menu : [{ text : '常规任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', timeout : 1000000, url : 'task.do?action=normal', method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } // }, { // text : '个别任务', // handler : function() { // if (!Ext.getCmp('form').getForm().isValid()) { // alert('请正确填写表单'); // return; // } // // var sm = new Ext.grid.CheckboxSelectionModel(); // var store1 = new Ext.data.Store({ // proxy : new Ext.data.HttpProxy({ // url : 'customerManager.do?action=queryAll' // }), // reader : new Ext.data.JsonReader({ // root : 'rows', // totalProperty : 'total', // id : 'id', // fields : ['id', 'name', 'username'] // }) // }); // // var paging = new Ext.PagingToolbar({ // pageSize : 20, // store : store1, // displayInfo : true, // displayMsg : '当前显示数据 {0} - {1} of {2}', // emptyMsg : '没有数据' // }); // // var win = new Ext.Window({ // title : '客户经理', // id : 'bind', // layout : 'fit', // border : false, // modal : true, // width : 500, // height : 400, // items : [new Ext.grid.GridPanel({ // id : 'grid1', // loadMask : true, //// tbar : [{ //// xtype : 'textfield', //// id : 'searchName', //// emptyText : '请输入客户经理名称...', //// width : 150 //// }, { //// text : '搜索', //// width : 45, //// xtype : 'button', //// handler : function() { //// //// } //// }], // store : store1, // sm : sm, // cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { // header : '客户经理名称', // width : 200, // dataIndex : 'name', // align : 'center' // }, { // header : '客户经理用户名', // width : 230, // dataIndex : 'username', // align : 'center' // }]), // bbar : paging // })], // buttons : [{ // text : '确定', // handler : function() { // var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); // if (mrecords.length < 1) { // alert('请选择要做任务的客户经理!'); // return; // } // var mids = ''; // for (var j = 0; j < mrecords.length; j++) { // mids += ',' + mrecords[j].get('id'); // } // // Ext.getCmp('bind').close(); // Ext.getCmp('form').getForm().submit({ // waitTitle : '提示', // waitMsg : '正在提交数据请稍后...', // url : 'task.do?action=indevi', // params : { // mids : mids // }, // method : 'post', // success : function(form, action) { // alert(action.result.myHashMap.msg); // }, // failure : function(form, action) { // alert(action.result.myHashMap.msg); // } // }); // // } // }, { // text : '取消', // handler : function() { // Ext.getCmp('bind').close(); // } // }] // }); // win.show(Ext.getBody()); // store1.load({ // params : { // start : 0, // limit : 20 // } // }); // // } }, { text : '分组任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var sm = new Ext.grid.CheckboxSelectionModel(); var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customerGroup.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var win = new Ext.Window({ title : '客户分组', id : 'bind', layout : 'fit', border : false, modal : true, width : 500, height : 400, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户分组名称', width : 200, dataIndex : 'name', align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var grecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (grecords.length < 1) { alert('请选择客户分组!'); return; } var gids = ''; for (var j = 0; j < grecords.length; j++) { gids += ',' + grecords[j].get('id'); } Ext.getCmp('bind').close(); Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=group', params : { gids : gids }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } }, { text : '取消', handler : function() { Ext.getCmp('bind').close(); } }] }); win.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20, all : 0 } }); } }, { text : '客户任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customer.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager', 'backup_number', 'address', 'order_type', 'gps', 'last_visit_time'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var sm = new Ext.grid.CheckboxSelectionModel(); var win1 = new Ext.Window({ title : '选择客户', id : 'chooseCustomer', layout : 'fit', border : false, modal : true, width : 800, height : 600, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户名称', width : 100, dataIndex : 'name', sortable : true, remoteSort : true, align : 'center' }, { header : '客户编号', width : 130, dataIndex : 'number', sortable : true, remoteSort : true, align : 'center' }, { header : '专卖证号', width : 130, dataIndex : 'sell_number', sortable : true, remoteSort : true, align : 'center' }, { header : '店铺名称', width : 200, dataIndex : 'store_name', sortable : true, remoteSort : true, align : 'left' }, { header : '客户级别', width : 90, dataIndex : 'level', sortable : true, remoteSort : true, align : 'center' }, { header : '电话号码', width : 100, dataIndex : 'phone_number', sortable : true, remoteSort : true, align : 'center' }, { header : '客户经理', width : 120, dataIndex : 'manager', sortable : true, remoteSort : true, align : 'center' }, { header : '备用号码', width : 100, dataIndex : 'backup_number', sortable : true, remoteSort : true, align : 'center' }, { header : '经营地址', width : 240, dataIndex : 'address', sortable : true, remoteSort : true, align : 'left', renderer : function(value, meta) { meta.attr = 'title="' + value + '"'; return value; } }, { header : '订货类型', width : 60, dataIndex : 'order_type', sortable : true, remoteSort : true, align : 'center' }, { header : 'GPS(经度,纬度)', width : 150, dataIndex : 'gps', sortable : true, remoteSort : true, align : 'center' }, { header : '最近一次拜访时间', width : 180, dataIndex : 'last_visit_time', sortable : true, remoteSort : true, align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (crecords.length < 1) { alert('请选择要拜访的客户!'); return; } var size = crecords.length; var cids = ""; for (var i = 0; i < size; i++) { cids += ',' + crecords[i].get('id'); } Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=customerTask', params : { cids : cids }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); Ext.getCmp('chooseCustomer').close(); } }, { text : '取消', handler : function() { Ext.getCmp('chooseCustomer').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }, { text : '自定义任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var cids = ''; var mid = ''; var win = new Ext.Window({ title : '自定义任务', id : 'editWin', layout : 'fit', border : false, modal : true, width : 500, height : 250, items : [new Ext.form.FormPanel({ id : 'editForm', frame : true, bodyStyle : 'padding : 30px; 20px;', defaults : { msgTarget : 'under' }, height : 'auto', labelWidth : 80, labelAlign : 'right', items : [{ xtype : 'compositefield', width : 500, items : [{ fieldLabel : '客户名称', xtype : 'textfield', id : 'customer', allowBlank : false, width : 300 }, { text : '浏览…', xtype : 'button', handler : function() { // 选择客户 var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customer.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager', 'backup_number', 'address', 'order_type', 'gps', 'last_visit_time'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var sm = new Ext.grid.CheckboxSelectionModel(); var win1 = new Ext.Window({ title : '选择客户', id : 'chooseCustomer', layout : 'fit', border : false, modal : true, width : 800, height : 600, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户名称', width : 100, dataIndex : 'name', sortable : true, remoteSort : true, align : 'center' }, { header : '客户编号', width : 130, dataIndex : 'number', sortable : true, remoteSort : true, align : 'center' }, { header : '专卖证号', width : 130, dataIndex : 'sell_number', sortable : true, remoteSort : true, align : 'center' }, { header : '店铺名称', width : 200, dataIndex : 'store_name', sortable : true, remoteSort : true, align : 'left' }, { header : '客户级别', width : 90, dataIndex : 'level', sortable : true, remoteSort : true, align : 'center' }, { header : '电话号码', width : 100, dataIndex : 'phone_number', sortable : true, remoteSort : true, align : 'center' }, { header : '客户经理', width : 120, dataIndex : 'manager', sortable : true, remoteSort : true, align : 'center' }, { header : '备用号码', width : 100, dataIndex : 'backup_number', sortable : true, remoteSort : true, align : 'center' }, { header : '经营地址', width : 240, dataIndex : 'address', sortable : true, remoteSort : true, align : 'left', renderer : function(value, meta) { meta.attr = 'title="' + value + '"'; return value; } }, { header : '订货类型', width : 60, dataIndex : 'order_type', sortable : true, remoteSort : true, align : 'center' }, { header : 'GPS(经度,纬度)', width : 150, dataIndex : 'gps', sortable : true, remoteSort : true, align : 'center' }, { header : '最近一次拜访时间', width : 180, dataIndex : 'last_visit_time', sortable : true, remoteSort : true, align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (crecords.length < 1) { alert('请选择要拜访的客户!'); return; } var size = crecords.length; var cnames = ''; for (var i = 0; i < size; i++) { cids += ',' + crecords[i].get('id'); cnames += ',' + crecords[i].get('name'); } Ext.getCmp('customer').setValue(cnames.substring(1)); Ext.getCmp('chooseCustomer').close(); } }, { text : '取消', handler : function() { Ext.getCmp('chooseCustomer').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }] }, { xtype : 'compositefield', width : 500, items : [{ fieldLabel : '客户经理', xtype : 'textfield', id : 'manager', allowBlank : false, width : 300 }, { text : '浏览…', xtype : 'button', handler : function() { // 选择客户经理 var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customerManager.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'username', 'department', 'area'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var win1 = new Ext.Window({ title : '选择客户经理', id : 'bind', layout : 'fit', border : false, modal : true, width : 600, height : 400, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), { header : '客户经理名称', width : 130, dataIndex : 'name', align : 'center' }, { header : '用户名', width : 130, dataIndex : 'username', align : 'center' }, { header : '部门', width : 130, dataIndex : 'department', align : 'center' }, { header : '片区', width : 130, dataIndex : 'area', align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (mrecords.length < 1) { alert('请选择客户经理!'); return; } mid = mrecords[0].get('id'); var manager = mrecords[0].get('name'); if (mrecords[0].get('department') != "") { manager = manager + "-" + mrecords[0].get('department'); } if (mrecords[0].get('area') != "") { manager = manager + "-" + mrecords[0].get('area'); } Ext.getCmp('manager').setValue(manager); Ext.getCmp('bind').close(); } }, { text : '取消', handler : function() { Ext.getCmp('bind').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }] }], buttons : [{ text : '确定', handler : function() { Ext.getCmp('editWin').close(); Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=newCustomerTask', params : { mid : mid, cids : cids, }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } }, { text : '取消', handler : function() { Ext.getCmp('editWin').close(); } }] })] }); win.show(Ext.getBody()); } }] }); panel = new Ext.form.FormPanel({ id : 'form', defaults : { width : 250, msgTarget : 'under' }, bodyStyle : 'padding : 50px; 150px;', labelWidth : 80, labelAlign : 'right', tbar : [{ xtype : 'button', id : 'ad', iconCls : 'add', text : '增加内容', align : 'right', width : 80, handler : function() { this.cn = this.cn + 1; var f = Ext.getCmp('form'); var a = Ext.getCmp('ad'); var t = Ext.getCmp('tsb'); var c = new Ext.form.TextField({ fieldLabel : '任务内容' + this.cn, allowBlank : false, name : 'content' + this.cn, id : 'content' + this.cn, xtype : 'textfield' }); f.remove(t); f.add(c); f.add(n); f.doLayout(); }, scope : this }], items : [{ fieldLabel : '任务起始时间', allowBlank : false, editable : false, name : 'start', id : 'start', xtype : 'datefield' }, { fieldLabel : '任务完成时间', allowBlank : false, editable : false, name : 'end', id : 'end', xtype : 'datefield' }, { fieldLabel : '任务标题', allowBlank : false, name : 'content', id : 'content', xtype : 'textfield' }, { fieldLabel : '任务内容' + this.cn, allowBlank : false, name : 'content' + this.cn, id : 'content' + this.cn, xtype : 'textfield' }, { xtype : 'button', id : 'tsb', text : '发放任务', align : 'right', width : 80, menu : [{ text : '常规任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=normal', method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } // }, { // text : '个别任务', // handler : function() { // if (!Ext.getCmp('form').getForm().isValid()) { // alert('请正确填写表单'); // return; // } // // // var sm = new Ext.grid.CheckboxSelectionModel(); // var store1 = new Ext.data.Store({ // proxy : new Ext.data.HttpProxy({ // url : 'customerManager.do?action=queryAll' // }), // reader : new Ext.data.JsonReader({ // root : 'rows', // totalProperty : 'total', // id : 'id', // fields : ['id', 'name', 'username'] // }) // }); // // var paging = new Ext.PagingToolbar({ // pageSize : 20, // store : store1, // displayInfo : true, // displayMsg : '当前显示数据 {0} - {1} of {2}', // emptyMsg : '没有数据' // }); // // var win = new Ext.Window({ // title : '客户经理', // id : 'bind', // layout : 'fit', // border : false, // modal : true, // width : 500, // height : 400, // items : [new Ext.grid.GridPanel({ // id : 'grid1', // loadMask : true, //// tbar : [{ //// xtype : 'textfield', //// id : 'searchName', //// emptyText : '请输入客户经理名称...', //// width : 150 //// }, { //// text : '搜索', //// width : 45, //// xtype : 'button', //// handler : function() { //// //// } //// }], // store : store1, // sm : sm, // cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { // header : '客户经理名称', // width : 200, // dataIndex : 'name', // align : 'center' // }, { // header : '客户经理用户名', // width : 230, // dataIndex : 'username', // align : 'center' // }]), // bbar : paging // })], // buttons : [{ // text : '确定', // handler : function() { // var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); // if (mrecords.length < 1) { // alert('请选择要做任务的客户经理!'); // return; // } // var mids = ''; // for (var j = 0; j < mrecords.length; j++) { // mids += ',' + mrecords[j].get('id'); // } // // Ext.getCmp('bind').close(); // Ext.getCmp('form').getForm().submit({ // waitTitle : '提示', // waitMsg : '正在提交数据请稍后...', // url : 'task.do?action=indevi', // params : { // mids : mids // }, // method : 'post', // success : function(form, action) { // alert(action.result.myHashMap.msg); // }, // failure : function(form, action) { // alert(action.result.myHashMap.msg); // } // }); // // } // }, { // text : '取消', // handler : function() { // Ext.getCmp('bind').close(); // } // }] // }); // win.show(Ext.getBody()); // store1.load({ // params : { // start : 0, // limit : 20 // } // }); // // } }, { text : '分组任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var sm = new Ext.grid.CheckboxSelectionModel(); var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customerGroup.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var win = new Ext.Window({ title : '客户分组', id : 'bind', layout : 'fit', border : false, modal : true, width : 500, height : 400, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户分组名称', width : 200, dataIndex : 'name', align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var grecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (grecords.length < 1) { alert('请选择客户分组!'); return; } var gids = ''; for (var j = 0; j < grecords.length; j++) { gids += ',' + grecords[j].get('id'); } Ext.getCmp('bind').close(); Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=group', params : { gids : gids }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } }, { text : '取消', handler : function() { Ext.getCmp('bind').close(); } }] }); win.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20, all : 0 } }); } }, { text : '客户任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customer.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager', 'backup_number', 'address', 'order_type', 'gps', 'last_visit_time'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var sm = new Ext.grid.CheckboxSelectionModel(); var win1 = new Ext.Window({ title : '选择客户', id : 'chooseCustomer', layout : 'fit', border : false, modal : true, width : 800, height : 600, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户名称', width : 100, dataIndex : 'name', sortable : true, remoteSort : true, align : 'center' }, { header : '客户编号', width : 130, dataIndex : 'number', sortable : true, remoteSort : true, align : 'center' }, { header : '专卖证号', width : 130, dataIndex : 'sell_number', sortable : true, remoteSort : true, align : 'center' }, { header : '店铺名称', width : 200, dataIndex : 'store_name', sortable : true, remoteSort : true, align : 'left' }, { header : '客户级别', width : 90, dataIndex : 'level', sortable : true, remoteSort : true, align : 'center' }, { header : '电话号码', width : 100, dataIndex : 'phone_number', sortable : true, remoteSort : true, align : 'center' }, { header : '客户经理', width : 120, dataIndex : 'manager', sortable : true, remoteSort : true, align : 'center' }, { header : '备用号码', width : 100, dataIndex : 'backup_number', sortable : true, remoteSort : true, align : 'center' }, { header : '经营地址', width : 240, dataIndex : 'address', sortable : true, remoteSort : true, align : 'left', renderer : function(value, meta) { meta.attr = 'title="' + value + '"'; return value; } }, { header : '订货类型', width : 60, dataIndex : 'order_type', sortable : true, remoteSort : true, align : 'center' }, { header : 'GPS(经度,纬度)', width : 150, dataIndex : 'gps', sortable : true, remoteSort : true, align : 'center' }, { header : '最近一次拜访时间', width : 180, dataIndex : 'last_visit_time', sortable : true, remoteSort : true, align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (crecords.length < 1) { alert('请选择要拜访的客户!'); return; } var size = crecords.length; var cids = ""; for (var i = 0; i < size; i++) { cids += ',' + crecords[i].get('id'); } Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=customerTask', params : { cids : cids }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); Ext.getCmp('chooseCustomer').close(); } }, { text : '取消', handler : function() { Ext.getCmp('chooseCustomer').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }, { text : '自定义任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var cids = ''; var mid = ''; var win = new Ext.Window({ title : '自定义任务', id : 'editWin', layout : 'fit', border : false, modal : true, width : 500, height : 250, items : [new Ext.form.FormPanel({ id : 'editForm', frame : true, bodyStyle : 'padding : 30px; 20px;', defaults : { msgTarget : 'under' }, height : 'auto', labelWidth : 80, labelAlign : 'right', items : [{ xtype : 'compositefield', width : 500, items : [{ fieldLabel : '客户名称', xtype : 'textfield', id : 'customer', allowBlank : false, width : 300 }, { text : '浏览…', xtype : 'button', handler : function() { // 选择客户 var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customer.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager', 'backup_number', 'address', 'order_type', 'gps', 'last_visit_time'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var sm = new Ext.grid.CheckboxSelectionModel(); var win1 = new Ext.Window({ title : '选择客户', id : 'chooseCustomer', layout : 'fit', border : false, modal : true, width : 800, height : 600, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户名称', width : 100, dataIndex : 'name', sortable : true, remoteSort : true, align : 'center' }, { header : '客户编号', width : 130, dataIndex : 'number', sortable : true, remoteSort : true, align : 'center' }, { header : '专卖证号', width : 130, dataIndex : 'sell_number', sortable : true, remoteSort : true, align : 'center' }, { header : '店铺名称', width : 200, dataIndex : 'store_name', sortable : true, remoteSort : true, align : 'left' }, { header : '客户级别', width : 90, dataIndex : 'level', sortable : true, remoteSort : true, align : 'center' }, { header : '电话号码', width : 100, dataIndex : 'phone_number', sortable : true, remoteSort : true, align : 'center' }, { header : '客户经理', width : 120, dataIndex : 'manager', sortable : true, remoteSort : true, align : 'center' }, { header : '备用号码', width : 100, dataIndex : 'backup_number', sortable : true, remoteSort : true, align : 'center' }, { header : '经营地址', width : 240, dataIndex : 'address', sortable : true, remoteSort : true, align : 'left', renderer : function(value, meta) { meta.attr = 'title="' + value + '"'; return value; } }, { header : '订货类型', width : 60, dataIndex : 'order_type', sortable : true, remoteSort : true, align : 'center' }, { header : 'GPS(经度,纬度)', width : 150, dataIndex : 'gps', sortable : true, remoteSort : true, align : 'center' }, { header : '最近一次拜访时间', width : 180, dataIndex : 'last_visit_time', sortable : true, remoteSort : true, align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (crecords.length < 1) { alert('请选择要拜访的客户!'); return; } var size = crecords.length; var cnames = ''; for (var i = 0; i < size; i++) { cids += ',' + crecords[i].get('id'); cnames += ',' + crecords[i].get('name'); } Ext.getCmp('customer').setValue(cnames.substring(1)); Ext.getCmp('chooseCustomer').close(); } }, { text : '取消', handler : function() { Ext.getCmp('chooseCustomer').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }] }, { xtype : 'compositefield', width : 500, items : [{ fieldLabel : '客户经理', xtype : 'textfield', id : 'manager', allowBlank : false, width : 300 }, { text : '浏览…', xtype : 'button', handler : function() { // 选择客户经理 var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customerManager.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'username', 'department', 'area'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var win1 = new Ext.Window({ title : '选择客户经理', id : 'bind', layout : 'fit', border : false, modal : true, width : 600, height : 400, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), { header : '客户经理名称', width : 130, dataIndex : 'name', align : 'center' }, { header : '用户名', width : 130, dataIndex : 'username', align : 'center' }, { header : '部门', width : 130, dataIndex : 'department', align : 'center' }, { header : '片区', width : 130, dataIndex : 'area', align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (mrecords.length < 1) { alert('请选择客户经理!'); return; } mid = mrecords[0].get('id'); var manager = mrecords[0].get('name'); if (mrecords[0].get('department') != "") { manager = manager + "-" + mrecords[0].get('department'); } if (mrecords[0].get('area') != "") { manager = manager + "-" + mrecords[0].get('area'); } Ext.getCmp('manager').setValue(manager); Ext.getCmp('bind').close(); } }, { text : '取消', handler : function() { Ext.getCmp('bind').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }] }], buttons : [{ text : '确定', handler : function() { Ext.getCmp('editWin').close(); Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=newCustomerTask', params : { mid : mid, cids : cids, }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } }, { text : '取消', handler : function() { Ext.getCmp('editWin').close(); } }] })] }); win.show(Ext.getBody()); } }] }] }); } return panel; } };
hairlun/customer-visit-web
WebRoot/task/index.js
JavaScript
apache-2.0
49,167
<?php namespace App\Presenters; use Nette; class ContactPresenter extends Nette\Application\UI\Presenter { }
literat/ete89e
app/presenters/ContactPresenter.php
PHP
apache-2.0
113
/** * Copyright 2002-2016 xiaoyuepeng * * 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. * * * @author xiaoyuepeng <[email protected]> */ package com.xyp260466.dubbo.annotation; import java.lang.annotation.*; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Created by xyp on 16-5-9. */ @Target({TYPE, FIELD, METHOD}) @Retention(RUNTIME) @Documented public @interface Consumer { String value() default ""; }
xyp260466/dubbo-lite
dubbo-spring/src/main/java/com/xyp260466/dubbo/annotation/Consumer.java
Java
apache-2.0
1,109
<?php namespace Test\Controllers; use Test\Models\EmailConfirmations; use Test\Models\ResetPasswords; /** * UserControlController * Provides help to users to confirm their passwords or reset them */ class UserControlController extends ControllerBase { public function initialize() { if ($this->session->has('auth-identity')) { $this->view->setTemplateBefore('private'); } } public function indexAction() { } /** * Confirms an e-mail, if the user must change thier password then changes it */ public function confirmEmailAction() { $code = $this->dispatcher->getParam('code'); $confirmation = EmailConfirmations::findFirstByCode($code); if (!$confirmation) { return $this->dispatcher->forward([ 'controller' => 'index', 'action' => 'index' ]); } if ($confirmation->confirmed != 'N') { return $this->dispatcher->forward([ 'controller' => 'session', 'action' => 'login' ]); } $confirmation->confirmed = 'Y'; $confirmation->user->active = 'Y'; /** * Change the confirmation to 'confirmed' and update the user to 'active' */ if (!$confirmation->save()) { foreach ($confirmation->getMessages() as $message) { $this->flash->error($message); } return $this->dispatcher->forward([ 'controller' => 'index', 'action' => 'index' ]); } /** * Identify the user in the application */ $this->auth->authUserById($confirmation->user->id); /** * Check if the user must change his/her password */ if ($confirmation->user->mustChangePassword == 'Y') { $this->flash->success('The email was successfully confirmed. Now you must change your password'); return $this->dispatcher->forward([ 'controller' => 'users', 'action' => 'changePassword' ]); } $this->flash->success('The email was successfully confirmed'); return $this->dispatcher->forward([ 'controller' => 'users', 'action' => 'index' ]); } public function resetPasswordAction() { $code = $this->dispatcher->getParam('code'); $resetPassword = ResetPasswords::findFirstByCode($code); if (!$resetPassword) { return $this->dispatcher->forward([ 'controller' => 'index', 'action' => 'index' ]); } if ($resetPassword->reset != 'N') { return $this->dispatcher->forward([ 'controller' => 'session', 'action' => 'login' ]); } $resetPassword->reset = 'Y'; /** * Change the confirmation to 'reset' */ if (!$resetPassword->save()) { foreach ($resetPassword->getMessages() as $message) { $this->flash->error($message); } return $this->dispatcher->forward([ 'controller' => 'index', 'action' => 'index' ]); } /** * Identify the user in the application */ $this->auth->authUserById($resetPassword->usersId); $this->flash->success('Please reset your password'); return $this->dispatcher->forward([ 'controller' => 'users', 'action' => 'changePassword' ]); } }
tetrapak07/testPhalcon
app/controllers/UserControlController.php
PHP
apache-2.0
3,697
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import org.apache.commons.logging.*; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol; import org.apache.hadoop.hdfs.protocol.FSConstants; import org.apache.hadoop.hdfs.server.common.HdfsConstants; import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException; import org.apache.hadoop.ipc.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Daemon; import org.apache.hadoop.http.HttpServer; import org.apache.hadoop.net.NetUtils; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.apache.hadoop.metrics.jvm.JvmMetrics; /********************************************************** * The Secondary NameNode is a helper to the primary NameNode. The Secondary is * responsible for supporting periodic checkpoints of the HDFS metadata. The * current design allows only one Secondary NameNode per HDFs cluster. * * The Secondary NameNode is a daemon that periodically wakes up (determined by * the schedule specified in the configuration), triggers a periodic checkpoint * and then goes back to sleep. The Secondary NameNode uses the ClientProtocol * to talk to the primary NameNode. * **********************************************************/ public class SecondaryNameNode implements Runnable { public static final Log LOG = LogFactory.getLog(SecondaryNameNode.class .getName()); private String fsName; private CheckpointStorage checkpointImage; private NamenodeProtocol namenode; private Configuration conf; private InetSocketAddress nameNodeAddr; private volatile boolean shouldRun; private HttpServer infoServer; private int infoPort; private String infoBindAddress; private Collection<File> checkpointDirs; private Collection<File> checkpointEditsDirs; private long checkpointPeriod; // in seconds private long checkpointSize; // size (in MB) of current Edit Log /** * Utility class to facilitate junit test error simulation. */ static class ErrorSimulator { private static boolean[] simulation = null; // error simulation events static void initializeErrorSimulationEvent(int numberOfEvents) { simulation = new boolean[numberOfEvents]; for (int i = 0; i < numberOfEvents; i++) { simulation[i] = false; } } static boolean getErrorSimulation(int index) { if (simulation == null) return false; assert (index < simulation.length); return simulation[index]; } static void setErrorSimulation(int index) { assert (index < simulation.length); simulation[index] = true; } static void clearErrorSimulation(int index) { assert (index < simulation.length); simulation[index] = false; } } FSImage getFSImage() { return checkpointImage; } /** * Create a connection to the primary namenode. */ public SecondaryNameNode(Configuration conf) throws IOException { try { initialize(conf); } catch (IOException e) { shutdown(); throw e; } } /** * Initialize SecondaryNameNode. */ private void initialize(Configuration conf) throws IOException { // initiate Java VM metrics JvmMetrics.init("SecondaryNameNode", conf.get("session.id")); // Create connection to the namenode. shouldRun = true; nameNodeAddr = NameNode.getAddress(conf); this.conf = conf; this.namenode = (NamenodeProtocol) RPC.waitForProxy( NamenodeProtocol.class, NamenodeProtocol.versionID, nameNodeAddr, conf); // initialize checkpoint directories fsName = getInfoServer(); checkpointDirs = FSImage.getCheckpointDirs(conf, "/tmp/hadoop/dfs/namesecondary"); checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf, "/tmp/hadoop/dfs/namesecondary"); checkpointImage = new CheckpointStorage(); checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs); // Initialize other scheduling parameters from the configuration checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600); checkpointSize = conf.getLong("fs.checkpoint.size", 4194304); // initialize the webserver for uploading files. String infoAddr = NetUtils.getServerAddress(conf, "dfs.secondary.info.bindAddress", "dfs.secondary.info.port", "dfs.secondary.http.address"); InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr); infoBindAddress = infoSocAddr.getHostName(); int tmpInfoPort = infoSocAddr.getPort(); infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort, tmpInfoPort == 0, conf); infoServer.setAttribute("name.system.image", checkpointImage); this.infoServer.setAttribute("name.conf", conf); infoServer.addInternalServlet("getimage", "/getimage", GetImageServlet.class); infoServer.start(); // The web-server port can be ephemeral... ensure we have the correct // info infoPort = infoServer.getPort(); conf .set("dfs.secondary.http.address", infoBindAddress + ":" + infoPort); LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" + infoPort); LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " + "(" + checkpointPeriod / 60 + " min)"); LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " + "(" + checkpointSize / 1024 + " KB)"); } /** * Shut down this instance of the datanode. Returns only after shutdown is * complete. */ public void shutdown() { shouldRun = false; try { if (infoServer != null) infoServer.stop(); } catch (Exception e) { LOG.warn("Exception shutting down SecondaryNameNode", e); } try { if (checkpointImage != null) checkpointImage.close(); } catch (IOException e) { LOG.warn(StringUtils.stringifyException(e)); } } // // The main work loop // public void run() { // // Poll the Namenode (once every 5 minutes) to find the size of the // pending edit log. // long period = 5 * 60; // 5 minutes long lastCheckpointTime = 0; if (checkpointPeriod < period) { period = checkpointPeriod; } while (shouldRun) { try { Thread.sleep(1000 * period); } catch (InterruptedException ie) { // do nothing } if (!shouldRun) { break; } try { long now = System.currentTimeMillis(); long size = namenode.getEditLogSize(); if (size >= checkpointSize || now >= lastCheckpointTime + 1000 * checkpointPeriod) { doCheckpoint(); lastCheckpointTime = now; } } catch (IOException e) { LOG.error("Exception in doCheckpoint: "); LOG.error(StringUtils.stringifyException(e)); e.printStackTrace(); } catch (Throwable e) { LOG.error("Throwable Exception in doCheckpoint: "); LOG.error(StringUtils.stringifyException(e)); e.printStackTrace(); Runtime.getRuntime().exit(-1); } } } /** * Download <code>fsimage</code> and <code>edits</code> files from the * name-node. * * @throws IOException */ private void downloadCheckpointFiles(CheckpointSignature sig) throws IOException { checkpointImage.cTime = sig.cTime; checkpointImage.checkpointTime = sig.checkpointTime; // get fsimage String fileid = "getimage=1"; File[] srcNames = checkpointImage.getImageFiles(); assert srcNames.length > 0 : "No checkpoint targets."; TransferFsImage.getFileClient(fsName, fileid, srcNames); LOG.info("Downloaded file " + srcNames[0].getName() + " size " + srcNames[0].length() + " bytes."); // get edits file fileid = "getedit=1"; srcNames = checkpointImage.getEditsFiles(); assert srcNames.length > 0 : "No checkpoint targets."; TransferFsImage.getFileClient(fsName, fileid, srcNames); LOG.info("Downloaded file " + srcNames[0].getName() + " size " + srcNames[0].length() + " bytes."); checkpointImage.checkpointUploadDone(); } /** * Copy the new fsimage into the NameNode */ private void putFSImage(CheckpointSignature sig) throws IOException { String fileid = "putimage=1&port=" + infoPort + "&machine=" + InetAddress.getLocalHost().getHostAddress() + "&token=" + sig.toString(); LOG.info("Posted URL " + fsName + fileid); TransferFsImage.getFileClient(fsName, fileid, (File[]) null); } /** * Returns the Jetty server that the Namenode is listening on. */ private String getInfoServer() throws IOException { URI fsName = FileSystem.getDefaultUri(conf); if (!"hdfs".equals(fsName.getScheme())) { throw new IOException("This is not a DFS"); } return NetUtils.getServerAddress(conf, "dfs.info.bindAddress", "dfs.info.port", "dfs.http.address"); } /** * Create a new checkpoint */ void doCheckpoint() throws IOException { // Do the required initialization of the merge work area. startCheckpoint(); // Tell the namenode to start logging transactions in a new edit file // Retuns a token that would be used to upload the merged image. CheckpointSignature sig = (CheckpointSignature) namenode.rollEditLog(); // error simulation code for junit test if (ErrorSimulator.getErrorSimulation(0)) { throw new IOException("Simulating error0 " + "after creating edits.new"); } downloadCheckpointFiles(sig); // Fetch fsimage and edits doMerge(sig); // Do the merge // // Upload the new image into the NameNode. Then tell the Namenode // to make this new uploaded image as the most current image. // putFSImage(sig); // error simulation code for junit test if (ErrorSimulator.getErrorSimulation(1)) { throw new IOException("Simulating error1 " + "after uploading new image to NameNode"); } namenode.rollFsImage(); checkpointImage.endCheckpoint(); LOG.warn("Checkpoint done. New Image Size: " + checkpointImage.getFsImageName().length()); } private void startCheckpoint() throws IOException { checkpointImage.unlockAll(); checkpointImage.getEditLog().close(); checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs); checkpointImage.startCheckpoint(); } /** * Merge downloaded image and edits and write the new image into current * storage directory. */ private void doMerge(CheckpointSignature sig) throws IOException { FSNamesystem namesystem = new FSNamesystem(checkpointImage, conf); assert namesystem.dir.fsImage == checkpointImage; checkpointImage.doMerge(sig); } /** * @param argv * The parameters passed to this program. * @exception Exception * if the filesystem does not exist. * @return 0 on success, non zero on error. */ private int processArgs(String[] argv) throws Exception { if (argv.length < 1) { printUsage(""); return -1; } int exitCode = -1; int i = 0; String cmd = argv[i++]; // // verify that we have enough command line parameters // if ("-geteditsize".equals(cmd)) { if (argv.length != 1) { printUsage(cmd); return exitCode; } } else if ("-checkpoint".equals(cmd)) { if (argv.length != 1 && argv.length != 2) { printUsage(cmd); return exitCode; } if (argv.length == 2 && !"force".equals(argv[i])) { printUsage(cmd); return exitCode; } } exitCode = 0; try { if ("-checkpoint".equals(cmd)) { long size = namenode.getEditLogSize(); if (size >= checkpointSize || argv.length == 2 && "force".equals(argv[i])) { doCheckpoint(); } else { System.err.println("EditLog size " + size + " bytes is " + "smaller than configured checkpoint " + "size " + checkpointSize + " bytes."); System.err.println("Skipping checkpoint."); } } else if ("-geteditsize".equals(cmd)) { long size = namenode.getEditLogSize(); System.out.println("EditLog size is " + size + " bytes"); } else { exitCode = -1; LOG.error(cmd.substring(1) + ": Unknown command"); printUsage(""); } } catch (RemoteException e) { // // This is a error returned by hadoop server. Print // out the first line of the error mesage, ignore the stack trace. exitCode = -1; try { String[] content; content = e.getLocalizedMessage().split("\n"); LOG.error(cmd.substring(1) + ": " + content[0]); } catch (Exception ex) { LOG.error(cmd.substring(1) + ": " + ex.getLocalizedMessage()); } } catch (IOException e) { // // IO exception encountered locally. // exitCode = -1; LOG.error(cmd.substring(1) + ": " + e.getLocalizedMessage()); } finally { // Does the RPC connection need to be closed? } return exitCode; } /** * Displays format of commands. * * @param cmd * The command that is being executed. */ private void printUsage(String cmd) { if ("-geteditsize".equals(cmd)) { System.err.println("Usage: java SecondaryNameNode" + " [-geteditsize]"); } else if ("-checkpoint".equals(cmd)) { System.err.println("Usage: java SecondaryNameNode" + " [-checkpoint [force]]"); } else { System.err.println("Usage: java SecondaryNameNode " + "[-checkpoint [force]] " + "[-geteditsize] "); } } /** * main() has some simple utility methods. * * @param argv * Command line parameters. * @exception Exception * if the filesystem does not exist. */ public static void main(String[] argv) throws Exception { StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG); Configuration tconf = new Configuration(); if (argv.length >= 1) { SecondaryNameNode secondary = new SecondaryNameNode(tconf); int ret = secondary.processArgs(argv); System.exit(ret); } // Create a never ending deamon Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf)); checkpointThread.start(); } static class CheckpointStorage extends FSImage { /** */ CheckpointStorage() throws IOException { super(); } @Override public boolean isConversionNeeded(StorageDirectory sd) { return false; } /** * Analyze checkpoint directories. Create directories if they do not * exist. Recover from an unsuccessful checkpoint is necessary. * * @param dataDirs * @param editsDirs * @throws IOException */ void recoverCreate(Collection<File> dataDirs, Collection<File> editsDirs) throws IOException { Collection<File> tempDataDirs = new ArrayList<File>(dataDirs); Collection<File> tempEditsDirs = new ArrayList<File>(editsDirs); this.storageDirs = new ArrayList<StorageDirectory>(); setStorageDirectories(tempDataDirs, tempEditsDirs); for (Iterator<StorageDirectory> it = dirIterator(); it.hasNext();) { StorageDirectory sd = it.next(); boolean isAccessible = true; try { // create directories if don't exist yet if (!sd.getRoot().mkdirs()) { // do nothing, directory is already created } } catch (SecurityException se) { isAccessible = false; } if (!isAccessible) throw new InconsistentFSStateException(sd.getRoot(), "cannot access checkpoint directory."); StorageState curState; try { curState = sd .analyzeStorage(HdfsConstants.StartupOption.REGULAR); // sd is locked but not opened switch (curState) { case NON_EXISTENT: // fail if any of the configured checkpoint dirs are // inaccessible throw new InconsistentFSStateException(sd.getRoot(), "checkpoint directory does not exist or is not accessible."); case NOT_FORMATTED: break; // it's ok since initially there is no current // and VERSION case NORMAL: break; default: // recovery is possible sd.doRecover(curState); } } catch (IOException ioe) { sd.unlock(); throw ioe; } } } /** * Prepare directories for a new checkpoint. * <p> * Rename <code>current</code> to <code>lastcheckpoint.tmp</code> and * recreate <code>current</code>. * * @throws IOException */ void startCheckpoint() throws IOException { for (StorageDirectory sd : storageDirs) { File curDir = sd.getCurrentDir(); File tmpCkptDir = sd.getLastCheckpointTmp(); assert !tmpCkptDir.exists() : tmpCkptDir.getName() + " directory must not exist."; if (curDir.exists()) { // rename current to tmp rename(curDir, tmpCkptDir); } if (!curDir.mkdir()) throw new IOException("Cannot create directory " + curDir); } } void endCheckpoint() throws IOException { for (StorageDirectory sd : storageDirs) { File tmpCkptDir = sd.getLastCheckpointTmp(); File prevCkptDir = sd.getPreviousCheckpoint(); // delete previous dir if (prevCkptDir.exists()) deleteDir(prevCkptDir); // rename tmp to previous if (tmpCkptDir.exists()) rename(tmpCkptDir, prevCkptDir); } } /** * Merge image and edits, and verify consistency with the signature. */ private void doMerge(CheckpointSignature sig) throws IOException { getEditLog().open(); StorageDirectory sdName = null; StorageDirectory sdEdits = null; Iterator<StorageDirectory> it = null; it = dirIterator(NameNodeDirType.IMAGE); if (it.hasNext()) sdName = it.next(); it = dirIterator(NameNodeDirType.EDITS); if (it.hasNext()) sdEdits = it.next(); if ((sdName == null) || (sdEdits == null)) throw new IOException("Could not locate checkpoint directories"); loadFSImage(FSImage.getImageFile(sdName, NameNodeFile.IMAGE)); loadFSEdits(sdEdits); sig.validateStorageInfo(this); saveFSImage(); } } }
shot/hadoop-source-reading
src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java
Java
apache-2.0
18,270
"""Custom Exception Classes for Phylotyper Module """ class PhylotyperError(Exception): """Basic exception for errors raised by Phylotyper modules""" def __init__(self, subtype, msg=None): if msg is None: msg = "An error occured for subtype {}".format(subtype) super(PhylotyperError, self).__init__(msg) self.subtype = subtype class ValuesError(PhylotyperError): """Unknown subtype""" def __init__(self, subtype, msg=None): super(PhylotyperError, self).__init__( subtype, msg="Unrecognized subtype {}".format(subtype)) class DatabaseError(PhylotyperError): """Missing data in Database""" def __init__(self, subtype, data, msg=None): m = "Database is missing data {} for {}".format(data, subtype) super(PhylotyperError, self).__init__(subtype, m) self.data = data
superphy/backend
app/modules/phylotyper/exceptions.py
Python
apache-2.0
874
<span class="boolfield"> <i class="{{ type.color }} {{ type.icon }}" aria-hidden="true"></i> {{ bool }} </span>
openstack/mistral-dashboard
mistraldashboard/default/templates/default/_booleanfield.html
HTML
apache-2.0
120
% Date Picker ## About A Date Picker is a control used for selecting a date. ## API Reference [moon.DatePicker]($api/#/kind/moon.DatePicker) ## Behavior When closed, the first title line should inform the user of the picker's function. The second line of text shows the currently selected value. When the picker is open, all content below is pushed downwards to make room for the entire height of the picker control in its open state. After selections have been made, pressing Enter/OK on the picker title will close the control. Once the picker is closed, the selected value(s) appear beneath the title. ### States * **Closed** * **Focused (hover)** * **Open** ### Sizing The width of the control will automatically scale to fit the area containing the control. ## Illustration ### Closed and Open ![](../../assets/dg-controls-date-picker.png)
enyojs/enyo-docs
developer-guide/design/controls/date-picker.md
Markdown
apache-2.0
865
maintainer "Belly, Inc." maintainer_email "[email protected]" license "Apache v2.0" description "Installs/Configures Google Go" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "1.0.0" # Operating systems supported %w{ debian ubuntu }.each do |os| supports os end
bellycard/procd
scripts/chef/cookbooks/go/metadata.rb
Ruby
apache-2.0
331
# 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 # # 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 (STATIC_BUILD) include_regular_expression("^.*$") set(OPENJPEG_VERSION_MAJOR 2) set(OPENJPEG_VERSION_MINOR 3) set(OPENJPEG_VERSION_BUILD 0) set(OPENJPEG_VERSION "${OPENJPEG_VERSION_MAJOR}.${OPENJPEG_VERSION_MINOR}.${OPENJPEG_VERSION_BUILD}") set(PACKAGE_VERSION "${OPENJPEG_VERSION_MAJOR}.${OPENJPEG_VERSION_MINOR}.${OPENJPEG_VERSION_BUILD}") set(OPENJPEG_NAME openjpeg-2.3.0) set(OPENJPEG_SOURCES_DIR ${CMAKE_BINARY_DIR}/${OPENJPEG_NAME}) #"https://github.com/uclouvain/openjpeg/archive/v2.3.0.tar.gz" include_directories( ${OPENJPEG_SOURCES_DIR}/src/lib/openjp3d ) set(OPENJPEG_SOURCES_DIR ${OPENJPEG_SOURCES_DIR}/src/lib/openjp2) include (${CMAKE_ROOT}/Modules/CheckIncludeFile.cmake) macro(ensure_file_include INCLUDE_FILENAME VARIABLE_NAME MANDATORY_STATUS) CHECK_INCLUDE_FILE(${INCLUDE_FILENAME} ${VARIABLE_NAME}) if (NOT ${${VARIABLE_NAME}}) if (${MANDATORY_STATUS}) message(FATAL_ERROR "The file ${INCLUDE_FILENAME} is mandatory but not found on your system") endif() endif() endmacro() ensure_file_include("stdint.h" OPJ_HAVE_STDINT_H YES) ensure_file_include("inttypes.h" OPJ_HAVE_INTTYPES_H YES) configure_file( ${OPENJPEG_SOURCES_DIR}/opj_config.h.cmake.in ${OPENJPEG_SOURCES_DIR}/opj_config.h @ONLY ) message(${CMAKE_CURRENT_BINARY_DIR}) configure_file( ${OPENJPEG_SOURCES_DIR}/opj_config_private.h.cmake.in ${OPENJPEG_SOURCES_DIR}/opj_config_private.h @ONLY ) include_directories( ${CMAKE_BINARY_DIR} ) include_directories( ${OPENJPEG_SOURCES_DIR} ) set(OPENJPEG_SRCS ${OPENJPEG_SOURCES_DIR}/thread.c ${OPENJPEG_SOURCES_DIR}/thread.h ${OPENJPEG_SOURCES_DIR}/bio.c ${OPENJPEG_SOURCES_DIR}/bio.h ${OPENJPEG_SOURCES_DIR}/cio.c ${OPENJPEG_SOURCES_DIR}/cio.h ${OPENJPEG_SOURCES_DIR}/dwt.c ${OPENJPEG_SOURCES_DIR}/dwt.h ${OPENJPEG_SOURCES_DIR}/event.c ${OPENJPEG_SOURCES_DIR}/event.h ${OPENJPEG_SOURCES_DIR}/image.c ${OPENJPEG_SOURCES_DIR}/image.h ${OPENJPEG_SOURCES_DIR}/invert.c ${OPENJPEG_SOURCES_DIR}/invert.h ${OPENJPEG_SOURCES_DIR}/j2k.c ${OPENJPEG_SOURCES_DIR}/j2k.h ${OPENJPEG_SOURCES_DIR}/jp2.c ${OPENJPEG_SOURCES_DIR}/jp2.h ${OPENJPEG_SOURCES_DIR}/mct.c ${OPENJPEG_SOURCES_DIR}/mct.h ${OPENJPEG_SOURCES_DIR}/mqc.c ${OPENJPEG_SOURCES_DIR}/mqc.h ${OPENJPEG_SOURCES_DIR}/mqc_inl.h ${OPENJPEG_SOURCES_DIR}/openjpeg.c ${OPENJPEG_SOURCES_DIR}/openjpeg.h ${OPENJPEG_SOURCES_DIR}/opj_clock.c ${OPENJPEG_SOURCES_DIR}/opj_clock.h ${OPENJPEG_SOURCES_DIR}/pi.c ${OPENJPEG_SOURCES_DIR}/pi.h ${OPENJPEG_SOURCES_DIR}/t1.c ${OPENJPEG_SOURCES_DIR}/t1.h ${OPENJPEG_SOURCES_DIR}/t2.c ${OPENJPEG_SOURCES_DIR}/t2.h ${OPENJPEG_SOURCES_DIR}/tcd.c ${OPENJPEG_SOURCES_DIR}/tcd.h ${OPENJPEG_SOURCES_DIR}/tgt.c ${OPENJPEG_SOURCES_DIR}/tgt.h ${OPENJPEG_SOURCES_DIR}/function_list.c ${OPENJPEG_SOURCES_DIR}/function_list.h ${OPENJPEG_SOURCES_DIR}/opj_codec.h ${OPENJPEG_SOURCES_DIR}/opj_includes.h ${OPENJPEG_SOURCES_DIR}/opj_intmath.h ${OPENJPEG_SOURCES_DIR}/opj_malloc.c ${OPENJPEG_SOURCES_DIR}/opj_malloc.h ${OPENJPEG_SOURCES_DIR}/opj_stdint.h ${OPENJPEG_SOURCES_DIR}/sparse_array.c ${OPENJPEG_SOURCES_DIR}/sparse_array.h ) if(BUILD_JPIP) add_definitions(-DUSE_JPIP) set(OPENJPEG_SRCS ${OPENJPEG_SRCS} ${OPENJPEG_SOURCES_DIR}/cidx_manager.c ${OPENJPEG_SOURCES_DIR}/cidx_manager.h ${OPENJPEG_SOURCES_DIR}/phix_manager.c ${OPENJPEG_SOURCES_DIR}/ppix_manager.c ${OPENJPEG_SOURCES_DIR}/thix_manager.c ${OPENJPEG_SOURCES_DIR}/tpix_manager.c ${OPENJPEG_SOURCES_DIR}/indexbox_manager.h ) endif() else() find_package(OpenJPEG REQUIRED) include_directories(${OPENJPEG_INCLUDE_DIRS}) include_directories(${OPENJPEG_INCLUDE_DIRS}/openjpeg-2.3/) link_libraries(${OPENJPEG_LIBRARIES}) endif()
GoogleCloudPlatform/wsi-to-dicom-converter
CMake/OpenJpeg.cmake
CMake
apache-2.0
4,763
<?php $curdir = dirname(__FILE__); require_once($curdir.'/Db.php'); class LoanStatus extends Db { protected static $table_name = "loanstatus"; protected static $db_fields = array("id", "name", "description"); public function findById($id){ $result = $this->getrec(self::$table_name, "id=".$id, ""); return !empty($result) ? $result:false; } public function findAll(){ $result_array = $this->getarray(self::$table_name, "", "", ""); return !empty($result_array) ? $result_array : false; } public function findLoanStatus($id){ $result = $this->getfrec(self::$table_name, "name", "id=".$id, "", ""); return !empty($result) ? $result['name'] : false; } public function addLoanStatus($data){ $fields = self::$db_fields; if($this->add(self::$table_name, $fields, $this->generateAddFields($fields, $data))){ return true; } return false; } public function updateLoanStatus($data){ $fields = array_slice(1, self::$db_fields); $id = $data['id']; unset($data['id']); if($this->update(self::$table_name, $fields, $this->generateAddFields($fields, $data), "id=".$id)){ return true; } return false; } } ?>
platinalfred/buladde
lib/LoanStatus.php
PHP
apache-2.0
1,146
<?php /** * DBDelTree action message. * * PHP Version 5 * * @category PHPAMI * @package Message * @subpackage Action * @author Jaime Ziga <[email protected]> * @license http://github.com/Adrian0350/PHP-AMI/ Apache License 2.0 * @version SVN: $Id$ * @link http://github.com/Adrian0350/PHP-AMI/ * * Copyright 2011 Marcelo Gornstein <[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. * */ require_once dirname(__FILE__) . '/ActionMessage.php'; /** * DBDelTree action message. * * PHP Version 5 * * @category PHPAMI * @package Message * @subpackage Action * @author Jaime Ziga <[email protected]> * @license http://github.com/Adrian0350/PHP-AMI/ Apache License 2.0 * @link http://github.com/Adrian0350/PHP-AMI/ */ class DBDelTreeAction extends ActionMessage { /** * Constructor. * * @param string $family Family. * @param string $key Name (optional) * * @return void */ public function __construct($family, $key = false) { parent::__construct('DBDelTree'); $this->setKey('Family', $family); if ($key != false) { $this->setKey('Key', $key); } } }
Adrian0350/PHP-AMI
src/PHPAMI/Message/Action/DBDelTreeAction.php
PHP
apache-2.0
1,740
/* ~ Copyright (c) 2014 George Norman. ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ -------------------------------------------------------------- ~ Renders <css-lab-about> tags - sharable among all projects. ~ -------------------------------------------------------------- */ /** * The &lt;css-lab-about&gt; tag renders a common introduction, displayed across all of the * CSS Lab projects and pages. There can be only one Introduction section per page. *<p> * Example: * <pre style="background:#eee; padding:6px;"> * &lt;css-lab-about style="margin-top:12px;"/&gt; * </pre> * * @module cssLabAboutTag */ var cssLabAboutTag = (function(tzDomHelper, tzCustomTagHelper) { "use strict"; // http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript var template = ['This page contains example code used for the <a href="http://www.thruzero.com/jcat3/apps/resources/resources.jsf?rid=css.overview">CSS Summary</a>', 'at <a href="http://www.thruzero.com/">ThruZero</a>. ', 'The example code (e.g., CSS and HTML) is defined with inline-templates and then rendered live, so it will always match the rendered example. ' ].join('\n'); return { getTagName: function() { return "css-lab-about"; }, /** * Render the first &lt;css-lab-about&gt; tag on the page - only one tag per page is supported. */ renderAll: function() { tzCustomTagHelper.renderFirst(this); }, /** * Render the &lt;css-lab-about&gt; tag identified by the given tagId. * * @param tagId ID of the tag to render. */ renderTagById: function(tagId) { tzCustomTagHelper.renderTagById(this, tagId); }, /** * Render the given aboutTagNode. * * @param aboutTagNode the node to retrieve the attributes from and then render the result to. */ renderTag: function(aboutTagNode) { this.render(aboutTagNode); }, /** * Render the 'About Application' HTML, into the given containerNode. * * @param containerNode where to render the result. */ render: function(containerNode) { containerNode.style.display = 'block'; //var template = tzCustomTagHelper.getTemplate(this.getTagName() + "Template"); // @-@:p1(geo) Experimental tzCustomTagHelper.renderTagFromTemplate(containerNode, template, {}); } } }(tzDomHelperModule, tzCustomTagHelperModule));
georgenorman/css-lab
src/js/tags/cssLabAbout.js
JavaScript
apache-2.0
2,522
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>快查网-chrome插件</title> <script type="text/javascript" src="../js/jquery.js" charset="utf-8"></script> <script type="text/javascript" src="../js/benchmark.js" charset="utf-8"></script> <script type="text/javascript" src="../js/show_desktop.js" charset="utf-8"></script> <script type="text/javascript" src="../js/test.js" charset="utf-8"></script> </head> <body> <div id="test1" style="cursor:hand;">good</div> </body> </html>
midoks/chrome-extensions
webtool/html/info.html
HTML
apache-2.0
570
--- result: pass --- Webpack preserves live bindings in modules. This remains true in cases where source modules are intentionally duplicated across bundles, since only a single _instance_ of each module is ever created.
GoogleChromeLabs/tooling.report
tests/code-splitting/subtests/shared-references-between-chunks/webpack/index.md
Markdown
apache-2.0
222
package me.soulmachine; import org.jruby.embed.ScriptingContainer; import java.util.List; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import javax.script.ScriptException; /** * A simple JRuby example to execute Python scripts from Java. */ final class JRubyExample { private JRubyExample() {} /** * Main entrypoint. * * @param args arguments * @throws ScriptException ScriptException */ public static void main(final String[] args) throws ScriptException { listEngines(); final String rubyHelloWord = "puts 'Hello World from JRuby!'"; // First way: Use built-in ScriptEngine from JDK { final ScriptEngineManager mgr = new ScriptEngineManager(); final ScriptEngine pyEngine = mgr.getEngineByName("ruby"); try { pyEngine.eval(rubyHelloWord); } catch (ScriptException ex) { ex.printStackTrace(); } } // Second way: Use ScriptingContainer() from JRuby { final ScriptingContainer scriptingContainer = new ScriptingContainer(); scriptingContainer.runScriptlet(rubyHelloWord); } // Call Ruby Methods from Java { final ScriptingContainer scriptingContainer = new ScriptingContainer(); final String rubyMethod = "def myAdd(a,b)\n\treturn a+b\nend"; final Object receiver = scriptingContainer.runScriptlet(rubyMethod); final Object[] arguments = new Object[2]; arguments[0] = Integer.valueOf(6); arguments[1] = Integer.valueOf(4); final Integer result = scriptingContainer.callMethod(receiver, "myAdd", arguments, Integer.class); System.out.println("Result: " + result); } } /** * Display all script engines. */ public static void listEngines() { final ScriptEngineManager mgr = new ScriptEngineManager(); final List<ScriptEngineFactory> factories = mgr.getEngineFactories(); for (final ScriptEngineFactory factory: factories) { System.out.println("ScriptEngineFactory Info"); final String engName = factory.getEngineName(); final String engVersion = factory.getEngineVersion(); final String langName = factory.getLanguageName(); final String langVersion = factory.getLanguageVersion(); System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion); final List<String> engNames = factory.getNames(); for (final String name: engNames) { System.out.printf("\tEngine Alias: %s\n", name); } System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion); } } }
soulmachine/JRubyExample
JRubyExample/src/main/java/me/soulmachine/JRubyExample.java
Java
apache-2.0
2,633
package com.arthurb.iterator.dinermergergery; import java.util.Iterator; /** * Created by Blackwood on 07.03.2016 18:16. */ public class DinerMenu implements Menu { static final int MAX_ITEMS = 6; int numberOfItems = 0; MenuItem[] menuItems; public DinerMenu() { menuItems = new MenuItem[MAX_ITEMS]; addItem("Vegetarian BLT", "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99); addItem("BLT", "Bacon with lettuce & tomato on whole wheat", false, 2.99); addItem("Soup of the day", "Soup of the day, with a side of potato salad", false, 2.99); addItem("Hotdog", "A got dog, with saurkraut, relish, onions, topped with cheese", false, 3.05); addItem("Steamed Veggies and Brown Rice", "Steamed vegetables over brown rice", true, 3.99); addItem("Pasta", "Spaghetti with Marinara Sauce, and a slice of sourdough bread", true, 3.89); } private void addItem(String name, String description, boolean vegetarian, double price) { MenuItem menuItem = new MenuItem(name, description, vegetarian, price); if (numberOfItems >= MAX_ITEMS) { // Ограничиваем размер меню, чтобы не запоминать слишком много рецептов System.err.println("Sorry, menu is full! Can't add item to menu"); } else { menuItems[numberOfItems] = menuItem; numberOfItems = numberOfItems + 1; } } public Iterator createIterator() { return new DinerMenuIterator(menuItems); } }
NeverNight/SimplesPatterns.Java
src/com/arthurb/iterator/dinermergergery/DinerMenu.java
Java
apache-2.0
1,583
/* eslint-disable local/html-template */ const documentModes = require('./document-modes'); const {AmpState, ampStateKey} = require('./amphtml-helpers'); const {html, joinFragments} = require('./html'); const jsModes = [ { value: 'default', description: `Unminified AMP JavaScript is served from the local server. For local development you will usually want to serve unminified JS to test your changes.`, }, { value: 'minified', description: html` Minified AMP JavaScript is served from the local server. This is only available after running <code>amp dist --fortesting</code> `, }, { value: 'cdn', description: 'Minified AMP JavaScript is served from the AMP Project CDN.', }, ]; const stateId = 'settings'; const htmlEnvelopePrefixStateKey = 'htmlEnvelopePrefix'; const jsModeStateKey = 'jsMode'; const panelStateKey = 'panel'; const htmlEnvelopePrefixKey = ampStateKey(stateId, htmlEnvelopePrefixStateKey); const panelKey = ampStateKey(stateId, panelStateKey); const PanelSelectorButton = ({expression, type, value}) => html` <button class="settings-panel-button" [class]="'settings-panel-button' + (${panelKey} != '${type}' ? '' : ' open')" data-type="${type}" tabindex="0" on="tap: AMP.setState({ ${stateId}: { ${panelStateKey}: (${panelKey} != '${type}' ? '${type}' : null), } })" > <span>${type}</span> <strong [text]="${expression}">${value}</strong> </button> `; const PanelSelector = ({children, compact = false, key, name = null}) => html` <amp-selector layout="container" name="${name || key}" class="${compact ? 'compact ' : ''}" on="select: AMP.setState({ ${stateId}: { ${panelStateKey}: null, ${key}: event.targetOption, } })" > ${joinFragments(children)} </amp-selector> `; const PanelSelectorBlock = ({children, id, selected, value}) => html` <div class="selector-block" ${selected ? ' selected' : ''} id="${id}" option="${value}" > <div class="check-icon icon"></div> ${children} </div> `; const HtmlEnvelopeSelector = ({htmlEnvelopePrefix}) => PanelSelector({ compact: true, key: htmlEnvelopePrefixStateKey, children: Object.entries(documentModes).map(([prefix, name]) => PanelSelectorBlock({ id: `select-html-mode-${name}`, value: prefix, selected: htmlEnvelopePrefix === prefix, children: html`<strong>${name}</strong>`, }) ), }); const JsModeSelector = ({jsMode}) => PanelSelector({ key: jsModeStateKey, name: 'mode', children: jsModes.map(({description, value}) => PanelSelectorBlock({ id: `serve-mode-${value}`, value, selected: jsMode === value, children: html` <strong>${value}</strong> <p>${description}</p> `, }) ), }); const SettingsPanelButtons = ({htmlEnvelopePrefix, jsMode}) => html` <div style="flex: 1"> <div class="settings-panel-button-container"> ${PanelSelectorButton({ type: 'HTML', expression: `${stateId}.documentModes[${htmlEnvelopePrefixKey}]`, value: documentModes[htmlEnvelopePrefix], })} ${PanelSelectorButton({ type: 'JS', expression: `${stateId}.${jsModeStateKey}`, value: jsMode, })} </div> ${SettingsPanel({htmlEnvelopePrefix, jsMode})} </div> `; const SettingsSubpanel = ({children, type}) => html` <div hidden [hidden]="${panelKey} != '${type}'">${children}</div> `; const SettingsPanel = ({htmlEnvelopePrefix, jsMode}) => html` <div class="settings-panel" hidden [hidden]="${panelKey} == null"> ${AmpState(stateId, { documentModes, [panelStateKey]: null, [htmlEnvelopePrefixStateKey]: htmlEnvelopePrefix, [jsModeStateKey]: jsMode, })} ${SettingsSubpanel({ type: 'HTML', children: html` <h4>Select an envelope to serve HTML documents.</h4> ${HtmlEnvelopeSelector({htmlEnvelopePrefix})} `, })} ${SettingsSubpanel({ type: 'JS', children: html` <h4>Select the JavaScript binaries to use in served documents.</h4> <form action="/serve_mode_change" action-xhr="/serve_mode_change" target="_blank" id="serve-mode-form" > ${JsModeSelector({jsMode})} </form> `, })} </div> `; module.exports = { SettingsPanel, SettingsPanelButtons, htmlEnvelopePrefixKey, };
jpettitt/amphtml
build-system/server/app-index/settings.js
JavaScript
apache-2.0
4,586
package org.apache.helix.controller.rebalancer.waged.model; /* * 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. */ import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.apache.helix.HelixException; import org.apache.helix.controller.rebalancer.util.WagedValidationUtil; import org.apache.helix.model.ClusterConfig; import org.apache.helix.model.InstanceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class represents a possible allocation of the replication. * Note that any usage updates to the AssignableNode are not thread safe. */ public class AssignableNode implements Comparable<AssignableNode> { private static final Logger LOG = LoggerFactory.getLogger(AssignableNode.class.getName()); // Immutable Instance Properties private final String _instanceName; private final String _faultZone; // maximum number of the partitions that can be assigned to the instance. private final int _maxPartition; private final ImmutableSet<String> _instanceTags; private final ImmutableMap<String, List<String>> _disabledPartitionsMap; private final ImmutableMap<String, Integer> _maxAllowedCapacity; // Mutable (Dynamic) Instance Properties // A map of <resource name, <partition name, replica>> that tracks the replicas assigned to the // node. private Map<String, Map<String, AssignableReplica>> _currentAssignedReplicaMap; // A map of <capacity key, capacity value> that tracks the current available node capacity private Map<String, Integer> _remainingCapacity; /** * Update the node with a ClusterDataCache. This resets the current assignment and recalculates * currentCapacity. * NOTE: While this is required to be used in the constructor, this can also be used when the * clusterCache needs to be * refreshed. This is under the assumption that the capacity mappings of InstanceConfig and * ResourceConfig could * subject to change. If the assumption is no longer true, this function should become private. */ AssignableNode(ClusterConfig clusterConfig, InstanceConfig instanceConfig, String instanceName) { _instanceName = instanceName; Map<String, Integer> instanceCapacity = fetchInstanceCapacity(clusterConfig, instanceConfig); _faultZone = computeFaultZone(clusterConfig, instanceConfig); _instanceTags = ImmutableSet.copyOf(instanceConfig.getTags()); _disabledPartitionsMap = ImmutableMap.copyOf(instanceConfig.getDisabledPartitionsMap()); // make a copy of max capacity _maxAllowedCapacity = ImmutableMap.copyOf(instanceCapacity); _remainingCapacity = new HashMap<>(instanceCapacity); _maxPartition = clusterConfig.getMaxPartitionsPerInstance(); _currentAssignedReplicaMap = new HashMap<>(); } /** * This function should only be used to assign a set of new partitions that are not allocated on * this node. It's because the any exception could occur at the middle of batch assignment and the * previous finished assignment cannot be reverted * Using this function avoids the overhead of updating capacity repeatedly. */ void assignInitBatch(Collection<AssignableReplica> replicas) { Map<String, Integer> totalPartitionCapacity = new HashMap<>(); for (AssignableReplica replica : replicas) { // TODO: the exception could occur in the middle of for loop and the previous added records cannot be reverted addToAssignmentRecord(replica); // increment the capacity requirement according to partition's capacity configuration. for (Map.Entry<String, Integer> capacity : replica.getCapacity().entrySet()) { totalPartitionCapacity.compute(capacity.getKey(), (key, totalValue) -> (totalValue == null) ? capacity.getValue() : totalValue + capacity.getValue()); } } // Update the global state after all single replications' calculation is done. for (String capacityKey : totalPartitionCapacity.keySet()) { updateRemainingCapacity(capacityKey, totalPartitionCapacity.get(capacityKey)); } } /** * Assign a replica to the node. * @param assignableReplica - the replica to be assigned */ void assign(AssignableReplica assignableReplica) { addToAssignmentRecord(assignableReplica); assignableReplica.getCapacity().entrySet().stream() .forEach(capacity -> updateRemainingCapacity(capacity.getKey(), capacity.getValue())); } /** * Release a replica from the node. * If the replication is not on this node, the assignable node is not updated. * @param replica - the replica to be released */ void release(AssignableReplica replica) throws IllegalArgumentException { String resourceName = replica.getResourceName(); String partitionName = replica.getPartitionName(); // Check if the release is necessary if (!_currentAssignedReplicaMap.containsKey(resourceName)) { LOG.warn("Resource {} is not on node {}. Ignore the release call.", resourceName, getInstanceName()); return; } Map<String, AssignableReplica> partitionMap = _currentAssignedReplicaMap.get(resourceName); if (!partitionMap.containsKey(partitionName) || !partitionMap.get(partitionName) .equals(replica)) { LOG.warn("Replica {} is not assigned to node {}. Ignore the release call.", replica.toString(), getInstanceName()); return; } AssignableReplica removedReplica = partitionMap.remove(partitionName); removedReplica.getCapacity().entrySet().stream() .forEach(entry -> updateRemainingCapacity(entry.getKey(), -1 * entry.getValue())); } /** * @return A set of all assigned replicas on the node. */ Set<AssignableReplica> getAssignedReplicas() { return _currentAssignedReplicaMap.values().stream() .flatMap(replicaMap -> replicaMap.values().stream()).collect(Collectors.toSet()); } /** * @return The current assignment in a map of <resource name, set of partition names> */ Map<String, Set<String>> getAssignedPartitionsMap() { Map<String, Set<String>> assignmentMap = new HashMap<>(); for (String resourceName : _currentAssignedReplicaMap.keySet()) { assignmentMap.put(resourceName, _currentAssignedReplicaMap.get(resourceName).keySet()); } return assignmentMap; } /** * @param resource Resource name * @return A set of the current assigned replicas' partition names in the specified resource. */ public Set<String> getAssignedPartitionsByResource(String resource) { return _currentAssignedReplicaMap.getOrDefault(resource, Collections.emptyMap()).keySet(); } /** * @param resource Resource name * @return A set of the current assigned replicas' partition names with the top state in the * specified resource. */ Set<String> getAssignedTopStatePartitionsByResource(String resource) { return _currentAssignedReplicaMap.getOrDefault(resource, Collections.emptyMap()).entrySet() .stream().filter(partitionEntry -> partitionEntry.getValue().isReplicaTopState()) .map(partitionEntry -> partitionEntry.getKey()).collect(Collectors.toSet()); } /** * @return The total count of assigned top state partitions. */ public int getAssignedTopStatePartitionsCount() { return (int) _currentAssignedReplicaMap.values().stream() .flatMap(replicaMap -> replicaMap.values().stream()) .filter(AssignableReplica::isReplicaTopState).count(); } /** * @return The total count of assigned replicas. */ public int getAssignedReplicaCount() { return _currentAssignedReplicaMap.values().stream().mapToInt(Map::size).sum(); } /** * @return The current available capacity. */ public Map<String, Integer> getRemainingCapacity() { return _remainingCapacity; } /** * @return A map of <capacity category, capacity number> that describes the max capacity of the * node. */ public Map<String, Integer> getMaxCapacity() { return _maxAllowedCapacity; } /** * Return the most concerning capacity utilization number for evenly partition assignment. * The method dynamically calculates the projected highest utilization number among all the * capacity categories assuming the new capacity usage is added to the node. * For example, if the current node usage is {CPU: 0.9, MEM: 0.4, DISK: 0.6}. Then this call shall * return 0.9. * @param newUsage the proposed new additional capacity usage. * @return The highest utilization number of the node among all the capacity category. */ public float getProjectedHighestUtilization(Map<String, Integer> newUsage) { float highestCapacityUtilization = 0; for (String capacityKey : _maxAllowedCapacity.keySet()) { float capacityValue = _maxAllowedCapacity.get(capacityKey); float utilization = (capacityValue - _remainingCapacity.get(capacityKey) + newUsage .getOrDefault(capacityKey, 0)) / capacityValue; highestCapacityUtilization = Math.max(highestCapacityUtilization, utilization); } return highestCapacityUtilization; } public String getInstanceName() { return _instanceName; } public Set<String> getInstanceTags() { return _instanceTags; } public String getFaultZone() { return _faultZone; } public boolean hasFaultZone() { return _faultZone != null; } /** * @return A map of <resource name, set of partition names> contains all the partitions that are * disabled on the node. */ public Map<String, List<String>> getDisabledPartitionsMap() { return _disabledPartitionsMap; } /** * @return The max partition count that are allowed to be allocated on the node. */ public int getMaxPartition() { return _maxPartition; } /** * Computes the fault zone id based on the domain and fault zone type when topology is enabled. * For example, when * the domain is "zone=2, instance=testInstance" and the fault zone type is "zone", this function * returns "2". * If cannot find the fault zone type, this function leaves the fault zone id as the instance name. * Note the WAGED rebalancer does not require full topology tree to be created. So this logic is * simpler than the CRUSH based rebalancer. */ private String computeFaultZone(ClusterConfig clusterConfig, InstanceConfig instanceConfig) { if (!clusterConfig.isTopologyAwareEnabled()) { // Instance name is the default fault zone if topology awareness is false. return instanceConfig.getInstanceName(); } String topologyStr = clusterConfig.getTopology(); String faultZoneType = clusterConfig.getFaultZoneType(); if (topologyStr == null || faultZoneType == null) { LOG.debug("Topology configuration is not complete. Topology define: {}, Fault Zone Type: {}", topologyStr, faultZoneType); // Use the instance name, or the deprecated ZoneId field (if exists) as the default fault // zone. String zoneId = instanceConfig.getZoneId(); return zoneId == null ? instanceConfig.getInstanceName() : zoneId; } else { // Get the fault zone information from the complete topology definition. String[] topologyKeys = topologyStr.trim().split("/"); if (topologyKeys.length == 0 || Arrays.stream(topologyKeys) .noneMatch(type -> type.equals(faultZoneType))) { throw new HelixException( "The configured topology definition is empty or does not contain the fault zone type."); } Map<String, String> domainAsMap = instanceConfig.getDomainAsMap(); StringBuilder faultZoneStringBuilder = new StringBuilder(); for (String key : topologyKeys) { if (!key.isEmpty()) { // if a key does not exist in the instance domain config, apply the default domain value. faultZoneStringBuilder.append(domainAsMap.getOrDefault(key, "Default_" + key)); if (key.equals(faultZoneType)) { break; } else { faultZoneStringBuilder.append('/'); } } } return faultZoneStringBuilder.toString(); } } /** * @throws HelixException if the replica has already been assigned to the node. */ private void addToAssignmentRecord(AssignableReplica replica) { String resourceName = replica.getResourceName(); String partitionName = replica.getPartitionName(); if (_currentAssignedReplicaMap.containsKey(resourceName) && _currentAssignedReplicaMap .get(resourceName).containsKey(partitionName)) { throw new HelixException(String .format("Resource %s already has a replica with state %s from partition %s on node %s", replica.getResourceName(), replica.getReplicaState(), replica.getPartitionName(), getInstanceName())); } else { _currentAssignedReplicaMap.computeIfAbsent(resourceName, key -> new HashMap<>()) .put(partitionName, replica); } } private void updateRemainingCapacity(String capacityKey, int usage) { if (!_remainingCapacity.containsKey(capacityKey)) { //if the capacityKey belongs to replicas does not exist in the instance's capacity, // it will be treated as if it has unlimited capacity of that capacityKey return; } _remainingCapacity.put(capacityKey, _remainingCapacity.get(capacityKey) - usage); } /** * Get and validate the instance capacity from instance config. * @throws HelixException if any required capacity key is not configured in the instance config. */ private Map<String, Integer> fetchInstanceCapacity(ClusterConfig clusterConfig, InstanceConfig instanceConfig) { Map<String, Integer> instanceCapacity = WagedValidationUtil.validateAndGetInstanceCapacity(clusterConfig, instanceConfig); // Remove all the non-required capacity items from the map. instanceCapacity.keySet().retainAll(clusterConfig.getInstanceCapacityKeys()); return instanceCapacity; } @Override public int hashCode() { return _instanceName.hashCode(); } @Override public int compareTo(AssignableNode o) { return _instanceName.compareTo(o.getInstanceName()); } @Override public String toString() { return _instanceName; } }
lei-xia/helix
helix-core/src/main/java/org/apache/helix/controller/rebalancer/waged/model/AssignableNode.java
Java
apache-2.0
15,277
select "${session_uuid}"
treasure-data/digdag
digdag-tests/src/test/resources/acceptance/emr/query.sql
SQL
apache-2.0
24
//**************************************************************************/ // Copyright (c) 1998-2006 Autodesk, Inc. // All rights reserved. // // These coded instructions, statements, and computer programs contain // unpublished proprietary information written by Autodesk, Inc., and are // protected by Federal copyright law. They may not be disclosed to third // parties or copied or duplicated in any form, in whole or in part, without // the prior written consent of Autodesk, Inc. //**************************************************************************/ // FILE: gfx.h // DESCRIPTION: main graphics system include file. // AUTHOR: Don Brittain // HISTORY: //**************************************************************************/ #if !defined(_GFX_H_) #define _GFX_H_ #include "maxheap.h" #include "geomlib.h" #include "export.h" #include "tab.h" #include "mtl.h" #include "BaseInterface.h" #include "HWMesh.h" typedef Tab<DWORD> DWTab; typedef unsigned short MtlID; class VertexBuffer: public MaxHeapOperators { public: Point3 position; DWORD color; }; class LineBuffer: public MaxHeapOperators { public: Point3 position; DWORD color; }; // strip-related stuff class Strip: public MaxHeapOperators { public: MtlID mID; DWORD smGrp; DWTab v; DWTab n; DWTab tv; void AddVert(DWORD vtx) { v.Append(1, &vtx); } void AddVert(DWORD vtx, DWORD tvtx) { v.Append(1, &vtx); tv.Append(1, &tvtx); } void AddVertN(DWORD vtx, DWORD nor) { v.Append(1, &vtx); n.Append(1, &nor); } void AddVertN(DWORD vtx, DWORD tvtx, DWORD nor) { v.Append(1, &vtx); tv.Append(1, &tvtx); n.Append(1, &nor); } }; typedef Strip *StripPtr; typedef Tab<StripPtr> StripTab; // Face Flags: (moved from mesh.h) // 3 LSBs hold the edge visibility flags // Bit 3 indicates the presence of texture verticies // if bit is 1, edge is visible #define EDGE_VIS 1 #define EDGE_INVIS 0 // first edge-visibility bit field #define VIS_BIT 0x0001 #define VIS_MASK 0x0007 #define EDGE_A (1<<0) #define EDGE_B (1<<1) #define EDGE_C (1<<2) #define EDGE_ALL (EDGE_A|EDGE_B|EDGE_C) #define FACE_HIDDEN (1<<3) #define HAS_TVERTS (1<<4) // DO NOT USE: This flag is obselete. #define FACE_WORK (1<<5) // used in various algorithms #define FACE_STRIP (1<<6) // flags to indicate that face normal is used because no smoothing group // normal is found #define FACE_NORM_A (1<<8) #define FACE_NORM_B (1<<9) #define FACE_NORM_C (1<<10) #define FACE_NORM_MASK 0x0700 #define FACE_INFOREGROUND (1<<11) //watje this is used to track faces that are in the foreground we should not draw thes but they are hitested against #define FACE_BACKFACING (1<<12) //watje this is used to track which faces are back faacing this is a temporary flag // The mat ID is stored in the HIWORD of the face flags #define FACE_MATID_SHIFT 16 #define FACE_MATID_MASK 0xFFFF class GWFace: public MaxHeapOperators { public: DWORD v[3]; // indexed references to the vertex array DWORD flags; // see face flags description above }; /*! \defgroup patchDisplayFlags Patch Display Flags For processWireFaces and general mesh class use */ //@{ #define DISP_VERTTICKS (1<<0) //!< Display vertices as tick marks #define DISP_SELVERTS (1<<10) //!< Display selected vertices. #define DISP_SELFACES (1<<11) //!< Display selected faces. #define DISP_SELEDGES (1<<12) //!< Display selected edges. #define DISP_SELPOLYS (1<<13) //!< Display selected polygons. #define DISP_OBJSELECTED (1<<8) //!< Mimics COMP_OBJSELECTED in mesh.h //@} // General definitions #define WM_SHUTDOWN (WM_USER+2001) #define WM_INIT_COMPLETE (WM_USER+2002) #define GW_MAX_FILE_LEN 128 #define GW_MAX_CAPTION_LEN 128 #define GW_MAX_VERTS 32 #define GFX_MAX_STRIP 100 #define GFX_MAX_TEXTURES 8 typedef BOOL (*HitFunc)(int, int, void *); // Rendering modes #define GW_NO_ATTS 0x0000000 #define GW_WIREFRAME 0x0000001 #define GW_ILLUM 0x0000002 #define GW_FLAT 0x0000004 #define GW_SPECULAR 0x0000008 #define GW_TEXTURE 0x0000010 #define GW_Z_BUFFER 0x0000020 #define GW_PERSP_CORRECT 0x0000040 #define GW_POLY_EDGES 0x0000080 #define GW_BACKCULL 0x0000100 #define GW_TWO_SIDED 0x0000200 #define GW_COLOR_VERTS 0x0000400 #define GW_SHADE_CVERTS 0x0000800 #define GW_PICK 0x0001000 #define GW_BOX_MODE 0x0002000 #define GW_ALL_EDGES 0x0004000 #define GW_VERT_TICKS 0x0008000 #define GW_SHADE_SEL_FACES 0x0010000 #define GW_TRANSPARENCY 0x0020000 #define GW_TRANSPARENT_PASS 0x0040000 #define GW_EMISSIVE_VERTS 0x0080000 #define GW_ALL_OPAQUE 0x0100000 #define GW_EDGES_ONLY 0x0200000 #define GW_CONSTANT 0x0400000 #define GW_HIDDENLINE 0x0800000 //this is the same as constant but the shade color will the color of the background #define GW_BLENDING 0x1000000 #define GW_DEPTHWRITE_DISABLE 0x2000000 //disable writing into the depth buffer #define GW_LIGHTING (GW_ILLUM | GW_SPECULAR) // spotlight shapes #define GW_SHAPE_RECT 0 #define GW_SHAPE_CIRCULAR 1 // texture tiling #define GW_TEX_NO_TILING 0 #define GW_TEX_REPEAT 1 #define GW_TEX_MIRROR 2 // texture operations #define GW_TEX_LEAVE 0 // Use the source pixel value #define GW_TEX_REPLACE 1 // Use the texture pixel value #define GW_TEX_MODULATE 2 // Multiply the source with the texture #define GW_TEX_ADD 3 // Add the source and texture #define GW_TEX_ADD_SIGNED 4 // Add the source and texture with an 0.5 subtraction #define GW_TEX_SUBTRACT 5 // Subtract the source from the texture #define GW_TEX_ADD_SMOOTH 6 // Add the source and the texture then subtract their product #define GW_TEX_ALPHA_BLEND 7 // Alpha blend the texture with the source #define GW_TEX_PREMULT_ALPHA_BLEND 8 // Alpha blend the the source with a premultiplied alpha texture #define GW_TEX_ALPHA_BLEND2 9 // Alpha blend the the source with a premultiplied alpha texture with GL_MODULATE as the tex env instead of GL_DECAL. // texture scale factors #define GW_TEX_SCALE_1X 0 // Multiply the tex op result by 1 #define GW_TEX_SCALE_2X 1 // Multiply the tex op result by 2 #define GW_TEX_SCALE_4X 2 // Multiply the tex op result by 4 // texture alpha sources #define GW_TEX_ZERO 0 // Use no alpha value #define GW_TEX_SOURCE 1 // Use the source alpha #define GW_TEX_TEXTURE 2 // Use the texture alpha #define GW_TEX_CONSTANT 3 // Use a constant BGRA color as an alpha #define GW_TEX_PREVIOUS 4 // Use the previous texture stage alpha // View volume clip flags #define GW_LEFT_PLANE 0x0100 #define GW_RIGHT_PLANE 0x0200 #define GW_BOTTOM_PLANE 0x0400 #define GW_TOP_PLANE 0x0800 #define GW_FRONT_PLANE 0x1000 #define GW_BACK_PLANE 0x2000 #define GW_PLANE_MASK 0x3f00 // edge styles #define GW_EDGE_SKIP 0 #define GW_EDGE_VIS 1 #define GW_EDGE_INVIS 2 // buffer types (for dual-plane stuff) #define BUF_F_BUFFER 0 #define BUF_Z_BUFFER 1 // support method return values #define GW_DOES_SUPPORT TRUE #define GW_DOES_NOT_SUPPORT FALSE // support queries #define GW_SPT_TXT_CORRECT 0 // allow persp correction to be toggled? #define GW_SPT_GEOM_ACCEL 1 // do 3D xforms, clipping, lighting thru driver? #define GW_SPT_TRI_STRIPS 2 // send down strips instead of individual triangles? #define GW_SPT_DUAL_PLANES 3 // allow dual planes to be used? #define GW_SPT_SWAP_MODEL 4 // update viewports with complete redraw on WM_PAINT? #define GW_SPT_INCR_UPDATE 5 // redraw only damaged areas on object move? #define GW_SPT_1_PASS_DECAL 6 // do decaling with only one pass? #define GW_SPT_DRIVER_CONFIG 7 // allow driver config dialog box? #define GW_SPT_TEXTURED_BKG 8 // is viewport background a texture? #define GW_SPT_VIRTUAL_VPTS 9 // are viewports bigger than the window allowed? #define GW_SPT_PAINT_DOES_BLIT 10 // does WM_PAINT cause a backbuffer blit? #define GW_SPT_WIREFRAME_STRIPS 11 // if true, wireframe objects are sent as tristrips #define GW_SPT_ORG_UPPER_LEFT 12 // true if device origin is at upper left, false o/w #define GW_SPT_ARRAY_PROCESSING 13 // true if the driver can handle vertex array data #define GW_SPT_NUM_LIGHTS 14 // number of lights supported #define GW_SPT_NUM_TEXTURES 15 // number of multitexture stages supported #define GW_SPT_WIRE_FACES 16 // support for wireframe faces with visibility flags #define GW_SPT_TOTAL 17 // always the max number of spt queries // display state of the graphics window #define GW_DISPLAY_MAXIMIZED 1 #define GW_DISPLAY_WINDOWED 2 #define GW_DISPLAY_INVISIBLE 3 // multi-pass rendering #define GW_PASS_ONE 0 #define GW_PASS_TWO 1 // light types enum LightType { OMNI_LGT, SPOT_LGT, DIRECT_LGT, AMBIENT_LGT }; // Light attenuation types -- not fully implemented #define GW_ATTEN_NONE 0x0000 #define GW_ATTEN_START 0x0001 #define GW_ATTEN_END 0x0002 #define GW_ATTEN_LINEAR 0x0010 #define GW_ATTEN_QUAD 0x0020 // General 3D light structure /*! \sa <a href="ms-its:3dsmaxsdk.chm::/start_data_types.html">Data Types</a>.\n\n \par Description: This class describes the lights used in the interactive renderer. All methods of this class are implemented by the system. */ class Light : public BaseInterfaceServer { public: /*! \remarks Class constructor. Sets the default values of the light.\n\n <b>type = OMNI_LGT;</b>\n\n <b>attenType = NO_ATTEN;</b>\n\n <b>atten = (float)0.0;</b>\n\n <b>intensity = (float)1.0;</b>\n\n <b>angle = (float)30.0;</b>\n\n <b>color[0] = (float)1.0;</b>\n\n <b>color[1] = (float)1.0;</b>\n\n <b>color[2] = (float)1.0;</b> \par Data Members: <b>LightType type;</b>\n\n One of the following values:\n\n <b>OMNI_LGT</b>\n\n Omni-directional.\n\n <b>SPOT_LGT</b>\n\n Spot light.\n\n <b>DIRECT_LGT</b>\n\n Directional light.\n\n <b>AMBIENT_LGT</b>\n\n Ambient light - global illumination.\n\n <b>Point3 color;</b>\n\n The color of the light. Individual values are from 0.0 to 1.0 with 1.0 as white.\n\n <b>Attenuation attenType;</b>\n\n Attenuation is not currently implemented. A developer should pass <b>NO_ATTEN</b>.\n\n <b>float atten;</b>\n\n Note: Attenuation is not currently implemented.\n\n Light attenuation factor.\n\n <b>float intensity;</b>\n\n Light multiplier factor.\n\n <b>float angle;</b>\n\n Angle of cone for spot and cone lights in degrees.\n\n <b>int shape;</b>\n\n One of the following values:\n\n <b>GW_SHAPE_RECT</b> - Rectangular spotlights.\n\n <b>GW_SHAPE_CIRCULAR</b> - Circular spotlights.\n\n <b>float aspect;</b>\n\n The aspect ratio of the light.\n\n <b>int overshoot;</b>\n\n Nonzero indicates the light supports overshoot; otherwise 0.\n\n <b>BOOL affectDiffuse;</b>\n\n This data member is available in release 2.0 and later only.\n\n This defaults to TRUE, but if the user set it to FALSE in the light modifier panel, then the\n\n light is not supposed to illuminate the diffuse component of an object's material.\n\n <b>BOOL affectSpecular;</b>\n\n This data member is available in release 2.0 and later only.\n\n This defaults to TRUE, but if the user set it to FALSE in the light modifier panel, then the\n\n light is not supposed to illuminate the specular component of an object's material. */ DllExport Light(); LightType type; Point3 color; int attenType; float attenStart; float attenEnd; float intensity; float hotSpotAngle; float fallOffAngle; int shape; float aspect; int overshoot; BOOL affectDiffuse; BOOL affectSpecular; }; enum CameraType { PERSP_CAM, ORTHO_CAM }; // General camera structure class Camera : public BaseInterfaceServer { public: DllExport Camera(); void setPersp(float f, float asp) { type = PERSP_CAM; persp.fov = f; persp.aspect = asp; makeMatrix(); } void setOrtho(float l, float t, float r, float b) { type = ORTHO_CAM; ortho.left = l; ortho.top = t; ortho.right = r; ortho.bottom = b; makeMatrix(); } void setClip(float h, float y) { hither = h; yon = y; makeMatrix(); } CameraType getType(void) { return type; } float getHither(void) { return hither; } float getYon(void) { return yon; } DllExport void reset(); DllExport void getProj(float mat[4][4]); private: DllExport void makeMatrix(); float proj[4][4]; CameraType type; union { struct : public MaxHeapOperators { float fov; float aspect; } persp; struct : public MaxHeapOperators { float left; float right; float bottom; float top; } ortho; }; float hither; float yon; }; const double pi = 3.141592653589793; const double piOver180 = 3.141592653589793 / 180.0; // Color types (used by setColor) enum ColorType { LINE_COLOR, FILL_COLOR, TEXT_COLOR, CLEAR_COLOR }; // Marker types enum MarkerType { POINT_MRKR, HOLLOW_BOX_MRKR, PLUS_SIGN_MRKR, ASTERISK_MRKR, X_MRKR, BIG_BOX_MRKR, CIRCLE_MRKR, TRIANGLE_MRKR, DIAMOND_MRKR, SM_HOLLOW_BOX_MRKR, SM_CIRCLE_MRKR, SM_TRIANGLE_MRKR, SM_DIAMOND_MRKR, DOT_MRKR, SM_DOT_MRKR, BOX2_MRKR, BOX3_MRKR, BOX4_MRKR, BOX5_MRKR, BOX6_MRKR, BOX7_MRKR, DOT2_MRKR, DOT3_MRKR, DOT4_MRKR, DOT5_MRKR, DOT6_MRKR, DOT7_MRKR }; #define AC_DIR_RL_CROSS 0 // right->left => crossing (AutoCAD compatible) #define AC_DIR_LR_CROSS 1 // left->right => crossing (ACAD incompatible) DllExport void setAutoCross(int onOff); DllExport int getAutoCross(); DllExport void setAutoCrossDir(int dir); DllExport int getAutoCrossDir(); // Region types (for built-in hit-testing) #define POINT_RGN 0x0001 #define RECT_RGN 0x0002 #define CIRCLE_RGN 0x0004 #define FENCE_RGN 0x0008 // region directions (left or right) #define RGN_DIR_UNDEF -1 #define RGN_DIR_RIGHT 0 #define RGN_DIR_LEFT 1 struct CIRCLE: public MaxHeapOperators { LONG x; LONG y; LONG r; }; /*! \sa <a href="ms-its:3dsmaxsdk.chm::/start_data_types.html">Data Types</a>.\n\n \par Description: This class describes the properties of a region used for built-in hit testing of items in the interactive renderer. \par Data Members: <b>int type;</b>\n\n The region type. One of the following values:\n\n <b>POINT_RGN</b>\n\n A single point.\n\n <b>RECT_RGN</b>\n\n A rectangular region.\n\n <b>CIRCLE_RGN</b>\n\n A circular region.\n\n <b>FENCE_RGN</b>\n\n An arbitrary multi-point polygon region.\n\n <b>int crossing;</b>\n\n If nonzero, elements that are contained within <b>or cross</b> the region boundary are hit. If zero, only those elements <b>entirely within</b> the boundary are hit. This is not used for point hit testing.\n\n <b>int epsilon;</b>\n\n Specifies the distance in pixels outside the pick point within which elements may be and still be hit. This is not used for rect or circle testing, is sometimes used with fence hit testing, where it doubles the size of the region, especially when selecting subobject edges or vertices and is always used for point hit testing.\n\n <b>union {</b>\n\n <b>POINT pt;</b>\n\n <b>RECT rect;</b>\n\n <b>CIRCLE circle;</b>\n\n <b>POINT *pts;</b>\n\n <b>};</b>\n\n The storage for the region. */ class HitRegion: public MaxHeapOperators { DWORD size; public: int type; int dir; // region direction int crossing; // not used for point int epsilon; // not used for rect or circle union { POINT pt; RECT rect; CIRCLE circle; POINT * pts; }; HitRegion() { dir = RGN_DIR_UNDEF; size = sizeof(HitRegion);} }; inline int ABS(const int x) { return (x > 0) ? x : -x; } typedef void (*GFX_ESCAPE_FN)(void *); // driver types for getDriver() method #define GW_DRV_RENDERER 0 #define GW_DRV_DEVICE 1 // for possible future implementation #define GW_HEIDI 0 #define GW_OPENGL 1 #define GW_DIRECT3D 2 #define GW_HEIDI3D 3 #define GW_NULL 4 #define GW_CUSTOM 5 // graphics window setup structure /*! \sa Class GraphicsWindow.\n\n \par Description: This class is the graphics window setup structure. An instance of this class is passed to the function <b>createGW()</b> to create a new graphics window.\n\n Note: This is no longer available for use by plug-ins in 3ds Max 2.0 and later. */ class GWinSetup: public MaxHeapOperators { public: DllExport GWinSetup(); MCHAR caption[GW_MAX_CAPTION_LEN]; MCHAR renderer[GW_MAX_FILE_LEN]; MCHAR device[GW_MAX_FILE_LEN]; DWORD winStyle; POINT size; POINT place; INT_PTR id; // WIN64 Cleanup: Shuler int type; bool quietMode; }; // abstract graphics window class /*! \sa Class InteractiveRenderer for Graphics Window, Class GWinSetup, Class HitRegion, <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_marker_types.html">List of Marker Types</a>, <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_rendering_limits.html">List of Rendering Limits</a>, Class Point3, Class IPoint3, Class Matrix3, Class Interface, Class ViewExp.\n\n \par Description: The abstract graphics window class. The methods here provide low-level access to 3ds Max's graphics system. These methods are available for plug-ins to do any graphics work not possible using the standard high-level graphics methods of 3ds Max.\n\n These methods are for use in the existing 3ds Max viewports. Note that these APIs are not for casual use, as they are not intended to be a high level graphics library. For example, many steps are required to display a single lit polygon. These APIs are optimized for speed, and not at all for plug-in programmer ease of use.\n\n These methods are provided, however, so that developers can do things that are otherwise impossible using the high-level methods.\n\n <b>Developers should use these methods with an understanding of exactly what they are doing since it's quite easy to crash 3ds Max when inappropriate arguments are supplied. The calls are specifically optimized for exactly the way 3ds Max uses them. In no way should the calls in GraphicsWindow be considered an "ordinary" 2D/3D API. (That's what OpenGL, D3D, and HEIDI are for.)</b>\n\n One final note of warning: most graphics windows methods execute in a separate thread (or in multiple separate threads) that are owned by the graphics window. Thus, due to thread scheduling, when a bad argument or incorrect sequencing of graphics windows calls causes 3ds Max to crash, it is not at all easy to figure out where the problem is. In particular, the location of the main 3ds Max thread is not relevant.\n\n All the methods of this class are implemented by the system. \par Method Groups: See <a href="class_graphics_window_groups.html">Method Groups for Class GraphicsWindow</a>. */ class GraphicsWindow : public InterfaceServer { public: virtual ~GraphicsWindow() {} /*! \remarks This is called after all four GraphicsWindows used by 3ds Max are created. SDK users shouldn't need this call */ virtual void postCreate(int ct, GraphicsWindow **gw) = 0; /*! \remarks This is used to tell the driver that it is shutting down. */ virtual void shutdown() = 0; /*! \remarks This returns "0x200" to indicate R2.0 */ virtual int getVersion() = 0; /*! \remarks This identifies the driver (and includes manufacturer info if available) */ virtual MCHAR * getDriverString(void) = 0; /*! \remarks This is called to put up the config dialog if the driver supports GW_SPT_CAN_CONFIG \par Parameters: <b>HWND hWnd</b>\n\n The parent window handle for the dialog. */ virtual void config(HWND hWnd) = 0; /*! \remarks Determines if the driver supports the specified feature. \par Parameters: <b>int what</b>\n\n One of the following values:\n\n <b>GW_SPT_TXT_CORRECT</b>\n\n This is used to enable or gray-out the perspective correction right-click viewport menu option.\n\n <b>GW_SPT_GEOM_ACCEL</b>\n\n This is used to indicate to 3ds Max (and the mesh class in particular) that the driver wants to handle all of the 3D data natively. In this case, meshes are rendered by passing 3D world space data and letting the driver transform, clip, and light the vertices. If this returns FALSE, then the mesh class handles all xforms/clip/lighting calculations (using a lazy evaluation algorithm) and then calls the hPolygon or hPolyline 2 1/2D calls for the driver to rasterize. (Primitives that are actually clipped are still sent to the polygon/polyline methods.)\n\n Right now, only the OpenGL driver returns TRUE to this query, but other drivers have been developed that return TRUE, and the HEIDI and D3D drivers may change in the future.\n\n <b>GW_SPT_TRI_STRIPS</b>\n\n If this returns TRUE, then 3ds Max will try to stripify meshes before calling the rendering methods. Right now, the drivers just return the user preference that is set in the driver config dialog. It defaults to TRUE.\n\n <b>GW_SPT_DUAL_PLANES</b>\n\n If a driver has dual-planes support it returns TRUE. Our OpenGL display driver only returns TRUE for this if the underlying display driver has implemented a custom OpenGL extension that allows us to handle this efficiently.\n\n <b>GW_SPT_SWAP_MODEL</b>\n\n This returns TRUE if 3ds Max has to redraw the whole scene any time the viewports are exposed.\n\n <b>GW_SPT_INCR_UPDATE</b>\n\n This returns TRUE if the driver can update a rectangular subset of the viewport without trashing the image outside that rectangle. This is TRUE for most drivers that blit the viewport region and FALSE for those that do page-flipping in the hardware. For OpenGL, this is TRUE if the display driver implements the Microsoft glSwapRectHintWIN extension.\n\n <b>GW_SPT_1_PASS_DECAL</b>\n\n This is TRUE if the driver can handle decalling with only one pass. Right now, this is TRUE for OpenGL, but FALSE for HEIDI and D3D. (And as with all of these options, it may change in a given driver anytime in the future.)\n\n <b>GW_SPT_DRIVER_CONFIG</b>\n\n This is TRUE if the driver has a configuration dialog box. This is TRUE for all three of our standard drivers.\n\n <b>GW_SPT_TEXTURED_BKG</b>\n\n This is TRUE if the viewport background is implemented as a textured rectangle, and FALSE if it is a blitted bitmap.\n\n <b>GW_SPT_VIRTUAL_VPTS</b>\n\n This is TRUE if the driver allows viewports to be made larger than the physical window they are attached to. Right now this is ony TRUE for OGL.\n\n <b>GW_SPT_PAINT_DOES_BLIT</b>\n\n This is TRUE if WM_PAINT messages result in a blit of the backbuffer (as opposed to a page-flipping swap). This allows 3ds Max to do quick damage region repair, and works together with the GW_SPT_SWAP_MODEL flag.\n\n <b>GW_SPT_WIREFRAME_STRIPS</b>\n\n This is TRUE if the driver wants 3ds Max to send down wireframe models using triangle strips instead of a bundle of 2-pt segments. This is only used by the OGL driver, and it is there as a user-choosable performance-accuracy tradeoff (since the strips are faster and are back-culled, but they displayhidden edges as though they are visible). */ virtual int querySupport(int what) = 0; /*! \remarks This returns the "output" window handle. (Input goes to an invisible window above the viewport. The invisible window is owned by 3ds Max.) */ virtual HWND getHWnd(void) = 0; /*! \remarks Sets the size and position of the GraphicsWindow. The coordinates are all Windows coordinates in the space of the GraphicsWindows' parent window. (The origin is the upper left.) \par Parameters: <b>int x</b>\n\n Window x origin.\n\n <b>int y</b>\n\n Window y origin.\n\n <b>int w</b>\n\n Window width.\n\n <b>int h</b>\n\n Window height. */ virtual void setPos(int x, int y, int w, int h) = 0; /*! \remarks The specified value may be sent to the driver to indicate the display state of the viewport window controlled by the driver. \par Parameters: <b>int s</b>\n\n The display state to set. One of the following values:\n\n <b>GW_DISPLAY_MAXIMIZED</b>\n\n <b>GW_DISPLAY_WINDOWED</b>\n\n <b>GW_DISPLAY_INVISIBLE</b> */ virtual void setDisplayState(int s) = 0; /*! \remarks This method returns the current state. One of the following values:\n\n <b>GW_DISPLAY_MAXIMIZED</b>\n\n <b>GW_DISPLAY_WINDOWED</b>\n\n <b>GW_DISPLAY_INVISIBLE</b> */ virtual int getDisplayState() = 0; /*! \remarks This method gets the current window size in X. */ virtual int getWinSizeX() = 0; /*! \remarks This method gets the current window size in Y. */ virtual int getWinSizeY() = 0; /*! \remarks This method returns the z-buffer depth (in bits) */ virtual DWORD getWinDepth(void) = 0; /*! \remarks This method returns the largest device Z value. */ virtual DWORD getHitherCoord(void) = 0; /*! \remarks This method returns the smallest device Z value. */ virtual DWORD getYonCoord(void) = 0; /*! \remarks This method returns the size (in pixels) that the specified text string will occupy \par Parameters: <b>MCHAR *text</b>\n\n The string to check.\n\n <b>SIZE *sp</b>\n\n The size is returned here. See <a href="ms-its:3dsmaxsdk.chm::/start_data_types.html">Data Types</a>. */ virtual void getTextExtents(MCHAR *text, SIZE *sp) = 0; /*! \remarks This method returns the largest number of triangles that can be in a strip */ virtual int getMaxStripLength() { return GFX_MAX_STRIP; } virtual void setFlags(DWORD f) = 0; virtual DWORD getFlags() = 0; /*! \remarks This method resets the update rectangle. The update rectangle is the region of the screen that needs to be updated to reflect items that have changed. When the system is done rendering items, the goal is to only update the region that has actually been altered. This method sets the update rectangle (the region that will be blitted to the display) to invalid. In this way when <b>enlargeUpdateRect()</b> is later called, the RECT passed will be used as the region. */ virtual void resetUpdateRect() = 0; /*! \remarks This method enlarges the update rectangle to include the RECT passed. If <b>rp</b> is NULL, then the whole window will later be updated. \par Parameters: <b>RECT *rp</b>\n\n Pointer to a rectangle (or NULL). */ virtual void enlargeUpdateRect(RECT *rp) = 0; /*! \remarks This method retrieves the current update rectangle. \par Parameters: <b>RECT *rp</b>\n\n The current update rectangle. \return Zero if the update rectangle is invalid; otherwise nonzero. */ virtual int getUpdateRect(RECT *rp) = 0; /*! \remarks This method is used internally and should not be called by plug-in developers. */ virtual void updateScreen() = 0; /*! \remarks This method is used internally. Most drivers control two image buffers. One is displayed on the screen, and the other is used to rasterize geometric primitives. When rasterization of a complete frame is done, the off-screen buffer is blitted onto the display screen. This is referred to as dual-plane mode. This method will turn dual-plane mode on or off. This is used internally by the File/Preferences... Viewport page Use Dual Planes toggle. \par Parameters: <b>int which</b>\n\n Specifies which buffer should use dual-planes.\n\n <b>BUF_F_BUFFER</b>\n\n The image (Framebuffer) buffer.\n\n <b>BUF_Z_BUFFER</b>\n\n The Z buffer.\n\n <b>int b</b>\n\n Nonzero to enable access (toggle on); 0 to toggle off. \return TRUE if the graphics window has access to the specified buffer; otherwise FALSE. */ virtual BOOL setBufAccess(int which, int b) = 0; /*! \remarks This method is used internally. It returns a boolean value indicating if dual plane mode is on or off for the specified buffer. \par Parameters: The buffer whose dual-planes setting will be returned.\n\n <b>int which</b>\n\n The buffer whose dual-planes setting will be returned. One of the following values:\n\n <b>BUF_F_BUFFER</b>\n\n The Framebuffer.\n\n <b>BUF_Z_BUFFER</b>\n\n The Z buffer. \return TRUE if the dual-plane mode is on; otherwise FALSE. */ virtual BOOL getBufAccess(int which) = 0; /*! \remarks This method is used internally. It retrieves the size of the specified buffer in bytes. \par Parameters: <b>int which</b>\n\n One of the following values:\n\n <b>int *size</b>\n\n The size of the buffer in bytes.\n\n Note the following concerning the HEIDI driver. For HEIDI getBufSize() always returns 10 if dual-planes are on (and 0 otherwise). This is because HEIDI actually never returns the image - it keeps its own copy stored away. Thus the "logical" way to think is that we actually get a copy of the buffer by calling getBuf, and that we give it back by calling setBuf. But in reality (with the HEIDI driver) getBuf and setBuf only tell HEIDI to do some internal buffer manipulation. \return TRUE if the size was returned; otherwise FALSE. */ virtual BOOL getBufSize(int which, int *size) = 0; /*! \remarks This method is used internally. It retrieves the specified buffer. \par Parameters: <b>int which</b>\n\n The buffer to retrieve. One of the following values:\n\n <b>BUF_F_BUFFER -</b> The image Framebuffer.\n\n <b>BUF_Z_BUFFER -</b> The Z buffer.\n\n <b>int size</b>\n\n The number of bytes to retrieve. This must be at least the size returned from <b>getBufSize()</b>.\n\n <b>void *buf</b>\n\n Storage for the buffer data. \return TRUE if the buffer was retrieved; otherwise FALSE. */ virtual BOOL getBuf(int which, int size, void *buf) = 0; /*! \remarks Stores the specified buffer. \par Parameters: <b>int which</b>\n\n The buffer to store. One of the following values:\n\n <b>BUF_F_BUFFER -</b> The image Framebuffer.\n\n <b>BUF_Z_BUFFER -</b> The Z buffer.\n\n <b>int size</b>\n\n The number of bytes to store.\n\n <b>void *buf</b>\n\n The buffer data.\n\n <b>RECT *rp</b>\n\n This allows only a subset of the saved image rect to be blitted back to the screen. \return TRUE if the buffer was stored; otherwise FALSE. */ virtual BOOL setBuf(int which, int size, void *buf, RECT *rp) = 0; /*! \remarks This method returns the viewport image of this graphics window in a packed DIB format. A packed DIB is the standard BMI header followed immediately by all the data bytes (pixels) that make up the image. This is the standard way in Windows to pass a DIB around. See the sample code below for an example of this call in use. Note how it is called twice: once to get the size, once to get the DIB. \par Parameters: <b>BITMAPINFO *bmi</b>\n\n The BITMAPINFO structure defines the dimensions and color information for a Windows device-independent bitmap (DIB). Note that if this parameter is NULL, then only the size value is returned.\n\n <b>int *size</b>\n\n The size of the image in bytes. \return TRUE if the image was returned; otherwise FALSE. \par Sample Code: The following sample code saves the current 3ds Max viewport to a user specified file.\n\n \code void TestGetDIB(IObjParam *ip) { BITMAPINFO *bmi = NULL; BITMAPINFOHEADER *bmih; BitmapInfo biFile; Bitmap *map; int size; TheManager->SelectFileOutput(\&biFile, ip->GetMAXHWnd(), _M("Testing")); if(!biFile.Name()[0]) return; ViewExp *vpt = ip->GetActiveViewport(); vpt->getGW()->getDIB(NULL, \&size); bmi = (BITMAPINFO *)malloc(size); bmih = (BITMAPINFOHEADER *)bmi; vpt->getGW()->getDIB(bmi, \&size); biFile.SetWidth((WORD)bmih->biWidth); biFile.SetHeight((WORD)bmih->biHeight); biFile.SetType(BMM_TRUE_32); map = TheManager->Create(\&biFile); map->OpenOutput(\&biFile); map->FromDib(bmi); map->Write(\&biFile); map->Close(\&biFile); if(bmi) free(bmi); ip->ReleaseViewport(vpt); } \endcode */ virtual BOOL getDIB(BITMAPINFO *bmi, int *size) = 0; /*! \remarks This method is used internally to zoom the viewport. */ virtual BOOL setBackgroundDIB(int width, int height, BITMAPINFO *bmi) = 0; /*! \remarks This method is used internally to pan the viewport. */ virtual void setBackgroundOffset(int x, int y) = 0; virtual int useClosestTextureSize(int bkg=FALSE) = 0; /*! \remarks This method returns the size of the texture bitmap that the driver wants sent in to the <b>getTextureHandle()</b> call (if bkg is FALSE). If bkg is TRUE, this returns the size of the texture that 3ds Max shoud send to the <b>setBackgroundDIB()</b> call. In general, the return value needs to be a power of 2, though that could be driver-specific \par Parameters: <b>int bkg=FALSE</b>\n\n TRUE to get the size for <b>setBackgroundDIB()</b>; FALSE to get the size for <b>getTextureHandle()</b>. */ virtual int getTextureSize(int bkg=FALSE) = 0; /*! \remarks This method returns a handle for the specified texture bitmap. This handle is then used with the <b>setTextureByHandle()</b> method (there is only one current texture active at any time). The texture dimensions must be a power of 2.\n\n When a material is on an object, and the material has a texture map, and when the button used to display the texture map is pressed, 3ds Max calls this method to get the texture handle. This basically loads the texture into the hardware RAM (if available). When this mapped object gets displayed the method <b>setTextureHanel()</b> is called. When the material is deleted, or the dispaly in viewport button is turned off, <b>freeTextureHandle()</b> is called. \par Parameters: <b>BITMAPINFO *bmi</b>\n\n The DIB image to use as a texture. \return The texture handle. */ virtual DWORD_PTR getTextureHandle(BITMAPINFO *bmi) = 0; /*! \remarks When you are finished with the texture handle, call this method to free it. \par Parameters: <b>DWORD_PTR handle</b>\n\n The texture handle to free. \return TRUE if the texture was set; otherwise FALSE. */ virtual void freeTextureHandle(DWORD_PTR handle) = 0; /*! \remarks This sets the current texture to the image whose handle is passed (see <b>getTextureHandle()</b>). The texture dimensions must be a power of 2. \par Parameters: <b>DWORD_PTR handle</b>\n\n The handle of the texture to make current. */ virtual BOOL setTextureByHandle(DWORD_PTR handle, int texStage=0) = 0; // WIN64 Cleanup: Shuler virtual void setTextureColorOp(int texStage=0, int texOp=GW_TEX_MODULATE, int texAlphaSource=GW_TEX_TEXTURE, int texScale=GW_TEX_SCALE_1X) = 0; virtual void setTextureAlphaOp(int texStage=0, int texOp=GW_TEX_MODULATE, int texAlphaSource=GW_TEX_TEXTURE, int texScale=GW_TEX_SCALE_1X) = 0; /*! \remarks Sets the way in which textures are tiled across the surface of the object. \par Parameters: The following parameters may use one of these values:\n\n <b>GW_TEX_NO_TILING</b>\n\n The texture clamped - Any UVW that is bigger than 1 is interpreted as being 1.\n\n <b>GW_TEX_REPEAT</b>\n\n As the UVW numbers keep getting larger than 1 the image is repeated.\n\n <b>GW_TEX_MIRROR</b>\n\n If UVW goes beyond 1, the numbers are interpreted as going backwards. So if you had 0 to 2 it would actually go 0 to 1 then 1 down to 0.\n\n <b>int u</b>\n\n The type of texturing in the U direction.\n\n <b>int v</b>\n\n The type of texturing in the V direction.\n\n <b>int w=GW_TEX_NO_TILING</b>\n\n The type of texturing in the W direction. \return TRUE if the tiling mode was set; otherwise FALSE. */ virtual BOOL setTextureTiling(int u, int v, int w=GW_TEX_NO_TILING, int texStage=0) = 0; /*! \remarks Returns the type of texture tiling set for the particular direction.\n\n For example, if <b>setTextureTiling(GW_TEX_NO_TILING, GW_TEX_REPEAT, GW_TEX_MIRROR)</b> were called first, then\n\n <b>getTextureTiling(0)</b> would yield <b>GW_TEX_NO_TILING</b>, and\n\n <b>getTextureTiling(1)</b> would yield <b>GW_TEX_REPEAT</b>. \par Parameters: <b>int which</b>\n\n This value is 0 or 1 and it represents the U or V direction respectively. The value 2 is not yet implemented. \return <b>GW_TEX_NO_TILING</b>\n\n The texture clamped - Any UVW that is bigger than 1 is interpreted as being 1.\n\n <b>GW_TEX_REPEAT</b>\n\n As the UVW numbers keep getting larger than 1 the image is repeated.\n\n <b>GW_TEX_MIRROR</b>\n\n If UVW goes beyond 1, the numbers are interpreted as going backwards. So if you had 0 to 2 it would actually go 0 to 1 then 1 down to 0. */ virtual int getTextureTiling(int which, int texStage=0) = 0; /*! \remarks If a developer is working with an existing 3ds Max instance of GraphicsWindow (one of 3ds Max's viewports) this method should NOT be called. */ virtual void beginFrame() = 0; /*! \remarks As above, if a developer is working with an existing 3ds Max instance of GraphicsWindow (one of 3ds Max's viewports) this method should NOT be called. */ virtual void endFrame() = 0; /*! \remarks This method sets the clipping boundaries within a viewport within the graphics window. This allows more than one viewport to appear within a single graphics window. It has the side-effect of building a 4x4 viewport matrix. This routine should be called anytime the graphics window is resized, or else rendering will still occur to the old window size. (And since most drivers do not do range-checking since it is too time-costly, this could cause a system crash.) \par Parameters: Note: all coordinates are in Windows format, with the origin in the upper left\n\n <b>int x</b>\n\n Specifies the left viewport origin.\n\n <b>int y</b>\n\n Specifies the top viewport origin.\n\n <b>int w</b>\n\n Specifies the viewport width.\n\n <b>int h</b>\n\n Specifies the viewport height. */ virtual void setViewport(int x, int y, int w, int h) = 0; /*! \remarks This method is used to setup a virtual viewport. Note that this is a no-op unless <b>GW_SPT_VIRTUAL_VPTS</b> is TRUE. Plug-in developers should not call this method -- it's for internal use only. */ virtual void setVirtualViewportParams(float zoom, float xOffset, float yOffset) = 0; /*! \remarks This method is used to set a virtual viewport as active. Note that this is a no-op unless <b>GW_SPT_VIRTUAL_VPTS</b> is TRUE. Plug-in developers should not call this method -- it's for internal use only. \par Parameters: <b>int onOff</b>\n\n TRUE to set the virtual viewport active; FALSE to make it inactive. */ virtual void setUseVirtualViewport(int onOff) = 0; /*! \remarks Clears the specified rectangular region of the screen. \par Parameters: <b>RECT *rp</b>\n\n Specifies the rectangular region to clear.\n\n <b>int useBkg = FALSE</b>\n\n Specifies if the background should be used to fill the cleared area. Nonzero indicate the background should be used; 0 indicates the 'clear' color should be used (see <b>setColor()</b> above). */ virtual void clearScreen(RECT *rp, int useBkg = FALSE) = 0; /*! \remarks Sets the current transformation matrix, and updates the modeling coordinates to normalized projection coordinates matrix. This routine also back-transforms each light and the eye point (so that lighting can be done in modeling coordinates).\n\n This method may be used to set a matrix that transforms the point passed to the drawing methods (like <b>text(), marker(), polyline()</b> or <b>polygon()</b>). Normally these methods expect world coordinates. However if this matrix is set to an objects transformation matrix you can pass objects space coordinates and they will be transformed into world space (and then put into screen space when they are drawn). If however this is set to the identity matrix you would pass world space coordinates. You can set this matrix to the objects matrix using the following code:\n\n <b>gw-\>setTransform(inode-\>GetObjectTM(t));</b>\n\n Note: For world-to-screen space conversions by the methods <b>text(), marker(), polyline()</b>, <b>polygon()</b>, etc, a developer must explicitly set this matrix to the identity. This is because the <b>GraphicsWindow</b>transform may have a non-identity matrix already in place from a previous operation. \par Parameters: <b>const Matrix3 \&m</b>\n\n The new current transformation matrix. */ virtual void setTransform(const Matrix3 &m) = 0; virtual Matrix3 getTransform(void) = 0; virtual void multiplePass(int pass, BOOL onOff, float scaleFact = 1.005f) = 0; /*! \remarks Sets the current transparency flags for the current pass.\n\n \par Parameters: <b>DWORD settings</b>\n\n This can be a combination if GW_TRANSPARENCY and GW_TRANSPARENT_PASS See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_rendering_limits.html">Rendering Limits</a>. You also use these settings in the Render limits as well. */ virtual void setTransparency(DWORD settings) = 0; /*! \remarks This method allows one to put an affine transformation on a texture. This allows you to translate, rotate or scale a texture on an object. \par Parameters: <b>const Matrix3 \&m</b>\n\n The texture transformation matrix. */ virtual void setTexTransform(const Matrix3 &m, int texStage=0) = 0; /*! \remarks This is used internally. It returns if the determinant of the current transform is positive or negative. If it's positive 0 is returned; if it's negative 1 is returned. */ virtual BOOL getFlipped(void)=0; /*! \remarks Sets the number of triangles skipped when the viewport is set as a 'Fast View Display' viewport. To disable fastview, specify 1. Note that the GraphicsWindow class doesn't actually do anything with this number other than store it. Since triangles are handed down to GFX one at a time, it is up to the code that feeds triangles to the GraphicsWindow to skip the specified number of triangles. The mesh rendering in 3ds Max uses the skip count in this way. \par Parameters: <b>int n</b>\n\n Specifies that every 'n-th' triangle should be drawn. If set to 2, every other triangle should be drawn. */ virtual void setSkipCount(int c) = 0; /*! \remarks Returns the current skip count setting. */ virtual int getSkipCount(void) = 0; virtual void setViewportLimits(DWORD l) = 0; virtual DWORD getViewportLimits(void) = 0; /*! \remarks Sets the rendering limits used by primitive calls.\n\n Note: Setting the rendering limits is used in communication between the various parts of 3ds Max that handle the display of objects. For example, setting this limit to <b>GW_POLY_EDGES</b> and then drawing a polygon won't result in a polygon drawn with edges. It only sets a flag that indicates the edge should be drawn.\n\n What happens is as follows. Inside the upper level 3ds Max, part of the code knows that polygon edges have been turned on. However this is not related through the object oriented architecture to the part of 3ds Max that does the actual drawing. When 3ds Max goes to draw objects it will see that the polygon edge flag is on. This tells it to do two drawing passed -- one to do the polygon, then it calls <b>outlinePass()</b> call with TRUE, draws a bunch of edges, then calls <b>outline Pass()</b> with FALSE. Thus, the drawing routine is responsible for looking at the flags and drawing appropriately. This method is only responsible setting the limit which can later be checked. \par Parameters: <b>DWORD l</b>\n\n Specifies the rendering limit used by the viewport. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_rendering_limits.html">Rendering Limits</a>. */ virtual void setRndLimits(DWORD l) = 0; /*! \remarks Retrieves the rendering limits used by primitive calls. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_rendering_limits.html">Rendering Limits</a>. */ virtual DWORD getRndLimits(void) = 0; /*! \remarks Returns the current rendering mode used by the viewport. This is a subset of the rendering limit, in that any limits imposed by the rendering limit are forced onto the current mode. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_rendering_limits.html">Rendering Limits</a>. */ virtual DWORD getRndMode(void) = 0; /*! \remarks Returns the maximum number of lights that may be used by the interactive renderer. */ virtual int getMaxLights(void) = 0; /*! \remarks Turns a light on or off, and sets the light parameters. The light's position is set through the current transformation matrix at the time of this call. A particular light is specified by its light number (-1 through <b>getMaxLights()-1</b>). Light number -1 is reserved for ambient light. If a particular field in the Light class is not needed for a particular type of light, that field's value is ignored (for example, only the color field is used for ambient light.) \par Parameters: <b>int num</b>\n\n The light number of the light to set. This is a value in the range -1 to <b>getMaxLights()-1</b>.\n\n <b>const Light *l</b>\n\n The light class instance used to set the light parameters. If this is NULL, the light is turned off. */ virtual void setLight(int num, const Light *l) = 0; /*! \remarks This allows a developer to control if a light is used to render an object. There is one bit per light (bits 0 through <b>getMaxLights()</b>). If the bit is set the light is NOT used to render the object. If the bit is off, the light IS used. This method allows you to set the exclusion vector controlling the lights. \par Parameters: <b>DWORD exclVec</b>\n\n The exclusion vector controlling the lights. */ virtual void setLightExclusion(DWORD exclVec) = 0; /*! \remarks This method is no longer used. */ virtual void setCamera(const Camera &c) = 0; /*! \remarks Sets the properties of the current camera used by the GraphicsWindow. \par Parameters: <b>float mat[4][4]</b>\n\n The transformation matrix times the projection matrix.\n\n <b>Matrix3 *invTM</b>\n\n This is the inverse of the affine part of the camera transformation matrix (not the inverse of the projection part).\n\n <b>int persp</b>\n\n Nonzero indicates this is a perspective view; 0 is orthogonal.\n\n <b>float hither</b>\n\n Near clip value.\n\n <b>float yon</b>\n\n Far clip value. */ virtual void setCameraMatrix(float mat[4][4], Matrix3 *invTM, int persp, float hither, float yon) = 0; /*! \remarks Retrieves the properties of the current camera. \par Parameters: <b>float mat[4][4]</b>\n\n The transformation matrix times the projection matrix.\n\n <b>Matrix3 *invTM</b>\n\n This is the inverse of the affine part of the camera transformation matrix (not the inverse of the projection part).\n\n <b>int *persp</b>\n\n Nonzero indicates this is a perspective view; 0 is orthogonal.\n\n <b>float *hither</b>\n\n Near clip value.\n\n <b>float *yon</b>\n\n Far clip value. */ virtual void getCameraMatrix(float mat[4][4], Matrix3 *invTM, int *persp, float *hither, float *yon) = 0; /*! \remarks Sets the RGB color used for the specified drawing type (line, fill, text, clear). \par Parameters: <b>ColorType t</b>\n\n One of the following values:\n\n <b>LINE_COLOR</b>\n\n Line drawing color.\n\n <b>FILL_COLOR</b>\n\n Polygon fill color.\n\n <b>TEXT_COLOR</b>\n\n Text drawing color.\n\n <b>CLEAR_COLOR</b>\n\n The color that the viewport is cleared to when you call <b>clearScreen()</b>.\n\n <b>float r</b>\n\n Specifies the red amount 0.0 - 1.0.\n\n <b>float g</b>\n\n Specifies the green amount 0.0 - 1.0.\n\n <b>float b</b>\n\n Specifies the blue amount 0.0 - 1.0. */ virtual void setColor(ColorType t, float r, float g, float b) = 0; void setColor(ColorType t, Point3 clr) { setColor(t,clr.x,clr.y,clr.z); } /*! \remarks Sets the current rendering material, and modifies the rendering mode parameter for controlling the rasterizer driver. Note: You must have your rendering limit set BEFORE you set the material because the material setting may lower the rendering mode based on the material limits. \par Parameters: <b>const Material \&m</b>\n\n The new material to instantiate\n\n <b>int index=0</b>\n\n Indicates which material index refers to the material which gets set. */ virtual void setMaterial(const Material &m, int index=0) = 0; /*! \remarks Returns the current rendering material.\n\n */ virtual Material *getMaterial(void) = 0; virtual int getMaxTextures(void) = 0; /*! \remarks This method converts coordinates to "<b>h</b>" format device coordinates. Note: This method maps points from the GraphicsWindow's current transform to device space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>const Point3 *in</b>\n\n The input point.\n\n <b>IPoint3 *out</b>\n\n The output point in integer format values in the native device coords for the device. For HEIDI and OpenGL the origin at the lower left. For Direct3D the origin is at the upper left. \return DWORD containing the clipping flags for the point. If a flag is set it indicates the transformed point lies outside the view volume. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_clip_flags.html">List of Clip Flags</a>. */ virtual DWORD hTransPoint(const Point3 *in, IPoint3 *out) = 0; /*! \remarks This method is used to convert coordinates to "<b>w</b>" format device coordinates. Note: This method maps points from the GraphicsWindow's current transform to device space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>.\n\n \par Parameters: <b>const Point3 *in</b>\n\n The input point.\n\n <b>IPoint3 *out</b>\n\n The output point in integer format with the origin at the upper left. \return DWORD containing the clipping flags for the point. If a flag is set it indicates the transformed point lies outside the view volume. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_clip_flags.html">List of Clip Flags</a>. */ virtual DWORD wTransPoint(const Point3 *in, IPoint3 *out) = 0; /*! \remarks This method is used to convert coordinates to "<b>h</b>" <b>floating point</b> coordinates. This is just a helper routine to avoid building up round-off error. 3ds Max uses it just for IK. Note: This method maps points from the GraphicsWindow's current transform to device space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>const Point3 *in</b>\n\n The input point.\n\n <b>Point3 *out</b>\n\n The output point in floating point format with the origin at the lower left. \return DWORD containing the clipping flags for the point. If a flag is set it indicates the transformed point lies outside the view volume. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_clip_flags.html">List of Clip Flags</a>. */ virtual DWORD transPoint(const Point3 *in, Point3 *out) = 0; /*! \remarks Lights a vertex, using all the current lights. The vertex appears to be transformed using the current transformation matrix, although actually the calculations are done using back-transformed light coordinates (for speed). The vertex position and normal are passed in, and a color is returned. The rendering uses the current material. \par Parameters: <b>const Point3 \&pos</b>\n\n Vertex position.\n\n <b>const Point3 \&nor</b>\n\n Vertex normal.\n\n <b>Point3 \&rgb</b>\n\n Returned color. */ virtual void lightVertex(const Point3 &pos, const Point3 &nor, Point3 &rgb) = 0; /*! \remarks Draws 2D fixed font annotation text to the specified location. Note: This routine DOES perform clipping of the text if it is off the screen. \par Parameters: <b>IPoint3 *xyz</b>\n\n This is the device coordinate for the text. The origin of the text is at the lower left corner.\n\n <b>MCHAR *s</b>\n\n The text to display. */ virtual void hText(IPoint3 *xyz, MCHAR *s) = 0; /*! \remarks Draws a marker at the specified location. \par Parameters: <b>IPoint3 *xyz</b>\n\n This is the device coordinate for the marker (with the origin at the lower left).\n\n <b>MarkerType type</b>\n\n See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_marker_types.html">List of Marker Types</a>. */ virtual void hMarker(IPoint3 *xyz, MarkerType type) = 0; /*! \remarks This method draws a multi-segment polyline. \par Parameters: <b>int ct</b>\n\n The number of points in the polyline. The maximum number of points that may be used in drawing a polyline is 32.\n\n <b>IPoint3 *xyz</b>\n\n Array of points. These are device coordinates with the origin at the lower left.\n\n <b>Point3 *rgb</b>\n\n If the shade mode is set to smooth and these colors for the vertices are specified the polyline will be drawn Gourand shaded. This is how 3ds Max draws lit wireframes for instance. If you simply want ordinary lines (drawn using the line color) pass NULL.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>int closed</b>\n\n If nonzero the first point is connected to the last point, i.e. the polyline is closed.\n\n <b>int *es</b>\n\n Edge state array. This is an array that Indicates if the 'i-th' edge is one of three state:\n\n <b>GW_EDGE_SKIP</b>\n\n Nonexistent - totally invisible.\n\n <b>GW_EDGE_VIS</b>\n\n Exists and is solid.\n\n <b>GW_EDGE_INVIS</b>\n\n Exists and is hidden - shown as a dotted line.\n\n You may pass NULL for this array and the method will assume that the edges are all solid. */ virtual void hPolyline(int ct, IPoint3 *xyz, Point3 *rgb, int closed, int *es) = 0; /*! \remarks This method is available in release 2.0 and later only.\n\n This method draws a multi-segment polyline. \par Parameters: <b>int ct</b>\n\n The number of points in the polyline. The maximum number of points that may be used in drawing a polyline is 32.\n\n <b>IPoint3 *xyz</b>\n\n Array of points. These are device coordinates with the origin at the lower left.\n\n <b>Point3 *rgb</b>\n\n If the shade mode is set to smooth and these colors for the vertices are specified the polyline will be drawn Gourand shaded. This is how 3ds Max draws lit wireframes for instance. If you simply want ordinary lines (drawn using the line color) pass NULL.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>Point3 *uvw</b>\n\n This is not currently used. Pass NULL.\n\n <b>int closed</b>\n\n If nonzero the first point is connected to the last point, i.e. the polyline is closed.\n\n <b>int *es</b>\n\n Edge state array. This is an array that Indicates if the 'i-th' edge is one of three state:\n\n <b>GW_EDGE_SKIP</b>\n\n Nonexistent - totally invisible.\n\n <b>GW_EDGE_VIS</b>\n\n Exists and is solid.\n\n <b>GW_EDGE_INVIS</b>\n\n Exists and is hidden - shown as a dotted line.\n\n You may pass NULL for this array and the method will assume that the edges are all solid. */ void hPolyline(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int closed, int *es) { hPolyline(ct, xyz, rgb, closed, es); } /*! \remarks This method draws a multi-point polygon. \par Parameters: <b>int ct</b>\n\n The number of points in the polygon.\n\n <b>IPoint3 *xyz</b>\n\n Array of points. These are device coordinates with the origin at the lower left.\n\n <b>Point3 *rgb</b>\n\n The color values at the vertices. The rendering mode must include <b>GW_ILLUM</b> for these values to be used.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>Point3 *uvw</b>\n\n The UVW coordinates. The rendering mode must include <b>GW_TEXTURE</b> for these values to be used. */ virtual void hPolygon(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0; /*! \remarks This method is used for drawing a series of triangles specified as 'strips'. It takes a count of 3 or more, and builds triangles in a strip. This sends a lot less data and the underlying graphics library has to set up a lot less data since it can use the previous information to start the rasterization. This results in a significant speed increase.\n\n Note that this routine does no clipping so all the points passed must be within view. \par Parameters: <b>int ct</b>\n\n The total number of points. After the first two points, each new point is used to create a new triangle.\n\n <b>IPoint3 *xyz</b>\n\n The point data with the origin at the lower left. For instance, to draw a quad, the first three points specify the first triangle and the next one is combined with the previous two to complete the square.\n\n The order for these points follows the 'standard' conventions for stripping used in most graphics libraries (for example Direct3D, OpenGL and Heidi).\n\n <b>Point3 *rgb</b>\n\n The colors for the vertices.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>Point3 *uvw</b>\n\n The UVW texture coordinates for the vertices. */ virtual void hTriStrip(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0; /*! \remarks Draws 2D fixed font annotation text to the specified location. Note: This routine DOES perform clipping of the text if it is off the screen. \par Parameters: <b>IPoint3 *xyz</b>\n\n This is the device coordinate for the text. The origin of the text is at the upper left corner.\n\n <b>MCHAR *s</b>\n\n The text to display. */ virtual void wText(IPoint3 *xyz, MCHAR *s) = 0; /*! \remarks Draws a marker at the specified location. \par Parameters: <b>IPoint3 *xyz</b>\n\n This is the device coordinate for the marker.\n\n <b>MarkerType type</b>\n\n See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_marker_types.html">List of Marker Types</a>. */ virtual void wMarker(IPoint3 *xyz, MarkerType type) = 0; /*! \remarks This method draws a multi-segment polyline. \par Parameters: <b>int ct</b>\n\n The number of points in the polyline. The maximum number of points that may be used in drawing a polyline is 32.\n\n <b>IPoint3 *xyz</b>\n\n Array of points. These are device coordinates with the origin at the upper left.\n\n <b>Point3 *rgb</b>\n\n If the shade mode is set to smooth and these colors for the vertices are specified the polyline will be drawn Gourand shaded. This is how 3ds Max draws lit wireframes for instance. If you simply want ordinary lines (drawn using the line color) pass NULL.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>int closed</b>\n\n If nonzero the first point is connected to the last point, i.e. the polyline is closed.\n\n <b>int *es</b>\n\n Edge state array. This is an array that Indicates if the 'i-th' edge is one of three state:\n\n <b>GW_EDGE_SKIP</b>\n\n Nonexistent - totally invisible.\n\n <b>GW_EDGE_VIS</b>\n\n Exists and is solid.\n\n <b>GW_EDGE_INVIS</b>\n\n Exists and is hidden - shown as a dotted line.\n\n You may pass NULL for this array and the method will assume that the edges are all solid. */ virtual void wPolyline(int ct, IPoint3 *xyz, Point3 *rgb, int closed, int *es) = 0; /*! \remarks This method is available in release 2.0 and later only.\n\n This method draws a multi-segment polyline. \par Parameters: <b>int ct</b>\n\n The number of points in the polyline. The maximum number of points that may be used in drawing a polyline is 32.\n\n <b>IPoint3 *xyz</b>\n\n Array of points. These are device coordinates with the origin at the upper left.\n\n <b>Point3 *rgb</b>\n\n If the shade mode is set to smooth and these colors for the vertices are specified the polyline will be drawn Gourand shaded. This is how 3ds Max draws lit wireframes for instance. If you simply want ordinary lines (drawn using the line color) pass NULL.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>Point3 *uvw</b>\n\n This is not currently used. Pass NULL.\n\n <b>int closed</b>\n\n If nonzero the first point is connected to the last point, i.e. the polyline is closed.\n\n <b>int *es</b>\n\n Edge state array. This is an array that Indicates if the 'i-th' edge is one of three state:\n\n <b>GW_EDGE_SKIP</b>\n\n Nonexistent - totally invisible.\n\n <b>GW_EDGE_VIS</b>\n\n Exists and is solid.\n\n <b>GW_EDGE_INVIS</b>\n\n Exists and is hidden - shown as a dotted line.\n\n You may pass NULL for this array and the method will assume that the edges are all solid. */ void wPolyline(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int closed, int *es) { wPolyline(ct, xyz, rgb, closed, es); } /*! \remarks This method draws a multi-point polygon. \par Parameters: <b>int ct</b>\n\n The number of points in the polygon.\n\n <b>IPoint3 *xyz</b>\n\n Array of points. These are device coordinates with the origin at the upper left.\n\n <b>Point3 *rgb</b>\n\n The color values at the vertices. The rendering mode must include <b>GW_ILLUM</b> for these values to be used.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>Point3 *uvw</b>\n\n The UVW coordinates. The rendering mode must include <b>GW_TEXTURE</b> for these values to be used. */ virtual void wPolygon(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0; /*! \remarks This method is used for drawing a series of triangles specified as 'strips'. It takes a count of 3 or more, and builds triangles in a strip. This sends a lot less data and the underlying graphics library has to set up a lot less data since it can use the previous information to start the rasterization. This results in a significant speed increase.\n\n Note that this routine does no clipping so all the points passed must be within view. \par Parameters: <b>int ct</b>\n\n The total number of points. After the first two points, each new point is used to create a new triangle.\n\n <b>IPoint3 *xyz</b>\n\n The point data with the origin at the upper left. For instance, to draw a quad, the first three points specify the first triangle and the next one is combined with the previous two to complete the square.\n\n The order for these points follows the 'standard' conventions for stripping used in most graphics libraries (for example Direct3D, OpenGL and Heidi).\n\n <b>Point3 *rgb</b>\n\n The colors for the vertices.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>Point3 *uvw</b>\n\n The UVW texture coordinates for the vertices. */ virtual void wTriStrip(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0; /*! \remarks Draws 2D fixed font annotation text to the specified location. This method does perform clipping.\n\n Note: This method maps points from the GraphicsWindow's current transform to screen space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>Point3 *xyz</b>\n\n This is the coordinate for the text.\n\n <b>MCHAR *s</b>\n\n The text to display. Note: This routine DOES perform clipping of the text if it is off the screen. */ virtual void text(Point3 *xyz, MCHAR *s) = 0; virtual void startMarkers() = 0; /*! \remarks Draws a marker at the specified location in world space. This method does perform clipping.\n\n Note: This method maps points from the GraphicsWindow's current transform to screen space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>Point3 *xyz</b>\n\n This is the coordinate for the marker.\n\n <b>MarkerType type</b>\n\n See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_marker_types.html">List of Marker Types</a>. */ virtual void marker(Point3 *xyz, MarkerType type) = 0; virtual void endMarkers() = 0; virtual void polyline(int ct, Point3 *xyz, Point3 *rgb, int closed, int *es) = 0; /*! \remarks Draws a multi-segment polyline with the coordinates specified in world space. This method does perform clipping.\n\n Note: The arrays of points and vertex related data all must be at least one element larger than the <b>ct</b> parameter that is passed in. The 3D clipper will use the "extra" space to clip as efficiently as possible. If room for the extra element is not provided, 3ds Max may crash.\n\n Note: This method maps points from the GraphicsWindow's current transform to screen space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>int ct</b>\n\n The number of points in the polyline. The maximum number of points that may be used in drawing a polyline is 32.\n\n <b>Point3 *xyz</b>\n\n Array of points. This array must be at least one element larger than the <b>ct</b> parameter that is passed in. The 3D clipper will use the "extra" space to clip as efficiently as possible. If room for the extra element is not provided, 3ds Max will crash.\n\n <b>Point3 *rgb</b>\n\n If the shade mode is set to smooth and these colors for the vertices are specified the polyline will be drawn Gourand shaded. This is how 3ds Max draws lit wireframes for instance. If you simply want ordinary lines (drawn using the line color) pass NULL.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>Point3 *uvw</b>\n\n This is not currently used. Pass NULL.\n\n <b>int closed</b>\n\n If nonzero the first point is connected to the last point, i.e. the polyline is closed.\n\n <b>int *es</b>\n\n Edge state array. This is an array that Indicates if the 'i-th' edge is one of three state:\n\n <b>GW_EDGE_SKIP</b>\n\n Nonexistent - totally invisible.\n\n <b>GW_EDGE_VIS</b>\n\n Exists and is solid.\n\n <b>GW_EDGE_INVIS</b>\n\n Exists and is hidden - shown as a dotted line.\n\n You may pass NULL for this array and the method will assume that the edges are all solid. */ void polyline(int ct, Point3 *xyz, Point3 *rgb, Point3 *uvw, int closed, int *es) { polyline(ct, xyz, rgb, closed, es); } /*! \remarks Draws a multi-segment polyline with the coordinates specified in world space. This method takes a polyline with a normal for each vertex. This is used for hardware accelerated lit wireframes (when <b>GW_SPT_GEOM_ACCEL</b> is TRUE).\n\n Note: The arrays of points and vertex related data all must be at least one element larger than the <b>ct</b> parameter that is passed in. The 3D clipper will use the "extra" space to clip as efficiently as possible. If room for the extra element is not provided, 3ds Max may crash.\n\n This method does perform clipping.\n\n Note: This method maps points from the GraphicsWindow's current transform to screen space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>int ct</b>\n\n The number of points in the polyline. The maximum number of points that may be used in drawing a polyline is 32.\n\n <b>Point3 *xyz</b>\n\n Array of points. This array must be at least one element larger than the <b>ct</b> parameter that is passed in. The 3D clipper will use the "extra" space to clip as efficiently as possible. If room for the extra element is not provided, 3ds Max will crash.\n\n <b>Point3 *nor</b>\n\n The normal values at the vertices, one for each vertex.\n\n <b>int closed</b>\n\n If nonzero the first point is connected to the last point, i.e. the polyline is closed.\n\n <b>int *es</b>\n\n Edge state array. This is an array that Indicates if the 'i-th' edge is one of three state:\n\n <b>GW_EDGE_SKIP</b>\n\n Nonexistent - totally invisible.\n\n <b>GW_EDGE_VIS</b>\n\n Exists and is solid.\n\n <b>GW_EDGE_INVIS</b>\n\n Exists and is hidden - shown as a dotted line.\n\n You may pass NULL for this array and the method will assume that the edges are all solid. */ virtual void polylineN(int ct, Point3 *xyz, Point3 *nor, int closed, int *es) = 0; /*! \remarks This method is used to begin efficiently sending a lot of 3D line segments. First call this method, then call <b>segment()</b> many times (with two points), then call <b>endSegments()</b>. */ virtual void startSegments() = 0; /*! \remarks This method draws a single 3D line segment between the specified points. Call <b>startSegments()</b> once before calling this method. \par Parameters: <b>Point3 *xyz</b>\n\n Points to the two line endpoints in world space.\n\n <b>int vis</b>\n\n Nonzero for the segment to be visible; zero for invisible. */ virtual void segment(Point3 *xyz, int vis) = 0; /*! \remarks Call this method after sending 3D line segments with <b>segment()</b>. */ virtual void endSegments() = 0; /*! \remarks Draws a multi-point polygon. Note: All arrays (<b>xyz, rgb, uvw</b>) must be at least one element larger than the <b>ct</b> parameter that is passed in. The 3D clipper will use the "extra" space to clip as efficiently as possible. If room for the extra element is not provided, 3ds Max may crash.\n\n Note: This method maps points from the GraphicsWindow's current transform to screen space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>int ct</b>\n\n The number of points in the polygon.\n\n <b>Point3 *xyz</b>\n\n Array of points.\n\n <b>Point3 *rgb</b>\n\n The color values at the vertices. The rendering mode must include <b>GW_ILLUM</b> for these values to be used.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>Point3 *uvw</b>\n\n The UVW coordinates. The rendering mode must include <b>GW_TEXTURE</b> for these values to be used. */ virtual void polygon(int ct, Point3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0; /*! \remarks Draws a multi-point polygon. Note: All arrays (<b>xyz, nor, uvw</b>) must be at least one element larger than the <b>ct</b> parameter that is passed in. The 3D clipper will use the "extra" space to clip as efficiently as possible. If room for the extra element is not provided, 3ds Max will crash.\n\n This method sends in normal vectors instead of color for 3D accelerated rendering (when <b>GW_SPT_GEOM_ACCEL</b> is TRUE)\n\n Note: This method maps points from the GraphicsWindow's current transform to screen space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>int ct</b>\n\n The number of points in the polygon.\n\n <b>Point3 *xyz</b>\n\n Array of points.\n\n <b>Point3 *nor</b>\n\n The normal values at the vertices, one for each vertex.\n\n <b>Point3 *uvw</b>\n\n The UVW coordinates. The rendering mode must include <b>GW_TEXTURE</b> for these values to be used. */ virtual void polygonN(int ct, Point3 *xyz, Point3 *nor, Point3 *uvw, int texNum=1) = 0; /*! \remarks This method is used for drawing a series of triangles specified as 'strips'. It takes a count of 3 or more, and builds triangles in a strip. This sends a lot less data and the underlying graphics library has to set up a lot less data since it can use the previous information to start the rasterization. This results in a significant speed increase. \par Parameters: <b>int ct</b>\n\n The total number of points. After the first two points, each new point is used to create a new triangle.\n\n <b>IPoint3 *xyz</b>\n\n The point data. For instance, to draw a quad, the first three points specify the first triangle and the next one is combined with the previous two to complete the square.\n\n The order for these points follows the 'standard' conventions for stripping used in most graphics libraries (for example Direct3D, OpenGL and Heidi).\n\n <b>Point3 *rgb</b>\n\n The colors for the vertices.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.)\n\n <b>Point3 *uvw</b>\n\n The UVW texture coordinates for the vertices. */ virtual void triStrip(int ct, Point3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0; /*! \remarks This method is used for drawing a series of triangles specified as 'strips'. It takes a count of 3 or more, and builds triangles in a strip. This sends a lot less data and the underlying graphics library has to set up a lot less data since it can use the previous information to start the rasterization. This results in a significant speed increase. This method sends in normal vectors instead of color for 3D accelerated rendering (when <b>GW_SPT_GEOM_ACCEL</b> is TRUE) \par Parameters: <b>int ct</b>\n\n The total number of points. After the first two points, each new point is used to create a new triangle.\n\n <b>Point3 *xyz</b>\n\n The point data. For instance, to draw a quad, the first three points specify the first triangle and the next one is combined with the previous two to complete the square.\n\n The order for these points follows the 'standard' conventions for stripping used in most graphics libraries (for example Direct3D, OpenGL and Heidi).\n\n <b>Point3 *nor</b>\n\n The normal for each vertex.\n\n <b>Point3 *uvw</b>\n\n The UVW texture coordinates for the vertices. */ virtual void triStripN(int ct, Point3 *xyz, Point3 *nor, Point3 *uvw, int texNum=1) = 0; /*! \remarks This method is called to begin sending a series of non-stripped triangles to render. Call this method, then any of the <b>triangle*()</b> methods many times, then <b>endTriangles()</b> to finish. */ virtual void startTriangles() = 0; /*! \remarks This method sends a single non-stripped triangle to render. Call <b>startTriangles()</b> first.\n\n Note: This method maps points from the GraphicsWindow's current transform to screen space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>Point3 *xyz</b>\n\n The three points for the triangle.\n\n <b>Point3 *rgb</b>\n\n The color for each vertex.\n\n Note: The use of these colors is not supported under the OpenGL driver. The rgb values are ignored. Only the current material is taken into consideration. (This is how OpenGL works.) */ virtual void triangle(Point3 *xyz, Point3 *rgb) = 0; /*! \remarks This method draws a single triangle by specifying the vertex points in world space, a normal, and texture coordinates for each vertex.\n\n Note: This method maps points from the GraphicsWindow's current transform to screen space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>Point3 *xyz</b>\n\n The three points for the triangle.\n\n <b>Point3 *nor</b>\n\n The three normals for the triangle.\n\n <b>Point3 *uvw</b>\n\n The texture coordinate for each vertex. */ virtual void triangleN(Point3 *xyz, Point3 *nor, Point3 *uvw, int texNum=1) = 0; /*! \remarks This method draws a single triangle by specifying the vertex points in world space, a normal, and a color for each vertex.\n\n Note: This method maps points from the GraphicsWindow's current transform to screen space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>Point3 *xyz</b>\n\n The three points for the triangle.\n\n <b>Point3 *nor</b>\n\n The normal for each vertex.\n\n <b>Point3 *rgb</b>\n\n The color for each vertex. */ virtual void triangleNC(Point3 *xyz, Point3 *nor, Point3 *rgb) = 0; /*! \remarks This method draws a single triangle by specifying the vertex points in world space, a normal, a color, and a texture coordinate for each vertex.\n\n Note: This method maps points from the GraphicsWindow's current transform to screen space. If the GraphicsWindow's transform is set to the identity matrix then the mapping is done from points specified in world space. Otherwise the points given are transformed by the GraphicsWindow transform, and are <b>then</b> considered to be in world space. Thus, to get a world-space to screen-space conversion, you need to set the transform to the identity with <b>gw-\>setTransform(Matrix3(1))</b>. \par Parameters: <b>Point3 *xyz</b>\n\n The three points for the triangle.\n\n <b>Point3 *nor</b>\n\n The normal for each vertex.\n\n <b>Point3 *rgb</b>\n\n The color for each vertex.\n\n <b>Point3 *uvw</b>\n\n The texture coordinate for each vertex. */ virtual void triangleNCT(Point3 *xyz, Point3 *nor, Point3 *rgb, Point3 *uvw, int texNum=1) = 0; virtual void triangleW(Point3 *xyz, int *es) = 0; virtual void triangleNW(Point3 *xyz, Point3 *nor, int *es) = 0; /*! \remarks Call this method to finish rendering triangles. See <b>startTriangles()</b> above. */ virtual void endTriangles() = 0; virtual void loadMeshData(DWORD_PTR id, int xyzCt, Point3 *xyz, int norCt, Point3 *nor, int texNum, int uvwCt, Point3 *uvw, int mtlCt, Material *mtl) = 0; virtual void processStrips(DWORD_PTR id, int stripCt, StripTab *s, GFX_ESCAPE_FN fn) = 0; virtual void processWireFaces(int xyzCt, Point3 *xyz, int faceCt, GWFace *face, int dispFlags, BitArray *faceSel, BitArray *edgeSel, int mtlCt, Material *mtl, GFX_ESCAPE_FN fn) = 0; /*! \remarks Sets the hit region used for hit testing. See Class HitRegion. \par Parameters: <b>HitRegion *rgn</b>\n\n The hit region to use. */ virtual void setHitRegion(HitRegion *rgn) = 0; /*! \remarks This methods clears the hit code. Call this method before performing a hit test. */ virtual void clearHitCode(void) = 0; /*! \remarks Returns TRUE if the hit code is set indicating a hit was made; otherwise FALSE. */ virtual BOOL checkHitCode(void) = 0; /*! \remarks This method allows drawing code to manually set the state of the hit code, which is returned by the <b>checkHitCode()</b> method. For more information see the topic on <a href="ms-its:3dsmaxsdk.chm::/vports_hit_testing.html">Hit Testing</a>.\n\n The new methods <b>setHitDistance()</b> and <b>setHitCode()</b> make it possible to work with GraphicsWindow hit-testing in otherwise impossible situations. Why are they necessary? An example from is shown below. The patch object contains bezier spline-based edges which can consist of up to 102 vertices. Since the GraphicsWindow::polyline function can only plot lines with up to 32 vertices, it is impossible to plot these in a single call to the polyline function. Multiple calls to the polyline call do not return a proper hitcode when using a "window"-type hit region. By using the new <b>setHitCode()</b> method, code can properly handle this situation. The code below shows the function in use from the PatchMesh::renderEdge method: \code int steps = GetMeshSteps(); int segNum = steps+2; float fsegNum = (float) (segNum-1); // If steps are too high for GraphicsWindow's buffer, we must draw it manually if((steps + 2) > GW_MAX_VERTS) { Point3 line[2]; Point3 prev,current(.0f,.0f,.0f); BOOL hitAll = TRUE; BOOL hitAny = FALSE; DWORD hitDist = 0xffffffff; for(int terp = 0; terp \ { prev = current; current = work.InterpCurve3D((float)terp / fsegNum); if (terp != 0) { line[0] = prev; line[1] = current; gw->clearHitCode(); gw->polyline(2, line, NULL, NULL, 0, NULL); if(gw->checkHitCode()) { hitAny = TRUE; if(gw->getHitDistance() \ hitDist = gw->getHitDistance(); } else hitAll = FALSE; } } if(hr && !hr->crossing && hr->type != POINT_RGN) gw->setHitCode(hitAll); else gw->setHitCode(hitAny); gw->setHitDistance(hitDist); } else { for(int terp = 0; terp \ fixedBuf[terp] = work.InterpCurve3D((float)terp / fsegNum); gw->polyline(steps+2, fixedBuf, NULL, NULL, 0, NULL); } \endcode Note that the <b>gw-\>polyline</b> call is preceded by a call to <b>clearHitCode()</b>, and followed by code which checks the hit code, maintaining "hitAny" and "hitAll" flags. When all the segments are drawn, the <b>gw-\>setHitCode()</b> call is made, setting the hit code depending on the hit region type. When the code which called this function checks the GraphicsWindow's hit code, it will contain the proper value. This code also keeps track of the closest hit distance and places that into the GraphicsWindow when all line segments are drawn. \par Parameters: <b>BOOL h</b>\n\n Set to TRUE if the hit code is set, otherwise FALSE. */ virtual void setHitCode(BOOL h) = 0; /*! \remarks If <b>checkHitCode()</b> returns TRUE you may call this method to return the hit distance. In wireframe mode this is the distance to the line. In shaded mode, this is the z distance. This allows you to perform 'smart' hit testing by choosing the item with the smallest hit distance. This method only returns meaningful values when the hit region is a point. */ virtual DWORD getHitDistance(void) = 0; /*! \remarks This method allows drawing code to manually set the hit distance, which is returned by the <b>getHitDistance()</b> method. For more information see the topic on <a href="ms-its:3dsmaxsdk.chm::/vports_hit_testing.html">Hit Testing</a>. \par Parameters: <b>DWORD d</b>\n\n In wireframe mode this is the distance to the line. In shaded mode, this is the z distance. */ virtual void setHitDistance(DWORD d) = 0; /*! \remarks Returns TRUE if the view is in perspective projection; otherwise FALSE (orthographic projection). */ virtual int isPerspectiveView(void) = 0; /*! \remarks This method is used internally. */ virtual float interpWorld(Point3 *world1, Point3 *world2, float sParam, Point3 *interpPt) = 0; //watje virtual void MarkerBufferSetMarkerType( MarkerType type) {}; virtual DWORD MarkerGetDXColor(Point3 p) {return 0;}; virtual VertexBuffer* MarkerBufferLock() { return NULL;}; virtual void MarkerBufferUnLock() {}; virtual int MarkerBufferSize( ) {return 0;}; virtual int MarkerBufferStride( ){ return 0;}; virtual void MarkerBufferDraw(int numberOfMarkers) {}; //watje virtual DWORD LineGetDXColor(Point3 p) {return 0;}; virtual LineBuffer* LineBufferLock() { return NULL;}; virtual void LineBufferUnLock() {}; virtual int LineBufferSize( ) {return 0;}; virtual int LineBufferStride( ){ return 0;}; virtual void LineBufferDraw(int numberOfSegments) {}; virtual void escape(GFX_ESCAPE_FN fn, void *data) = 0; /*! \remarks This method calculates the depth value of the screen pixel located at positon x,y. This method returns TRUE if the depth value is calculated, FALSE otherwise. It is currently supported in Direct3D and OpenGL driver. Thus returning FALSE for unsupported driver. This method is used to locate center pivot in SteeringWheel. \param[in] x The x coordinate in screen space. \n \param[in] y The y coordinate in screen space. \n \param[out] z A pointer to the buffer that receives the calculated depth value. \return TRUE if calculated correctly, FALSE if the method failed or not supported. */ virtual BOOL getDepthValue(float x, float y, float* z) { return FALSE; } /*! \remarks This method will clear the depth buffer bits of this GraphicsWindow. It is currently supported in Direct3D and OpenGL driver. This method is used clear the depth before actually drawing the ViewCube, which cannot be messed up with the scene geometry. */ virtual void clearViewportDepth() {}; /*! \remarks This take a GFX_MESH::HWTupleMesh and creates a hardware specific mesh buffers \param[in]GFX_MESH::HWTupleMesh *hwMesh the mesh used to create the Hardware specific buffers. \n \return the hardware specific IHWDrawMesh. */ virtual GFX_MESH::IHWSubMesh *CreateHWDrawMesh(GFX_MESH::HWTupleMesh *hwMesh) {return NULL;}; /*! \remarks This draws the hwMesh to the display. If the hardware mesh holds a valid IHWDrawMesh it will use that to draw the mesh in retained mode. Otherwise the buffers in the hwmesh will be used to draw the mesh in immediate mode which is much slower. \param[in]GFX_MESH::HWTupleMesh *hwMesh the mesh to be drawn. \n */ virtual void DrawHWDrawMesh(GFX_MESH::HWTupleMesh *hwMesh) {}; }; // for Windows int coords with origin at upper-left inline int wIsFacingBack(const IPoint3 &v0, const IPoint3 &v1, const IPoint3 &v2, int flip=0 ) { int s = ( (v0[0]-v1[0])*(v2[1]-v1[1]) - (v2[0]-v1[0])*(v0[1]-v1[1]) ) < 0; return flip ? !s : s; } // for HEIDI int coords with origin at lower-left inline int hIsFacingBack(const IPoint3 &v0, const IPoint3 &v1, const IPoint3 &v2, int flip=0 ) { int s = ( (v0[0]-v1[0])*(v2[1]-v1[1]) - (v2[0]-v1[0])*(v0[1]-v1[1]) ); return flip ? s < 0 : s > 0; } // CAL-03/05/03: include side facing in the facing type enum FacingType {kFrontFacing, kSideFacing, kBackFacing}; //! \brief Returns the facing of a given triangle relative to the screen. /*! \remarks Returns whether a given triangle is front-facing, side-facing, or back-facing relative to the screen. The triangle is passed as three points in screen space. This function is used for "w" format device coordinates. \param v0 The 1st triangle vertex \param v1 The 2nd triangle vertex \param v2 The 3rd triangle vertex \param flip If true, flip the triangle (so backfacing would return frontfacing) */ inline FacingType wFacingType(const IPoint3 &v0, const IPoint3 &v1, const IPoint3 &v2, int flip=0 ) { int s = ( (v0[0]-v1[0])*(v2[1]-v1[1]) - (v2[0]-v1[0])*(v0[1]-v1[1]) ); return (s == 0) ? kSideFacing : ((flip ? s > 0 : s < 0) ? kBackFacing : kFrontFacing); } //! \brief Returns the facing of a given triangle relative to the screen. /*! \remarks The methods wFacingType() and hFacingType() will return whether a given triangle is front-facing, side-facing, or back-facing relative to the screen. The triangle is passed as three points in screen space. This function is used for "h" format device coordinates. \param v0 The 1st triangle vertex \param v1 The 2nd triangle vertex \param v2 The 3rd triangle vertex \param flip If true, flip the triangle (so backfacing would return frontfacing) */ inline FacingType hFacingType(const IPoint3 &v0, const IPoint3 &v1, const IPoint3 &v2, int flip=0 ) { int s = ( (v0[0]-v1[0])*(v2[1]-v1[1]) - (v2[0]-v1[0])*(v0[1]-v1[1]) ); return (s == 0) ? kSideFacing : ((flip ? s < 0 : s > 0) ? kBackFacing : kFrontFacing); } /*! \remarks This function is available in release 2.0 and later only.\n\n This function is not supported for use in the SDK. */ DllExport HINSTANCE GetGraphicsLibHandle(MCHAR *driverLibName); /*! \remarks This function is available in release 2.0 and later only.\n\n This function is not supported for use in the SDK. */ DllExport BOOL GraphicsSystemIsAvailable(HINSTANCE drv); /*! \remarks This function is available in release 2.0 and later only.\n\n This function is not supported for use in the SDK. */ DllExport BOOL GraphicsSystemCanConfigure(HINSTANCE drv); /*! \remarks This function is available in release 2.0 and later only.\n\n This function is not supported for use in the SDK. */ DllExport BOOL GraphicsSystemConfigure(HWND hWnd, HINSTANCE drv); /*! \remarks This function is available in release 2.0 and later only.\n\n This function is not supported for use in the SDK. */ DllExport void FreeGraphicsLibHandle(HINSTANCE drv); /*! \remarks This function is used internally to create a new graphics window. Use of this method is not supported for plug-ins. */ DllExport GraphicsWindow *createGW(HWND hWnd, GWinSetup &gws); /*! \remarks Returns a bounding rectangle that encloses the entire hit region. For example if the hit regions was a fence region, this method would return the smallest rectangle that included the entire set of fence region points. \par Parameters: <b>HitRegion *hr</b>\n\n The hit region to check.\n\n <b>RECT *rect</b>\n\n The returned bounding rectangle. */ DllExport void getRegionRect(HitRegion *hr, RECT *rect); /*! \remarks Returns TRUE if the specified point is inside the region <b>hr</b>; otherwise FALSE. */ DllExport BOOL pointInRegion(int x, int y, HitRegion *hr); /*! \remarks Returns the signed distance from <b>x,y</b> to the line defined by <b>p1-\>p2</b>. */ DllExport int distToLine(int x, int y, int *p1, int *p2); DllExport int zDepthToLine(int x, int y, int *p1, int *p2); /*! \remarks Returns nonzero if the line defined by <b>p1-\>p2</b> crosses into the RECT and 0 otherwise. */ DllExport int lineCrossesRect(RECT *rc, int *p1, int *p2); DllExport int segCrossesRect(RECT *rc, int *p1, int *p2); /*! \remarks Returns nonzero if the line defined by <b>p1-\>p2</b> crosses the circle center at (<b>cx, cy</b>) with a radius of <b>r</b> 0 otherwise. */ DllExport int segCrossesCircle(int cx, int cy, int r, int *p1, int *p2); /*! \remarks Returns TRUE if the point passed is inside the specified triangle. \par Parameters: <b>IPoint3 \&p0</b>\n\n The first point of the triangle.\n\n <b>IPoint3 \&p1</b>\n\n The second point of the triangle.\n\n <b>IPoint3 \&p2</b>\n\n The third point of the triangle.\n\n <b>IPoint3 \&q</b>\n\n The point to check. \return Returns TRUE if the point passed is inside the specified triangle; otherwise FALSE. */ DllExport BOOL insideTriangle(IPoint3 &p0, IPoint3 &p1, IPoint3 &p2, IPoint3 &q); /*! \remarks Returns the z value of where the projected screen point <b>q</b> would intersect the triangle defined by (<b>p0, p1, p2</b>). \par Parameters: <b>IPoint3 \&p0</b>\n\n The first point of the triangle.\n\n <b>IPoint3 \&p1</b>\n\n The second point of the triangle.\n\n <b>IPoint3 \&p2</b>\n\n The third point of the triangle.\n\n <b>IPoint3 \&q</b>\n\n The screen point to check. */ DllExport int getZfromTriangle(IPoint3 &p0, IPoint3 &p1, IPoint3 &p2, IPoint3 &q); DllExport int getClosestPowerOf2(int num); /*! \defgroup viewportDrawingColors Viewport Drawing Color Indices \todo Document Viewport Drawing Colors defines */ //@{ #define COLOR_SELECTION 0 //!< #define COLOR_SUBSELECTION 1 //!< #define COLOR_FREEZE 2 //!< #define COLOR_GRID 3 //!< #define COLOR_GRID_INTENS 4 //!< #define COLOR_SF_LIVE 5 //!< #define COLOR_SF_ACTION 6 //!< #define COLOR_SF_TITLE 7 //!< #define COLOR_VP_LABELS 8 //!< #define COLOR_VP_INACTIVE 9 //!< #define COLOR_ARCBALL 10 //!< #define COLOR_ARCBALL_HILITE 11 //!< #define COLOR_ANIM_BUTTON 12 //!< #define COLOR_SEL_BOXES 13 //!< #define COLOR_LINK_LINES 14 //!< #define COLOR_TRAJECTORY 15 //!< #define COLOR_ACTIVE_AXIS 16 //!< #define COLOR_INACTIVE_AXIS 17 //!< #define COLOR_SPACE_WARPS 18 //!< #define COLOR_DUMMY_OBJ 19 //!< #define COLOR_POINT_OBJ 20 //!< #define COLOR_POINT_AXES 21 //!< #define COLOR_TAPE_OBJ 22 //!< #define COLOR_BONES 23 //!< #define COLOR_GIZMOS 24 //!< #define COLOR_SEL_GIZMOS 25 //!< #define COLOR_SPLINE_VECS 26 //!< #define COLOR_SPLINE_HANDLES 27 //!< #define COLOR_PATCH_LATTICE 28 //!< No longer used #define COLOR_PARTICLE_EM 29 //!< #define COLOR_CAMERA_OBJ 30 //!< #define COLOR_CAMERA_CONE 31 //!< #define COLOR_CAMERA_HORIZ 32 //!< #define COLOR_NEAR_RANGE 33 //!< #define COLOR_FAR_RANGE 34 //!< #define COLOR_LIGHT_OBJ 35 //!< #define COLOR_TARGET_LINE 36 //!< #define COLOR_HOTSPOT 37 //!< #define COLOR_FALLOFF 38 //!< #define COLOR_START_RANGE 39 //!< #define COLOR_END_RANGE 40 //!< #define COLOR_VIEWPORT_BKG 41 //!< #define COLOR_TRAJ_TICS_1 42 //!< #define COLOR_TRAJ_TICS_2 43 //!< #define COLOR_TRAJ_TICS_3 44 //!< #define COLOR_GHOST_BEFORE 45 //!< #define COLOR_GHOST_AFTER 46 //!< #define COLOR_12FIELD_GRID 47 //!< #define COLOR_START_RANGE1 48 //!< #define COLOR_END_RANGE1 49 //!< #define COLOR_CAMERA_CLIP 50 //!< #define COLOR_NURBS_CV 51 //!< #define COLOR_NURBS_LATTICE 52 //!< #define COLOR_NURBS_CP 53 //!< #define COLOR_NURBS_FP 54 //!< #define COLOR_NURBS_DEP 55 //!< #define COLOR_NURBS_ERROR 56 //!< #define COLOR_NURBS_HILITE 57 //!< #define COLOR_NURBS_FUSE 58 //!< #define COLOR_END_EFFECTOR 59 //!< #define COLOR_END_EFFECTOR_STRING 60 //!< #define COLOR_JOINT_LIMIT_SEL 61 //!< #define COLOR_JOINT_LIMIT_UNSEL 62 //!< #define COLOR_IK_TERMINATOR 63 //!< #define COLOR_SF_USER 64 //!< #define COLOR_VERT_TICKS 65 //!< #define COLOR_XRAY 66 //!< #define COLOR_GROUP_OBJ 67 //!< #define COLOR_MANIPULATOR_X 68 //!< #define COLOR_MANIPULATOR_Y 69 //!< #define COLOR_MANIPULATOR_Z 70 //!< #define COLOR_MANIPULATOR_ACTIVE 71 //!< #define COLOR_VPT_CLIPPING 72 //!< #define COLOR_DECAY_RADIUS 73 //!< #define COLOR_VERT_NUMBERS 74 //!< #define COLOR_CROSSHAIR_CURSOR 75 //!< #define COLOR_SV_WINBK 76 //!< SV Window Background #define COLOR_SV_NODEBK 77 //!< SV Default Node Background #define COLOR_SV_SELNODEBK 78 //!< SV Selected Node Background #define COLOR_SV_NODE_HIGHLIGHT 79 //!< SV Viewport Selected Node Highlight #define COLOR_SV_MATERIAL_HIGHLIGHT 80 //!< SV MEDIT Selected Node Highlight #define COLOR_SV_MODIFIER_HIGHLIGHT 81 //!< SV Selected Modifier Highlight #define COLOR_SV_PLUGIN_HIGHLIGHT 82 //!< SV Plug-in Highlight #define COLOR_SV_SUBANIM_LINE 83 //!< SV Subanim line color #define COLOR_SV_CHILD_LINE 84 //!< SV Child node line color #define COLOR_SV_FRAME 85 //!< SV Frame color #define COLOR_SV_SELTEXT 86 //!< SV Selected Label Color #define COLOR_SV_TEXT 87 //!< SV Label Color #define COLOR_UNSEL_TAB 88 #define COLOR_ATMOS_APPARATUS 89 //!< #define COLOR_SUBSELECTION_HARD 90 //!< #define COLOR_SUBSELECTION_MEDIUM 91 //!< #define COLOR_SUBSELECTION_SOFT 92 //!< #define COLOR_SV_UNFOLD_BUTTON 93 //!< SV Unfold Button #define COLOR_SV_GEOMOBJECT_BK 94 //!< Geometry Object Node Background #define COLOR_SV_LIGHT_BK 95 //!< Light Node Background #define COLOR_SV_CAMERA_BK 96 //!< Camera Node Background #define COLOR_SV_SHAPE_BK 97 //!< Shape Node Background #define COLOR_SV_HELPER_BK 98 //!< Helper Node Background #define COLOR_SV_SYSTEM_BK 99 //!< System Node Background #define COLOR_SV_CONTROLLER_BK 100 //!< Controller Node Background #define COLOR_SV_MODIFIER_BK 101 //!< Modifier Node Background #define COLOR_SV_MATERIAL_BK 102 //!< Material Node Background #define COLOR_SV_MAP_BK 103 //!< Map Node Background #define COLOR_SETKEY_BUTTON 104 #define COLOR_BACK_LINES 105 //!< Backface lines on selected objects #define COLOR_BACK_VERTS 106 //!< Backface vertices on selected objects #define COLOR_MANIPULATOR_CONTOUR 107 //!< Background color for the rotation gizmo #define COLOR_MANIPULATOR_SCREEN 108 //!< screen space manipulator handle color for the rotation gizmo #define COLOR_MANIPULATOR_TRAIL 109 //!< move gizmo displacement trail color //@} const int kColorNormalsUnspecified = 110; const int kColorNormalsSpecified = 111; const int kColorNormalsExplicit = 112; /*! \addtogroup viewportDrawingColors */ //@{ #define COLOR_SV_GRID 113 //!< SV Grid #define COLOR_SV_REL_INSTANCE 114 //!< SV Relationship Instances #define COLOR_SV_REL_CONSTRAINT 115 //!< SV Relationship Contraints #define COLOR_SV_REL_PARAMWIRE 116 //!< SV Relationship Param Wires #define COLOR_SV_REL_LIGHT 117 //!< SV Relationship Lights #define COLOR_SV_REL_MODIFIER 118 //!< SV Relationship Modifiers #define COLOR_SV_REL_CONTROLLER 119 //!< SV Relationship Controllers #define COLOR_SV_REL_OTHER 120 //!< SV Relationship Others #define COLOR_SV_SPACEWARP_BK 121 //!< SV SpaceWarp #define COLOR_SV_BASEOBJECT_BK 122 //!< SV BaseObject #define COLOR_VP_STATISTICS 123 //!< Colour for viewport statistics display #define COLOR_SPLINE_KNOT_UNSELECTED 124 //!< color of bezier knots unselected #define COLOR_SPLINE_KNOT_FIRST 125 //!< color of first knot of the bezier spline #define COLOR_HIDDENLINE_UNSELECTED 126 //!< color of first knot of the bezier spline #define COLOR_VP_LABEL_HIGHLIGHT 127 //!< Color of selected/mouse over viewport labels #define COLOR_TOTAL 128 //!< always the max number of colors //@} // Returns/sets color values for drawing in the viewport (selection, subsel, etc) DllExport Point3 GetUIColor(int which); DllExport void SetUIColor(int which, Point3 *clr); DllExport Point3 GetDefaultUIColor(int which); #define GetSelColor() GetUIColor(COLOR_SELECTION) /*! \remarks Returns the color used for sub-object selection. */ #define GetSubSelColor() GetUIColor(COLOR_SUBSELECTION) #define GetFreezeColor() GetUIColor(COLOR_FREEZE) //! Internal Use only //! NH Flags used to tell Max graphics drivers that the user has returned from various system events //! Internal Use only - resolves issues with DirectX - the flags are used with GraphicsWindow::setFlags #define SYSTEM_LOCK_RETURN 0x001 #define SYSTEM_REMOTE_RETURN 0x002 #endif // _GFX_H_
LiangYue1981816/CrossEngine
Tools/MaxExporter/MaxSDKs/2010/include/gfx.h
C
apache-2.0
101,873
/** * * Web Starter Kit * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License * */ 'use strict'; // Include Gulp & Tools We'll Use var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var del = require('del'); var runSequence = require('run-sequence'); var browserSync = require('browser-sync'); var reload = browserSync.reload; // Clean Output Directory gulp.task('clean', del.bind(null, ['./index.js', './assertRank.js', './specs.js'])); gulp.task('es6', ['clean'], function () { return gulp.src(['./src/**/*.js']) // .pipe($.sourcemaps.init({loadMaps: true})) .pipe($['6to5']()).on('error', console.error.bind(console)) // .pipe($.sourcemaps.write()) .pipe(gulp.dest('.')) .pipe($.size({title: 'es6'})) }) gulp.task('browserify', ['es6'], function () { return gulp.src(['./specs.js']) .pipe($.browserify({debug: false})) .pipe(gulp.dest('.')) .pipe($.size({title: 'browserify'})) }) // Watch Files For Changes & Reload gulp.task('serve', ['browserify'], function () { browserSync({ notify: false, browser: 'skip', ghostMode: false, // Customize the BrowserSync console logging prefix logPrefix: 'WSK', port: 3010, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: ['.', 'src'] }); gulp.watch(['gulpfile.js'], process.exit) gulp.watch(['./src/**/*.{js,html}'], ['browserify', reload]); }); gulp.task('default', ['es6']) // Load custom tasks from the `tasks` directory // try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
markuz-brasil/runtime-type-system
gulpfile.js
JavaScript
apache-2.0
2,272
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-65704319-1', 'auto'); ga('send', 'pageview');
sofiamoral/sofiamoral.github.io
js/custom.js
JavaScript
apache-2.0
391
/** * Copyright 2017 Shusheng Shao <[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. */ #include <mpl/mlog.h> #include <mpl/msysinfo.h> #include <mpl/mdatetime.h> #include <mpl/mapplication.h> #include <mpl/mprocess.h> #include <mpl/mstring.h> #include <mpl/merror.h> #include <mpl/mfile.h> #ifdef _MSC_VER # pragma warning (push) # pragma warning (disable: 4996) #endif MPL_BEGIN_NAMESPACE MLog *MLog::_ins = NULL; MLog *MLog::instance() { if (NULL == _ins) { _ins = new MLog(); atexit(desposed); } return _ins; } void MLog::desposed() { if (NULL != _ins) { delete _ins; _ins = NULL; } } MLog::MLog() : _priority(kDebug) , _performance(kNormal) , _pattern(kSyslog) { } MLog::~MLog() { } void MLog::init(const char *logfile, int priority, int performance) { if (logfile != NULL) { _logfile = logfile; _pattern = kFile; } _priority = priority; _performance = performance; } void MLog::initdir(const char *logdir, const char *prefix, int priority, int performance) { if (logdir != NULL) { _logdir = logdir; _pattern = kDir; } if (prefix != NULL) _prefix = prefix; _priority = priority; _performance = performance; } void MLog::log(const std::string &file, const std::string &func, uint32_t line, int pri, const char *__format, ...) { MScopedLock locker(_mutex); // according to pri if (pri > _priority) return; // combine log head std::string head; int len; std::string buffer; va_list vargs; va_start(vargs, __format); len = vsnprintf(NULL, 0, __format, vargs); buffer.resize(len); va_start(vargs, __format); vsnprintf(&buffer[0], len + 1, __format, vargs); va_end(vargs); // DATETIME HOSTNAME APPLICATIONNAME[PID] FILE FUNC[LINE] #if defined(_MSC_VER) || defined(M_OS_WIN) const char *fmt = "%s %s %s[%ld] %s %s[%u]: <%s> %s\n"; #else const char *fmt = "%s %s %s[%lld] %s %s[%u]: <%s> %s\n"; #endif std::string logstr = format(fmt, now().c_str(), hostname().c_str(), applicationName().c_str(), process::pid(), file.c_str(), func.c_str(), line, strpriority(pri).c_str(), buffer.c_str()); std::cout << logstr; switch (_pattern) { case kFile: logToFile(logstr); break; case kDir: logToDir(logstr); break; default: logToSyslog(logstr); break; } } std::string MLog::strpriority(int pri) const { std::string ret = "debug"; switch (pri) { case kEmerg: ret = "emerg"; break; case kAlert: ret = "alert"; break; case kCrit: ret = "crit"; break; case kError: ret = "error"; break; case kWarn: ret = "warn"; break; case kNotice: ret = "notice"; break; case kInfo: ret = "info"; break; default: break; } return ret; } void MLog::logToFile(const std::string &logstr) { file::appendbuf(_logfile.c_str(), logstr.c_str(), logstr.size()); } void MLog::logToDir(const std::string &logstr) { std::string logfile = _logdir + DIRECTORY_SEPARATOR + _prefix + MDateTime::currentDateTime().toString("%Y%m%d") + std::string(".log"); file::appendbuf(logfile.c_str(), logstr.c_str(), logstr.size()); } void MLog::logToSyslog(const std::string &logstr) { #ifdef M_OS_LINUX syslog(LOG_DEBUG, "%s", logstr.c_str()); #else OutputDebugString(logstr.c_str()); #endif } MPL_END_NAMESPACE #ifdef _MSC_VER # pragma warning (pop) #endif
i-black-angel/libpunica
src/mlog.cpp
C++
apache-2.0
3,839
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include <time.h> #include "Basics/system-functions.h" #include "Basics/tri-strings.h" #include "Replication/common-defines.h" namespace arangodb { /// @brief generate a timestamp string in a target buffer void TRI_GetTimeStampReplication(char* dst, size_t maxLength) { struct tm tb; time_t tt = time(nullptr); TRI_gmtime(tt, &tb); strftime(dst, maxLength, "%Y-%m-%dT%H:%M:%SZ", &tb); } /// @brief generate a timestamp string in a target buffer void TRI_GetTimeStampReplication(double timeStamp, char* dst, size_t maxLength) { struct tm tb; time_t tt = static_cast<time_t>(timeStamp); TRI_gmtime(tt, &tb); strftime(dst, maxLength, "%Y-%m-%dT%H:%M:%SZ", &tb); } bool TRI_ExcludeCollectionReplication(std::string const& name, bool includeSystem, bool includeFoxxQueues) { if (name.empty()) { // should not happen... return true; } if (name[0] != '_') { // all regular collections are included return false; } if (!includeSystem) { // do not include any system collections return true; } if (TRI_IsPrefixString(name.c_str(), "_statistics") || name == "_configuration" || name == "_frontend" || name == "_cluster_kickstarter_plans" || name == "_routing" || name == "_fishbowl" || name == "_foxxlog" || name == "_sessions") { // these system collections will always be excluded return true; } else if (!includeFoxxQueues && (name == "_jobs" || name == "_queues")) { return true; } return false; } } // namespace arangodb
fceller/arangodb
arangod/Replication/common-defines.cpp
C++
apache-2.0
2,510
#!/bin/bash -e # # Copyright 2014 The Kythe 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. # # This script tests the indexpack binary. It requires the jq command (≥ 1.4). kindex_contents() { $viewindex --files "$1" | $jq -c -S . } tmp="$(mktemp -d 2>/dev/null || mktemp -d -t 'kythetest')" trap 'rm -rf "$tmp"' EXIT ERR INT $indexpack --to_archive "$tmp/archive" "$input" >/dev/null $indexpack --from_archive "$tmp/archive" "$tmp/idx" kindex_file="$(find "$tmp/idx" -name "*.kindex")" result="$(kindex_contents "$kindex_file")" expected="$(kindex_contents $input)" if [[ ! "$result" == "$expected" ]]; then echo "ERROR: expected $expected; received $result" >&2 exit 1 fi
bzz/kythe
kythe/go/platform/tools/indexpack_test.sh
Shell
apache-2.0
1,213
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>ClickCloud | Rapid deployment</title> <link rel="stylesheet" type="text/css" href="static/styles/font-awesome.css" /> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="static/styles/font-awesome-ie7.min.css"> <![endif]--> <link rel="stylesheet" type="text/css" href="static/styles/master.css" /> <link rel="stylesheet" type="text/css" href="static/styles/index.css" /><!-- Only Hadoop Install --> <script type="text/javascript" src="static/scripts/jquery.js"></script> <script type="text/javascript" src="static/scripts/click.js"></script> <script type="text/javascript"> window.addEventListener('load', function () { crumbsContent = crumbs([{ name: 'Home', url: 'index.html' }, { name: 'Hadoop', url: '' }]); var crumbs_ = document.getElementById('crumbs'); if (!!crumbs_) { crumbs_.insertAdjacentHTML('afterBegin', crumbsContent); } clickgo(document.getElementsByClassName('alert')); clicktoggle(document.getElementById('_01'), document.getElementById('_01_')); clicktoggle(document.getElementById('_02'), document.getElementById('_02_')); clickfocus(document.getElementsByClassName('_focus_')); __IFRAME__ = document.getElementById('iframe_just_me'); window.switch_ = function (flag) { switch (flag) { case 'clusters': iframe_switch('My Cluster', '>> Cluster list', [ { url: 'parts/clusters', d: {} }, ]); break; case 'host-add': iframe_switch('Add Host', '>> Register your machine to the system', [ { url: 'parts/host-add', d: {} }, ]); break; case 'hosts': iframe_switch('My Hosts', '>> Registered host', [ { url: 'parts/hosts', d: {} }, ]); break; case 'dns': iframe_switch('Domain Name System', '>> Configuration /etc/hosts', [ { url: 'parts/dns', d: {} }, ]); break; case 'hs': iframe_switch('Install Hadoop and Spark Enviroment', '>> include HDFS and YARN cluster', [ { url: 'parts/hs', d: {} }, ]); break; } } }); </script> </head> <body> <div class="row-head"> <div class="column-logo"> </div> </div> <div class="row-navigation"> <div class="column-icons"> </div> <div class="column-crumbs"> <div class="crumbs" id="crumbs"></div> </div> </div> <div class="row-main"> <div class="column-list"> <ul> <li><a class="_focus_" href="javascript:void(0);"><i class="icon-dashboard icon-large"></i>Dashboard</a></li> <li><a class="_focus_" href="javascript:switch_('dns');"><i class="icon-book icon-large"></i>DNS</a></li> <li> <a id="_01" focus="1" href="javascript:void(0);"><i class="icon-book icon-large"></i>Hadoop</a> <ul id="_01_"> <li><a class="_focus_" href="javascript:switch_('hs');">Install Hadoop and Spark</a></li> </ul> </li> <li><a class="_focus_" href="javascript:void(0);"><i class="icon-tasks icon-large"></i>Tasks</a></li> <li><a class="_focus_" href="javascript:void(0);"><i class="icon-bar-chart icon-large"></i>Monitor</a></li> <li> <a id="_02" focus="1" href="javascript:void(0);"><i class="icon-sitemap icon-large"></i>My Cluster</a> <ul id="_02_"> <li><a class="_focus_" href="javascript:switch_('clusters');">Clusters</a></li> <li><a class="_focus_" href="javascript:switch_('host-add');">Add Host</a></li> <li><a class="_focus_" href="javascript:switch_('hosts');">Hosts</a></li> </ul> </li> <li><a class="_focus_" href="javascript:void(0);"><i class="icon-lightbulb icon-large"></i>Issues</a></li> <li><a class="_focus_" href="javascript:void(0);"><i class="icon-file icon-large"></i>Other Pages</a></li> </ul> </div> <div class="column-board" id="board-main" style="display:none;"> <div class="title"> <span class="maintitle" id="board-main-title"></span> <span class="subtitle" id="board-sub-title"></span> </div> <div class="alert"> <i class="icon-ok"></i> Welcome to use <b>ClickCloud</b> Deployment Service, the rapid deployment plan </div> <div id="iframe_just_me"> <!-- append to here--> </div> </div> </div> </body> </html>
codemeow5/deployment
web2/html/index.html
HTML
apache-2.0
5,598
package event import ( "time" "github.com/go-kit/kit/log" ) type logService struct { logger log.Logger next Service } // LogServiceMiddleware given a Logger wraps the next Service with logging capabilities. func LogServiceMiddleware(logger log.Logger, store string) ServiceMiddleware { return func(next Service) Service { logger = log.With( logger, "service", "event", "store", store, ) return &logService{logger: logger, next: next} } } func (s *logService) Count(ns string, opts QueryOptions) (count int, err error) { defer func(begin time.Time) { ps := []interface{}{ "count", count, "duration_ns", time.Since(begin).Nanoseconds(), "method", "Count", "namespace", ns, "opts", opts, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Count(ns, opts) } func (s *logService) Put(ns string, input *Event) (output *Event, err error) { defer func(begin time.Time) { ps := []interface{}{ "duration_ns", time.Since(begin).Nanoseconds(), "input", input, "method", "Put", "namespace", ns, "output", output, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Put(ns, input) } func (s *logService) Query(ns string, opts QueryOptions) (list List, err error) { defer func(begin time.Time) { ps := []interface{}{ "datapoints", len(list), "duration_ns", time.Since(begin).Nanoseconds(), "method", "Query", "namespace", ns, "opts", opts, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Query(ns, opts) } func (s *logService) Setup(ns string) (err error) { defer func(begin time.Time) { ps := []interface{}{ "duration_ns", time.Since(begin).Nanoseconds(), "method", "Setup", "namespace", ns, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Setup(ns) } func (s *logService) Teardown(ns string) (err error) { defer func(begin time.Time) { ps := []interface{}{ "duration_ns", time.Since(begin).Nanoseconds(), "method", "Teardown", "namespace", ns, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Teardown(ns) } type logSource struct { logger log.Logger next Source } // LogSourceMiddleware given a Logger wraps the next Source logging capabilities. func LogSourceMiddleware(store string, logger log.Logger) SourceMiddleware { return func(next Source) Source { logger = log.With( logger, "source", "event", "store", store, ) return &logSource{ logger: logger, next: next, } } } func (s *logSource) Ack(id string) (err error) { defer func(begin time.Time) { ps := []interface{}{ "ack_id", id, "duration_ns", time.Since(begin).Nanoseconds(), "method", "Ack", } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Ack(id) } func (s *logSource) Consume() (change *StateChange, err error) { defer func(begin time.Time) { ps := []interface{}{ "duration_ns", time.Since(begin).Nanoseconds(), "method", "Consume", } if change != nil { ps = append(ps, "namespace", change.Namespace, "event_new", change.New, "event_old", change.Old, ) } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Consume() } func (s *logSource) Propagate(ns string, old, new *Event) (id string, err error) { defer func(begin time.Time) { ps := []interface{}{ "duration_ns", time.Since(begin).Nanoseconds(), "id", id, "method", "Propagate", "namespace", ns, "event_new", new, "event_old", old, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Propagate(ns, old, new) }
tapglue/snaas
service/event/logging.go
GO
apache-2.0
3,954
# Hieracium peterfii Nyár. & Zahn SPECIES #### Status ACCEPTED #### According to Euro+Med Plantbase #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium peterfii/README.md
Markdown
apache-2.0
169
<template name="home_footer"> <footer> <section class="container"> <div class="blk-card-bg blk-card text-center"> <div class="client-logos"> <ul class="thumb-list"> <li> <img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/customers/soylent.svg" alt="" width="128"> </li> <li> <img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/customers/freshdesk.png" alt="" width="156"> </li> <li> <img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/customers/proxyclick.svg" alt="" width="125"> </li> <li> <img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/customers/sharetribe.svg" alt="" width="218"> </li> <li> <img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/customers/vinylmeplease.png" alt="" width="119"> </li> </ul> </div> <h2 class="mar-t-zero">YOU’D FEEL A DEEP KINSHIP <br class="hidden-xs">WITH OUR CUSTOMERS.</h2> <p>We know why. Because they’re all doing great work. Just like you.</p> <div class="mar-t-sm mar-b-xs hidden-xs hidden-sm"> <a href="/trial-signup/" class="btn btn-sec btn-primary btn-primary-sec btn-md btn-suffix"> <img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/chargebee-icon-white.svg" alt="" style="width: 30px; margin-top: -4px; margin-right: 10px;"> SIGN UP FOR FREE </a> </div> <div class="hidden-xs hidden-sm"><a href="/pricing/" class="btn-flat">View our Plans and Pricing</a></div> <!--Start Mobile-view Demo request --> <div class="mar-t-sm mar-b-xs visible-xs visible-sm"> <a href="https://chargebee.typeform.com/to/PWNukp" data-mode="1" target="_blank" class="typeform-share btn btn-sec btn-primary btn-primary-sec btn-md btn-suffix"> <!-- <img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/chargebee-icon-white.svg" alt=""> --> Fancy a demo? </a> </div> <div class="visible-xs visible-sm"><a href="/trial-signup/" class="btn-flat">SIGN UP FOR FREE</a></div> <!--Start Mobile-view Demo request --> <div class="blk-testimonial bg-light hidden-xs"> <blockquote> <div class="media"> <div class="media-left"> <img class="media-object img-circle" src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/client-matt.jpeg" width="100" alt=""> </div> <div class="media-body"> <div class="blk-clientdescription"> Chargebee has given us greater control over our member management and product diversification as well as deep insight into our revenue cycles and member cash flow. </div> <div class="blk-clientname"> Matt Fiedler, <div>Founder, Vinyl Me, Please</div> </div> </div> </div> </blockquote> </div> </div> </section> <section class="bg-light pad-y-md hidden-xs"> <div class="container"> <article class="footer-anchor-part"> <div class="row"> <div class="col-md-10 col-md-offset-2"> <div class="row"> <div class="col-sm-4"> <div class="footer-links"> <h6 class="text-uppercase">PRODUCT</h6> <ul> <li><a href="/subscriptions">Features</a></li> <li><a href="/recurring-billing-saas.html">Recurring Billing - How It Works</a></li> <li><a href="/features/eu-vat/">EU VAT</a></li> <li><a href="/pricing/">Pricing and Plans</a></li> <li><a href="/partners.html">Partners</a></li> <li><a href="/integrations/">Integrations</a></li> <li><a href="/features/webhooks/">Webhooks</a></li> </ul> </div> <div class="footer-links"> <h6 class="text-uppercase">DEVELOPERS</h6> <ul> <li><a href="/developers/">Developer Central</a></li> <li><a href="https://apidocs.chargebee.com/docs/api/" onclick="ga('send', 'event', 'website', 'click', 'api-docs');">API Reference</a></li> <li><a href="/tutorials/">API Integration Tutorials</a></li> </ul> </div> </div> <div class="col-sm-4"> <div class="footer-links"> <h6 class="text-uppercase">SUPPORT</h6> <ul> <li><a href="/docs/">Product Documentation</a></li> <li><a href="/discussions/">Support</a></li> <li><a href="/guides/trials">Guides</a></li> <li><a href="/faq/">FAQ - Online Billing</a></li> <li><a href="/status/" target="_blank">Chargebee Service Status</a></li> </ul> </div> <div class="footer-links"> <h6 class="text-uppercase">PAYMENT GATEWAYS</h6> <ul> <li><a href="/payment-gateways/">Find a Payment Gateway</a></li> <li><a href="/do-more-with-stripe.html">Do More With Stripe</a></li> <li><a href="/payment-gateways/braintree/">Do More With Braintree</a></li> </ul> </div> </div> <div class="col-sm-4"> <div class="footer-links"> <div class="chargebee-icon mar-b-xs"><img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/chargebee-icon.svg" alt="" width="30"></div> <ul> <li><a href="/about/">About Us</a></li> <li><a href="/customers/">Customers</a></li> <li><a href="/blog/">Blog</a></li> <li><a href="/security.html">Security</a></li> <li><a href="/press/brand-guidelines/">Press</a></li> <li><a href="/careers/">Careers</a></li> <li><a href="/schedule-a-demo/">Schedule a Demo</a></li> </ul> </div> </div> </div> </div> </div> </article> </div> </section> <section class="bg-dark-primary pad-y-md"> <div class="container"> <div class="row"> <div class="col-md-8"> <article class="blk-recent-activity"> <h5>FEATURED STORY</h5> <div class="media"> <div class="media-left"> <a href="/blog/the-chargebee-redesign/"> <img class="media-object img-circle" src="/blog/images/posts/thumbs/chargebee-new-face.png" width="140" alt=""> </a> </div> <div class="media-body"> <h4 class="media-heading ff-brandon"> <a href="/blog/the-chargebee-redesign/">Spinning out the new Chargebee</a></h4> <div class="post-author"><p><em>By Kirthika S</em></p></div> <p>The decision to redesign Chargebee, how it came about, and where we're headed. <a href="/blog/the-chargebee-redesign/">Read More ></a></p> </div> </div> </article> </div> <div class="col-md-4 hidden-sm"> <article class="blk-subscription"> <div class="mar-t-md mar-b-xs"> For more stories, product announcements, events, and walkthroughs, subscribe to our newsletter </div> <div class="blk-subscribe"> <form action="//chargebee.us4.list-manage.com/subscribe/post?u=e11a967531022bc3af44ad5ea&amp;id=52a6570bc7" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate form" target="_blank" novalidate> <input type="text" name="EMAIL" class="required email form-control" id="mce-EMAIL" placeholder="Enter your mail"> <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="btn"> <span class="subscribe-placeholder">What's your email?</span> </form> </div> </article> </div> </div> </div> </section> <section class="bg-dark-primary blk-subfooter pad-y-sm"> <div class="container"> <div class="row"> <div class="col-sm-4 col-sm-push-8"> <ul class="blk-socialmedia"> <li><a href="/terms.html">Terms</a></li> <li><a href="/privacy.html">Privacy</a></li> <li><a href="#"><i class="fa fa-facebook"></i></a></li> <li><a href="#"><i class="fa fa-twitter"></i></a></li> </ul> </div> <div class="col-sm-4 hidden-xs text-center"> <div class="blk-copyright"> <a href="#"><img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/chargebee-icon-gray.svg" alt="" width="30"></a> </div> </div> <div class="col-sm-4 col-sm-pull-8"> <div class="blk-copyright"> ©2015 Chargebee Inc. All rights reserved. </div> </div> </div> </div> </section> </footer> <!-- End Footer--> </template>
Jasonudoo/mytestcase
client/templates/includes/home_footer.html
HTML
apache-2.0
11,853
/* * 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.taverna.workbench.views.graph.config; import javax.swing.JPanel; import org.apache.taverna.configuration.Configurable; import org.apache.taverna.configuration.ConfigurationUIFactory; /** * ConfigurationFactory for the GraphViewConfiguration. * * @author David Withers */ public class GraphViewConfigurationUIFactory implements ConfigurationUIFactory { private GraphViewConfiguration graphViewConfiguration; @Override public boolean canHandle(String uuid) { return uuid.equals(getConfigurable().getUUID()); } @Override public JPanel getConfigurationPanel() { return new GraphViewConfigurationPanel(graphViewConfiguration); } @Override public Configurable getConfigurable() { return graphViewConfiguration; } public void setGraphViewConfiguration( GraphViewConfiguration graphViewConfiguration) { this.graphViewConfiguration = graphViewConfiguration; } }
ThilinaManamgoda/incubator-taverna-workbench
taverna-graph-view/src/main/java/org/apache/taverna/workbench/views/graph/config/GraphViewConfigurationUIFactory.java
Java
apache-2.0
1,714
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cloudsearchv2.model.transform; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.cloudsearchv2.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * UpdateDomainEndpointOptionsResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateDomainEndpointOptionsResultStaxUnmarshaller implements Unmarshaller<UpdateDomainEndpointOptionsResult, StaxUnmarshallerContext> { public UpdateDomainEndpointOptionsResult unmarshall(StaxUnmarshallerContext context) throws Exception { UpdateDomainEndpointOptionsResult updateDomainEndpointOptionsResult = new UpdateDomainEndpointOptionsResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 2; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return updateDomainEndpointOptionsResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("DomainEndpointOptions", targetDepth)) { updateDomainEndpointOptionsResult.setDomainEndpointOptions(DomainEndpointOptionsStatusStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return updateDomainEndpointOptionsResult; } } } } private static UpdateDomainEndpointOptionsResultStaxUnmarshaller instance; public static UpdateDomainEndpointOptionsResultStaxUnmarshaller getInstance() { if (instance == null) instance = new UpdateDomainEndpointOptionsResultStaxUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-cloudsearch/src/main/java/com/amazonaws/services/cloudsearchv2/model/transform/UpdateDomainEndpointOptionsResultStaxUnmarshaller.java
Java
apache-2.0
2,682
/* * Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved. * * The Sun Project JXTA(TM) Software License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: "This product includes software * developed by Sun Microsystems, Inc. for JXTA(TM) technology." * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must * not be used to endorse or promote products derived from this software * without prior written permission. For written permission, please contact * Project JXTA at http://www.jxta.org. * * 5. Products derived from this software may not be called "JXTA", nor may * "JXTA" appear in their name, without prior written permission of Sun. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 SUN * MICROSYSTEMS OR ITS 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. * * JXTA is a registered trademark of Sun Microsystems, Inc. in the United * States and other countries. * * Please see the license information page at : * <http://www.jxta.org/project/www/license.html> for instructions on use of * the license in source files. * * ==================================================================== * * This software consists of voluntary contributions made by many individuals * on behalf of Project JXTA. For more information on Project JXTA, please see * http://www.jxta.org. * * This license is based on the BSD license adopted by the Apache Foundation. */ package net.jxta.platform; import net.jxta.document.Advertisement; import net.jxta.document.AdvertisementFactory; import net.jxta.document.MimeMediaType; import net.jxta.document.StructuredDocumentFactory; import net.jxta.document.StructuredDocumentUtils; import net.jxta.document.XMLDocument; import net.jxta.document.XMLElement; import net.jxta.endpoint.EndpointAddress; import net.jxta.id.ID; import net.jxta.id.IDFactory; import net.jxta.impl.membership.pse.PSEUtils; import net.jxta.impl.membership.pse.PSEUtils.IssuerInfo; import net.jxta.impl.peergroup.StdPeerGroup; import net.jxta.impl.protocol.HTTPAdv; import net.jxta.impl.protocol.PSEConfigAdv; import net.jxta.impl.protocol.PeerGroupConfigAdv; import net.jxta.impl.protocol.PlatformConfig; import net.jxta.impl.protocol.RdvConfigAdv; import net.jxta.impl.protocol.RdvConfigAdv.RendezVousConfiguration; import net.jxta.impl.protocol.RelayConfigAdv; import net.jxta.impl.protocol.TCPAdv; import net.jxta.logging.Logging; import net.jxta.peer.PeerID; import net.jxta.peergroup.PeerGroup; import net.jxta.peergroup.PeerGroupID; import net.jxta.protocol.ConfigParams; import net.jxta.protocol.TransportAdvertisement; import javax.security.cert.CertificateException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.Enumeration; import java.util.List; import java.util.MissingResourceException; import java.util.NoSuchElementException; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Logger; import net.jxta.impl.protocol.MulticastAdv; /** * NetworkConfigurator provides a simple programmatic interface for JXTA configuration. * <p/> * By default, it defines an edge configuration with TCP in auto mode w/port * range 9701-9799, multicast enabled on group "224.0.1.85", and port 1234, * HTTP transport with only outgoing enabled. * <p/> * By default a new PeerID is always generated. This can be overridden via * {@link NetworkConfigurator#setPeerID} method or loading a PlatformConfig via * {@link NetworkConfigurator#load}. * <p/> * A facility is provided to initialize a configuration by loading from an * existing configuration. This provides limited platform configuration lifecycle * management as well as configuration change management. * <p/> * Also by default, this class sets the default platform configurator to * {@link net.jxta.impl.peergroup.NullConfigurator}. <code>NullConfigurator<code> * is a no operation configurator intended to prevent any other configurators from * being invoked. * <p/> * NetworkConfigurator makes use of classes from the {@code net.jxta.impl.*} * packages. Applications are very strongly encouraged to avoid importing these * classes as their interfaces may change without notice in future JXTA releases. * The NetworkConfigurator API abstracts the configuration implementation details * and will provide continuity and stability i.e. the NetworkConfigurator API * won't change and it will automatically accommodate changes to service * configuration. * <p/> * <em> Configuration example :</em> * <pre> * NetworkConfigurator config = new NetworkConfigurator(); * if (!config.exists()) { * // Create a new configuration with a new name, principal, and pass * config.setName("New Name"); * config.setPrincipal("username"); * config.setPassword("password"); * try { * //persist it * config.save(); * } catch (IOException io) { * // deal with the io error * } * } else { * // Load the pre-existing configuration * File pc = new File(config.getHome(), "PlatformConfig"); * try { * config.load(pc.toURI()); * // make changes if so desired * .. * .. * // store the PlatformConfig under the default home * config.save(); * } catch (CertificateException ce) { * // In case the root cert is invalid, this creates a new one * try { * //principal * config.setPrincipal("principal"); * //password to encrypt private key with * config.setPassword("password"); * config.save(); * } catch (Exception e) { * e.printStackTrace(); * } * } * <p/> * </pre> * * @since JXTA JSE 2.4 */ public class NetworkConfigurator { /** * Logger */ private final static transient Logger LOG = Logger.getLogger(NetworkConfigurator.class.getName()); // begin configuration modes /** * Relay off Mode */ public final static int RELAY_OFF = 1 << 2; /** * Relay client Mode */ public final static int RELAY_CLIENT = 1 << 3; /** * Relay Server Mode */ public final static int RELAY_SERVER = 1 << 4; /** * Proxy Server Mode */ public final static int PROXY_SERVER = 1 << 5; /** * TCP transport client Mode */ public final static int TCP_CLIENT = 1 << 6; /** * TCP transport Server Mode */ public final static int TCP_SERVER = 1 << 7; /** * HTTP transport client Mode */ public final static int HTTP_CLIENT = 1 << 8; /** * HTTP transport server Mode */ public final static int HTTP_SERVER = 1 << 9; /** * IP multicast transport Mode */ public final static int IP_MULTICAST = 1 << 10; /** * RendezVousService Mode */ public final static int RDV_SERVER = 1 << 11; /** * RendezVousService Client */ public final static int RDV_CLIENT = 1 << 12; /** * RendezVousService Ad-Hoc mode */ public final static int RDV_AD_HOC = 1 << 13; /** * HTTP2 (netty http tunnel) client */ public final static int HTTP2_CLIENT = 1 << 14; /** * HTTP2 (netty http tunnel) server */ public final static int HTTP2_SERVER = 1 << 15; /** * Default AD-HOC configuration */ public final static int ADHOC_NODE = TCP_CLIENT | TCP_SERVER | IP_MULTICAST | RDV_AD_HOC | RELAY_OFF; /** * Default Edge configuration */ public final static int EDGE_NODE = TCP_CLIENT | TCP_SERVER | HTTP_CLIENT | HTTP2_CLIENT | IP_MULTICAST | RDV_CLIENT | RELAY_CLIENT; /** * Default Rendezvous configuration */ public final static int RDV_NODE = RDV_SERVER | TCP_CLIENT | TCP_SERVER | HTTP_SERVER | HTTP2_SERVER; /** * Default Relay configuration */ public final static int RELAY_NODE = RELAY_SERVER | TCP_CLIENT | TCP_SERVER | HTTP_SERVER | HTTP2_SERVER; // /** // * Default Proxy configuration // * // * @since 2.6 Will be removed in a future release // */ // @Deprecated // public final static int PROXY_NODE = PROXY_SERVER | RELAY_NODE; // /** // * Default Rendezvous/Relay/Proxy configuration // * // * @since 2.6 Will be removed in a future release // */ // @Deprecated // public final static int RDV_RELAY_PROXY_NODE = RDV_NODE | PROXY_NODE; // end configuration modes /** * Default mode */ protected transient int mode = EDGE_NODE; /** * Default PlatformConfig Peer Description */ protected transient String description = "Platform Config Advertisement created by : " + NetworkConfigurator.class.getName(); /** * The location which will serve as the parent for all stored items used * by JXTA. */ private transient URI storeHome = null; /** * Default peer name */ protected transient String name = "unknown"; /** * AuthenticationType used by PSEMembership to specify the type of authentication. */ protected transient String authenticationType = null; /** * Password value used to generate root Certificate and to protect the * Certificate's PrivateKey. */ protected transient String password = null; /** * Default PeerID */ protected transient PeerID peerid = null; /** * Principal value used to generate root certificate */ protected transient String principal = null; /** * Public Certificate chain */ protected transient X509Certificate[] cert = null; /** * Subject private key */ protected transient PrivateKey subjectPkey = null; /** * Freestanding keystore location */ protected transient URI keyStoreLocation = null; /** * Proxy Service Document */ @Deprecated protected transient XMLElement proxyConfig; /** * Personal Security Environment Config Advertisement * * @see net.jxta.impl.membership.pse.PSEConfig */ protected transient PSEConfigAdv pseConf; /** * Rendezvous Config Advertisement */ protected transient RdvConfigAdv rdvConfig; /** * Default Rendezvous Seeding URI */ protected URI rdvSeedingURI = null; /** * Relay Config Advertisement */ protected transient RelayConfigAdv relayConfig; /** * Default Relay Seeding URI */ protected transient URI relaySeedingURI = null; /** * TCP Config Advertisement */ protected transient TCPAdv tcpConfig; /** * Multicating Config Advertisement */ protected transient MulticastAdv multicastConfig; /** * Default TCP transport state */ protected transient boolean tcpEnabled = true; /** * Default Multicast transport state */ protected transient boolean multicastEnabled = true; /** * HTTP Config Advertisement */ protected transient HTTPAdv httpConfig; /** * Default HTTP transport state */ protected transient boolean httpEnabled = true; /** * HTTP2 Config Advertisement */ protected transient TCPAdv http2Config; /** * Default HTTP2 transport state */ protected transient boolean http2Enabled = true; /** * Infrastructure Peer Group Configuration */ protected transient PeerGroupConfigAdv infraPeerGroupConfig; /** * Creates NetworkConfigurator instance with default AD-HOC configuration * * @param storeHome the URI to persistent store * @return NetworkConfigurator instance with default AD-HOC configuration */ public static NetworkConfigurator newAdHocConfiguration(URI storeHome) { return new NetworkConfigurator(ADHOC_NODE, storeHome); } /** * Creates NetworkConfigurator instance with default Edge configuration * * @param storeHome the URI to persistent store * @return NetworkConfigurator instance with default AD-HOC configuration */ public static NetworkConfigurator newEdgeConfiguration(URI storeHome) { return new NetworkConfigurator(EDGE_NODE, storeHome); } /** * Creates NetworkConfigurator instance with default Rendezvous configuration * * @param storeHome the URI to persistent store * @return NetworkConfigurator instance with default Rendezvous configuration */ public static NetworkConfigurator newRdvConfiguration(URI storeHome) { return new NetworkConfigurator(RDV_NODE, storeHome); } /** * Creates NetworkConfigurator instance with default Relay configuration * * @param storeHome the URI to persistent store * @return NetworkConfigurator instance with default Relay configuration */ public static NetworkConfigurator newRelayConfiguration(URI storeHome) { return new NetworkConfigurator(RELAY_NODE, storeHome); } /** * Creates NetworkConfigurator instance with default Rendezvous configuration * * @param storeHome the URI to persistent store * @return NetworkConfigurator instance with default Rendezvous configuration */ public static NetworkConfigurator newRdvRelayConfiguration(URI storeHome) { return new NetworkConfigurator(RDV_NODE | RELAY_SERVER, storeHome); } // /** // * Creates NetworkConfigurator instance with default Proxy configuration // * // * @param storeHome the URI to persistent store // * @return NetworkConfigurator instance with defaultProxy configuration // * // * @since 2.6 Will be removed in a future release // */ // @Deprecated // public static NetworkConfigurator newProxyConfiguration(URI storeHome) { // return new NetworkConfigurator(PROXY_NODE, storeHome); // } // /** // * Creates NetworkConfigurator instance with default Rendezvous, Relay, Proxy configuration // * // * @param storeHome the URI to persistent store // * @return NetworkConfigurator instance with default Rendezvous, Relay, Proxy configuration // * // * @since 2.6 It will be removed in a future release // */ // @Deprecated // public static NetworkConfigurator newRdvRelayProxyConfiguration(URI storeHome) { // return new NetworkConfigurator(RDV_RELAY_PROXY_NODE, storeHome); // } /** * Creates the default NetworkConfigurator. The configuration is stored with a default configuration mode of EDGE_NODE */ public NetworkConfigurator() { this(EDGE_NODE, new File(".jxta").toURI()); } /** * Creates a NetworkConfigurator with the default configuration of the * specified mode. <p/>Valid modes include ADHOC_NODE, EDGE_NODE, RDV_NODE * PROXY_NODE, RELAY_NODE, RDV_RELAY_PROXY_NODE, or any combination of * specific configuration.<p/> e.g. RDV_NODE | HTTP_CLIENT * * @param mode the new configuration mode * @param storeHome the URI to persistent store * @see #setMode */ public NetworkConfigurator(int mode, URI storeHome) { Logging.logCheckedFine(LOG, "Creating a default configuration"); setStoreHome(storeHome); httpConfig = createHttpAdv(); rdvConfig = createRdvConfigAdv(); relayConfig = createRelayConfigAdv(); // proxyConfig = createProxyAdv(); tcpConfig = createTcpAdv(); multicastConfig = createMulticastAdv(); http2Config = createHttp2Adv(); infraPeerGroupConfig = createInfraConfigAdv(); setMode(mode); } /** * Sets PlaformConfig Peer Description element * * @param description the peer description */ public void setDescription(String description) { this.description = description; } /** * Set the current directory for configuration and cache persistent store * <p/>(default is $CWD/.jxta) * <p/> * <dt>Simple example :</dt> * <pre> * <code> * //Create an application home * File appHome = new File(System.getProperty("JXTA_HOME", ".cache")); * //Create an instance home under the application home * File instanceHome = new File(appHome, instanceName); * jxtaConfig.setHome(instanceHome); * </code> * </pre> * * @param home the new home value * @see #getHome */ public void setHome(File home) { this.storeHome = home.toURI(); } /** * Returns the current directory for configuration and cache persistent * store. This is the same location as returned by {@link #getStoreHome()} * which is more general than this method. * * @return Returns the current home directory * @see #setHome */ public File getHome() { if ("file".equalsIgnoreCase(storeHome.getScheme())) { return new File(storeHome); } else { throw new UnsupportedOperationException("Home location is not a file:// URI : " + storeHome); } } /** * Returns the location which will serve as the parent for all stored items * used by JXTA. * * @return The location which will serve as the parent for all stored * items used by JXTA. * @see net.jxta.peergroup.PeerGroup#getStoreHome() */ public URI getStoreHome() { return storeHome; } /** * Sets the location which will serve as the parent for all stored items * used by JXTA. * * @param newHome new home directory URI * @see net.jxta.peergroup.PeerGroup#getStoreHome() */ public void setStoreHome(URI newHome) { // Fail if the URI is not absolute. if (!newHome.isAbsolute()) { throw new IllegalArgumentException("Only absolute URIs accepted for store home location."); } // Fail if the URI is Opaque. if (newHome.isOpaque()) { throw new IllegalArgumentException("Only hierarchical URIs accepted for store home location."); } // FIXME this should be removed when 1488 is committed if (!"file".equalsIgnoreCase(newHome.getScheme())) { throw new IllegalArgumentException("Only file based URI currently supported"); } // Adds a terminating / if (!newHome.toString().endsWith("/")) { newHome = URI.create(newHome.toString() + "/"); } storeHome = newHome; } /** * Toggles HTTP transport state * * @param enabled if true, enables HTTP transport */ public void setHttpEnabled(boolean enabled) { this.httpEnabled = enabled; if (!httpEnabled) { httpConfig.setClientEnabled(false); httpConfig.setServerEnabled(false); } } /** * Toggles the HTTP transport server (incoming) mode * * @param incoming toggles HTTP transport server mode */ public void setHttpIncoming(boolean incoming) { httpConfig.setServerEnabled(incoming); } /** * Toggles the HTTP transport client (outgoing) mode * * @param outgoing toggles HTTP transport client mode */ public void setHttpOutgoing(boolean outgoing) { httpConfig.setClientEnabled(outgoing); } /** * Sets the HTTP listening port (default 9901) * * @param port the new HTTP port value */ public void setHttpPort(int port) { httpConfig.setPort(port); } /** * Sets the HTTP interface Address to bind the HTTP transport to * <p/>e.g. "192.168.1.1" * * @param address the new address value */ public void setHttpInterfaceAddress(String address) { httpConfig.setInterfaceAddress(address); } /** * Returns the HTTP interface Address * * @param address the HTTP interface address */ public String getHttpInterfaceAddress() { return httpConfig.getInterfaceAddress(); } /** * Sets the HTTP JXTA Public Address * e.g. "192.168.1.1:9700" * * @param address the HTTP transport public address * @param exclusive determines whether an address is advertised exclusively */ public void setHttpPublicAddress(String address, boolean exclusive) { httpConfig.setServer(address); httpConfig.setPublicAddressOnly(exclusive); } public boolean isHttp2Enabled() { return http2Enabled; } public void setHttp2Enabled(boolean enabled) { http2Enabled = enabled; if(http2Enabled) { http2Config.setClientEnabled(false); http2Config.setServerEnabled(false); } } public boolean getHttp2IncomingStatus() { return http2Config.getServerEnabled(); } public void setHttp2Incoming(boolean enabled) { http2Config.setServerEnabled(enabled); } public boolean getHttp2OutgoingStatus() { return http2Config.getClientEnabled(); } public void setHttp2Outgoing(boolean enabled) { http2Config.setClientEnabled(enabled); } public int getHttp2Port() { return http2Config.getPort(); } public void setHttp2Port(int port) { http2Config.setPort(port); } public int getHttp2StartPort() { return http2Config.getStartPort(); } public void setHttp2StartPort(int startPort) { http2Config.setStartPort(startPort); } public int getHttp2EndPort() { return http2Config.getEndPort(); } public void setHttp2EndPort(int endPort) { http2Config.setEndPort(endPort); } public String getHttp2InterfaceAddress() { return http2Config.getInterfaceAddress(); } public void setHttp2InterfaceAddress(String address) { http2Config.setInterfaceAddress(address); } public String getHttp2PublicAddress() { return http2Config.getServer(); } public boolean isHttp2PublicAddressExclusive() { return http2Config.getPublicAddressOnly(); } public void setHttp2PublicAddress(String address, boolean exclusive) { http2Config.setServer(address); http2Config.setPublicAddressOnly(exclusive); } /** * Returns the HTTP JXTA Public Address * * @return exclusive determines whether an address is advertised exclusively */ public String getHttpPublicAddress() { return httpConfig.getServer(); } /** * Returns the HTTP JXTA Public Address exclusivity * * @return exclusive determines whether an address is advertised exclusively */ public boolean isHttpPublicAddressExclusive() { return httpConfig.getPublicAddressOnly(); } /** * Sets the ID which will be used for new net peer group instances. * <p/> * <p/>By Setting an alternate infrastructure PeerGroup ID (aka NetPeerGroup), * it prevents heterogeneous infrastructure PeerGroups from intersecting. * <p/>This is highly recommended practice for application deployment * * @param id the new infrastructure PeerGroupID as a string * @see net.jxta.peergroup.PeerGroupFactory#setNetPGID */ public void setInfrastructureID(ID id) { if (id == null || id.equals(ID.nullID)) { throw new IllegalArgumentException("PeerGroupID can not be null"); } infraPeerGroupConfig.setPeerGroupID(id); } /** * Sets the ID which will be used for new net peer group instances. * <p/> * <p/>By Setting an alternate infrastructure PeerGroup ID (aka NetPeerGroup), * it prevents heterogeneous infrastructure PeerGroups from intersecting. * <p/>This is highly recommended practice for application deployment * * @param idStr the new infrastructure PeerGroupID as a string * @see net.jxta.peergroup.PeerGroupFactory#setNetPGID */ public void setInfrastructureID(String idStr) { if (idStr == null || idStr.length() == 0) { throw new IllegalArgumentException("PeerGroupID string can not be empty or null"); } PeerGroupID pgid = (PeerGroupID) ID.create(URI.create(idStr)); setInfrastructureID(pgid); } /** * Gets the ID which will be used for new net peer group instances. * <p/> * * @return the infrastructure PeerGroupID as a string */ public String getInfrastructureIDStr() { return infraPeerGroupConfig.getPeerGroupID().toString(); } /** * Sets the infrastructure PeerGroup name meta-data * * @param name the Infrastructure PeerGroup name * @see net.jxta.peergroup.PeerGroupFactory#setNetPGName */ public void setInfrastructureName(String name) { infraPeerGroupConfig.setName(name); } /** * Gets the infrastructure PeerGroup name meta-data * * @return the Infrastructure PeerGroup name */ public String getInfrastructureName() { return infraPeerGroupConfig.getName(); } /** * Sets the infrastructure PeerGroup description meta-data * * @param description the infrastructure PeerGroup description * @see net.jxta.peergroup.PeerGroupFactory#setNetPGDesc */ public void setInfrastructureDescriptionStr(String description) { infraPeerGroupConfig.setDescription(description); } /** * Returns the infrastructure PeerGroup description meta-data * * @return the infrastructure PeerGroup description meta-data */ public String getInfrastructureDescriptionStr() { return infraPeerGroupConfig.getDescription(); } /** * Sets the infrastructure PeerGroup description meta-data * * @param description the infrastructure PeerGroup description * @see net.jxta.peergroup.PeerGroupFactory#setNetPGDesc */ public void setInfrastructureDesc(XMLElement description) { infraPeerGroupConfig.setDesc(description); } /** * Sets the current node configuration mode. * <p/>The default mode is EDGE, unless modified at construction time. * A node configuration mode defined a preset configuration * parameters based on a operating mode. i.e. an EDGE mode, enable * client/server side tcp, multicast, client side http, RelayService * client mode. * <p/> Valid modes include EDGE, RDV_SERVER, * RELAY_OFF, RELAY_CLIENT, RELAY_SERVER, PROXY_SERVER, or any combination * of which.<p/> e.g. RDV_SERVER + RELAY_SERVER * * @param mode the new configuration mode * @see #getMode */ public void setMode(int mode) { this.mode = mode; if ((mode & PROXY_SERVER) == PROXY_SERVER && ((mode & RELAY_SERVER) != RELAY_SERVER)) { mode = mode | RELAY_SERVER; } // RELAY config relayConfig.setClientEnabled((mode & RELAY_CLIENT) == RELAY_CLIENT); relayConfig.setServerEnabled((mode & RELAY_SERVER) == RELAY_SERVER); // RDV_SERVER if ((mode & RDV_SERVER) == RDV_SERVER) { rdvConfig.setConfiguration(RendezVousConfiguration.RENDEZVOUS); } else if ((mode & RDV_CLIENT) == RDV_CLIENT) { rdvConfig.setConfiguration(RendezVousConfiguration.EDGE); } else if ((mode & RDV_AD_HOC) == RDV_AD_HOC) { rdvConfig.setConfiguration(RendezVousConfiguration.AD_HOC); } // TCP tcpConfig.setClientEnabled((mode & TCP_CLIENT) == TCP_CLIENT); tcpConfig.setServerEnabled((mode & TCP_SERVER) == TCP_SERVER); // HTTP httpConfig.setClientEnabled((mode & HTTP_CLIENT) == HTTP_CLIENT); httpConfig.setServerEnabled((mode & HTTP_SERVER) == HTTP_SERVER); // HTTP2 http2Config.setClientEnabled((mode & HTTP2_CLIENT) == HTTP2_CLIENT); http2Config.setServerEnabled((mode & HTTP2_SERVER) == HTTP2_SERVER); // Multicast multicastConfig.setMulticastState((mode & IP_MULTICAST) == IP_MULTICAST); // EDGE if (mode == EDGE_NODE) { rdvConfig.setConfiguration(RendezVousConfiguration.EDGE); } } /** * Returns the current configuration mode * <p/>The default mode is EDGE, unless modified at construction time or through * Method {@link NetworkConfigurator#setMode}. A node configuration mode defined a preset configuration * parameters based on a operating mode. i.e. an EDGE mode, enable * client/server side tcp, multicast, client side http, RelayService * client mode. * * @return mode the current mode value * @see #setMode */ public int getMode() { return mode; } /** * Sets the IP group multicast packet size * * @param size the new multicast packet */ public void setMulticastSize(int size) { multicastConfig.setMulticastSize(size); } /** * Gets the IP group multicast packet size * * @return the multicast packet */ public int getMulticastSize() { return multicastConfig.getMulticastSize(); } /** * Sets the IP group multicast address (default 224.0.1.85) * * @param mcastAddress the new multicast group address * @see #setMulticastPort */ public void setMulticastAddress(String mcastAddress) { multicastConfig.setMulticastAddr(mcastAddress); } /** * Gets the multicast network interface * * @return the multicast network interface, null if none specified */ public String getMulticastInterface() { return multicastConfig.getMulticastInterface(); } /** * Sets the multicast network interface * * @param interfaceAddress multicast network interface */ public void setMulticastInterface(String interfaceAddress) { multicastConfig.setMulticastInterface(interfaceAddress); } /** * Sets the IP group multicast port (default 1234) * * @param port the new IP group multicast port * @see #setMulticastAddress */ public void setMulticastPort(int port) { multicastConfig.setMulticastPort(port); } /** * Sets the group multicast thread pool size (default 10) * * @param size the new multicast thread pool size */ public void setMulticastPoolSize(int size) { multicastConfig.setMulticastPoolSize(size); } /** * Sets the node name * * @param name node name */ public void setName(String name) { this.name = name; } /** * Gets the node name * * @return node name */ public String getName() { return this.name; } /** * Sets the Principal for the peer root certificate * * @param principal the new principal value * @see #setPassword * @see #getPrincipal * @see #setPrincipal */ public void setPrincipal(String principal) { this.principal = principal; } /** * Gets the Principal for the peer root certificate * * @return principal if a principal is set, null otherwise * @see #setPassword * @see #getPrincipal * @see #setPrincipal */ public String getPrincipal() { return principal; } /** * Sets the public Certificate for this configuration. * * @param cert the new cert value */ public void setCertificate(X509Certificate cert) { this.cert = new X509Certificate[]{cert}; } /** * Returns the public Certificate for this configuration. * * @return X509Certificate */ public X509Certificate getCertificate() { return (cert == null || cert.length == 0 ? null : cert[0]); } /** * Sets the public Certificate chain for this configuration. * * @param certificateChain the new Certificate chain value */ public void setCertificateChain(X509Certificate[] certificateChain) { this.cert = certificateChain; } /** * Gets the public Certificate chain for this configuration. * * @return X509Certificate chain */ public X509Certificate[] getCertificateChain() { return cert; } /** * Sets the Subject private key * * @param subjectPkey the subject private key */ public void setPrivateKey(PrivateKey subjectPkey) { this.subjectPkey = subjectPkey; } /** * Gets the Subject private key * * @return the subject private key */ public PrivateKey getPrivateKey() { return this.subjectPkey; } /** * Sets freestanding keystore location * * @param keyStoreLocation the absolute location of the freestanding keystore */ public void setKeyStoreLocation(URI keyStoreLocation) { this.keyStoreLocation = keyStoreLocation; } /** * Gets the freestanding keystore location * * @return the location of the freestanding keystore */ public URI getKeyStoreLocation() { return keyStoreLocation; } /** * Gets the authenticationType * * @return authenticationType the authenticationType value */ public String getAuthenticationType() { return this.authenticationType; } /** * Sets the authenticationType * * @param authenticationType the new authenticationType value */ public void setAuthenticationType(String authenticationType) { this.authenticationType = authenticationType; } /** * Sets the password used to sign the private key of the root certificate * * @param password the new password value * @see #setPassword * @see #getPrincipal * @see #setPrincipal */ public void setPassword(String password) { this.password = password; } /** * Gets the password used to sign the private key of the root certificate * * @return password if a password is set, null otherwise * @see #setPassword * @see #getPrincipal * @see #setPrincipal */ public String getPassword() { return password; } /** * Sets the PeerID (by default, a new PeerID is generated). * <p/>Note: Persist the PeerID generated, or use load() * to avoid overridding a node's PeerID between restarts. * * @param peerid the new <code>net.jxta.peer.PeerID</code> */ public void setPeerID(PeerID peerid) { this.peerid = peerid; } /** * Gets the PeerID * * @return peerid the <code>net.jxta.peer.PeerID</code> value */ public PeerID getPeerID() { return this.peerid; } /** * Sets Rendezvous Seeding URI * * @param seedURI Rendezvous service seeding URI */ public void addRdvSeedingURI(URI seedURI) { rdvConfig.addSeedingURI(seedURI); } // /** // * Sets Rendezvous Access Control URI // * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvousACL.cgi?3 // * // * @param aclURI Rendezvous Access Control URI // * // * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRendezvousSeedsStatus'. // * They will be deprecated and removed in a future release. // */ // @Deprecated // public void setRdvACLURI(URI aclURI) { // rdvConfig.setAclUri(aclURI); // } // /** // * Gets Rendezvous Access Control URI if set // * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvousACL.cgi?3 // * // * @return aclURI Rendezvous Access Control URI // * // * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRendezvousSeedsStatus'. // * They will be deprecated and removed in a future release. // */ // @Deprecated // public URI getRdvACLURI() { // return rdvConfig.getAclUri(); // } // /** // * Sets Relay Access Control URI // * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/relayACL.cgi?3 // * // * @param aclURI Relay Access Control URI // * // * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRelaySeedsStatus'. // * They will be deprecated and removed in a future release. // */ // @Deprecated // public void setRelayACLURI(URI aclURI) { // relayConfig.setAclUri(aclURI); // } // /** // * Gets Relay Access Control URI if set // * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/relayACL.cgi?3 // * // * @return aclURI Relay Access Control URI // * // * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRelaySeedsStatus'. // * They will be deprecated and removed in a future release. // */ // @Deprecated // public URI getRelayACLURI() { // return relayConfig.getAclUri(); // } /** * Sets the RelayService maximum number of simultaneous relay clients * * @param relayMaxClients the new relayMaxClients value */ public void setRelayMaxClients(int relayMaxClients) { if ((relayMaxClients != -1) && (relayMaxClients <= 0)) { throw new IllegalArgumentException("Relay Max Clients : " + relayMaxClients + " must be > 0"); } relayConfig.setMaxClients(relayMaxClients); } /** * Sets the RelayService Seeding URI * <p/>A seeding URI (when read) is expected to provide a list of * physical endpoint addresse(s) to relay peers * * @param seedURI RelayService seeding URI */ public void addRelaySeedingURI(URI seedURI) { relayConfig.addSeedingURI(seedURI); } /** * Sets the RendezVousService maximum number of simultaneous rendezvous clients * * @param rdvMaxClients the new rendezvousMaxClients value */ public void setRendezvousMaxClients(int rdvMaxClients) { if ((rdvMaxClients != -1) && (rdvMaxClients <= 0)) { throw new IllegalArgumentException("Rendezvous Max Clients : " + rdvMaxClients + " must be > 0"); } rdvConfig.setMaxClients(rdvMaxClients); } /** * Toggles TCP transport state * * @param enabled if true, enables TCP transport */ public void setTcpEnabled(boolean enabled) { this.tcpEnabled = enabled; if (!tcpEnabled) { tcpConfig.setClientEnabled(false); tcpConfig.setServerEnabled(false); } } /** * Sets the TCP transport listening port (default 9701) * * @param port the new tcpPort value */ public void setTcpPort(int port) { tcpConfig.setPort(port); } /** * Sets the lowest port on which the TCP Transport will listen if configured * to do so. Valid values are <code>-1</code>, <code>0</code> and * <code>1-65535</code>. The <code>-1</code> value is used to signify that * the port range feature should be disabled. The <code>0</code> specifies * that the Socket API dynamic port allocation should be used. For values * <code>1-65535</code> the value must be equal to or less than the value * used for end port. * * @param start the lowest port on which to listen. */ public void setTcpStartPort(int start) { tcpConfig.setStartPort(start); } /** * Returns the highest port on which the TCP Transport will listen if * configured to do so. Valid values are <code>-1</code>, <code>0</code> and * <code>1-65535</code>. The <code>-1</code> value is used to signify that * the port range feature should be disabled. The <code>0</code> specifies * that the Socket API dynamic port allocation should be used. For values * <code>1-65535</code> the value must be equal to or greater than the value * used for start port. * * @param end the new TCP end port */ public void setTcpEndPort(int end) { tcpConfig.setEndPort(end); } /** * Toggles TCP transport server (incoming) mode (default is on) * * @param incoming the new TCP server mode */ public void setTcpIncoming(boolean incoming) { tcpConfig.setServerEnabled(incoming); } /** * Toggles TCP transport client (outgoing) mode (default is true) * * @param outgoing the new tcpOutgoing value */ public void setTcpOutgoing(boolean outgoing) { tcpConfig.setClientEnabled(outgoing); } /** * Sets the TCP transport interface address * <p/>e.g. "192.168.1.1" * * @param address the TCP transport interface address */ public void setTcpInterfaceAddress(String address) { tcpConfig.setInterfaceAddress(address); } /** * Sets the node public address * <p/>e.g. "192.168.1.1:9701" * <p/>This address is the physical address defined in a node's * AccessPointAdvertisement. This often required for NAT'd/FW nodes * * @param address the TCP transport public address * @param exclusive public address advertised exclusively */ public void setTcpPublicAddress(String address, boolean exclusive) { tcpConfig.setServer(address); tcpConfig.setPublicAddressOnly(exclusive); } /** * Toggles whether to use IP group multicast (default is true) * * @param multicastOn the new useMulticast value */ public void setUseMulticast(boolean multicastOn) { multicastConfig.setMulticastState(multicastOn); } /** * Determines whether to restrict RelayService leases to those defined in * the seed list. In other words, only registered endpoint address seeds * and seeds fetched from seeding URIs will be used. * </p>WARNING: Disabling 'use only relay seed' will cause this peer to * search and fetch RdvAdvertisements for use as relay candidates. Rdvs * are not necessarily relays. * * @param useOnlyRelaySeeds restrict RelayService lease to seed list */ public void setUseOnlyRelaySeeds(boolean useOnlyRelaySeeds) { relayConfig.setUseOnlySeeds(useOnlyRelaySeeds); } /** * Determines whether to restrict RendezvousService leases to those defined in * the seed list. In other words, only registered endpoint address seeds * and seeds fetched from seeding URIs will be used. * * @param useOnlyRendezvouSeeds restrict RendezvousService lease to seed list */ public void setUseOnlyRendezvousSeeds(boolean useOnlyRendezvouSeeds) { rdvConfig.setUseOnlySeeds(useOnlyRendezvouSeeds); } /** * Adds RelayService peer seed address * <p/>A RelayService seed is defined as a physical endpoint address * <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701 * * @param seedURI the relay seed URI */ public void addSeedRelay(URI seedURI) { relayConfig.addSeedRelay(seedURI.toString()); } /** * Adds Rendezvous peer seed, physical endpoint address * <p/>A RendezVousService seed is defined as a physical endpoint address * <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701 * * @param seedURI the rendezvous seed URI */ public void addSeedRendezvous(URI seedURI) { rdvConfig.addSeedRendezvous(seedURI); } /** * Returns true if a PlatformConfig file exist under store home * * @return true if a PlatformConfig file exist under store home */ public boolean exists() { URI platformConfig = storeHome.resolve("PlatformConfig"); try { return null != read(platformConfig); } catch (IOException failed) { return false; } } /** * Sets the PeerID for this Configuration * * @param peerIdStr the new PeerID as a string */ public void setPeerId(String peerIdStr) { this.peerid = (PeerID) ID.create(URI.create(peerIdStr)); } /** * Sets the new RendezvousService seeding URI as a string. * <p/>A seeding URI (when read) is expected to provide a list of * physical endpoint address to rendezvous peers * * @param seedURIStr the new rendezvous seed URI as a string */ public void addRdvSeedingURI(String seedURIStr) { rdvConfig.addSeedingURI(URI.create(seedURIStr)); } /** * Sets the new RelayService seeding URI as a string. * <p/>A seeding URI (when read) is expected to provide a list of * physical endpoint address to relay peers * * @param seedURIStr the new RelayService seed URI as a string */ public void addRelaySeedingURI(String seedURIStr) { relayConfig.addSeedingURI(URI.create(seedURIStr)); } /** * Sets the List relaySeeds represented as Strings * <p/>A RelayService seed is defined as a physical endpoint address * <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701 * * @param seeds the Set RelayService seed URIs as a string */ public void setRelaySeedURIs(List<String> seeds) { relayConfig.clearSeedRelays(); for (String seedStr : seeds) { relayConfig.addSeedRelay(new EndpointAddress(seedStr)); } } /** * Sets the relaySeeds represented as Strings * <p/>A seeding URI (when read) is expected to provide a list of * physical endpoint address to relay peers * * @param seedURIs the List relaySeeds represented as Strings */ public void setRelaySeedingURIs(Set<String> seedURIs) { relayConfig.clearSeedingURIs(); for (String seedStr : seedURIs) { relayConfig.addSeedingURI(URI.create(seedStr)); } } /** * Clears the List of RelayService seeds */ public void clearRelaySeeds() { relayConfig.clearSeedRelays(); } /** * Clears the List of RelayService seeding URIs */ public void clearRelaySeedingURIs() { relayConfig.clearSeedingURIs(); } /** * Sets the List of RendezVousService seeds represented as Strings * <p/>A RendezvousService seed is defined as a physical endpoint address * <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701 * * @param seeds the Set of rendezvousSeeds represented as Strings */ public void setRendezvousSeeds(Set<String> seeds) { rdvConfig.clearSeedRendezvous(); for (String seedStr : seeds) { rdvConfig.addSeedRendezvous(URI.create(seedStr)); } } /** * Sets the List of RendezVousService seeding URIs represented as Strings. * A seeding URI (when read) is expected to provide a list of * physical endpoint address to rendezvous peers. * * @param seedingURIs the List rendezvousSeeds represented as Strings. */ public void setRendezvousSeedingURIs(List<String> seedingURIs) { rdvConfig.clearSeedingURIs(); for (String seedStr : seedingURIs) { rdvConfig.addSeedingURI(URI.create(seedStr)); } } /** * Clears the list of RendezVousService seeds */ public void clearRendezvousSeeds() { rdvConfig.clearSeedRendezvous(); } /** * Clears the list of RendezVousService seeding URIs */ public void clearRendezvousSeedingURIs() { rdvConfig.clearSeedingURIs(); } /** * Load a configuration from the specified store home uri * <p/> * e.g. file:/export/dist/EdgeConfig.xml, e.g. http://configserver.net/configservice?Edge * * @return The loaded configuration. * @throws IOException if an i/o error occurs * @throws CertificateException if the MembershipService is invalid */ public ConfigParams load() throws IOException, CertificateException { return load(storeHome.resolve("PlatformConfig")); } /** * Loads a configuration from a specified uri * <p/> * e.g. file:/export/dist/EdgeConfig.xml, e.g. http://configserver.net/configservice?Edge * * @param uri the URI to PlatformConfig * @return The loaded configuration. * @throws IOException if an i/o error occurs * @throws CertificateException if the MemebershipService is invalid */ public ConfigParams load(URI uri) throws IOException, CertificateException { if (uri == null) throw new IllegalArgumentException("URI can not be null"); Logging.logCheckedFine(LOG, "Loading configuration : ", uri); PlatformConfig platformConfig = read(uri); name = platformConfig.getName(); peerid = platformConfig.getPeerID(); description = platformConfig.getDescription(); XMLElement<?> param; // TCP tcpEnabled = platformConfig.isSvcEnabled(PeerGroup.tcpProtoClassID); tcpConfig = loadTcpAdv(platformConfig, PeerGroup.tcpProtoClassID); multicastEnabled = platformConfig.isSvcEnabled(PeerGroup.multicastProtoClassID); multicastConfig = loadMulticastAdv(platformConfig, PeerGroup.multicastProtoClassID); // HTTP try { param = (XMLElement) platformConfig.getServiceParam(PeerGroup.httpProtoClassID); httpEnabled = platformConfig.isSvcEnabled(PeerGroup.httpProtoClassID); Enumeration httpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType()); // get the TransportAdv from either TransportAdv if (httpChilds.hasMoreElements()) { param = (XMLElement) httpChilds.nextElement(); } else { throw new IllegalStateException("Missing HTTP Advertisment"); } // Read-in the adv as it is now. httpConfig = (HTTPAdv) AdvertisementFactory.newAdvertisement(param); } catch (Exception failure) { IOException ioe = new IOException("error processing the HTTP config advertisement"); ioe.initCause(failure); throw ioe; } // HTTP2 http2Enabled = platformConfig.isSvcEnabled(PeerGroup.http2ProtoClassID); http2Config = loadTcpAdv(platformConfig, PeerGroup.http2ProtoClassID); // // ProxyService // try { // param = (XMLElement) platformConfig.getServiceParam(PeerGroup.proxyClassID); // if (param != null && !platformConfig.isSvcEnabled(PeerGroup.proxyClassID)) { // mode = mode | PROXY_SERVER; // } // } catch (Exception failure) { // IOException ioe = new IOException("error processing the pse config advertisement"); // ioe.initCause(failure); // throw ioe; // } // Rendezvous try { param = (XMLElement) platformConfig.getServiceParam(PeerGroup.rendezvousClassID); // backwards compatibility param.addAttribute("type", RdvConfigAdv.getAdvertisementType()); rdvConfig = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(param); if (rdvConfig.getConfiguration() == RendezVousConfiguration.AD_HOC) { mode = mode | RDV_AD_HOC; } else if (rdvConfig.getConfiguration() == RendezVousConfiguration.EDGE) { mode = mode | RDV_CLIENT; } else if (rdvConfig.getConfiguration() == RendezVousConfiguration.RENDEZVOUS) { mode = mode | RDV_SERVER; } } catch (Exception failure) { IOException ioe = new IOException("error processing the rendezvous config advertisement"); ioe.initCause(failure); throw ioe; } // Relay try { param = (XMLElement) platformConfig.getServiceParam(PeerGroup.relayProtoClassID); if (param != null && !platformConfig.isSvcEnabled(PeerGroup.relayProtoClassID)) { mode = mode | RELAY_OFF; } // backwards compatibility param.addAttribute("type", RelayConfigAdv.getAdvertisementType()); relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(param); } catch (Exception failure) { IOException ioe = new IOException("error processing the relay config advertisement"); ioe.initCause(failure); throw ioe; } // PSE param = (XMLElement) platformConfig.getServiceParam(PeerGroup.membershipClassID); if (param != null) { Advertisement adv = null; try { adv = AdvertisementFactory.newAdvertisement(param); } catch (NoSuchElementException notAnAdv) { CertificateException cnfe = new CertificateException("No membership advertisement found"); cnfe.initCause(notAnAdv); } catch (IllegalArgumentException invalidAdv) { CertificateException cnfe = new CertificateException("Invalid membership advertisement"); cnfe.initCause(invalidAdv); } if (adv instanceof PSEConfigAdv) { pseConf = (PSEConfigAdv) adv; cert = pseConf.getCertificateChain(); } else { throw new CertificateException("Error processing the Membership config advertisement. Unexpected membership advertisement " + adv.getAdvertisementType()); } } // Infra Group infraPeerGroupConfig = (PeerGroupConfigAdv) platformConfig.getSvcConfigAdvertisement(PeerGroup.peerGroupClassID); if (null == infraPeerGroupConfig) { infraPeerGroupConfig = createInfraConfigAdv(); try { URI configPropsURI = storeHome.resolve("config.properties"); InputStream configPropsIS = configPropsURI.toURL().openStream(); ResourceBundle rsrcs = new PropertyResourceBundle(configPropsIS); configPropsIS.close(); NetGroupTunables tunables = new NetGroupTunables(rsrcs, new NetGroupTunables()); infraPeerGroupConfig.setPeerGroupID(tunables.id); infraPeerGroupConfig.setName(tunables.name); infraPeerGroupConfig.setDesc(tunables.desc); } catch (IOException ignored) { //ignored } catch (MissingResourceException ignored) { //ignored } } return platformConfig; } private TCPAdv loadTcpAdv(PlatformConfig platformConfig, ModuleClassID moduleClassID) { XMLElement<?> param = (XMLElement<?>) platformConfig.getServiceParam(moduleClassID); Enumeration<?> tcpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType()); // get the TransportAdv from either TransportAdv or tcpConfig if (tcpChilds.hasMoreElements()) { param = (XMLElement<?>) tcpChilds.nextElement(); } else { throw new IllegalStateException("Missing TCP Advertisement"); } return (TCPAdv) AdvertisementFactory.newAdvertisement(param); } private MulticastAdv loadMulticastAdv(PlatformConfig platformConfig, ModuleClassID moduleClassID) { XMLElement<?> param2 = (XMLElement<?>) platformConfig.getServiceParam(moduleClassID); Enumeration<?> tcpChilds2 = param2.getChildren(TransportAdvertisement.getAdvertisementType()); // get the TransportAdv from either TransportAdv or multicastConfig if (tcpChilds2.hasMoreElements()) { param2 = (XMLElement<?>) tcpChilds2.nextElement(); } else { throw new IllegalStateException("Missing Multicast Advertisment"); } return (MulticastAdv) AdvertisementFactory.newAdvertisement(param2); } /** * Persists a PlatformConfig advertisement under getStoreHome()+"/PlaformConfig" * <p/> * Home may be overridden by a call to setHome() * * @throws IOException If there is a failure saving the PlatformConfig. * @see #load */ public void save() throws IOException { httpEnabled = (httpConfig.isClientEnabled() || httpConfig.isServerEnabled()); tcpEnabled = (tcpConfig.isClientEnabled() || tcpConfig.isServerEnabled()); http2Enabled = (http2Config.isClientEnabled() || http2Config.isServerEnabled()); ConfigParams advertisement = getPlatformConfig(); OutputStream out = null; try { if ("file".equalsIgnoreCase(storeHome.getScheme())) { File saveDir = new File(storeHome); saveDir.mkdirs(); // Sadly we can't use URL.openConnection() to create the // OutputStream for file:// URLs. bogus. out = new FileOutputStream(new File(saveDir, "PlatformConfig")); } else { out = storeHome.resolve("PlatformConfig").toURL().openConnection().getOutputStream(); } XMLDocument aDoc = (XMLDocument) advertisement.getDocument(MimeMediaType.XMLUTF8); OutputStreamWriter os = new OutputStreamWriter(out, "UTF-8"); aDoc.sendToWriter(os); os.flush(); } finally { if (null != out) { out.close(); } } } /** * Returns a XMLDocument representation of an Advertisement * * @param enabled whether the param doc is enabled, adds a "isOff" * element if disabled * @param adv the Advertisement to retrieve the param doc from * @return the parmDoc value */ protected XMLDocument getParmDoc(boolean enabled, Advertisement adv) { XMLDocument parmDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); XMLDocument doc = (XMLDocument) adv.getDocument(MimeMediaType.XMLUTF8); StructuredDocumentUtils.copyElements(parmDoc, parmDoc, doc); if (!enabled) { parmDoc.appendChild(parmDoc.createElement("isOff")); } return parmDoc; } /** * Creates an HTTP transport advertisement * * @return an HTTP transport advertisement */ protected HTTPAdv createHttpAdv() { httpConfig = (HTTPAdv) AdvertisementFactory.newAdvertisement(HTTPAdv.getAdvertisementType()); httpConfig.setProtocol("http"); httpConfig.setPort(9700); httpConfig.setClientEnabled((mode & HTTP_CLIENT) == HTTP_CLIENT); httpConfig.setServerEnabled((mode & HTTP_SERVER) == HTTP_SERVER); return httpConfig; } /** * Creates Personal Security Environment Config Advertisement * <p/>The configuration advertisement can include an optional seed certificate * chain and encrypted private key. If this seed information is present the PSE * Membership Service will require an initial authentication to unlock the * encrypted private key before creating the PSE keystore. The newly created * PSE keystore will be "seeded" with the certificate chain and the private key. * * @param principal principal * @param password the password used to sign the private key of the root certificate * @return PSEConfigAdv an PSE config advertisement * @see net.jxta.impl.protocol.PSEConfigAdv */ protected PSEConfigAdv createPSEAdv(String principal, String password) { pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType()); if (principal != null && password != null) { IssuerInfo info = PSEUtils.genCert(principal, null); pseConf.setCertificate(info.cert); pseConf.setPrivateKey(info.subjectPkey, password.toCharArray()); } return pseConf; } /** * Creates Personal Security Environment Config Advertisement * <p/>The configuration advertisement can include an optional seed certificate * chain and encrypted private key. If this seed information is present the PSE * Membership Service will require an initial authentication to unlock the * encrypted private key before creating the PSE keystore. The newly created * PSE keystore will be "seeded" with the certificate chain and the private key. * * @param cert X509Certificate * @return PSEConfigAdv an PSE config advertisement * @see net.jxta.impl.protocol.PSEConfigAdv */ protected PSEConfigAdv createPSEAdv(X509Certificate cert) { pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType()); if (subjectPkey != null && password != null) { pseConf.setCertificate(cert); pseConf.setPrivateKey(subjectPkey, password.toCharArray()); } return pseConf; } /** * Creates Personal Security Environment Config Advertisement * <p/>The configuration advertisement can include an optional seed certificate * chain and encrypted private key. If this seed information is present the PSE * Membership Service will require an initial authentication to unlock the * encrypted private key before creating the PSE keystore. The newly created * PSE keystore will be "seeded" with the certificate chain and the private key. * * @param certificateChain X509Certificate[] * @return PSEConfigAdv an PSE config advertisement * @see net.jxta.impl.protocol.PSEConfigAdv */ protected PSEConfigAdv createPSEAdv(X509Certificate[] certificateChain) { pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType()); if (subjectPkey != null && password != null) { pseConf.setCertificateChain(certificateChain); pseConf.setPrivateKey(subjectPkey, password.toCharArray()); } return pseConf; } /** * Creates a ProxyService configuration advertisement * * @return ProxyService configuration advertisement */ @Deprecated protected XMLDocument createProxyAdv() { return (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); } /** * Creates a RendezVousService configuration advertisement with default values (EDGE) * * @return a RdvConfigAdv */ protected RdvConfigAdv createRdvConfigAdv() { rdvConfig = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType()); if (mode == RDV_AD_HOC) { rdvConfig.setConfiguration(RendezVousConfiguration.AD_HOC); } else if ((mode & RDV_CLIENT) == RDV_CLIENT) { rdvConfig.setConfiguration(RendezVousConfiguration.EDGE); } else if ((mode & RDV_SERVER) == RDV_SERVER) { rdvConfig.setConfiguration(RendezVousConfiguration.RENDEZVOUS); } // A better alternative is to reference rdv service defaults (currently private) // rdvConfig.setMaxClients(200); return rdvConfig; } /** * Creates a RelayService configuration advertisement with default values (EDGE) * * @return a RelayConfigAdv */ protected RelayConfigAdv createRelayConfigAdv() { relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(RelayConfigAdv.getAdvertisementType()); // Since 2.6 - We should only use seeds when it comes to relay (see Javadoc) // relayConfig.setUseOnlySeeds(false); relayConfig.setClientEnabled((mode & RELAY_CLIENT) == RELAY_CLIENT || mode == EDGE_NODE); relayConfig.setServerEnabled((mode & RELAY_SERVER) == RELAY_SERVER); return relayConfig; } /** * Creates an TCP transport advertisement with the platform default values. * multicast on, 224.0.1.85:1234, with a max packet size of 16K * * @return a TCP transport advertisement */ protected TCPAdv createTcpAdv() { tcpConfig = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType()); tcpConfig.setProtocol("tcp"); tcpConfig.setInterfaceAddress(null); tcpConfig.setPort(9701); //tcpConfig.setStartPort(9701); //tcpConfig.setEndPort(9799); tcpConfig.setServer(null); tcpConfig.setClientEnabled((mode & TCP_CLIENT) == TCP_CLIENT); tcpConfig.setServerEnabled((mode & TCP_SERVER) == TCP_SERVER); return tcpConfig; } /** * Creates an multicast transport advertisement with the platform default values. * Multicast on, 224.0.1.85:1234, with a max packet size of 16K. * * @return a TCP transport advertisement */ protected MulticastAdv createMulticastAdv() { multicastConfig = (MulticastAdv) AdvertisementFactory.newAdvertisement(MulticastAdv.getAdvertisementType()); multicastConfig.setProtocol("tcp"); multicastConfig.setMulticastAddr("224.0.1.85"); multicastConfig.setMulticastPort(1234); multicastConfig.setMulticastSize(16384); multicastConfig.setMulticastState((mode & IP_MULTICAST) == IP_MULTICAST); return multicastConfig; } protected TCPAdv createHttp2Adv() { http2Config = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType()); http2Config.setProtocol("http2"); http2Config.setInterfaceAddress(null); http2Config.setPort(8080); http2Config.setStartPort(8080); http2Config.setEndPort(8089); http2Config.setServer(null); http2Config.setClientEnabled((mode & HTTP2_CLIENT) == TCP_CLIENT); http2Config.setServerEnabled((mode & HTTP2_SERVER) == TCP_SERVER); return http2Config; } protected PeerGroupConfigAdv createInfraConfigAdv() { infraPeerGroupConfig = (PeerGroupConfigAdv) AdvertisementFactory.newAdvertisement( PeerGroupConfigAdv.getAdvertisementType()); NetGroupTunables tunables = new NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config"), new NetGroupTunables()); infraPeerGroupConfig.setPeerGroupID(tunables.id); infraPeerGroupConfig.setName(tunables.name); infraPeerGroupConfig.setDesc(tunables.desc); return infraPeerGroupConfig; } /** * Returns a PlatformConfig which represents a platform configuration. * <p/>Fine tuning is achieved through accessing each configured advertisement * and achieved through accessing each configured advertisement and modifying * each object directly. * * @return the PeerPlatformConfig Advertisement */ public ConfigParams getPlatformConfig() { PlatformConfig advertisement = (PlatformConfig) AdvertisementFactory.newAdvertisement( PlatformConfig.getAdvertisementType()); advertisement.setName(name); advertisement.setDescription(description); if (tcpConfig != null) { boolean enabled = tcpEnabled && (tcpConfig.isServerEnabled() || tcpConfig.isClientEnabled()); advertisement.putServiceParam(PeerGroup.tcpProtoClassID, getParmDoc(enabled, tcpConfig)); } if (multicastConfig != null) { boolean enabled = multicastConfig.getMulticastState(); advertisement.putServiceParam(PeerGroup.multicastProtoClassID, getParmDoc(enabled, multicastConfig)); } if (httpConfig != null) { boolean enabled = httpEnabled && (httpConfig.isServerEnabled() || httpConfig.isClientEnabled()); advertisement.putServiceParam(PeerGroup.httpProtoClassID, getParmDoc(enabled, httpConfig)); } if (http2Config != null) { boolean enabled = http2Enabled && (http2Config.isServerEnabled() || http2Config.isClientEnabled()); advertisement.putServiceParam(PeerGroup.http2ProtoClassID, getParmDoc(enabled, http2Config)); } if (relayConfig != null) { boolean isOff = ((mode & RELAY_OFF) == RELAY_OFF) || (relayConfig.isServerEnabled() && relayConfig.isClientEnabled()); XMLDocument relayDoc = (XMLDocument) relayConfig.getDocument(MimeMediaType.XMLUTF8); if (isOff) { relayDoc.appendChild(relayDoc.createElement("isOff")); } advertisement.putServiceParam(PeerGroup.relayProtoClassID, relayDoc); } if (rdvConfig != null) { XMLDocument rdvDoc = (XMLDocument) rdvConfig.getDocument(MimeMediaType.XMLUTF8); advertisement.putServiceParam(PeerGroup.rendezvousClassID, rdvDoc); } if (principal == null) { principal = System.getProperty("impl.membership.pse.authentication.principal", "JxtaCN"); } if (password == null) { password = System.getProperty("impl.membership.pse.authentication.password", "the!one!password"); } if (cert != null) { pseConf = createPSEAdv(cert); } else { pseConf = createPSEAdv(principal, password); cert = pseConf.getCertificateChain(); } if (pseConf != null) { if (keyStoreLocation != null) { if (keyStoreLocation.isAbsolute()) { pseConf.setKeyStoreLocation(keyStoreLocation); } else { Logging.logCheckedWarning(LOG, "Keystore location set, but is not absolute: ", keyStoreLocation); } } XMLDocument pseDoc = (XMLDocument) pseConf.getDocument(MimeMediaType.XMLUTF8); advertisement.putServiceParam(PeerGroup.membershipClassID, pseDoc); } if (authenticationType == null) { authenticationType = System.getProperty("impl.membership.pse.authentication.type", "StringAuthentication"); } StdPeerGroup.setPSEMembershipServiceKeystoreInfoFactory(new StdPeerGroup.DefaultPSEMembershipServiceKeystoreInfoFactory(authenticationType, password)); if (peerid == null) { peerid = IDFactory.newPeerID(PeerGroupID.worldPeerGroupID, cert[0].getPublicKey().getEncoded()); } advertisement.setPeerID(peerid); // if (proxyConfig != null && ((mode & PROXY_SERVER) == PROXY_SERVER)) { // advertisement.putServiceParam(PeerGroup.proxyClassID, proxyConfig); // } if ((null != infraPeerGroupConfig) && (null != infraPeerGroupConfig.getPeerGroupID()) && (ID.nullID != infraPeerGroupConfig.getPeerGroupID()) && (PeerGroupID.defaultNetPeerGroupID != infraPeerGroupConfig.getPeerGroupID())) { advertisement.setSvcConfigAdvertisement(PeerGroup.peerGroupClassID, infraPeerGroupConfig); } return advertisement; } /** * @param location The location of the platform config. * @return The platformConfig * @throws IOException Thrown for failures reading the PlatformConfig. */ private PlatformConfig read(URI location) throws IOException { URL url; try { url = location.toURL(); } catch (MalformedURLException mue) { IllegalArgumentException failure = new IllegalArgumentException("Failed to convert URI to URL"); failure.initCause(mue); throw failure; } InputStream input = url.openStream(); try { XMLDocument document = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, input); PlatformConfig platformConfig = (PlatformConfig) AdvertisementFactory.newAdvertisement(document); return platformConfig; } finally { input.close(); } } /** * Indicates whether Http is enabled * * @return true if Http is enabled, else returns false * @see #setHttpEnabled */ public boolean isHttpEnabled() { return this.httpEnabled; } /** * Retrieves the Http incoming status * * @return true if Http incomming status is enabled, else returns false * @see #setHttpIncoming */ public boolean getHttpIncomingStatus() { return httpConfig.getServerEnabled(); } /** * Retrieves the Http outgoing status * * @return true if Http outgoing status is enabled, else returns false * @see #setHttpOutgoing */ public boolean getHttpOutgoingStatus() { return httpConfig.getClientEnabled(); } /** * Retrieves the Http port * * @return the current Http port * @see #setHttpPort */ public int getHttpPort() { return httpConfig.getPort(); } /** * Retrieves the current infrastructure ID * * @return the current infrastructure ID * @see #setInfrastructureID */ public ID getInfrastructureID() { return infraPeerGroupConfig.getPeerGroupID(); } /** * Retrieves the current multicast address * * @return the current multicast address * @see #setMulticastAddress */ public String getMulticastAddress() { return multicastConfig.getMulticastAddr(); } /** * Retrieves the current multicast port * * @return the current mutlicast port * @see #setMulticastPort */ public int getMulticastPort() { return multicastConfig.getMulticastPort(); } /** * Gets the group multicast thread pool size * * @return multicast thread pool size */ public int getMulticastPoolSize() { return multicastConfig.getMulticastPoolSize(); } /** * Indicates whether tcp is enabled * * @return true if tcp is enabled, else returns false * @see #setTcpEnabled */ public boolean isTcpEnabled() { return this.tcpEnabled; } /** * Retrieves the current tcp end port * * @return the current tcp port * @see #setTcpEndPort */ public int getTcpEndport() { return tcpConfig.getEndPort(); } /** * Retrieves the Tcp incoming status * * @return true if tcp incoming is enabled, else returns false * @see #setTcpIncoming */ public boolean getTcpIncomingStatus() { return tcpConfig.getServerEnabled(); } /** * Retrieves the Tcp outgoing status * * @return true if tcp outcoming is enabled, else returns false * @see #setTcpOutgoing */ public boolean getTcpOutgoingStatus() { return tcpConfig.getClientEnabled(); } /** * Retrieves the Tcp interface address * * @return the current tcp interface address * @see #setTcpInterfaceAddress */ public String getTcpInterfaceAddress() { return tcpConfig.getInterfaceAddress(); } /** * Retrieves the current Tcp port * * @return the current tcp port * @see #setTcpPort */ public int getTcpPort() { return tcpConfig.getPort(); } /** * Retrieves the current Tcp public address * * @return the current tcp public address * @see #setTcpPublicAddress */ public String getTcpPublicAddress() { return tcpConfig.getServer(); } /** * Indicates whether the current Tcp public address is exclusive * * @return true if the current tcp public address is exclusive, else returns false * @see #setTcpPublicAddress */ public boolean isTcpPublicAddressExclusive() { return tcpConfig.getPublicAddressOnly(); } /** * Retrieves the current Tcp start port * * @return the current tcp start port * @see #setTcpStartPort */ public int getTcpStartPort() { return tcpConfig.getStartPort(); } /** * Retrieves the multicast use status * * @return true if multicast is enabled, else returns false * @see #setUseMulticast */ public boolean getMulticastStatus() { return multicastConfig.getMulticastState(); } /** * Retrieves the use relay seeds only status * * @return true if only relay seeds are used, else returns false * @see #setUseOnlyRelaySeeds */ public boolean getUseOnlyRelaySeedsStatus() { return relayConfig.getUseOnlySeeds(); } /** * Retrieves the use rendezvous seeds only status * * @return true if only rendezvous seeds are used, else returns false * @see #setUseOnlyRendezvousSeeds */ public boolean getUseOnlyRendezvousSeedsStatus() { return rdvConfig.getUseOnlySeeds(); } /** * Retrieves the RendezVousService maximum number of simultaneous rendezvous clients * * @return the RendezVousService maximum number of simultaneous rendezvous clients * @see #setRendezvousMaxClients */ public int getRendezvousMaxClients() { return rdvConfig.getMaxClients(); } /** * Retrieves the RelayVousService maximum number of simultaneous relay clients * * @return the RelayService maximum number of simultaneous relay clients * @see #setRelayMaxClients */ public int getRelayMaxClients() { return relayConfig.getMaxClients(); } /** * Retrieves the rendezvous seedings * * @return the array of rendezvous seeding URL * @see #addRdvSeedingURI */ public URI[] getRdvSeedingURIs() { return rdvConfig.getSeedingURIs(); } /** * Retrieves the rendezvous seeds * * @return the array of rendezvous seeds URL * @see #addRdvSeedURI */ public URI[] getRdvSeedURIs() { return rdvConfig.getSeedRendezvous(); } /** * Retrieves the relay seeds * * @return the array of relay seeds URL * @see #addRelaySeedURI */ public URI[] getRelaySeedURIs() { return relayConfig.getSeedRelayURIs(); } /** * Retrieves the relay seeds * * @return the array of rendezvous seed URL * @see #addRelaySeedingURI */ public URI[] getRelaySeedingURIs() { return relayConfig.getSeedingURIs(); } /** * Holds the construction tunables for the Net Peer Group. This consists of * the peer group id, the peer group name and the peer group description. */ static class NetGroupTunables { final ID id; final String name; final XMLElement desc; /** * Constructor for loading the default Net Peer Group construction * tunables. */ NetGroupTunables() { id = PeerGroupID.defaultNetPeerGroupID; name = "NetPeerGroup"; desc = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", "default Net Peer Group"); } /** * Constructor for loading the default Net Peer Group construction * tunables. * * @param pgid the PeerGroupID * @param pgname the group name * @param pgdesc the group description */ NetGroupTunables(ID pgid, String pgname, XMLElement pgdesc) { id = pgid; name = pgname; desc = pgdesc; } /** * Constructor for loading the Net Peer Group construction * tunables from the provided resource bundle. * * @param rsrcs The resource bundle from which resources will be loaded. * @param defaults default values */ NetGroupTunables(ResourceBundle rsrcs, NetGroupTunables defaults) { ID idTmp; String nameTmp; XMLElement descTmp; try { String idTmpStr = rsrcs.getString("NetPeerGroupID").trim(); if (idTmpStr.startsWith(ID.URNNamespace + ":")) { idTmpStr = idTmpStr.substring(5); } idTmp = IDFactory.fromURI(new URI(ID.URIEncodingName + ":" + ID.URNNamespace + ":" + idTmpStr)); nameTmp = rsrcs.getString("NetPeerGroupName").trim(); descTmp = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", rsrcs.getString("NetPeerGroupDesc").trim()); } catch (Exception failed) { if (null != defaults) { Logging.logCheckedFine(LOG, "NetPeerGroup tunables not defined or could not be loaded. Using defaults.\n\n", failed); idTmp = defaults.id; nameTmp = defaults.name; descTmp = defaults.desc; } else { Logging.logCheckedSevere(LOG, "NetPeerGroup tunables not defined or could not be loaded.\n", failed); throw new IllegalStateException("NetPeerGroup tunables not defined or could not be loaded."); } } id = idTmp; name = nameTmp; desc = descTmp; } } }
johnjianfang/jxse
src/main/java/net/jxta/platform/NetworkConfigurator.java
Java
apache-2.0
82,829
import Observable from '../Observable'; import mergeStatic from './merge-static'; export default function merge<R>(...observables: (Observable<any>|number)[]): Observable<R> { observables.unshift(this); return mergeStatic.apply(this, observables); }
jaawerth/RxJS-1
src/operators/merge.ts
TypeScript
apache-2.0
254
package com.sissi.protocol.message; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlValue; import com.sissi.io.read.Metadata; /** * @author kim 2014年1月28日 */ @Metadata(uri = Message.XMLNS, localName = Thread.NAME) @XmlRootElement public class Thread { public final static String NAME = "thread"; private String text; private String parent; public Thread() { super(); } public Thread(String text) { super(); this.text = text; } public Thread(String text, String parent) { super(); this.text = text; this.parent = parent; } @XmlValue public String getText() { return this.text; } public Thread setText(String text) { this.text = text; return this; } @XmlAttribute public String getParent() { return this.parent; } public Thread setParent(String parent) { this.parent = parent; return this; } public boolean content() { return this.text != null && this.text.length() > 0; } }
KimShen/sissi
src/main/java/com/sissi/protocol/message/Thread.java
Java
apache-2.0
1,026
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0) on Fri Feb 01 09:13:22 EST 2013 --> <title>Uses of Class org.drip.analytics.holset.IEPHoliday</title> <meta name="date" content="2013-02-01"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.drip.analytics.holset.IEPHoliday"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/drip/analytics/holset/IEPHoliday.html" title="class in org.drip.analytics.holset">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/drip/analytics/holset/\class-useIEPHoliday.html" target="_top">Frames</a></li> <li><a href="IEPHoliday.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.drip.analytics.holset.IEPHoliday" class="title">Uses of Class<br>org.drip.analytics.holset.IEPHoliday</h2> </div> <div class="classUseContainer">No usage of org.drip.analytics.holset.IEPHoliday</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/drip/analytics/holset/IEPHoliday.html" title="class in org.drip.analytics.holset">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/drip/analytics/holset/\class-useIEPHoliday.html" target="_top">Frames</a></li> <li><a href="IEPHoliday.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
tectronics/rootfinder
2.1/docs/Javadoc/org/drip/analytics/holset/class-use/IEPHoliday.html
HTML
apache-2.0
4,253
# kauri
riversoforion/kauri
README.md
Markdown
apache-2.0
8
#import <Cocoa/Cocoa.h> FOUNDATION_EXPORT double SwiftHTTPVersionNumber; FOUNDATION_EXPORT const unsigned char SwiftHTTPVersionString[];
inderdhir/MemeGrabber
Pods/Target Support Files/SwiftHTTP/SwiftHTTP-umbrella.h
C
apache-2.0
140
--- layout: default title: CAS - Password Management category: Password Management --- # Password Management If authentication fails due to a rejected password policy, CAS is able to intercept that request and allow the user to update the account password in place. The password management features of CAS are rather modest, and alternatively should the functionality provide inadequate for your policy, you may always redirect CAS to use a separate and standalone application that is fully in charge of managing the account password and associated flows. CAS may also allow users to reset their passwords voluntarily. Those who have forgotten their account password may receive a secure link with a time-based expiration policy at their registered email address and/or phone. The link will allow the user to provide answers to his/her pre-defined security questions, which if successfully done, will allow the user to next reset their password and login again. You may also specify a pattern for accepted passwords. By default, after a user has successfully changed their password they will be redirected to the login screen to enter their new password and log in. CAS can also be configured to automatically log the user in after a successful change. This behavior can be altered via CAS settings. To learn more about available notification options, please [see this guide](SMS-Messaging-Configuration.html) or [this guide](Sending-Email-Configuration.html). To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#password-management). ## JSON Accounts and password may be stored inside a static modest JSON resource. This option is most useful during development and for demo purposes. To learn more, please [see this guide](Password-Management-JSON.html). ## Groovy Accounts and password may be handled and calculated via a Groovy script. To learn more, please [see this guide](Password-Management-Groovy.html). ## LDAP The account password and security questions may be stored inside an LDAP server. To learn more, please [see this guide](Password-Management-LDAP.html). ## JDBC The account password and security questions may be stored inside a relational database. To learn more, please [see this guide](Password-Management-JDBC.html). ## REST The account password and security questions can also be managed using a REST API. To learn more please [see this guide](Password-Management-REST.html). ## Custom To design your own password management storage options and strategy, please [see this guide](Password-Management-Custom.html).
tduehr/cas
docs/cas-server-documentation/password_management/Password-Management.md
Markdown
apache-2.0
2,623
package instance import ( "io/ioutil" "os" "testing" "github.com/scaleway/scaleway-cli/internal/core" ) func Test_UserDataGet(t *testing.T) { t.Run("Get an existing key", core.Test(&core.TestConfig{ BeforeFunc: core.BeforeFuncCombine( createServer("Server"), core.ExecBeforeCmd("scw instance user-data set server-id={{.Server.ID}} key=happy content=true"), ), Commands: GetCommands(), Cmd: "scw instance user-data get server-id={{.Server.ID}} key=happy", AfterFunc: deleteServer("Server"), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), ), })) t.Run("Get an nonexistent key", core.Test(&core.TestConfig{ BeforeFunc: createServer("Server"), Commands: GetCommands(), Cmd: "scw instance user-data get server-id={{.Server.ID}} key=happy", AfterFunc: deleteServer("Server"), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(1), ), })) } func Test_UserDataList(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ BeforeFunc: core.BeforeFuncCombine( createServer("Server"), core.ExecBeforeCmd("scw instance user-data set server-id={{ .Server.ID }} key=foo content=bar"), core.ExecBeforeCmd("scw instance user-data set server-id={{ .Server.ID }} key=bar content=foo"), ), Commands: GetCommands(), Cmd: "scw instance user-data list server-id={{ .Server.ID }}", AfterFunc: deleteServer("Server"), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), ), })) } func Test_UserDataFileUpload(t *testing.T) { content := "cloud-init file content" t.Run("on-cloud-init", core.Test(&core.TestConfig{ Commands: GetCommands(), BeforeFunc: core.BeforeFuncCombine( core.ExecStoreBeforeCmd("Server", "scw instance server create stopped=true image=ubuntu-bionic"), func(ctx *core.BeforeFuncCtx) error { file, _ := ioutil.TempFile("", "test") _, _ = file.WriteString(content) ctx.Meta["filePath"] = file.Name() return nil }, ), Cmd: `scw instance user-data set key=cloud-init server-id={{ .Server.ID }} content=@{{ .filePath }}`, Check: core.TestCheckCombine( core.TestCheckGolden(), ), AfterFunc: core.AfterFuncCombine( func(ctx *core.AfterFuncCtx) error { _ = os.RemoveAll(ctx.Meta["filePath"].(string)) return nil }, ), })) t.Run("on-random-key", core.Test(&core.TestConfig{ Commands: GetCommands(), BeforeFunc: core.BeforeFuncCombine( core.ExecStoreBeforeCmd("Server", "scw instance server create stopped=true image=ubuntu-bionic"), func(ctx *core.BeforeFuncCtx) error { file, _ := ioutil.TempFile("", "test") _, _ = file.WriteString(content) ctx.Meta["filePath"] = file.Name() return nil }, ), Cmd: `scw instance user-data set key=foobar server-id={{ .Server.ID }} content=@{{ .filePath }}`, Check: core.TestCheckCombine( core.TestCheckGolden(), ), AfterFunc: core.AfterFuncCombine( func(ctx *core.AfterFuncCtx) error { _ = os.RemoveAll(ctx.Meta["filePath"].(string)) return nil }, ), })) }
scaleway/scaleway-cli
internal/namespaces/instance/v1/custom_user_data_test.go
GO
apache-2.0
3,105
# wardtrack A web application to track and visualise questionnaire data.
KHP-Informatics/wardtrack
README.md
Markdown
apache-2.0
74
using ArangoDB.Client.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArangoDB.Client { public class BaseResultAnalyzer { IArangoDatabase db; public BaseResultAnalyzer(IArangoDatabase db) { this.db = db; } public void ThrowIfNeeded(BaseResult baseResult) { if (baseResult.HasError() && db.Setting.ThrowForServerErrors == true) { throw new ArangoServerException(baseResult); } } public void Throw(BaseResult baseResult) { if (baseResult.HasError()) throw new ArangoServerException(baseResult); } } }
ra0o0f/arangoclient.net
src/ArangoDB.Client/BaseResultAnalyzer.cs
C#
apache-2.0
774
/** * Copyright (C) 2016 - 2030 youtongluan. * * 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.yx.asm; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.yx.bean.Loader; import org.yx.conf.AppInfo; import org.yx.exception.SumkException; import org.yx.log.Log; import org.yx.log.Logs; import org.yx.main.StartContext; public final class AsmUtils { private static Method defineClass; static { try { defineClass = getMethod(ClassLoader.class, "defineClass", new Class<?>[] { String.class, byte[].class, int.class, int.class }); defineClass.setAccessible(true); } catch (Exception e) { Log.printStack("sumk.error", e); StartContext.startFailed(); } } public static String proxyCalssName(Class<?> clz) { String name = clz.getName(); int index = name.lastIndexOf('.'); return name.substring(0, index) + ".sumkbox" + name.substring(index); } public static int asmVersion() { return AppInfo.getInt("sumk.asm.version", Opcodes.ASM7); } public static int jvmVersion() { return AppInfo.getInt("sumk.asm.jvm.version", Opcodes.V1_8); } public static InputStream openStreamForClass(String name) { String internalName = name.replace('.', '/') + ".class"; return Loader.getResourceAsStream(internalName); } public static boolean sameType(Type[] types, Class<?>[] clazzes) { if (types.length != clazzes.length) { return false; } for (int i = 0; i < types.length; i++) { if (!Type.getType(clazzes[i]).equals(types[i])) { return false; } } return true; } public static List<MethodParamInfo> buildMethodInfos(List<Method> methods) throws IOException { Map<Class<?>, List<Method>> map = new HashMap<>(); for (Method m : methods) { List<Method> list = map.get(m.getDeclaringClass()); if (list == null) { list = new ArrayList<>(); map.put(m.getDeclaringClass(), list); } list.add(m); } List<MethodParamInfo> ret = new ArrayList<>(); for (List<Method> ms : map.values()) { ret.addAll(buildMethodInfos(ms.get(0).getDeclaringClass(), ms)); } return ret; } private static List<MethodParamInfo> buildMethodInfos(Class<?> declaringClass, List<Method> methods) throws IOException { String classFullName = declaringClass.getName(); ClassReader cr = new ClassReader(openStreamForClass(classFullName)); MethodInfoClassVisitor cv = new MethodInfoClassVisitor(methods); cr.accept(cv, 0); return cv.getMethodInfos(); } public static Method getMethod(Class<?> clz, String methodName, Class<?>[] paramTypes) { while (clz != Object.class) { Method[] ms = clz.getDeclaredMethods(); for (Method m : ms) { if (!m.getName().equals(methodName)) { continue; } Class<?>[] paramTypes2 = m.getParameterTypes(); if (!Arrays.equals(paramTypes2, paramTypes)) { continue; } return m; } clz = clz.getSuperclass(); } return null; } public static Class<?> loadClass(String fullName, byte[] b) throws Exception { String clzOutPath = AppInfo.get("sumk.asm.debug.output"); if (clzOutPath != null && clzOutPath.length() > 0) { try { File f = new File(clzOutPath, fullName + ".class"); try (FileOutputStream fos = new FileOutputStream(f)) { fos.write(b); fos.flush(); } } catch (Exception e) { if (Logs.asm().isTraceEnabled()) { Logs.asm().error(e.getLocalizedMessage(), e); } } } synchronized (AsmUtils.class) { try { return Loader.loadClass(fullName); } catch (Throwable e) { if (!(e instanceof ClassNotFoundException)) { Logs.asm().warn(fullName + " 加载失败", e); } } Class<?> clz = (Class<?>) defineClass.invoke(Loader.loader(), fullName, b, 0, b.length); if (clz == null) { throw new SumkException(-235345436, "cannot load class " + fullName); } return clz; } } public static final int BADMODIFIERS = Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.PRIVATE; public static boolean notPublicOnly(int modifiers) { return (modifiers & (Modifier.PUBLIC | BADMODIFIERS)) != Modifier.PUBLIC; } public static boolean canProxy(int modifiers) { return (modifiers & BADMODIFIERS) == 0; } public static List<Object> getImplicitFrame(String desc) { List<Object> locals = new ArrayList<>(5); if (desc.isEmpty()) { return locals; } int i = 0; while (desc.length() > i) { int j = i; switch (desc.charAt(i++)) { case 'Z': case 'C': case 'B': case 'S': case 'I': locals.add(Opcodes.INTEGER); break; case 'F': locals.add(Opcodes.FLOAT); break; case 'J': locals.add(Opcodes.LONG); break; case 'D': locals.add(Opcodes.DOUBLE); break; case '[': while (desc.charAt(i) == '[') { ++i; } if (desc.charAt(i) == 'L') { ++i; while (desc.charAt(i) != ';') { ++i; } } locals.add(desc.substring(j, ++i)); break; case 'L': while (desc.charAt(i) != ';') { ++i; } locals.add(desc.substring(j + 1, i++)); break; default: break; } } return locals; } public static Method getSameMethod(Method method, Class<?> otherClass) { Class<?> clz = method.getDeclaringClass(); if (clz == otherClass) { return method; } String methodName = method.getName(); Class<?>[] argTypes = method.getParameterTypes(); Method[] proxyedMethods = otherClass.getMethods(); for (Method proxyedMethod : proxyedMethods) { if (proxyedMethod.getName().equals(methodName) && Arrays.equals(argTypes, proxyedMethod.getParameterTypes()) && !proxyedMethod.getDeclaringClass().isInterface()) { return proxyedMethod; } } return method; } }
youtongluan/sumk
src/main/java/org/yx/asm/AsmUtils.java
Java
apache-2.0
6,539
# Jacksonia aculeata W.Fitzg. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Jacksonia/Jacksonia aculeata/README.md
Markdown
apache-2.0
185
/********************************************************************** Copyright (c) 2009 Stefan Seelmann. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********************************************************************/ package com.example.dao; import java.util.Collection; import com.example.Team; public class TeamDao extends AbstractDao<Team> { public Collection<Team> findByName( String name ) { return super.findByQuery( "name.startsWith(s1)", "java.lang.String s1", name ); } public Team loadWithUsers( Object id ) { return super.load( id, "users" ); } public Team load( Object id ) { return super.load( id ); } public Collection<Team> loadAll() { return super.loadAll(); } }
seelmann/ldapcon2009-datanucleus
DataNucleus-Advanced/src/main/java/com/example/dao/TeamDao.java
Java
apache-2.0
1,280
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module LifesciencesV2beta # Cloud Life Sciences API # # Cloud Life Sciences is a suite of services and tools for managing, processing, # and transforming life sciences data. # # @example # require 'google/apis/lifesciences_v2beta' # # Lifesciences = Google::Apis::LifesciencesV2beta # Alias the module # service = Lifesciences::CloudLifeSciencesService.new # # @see https://cloud.google.com/life-sciences class CloudLifeSciencesService < Google::Apis::Core::BaseService # @return [String] # API key. Your API key identifies your project and provides you with API access, # quota, and reports. Required unless you provide an OAuth 2.0 token. attr_accessor :key # @return [String] # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. attr_accessor :quota_user def initialize super('https://lifesciences.googleapis.com/', '') @batch_path = 'batch' end # Gets information about a location. # @param [String] name # Resource name for the location. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::Location] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::Location] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_project_location(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v2beta/{+name}', options) command.response_representation = Google::Apis::LifesciencesV2beta::Location::Representation command.response_class = Google::Apis::LifesciencesV2beta::Location command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists information about the supported locations for this service. # @param [String] name # The resource that owns the locations collection, if applicable. # @param [String] filter # The standard list filter. # @param [Fixnum] page_size # The standard list page size. # @param [String] page_token # The standard list page token. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::ListLocationsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::ListLocationsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_project_locations(name, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v2beta/{+name}/locations', options) command.response_representation = Google::Apis::LifesciencesV2beta::ListLocationsResponse::Representation command.response_class = Google::Apis::LifesciencesV2beta::ListLocationsResponse command.params['name'] = name unless name.nil? command.query['filter'] = filter unless filter.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Starts asynchronous cancellation on a long-running operation. The server makes # a best effort to cancel the operation, but success is not guaranteed. Clients # may use Operations.GetOperation or Operations.ListOperations to check whether # the cancellation succeeded or the operation completed despite cancellation. # Authorization requires the following [Google IAM](https://cloud.google.com/iam) # permission: * `lifesciences.operations.cancel` # @param [String] name # The name of the operation resource to be cancelled. # @param [Google::Apis::LifesciencesV2beta::CancelOperationRequest] cancel_operation_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::Empty] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::Empty] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def cancel_operation(name, cancel_operation_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v2beta/{+name}:cancel', options) command.request_representation = Google::Apis::LifesciencesV2beta::CancelOperationRequest::Representation command.request_object = cancel_operation_request_object command.response_representation = Google::Apis::LifesciencesV2beta::Empty::Representation command.response_class = Google::Apis::LifesciencesV2beta::Empty command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets the latest state of a long-running operation. Clients can use this method # to poll the operation result at intervals as recommended by the API service. # Authorization requires the following [Google IAM](https://cloud.google.com/iam) # permission: * `lifesciences.operations.get` # @param [String] name # The name of the operation resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_project_location_operation(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v2beta/{+name}', options) command.response_representation = Google::Apis::LifesciencesV2beta::Operation::Representation command.response_class = Google::Apis::LifesciencesV2beta::Operation command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists operations that match the specified filter in the request. Authorization # requires the following [Google IAM](https://cloud.google.com/iam) permission: * # `lifesciences.operations.list` # @param [String] name # The name of the operation's parent resource. # @param [String] filter # A string for filtering Operations. The following filter fields are supported: * # createTime: The time this job was created * events: The set of event (names) # that have occurred while running the pipeline. The : operator can be used to # determine if a particular event has occurred. * error: If the pipeline is # running, this value is NULL. Once the pipeline finishes, the value is the # standard Google error code. * labels.key or labels."key with space" where key # is a label key. * done: If the pipeline is running, this value is false. Once # the pipeline finishes, the value is true. # @param [Fixnum] page_size # The maximum number of results to return. The maximum value is 256. # @param [String] page_token # The standard list page token. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::ListOperationsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::ListOperationsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_project_location_operations(name, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v2beta/{+name}/operations', options) command.response_representation = Google::Apis::LifesciencesV2beta::ListOperationsResponse::Representation command.response_class = Google::Apis::LifesciencesV2beta::ListOperationsResponse command.params['name'] = name unless name.nil? command.query['filter'] = filter unless filter.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Runs a pipeline. The returned Operation's metadata field will contain a google. # cloud.lifesciences.v2beta.Metadata object describing the status of the # pipeline execution. The response field will contain a google.cloud. # lifesciences.v2beta.RunPipelineResponse object if the pipeline completes # successfully. **Note:** Before you can use this method, the *Life Sciences # Service Agent* must have access to your project. This is done automatically # when the Cloud Life Sciences API is first enabled, but if you delete this # permission you must disable and re-enable the API to grant the Life Sciences # Service Agent the required permissions. Authorization requires the following [ # Google IAM](https://cloud.google.com/iam/) permission: * `lifesciences. # workflows.run` # @param [String] parent # The project and location that this request should be executed against. # @param [Google::Apis::LifesciencesV2beta::RunPipelineRequest] run_pipeline_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def run_pipeline(parent, run_pipeline_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v2beta/{+parent}/pipelines:run', options) command.request_representation = Google::Apis::LifesciencesV2beta::RunPipelineRequest::Representation command.request_object = run_pipeline_request_object command.response_representation = Google::Apis::LifesciencesV2beta::Operation::Representation command.response_class = Google::Apis::LifesciencesV2beta::Operation command.params['parent'] = parent unless parent.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end protected def apply_command_defaults(command) command.query['key'] = key unless key.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? end end end end end
googleapis/google-api-ruby-client
google-api-client/generated/google/apis/lifesciences_v2beta/service.rb
Ruby
apache-2.0
17,086
package com.metrink.action; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Provider; import com.metrink.alert.ActionBean; import com.metrink.alert.AlertBean; import com.metrink.metric.Metric; /** * The base action for all SMS actions. * * A list of gateways can be found here: http://www.emailtextmessages.com/ * */ public abstract class SmsAction implements Action { private static final Logger LOG = LoggerFactory.getLogger(SmsAction.class); private final Provider<SimpleEmail> emailProvider; public SmsAction(final Provider<SimpleEmail> emailProvider) { this.emailProvider = emailProvider; } @Override public void triggerAction(Metric metric, AlertBean alertBean, ActionBean actionBean) { final String toAddr = constructAddress(actionBean.getValue()); final String alertQuery = alertBean.getAlertQuery().substring(0, alertBean.getAlertQuery().lastIndexOf(" do ")); final StringBuilder sb = new StringBuilder(); sb.append(metric.getId()); sb.append(" "); sb.append(metric.getValue()); sb.append(" triggered "); sb.append(alertQuery); try { final SimpleEmail email = emailProvider.get(); email.addTo(toAddr); email.setSubject("METRINK Alert"); email.setMsg(sb.toString()); final String messageId = email.send(); LOG.info("Sent message {} to {}", messageId, toAddr); } catch (final EmailException e) { LOG.error("Error sending email: {}", e.getMessage()); } } /** * Given a phone number, create the address for the gateway. * @param phoneNumber the phone number. * @return the email address to use. */ protected abstract String constructAddress(String phoneNumber); }
Metrink/metrink
src/main/java/com/metrink/action/SmsAction.java
Java
apache-2.0
1,947
/* Fix a gap in ui-bootstrap's styling */ .nav, .pagination, .carousel, .panel-title a { cursor: pointer; } body { min-height: 2000px; padding-top: 70px; } /* Fix tag filters on index page */ #tags span.label { font-size: 100%; line-height: 2; margin: 2px; } .label-toggle { cursor: pointer; } /* Doc card *******************/ .doc-list { vertical-align: top; } .doc { background: rgba(226,226,226,1); padding: 10px 20px; border: 2px #fff solid; border-radius: 20px; margin: 10px; display: inline-block; width: 350px; cursor: pointer; text-decoration: none; color: black; } .doc:hover { text-decoration: none; } .thumb { display: inline-block; float: right; text-align: center; padding-top: 5px; width: 100px; } .doc dl { margin-bottom: 10px; } .filename { overflow: hidden; white-space: nowrap; width: 200px; position: relative; } .filename:after { content: ""; width: 50px; height: 50px; position: absolute; top: 0; right: 0; background: -moz-linear-gradient(left, rgba(226,226,226,0) 0%, rgba(226,226,226,1) 100%); background: -webkit-linear-gradient(left, rgba(226,226,226,0) 0%, rgba(226,226,226,1) 100%); background: -o-linear-gradient(left, rgba(226,226,226,0) 0%, rgba(226,226,226,1) 100%); background: -ms-linear-gradient(left, rgba(226,226,226,0) 0%, rgba(226,226,226,1) 100%); background: linear-gradient(left, rgba(226,226,226,0) 0%, rgba(226,226,226,1) 100%); } /* Draggable thumbnail **********************************************/ #properties { width: 400px; display: inline-block; vertical-align: top; } #thumbnail { width: 400px; display: inline-block; } #full-image-viewport { height: 400px; width: 400px; overflow: hidden; border: solid thin black; } #full-image { position: relative; cursor: move; } /* Drag and drop upload *****************************************/ .drop-box { background: #F8F8F8; border: 5px dashed #DDD; border-radius: 7px; width: 300px; height: 200px; text-align: center; padding-top: 50px; font-size: 18pt; font-weight: bold; } .drop-box.dragover { border: 5px dashed blue; }
stevearm/filecabinet
couchapp/_attachments/css/main.css
CSS
apache-2.0
2,274
/** * Copyright 2017-2019 The GreyCat Authors. All rights reserved. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package greycat.internal.task; import greycat.*; import greycat.base.BaseNode; import greycat.plugin.Job; import greycat.struct.Buffer; class ActionDelete implements Action { @Override public void eval(final TaskContext ctx) { TaskResult previous = ctx.result(); DeferCounter counter = ctx.graph().newCounter(previous.size()); for (int i = 0; i < previous.size(); i++) { if (previous.get(i) instanceof BaseNode) { ((Node) previous.get(i)).drop(new Callback() { @Override public void on(Object result) { counter.count(); } }); } } counter.then(new Job() { @Override public void run() { previous.clear(); ctx.continueTask(); } }); } @Override public void serialize(final Buffer builder) { builder.writeString(CoreActionNames.DELETE); builder.writeChar(Constants.TASK_PARAM_OPEN); builder.writeChar(Constants.TASK_PARAM_CLOSE); } @Override public final String name() { return CoreActionNames.DELETE; } }
datathings/greycat
greycat/src/main/java/greycat/internal/task/ActionDelete.java
Java
apache-2.0
1,871
//Declare app level module which depends on filters, and services var SFApplicationAuth = angular.module('SFApplicationAuth.Auth',[]); SFApplicationAuth.config( [ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider ) { console.log("inciando bootstrap auth"); $stateProvider.state('auth', { url: '/auth', abstract: true, templateUrl: 'modules/auth/partials/template.html', data: { isPublic: true } }); $stateProvider.state('auth.login', { url: '/login', templateUrl: 'modules/auth/partials/login.html', controller: 'AuthController' }); $stateProvider.state('auth.logout', { url: '/logout', controller: 'LogoutController' }); $stateProvider.state('auth.reset-password', { url: '/reset-password', templateUrl: 'application/auth/partials/reset-password.html', controller: 'AuthController' }); }]); SFApplicationAuth.run(['$rootScope', '$state', '$location', '$log', 'authFactory', function($rootScope, $state, $location, $log, authFactory) { $log.log('Running Auth...'); $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { $log.log('$stateChangeStart'); if( toState && ( "data" in toState ) === true && ( "isPublic" in toState.data ) === true && toState.data.isPublic == true ) { $log.log( 'Public page...' ); } else if( toState && ( "data" in toState ) === true && ( ( "isPublic" in toState.data ) === false || ( "isPublic" in toState.data ) === true && toState.data.isPublic == false ) ) { $log.log( 'Private page...' ); /** * Check if has some webSession active and do the logout. */ if( ! authFactory.checkIsLogged() ) { $log.error( 'You don\'t have permission to access this area.' ); /** * Prevent Default action. */ event.preventDefault(); $log.log( 'Fazendo loggof' ); /** * Redirect to login */ $state.go( 'auth.logout' ); } } }); $rootScope.$on('$stateChangeSuccess', function(next, current) { $log.log('$stateChangeSuccess'); }); $rootScope.$on('$stateChangeError', function( event, toState, toParams, fromState, fromParams, rejection) { $log.log('$stateChangeError'); }); $rootScope.$on('$stateUpdate', function(next, current) { $log.log('$stateUpdate'); }); $rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams){ $log.log('$stateNotFound'); $log.log(unfoundState.to); // "lazy.state" $log.log(unfoundState.toParams); // {a:1, b:2} $log.log(unfoundState.options); // {inherit:false} + default options }); $rootScope.$on('$viewContentLoading', function(event, viewConfig){ $log.log('$viewContentLoading'); }); $rootScope.$on('$viewContentLoaded', function(event, viewConfig){ $log.log('$viewContentLoaded'); }); }]);
chacal88/sb-admin-angular
app/modules/auth/application/bootstrap.js
JavaScript
apache-2.0
2,840
package com.at.springboot.mybatis.po; public class JsonUser { /** * This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.JSON_USER_ID * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ private byte[] jsonUserId; /** * This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.USER_NAME * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ private String userName; /** * This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.LAST_LOGIN_RESULT * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ private String lastLoginResult; /** * This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.LAST_LOGIN_INFO * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ private String lastLoginInfo; /** * This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.JSON_USER_ID * @return the value of JSON_USER.JSON_USER_ID * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public byte[] getJsonUserId() { return jsonUserId; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.JSON_USER_ID * @param jsonUserId the value for JSON_USER.JSON_USER_ID * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public void setJsonUserId(byte[] jsonUserId) { this.jsonUserId = jsonUserId; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.USER_NAME * @return the value of JSON_USER.USER_NAME * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public String getUserName() { return userName; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.USER_NAME * @param userName the value for JSON_USER.USER_NAME * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.LAST_LOGIN_RESULT * @return the value of JSON_USER.LAST_LOGIN_RESULT * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public String getLastLoginResult() { return lastLoginResult; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.LAST_LOGIN_RESULT * @param lastLoginResult the value for JSON_USER.LAST_LOGIN_RESULT * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public void setLastLoginResult(String lastLoginResult) { this.lastLoginResult = lastLoginResult == null ? null : lastLoginResult.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.LAST_LOGIN_INFO * @return the value of JSON_USER.LAST_LOGIN_INFO * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public String getLastLoginInfo() { return lastLoginInfo; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.LAST_LOGIN_INFO * @param lastLoginInfo the value for JSON_USER.LAST_LOGIN_INFO * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public void setLastLoginInfo(String lastLoginInfo) { this.lastLoginInfo = lastLoginInfo == null ? null : lastLoginInfo.trim(); } }
alphatan/workspace_java
spring-boot-web-fps-demo/src/main/java/com/at/springboot/mybatis/po/JsonUser.java
Java
apache-2.0
3,937
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.stylehair.servicos; import br.com.stylehair.dao.AgendamentoDAO; import br.com.stylehair.entity.Agendamento; import com.google.gson.Gson; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; /** * * @author vinicius */ @Stateless @Path("agendamento") public class AgendamentoResource { @PersistenceContext(unitName = "StyleHairPU") private EntityManager em; private Gson gson = new Gson(); @Context private UriInfo context; @GET @Produces("application/json") public String getJson() { AgendamentoDAO dao = new AgendamentoDAO(em); List<Agendamento> agendamentos; agendamentos = dao.buscarTodosAgendamentos(); return gson.toJson(agendamentos); } @GET @Path("{agendamentoId}") @Produces("application/json") public String getAgendamento(@PathParam("agendamentoId") String id){ System.out.println("pegando o cliente"); Long n = Long.parseLong(id); System.out.println(n); AgendamentoDAO dao = new AgendamentoDAO(em); Agendamento agend = dao.consultarPorId(Agendamento.class, Long.parseLong(id)); return gson.toJson(agend); } @GET @Path("{buscardata}/{dia}/{mes}/{ano}") @Produces("application/json") public String getAgendamentoPorData(@PathParam("dia") String dia,@PathParam("mes") String mes,@PathParam("ano") String ano ) { AgendamentoDAO dao = new AgendamentoDAO(em); List<Agendamento> agendamentos; SimpleDateFormat dateFormat_hora = new SimpleDateFormat("HH:mm"); Date data = new Date(); String horaAtual = dateFormat_hora.format(data); System.out.println("hora Atual" + horaAtual); Date d1 = new Date(); SimpleDateFormat dateFormataData = new SimpleDateFormat("dd/MM/yyyy"); String dataHoje = dateFormataData.format(d1); System.out.println("dataHoje ----" + dataHoje + "-------- " + dia+"/"+mes+"/"+ano ); if(dataHoje.equalsIgnoreCase(dia+"/"+mes+"/"+ano)){ agendamentos = dao.buscarAgendamentoPorData(dia+"/"+mes+"/"+ano + " ",horaAtual); return gson.toJson(agendamentos); } agendamentos = dao.buscarAgendamentoPorData(dia+"/"+mes+"/"+ano + " ","08:00"); return gson.toJson(agendamentos); } @POST @Consumes("application/json") @Produces("application/json") public String salvarAgendamento(String agendamento) throws Exception{ Agendamento ag1 = gson.fromJson(agendamento, Agendamento.class); AgendamentoDAO dao = new AgendamentoDAO(em); return gson.toJson(dao.salvar(ag1)); } @PUT @Consumes("application/json") public void atualizarAgendamento(String agendamento) throws Exception { salvarAgendamento(agendamento); } }
ViniciusBezerra94/WsStyleHair
src/main/java/br/com/stylehair/servicos/AgendamentoResource.java
Java
apache-2.0
3,529
const spinny = 'div.spinny'; exports.command = function navigateTo (url, expectSpinny = true) { this.url('data:,'); // https://github.com/nightwatchjs/nightwatch/issues/1724 this.url(url); if (expectSpinny) { this.waitForElementVisible(spinny); this.waitForElementNotVisible(spinny); } return this; };
wwitzel3/awx
awx/ui/test/e2e/commands/navigateTo.js
JavaScript
apache-2.0
341
package com.sampleapp.base; import android.app.Application; import com.crashlytics.android.Crashlytics; import com.sampleapp.BuildConfig; import com.sampleapp.utils.UtilsModule; import io.fabric.sdk.android.Fabric; import timber.log.Timber; /** * Created by saveen_dhiman on 05-November-16. * Initialization of required libraries */ public class SampleApplication extends Application { private AppComponent mAppComponent; @Override public void onCreate() { super.onCreate(); Fabric.with(this, new Crashlytics()); //create component mAppComponent = DaggerAppComponent.builder() .utilsModule(new UtilsModule(this)).build(); //configure timber for logging if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } } public AppComponent getAppComponent() { return mAppComponent; } }
saveendhiman/SampleApp
app/src/main/java/com/sampleapp/base/SampleApplication.java
Java
apache-2.0
915
# Agrostis filiformis Vill. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Apera/Apera spica-venti/ Syn. Agrostis filiformis/README.md
Markdown
apache-2.0
182
<!-- Footer --> <footer class="text-center"> <div class="footer-above"> <div class="container"> <div class="row"> <div class="footer-col col-md-4"> <h3>{{ site.footer.location }}</h3> <p> {% for adress in site.address %} {{ adress.line }} <br> {% endfor %} </p> </div> <div class="footer-col col-md-4"> <h3>{{ site.footer.social }}</h3> <ul class="list-inline"> {% for network in site.social %} <li> <a href="{{ network.url }}" class="btn-social btn-outline"><i class="fa fa-fw fa-{{ network.title }}"></i></a> </li> {% endfor %} </ul> </div> <div class="footer-col col-md-4"> <h3>{{ site.footer.credits }}</h3> <p> {% for adress in site.credits %} {{ adress.line }} <br> {% endfor %} </p> </div> </div> </div> </div> <div class="footer-below"> <div class="container"> <div class="row"> <div class="col-lg-12"> Copyright &copy; {{ site.footer.copyright }} 20{{ site.time | date: '%y' }} </div> </div> </div> </div> </footer> <!-- Scroll to Top Button (Only visible on small and extra-small screen sizes) --> <div class="scroll-top page-scroll visible-xs visible-sm"> <a class="btn btn-primary" href="#page-top"> <i class="fa fa-chevron-up"></i> </a> </div>
coger/coger.github.io
_includes/footer.html
HTML
apache-2.0
2,062
/* * Copyright 2017 Axway Software * * 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.axway.ats.core.filesystem.exceptions; import java.io.File; import com.axway.ats.common.filesystem.FileSystemOperationException; /** * Exception thrown when a file does not exist */ @SuppressWarnings( "serial") public class FileDoesNotExistException extends FileSystemOperationException { /** * Constructor * * @param fileName name of the file which does not exist */ public FileDoesNotExistException( String fileName ) { super("File '" + fileName + "' does not exist"); } /** * Constructor * * @param file the file which does not exist */ public FileDoesNotExistException( File file ) { super("File '" + file.getPath() + "' does not exist"); } }
Axway/ats-framework
corelibrary/src/main/java/com/axway/ats/core/filesystem/exceptions/FileDoesNotExistException.java
Java
apache-2.0
1,344
package com.fasterxml.jackson.databind.node; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.io.NumberOutput; import com.fasterxml.jackson.databind.SerializerProvider; /** * Numeric node that contains simple 32-bit integer values. */ @SuppressWarnings("serial") public class IntNode extends NumericNode { // // // Let's cache small set of common value final static int MIN_CANONICAL = -1; final static int MAX_CANONICAL = 10; private final static IntNode[] CANONICALS; static { int count = MAX_CANONICAL - MIN_CANONICAL + 1; CANONICALS = new IntNode[count]; for (int i = 0; i < count; ++i) { CANONICALS[i] = new IntNode(MIN_CANONICAL + i); } } /** * Integer value this node contains */ protected final int _value; /* ************************************************ * Construction ************************************************ */ public IntNode(int v) { _value = v; } public static IntNode valueOf(int i) { if (i > MAX_CANONICAL || i < MIN_CANONICAL) return new IntNode(i); return CANONICALS[i - MIN_CANONICAL]; } /* /********************************************************** /* BaseJsonNode extended API /********************************************************** */ @Override public JsonToken asToken() { return JsonToken.VALUE_NUMBER_INT; } @Override public JsonParser.NumberType numberType() { return JsonParser.NumberType.INT; } /* /********************************************************** /* Overrridden JsonNode methods /********************************************************** */ @Override public boolean isIntegralNumber() { return true; } @Override public boolean isInt() { return true; } @Override public boolean canConvertToInt() { return true; } @Override public boolean canConvertToLong() { return true; } @Override public Number numberValue() { return Integer.valueOf(_value); } @Override public short shortValue() { return (short) _value; } @Override public int intValue() { return _value; } @Override public long longValue() { return (long) _value; } @Override public float floatValue() { return (float) _value; } @Override public double doubleValue() { return (double) _value; } @Override public BigDecimal decimalValue() { return BigDecimal.valueOf(_value); } @Override public BigInteger bigIntegerValue() { return BigInteger.valueOf(_value); } @Override public String asText() { return NumberOutput.toString(_value); } @Override public boolean asBoolean(boolean defaultValue) { return _value != 0; } @Override public final void serialize(JsonGenerator g, SerializerProvider provider) throws IOException { g.writeNumber(_value); } @Override public boolean equals(Object o) { if (o == this) return true; if (o == null) return false; if (o instanceof IntNode) { return ((IntNode) o)._value == _value; } return false; } @Override public int hashCode() { return _value; } }
FasterXML/jackson-databind
src/main/java/com/fasterxml/jackson/databind/node/IntNode.java
Java
apache-2.0
3,398
## AWS Health AWS_EBS_VOLUME_LOST **Note:** This instruction is deprecated. Please refer to the [stepbystep/README](https://github.com/aws/aws-health-tools/blob/master/automated-actions/AWS_EBS_VOLUME_LOST/stepbystep/README.md) for the latest instruction. --- ### Description Underlying hardware related to your EBS volume has failed, and the data associated with the volume is unrecoverable. If you have an EBS snapshot of the volume, you need to restore that volume from your snapshot. This tools checks if the failed volume has a snapshot and is part of a root volume on an EC2 instance. Tool will restore the instance root volume from latest snapshot automatically if it does, and upload the results to an Elasticsearch instance. Notification on update will be sent to SNS topic assigned. ### Core Functionality Stack > [![Launch EBS VOLUME LOST Stack into N. Virginia with CloudFormation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/cloudformation-launch-stack-button.png)](https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/new?stackName=AWSEBSVolLost&templateURL=https://s3.amazonaws.com/aws-health-tools-assets/cloudformation-templates/aws_ebs_vol_lost_cfn.yaml) ### Important App Stack > [![Launch IMPORTANT APP Stack into N. Virginia with CloudFormation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/cloudformation-launch-stack-button.png)](https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/new?stackName=AWSEBSVolLost&templateURL=https://s3.amazonaws.com/aws-health-tools-assets/cloudformation-templates/aws_ebs_vol_lost_importantapp-cfn.yaml) ### Setup 1. Launch the CloudFormation Core Functionality Stack (**aws_ebs_vol_lost_cfn.yaml**). * This template will build out the required Step and Lambda functions that will action a Personal Health Dashboard event. It also creates a small Elasticsearch domain for visualisation. 1. Launch the CloudFormation Important App stack (**aws_ebs_vol_lost_importantapp-cfn.yaml**). * This template will build out a mock application that will be impacted by an EBS service disruption. ##### Creating a Mock Event 1. With both CloudFormation stacks completed - copy the **VolumeId** from the Outputs of the **Important App** stack. 1. Replace all **vol-xxxxxxxxxxxxxxxxx** values in the **phd-mock-payload.json** with the copied value. 1. Modifiy the **time** to within the past 14 days in **phd-mock-event.json**. 1. Post the mock event to CloudWatch using the AWS CLI command **aws events put-events --entries file://phd-mock-event.json** - this will trigger a CloudWatch Rule that will in turn launch the Step Function to replace the volume. 1. Open the Kibana dashboard (the URL can be found in the Outputs of the **Core Functionality** Stack) 1. In Kibana, under **Management > Index Patterns**, create an index pattern named **phd-events** using **PhdEventTime** as the **Time Filter**. 1. Under **Management > Saved Objects**, import **elasticsearch-objects.json**, overwriting all objects, and using **phd-events** as the new index pattern. 1. Navigate to **Dashboard > PHD Events** to see the event(s). 1. Repeat steps 1 to 4 to create additional mock events. #### CloudFormation Choose **Launch Stack** to launch the CloudFormation template in the US East (N. Virginia) Region in your account: The **Core Functionality** CloudFormation template requires the following parameters: * *SNSTopicName* - Enter the SNS topic to send notification to - this must exist in US East (N. Virginia) region * *PublicCidr* - The public IP from which Kibana will be accessible * *SubnetIds* - Two public subnets for Kibana access * *VpcId* - The VPC to which the subnets belong The **Important App** CloudFormation template requires the following parameters: * *InstanceType* - The size of the EC2 Instance * *KeyName* - The Keypair used to access the EC2 Instance * *RestoreImageId* - Leave blank. This is used by the Step Function for automatic replacement * *SSHLocation* - The public IP from wich the EC2 Instance wil be accessible * *SubnetId* - The subnet in which the EC2 Instance will reside * *VpcId* - The VPC to which the subnet belongs #### Disclaimer These CloudFormation templates are for demo and proof-of-concept purposes only. They and are not intended for production environments. Amongst other deficiencies, they: * do not follow the rule of least privileged access, and will create IAM Roles with the 'AdministratorAccess' AWS Managed policy * will serve public traffic from the Elasticsearch domain over unencrypted HTTP connections ### License AWS Health Tools are licensed under the Apache 2.0 License.
chetankrishna08/aws-health-tools
automated-actions/AWS_EBS_VOLUME_LOST/SydneySummitDemo/readme.md
Markdown
apache-2.0
4,703
package lena.lerning.selenium; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.concurrent.TimeUnit; import static org.openqa.selenium.support.ui.ExpectedConditions.titleContains; /** * Created by Lena on 01/05/2017. */ public class EdgeTest { private WebDriver driver; private WebDriverWait wait; @Before public void edgeStart(){ driver = new EdgeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @Test public void firstTest(){ driver.get("http://www.google.com"); driver.findElement(By.name("q")).sendKeys("webdriver"); driver.findElement(By.name("q")).sendKeys(Keys.ENTER); wait.until(titleContains("webdriver")); } @After public void stop(){ driver.quit(); driver=null; } }
etarnovskaya/sel_6_Lena
sel-test/src/test/java/lena/lerning/selenium/EdgeTest.java
Java
apache-2.0
1,062
package com.twitter.finagle.mdns import com.twitter.finagle.{Announcer, Announcement, Resolver, Addr, Address} import com.twitter.util.{Future, Return, Throw, Try, Var} import java.lang.management.ManagementFactory import java.net.{InetSocketAddress, SocketAddress} import scala.collection.mutable class MDNSAddressException(addr: String) extends Exception("Invalid MDNS address \"%s\"".format(addr)) private case class MdnsAddrMetadata( name: String, regType: String, domain: String) private object MdnsAddrMetadata { private val key = "mdns_addr_metadata" def toAddrMetadata(metadata: MdnsAddrMetadata) = Addr.Metadata(key -> metadata) def fromAddrMetadata(metadata: Addr.Metadata): Option[MdnsAddrMetadata] = metadata.get(key) match { case some@Some(_: MdnsAddrMetadata) => some.asInstanceOf[Option[MdnsAddrMetadata]] case _ => None } def unapply(metadata: Addr.Metadata): Option[(String, String, String)] = fromAddrMetadata(metadata).map { case MdnsAddrMetadata(name, regType, domain) => (name, regType, domain) } } private trait MDNSAnnouncerIface { def announce( addr: InetSocketAddress, name: String, regType: String, domain: String): Future[Announcement] } private trait MDNSResolverIface { def resolve(regType: String, domain: String): Var[Addr] } private[mdns] object MDNS { lazy val pid = ManagementFactory.getRuntimeMXBean.getName.split("@") match { case Array(pid, _) => pid case _ => "unknown" } def mkName(ps: Any*) = ps.mkString("/") def parse(addr: String) = { addr.split("\\.").toList.reverse match { case domain :: prot :: app :: name => (name.reverse.mkString("."), app + "." + prot, domain) case _ => throw new MDNSAddressException(addr) } } } class MDNSAnnouncer extends Announcer { import MDNS._ val scheme = "mdns" private[this] val announcer: MDNSAnnouncerIface = try { new DNSSDAnnouncer } catch { case _: ClassNotFoundException => new JmDNSAnnouncer } /** * Announce an address via MDNS. * * The addr must be in the style of `[name]._[group]._tcp.local.` * (e.g. myservice._twitter._tcp.local.). In order to ensure uniqueness * the final name will be [name]/[port]/[pid]. */ def announce(ia: InetSocketAddress, addr: String): Future[Announcement] = { val (name, regType, domain) = parse(addr) val serviceName = mkName(name, ia.getPort, pid) announcer.announce(ia, serviceName, regType, domain) } } class MDNSResolver extends Resolver { import MDNS._ val scheme = "mdns" private[this] val resolver: MDNSResolverIface = try { new DNSSDResolver } catch { case _: ClassNotFoundException => new JmDNSResolver } /** * Resolve a service via mdns * * The address must be in the style of `[name]._[group]._tcp.local.` * (e.g. "myservice._twitter._tcp.local."). */ def bind(arg: String): Var[Addr] = { val (name, regType, domain) = parse(arg) resolver.resolve(regType, domain) map { case Addr.Bound(addrs, attrs) => val filtered = addrs.filter { case Address.Inet(ia, MdnsAddrMetadata(n, _, _)) => n.startsWith(name) case _ => false } Addr.Bound(filtered, attrs) case a => a } } }
lukiano/finagle
finagle-mdns/src/main/scala/com/twitter/finagle/mdns/MDNS.scala
Scala
apache-2.0
3,301
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.common.notification.exception; /** * This exception is thrown if the given role id is not known to the given context. */ public class UnknownRoleException extends Exception { private static final long serialVersionUID = -1925770520412550327L; private final String roleId; private final String context; /** * Constructs an Unknown Role exception. * * @param roleId * @param context */ public UnknownRoleException(final String roleId, final String context) { super("Role " + roleId + " not recognized for context " + context); this.roleId = roleId; this.context = context; } public String getRoleId() { return roleId; } public String getContext() { return context; } }
vivantech/kc_fixes
src/main/java/org/kuali/kra/common/notification/exception/UnknownRoleException.java
Java
apache-2.0
1,435
package org.develnext.jphp.android.ext.classes.app; import android.os.Bundle; import org.develnext.jphp.android.AndroidStandaloneLoader; import org.develnext.jphp.android.ext.AndroidExtension; import php.runtime.annotation.Reflection; @Reflection.Name(AndroidExtension.NAMESPACE + "app\\BootstrapActivity") public class WrapBootstrapActivity extends WrapActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreateClearly(savedInstanceState); AndroidStandaloneLoader.INSTANCE.run(this); getEnvironment().invokeMethodNoThrow(this, "onCreate"); } }
livingvirus/jphp
jphp-android/src/main/java/org/develnext/jphp/android/ext/classes/app/WrapBootstrapActivity.java
Java
apache-2.0
616
package com.truward.brikar.maintenance.log.processor; import com.truward.brikar.common.log.LogUtil; import com.truward.brikar.maintenance.log.CommaSeparatedValueParser; import com.truward.brikar.maintenance.log.Severity; import com.truward.brikar.maintenance.log.message.LogMessage; import com.truward.brikar.maintenance.log.message.MaterializedLogMessage; import com.truward.brikar.maintenance.log.message.MultiLinePartLogMessage; import com.truward.brikar.maintenance.log.message.NullLogMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Message processor that converts a line into a message. * * @author Alexander Shabanov */ @ParametersAreNonnullByDefault public final class LogMessageProcessor { public static final Pattern RECORD_PATTERN = Pattern.compile( "^(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}) " + // date+time "(\\p{Upper}+) " + // severity "([\\w\\p{Punct}]+) " + // class name "((?:[\\w]+=[\\w\\+/.\\$]+)(?:, (?:[\\w]+=[\\w\\+/\\.\\$]+))*)? " + // variables "\\[[\\w\\p{Punct}&&[^\\]]]+\\] " + // thread ID "(.+)" + // message "$" ); private static final String METRIC_MARKER = LogUtil.METRIC_ENTRY + ' '; private final Logger log = LoggerFactory.getLogger(getClass()); private final DateFormat dateFormat; public LogMessageProcessor() { this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } public LogMessage parse(String line, LogMessage previousMessage) { if (previousMessage.hasMetrics() && line.startsWith("\t")) { // special case: this line is a continuation of metrics entry started on the previous line final MaterializedLogMessage logMessage = new MaterializedLogMessage(previousMessage.getUnixTime(), previousMessage.getSeverity(), line); addAttributesFromMetrics(logMessage, line.substring(1)); return logMessage; } final Matcher matcher = RECORD_PATTERN.matcher(line); if (!matcher.matches()) { return new MultiLinePartLogMessage(line); } if (matcher.groupCount() < 5) { log.error("Count of groups is not six: actual={} for line={}", matcher.groupCount(), line); return NullLogMessage.INSTANCE; // should not happen } final Date date; try { date = dateFormat.parse(matcher.group(1)); } catch (ParseException e) { log.error("Malformed date in line={}", line, e); return NullLogMessage.INSTANCE; // should not happen } final Severity severity = Severity.fromString(matcher.group(2), Severity.WARN); final MaterializedLogMessage logMessage = new MaterializedLogMessage(date.getTime(), severity, line); addAttributesFromVariables(logMessage, matcher.group(4)); final String message = matcher.group(5); if (message != null) { final int metricIndex = message.indexOf(METRIC_MARKER); if (metricIndex >= 0) { addAttributesFromMetrics(logMessage, message.substring(metricIndex + METRIC_MARKER.length())); } } return logMessage; } // // Private // private void addAttributesFromMetrics(MaterializedLogMessage logMessage, String metricBody) { putAllAttributes(logMessage, new CommaSeparatedValueParser(metricBody).readAsMap()); } private void addAttributesFromVariables(MaterializedLogMessage logMessage, @Nullable String variables) { if (variables != null) { putAllAttributes(logMessage, new CommaSeparatedValueParser(variables).readAsMap()); } } private void putAllAttributes(MaterializedLogMessage logMessage, Map<String, String> vars) { for (final Map.Entry<String, String> entry : vars.entrySet()) { final String key = entry.getKey(); final Object value; if (LogUtil.TIME_DELTA.equals(key)) { value = Long.parseLong(entry.getValue()); } else if (LogUtil.START_TIME.equals(key)) { value = Long.parseLong(entry.getValue()); } else if (LogUtil.COUNT.equals(key)) { value = Long.parseLong(entry.getValue()); } else if (LogUtil.FAILED.equals(key)) { value = Boolean.valueOf(entry.getValue()); } else { value = entry.getValue(); } logMessage.putAttribute(key, value); } } }
truward/brikar
brikar-maintenance/src/main/java/com/truward/brikar/maintenance/log/processor/LogMessageProcessor.java
Java
apache-2.0
4,636
using UnityEngine; using System.Collections; namespace MagicalFX { public class FX_SpawnDirection : MonoBehaviour { public int Number = 10; public float Frequency = 1; public bool FixRotation = false; public bool Normal; public GameObject FXSpawn; public float LifeTime = 0; public float TimeSpawn = 0; private float timeTemp; public bool UseObjectForward = true; public Vector3 Direction = Vector3.forward; void Start () { counter = 0; timeTemp = Time.time; if (TimeSpawn <= 0) { for (int i=0; i<Number-1; i++) { if (UseObjectForward) { Direction = this.transform.forward; } Spawn (this.transform.position + (Direction * Frequency * i)); } Destroy(this.gameObject); } } private int counter = 0; void Update () { if(counter >= Number-1) Destroy(this.gameObject); if (TimeSpawn > 0.0f) { if (Time.time > timeTemp + TimeSpawn) { if (UseObjectForward) { Direction = this.transform.forward; } Spawn (this.transform.position + (Direction * Frequency * counter)); counter+=1; timeTemp = Time.time; } } } void Spawn (Vector3 position) { if (FXSpawn != null) { Quaternion rotate = this.transform.rotation; if (!FixRotation) rotate = FXSpawn.transform.rotation; GameObject fx = (GameObject)GameObject.Instantiate (FXSpawn, position, rotate); if (Normal) fx.transform.forward = this.transform.forward; if (LifeTime > 0) GameObject.Destroy (fx.gameObject, LifeTime); } } } }
yimogod/boom
trunk/effect/Assets/Magical/Sources/Scripts/FX_SpawnDirection.cs
C#
apache-2.0
1,578
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="generator" content="Source Themes Academic 3.1.1"> <meta name="generator" content="Hugo 0.55.6" /> <meta name="author" content="Gregor von Laszewski"> <meta name="description" content="Home page of Gregor von Laszewski"> <link rel="alternate" hreflang="en-us" href="http://laszewski.github.io/proceeding/"> <meta name="theme-color" content="#3f51b5"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha256-eSi1q2PG6J7g7ib17yAaWMcrr5GrtohYChqibrV7PBE=" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" integrity="sha256-ygkqlh3CYSUri3LhQxzdcm0n1EQvH2Y+U5S2idbLtxs=" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Montserrat:400,700|Roboto:400,400italic,700|Roboto+Mono"> <link rel="stylesheet" href="/styles.css"> <link rel="alternate" href="http://laszewski.github.io/proceeding/index.xml" type="application/rss+xml" title="Gregor von Laszewski"> <link rel="feed" href="http://laszewski.github.io/proceeding/index.xml" type="application/rss+xml" title="Gregor von Laszewski"> <link rel="manifest" href="/site.webmanifest"> <link rel="icon" type="image/png" href="/img/icon.png"> <link rel="apple-touch-icon" type="image/png" href="/img/icon-192.png"> <link rel="canonical" href="http://laszewski.github.io/proceeding/"> <meta property="twitter:card" content="summary_large_image"> <meta property="og:site_name" content="Gregor von Laszewski"> <meta property="og:url" content="http://laszewski.github.io/proceeding/"> <meta property="og:title" content="Proceedings | Gregor von Laszewski"> <meta property="og:description" content="Home page of Gregor von Laszewski"> <meta property="og:image" content="http://laszewski.github.io/img/icon-192.png"> <meta property="og:locale" content="en-us"> <meta property="og:updated_time" content="2017-01-01T00:00:00-05:00"> <title>Proceedings | Gregor von Laszewski</title> </head> <body id="top" data-spy="scroll" data-target="#TableOfContents" data-offset="71" > <aside class="search-results" id="search"> <div class="container"> <section class="search-header fixed-top"> <div class="row no-gutters justify-content-between mb-3"> <div class="col-6"> <h1>Search</h1> </div> <div class="col-6 col-search-close"> <a class="js-search" href="#"><i class="fas fa-times-circle text-muted" aria-hidden="true"></i></a> </div> </div> <div id="search-box"> <input name="q" id="search-query" placeholder="Search..." autocapitalize="off" autocomplete="off" autocorrect="off" role="textbox" spellcheck="false" type="search"> </div> </section> <section class="section-search-results"> <div id="search-hits"> </div> </section> </div> </aside> <nav class="navbar navbar-light fixed-top navbar-expand-lg py-0" id="navbar-main"> <div class="container"> <a class="navbar-brand" href="/">Gregor von Laszewski</a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation"> <span><i class="fas fa-bars"></i></span> </button> <div class="collapse navbar-collapse" id="navbar"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="/#about"> <span>Home</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/publication"> <span>Publications</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/#projects"> <span>Projects</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/#books"> <span>Books</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/#proceedings"> <span>Proceedings</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/#history"> <span>History</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/post/shuttle"> <span>Free Shuttle</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/#contact"> <span>Contact</span> </a> </li> <li class="nav-item"> <a class="nav-link js-search" href="#"><i class="fas fa-search" aria-hidden="true"></i></a> </li> </ul> </div> </div> </nav> <div class="universal-wrapper pt-3"> <h1 itemprop="name">Proceedings</h1> </div> <div class="universal-wrapper"> <div> <h2><a href="/proceeding/e516-sp20-proceeding/">E516 - Spring 2020 Proceedings</a></h2> <div class="article-style"> Here you find the Documents produced by the students for this class. Please note that some may be edited by Gregor von Laszewski or the support staff for this class. We try to update this document frequently. The best we to read them is with an ePub reader. If you do not have one you also use the PDF version. However, PDF does not render as well as ePub. </div> </div> <div> <h2><a href="/proceeding/e516-sp19-proceeding/">E516 - Fall 2019 Proceedings</a></h2> <div class="article-style"> Here you find the Documents produced by the students for this class. Please note that some may be edited by Gregor von Laszewski or the support staff for this class. We try to update this document frequently. The best we to read them is with an ePub reader. If you do not have one you also use the PDF version. However, PDF does not render as well as ePub. </div> </div> </div> <div class="container"> <footer class="site-footer"> <p class="powered-by"> &copy; Gregor von Laszewski, 2018-2020 &middot; <span class="float-right" aria-hidden="true"> <a href="#" id="back_to_top"> <span class="button_icon"> <i class="fas fa-chevron-up fa-2x"></i> </span> </a> </span> </p> </footer> </div> <div id="modal" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Cite</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <pre><code class="tex hljs"></code></pre> </div> <div class="modal-footer"> <a class="btn btn-outline-primary my-1 js-copy-cite" href="#" target="_blank"> <i class="fas fa-copy"></i> Copy </a> <a class="btn btn-outline-primary my-1 js-download-cite" href="#" target="_blank"> <i class="fas fa-download"></i> Download </a> <div id="modal-error"></div> </div> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha512-+NqPlbbtM1QqiK8ZAo4Yrj2c4lNQoGv8P79DPtKzj++l5jnN39rHA/xsqn8zE9l0uSoxaCdrOgFs6yjyfbBxSg==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.3/imagesloaded.pkgd.min.js" integrity="sha512-umsR78NN0D23AzgoZ11K7raBD+R6hqKojyBZs1w8WvYlsI+QuKRGBx3LFCwhatzBunCjDuJpDHwxD13sLMbpRA==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha256-VsEqElsCHSGmnmHXGQzvoWjWwoznFSZc6hs7ARLRacQ=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.4/isotope.pkgd.min.js" integrity="sha512-VDBOIlDbuC4VWxGJNmuFRQ0Li0SKkDpmGyuhAG5LTDLd/dJ/S0WMVxriR2Y+CyPL5gzjpN4f/6iqWVBJlht0tQ==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" integrity="sha256-X5PoE3KU5l+JcX+w09p/wHl9AzK333C4hJ2I9S5mD4M=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js" integrity="sha256-/BfiIkHlHoVihZdc6TFuj7MmJ0TWcWsMXkeDFwhi0zw=" crossorigin="anonymous"></script> <script>hljs.initHighlightingOnLoad();</script> <script> const search_index_filename = "/index.json"; const i18n = { 'placeholder': "Search...", 'results': "results found", 'no_results': "No results found" }; const content_type = { 'post': "Posts", 'project': "Projects", 'publication' : "Publications", 'talk' : "Talks" }; </script> <script id="search-hit-fuse-template" type="text/x-template"> <div class="search-hit" id="summary-{{key}}"> <div class="search-hit-content"> <div class="search-hit-name"> <a href="{{relpermalink}}">{{title}}</a> <div class="article-metadata search-hit-type">{{type}}</div> <p class="search-hit-description">{{snippet}}</p> </div> </div> </div> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js" integrity="sha256-VzgmKYmhsGNNN4Ph1kMW+BjoYJM2jV5i4IlFoeZA9XI=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js" integrity="sha256-4HLtjeVgH0eIB3aZ9mLYF6E8oU5chNdjU6p6rrXpl9U=" crossorigin="anonymous"></script> <script src="/js/academic.min.14cafafda844d960749b7551524d1c3a.js"></script> </body> </html>
laszewski/laszewski.github.io
backup/proceeding/index.html
HTML
apache-2.0
12,133
package ru.job4j.servlet.services; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.job4j.servlet.model.User; import ru.job4j.servlet.repository.RepositoryException; import ru.job4j.servlet.repository.UserStore; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * UpdateUserController. * * @author Stanislav ([email protected]) * @since 11.01.2018 */ public class UpdateUserController extends HttpServlet { private static final Logger LOG = LoggerFactory.getLogger(UpdateUserController.class); private static final long serialVersionUID = 6328444530140780881L; private UserStore userStore = UserStore.getInstance(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { User user = userStore.findByID(Integer.valueOf(req.getParameter("id"))); if (user != null) { String name = req.getParameter("name"); String login = req.getParameter("login"); String email = req.getParameter("email"); if (name != null && !name.trim().isEmpty()) { user.setName(name); } if (login != null && !login.trim().isEmpty()) { user.setLogin(login); } if (email != null && !email.trim().isEmpty()) { user.setEmail(email); } userStore.update(user); } } catch (NumberFormatException e) { LOG.error("Not the correct format id. ", e); } catch (RepositoryException e) { LOG.error("Error adding user. ", e); } resp.sendRedirect(req.getContextPath().length() == 0 ? "/" : req.getContextPath()); } }
StanislavEsin/estanislav
chapter_007/src/main/java/ru/job4j/servlet/services/UpdateUserController.java
Java
apache-2.0
1,967
package com.kenshin.windystreet.db; import org.litepal.crud.DataSupport; /** * Created by Kenshin on 2017/4/3. */ public class County extends DataSupport { private int id; //编号 private String countyName; //县名 private String weatherId; //对应的天气id private int cityId; //所属市的id public void setId(int id) { this.id = id; } public void setCountyName(String countyName) { this.countyName = countyName; } public void setWeatherId(String weatherId) { this.weatherId = weatherId; } public void setCityId(int cityId) { this.cityId = cityId; } public int getId() { return id; } public String getCountyName() { return countyName; } public String getWeatherId() { return weatherId; } public int getCityId() { return cityId; } }
Asucanc/Windy-Street-Weather
app/src/main/java/com/kenshin/windystreet/db/County.java
Java
apache-2.0
901
/* * Copyright 2016-present Facebook, 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.facebook.buck.core.model.actiongraph; import com.facebook.buck.core.rules.BuildRuleResolver; import com.facebook.buck.core.util.immutables.BuckStyleImmutable; import org.immutables.value.Value; /** Holds an ActionGraph with the BuildRuleResolver that created it. */ @Value.Immutable @BuckStyleImmutable interface AbstractActionGraphAndResolver { @Value.Parameter ActionGraph getActionGraph(); @Value.Parameter BuildRuleResolver getResolver(); }
LegNeato/buck
src/com/facebook/buck/core/model/actiongraph/AbstractActionGraphAndResolver.java
Java
apache-2.0
1,075
# -*- coding: utf-8 -*- # # 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. import unittest from cryptography.fernet import Fernet from airflow import settings from airflow.models import Variable, crypto from tests.test_utils.config import conf_vars class TestVariable(unittest.TestCase): def setUp(self): crypto._fernet = None def tearDown(self): crypto._fernet = None @conf_vars({('core', 'fernet_key'): ''}) def test_variable_no_encryption(self): """ Test variables without encryption """ Variable.set('key', 'value') session = settings.Session() test_var = session.query(Variable).filter(Variable.key == 'key').one() self.assertFalse(test_var.is_encrypted) self.assertEqual(test_var.val, 'value') @conf_vars({('core', 'fernet_key'): Fernet.generate_key().decode()}) def test_variable_with_encryption(self): """ Test variables with encryption """ Variable.set('key', 'value') session = settings.Session() test_var = session.query(Variable).filter(Variable.key == 'key').one() self.assertTrue(test_var.is_encrypted) self.assertEqual(test_var.val, 'value') def test_var_with_encryption_rotate_fernet_key(self): """ Tests rotating encrypted variables. """ key1 = Fernet.generate_key() key2 = Fernet.generate_key() with conf_vars({('core', 'fernet_key'): key1.decode()}): Variable.set('key', 'value') session = settings.Session() test_var = session.query(Variable).filter(Variable.key == 'key').one() self.assertTrue(test_var.is_encrypted) self.assertEqual(test_var.val, 'value') self.assertEqual(Fernet(key1).decrypt(test_var._val.encode()), b'value') # Test decrypt of old value with new key with conf_vars({('core', 'fernet_key'): ','.join([key2.decode(), key1.decode()])}): crypto._fernet = None self.assertEqual(test_var.val, 'value') # Test decrypt of new value with new key test_var.rotate_fernet_key() self.assertTrue(test_var.is_encrypted) self.assertEqual(test_var.val, 'value') self.assertEqual(Fernet(key2).decrypt(test_var._val.encode()), b'value')
Fokko/incubator-airflow
tests/models/test_variable.py
Python
apache-2.0
3,100
# Stilbum clavaeforme (Preuss) Goid. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Annali Bot. (Torino) 21: 49 (1935) #### Original name Stilbum claviforme (Preuss) Goid. ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricostilbomycetes/Agaricostilbales/Chionosphaeraceae/Stilbum/Stilbum clavaeforme/README.md
Markdown
apache-2.0
226
package water.api; import org.reflections.Reflections; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import hex.schemas.ModelBuilderSchema; import water.DKV; import water.H2O; import water.Iced; import water.Job; import water.Key; import water.Value; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.H2OKeyNotFoundArgumentException; import water.exceptions.H2ONotFoundArgumentException; import water.fvec.Frame; import water.util.IcedHashMap; import water.util.Log; import water.util.MarkdownBuilder; import water.util.Pair; import water.util.PojoUtils; import water.util.ReflectionUtils; /** * Base Schema class; all REST API Schemas inherit from here. * <p> * The purpose of Schemas is to provide a stable, versioned interface to * the functionality in H2O, which allows the back end implementation to * change rapidly without breaking REST API clients such as the Web UI * and R and Python bindings. Schemas also allow for functionality which exposes the * schema metadata to clients, allowing them to do service discovery and * to adapt dynamically to new H2O functionality, e.g. to be able to call * any ModelBuilder, even new ones written since the client was built, * without knowing any details about the specific algo. * <p> * In most cases, Java developers who wish to expose new functionality through the * REST API will need only to define their schemas with the fields that they * wish to expose, adding @API annotations to denote the field metadata. * Their fields will be copied back and forth through the reflection magic in this * class. If there are fields they have to adapt between the REST API representation * and the back end this can be done piecemeal by overriding the fill* methods, calling * the versions in super, and making only those changes that are absolutely necessary. * A lot of work has gone into avoiding boilerplate code. * <p> * Schemas are versioned for stability. When you look up the schema for a given impl * object or class you supply a version number. If a schema for that version doesn't * exist then the versions are searched in reverse order. For example, if you ask for * version 5 and the highest schema version for that impl class is 3 then V3 will be returned. * This allows us to move to higher versions without having to write gratuitous new schema * classes for the things that haven't changed in the new version. * <p> * The current version can be found by calling * Schema.getHighestSupportedVersion(). For schemas that are still in flux * because development is ongoing we also support an EXPERIMENTAL_VERSION, which * indicates that there are no interface stability guarantees between H2O versions. * Eventually these schemas will move to a normal, stable version number. Call * Schema.getExperimentalVersion() to find the experimental version number (99 as * of this writing). * <p> * Schema names must be unique within an application in a single namespace. The * class getSimpleName() is used as the schema name. During Schema discovery and * registration there are checks to ensure that the names are unique. * <p> * Most schemas have a 1-to-1 mapping to an Iced implementation object, aka the "impl" * or implementation class. This class is specified as a type parameter to the Schema class. * This type parameter is used by reflection magic to avoid a large amount of boilerplate * code. * <p> * Both the Schema and the Iced object may have children, or (more often) not. * Occasionally, e.g. in the case of schemas used only to handle HTTP request * parameters, there will not be a backing impl object and the Schema will be * parameterized by Iced. * <p> * Other than Schemas backed by Iced this 1-1 mapping is enforced: a check at Schema * registration time ensures that at most one Schema is registered for each Iced class. * This 1-1 mapping allows us to have generic code here in the Schema class which does * all the work for common cases. For example, one can write code which accepts any * Schema instance and creates and fills an instance of its associated impl class: * {@code * I impl = schema.createAndFillImpl(); * } * <p> * Schemas have a State section (broken into Input, Output and InOut fields) * and an Adapter section. The adapter methods fill the State to and from the * Iced impl objects and from HTTP request parameters. In the simple case, where * the backing object corresponds 1:1 with the Schema and no adapting need be * done, the methods here in the Schema class will do all the work based on * reflection. In that case your Schema need only contain the fields you wish * to expose, and no adapter code. * <p> * Methods here allow us to convert from Schema to Iced (impl) and back in a * flexible way. The default behaviour is to map like-named fields back and * forth, often with some default type conversions (e.g., a Keyed object like a * Model will be automagically converted back and forth to a Key). * Subclasses can override methods such as fillImpl or fillFromImpl to * provide special handling when adapting from schema to impl object and back. * Usually they will want to call super to get the default behavior, and then * modify the results a bit (e.g., to map differently-named fields, or to * compute field values). * <p> * Schema Fields must have a single @API annotation describing their direction * of operation and any other properties such as "required". Fields are * API.Direction.INPUT by default. Transient and static fields are ignored. * <p> * Most Java developers need not be concerned with the details that follow, because the * framework will make these calls as necessary. * <p> * Some use cases: * <p> * To find and create an instance of the appropriate schema for an Iced object, with the * given version or the highest previous version:<pre> * Schema s = Schema.schema(6, impl); * </pre> * <p> * To create a schema object and fill it from an existing impl object (the common case):<pre> * S schema = MySchemaClass(version).fillFromImpl(impl);</pre> * or more generally: * <pre> * S schema = Schema(version, impl).fillFromImpl(impl);</pre> * To create an impl object and fill it from an existing schema object (the common case): * <pre> * I impl = schema.createImpl(); // create an empty impl object and any empty children * schema.fillImpl(impl); // fill the empty impl object and any children from the Schema and its children</pre> * or * <pre> * I impl = schema.createAndFillImpl(); // helper which does schema.fillImpl(schema.createImpl())</pre> * <p> * Schemas that are used for HTTP requests are filled with the default values of their impl * class, and then any present HTTP parameters override those default values. * <p> * To create a schema object filled from the default values of its impl class and then * overridden by HTTP request params: * <pre> * S schema = MySchemaClass(version); * I defaults = schema.createImpl(); * schema.fillFromImpl(defaults); * schema.fillFromParms(parms); * </pre> * or more tersely: * <pre> * S schema = MySchemaClass(version).fillFromImpl(schema.createImpl()).fillFromParms(parms); * </pre> * @see Meta#getSchema_version() * @see Meta#getSchema_name() * @see Meta#getSchema_type() * @see water.api.API */ public class Schema<I extends Iced, S extends Schema<I,S>> extends Iced { private transient Class<I> _impl_class = getImplClass(); // see getImplClass() private static final int HIGHEST_SUPPORTED_VERSION = 3; private static final int EXPERIMENTAL_VERSION = 99; /** * Metadata for a Schema, including the version, name and type. This information is included in all REST API * responses as a field in the Schema so that the payloads are self-describing, and it is also available through * the /Metadata/schemas REST API endpoint for the purposes of REST service discovery. */ public static final class Meta extends Iced { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CAREFUL: This class has its own JSON serializer. If you add a field here you probably also want to add it to the serializer! //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version, meaning that * there are no stability guarantees between H2O versions. */ @API(help="Version number of this Schema. Must not be changed after creation (treat as final).", direction=API.Direction.OUTPUT) private int schema_version; /** Get the simple schema (class) name, for example DeepLearningParametersV3. Must not be changed after creation (treat as final). */ @API(help="Simple name of this Schema. NOTE: the schema_names form a single namespace.", direction=API.Direction.OUTPUT) private String schema_name; /** Get the simple name of H2O type that this Schema represents, for example DeepLearningParameters. */ @API(help="Simple name of H2O type that this Schema represents. Must not be changed after creation (treat as final).", direction=API.Direction.OUTPUT) private String schema_type; // subclasses can redefine this /** Default constructor used only for newInstance() in generic reflection-based code. */ public Meta() {} /** Standard constructor which supplies all the fields. The fields should be treated as immutable once set. */ public Meta(int version, String name, String type) { this.schema_version = version; this.schema_name = name; this.schema_type = type; } /** * Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version, * meaning that there are no stability guarantees between H2O versions. */ public int getSchema_version() { return schema_version; } /** Get the simple schema (class) name, for example DeepLearningParametersV3. */ public String getSchema_name() { return schema_name; } /** Get the simple name of the H2O type that this Schema represents, for example DeepLearningParameters. */ public String getSchema_type() { return schema_type; } /** Set the simple name of the H2O type that this Schema represents, for example Key&lt;Frame&gt;. NOTE: using this is a hack and should be avoided. */ protected void setSchema_type(String schema_type) { this.schema_type = schema_type; } // TODO: make private in Iced: /** Override the JSON serializer to prevent a recursive loop in AutoBuffer. User code should not call this, and soon it should be made protected. */ @Override public final water.AutoBuffer writeJSON_impl(water.AutoBuffer ab) { // Overridden because otherwise we get in a recursive loop trying to serialize this$0. ab.putJSON4("schema_version", schema_version) .put1(',').putJSONStr("schema_name", schema_name) .put1(',').putJSONStr("schema_type", schema_type); return ab; } } @API(help="Metadata on this schema instance, to make it self-describing.", direction=API.Direction.OUTPUT) private Meta __meta = null; /** Get the metadata for this schema instance which makes it self-describing when serialized to JSON. */ protected Meta get__meta() { return __meta; } // Registry which maps a simple schema name to its class. NOTE: the simple names form a single namespace. // E.g., "DeepLearningParametersV2" -> hex.schemas.DeepLearningV2.DeepLearningParametersV2 private static Map<String, Class<? extends Schema>> schemas = new HashMap<>(); // Registry which maps a Schema simpleName to its Iced Class. // E.g., "DeepLearningParametersV2" -> hex.deeplearning.DeepLearning.DeepLearningParameters private static Map<String, Class<? extends Iced>> schema_to_iced = new HashMap<>(); // Registry which maps an Iced simpleName (type) and schema_version to its Schema Class. // E.g., (DeepLearningParameters, 2) -> "DeepLearningParametersV2" // // Note that iced_to_schema gets lazily filled if a higher version is asked for than is // available (e.g., if the highest version of Frame is FrameV2 and the client asks for // the schema for (Frame, 17) then FrameV2 will be returned, and all the mappings between // 17 and 3 will get added to the Map. private static Map<Pair<String, Integer>, Class<? extends Schema>> iced_to_schema = new HashMap<>(); /** * Default constructor; triggers lazy schema registration. * @throws water.exceptions.H2OFailException if there is a name collision or there is more than one schema which maps to the same Iced class */ public Schema() { String name = this.getClass().getSimpleName(); int version = extractVersion(name); String type = _impl_class.getSimpleName(); __meta = new Meta(version, name, type); if (null == schema_to_iced.get(name)) { Log.debug("Registering schema: " + name + " schema_version: " + version + " with Iced class: " + _impl_class.toString()); if (null != schemas.get(name)) throw H2O.fail("Found a duplicate schema name in two different packages: " + schemas.get(name) + " and: " + this.getClass().toString()); schemas.put(name, this.getClass()); schema_to_iced.put(name, _impl_class); if (_impl_class != Iced.class) { Pair versioned = new Pair(type, version); // Check for conflicts if (null != iced_to_schema.get(versioned)) { throw H2O.fail("Found two schemas mapping to the same Iced class with the same version: " + iced_to_schema.get(versioned) + " and: " + this.getClass().toString() + " both map to version: " + version + " of Iced class: " + _impl_class); } iced_to_schema.put(versioned, this.getClass()); } } } private static Pattern _version_pattern = null; /** Extract the version number from the schema class name. Returns -1 if there's no version number at the end of the classname. */ private static int extractVersion(String clz_name) { if (null == _version_pattern) // can't just use a static initializer _version_pattern = Pattern.compile(".*V(\\d+)"); Matcher m = _version_pattern.matcher(clz_name); if (! m.matches()) return -1; return Integer.valueOf(m.group(1)); } /** * Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version, meaning that * there are no stability guarantees between H2O versions. */ public int getSchemaVersion() { return __meta.schema_version; } private static int latest_version = -1; /** * Get the highest schema version number that we've encountered during schema registration. */ public final static int getLatestVersion() { return latest_version; } /** * Get the highest schema version that we support. This bounds the search for a schema if we haven't yet * registered all schemas and don't yet know the latest_version. */ public final static int getHighestSupportedVersion() { return HIGHEST_SUPPORTED_VERSION; } /** * Get the experimental schema version, which indicates that a schema is not guaranteed stable between H2O releases. */ public final static int getExperimentalVersion() { return EXPERIMENTAL_VERSION; } /** * Register the given schema class. * @throws water.exceptions.H2OFailException if there is a name collision, if the type parameters are bad, or if the version is bad */ private static void register(Class<? extends Schema> clz) { synchronized(clz) { // Was there a race to get here? If so, return. Class<? extends Schema> existing = schemas.get(clz.getSimpleName()); if (null != existing) { if (clz != existing) throw H2O.fail("Two schema classes have the same simpleName; this is not supported: " + clz + " and " + existing + "."); return; } // Check that the Schema has the correct type parameters: if (clz.getGenericSuperclass() instanceof ParameterizedType) { Type[] schema_type_parms = ((ParameterizedType) (clz.getGenericSuperclass())).getActualTypeArguments(); if (schema_type_parms.length < 2) throw H2O.fail("Found a Schema that does not pass at least two type parameters. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz); Class parm0 = ReflectionUtils.findActualClassParameter(clz, 0); if (!Iced.class.isAssignableFrom(parm0)) throw H2O.fail("Found a Schema with bad type parameters. First parameter is a subclass of Iced. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm0); if (Schema.class.isAssignableFrom(parm0)) throw H2O.fail("Found a Schema with bad type parameters. First parameter is a subclass of Schema. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm0); Class parm1 = ReflectionUtils.findActualClassParameter(clz, 1); if (!Schema.class.isAssignableFrom(parm1)) throw H2O.fail("Found a Schema with bad type parameters. Second parameter is not a subclass of Schema. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm1); } else { throw H2O.fail("Found a Schema that does not have a parameterized superclass. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz); } int version = extractVersion(clz.getSimpleName()); if (version > getHighestSupportedVersion() && version != EXPERIMENTAL_VERSION) throw H2O.fail("Found a schema with a version higher than the highest supported version; you probably want to bump the highest supported version: " + clz); // NOTE: we now allow non-versioned schemas, for example base classes like ModelMetricsBase, so that we can fetch the metadata for them. if (version > -1 && version != EXPERIMENTAL_VERSION) { // Track highest version of all schemas; only valid after all are registered at startup time. if (version > HIGHEST_SUPPORTED_VERSION) throw H2O.fail("Found a schema with a version greater than the highest supported version of: " + getHighestSupportedVersion() + ": " + clz); if (version > latest_version) { synchronized (Schema.class) { if (version > latest_version) latest_version = version; } } } Schema s = null; try { s = clz.newInstance(); } catch (Exception e) { Log.err("Failed to instantiate schema class: " + clz + " because: " + e); } if (null != s) { Log.debug("Registered Schema: " + clz.getSimpleName()); // Validate the fields: SchemaMetadata meta = new SchemaMetadata(s); for (SchemaMetadata.FieldMetadata field_meta : meta.fields) { String name = field_meta.name; if ("__meta".equals(name) || "__http_status".equals(name) || "_exclude_fields".equals(name) || "_include_fields".equals(name)) continue; if ("Gini".equals(name)) // proper name continue; if (name.endsWith("AUC")) // trainAUC, validAUC continue; // TODO: remove after we move these into a TwoDimTable: if ("F0point5".equals(name) || "F0point5_for_criteria".equals(name) || "F1_for_criteria".equals(name) || "F2_for_criteria".equals(name)) continue; if (name.startsWith("_")) Log.warn("Found schema field which violates the naming convention; name starts with underscore: " + meta.name + "." + name); if (!name.equals(name.toLowerCase()) && !name.equals(name.toUpperCase())) // allow AUC but not residualDeviance Log.warn("Found schema field which violates the naming convention; name has mixed lowercase and uppercase characters: " + meta.name + "." + name); } } } } /** * Create an appropriate implementation object and any child objects but does not fill them. * The standard purpose of a createImpl without a fillImpl is to be able to get the default * values for all the impl's fields. * <p> * For objects without children this method does all the required work. For objects * with children the subclass will need to override, e.g. by calling super.createImpl() * and then calling createImpl() on its children. * <p> * Note that impl objects for schemas which override this method don't need to have * a default constructor (e.g., a Keyed object constructor can still create and set * the Key), but they must not fill any fields which can be filled later from the schema. * <p> * TODO: We could handle the common case of children with the same field names here * by finding all of our fields that are themselves Schemas. * @throws H2OIllegalArgumentException if Class.newInstance fails */ public I createImpl() { try { return this.getImplClass().newInstance(); } catch (Exception e) { String msg = "Exception instantiating implementation object of class: " + this.getImplClass().toString() + " for schema class: " + this.getClass(); Log.err(msg + ": " + e); H2OIllegalArgumentException heae = new H2OIllegalArgumentException(msg); heae.initCause(e); throw heae; } } /** Fill an impl object and any children from this schema and its children. If a schema doesn't need to adapt any fields if does not need to override this method. */ public I fillImpl(I impl) { PojoUtils.copyProperties(impl, this, PojoUtils.FieldNaming.CONSISTENT); // TODO: make field names in the impl classes consistent and remove PojoUtils.copyProperties(impl, this, PojoUtils.FieldNaming.DEST_HAS_UNDERSCORES); return impl; } /** Convenience helper which creates and fills an impl object from this schema. */ final public I createAndFillImpl() { return this.fillImpl(this.createImpl()); } /** Fill this Schema from the given implementation object. If a schema doesn't need to adapt any fields if does not need to override this method. */ public S fillFromImpl(I impl) { PojoUtils.copyProperties(this, impl, PojoUtils.FieldNaming.ORIGIN_HAS_UNDERSCORES); PojoUtils.copyProperties(this, impl, PojoUtils.FieldNaming.CONSISTENT); // TODO: make field names in the impl classes consistent and remove return (S)this; } /** Return the class of the implementation type parameter I for the given Schema class. Used by the metadata facilities and the reflection-base field-copying magic in PojoUtils. */ public static Class<? extends Iced> getImplClass(Class<? extends Schema> clz) { Class<? extends Iced> impl_class = (Class<? extends Iced>)ReflectionUtils.findActualClassParameter(clz, 0); if (null == impl_class) Log.warn("Failed to find an impl class for Schema: " + clz); return impl_class; } /** Return the class of the implementation type parameter I for this Schema. Used by generic code which deals with arbitrary schemas and their backing impl classes. */ public Class<I> getImplClass() { if (null == _impl_class) _impl_class = (Class<I>) ReflectionUtils.findActualClassParameter(this.getClass(), 0); if (null == _impl_class) Log.warn("Failed to find an impl class for Schema: " + this.getClass()); return _impl_class; } /** * Fill this Schema object from a set of parameters. * * @param parms parameters - set of tuples (parameter name, parameter value) * @return this schema * * @see #fillFromParms(Properties, boolean) */ public S fillFromParms(Properties parms) { return fillFromParms(parms, true); } /** * Fill this Schema from a set of (generally HTTP) parameters. * <p> * Using reflection this process determines the type of the target field and * conforms the types if possible. For example, if the field is a Keyed type * the name (ID) will be looked up in the DKV and mapped appropriately. * <p> * The process ignores parameters which are not fields in the schema, and it * verifies that all fields marked as required are present in the parameters * list. * <p> * It also does various sanity checks for broken Schemas, for example fields must * not be private, and since input fields get filled here they must not be final. * @param parms Properties map of parameter values * @param checkRequiredFields perform check for missing required fields * @return this schema * @throws H2OIllegalArgumentException for bad/missing parameters */ public S fillFromParms(Properties parms, boolean checkRequiredFields) { // Get passed-in fields, assign into Schema Class thisSchemaClass = this.getClass(); Map<String, Field> fields = new HashMap<>(); Field current = null; // declare here so we can print in catch{} try { Class clz = thisSchemaClass; do { Field[] some_fields = clz.getDeclaredFields(); for (Field f : some_fields) { current = f; if (null == fields.get(f.getName())) fields.put(f.getName(), f); } clz = clz.getSuperclass(); } while (Iced.class.isAssignableFrom(clz.getSuperclass())); } catch (SecurityException e) { throw H2O.fail("Exception accessing field: " + current + " in class: " + this.getClass() + ": " + e); } for( String key : parms.stringPropertyNames() ) { try { Field f = fields.get(key); // No such field error, if parm is junk if (null == f) { throw new H2OIllegalArgumentException("Unknown parameter: " + key, "Unknown parameter in fillFromParms: " + key + " for class: " + this.getClass().toString()); } int mods = f.getModifiers(); if( Modifier.isTransient(mods) || Modifier.isStatic(mods) ) { // Attempting to set a transient or static; treat same as junk fieldname throw new H2OIllegalArgumentException( "Bad parameter for field: " + key + " for class: " + this.getClass().toString(), "Bad parameter definition for field: " + key + " in fillFromParms for class: " + this.getClass().toString() + " (field was declared static or transient)"); } // Only support a single annotation which is an API, and is required API api = (API)f.getAnnotations()[0]; // Must have one of these set to be an input field if( api.direction() == API.Direction.OUTPUT ) { throw new H2OIllegalArgumentException( "Attempting to set output field: " + key + " for class: " + this.getClass().toString(), "Attempting to set output field: " + key + " in fillFromParms for class: " + this.getClass().toString() + " (field was annotated as API.Direction.OUTPUT)"); } // Parse value and set the field setField(this, f, key, parms.getProperty(key), api.required(), thisSchemaClass); } catch( ArrayIndexOutOfBoundsException aioobe ) { // Come here if missing annotation throw H2O.fail("Broken internal schema; missing API annotation for field: " + key); } catch( IllegalAccessException iae ) { // Come here if field is final or private throw H2O.fail("Broken internal schema; field cannot be private nor final: " + key); } } // Here every thing in 'parms' was set into some field - so we have already // checked for unknown or extra parms. // Confirm required fields are set if (checkRequiredFields) { for (Field f : fields.values()) { int mods = f.getModifiers(); if (Modifier.isTransient(mods) || Modifier.isStatic(mods)) continue; // Ignore transient & static try { API api = (API) f.getAnnotations()[0]; // TODO: is there a more specific way we can do this? if (api.required()) { if (parms.getProperty(f.getName()) == null) { IcedHashMap.IcedHashMapStringObject values = new IcedHashMap.IcedHashMapStringObject(); values.put("schema", this.getClass().getSimpleName()); values.put("argument", f.getName()); throw new H2OIllegalArgumentException( "Required field " + f.getName() + " not specified", "Required field " + f.getName() + " not specified for schema class: " + this .getClass(), values); } } } catch (ArrayIndexOutOfBoundsException e) { throw H2O.fail("Missing annotation for API field: " + f.getName()); } } } return (S) this; } /** * Safe method to set the field on given schema object * @param o schema object to modify * @param f field to modify * @param key name of field to modify * @param value string-based representation of value to set * @param required is field required by API * @param thisSchemaClass class of schema handling this (can be null) * @throws IllegalAccessException */ public static <T extends Schema> void setField(T o, Field f, String key, String value, boolean required, Class thisSchemaClass) throws IllegalAccessException { // Primitive parse by field type Object parse_result = parse(key, value, f.getType(), required, thisSchemaClass); if (parse_result != null && f.getType().isArray() && parse_result.getClass().isArray() && (f.getType().getComponentType() != parse_result.getClass().getComponentType())) { // We have to conform an array of primitives. There's got to be a better way. . . if (parse_result.getClass().getComponentType() == int.class && f.getType().getComponentType() == Integer.class) { int[] from = (int[])parse_result; Integer[] copy = new Integer[from.length]; for (int i = 0; i < from.length; i++) copy[i] = from[i]; f.set(o, copy); } else if (parse_result.getClass().getComponentType() == Integer.class && f.getType().getComponentType() == int.class) { Integer[] from = (Integer[])parse_result; int[] copy = new int[from.length]; for (int i = 0; i < from.length; i++) copy[i] = from[i]; f.set(o, copy); } else if (parse_result.getClass().getComponentType() == Double.class && f.getType().getComponentType() == double.class) { Double[] from = (Double[])parse_result; double[] copy = new double[from.length]; for (int i = 0; i < from.length; i++) copy[i] = from[i]; f.set(o, copy); } else if (parse_result.getClass().getComponentType() == Float.class && f.getType().getComponentType() == float.class) { Float[] from = (Float[])parse_result; float[] copy = new float[from.length]; for (int i = 0; i < from.length; i++) copy[i] = from[i]; f.set(o, copy); } else { throw H2O.fail("Don't know how to cast an array of: " + parse_result.getClass().getComponentType() + " to an array of: " + f.getType().getComponentType()); } } else { f.set(o, parse_result); } } static <E> Object parsePrimitve(String s, Class fclz) { if (fclz.equals(String.class)) return s; // Strings already the right primitive type if (fclz.equals(int.class)) return parseInteger(s, int.class); if (fclz.equals(long.class)) return parseInteger(s, long.class); if (fclz.equals(short.class)) return parseInteger(s, short.class); if (fclz.equals(boolean.class)) { if (s.equals("0")) return Boolean.FALSE; if (s.equals("1")) return Boolean.TRUE; return Boolean.valueOf(s); } if (fclz.equals(byte.class)) return parseInteger(s, byte.class); if (fclz.equals(double.class)) return Double.valueOf(s); if (fclz.equals(float.class)) return Float.valueOf(s); //FIXME: if (fclz.equals(char.class)) return Character.valueOf(s); throw H2O.fail("Unknown primitive type to parse: " + fclz.getSimpleName()); } // URL parameter parse static <E> Object parse(String field_name, String s, Class fclz, boolean required, Class schemaClass) { if (fclz.isPrimitive() || String.class.equals(fclz)) { try { return parsePrimitve(s, fclz); } catch (NumberFormatException ne) { String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": cannot convert \"" + s + "\" to type " + fclz.getSimpleName(); throw new H2OIllegalArgumentException(msg); } } // An array? if (fclz.isArray()) { // Get component type Class<E> afclz = (Class<E>) fclz.getComponentType(); // Result E[] a = null; // Handle simple case with null-array if (s.equals("null") || s.length() == 0) return null; // Splitted values String[] splits; // "".split(",") => {""} so handle the empty case explicitly if (s.startsWith("[") && s.endsWith("]") ) { // It looks like an array read(s, 0, '[', fclz); read(s, s.length() - 1, ']', fclz); String inside = s.substring(1, s.length() - 1).trim(); if (inside.length() == 0) splits = new String[]{}; else splits = splitArgs(inside); } else { // Lets try to parse single value as an array! // See PUBDEV-1955 splits = new String[] { s.trim() }; } // Can't cast an int[] to an Object[]. Sigh. if (afclz == int.class) { // TODO: other primitive types. . . a = (E[]) Array.newInstance(Integer.class, splits.length); } else if (afclz == double.class) { a = (E[]) Array.newInstance(Double.class, splits.length); } else if (afclz == float.class) { a = (E[]) Array.newInstance(Float.class, splits.length); } else { // Fails with primitive classes; need the wrapper class. Thanks, Java. a = (E[]) Array.newInstance(afclz, splits.length); } for (int i = 0; i < splits.length; i++) { if (String.class == afclz || KeyV3.class.isAssignableFrom(afclz)) { // strip quotes off string values inside array String stripped = splits[i].trim(); if ("null".equals(stripped)) { a[i] = null; } else if (!stripped.startsWith("\"") || !stripped.endsWith("\"")) { String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": string and key arrays' values must be double quoted, but the client sent: " + stripped; IcedHashMap.IcedHashMapStringObject values = new IcedHashMap.IcedHashMapStringObject(); values.put("function", fclz.getSimpleName() + ".fillFromParms()"); values.put("argument", field_name); values.put("value", stripped); throw new H2OIllegalArgumentException(msg, msg, values); } stripped = stripped.substring(1, stripped.length() - 1); a[i] = (E) parse(field_name, stripped, afclz, required, schemaClass); } else { a[i] = (E) parse(field_name, splits[i].trim(), afclz, required, schemaClass); } } return a; } if (fclz.equals(Key.class)) if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s); else if (!required && (s == null || s.length() == 0)) return null; else return Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s); // If the key name is in an array we need to trim surrounding quotes. if (KeyV3.class.isAssignableFrom(fclz)) { if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s); if (!required && (s == null || s.length() == 0)) return null; return KeyV3.make(fclz, Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s)); // If the key name is in an array we need to trim surrounding quotes. } if (Enum.class.isAssignableFrom(fclz)) return Enum.valueOf(fclz, s); // TODO: try/catch needed! // TODO: these can be refactored into a single case using the facilities in Schema: if (FrameV3.class.isAssignableFrom(fclz)) { if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s); else if (!required && (s == null || s.length() == 0)) return null; else { Value v = DKV.get(s); if (null == v) return null; // not required if (!v.isFrame()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Frame", v.get().getClass()); return new FrameV3((Frame) v.get()); // TODO: version! } } if (JobV3.class.isAssignableFrom(fclz)) { if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(s); else if (!required && (s == null || s.length() == 0)) return null; else { Value v = DKV.get(s); if (null == v) return null; // not required if (!v.isJob()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Job", v.get().getClass()); return new JobV3().fillFromImpl((Job) v.get()); // TODO: version! } } // TODO: for now handle the case where we're only passing the name through; later we need to handle the case // where the frame name is also specified. if (FrameV3.ColSpecifierV3.class.isAssignableFrom(fclz)) { return new FrameV3.ColSpecifierV3(s); } if (ModelSchema.class.isAssignableFrom(fclz)) throw H2O.fail("Can't yet take ModelSchema as input."); /* if( (s==null || s.length()==0) && required ) throw new IllegalArgumentException("Missing key"); else if (!required && (s == null || s.length() == 0)) return null; else { Value v = DKV.get(s); if (null == v) return null; // not required if (! v.isModel()) throw new IllegalArgumentException("Model argument points to a non-model object."); return v.get(); } */ throw H2O.fail("Unimplemented schema fill from " + fclz.getSimpleName()); } // parse() /** * Helper functions for parse() **/ /** * Parses a string into an integer data type specified by parameter return_type. Accepts any format that * is accepted by java's BigDecimal class. * - Throws a NumberFormatException if the evaluated string is not an integer or if the value is too large to * be stored into return_type without overflow. * - Throws an IllegalAgumentException if return_type is not an integer data type. **/ static private <T> T parseInteger(String s, Class<T> return_type) { try { java.math.BigDecimal num = new java.math.BigDecimal(s); T result = (T) num.getClass().getDeclaredMethod(return_type.getSimpleName() + "ValueExact", new Class[0]).invoke(num); return result; } catch (InvocationTargetException ite) { throw new NumberFormatException("The expression's numeric value is out of the range of type " + return_type.getSimpleName()); } catch (NoSuchMethodException nsme) { throw new IllegalArgumentException(return_type.getSimpleName() + " is not an integer data type"); } catch (IllegalAccessException iae) { throw H2O.fail("Cannot parse expression as " + return_type.getSimpleName() + " (Illegal Access)"); } } static private int read( String s, int x, char c, Class fclz ) { if( peek(s,x,c) ) return x+1; throw new IllegalArgumentException("Expected '"+c+"' while reading a "+fclz.getSimpleName()+", but found "+s); } static private boolean peek( String s, int x, char c ) { return x < s.length() && s.charAt(x) == c; } // Splits on commas, but ignores commas in double quotes. Required // since using a regex blow the stack on long column counts // TODO: detect and complain about malformed JSON private static String[] splitArgs(String argStr) { StringBuffer sb = new StringBuffer (argStr); StringBuffer arg = new StringBuffer (); List<String> splitArgList = new ArrayList<String> (); boolean inDoubleQuotes = false; boolean inSquareBrackets = false; // for arrays of arrays for (int i=0; i < sb.length(); i++) { if (sb.charAt(i) == '"' && !inDoubleQuotes && !inSquareBrackets) { inDoubleQuotes = true; arg.append(sb.charAt(i)); } else if (sb.charAt(i) == '"' && inDoubleQuotes && !inSquareBrackets) { inDoubleQuotes = false; arg.append(sb.charAt(i)); } else if (sb.charAt(i) == ',' && !inDoubleQuotes && !inSquareBrackets) { splitArgList.add(arg.toString()); // clear the field for next word arg.setLength(0); } else if (sb.charAt(i) == '[') { inSquareBrackets = true; arg.append(sb.charAt(i)); } else if (sb.charAt(i) == ']') { inSquareBrackets = false; arg.append(sb.charAt(i)); } else { arg.append(sb.charAt(i)); } } if (arg.length() > 0) splitArgList.add(arg.toString()); return splitArgList.toArray(new String[splitArgList.size()]); } private static boolean schemas_registered = false; /** * Find all schemas using reflection and register them. */ synchronized static public void registerAllSchemasIfNecessary() { if (schemas_registered) return; // if (!Paxos._cloudLocked) return; // TODO: It's never getting locked. . . :-( long before = System.currentTimeMillis(); // Microhack to effect Schema.register(Schema.class), which is // normally not allowed because it has no version: new Schema(); String[] packages = new String[] { "water", "hex", /* Disallow schemas whose parent is in another package because it takes ~4s to do the getSubTypesOf call: "" */}; // For some reason when we're run under Hadoop Reflections is failing to find some of the classes unless we're extremely explicit here: Class<? extends Schema> clzs[] = new Class[] { Schema.class, ModelBuilderSchema.class, ModelSchema.class, ModelOutputSchema.class, ModelParametersSchema.class }; for (String pkg : packages) { Reflections reflections = new Reflections(pkg); for (Class<? extends Schema> clz : clzs) { // NOTE: Reflections sees ModelOutputSchema but not ModelSchema. Another bug to work around: Log.debug("Registering: " + clz.toString() + " in package: " + pkg); if (!Modifier.isAbstract(clz.getModifiers())) Schema.register(clz); // Register the subclasses: Log.debug("Registering subclasses of: " + clz.toString() + " in package: " + pkg); for (Class<? extends Schema> schema_class : reflections.getSubTypesOf(clz)) if (!Modifier.isAbstract(schema_class.getModifiers())) Schema.register(schema_class); } } schemas_registered = true; Log.info("Registered: " + Schema.schemas().size() + " schemas in: " + (System.currentTimeMillis() - before) + "mS"); } /** * Return an immutable Map of all the schemas: schema_name -> schema Class. */ protected static Map<String, Class<? extends Schema>> schemas() { return Collections.unmodifiableMap(new HashMap<>(schemas)); } /** * For a given version and Iced class return the appropriate Schema class, if any.f * @see #schemaClass(int, java.lang.String) */ protected static Class<? extends Schema> schemaClass(int version, Class<? extends Iced> impl_class) { return schemaClass(version, impl_class.getSimpleName()); } /** * For a given version and type (Iced class simpleName) return the appropriate Schema * class, if any. * <p> * If a higher version is asked for than is available (e.g., if the highest version of * Frame is FrameV2 and the client asks for the schema for (Frame, 17) then FrameV2 will * be returned. This compatibility lookup is cached. */ private static Class<? extends Schema> schemaClass(int version, String type) { if (version < 1) return null; Class<? extends Schema> clz = iced_to_schema.get(new Pair(type, version)); if (null != clz) return clz; // found! clz = schemaClass(version - 1, type); if (null != clz) iced_to_schema.put(new Pair(type, version), clz); // found a lower-numbered schema: cache return clz; } /** * For a given version and Iced object return an appropriate Schema instance, if any. * @see #schema(int, java.lang.String) */ public static Schema schema(int version, Iced impl) { return schema(version, impl.getClass().getSimpleName()); } /** * For a given version and Iced class return an appropriate Schema instance, if any. * @throws H2OIllegalArgumentException if Class.newInstance() throws * @see #schema(int, java.lang.String) */ public static Schema schema(int version, Class<? extends Iced> impl_class) { return schema(version, impl_class.getSimpleName()); } // FIXME: can be parameterized by type: public static <T extends Schema> T newInstance(Class<T> clz) public static <T extends Schema> T newInstance(Class<T> clz) { T s = null; try { s = clz.newInstance(); } catch (Exception e) { throw new H2OIllegalArgumentException("Failed to instantiate schema of class: " + clz.getCanonicalName() + ", cause: " + e); } return s; } /** * For a given version and type (Iced class simpleName) return an appropriate new Schema * object, if any. * <p> * If a higher version is asked for than is available (e.g., if the highest version of * Frame is FrameV2 and the client asks for the schema for (Frame, 17) then an instance * of FrameV2 will be returned. This compatibility lookup is cached. * @throws H2ONotFoundArgumentException if an appropriate schema is not found */ private static Schema schema(int version, String type) { Class<? extends Schema> clz = schemaClass(version, type); if (null == clz) clz = schemaClass(Schema.getExperimentalVersion(), type); if (null == clz) throw new H2ONotFoundArgumentException("Failed to find schema for version: " + version + " and type: " + type, "Failed to find schema for version: " + version + " and type: " + type); return Schema.newInstance(clz); } /** * For a given schema_name (e.g., "FrameV2") return an appropriate new schema object (e.g., a water.api.Framev2). * @throws H2ONotFoundArgumentException if an appropriate schema is not found */ protected static Schema newInstance(String schema_name) { Class<? extends Schema> clz = schemas.get(schema_name); if (null == clz) throw new H2ONotFoundArgumentException("Failed to find schema for schema_name: " + schema_name, "Failed to find schema for schema_name: " + schema_name); return Schema.newInstance(clz); } /** * Generate Markdown documentation for this Schema possibly including only the input or output fields. * @throws H2ONotFoundArgumentException if reflection on a field fails */ public StringBuffer markdown(StringBuffer appendToMe, boolean include_input_fields, boolean include_output_fields) { return markdown(new SchemaMetadata(this), appendToMe, include_input_fields, include_output_fields); } /** * Append Markdown documentation for another Schema, given we already have the metadata constructed. * @throws H2ONotFoundArgumentException if reflection on a field fails */ public StringBuffer markdown(SchemaMetadata meta, StringBuffer appendToMe) { return markdown(meta, appendToMe, true, true); } /** * Generate Markdown documentation for this Schema, given we already have the metadata constructed. * @throws H2ONotFoundArgumentException if reflection on a field fails */ public StringBuffer markdown(SchemaMetadata meta , StringBuffer appendToMe, boolean include_input_fields, boolean include_output_fields) { MarkdownBuilder builder = new MarkdownBuilder(); builder.comment("Preview with http://jbt.github.io/markdown-editor"); builder.heading1("schema ", this.getClass().getSimpleName()); builder.hline(); // builder.paragraph(metadata.summary); // TODO: refactor with Route.markdown(): // fields boolean first; // don't print the table at all if there are no rows try { if (include_input_fields) { first = true; builder.heading2("input fields"); for (SchemaMetadata.FieldMetadata field_meta : meta.fields) { if (field_meta.direction == API.Direction.INPUT || field_meta.direction == API.Direction.INOUT) { if (first) { builder.tableHeader("name", "required?", "level", "type", "schema?", "schema", "default", "description", "values", "is member of frames", "is mutually exclusive with"); first = false; } builder.tableRow( field_meta.name, String.valueOf(field_meta.required), field_meta.level.name(), field_meta.type, String.valueOf(field_meta.is_schema), field_meta.is_schema ? field_meta.schema_name : "", (null == field_meta.value ? "(null)" : field_meta.value.toString()), // Something better for toString()? field_meta.help, (field_meta.values == null || field_meta.values.length == 0 ? "" : Arrays.toString(field_meta.values)), (field_meta.is_member_of_frames == null ? "[]" : Arrays.toString(field_meta.is_member_of_frames)), (field_meta.is_mutually_exclusive_with == null ? "[]" : Arrays.toString(field_meta.is_mutually_exclusive_with)) ); } } if (first) builder.paragraph("(none)"); } if (include_output_fields) { first = true; builder.heading2("output fields"); for (SchemaMetadata.FieldMetadata field_meta : meta.fields) { if (field_meta.direction == API.Direction.OUTPUT || field_meta.direction == API.Direction.INOUT) { if (first) { builder.tableHeader("name", "type", "schema?", "schema", "default", "description", "values", "is member of frames", "is mutually exclusive with"); first = false; } builder.tableRow( field_meta.name, field_meta.type, String.valueOf(field_meta.is_schema), field_meta.is_schema ? field_meta.schema_name : "", (null == field_meta.value ? "(null)" : field_meta.value.toString()), // something better than toString()? field_meta.help, (field_meta.values == null || field_meta.values.length == 0 ? "" : Arrays.toString(field_meta.values)), (field_meta.is_member_of_frames == null ? "[]" : Arrays.toString(field_meta.is_member_of_frames)), (field_meta.is_mutually_exclusive_with == null ? "[]" : Arrays.toString(field_meta.is_mutually_exclusive_with))); } } if (first) builder.paragraph("(none)"); } // TODO: render examples and other stuff, if it's passed in } catch (Exception e) { IcedHashMap.IcedHashMapStringObject values = new IcedHashMap.IcedHashMapStringObject(); values.put("schema", this); // TODO: This isn't quite the right exception type: throw new H2OIllegalArgumentException("Caught exception using reflection on schema: " + this, "Caught exception using reflection on schema: " + this + ": " + e, values); } if (null != appendToMe) appendToMe.append(builder.stringBuffer()); return builder.stringBuffer(); } // markdown() }
madmax983/h2o-3
h2o-core/src/main/java/water/api/Schema.java
Java
apache-2.0
52,870
# Develop based on 'TypeScript & AngularJS TodoMVC Example' ## available on Chrome
deggs7/sign-in-board-stackeasy
README.md
Markdown
apache-2.0
84
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>obl</title> <link rel="root" href=""/> <!-- for JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/> <link rel="stylesheet" type="text/css" href="../../css/style.css"/> <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/> <link rel="stylesheet" type="text/css" href="../../css/hint.css"/> <script type="text/javascript" src="../../lib/ext/head.load.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script> <script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script> <!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo --> <!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page. <script> (function() { var cx = '001145188882102106025:dl1mehhcgbo'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); </script> --> <!-- <link rel="shortcut icon" href="favicon.ico"/> --> </head> <body> <div id="main" class="center"> <div id="hp-header"> <table width="100%"><tr><td width="50%"> <span class="header-text"><a href="http://universaldependencies.org/#language-ru">home</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/_ru/dep/obl.md" target="#">edit page</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span> </td><td> <gcse:search></gcse:search> </td></tr></table> </div> <hr/> <div class="v2complete"> This page pertains to UD version 2. </div> <div id="content"> <noscript> <div id="noscript"> It appears that you have Javascript disabled. Please consider enabling Javascript for this page to see the visualizations. </div> </noscript> <!-- The content may include scripts and styles, hence we must load the shared libraries before the content. --> <script type="text/javascript"> console.time('loading libraries'); var root = '../../'; // filled in by jekyll head.js( // External libraries // DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all. root + 'lib/ext/jquery.min.js', root + 'lib/ext/jquery.svg.min.js', root + 'lib/ext/jquery.svgdom.min.js', root + 'lib/ext/jquery.timeago.js', root + 'lib/ext/jquery-ui.min.js', root + 'lib/ext/waypoints.min.js', root + 'lib/ext/jquery.address.min.js' ); </script> <h2><code>obl</code>: oblique modifier</h2> <p>The <code class="language-plaintext highlighter-rouge">obl</code> relation is used for non-core nominal dependents of clausal predicates.</p> <pre><code class="language-sdparse">Последний раз мы разговаривали зимой . \n Last time we talked in-winter . obl(разговаривали, зимой) obl(talked, in-winter) </code></pre> <p>One subtype of <code class="language-plaintext highlighter-rouge">obl</code> is introduced in Russian: <a href="">obl:agent</a> for agents of passive verbs. <!-- Interlanguage links updated St lis 3 20:59:04 CET 2021 --></p> <!-- "in other languages" links --> <hr/> obl in other languages: [<a href="../../bg/dep/obl.html">bg</a>] [<a href="../../bm/dep/obl.html">bm</a>] [<a href="../../cop/dep/obl.html">cop</a>] [<a href="../../cs/dep/obl.html">cs</a>] [<a href="../../de/dep/obl.html">de</a>] [<a href="../../ess/dep/obl.html">ess</a>] [<a href="../../fr/dep/obl.html">fr</a>] [<a href="../../fro/dep/obl.html">fro</a>] [<a href="../../ga/dep/obl.html">ga</a>] [<a href="../../gd/dep/obl.html">gd</a>] [<a href="../../gsw/dep/obl.html">gsw</a>] [<a href="../../hy/dep/obl.html">hy</a>] [<a href="../../ja/dep/obl.html">ja</a>] [<a href="../../no/dep/obl.html">no</a>] [<a href="../../pcm/dep/obl.html">pcm</a>] [<a href="../../ru/dep/obl.html">ru</a>] [<a href="../../sv/dep/obl.html">sv</a>] [<a href="../../swl/dep/obl.html">swl</a>] [<a href="../../tr/dep/obl.html">tr</a>] [<a href="../../u/dep/obl.html">u</a>] [<a href="../../yue/dep/obl.html">yue</a>] [<a href="../../zh/dep/obl.html">zh</a>] </div> <!-- support for embedded visualizations --> <script type="text/javascript"> var root = '../../'; // filled in by jekyll head.js( // We assume that external libraries such as jquery.min.js have already been loaded outside! // (See _layouts/base.html.) // brat helper modules root + 'lib/brat/configuration.js', root + 'lib/brat/util.js', root + 'lib/brat/annotation_log.js', root + 'lib/ext/webfont.js', // brat modules root + 'lib/brat/dispatcher.js', root + 'lib/brat/url_monitor.js', root + 'lib/brat/visualizer.js', // embedding configuration root + 'lib/local/config.js', // project-specific collection data root + 'lib/local/collections.js', // Annodoc root + 'lib/annodoc/annodoc.js', // NOTE: non-local libraries 'https://spyysalo.github.io/conllu.js/conllu.js' ); var webFontURLs = [ // root + 'static/fonts/Astloch-Bold.ttf', root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf', root + 'static/fonts/Liberation_Sans-Regular.ttf' ]; var setupTimeago = function() { jQuery("time.timeago").timeago(); }; head.ready(function() { setupTimeago(); // mark current collection (filled in by Jekyll) Collections.listing['_current'] = 'ru'; // perform all embedding and support functions Annodoc.activate(Config.bratCollData, Collections.listing); }); </script> <!-- google analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-55233688-1', 'auto'); ga('send', 'pageview'); </script> <div id="footer"> <p class="footer-text">&copy; 2014–2021 <a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>. Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>. </div> </div> </body> </html>
UniversalDependencies/universaldependencies.github.io
ru/dep/obl.html
HTML
apache-2.0
7,672
package eu.uqasar.model.measure; /* * #%L * U-QASAR * %% * Copyright (C) 2012 - 2015 U-QASAR Consortium * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.wicket.model.IModel; import eu.uqasar.util.resources.IResourceKeyProvider; import eu.uqasar.util.resources.ResourceBundleLocator; public enum MetricSource implements IResourceKeyProvider { TestingFramework("test"), IssueTracker("issue"), StaticAnalysis("static"), ContinuousIntegration("ci"), CubeAnalysis("cube"), VersionControl("vcs"), Manual("manual"), ; private final String labelKey; MetricSource(final String labelKey) { this.labelKey = labelKey; } public String toString() { return getLabelModel().getObject(); } public IModel<String> getLabelModel() { return ResourceBundleLocator.getLabelModel(this.getClass(), this); } @Override public String getKey() { return "label.source." + this.labelKey; } public static List<MetricSource> getAllMetricSources(){ List<MetricSource> list = new ArrayList<>(); Collections.addAll(list, MetricSource.values()); return list; } }
U-QASAR/u-qasar.platform
src/main/java/eu/uqasar/model/measure/MetricSource.java
Java
apache-2.0
1,796
'use strict'; import * as _ from 'lodash'; import * as fs from 'fs'; import * as xml2js from 'xml2js'; import * as Mustache from 'mustache'; import * as helpers from './helpers'; import * as utils from './utils'; import * as conf from './conf'; const parseString: (xml: string, options: xml2js.Options) => Promise<any> = helpers.promisify_callback(xml2js.parseString); const readFile = helpers.promisify_callback(fs.readFile); // alike xpath //k function deepGetKey(o, k) { if (!o) { return undefined; } else if (k in o) { return o[k]; } else if (_.isArray(o)) { return o.length === 1 ? deepGetKey(o[0], k) : undefined; } else { let ks = _.keys(o); return ks.length === 1 ? deepGetKey(o[ks[0]], k) : undefined; } } function raw_soap(url, body) { let headers = { SOAPAction: "", "content-type": "text/xml", }; return utils.post(url, body, { headers }).then(result => ( parseString(result, { explicitArray: false, ignoreAttrs: true }) )); } function soap(templateName, params, opts : { responseTag: string, fault_to_string?: (any) => string }) { if (!conf.esup_activ_bo.url) throw "configuration issue: conf.esup_activ_bo.url is missing"; let templateFile = __dirname + "/templates/esup-activ-bo/" + templateName; return readFile(templateFile).then(data => ( Mustache.render(data.toString(), helpers.mapLeaves(params, helpers.escapeXml)) )).then(body => { //console.log(body); const operation = conf.esup_activ_bo.url.replace(/\/AccountManagement$/, '') + '/' + (templateName.match(/Cas/) ? 'CasAccountManagement' : 'AccountManagement'); return raw_soap(operation, body); }).then(xml => { //console.dir(xml, { depth: null }); let response = deepGetKey(xml, opts.responseTag); if (response === undefined) throw get_fault(xml, opts.fault_to_string) || JSON.stringify(xml); return response; }) } const fault_detail_key = (fault) => fault.detail && Object.keys(fault.detail)[0] // Example of response: // <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Identification ...chou..e : (&amp;(supannEmpId=14464)(up1BirthDay=19741002000000Z))</faultstring><detail><AuthentificationException xmlns="http://remote.services.activbo.esupportail.org" /></detail></soap:Fault></soap:Body></soap:Envelope> function get_fault(xml, to_string = undefined) { let fault = deepGetKey(xml, 'soap:Fault'); return fault && (to_string && to_string(fault) || fault.faultstring); } function _get_entries(response) { let entries = deepGetKey(response, 'entry'); if (!_.isArray(entries)) return undefined; let r = _.zipObject(_.map(entries, 'key'), _.map(entries, 'value')); r = _.mapValues(r, val => val.split(conf.esup_activ_bo.multiValue_separator)); return r; } // returns "attrPersoInfo" + code, mail, supannAliasLogin // throws: "Authentification invalide pour l'utilisateur xxx" // throws: "Login invalide" export const authentificateUser = (supannAliasLogin: string, password: string, attrPersoInfo: string[]) => ( soap("authentificateUser.xml", { id: supannAliasLogin, password, attrPersoInfo }, { responseTag: 'ns1:authentificateUserResponse' }).then(_get_entries) ) export const authentificateUserWithCas = (supannAliasLogin: string, proxyticket: string, targetUrl: string, attrPersoInfo: string[]) => ( soap("authentificateUserWithCas.xml", { id: supannAliasLogin, proxyticket, targetUrl, attrPersoInfo }, { responseTag: 'ns1:authentificateUserWithCasResponse' }).then(_get_entries) ) // returns "attrPersoInfo" + possibleChannels, mail, supannAliasLogin + code if account is not activated // ("code" is useful for setPassword or validateCode) // throws: "AuthentificationException" export function validateAccount(userInfoToValidate: Dictionary<string>, attrPersoInfo: string[]): Promise<Dictionary<string>> { console.log("esup_activ_bo._validateAccount " + JSON.stringify(userInfoToValidate)); const hashInfToValidate = _.map(userInfoToValidate, (value, key) => ({ value, key })); let params = { hashInfToValidate, attrPersoInfo }; return soap("validateAccount.xml", params, { responseTag: 'ns1:validateAccountResponse', fault_to_string: fault_detail_key }).then(_get_entries); } // throws: "UserPermissionException" export const updatePersonalInformations = (supannAliasLogin: string, code: string, userInfo: Dictionary<string>) => { const hashBeanPersoInfo = _.map(userInfo, (value, key) => { if (_.isArray(value)) value = value.join(conf.esup_activ_bo.multiValue_separator) return { value, key } }); return soap("updatePersonalInformations.xml", { id: supannAliasLogin, code, hashBeanPersoInfo }, { responseTag: 'ns1:updatePersonalInformationsResponse', fault_to_string: fault_detail_key }) } async function _getCode(hashInfToValidate: Dictionary<string>): Promise<string> { const vals = await validateAccount(hashInfToValidate, []); if (!vals.code) throw "esup_activ_bo.validateAccount did not return code for " + JSON.stringify(hashInfToValidate) + ". Account already activated?"; return vals.code; } // NB: no error in case of unknown channel // throws: "Utilisateur xxx inconnu" // throws: "Utilisateur sdianat n'a pas de mail perso" export const sendCode = (supannAliasLogin: string, channel: string) => ( // Response in case of success: // <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><ns1:sendCodeResponse xmlns:ns1="http://remote.services.activbo.esupportail.org" /></soap:Body></soap:Envelope> soap("sendCode.xml", { id: supannAliasLogin, channel }, { responseTag: 'ns1:sendCodeResponse' }).then(response => { if (response === '') return; // OK! else throw "unexpected sendCode error: " + JSON.stringify(response); }) ); export const validateCode = (supannAliasLogin: string, code: string) => ( // Response in case of success: // <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><ns1:validateCodeResponse xmlns:ns1="http://remote.services.activbo.esupportail.org"><ns1:out>true</ns1:out></ns1:validateCodeResponse></soap:Body></soap:Envelope> soap("validateCode.xml", { id: supannAliasLogin, code }, { responseTag: 'ns1:validateCodeResponse' }).then(response => { return response['ns1:out'] === 'true'; }) ); export function setPassword(supannAliasLogin: string, code: string, password: string) { console.log("esup_activ_bo._setPassword " + supannAliasLogin + " using code " + code); let params = { id: supannAliasLogin, code, password }; return soap("setPassword.xml", params, { responseTag: 'ns1:setPasswordResponse' }).then(response => { if (response === '') return; // OK! else throw "unexpected setPassword error: " + JSON.stringify(response); }); } // TODO //export const changeLogin = (supannAliasLogin: string, code: string, newLogin: string, currentPassword: string) => ... //export const changeLogin = (supannAliasLogin: string, code: string, newLogin: string) => ... export const setNewAccountPassword = (uid: string, supannAliasLogin: string, password: string) => ( _getCode({ uid }).then(code => ( code && setPassword(supannAliasLogin, code, password) )) );
prigaux/compte-externe
server/esup_activ_bo.ts
TypeScript
apache-2.0
7,793
--- title: Common Addons --- ## Kubernetes Dashboard [Kubernetes Dashboard](https://github.com/kubernetes/dashboard) is a general purpose, web-based UI for Kubernetes clusters. It allows users to manage applications running in the cluster and troubleshoot them, as well as manage the cluster itself. ### Installation [Installation](https://github.com/kubernetes/dashboard) is straight forward: ``` kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/master/src/deploy/recommended/kubernetes-dashboard.yaml ``` ### Granting Permissions You can grant full admin privileges to Dashboard's Service Account by creating below `ClusterRoleBinding`. ``` kubectl create clusterrolebinding kubernetes-dashboard --clusterrole=cluster-admin --serviceaccount=kube-system:kubernetes-dashboard ``` ### Accessing the Dashboard To access Dashboard from your local workstation you must create a secure channel to your Kubernetes cluster. Run the following command: ``` kubectl proxy ``` Now access Dashboard at: [http://localhost:8001/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/.](http://localhost:8001/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/.) Skip the selection of Kubeconfig or Token: ![Selection](https://raw.githubusercontent.com/sapcc/kubernikus/master/assets/images/docs/containers/kubernetes/selection.png) ### Exposing the Dashboard In order to expose the Dashboard without the local proxy, we need to: * Create a service of type `LoadBalancer` * Open the security groups for load-balancer to node communication * Assign a floating IP Let's create the service: ``` kubectl expose deployment kubernetes-dashboard --namespace kube-system --type=LoadBalancer --name kubernete-dashboard-external --port=443 --target-port=8443 ``` This will create a Kubernetes service that exposes the dashboard on a high-level service port on each node of the cluster. Additionally, a load-balancer is created in OpenStack which points to each node. ![Load Balancer](https://raw.githubusercontent.com/sapcc/kubernikus/master/assets/images/docs/containers/kubernetes/loadbalancer0.png) As the load-balancers are not in the default instance group, they need to be added to the security group explicitly. Without this, the health monitors won't be able to reach the node port and the listener will be offline. ![Security Group](https://raw.githubusercontent.com/sapcc/kubernikus/master/assets/images/docs/containers/kubernetes/loadbalancer1.png) Once the health monitors turn healthy, attaching a floating IP will make the dashboard accessible from the outside via `https` on port `443`. ![FIP](https://raw.githubusercontent.com/sapcc/kubernikus/master/assets/images/docs/containers/kubernetes/loadbalancer2.png) ~> This setup exposes an unauthenticated Dashboard with full access to the cluster. This is a security risk. See the [Access Control](https://github.com/kubernetes/dashboard/wiki/Access-control) documentation for more info. ## Private Docker Registry in Kubernikus You can create a private docker registry in your Kubernikus cluster to store your Docker images. ### How it works The private registry runs as a Pod in your cluster. A proxy on each node is exposing a port onto the node (via a hostPort), which Docker accepts as "secure", since it is accessed by localhost. ### Create a persisten volume claim There is already a default storageClass and your cluster knows that storage exists. You just have to create a persistent volume claim to claim the storage. Adjust the storage size as needed. ``` kind: PersistentVolumeClaim apiVersion: v1 metadata: name: registry-storage spec: accessModes: - ReadWriteOnce resources: requests: storage: 5Gi ``` ### Run the registry Now you can run the Docker registry: ``` apiVersion: v1 kind: ReplicationController metadata: name: kube-registry-v0 labels: k8s-app: kube-registry-upstream version: v0 kubernetes.io/cluster-service: "true" spec: replicas: 1 selector: k8s-app: kube-registry-upstream version: v0 template: metadata: labels: k8s-app: kube-registry-upstream version: v0 kubernetes.io/cluster-service: "true" spec: containers: - name: registry image: registry:2.5.1 resources: limits: cpu: 100m memory: 100Mi requests: cpu: 100m memory: 100Mi env: - name: REGISTRY_HTTP_ADDR value: :5000 - name: REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY value: /var/lib/registry volumeMounts: - name: image-store mountPath: /var/lib/registry ports: - containerPort: 5000 name: registry protocol: TCP volumes: - name: image-store persistentVolumeClaim: claimName: registry-storage ``` ### Expose registry in the cluster ``` apiVersion: v1 kind: Service metadata: name: kube-registry labels: k8s-app: kube-registry-upstream kubernetes.io/cluster-service: "true" kubernetes.io/name: "KubeRegistry" spec: selector: k8s-app: kube-registry-upstream ports: - name: registry port: 5000 protocol: TCP ``` ### Expose the registry on each node Now that there is a running Service, you need to expose it onto each Kubernetes Node so that Docker will see it as localhost. ``` apiVersion: extensions/v1beta1 kind: DaemonSet metadata: name: registry-proxy-v0 labels: k8s-app: kube-registry-proxy kubernetes.io/cluster-service: "true" version: v0.4 spec: template: metadata: labels: k8s-app: kube-registry-proxy kubernetes.io/name: "kube-registry-proxy" kubernetes.io/cluster-service: "true" version: v0.4 spec: containers: - name: kube-registry-proxy image: gcr.io/google_containers/kube-registry-proxy:0.4 resources: limits: cpu: 100m memory: 50Mi env: - name: REGISTRY_HOST value: kube-registry - name: REGISTRY_PORT value: "5000" ports: - name: registry containerPort: 80 hostPort: 5000 ``` ### Access registry from outside Through a ssh tunnel you can push or pull images from your cluster registry. At first, export your local ip: ``` export local_ip=$(ipconfig getifaddr en0) ``` Add `${local_ip}:5000` to your local docker daemon config insecure registries. Save and restart docker daemon. After start the ssh tunnel: ``` ssh -N -L '*:5000:localhost:5000' <username>@<remote-registry-server> ``` Now you can pull or push images ``` docker pull ${local_ip}:5000/<user>/<image> ``` ## Deploy HANA Express database on Kubernikus Create a Kubernetes cluster and deploy SAP HANA, express edition containers (database server only). ### Step 1: Create Kubernetes Cluster Login to the Converged Cloud Dashboard and navigate to your project. Open `Containers > Kubernetes`. Click `Create Cluster`, choose a cluster name (max. 20 digits), give your nodepool a name, choose a number of nodes and use at least a `m1.large` flavor which offers you `4 vCPU, ~8 GB RAM` per node. Create the `kluster` (Cluster by Kubernikus). ### Step 2: Connect to your kluster Use the following instructions to get access to your Kubernetes Cluster. [Authenticating with Kubernetes](https://kubernikus.eu-nl-1.cloud.sap/docs/guide/authentication/#authenticating-with-kubernetes). ### Step 3: Create the deployments configuration files At first, you should create a `secret` with your Docker credentials in order to pull images from the docker registry. ``` kubectl create secret docker-registry docker-secret \ --docker-server=https://index.docker.io/v1/ \ --docker-username=<<DOCKER_USER>> \ --docker-password=<<DOCKER_PASSWORD>> \ --docker-email=<<DOCKER_EMAIL>> ``` ### Step 4: Create the deployments configuration files Create a file `hxe.yaml` on your local machine and copy the following content into it. Replace the password inside the ConfigMap with your own one. Please check the password policy to avoid errors: ``` SAP HANA, express edition requires a very strong password that complies with these rules: At least 8 characters At least 1 uppercase letter At least 1 lowercase letter At least 1 number Can contain special characters, but not backtick, dollar sign, backslash, single or double quote Cannot contain dictionary words Cannot contain simplistic or systematic values, like strings in ascending or descending numerical or alphabetical order ``` Create your local yaml file (`hxe.yaml`): ``` kind: ConfigMap apiVersion: v1 metadata: creationTimestamp: 2018-01-18T19:14:38Z name: hxe-pass data: password.json: |+ {"master_password" : "HXEHana1"} --- kind: PersistentVolume apiVersion: v1 metadata: name: persistent-vol-hxe labels: type: local spec: storageClassName: manual capacity: storage: 150Gi accessModes: - ReadWriteOnce hostPath: path: "/data/hxe_pv" --- kind: PersistentVolumeClaim apiVersion: v1 metadata: name: hxe-pvc spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 50Gi --- apiVersion: apps/v1 kind: Deployment metadata: name: hxe spec: selector: matchLabels: app: hxe replicas: 1 template: metadata: labels: app: hxe spec: initContainers: - name: install image: busybox command: [ 'sh', '-c', 'chown 12000:79 /hana/mounts' ] volumeMounts: - name: hxe-data mountPath: /hana/mounts restartPolicy: Always volumes: - name: hxe-data persistentVolumeClaim: claimName: hxe-pvc - name: hxe-config configMap: name: hxe-pass imagePullSecrets: - name: docker-secret containers: - name: hxe-container image: "store/saplabs/hanaexpress:2.00.022.00.20171211.1" ports: - containerPort: 39013 name: port1 - containerPort: 39015 name: port2 - containerPort: 39017 name: port3 - containerPort: 8090 name: port4 - containerPort: 39041 name: port5 - containerPort: 59013 name: port6 args: [ "--agree-to-sap-license", "--dont-check-system", "--passwords-url", "file:///hana/hxeconfig/password.json" ] volumeMounts: - name: hxe-data mountPath: /hana/mounts - name: hxe-config mountPath: /hana/hxeconfig ``` Now create the resources with `kubectl`: ``` kubectl create -f hxe.yaml ``` The deployment creates in this example just one pod. It should be running after some seconds. The name of the pod starts with hxe and is followed by some generated numbers / hash (eg. hxe-699d795cf6-7m6jk) ``` kubectl get pods ``` Let's look into the pod for more information ``` kubectl describe pod hxe-<<value>> kubectl logs hxe-<<value>> ``` You can check if SAP HANA, express edition is running by using `HDB info` inside the pod with `kubectl exec -it hxe-pod bash`. ### Step 5: Get access to the database The container is running and pods are available inside the Kubernetes cluster. Now, you can create a [Kubernetes service](https://kubernetes.io/docs/concepts/services-networking/service/) to reach the pod. `kubectl expose deployment hxe --name=hxe-svc --type=LoadBalancer --port=39013` This example exposes the pod on port 39013. With `kubectl get svc` you can check the assigned floating ip.
sapcc/kubernikus
docs/guide/common_addons.md
Markdown
apache-2.0
11,715
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for download_data.""" from unittest import mock from google.protobuf import text_format import tensorflow as tf from tensorboard.backend.event_processing import plugin_event_multiplexer from tensorboard.plugins import base_plugin from tensorboard.plugins.hparams import api_pb2 from tensorboard.plugins.hparams import backend_context from tensorboard.plugins.hparams import download_data EXPERIMENT = """ description: 'Test experiment' user: 'Test user' hparam_infos: [ { name: 'initial_temp' type: DATA_TYPE_FLOAT64 }, { name: 'final_temp' type: DATA_TYPE_FLOAT64 }, { name: 'string_hparam' }, { name: 'bool_hparam' }, { name: 'optional_string_hparam' } ] metric_infos: [ { name: { tag: 'current_temp' } }, { name: { tag: 'delta_temp' } }, { name: { tag: 'optional_metric' } } ] """ SESSION_GROUPS = """ session_groups { name: "group_1" hparams { key: "bool_hparam" value { bool_value: true } } hparams { key: "final_temp" value { number_value: 150.0 } } hparams { key: "initial_temp" value { number_value: 270.0 } } hparams { key: "string_hparam" value { string_value: "a string" } } metric_values { name { tag: "current_temp" } value: 10 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: 15 training_step: 2 wall_time_secs: 10.0 } metric_values { name { tag: "optional_metric" } value: 33 training_step: 20 wall_time_secs: 2.0 } sessions { name: "session_1" start_time_secs: 314159 end_time_secs: 314164 status: STATUS_SUCCESS metric_values { name { tag: "current_temp" } value: 10 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: 15 training_step: 2 wall_time_secs: 10.0 } metric_values { name { tag: "optional_metric" } value: 33 training_step: 20 wall_time_secs: 2.0 } } } session_groups { name: "group_2" hparams { key: "bool_hparam" value { bool_value: false } } hparams { key: "final_temp" value { number_value: 100.0 } } hparams { key: "initial_temp" value { number_value: 280.0 } } hparams { key: "string_hparam" value { string_value: "AAAAA"}} metric_values { name { tag: "current_temp" } value: 51.0 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: 44.5 training_step: 2 wall_time_secs: 10.3333333 } sessions { name: "session_2" start_time_secs: 314159 end_time_secs: 314164 status: STATUS_SUCCESS metric_values { name { tag: "current_temp" } value: 100 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: 150 training_step: 3 wall_time_secs: 11.0 } } sessions { name: "session_3" start_time_secs: 314159 end_time_secs: 314164 status: STATUS_FAILURE metric_values { name { tag: "current_temp" } value: 1.0 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: 1.5 training_step: 2 wall_time_secs: 10.0 } } sessions { name: "session_5" start_time_secs: 314159 end_time_secs: 314164 status: STATUS_SUCCESS metric_values { name { tag: "current_temp" } value: 52.0 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: -18 training_step: 2 wall_time_secs: 10.0 } } } session_groups { name: "group_3" hparams { key: "bool_hparam" value { bool_value: true } } hparams { key: "final_temp" value { number_value: 0.000012 } } hparams { key: "initial_temp" value { number_value: 300.0 } } hparams { key: "string_hparam" value { string_value: "a string_3"}} hparams { key: 'optional_string_hparam' value { string_value: 'BB' } } metric_values { name { tag: "current_temp" } value: 101.0 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: -15100000.0 training_step: 2 wall_time_secs: 10.0 } sessions { name: "session_4" start_time_secs: 314159 end_time_secs: 314164 status: STATUS_UNKNOWN metric_values { name { tag: "current_temp" } value: 101.0 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: -151000000.0 training_step: 2 wall_time_secs: 10.0 } } } total_size: 3 """ EXPECTED_LATEX = r"""\begin{table}[tbp] \begin{tabular}{llllllll} initial\_temp & final\_temp & string\_hparam & bool\_hparam & optional\_string\_hparam & current\_temp & delta\_temp & optional\_metric \\ \hline $270$ & $150$ & a string & $1$ & & $10$ & $15$ & $33$ \\ $280$ & $100$ & AAAAA & $0$ & & $51$ & $44.5$ & - \\ $300$ & $1.2\cdot 10^{-5}$ & a string\_3 & $1$ & BB & $101$ & $-1.51\cdot 10^{7}$ & - \\ \hline \end{tabular} \end{table} """ EXPECTED_CSV = """initial_temp,final_temp,string_hparam,bool_hparam,optional_string_hparam,current_temp,delta_temp,optional_metric\r 270.0,150.0,a string,True,,10.0,15.0,33.0\r 280.0,100.0,AAAAA,False,,51.0,44.5,\r 300.0,1.2e-05,a string_3,True,BB,101.0,-15100000.0,\r """ class DownloadDataTest(tf.test.TestCase): def setUp(self): self._mock_multiplexer = mock.create_autospec( plugin_event_multiplexer.EventMultiplexer ) self._mock_tb_context = base_plugin.TBContext( multiplexer=self._mock_multiplexer ) def _run_handler(self, experiment, session_groups, response_format): experiment_proto = text_format.Merge(experiment, api_pb2.Experiment()) session_groups_proto = text_format.Merge( session_groups, api_pb2.ListSessionGroupsResponse() ) num_columns = len(experiment_proto.hparam_infos) + len( experiment_proto.metric_infos ) handler = download_data.Handler( backend_context.Context(self._mock_tb_context), experiment_proto, session_groups_proto, response_format, [True] * num_columns, ) return handler.run() def test_csv(self): body, mime_type = self._run_handler( EXPERIMENT, SESSION_GROUPS, download_data.OutputFormat.CSV ) self.assertEqual("text/csv", mime_type) self.assertEqual(EXPECTED_CSV, body) def test_latex(self): body, mime_type = self._run_handler( EXPERIMENT, SESSION_GROUPS, download_data.OutputFormat.LATEX ) self.assertEqual("application/x-latex", mime_type) self.assertEqual(EXPECTED_LATEX, body) def test_json(self): body, mime_type = self._run_handler( EXPERIMENT, SESSION_GROUPS, download_data.OutputFormat.JSON ) self.assertEqual("application/json", mime_type) expected_result = { "header": [ "initial_temp", "final_temp", "string_hparam", "bool_hparam", "optional_string_hparam", "current_temp", "delta_temp", "optional_metric", ], "rows": [ [270.0, 150.0, "a string", True, "", 10.0, 15.0, 33.0], [280.0, 100.0, "AAAAA", False, "", 51.0, 44.5, None], [ 300.0, 1.2e-05, "a string_3", True, "BB", 101.0, -15100000.0, None, ], ], } self.assertEqual(expected_result, body) if __name__ == "__main__": tf.test.main()
tensorflow/tensorboard
tensorboard/plugins/hparams/download_data_test.py
Python
apache-2.0
8,571
package com.feiyu.storm.streamingdatacollection.spout; /** * from https://github.com/apache/incubator-storm/blob/master/examples/storm-starter/src/jvm/storm/starter/spout/RandomSentenceSpout.java * modified by feiyu */ import java.util.Map; import java.util.Random; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; import backtype.storm.utils.Utils; @SuppressWarnings("serial") public class ForTestFakeSpout extends BaseRichSpout { private SpoutOutputCollector _collector; private Random _rand; @SuppressWarnings("rawtypes") @Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { _collector = collector; _rand = new Random(); } @Override public void nextTuple() { Utils.sleep(5000); String[] tweets = new String[]{ "I rated X-Men: Days of Future Past 8/10 #IMDb http://www.imdb.com/title/tt1877832", "I rated Game of Thrones 10/10 #IMDb http://www.imdb.com/title/tt0944947", "I rated Snowpiercer 7/10 #IMDb really enjoyed this. Beautifully shot & choreographed. Great performance from Swinton http://www.imdb.com/title/tt1706620", "Back on form. That ending = awesome! - I rated X-Men: Days of Future Past 7/10 #IMDb http://www.imdb.com/title/tt1877832", "A great movie especially for those trying to learn German ~> I rated Run Lola Run 8/10 #IMDb http://www.imdb.com/title/tt0130827", "I rated Breaking Bad 8/10 #IMDb :: I would say 7 but last season made it worth it... Matter of taste @mmelgarejoc http://www.imdb.com/title/tt0903747", "I rated White House Down 7/10 #IMDb bunch of explosions and one liners, fun for all http://www.imdb.com/title/tt2334879" }; String tweet = tweets[_rand.nextInt(tweets.length)]; _collector.emit(new Values(tweet)); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("tweet")); } }
faustineinsun/WiseCrowdRec
deprecated-wisecrowdrec-springmvc/WiseCrowdRec/src/main/java/com/feiyu/storm/streamingdatacollection/spout/ForTestFakeSpout.java
Java
apache-2.0
2,356
/* * Copyright 2021 HM Revenue & Customs * * 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 controllers import controllers.actions.SuccessfulAuthAction import org.scalatestplus.mockito.MockitoSugar import play.api.i18n.Messages import play.api.mvc.BodyParsers import play.api.test.FakeRequest import play.api.test.Helpers._ import utils.AmlsSpec import views.html.{unauthorised, unauthorised_role} class AmlsControllerSpec extends AmlsSpec { trait UnauthenticatedFixture extends MockitoSugar { self => implicit val unauthenticatedRequest = FakeRequest() val request = addToken(unauthenticatedRequest) lazy val view1 = app.injector.instanceOf[unauthorised] lazy val view2 = app.injector.instanceOf[unauthorised_role] val controller = new AmlsController(SuccessfulAuthAction, commonDependencies, mockMcc, messagesApi, mock[BodyParsers.Default], unauthorisedView = view1, unauthorisedRole = view2) } "AmlsController" must { "load the unauthorised page with an unauthenticated request" in new UnauthenticatedFixture { val result = controller.unauthorised(request) status(result) must be(OK) contentAsString(result) must include(Messages("unauthorised.title")) } "load the unauthorised role with an unauthenticated request" in new UnauthenticatedFixture { val result = controller.unauthorised_role(request) status(result) mustBe UNAUTHORIZED contentAsString(result) must include(Messages("unauthorised.title")) } } }
hmrc/amls-frontend
test/controllers/AmlsControllerSpec.scala
Scala
apache-2.0
2,119
/* * Copyright 2016 Axibase Corporation 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 * * https://www.axibase.com/atsd/axibase-apache-2.0.pdf * * 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.axibase.tsd.model.meta; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.experimental.Accessors; import java.util.Map; @Data /* Use chained setters that return this instead of void */ @Accessors(chain = true) @JsonIgnoreProperties(ignoreUnknown = true) public class EntityAndTags { @JsonProperty("entity") private String entityName; private Long lastInsertTime; @JsonProperty private Map<String, String> tags; }
axibase/atsd-api-java
src/main/java/com/axibase/tsd/model/meta/EntityAndTags.java
Java
apache-2.0
1,151
# paragon.storage.local Use the `paragon.storage.local` API to store, retrieve, and track changes to user data. ## Methods The 'paragon.storage.local' object has the following methods: ### get(keys, callback) Returns an object that has the properties corresponding to the keys referenced from the local storage store. * `keys` Object - String or an array of strings pointing to names in the local storage store. * `callback` function - will be called with `callback(object)`. ### set(value, callback) Adds/Replaces and saves values to the local store. * `value` Object - Value referenced in the store. * `callback` function - will be called with `callback()`. ### remove(keys, callback) Removes the item(s) referenced from the storage. * `keys` Object - Item(s) in the storage. * `callback` function - will be called with `callback()`. ### clear(callback) Deletes local storage file. * `callback` function - will be called with `callback()`.
mindthegab/SFE-Minuet-DesktopClient
docs/api/storage-local.md
Markdown
apache-2.0
957
# Astragalus lesbiacus P.Candargy SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Astracantha/Astracantha trojana/ Syn. Astragalus lesbiacus/README.md
Markdown
apache-2.0
188
# Sedum leblancei Raym.-Hamet SPECIES #### Status ACCEPTED #### According to GRIN Taxonomy for Plants #### Published in Repert. Spec. Nov. egni Veg. 8:311. 1910 #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Saxifragales/Crassulaceae/Sedum/Sedum leblancei/README.md
Markdown
apache-2.0
206
# Fraxinus fungosa Lodd. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Oleaceae/Fraxinus/Fraxinus fungosa/README.md
Markdown
apache-2.0
172
# Helichrysum dracaenifolium Humbert SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Helichrysum dracaenifolium/README.md
Markdown
apache-2.0
184
# Stipa durifolia Torres SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Stipa/Stipa durifolia/README.md
Markdown
apache-2.0
180
# Massariella bispora M.A. Curtis SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Massariella bispora M.A. Curtis ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Amphisphaeriaceae/Massariella/Massariella bispora/README.md
Markdown
apache-2.0
191
# Briza triloba var. interrupta VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Briza/Briza subaristata/ Syn. Briza triloba interrupta/README.md
Markdown
apache-2.0
186
# Raphanus sativus var. incarnatus Sazonova VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Raphanus/Raphanus sativus/Raphanus sativus incarnatus/README.md
Markdown
apache-2.0
191
# Gomphrena decumbens subvar. decumbens SUBVARIETY #### Status ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Amaranthaceae/Gomphrena/Gomphrena serrata/Gomphrena decumbens decumbens/README.md
Markdown
apache-2.0
182
<?php /** * This example populates a first party audience segment. To determine which * audience segments exist, run GetAllAudienceSegments.php. * * PHP version 5 * * Copyright 2014, Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @package GoogleApiAdsDfp * @subpackage v201611 * @category WebServices * @copyright 2014, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, * Version 2.0 */ error_reporting(E_STRICT | E_ALL); // You can set the include path to src directory or reference // DfpUser.php directly via require_once. // $path = '/path/to/dfp_api_php_lib/src'; $path = dirname(__FILE__) . '/../../../../src'; set_include_path(get_include_path() . PATH_SEPARATOR . $path); require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php'; require_once 'Google/Api/Ads/Dfp/Util/v201611/StatementBuilder.php'; require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php'; // Set the ID of the first party audience segment to populate. $audienceSegmentId = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'; try { // Get DfpUser from credentials in "../auth.ini" // relative to the DfpUser.php file's directory. $user = new DfpUser(); // Log SOAP XML request and response. $user->LogDefaults(); // Get the AudienceSegmentService. $audienceSegmentService = $user->GetService('AudienceSegmentService', 'v201611'); // Create a statement to only select a specified first party audience // segment. $statementBuilder = new StatementBuilder(); $statementBuilder->Where('id = :id and type = :type') ->OrderBy('id ASC') ->Limit(1) ->WithBindVariableValue('id', $audienceSegmentId) ->WithBindVariableValue('type', 'FIRST_PARTY'); // Default for total result set size. $totalResultSetSize = 0; do { // Get audience segments by statement. $page = $audienceSegmentService->getAudienceSegmentsByStatement( $statementBuilder->ToStatement()); // Display results. if (isset($page->results)) { $totalResultSetSize = $page->totalResultSetSize; $i = $page->startIndex; foreach ($page->results as $audienceSegment) { printf("%d) Audience segment with ID %d and name '%s' will be " . "populated.\n", $i++, $audienceSegment->id, $audienceSegment->name); } } $statementBuilder->IncreaseOffsetBy(StatementBuilder::SUGGESTED_PAGE_LIMIT); } while ($statementBuilder->GetOffset() < $totalResultSetSize); printf("Number of audience segments to be populated: %d\n", $totalResultSetSize); if ($totalResultSetSize > 0) { // Remove limit and offset from statement. $statementBuilder->RemoveLimitAndOffset(); // Create action. $action = new PopulateAudienceSegments(); // Perform action. $result = $audienceSegmentService->performAudienceSegmentAction($action, $statementBuilder->ToStatement()); // Display results. if (isset($result) && $result->numChanges > 0) { printf("Number of audience segments populated: %d\n", $result->numChanges); } else { printf("No audience segments were populated.\n"); } } } catch (OAuth2Exception $e) { ExampleUtils::CheckForOAuth2Errors($e); } catch (ValidationException $e) { ExampleUtils::CheckForOAuth2Errors($e); } catch (Exception $e) { printf("%s\n", $e->getMessage()); }
Getsidecar/googleads-php-lib
examples/Dfp/v201611/AudienceSegmentService/PopulateFirstPartyAudienceSegments.php
PHP
apache-2.0
3,948
package main import ( "log" "net/http" "github.com/gophergala/melted_brains/http_handler" "golang.org/x/net/websocket" ) func main() { http.HandleFunc("/game/", http_handler.GameHandler) http.Handle("/events/", websocket.Handler(http_handler.EventsHandler)) http.Handle("/waiting/", websocket.Handler(http_handler.EventsHandler)) http.Handle("/", http.FileServer(http.Dir("./static"))) err := http.ListenAndServe(":8000", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
gophergala/melted_brains
server.go
GO
apache-2.0
498
import React from 'react'; import renderer from 'react-test-renderer'; import VideoQuestion from './VideoQuestion'; jest.mock('expo', () => ({ Video: 'Video' })); it('renders without crashing', () => { const tree = renderer.create( <VideoQuestion video={require('../../assets/videos/placeholder.mp4')} question="Wer ist eine Ananas?" answers={[ 'Ich bin eine Ananas', 'Du bist eine Ananas', 'Wir sind eine Ananas' ]} /> ); expect(tree).toMatchSnapshot(); });
cognostics/serlo-abc
src/components/exercises/VideoQuestion.test.js
JavaScript
apache-2.0
526
# Heterodermia erinacea (Ach.) W. A. Weber SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in in Egan, Bryologist 90(2): 163 (1987) #### Original name Lichen erinaceus Ach. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Lecanoromycetes/Teloschistales/Physciaceae/Heterodermia/Heterodermia erinacea/README.md
Markdown
apache-2.0
248
#!/usr/bin/python # # Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from exaqute.ExaquteTask import * from pycompss.api.task import task from pycompss.api.api import compss_wait_on from pycompss.api.api import compss_barrier from pycompss.api.api import compss_delete_object from pycompss.api.api import compss_delete_file from pycompss.api.parameter import * from pycompss.api.implement import implement from pycompss.api.constraint import * class ExaquteTask(object): def __init__(self, *args, **kwargs): global scheduler scheduler = "Current scheduler is PyCOMPSs" self.task_instance = task(*args, **kwargs) def __call__(self, f): return self.task_instance.__call__(f) def barrier(): # Wait compss_barrier() def get_value_from_remote(obj): # Gather obj = compss_wait_on(obj) return obj def delete_object(obj): # Release compss_delete_object(obj) def delete_file(file_path): compss_delete_file(file_path) def compute(obj): # Submit task return obj
mF2C/COMPSs
compss/programming_model/bindings/python/src/exaqute/ExaquteTaskPyCOMPSs.py
Python
apache-2.0
1,613