repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
lhillah/pnmlframework
pnmlFw-PT-HLPNG/src/fr/lip6/move/pnml/pthlpng/hlcorestructure/hlapi/RefTransitionHLAPI.java
12908
/** * Copyright 2009-2016 Université Paris Ouest and Sorbonne Universités, Univ. Paris 06 - CNRS UMR 7606 (LIP6) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Project leader / Initial Contributor: * Lom Messan Hillah - <[email protected]> * * Contributors: * ${ocontributors} - <$oemails}> * * Mailing list: * [email protected] */ /** * (C) Sorbonne Universités, UPMC Univ Paris 06, UMR CNRS 7606 (LIP6) * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Lom HILLAH (LIP6) - Initial models and implementation * Rachid Alahyane (UPMC) - Infrastructure and continuous integration * Bastien Bouzerau (UPMC) - Architecture * Guillaume Giffo (UPMC) - Code generation refactoring, High-level API * * $Id ggiffo, Thu Feb 11 16:30:27 CET 2016$ */ package fr.lip6.move.pnml.pthlpng.hlcorestructure.hlapi; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.List; import org.apache.axiom.om.OMElement; import org.eclipse.emf.common.util.DiagnosticChain; import fr.lip6.move.pnml.framework.hlapi.HLAPIClass; import fr.lip6.move.pnml.framework.utils.IdRefLinker; import fr.lip6.move.pnml.framework.utils.ModelRepository; import fr.lip6.move.pnml.framework.utils.exception.InnerBuildException; import fr.lip6.move.pnml.framework.utils.exception.InvalidIDException; import fr.lip6.move.pnml.framework.utils.exception.OtherException; import fr.lip6.move.pnml.framework.utils.exception.VoidRepositoryException; import fr.lip6.move.pnml.pthlpng.hlcorestructure.Arc; import fr.lip6.move.pnml.pthlpng.hlcorestructure.HlcorestructureFactory; import fr.lip6.move.pnml.pthlpng.hlcorestructure.Name; import fr.lip6.move.pnml.pthlpng.hlcorestructure.NodeGraphics; import fr.lip6.move.pnml.pthlpng.hlcorestructure.Page; import fr.lip6.move.pnml.pthlpng.hlcorestructure.RefTransition; import fr.lip6.move.pnml.pthlpng.hlcorestructure.ToolInfo; import fr.lip6.move.pnml.pthlpng.hlcorestructure.TransitionNode; import fr.lip6.move.pnml.pthlpng.hlcorestructure.impl.HlcorestructureFactoryImpl; public class RefTransitionHLAPI implements HLAPIClass, PnObjectHLAPI, NodeHLAPI, TransitionNodeHLAPI { /** * The contained LLAPI element. */ private RefTransition item; /** * this constructor allows you to set all 'settable' values excepted container. */ public RefTransitionHLAPI(java.lang.String id , NameHLAPI name , NodeGraphicsHLAPI nodegraphics , TransitionNodeHLAPI ref) throws InvalidIDException, VoidRepositoryException {// BEGIN CONSTRUCTOR BODY HlcorestructureFactory fact = HlcorestructureFactoryImpl.eINSTANCE; synchronized (fact) { item = fact.createRefTransition(); } if (id != null) { item.setId(ModelRepository.getInstance().getCurrentIdRepository().checkId(id, this)); } if (name != null) item.setName((Name) name.getContainedItem()); if (nodegraphics != null) item.setNodegraphics((NodeGraphics) nodegraphics.getContainedItem()); if (ref != null) item.setRef((TransitionNode) ref.getContainedItem()); } /** * this constructor allows you to set all 'settable' values, including container * if any. */ public RefTransitionHLAPI(java.lang.String id , NameHLAPI name , NodeGraphicsHLAPI nodegraphics , TransitionNodeHLAPI ref , PageHLAPI containerPage) throws InvalidIDException, VoidRepositoryException {// BEGIN CONSTRUCTOR BODY HlcorestructureFactory fact = HlcorestructureFactoryImpl.eINSTANCE; synchronized (fact) { item = fact.createRefTransition(); } if (id != null) { item.setId(ModelRepository.getInstance().getCurrentIdRepository().checkId(id, this)); } if (name != null) item.setName((Name) name.getContainedItem()); if (nodegraphics != null) item.setNodegraphics((NodeGraphics) nodegraphics.getContainedItem()); if (ref != null) item.setRef((TransitionNode) ref.getContainedItem()); if (containerPage != null) item.setContainerPage((Page) containerPage.getContainedItem()); } /** * This constructor give access to required stuff only (not container if any) */ public RefTransitionHLAPI(java.lang.String id , TransitionNodeHLAPI ref) throws InvalidIDException, VoidRepositoryException {// BEGIN CONSTRUCTOR BODY HlcorestructureFactory fact = HlcorestructureFactoryImpl.eINSTANCE; synchronized (fact) { item = fact.createRefTransition(); } if (id != null) { item.setId(ModelRepository.getInstance().getCurrentIdRepository().checkId(id, this)); } if (ref != null) item.setRef((TransitionNode) ref.getContainedItem()); } /** * This constructor give access to required stuff only (and container) */ public RefTransitionHLAPI(java.lang.String id , TransitionNodeHLAPI ref , PageHLAPI containerPage) throws InvalidIDException, VoidRepositoryException {// BEGIN CONSTRUCTOR BODY HlcorestructureFactory fact = HlcorestructureFactoryImpl.eINSTANCE; synchronized (fact) { item = fact.createRefTransition(); } if (id != null) { item.setId(ModelRepository.getInstance().getCurrentIdRepository().checkId(id, this)); } if (ref != null) item.setRef((TransitionNode) ref.getContainedItem()); if (containerPage != null) item.setContainerPage((Page) containerPage.getContainedItem()); } /** * This constructor encapsulate a low level API object in HLAPI. */ public RefTransitionHLAPI(RefTransition lowLevelAPI) { item = lowLevelAPI; } // access to low level API /** * Return encapsulated object */ public RefTransition getContainedItem() { return item; } // getters giving LLAPI object /** * Return the encapsulate Low Level API object. */ public String getId() { return item.getId(); } /** * Return the encapsulate Low Level API object. */ public Name getName() { return item.getName(); } /** * Return the encapsulate Low Level API object. */ public List<ToolInfo> getToolspecifics() { return item.getToolspecifics(); } /** * Return the encapsulate Low Level API object. */ public Page getContainerPage() { return item.getContainerPage(); } /** * Return the encapsulate Low Level API object. */ public List<Arc> getInArcs() { return item.getInArcs(); } /** * Return the encapsulate Low Level API object. */ public List<Arc> getOutArcs() { return item.getOutArcs(); } /** * Return the encapsulate Low Level API object. */ public NodeGraphics getNodegraphics() { return item.getNodegraphics(); } /** * Return the encapsulate Low Level API object. */ public List<RefTransition> getReferencingTransitions() { return item.getReferencingTransitions(); } /** * Return the encapsulate Low Level API object. */ public TransitionNode getRef() { return item.getRef(); } // getters giving HLAPI object /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * * @return : null if the element is null */ public NameHLAPI getNameHLAPI() { if (item.getName() == null) return null; return new NameHLAPI(item.getName()); } /** * This accessor automatically encapsulate all elements of the selected sublist. * WARNING : this can creates a lot of new object in memory. */ public java.util.List<ToolInfoHLAPI> getToolspecificsHLAPI() { java.util.List<ToolInfoHLAPI> retour = new ArrayList<ToolInfoHLAPI>(); for (ToolInfo elemnt : getToolspecifics()) { retour.add(new ToolInfoHLAPI(elemnt)); } return retour; } /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * * @return : null if the element is null */ public PageHLAPI getContainerPageHLAPI() { if (item.getContainerPage() == null) return null; return new PageHLAPI(item.getContainerPage()); } /** * This accessor automatically encapsulate all elements of the selected sublist. * WARNING : this can creates a lot of new object in memory. */ public java.util.List<ArcHLAPI> getInArcsHLAPI() { java.util.List<ArcHLAPI> retour = new ArrayList<ArcHLAPI>(); for (Arc elemnt : getInArcs()) { retour.add(new ArcHLAPI(elemnt)); } return retour; } /** * This accessor automatically encapsulate all elements of the selected sublist. * WARNING : this can creates a lot of new object in memory. */ public java.util.List<ArcHLAPI> getOutArcsHLAPI() { java.util.List<ArcHLAPI> retour = new ArrayList<ArcHLAPI>(); for (Arc elemnt : getOutArcs()) { retour.add(new ArcHLAPI(elemnt)); } return retour; } /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * * @return : null if the element is null */ public NodeGraphicsHLAPI getNodegraphicsHLAPI() { if (item.getNodegraphics() == null) return null; return new NodeGraphicsHLAPI(item.getNodegraphics()); } /** * This accessor automatically encapsulate all elements of the selected sublist. * WARNING : this can creates a lot of new object in memory. */ public java.util.List<RefTransitionHLAPI> getReferencingTransitionsHLAPI() { java.util.List<RefTransitionHLAPI> retour = new ArrayList<RefTransitionHLAPI>(); for (RefTransition elemnt : getReferencingTransitions()) { retour.add(new RefTransitionHLAPI(elemnt)); } return retour; } /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * * @return : null if the element is null */ public TransitionNodeHLAPI getRefHLAPI() { if (item.getRef() == null) return null; TransitionNode object = item.getRef(); if (object.getClass().equals(fr.lip6.move.pnml.pthlpng.hlcorestructure.impl.RefTransitionImpl.class)) { return new fr.lip6.move.pnml.pthlpng.hlcorestructure.hlapi.RefTransitionHLAPI( (fr.lip6.move.pnml.pthlpng.hlcorestructure.RefTransition) object); } if (object.getClass().equals(fr.lip6.move.pnml.pthlpng.hlcorestructure.impl.TransitionImpl.class)) { return new fr.lip6.move.pnml.pthlpng.hlcorestructure.hlapi.TransitionHLAPI( (fr.lip6.move.pnml.pthlpng.hlcorestructure.Transition) object); } return null; } // Special getter for list of generics object, return only one object type. // setters (including container setter if aviable) /** * set Id */ public void setIdHLAPI( java.lang.String elem) throws InvalidIDException, VoidRepositoryException { if (elem != null) { try { item.setId(ModelRepository.getInstance().getCurrentIdRepository().changeId(this, elem)); } catch (OtherException e) { ModelRepository.getInstance().getCurrentIdRepository().checkId(elem, this); } } } /** * set Name */ public void setNameHLAPI( NameHLAPI elem) { if (elem != null) item.setName((Name) elem.getContainedItem()); } /** * set Nodegraphics */ public void setNodegraphicsHLAPI( NodeGraphicsHLAPI elem) { if (elem != null) item.setNodegraphics((NodeGraphics) elem.getContainedItem()); } /** * set Ref */ public void setRefHLAPI( TransitionNodeHLAPI elem) { if (elem != null) item.setRef((TransitionNode) elem.getContainedItem()); } /** * set ContainerPage */ public void setContainerPageHLAPI( PageHLAPI elem) { if (elem != null) item.setContainerPage((Page) elem.getContainedItem()); } // setters/remover for lists. public void addToolspecificsHLAPI(ToolInfoHLAPI unit) { item.getToolspecifics().add((ToolInfo) unit.getContainedItem()); } public void removeToolspecificsHLAPI(ToolInfoHLAPI unit) { item.getToolspecifics().remove((ToolInfo) unit.getContainedItem()); } // equals method public boolean equals(RefTransitionHLAPI item) { return item.getContainedItem().equals(getContainedItem()); } // PNML /** * Returns the PNML xml tree for this object. */ public String toPNML() { return item.toPNML(); } /** * Writes the PNML XML tree of this object into file channel. */ public void toPNML(FileChannel fc) { item.toPNML(fc); } /** * creates an object from the xml nodes.(symetric work of toPNML) */ public void fromPNML(OMElement subRoot, IdRefLinker idr) throws InnerBuildException, InvalidIDException, VoidRepositoryException { item.fromPNML(subRoot, idr); } public boolean validateOCL(DiagnosticChain diagnostics) { return item.validateOCL(diagnostics); } }
epl-1.0
ttimbul/eclipse.wst
bundles/org.eclipse.wst.xsd.ui/src-common/org/eclipse/wst/xsd/ui/internal/common/properties/sections/XSDFacetSectionFilter.java
1429
/******************************************************************************* * Copyright (c) 2001, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.xsd.ui.internal.common.properties.sections; import org.eclipse.jface.viewers.IFilter; import org.eclipse.xsd.XSDFeature; import org.eclipse.xsd.XSDSchema; import org.eclipse.xsd.XSDSimpleTypeDefinition; import org.eclipse.xsd.XSDTypeDefinition; public class XSDFacetSectionFilter implements IFilter { public boolean select(Object toTest) { if (toTest instanceof XSDFeature) { XSDTypeDefinition type = ((XSDFeature)toTest).getResolvedFeature().getType(); if (type instanceof XSDSimpleTypeDefinition) { return true; } } else if (toTest instanceof XSDSimpleTypeDefinition) { XSDSimpleTypeDefinition st = (XSDSimpleTypeDefinition)toTest; if (st.eContainer() instanceof XSDSchema || st.eContainer() instanceof XSDFeature) { return true; } } return false; } }
epl-1.0
lincolnthree/windup
rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/model/RMIServiceModel.java
1411
package org.jboss.windup.rules.apps.javaee.model; import org.jboss.windup.rules.apps.java.model.JavaClassModel; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.frames.Adjacency; import com.tinkerpop.frames.modules.typedgraph.TypeValue; /** * RMI Service marker interface. * * @author <a href="mailto:[email protected]">Brad Davis</a> */ @TypeValue(RMIServiceModel.TYPE) public interface RMIServiceModel extends RemoteServiceModel { public static final String TYPE = "RMIService"; public static final String RMI_IMPLEMENTATION_CLASS = "rmiImplementationClass"; public static final String RMI_INTERFACE = "rmiInterface"; /** * Contains the RMI implementation class */ @Adjacency(label = RMI_IMPLEMENTATION_CLASS, direction = Direction.OUT) public void setImplementationClass(JavaClassModel implRef); /** * Contains the RMI implementation class */ @Adjacency(label = RMI_IMPLEMENTATION_CLASS, direction = Direction.OUT) public JavaClassModel getImplementationClass(); /** * Contains the RMI implementation class */ @Adjacency(label = RMI_INTERFACE, direction = Direction.OUT) public void setInterface(JavaClassModel interfaceRef); /** * Contains the RMI implementation class */ @Adjacency(label = RMI_INTERFACE, direction = Direction.OUT) public JavaClassModel getInterface(); }
epl-1.0
bradsdavis/windup
rules-base/api/src/main/java/org/jboss/windup/rules/files/condition/FileContentHandler.java
2110
package org.jboss.windup.rules.files.condition; import static org.joox.JOOX.$; import org.apache.commons.lang.StringUtils; import org.jboss.windup.config.exception.ConfigurationException; import org.jboss.windup.config.operation.Iteration; import org.jboss.windup.config.parser.ElementHandler; import org.jboss.windup.config.parser.NamespaceElementHandler; import org.jboss.windup.config.parser.ParserContext; import org.jboss.windup.util.exception.WindupException; import org.ocpsoft.rewrite.config.Condition; import org.w3c.dom.Element; /** * Represents a {@link FileContent} {@link Condition}. * * Example: * * <pre> * &lt;filecontent pattern="Some example {text}"&gt; filename="{filename}" /&gt; * </pre> * * @author jsightler * */ @NamespaceElementHandler(elementName = FileContentHandler.ELEM_NAME, namespace = "http://windup.jboss.org/v1/xml") public class FileContentHandler implements ElementHandler<FileContent> { public static final String ELEM_NAME = "filecontent"; private static final String ATTR_PATTERN = "pattern"; private static final String ATTR_FILENAME = "filename"; @Override public FileContent processElement(ParserContext handlerManager, Element element) throws ConfigurationException { String contentPattern = $(element).attr(ATTR_PATTERN); String filenamePattern = $(element).attr(ATTR_FILENAME); String as = $(element).attr("as"); if (as == null) { as = Iteration.DEFAULT_VARIABLE_LIST_STRING; } if (StringUtils.isBlank(contentPattern)) { throw new WindupException("The '" + ELEM_NAME + "' element must have a non-empty '" + ATTR_PATTERN + "' attribute"); } if (StringUtils.isBlank(filenamePattern)) { throw new WindupException("The '" + ELEM_NAME + "' element must have a non-empty '" + ATTR_FILENAME + "' attribute"); } FileContent fileContent = FileContent.matches(contentPattern).inFilesNamed(filenamePattern); fileContent.setOutputVariablesName(as); return fileContent; } }
epl-1.0
sleshchenko/che
multiuser/api/che-multiuser-api-resource/src/test/java/org/eclipse/che/multiuser/resource/api/usage/ResourceServiceTest.java
7187
/* * Copyright (c) 2012-2018 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.multiuser.resource.api.usage; import static com.jayway.restassured.RestAssured.given; import static java.util.Collections.singletonList; import static org.everrest.assured.JettyHttpServer.ADMIN_USER_NAME; import static org.everrest.assured.JettyHttpServer.ADMIN_USER_PASSWORD; import static org.everrest.assured.JettyHttpServer.SECURE_PATH; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import com.jayway.restassured.response.Response; import java.util.ArrayList; import java.util.List; import org.eclipse.che.api.core.rest.ApiExceptionMapper; import org.eclipse.che.dto.server.DtoFactory; import org.eclipse.che.multiuser.resource.shared.dto.ProvidedResourcesDto; import org.eclipse.che.multiuser.resource.shared.dto.ResourceDto; import org.eclipse.che.multiuser.resource.shared.dto.ResourcesDetailsDto; import org.eclipse.che.multiuser.resource.spi.impl.ResourceImpl; import org.eclipse.che.multiuser.resource.spi.impl.ResourcesDetailsImpl; import org.everrest.assured.EverrestJetty; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.testng.MockitoTestNGListener; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Tests for {@link ResourceService} * * @author Sergii Leschenko */ @Listeners({EverrestJetty.class, MockitoTestNGListener.class}) public class ResourceServiceTest { private static final String RESOURCE_TYPE = "test"; private static final Long RESOURCE_AMOUNT = 1000L; private static final String RESOURCE_UNIT = "mb"; @SuppressWarnings("unused") // is declared for deploying by everrest-assured private ApiExceptionMapper exceptionMapper; @Mock ResourceImpl resource; @Mock private ResourceManager resourceManager; @InjectMocks private ResourceService service; @BeforeMethod public void setUp() throws Exception { when(resource.getType()).thenReturn(RESOURCE_TYPE); when(resource.getAmount()).thenReturn(RESOURCE_AMOUNT); when(resource.getUnit()).thenReturn(RESOURCE_UNIT); } @Test public void shouldReturnTotalResourcesForGivenAccount() throws Exception { doReturn(singletonList(resource)).when(resourceManager).getTotalResources(any()); final Response response = given() .auth() .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) .contentType("application/json") .when() .get(SECURE_PATH + "/resource/account123"); assertEquals(response.statusCode(), 200); verify(resourceManager).getTotalResources(eq("account123")); final List<ResourceDto> resources = unwrapDtoList(response, ResourceDto.class); assertEquals(resources.size(), 1); final ResourceDto fetchedResource = resources.get(0); assertEquals(fetchedResource.getType(), RESOURCE_TYPE); assertEquals(new Long(fetchedResource.getAmount()), RESOURCE_AMOUNT); assertEquals(fetchedResource.getUnit(), RESOURCE_UNIT); } @Test public void shouldReturnUsedResourcesForGivenAccount() throws Exception { doReturn(singletonList(resource)).when(resourceManager).getUsedResources(any()); final Response response = given() .auth() .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) .contentType("application/json") .when() .get(SECURE_PATH + "/resource/account123/used"); assertEquals(response.statusCode(), 200); verify(resourceManager).getUsedResources(eq("account123")); final List<ResourceDto> resources = unwrapDtoList(response, ResourceDto.class); assertEquals(resources.size(), 1); final ResourceDto fetchedResource = resources.get(0); assertEquals(fetchedResource.getType(), RESOURCE_TYPE); assertEquals(new Long(fetchedResource.getAmount()), RESOURCE_AMOUNT); assertEquals(fetchedResource.getUnit(), RESOURCE_UNIT); } @Test public void shouldReturnAvailableResourcesForGivenAccount() throws Exception { doReturn(singletonList(resource)).when(resourceManager).getAvailableResources(any()); final Response response = given() .auth() .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) .contentType("application/json") .when() .get(SECURE_PATH + "/resource/account123/available"); assertEquals(response.statusCode(), 200); verify(resourceManager).getAvailableResources(eq("account123")); final List<ResourceDto> resources = unwrapDtoList(response, ResourceDto.class); assertEquals(resources.size(), 1); final ResourceDto fetchedResource = resources.get(0); assertEquals(fetchedResource.getType(), RESOURCE_TYPE); assertEquals(new Long(fetchedResource.getAmount()), RESOURCE_AMOUNT); assertEquals(fetchedResource.getUnit(), RESOURCE_UNIT); } @Test public void testGetsResourceDetails() throws Exception { // given final ResourceDto testResource = DtoFactory.newDto(ResourceDto.class).withType("test").withAmount(1234).withUnit("mb"); final ResourcesDetailsDto toFetch = DtoFactory.newDto(ResourcesDetailsDto.class) .withAccountId("account123") .withProvidedResources( singletonList( DtoFactory.newDto(ProvidedResourcesDto.class) .withId("resource123") .withProviderId("provider") .withOwner("account123") .withStartTime(123L) .withEndTime(321L) .withResources(singletonList(testResource)))) .withTotalResources(singletonList(testResource)); // when when(resourceManager.getResourceDetails(eq("account123"))) .thenReturn(new ResourcesDetailsImpl(toFetch)); // then final Response response = given() .auth() .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) .contentType("application/json") .when() .expect() .statusCode(200) .get(SECURE_PATH + "/resource/account123/details"); final ResourcesDetailsDto resourceDetailsDto = DtoFactory.getInstance() .createDtoFromJson(response.body().print(), ResourcesDetailsDto.class); assertEquals(resourceDetailsDto, toFetch); verify(resourceManager).getResourceDetails("account123"); } private static <T> List<T> unwrapDtoList(Response response, Class<T> dtoClass) { return new ArrayList<>( DtoFactory.getInstance().createListDtoFromJson(response.body().print(), dtoClass)); } }
epl-1.0
forge/javaee-descriptors
api/src/main/java/org/jboss/shrinkwrap/descriptor/api/ejbjar30/MethodType.java
6829
package org.jboss.shrinkwrap.descriptor.api.ejbjar30; import java.util.List; import org.jboss.shrinkwrap.descriptor.api.Child; /** * This interface defines the contract for the <code> methodType </code> xsd type * @author <a href="mailto:[email protected]">Ralf Battenfeld</a> * @author <a href="mailto:[email protected]">Andrew Lee Rubinger</a> */ public interface MethodType<T> extends Child<T> { // --------------------------------------------------------------------------------------------------------|| // ClassName: MethodType ElementName: xsd:string ElementType : description // MaxOccurs: -unbounded isGeneric: true isAttribute: false isEnum: false isDataType: true // --------------------------------------------------------------------------------------------------------|| /** * Creates for all String objects representing <code>description</code> elements, * a new <code>description</code> element * @param values list of <code>description</code> objects * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> description(String ... values); /** * Returns all <code>description</code> elements * @return list of <code>description</code> */ public List<String> getAllDescription(); /** * Removes the <code>description</code> element * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> removeAllDescription(); // --------------------------------------------------------------------------------------------------------|| // ClassName: MethodType ElementName: javaee:xsdNMTOKENType ElementType : ejb-name // MaxOccurs: - isGeneric: true isAttribute: false isEnum: false isDataType: true // --------------------------------------------------------------------------------------------------------|| /** * Sets the <code>ejb-name</code> element * @param ejbName the value for the element <code>ejb-name</code> * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> ejbName(String ejbName); /** * Returns the <code>ejb-name</code> element * @return the node defined for the element <code>ejb-name</code> */ public String getEjbName(); /** * Removes the <code>ejb-name</code> element * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> removeEjbName(); // --------------------------------------------------------------------------------------------------------|| // ClassName: MethodType ElementName: javaee:method-intfType ElementType : method-intf // MaxOccurs: - isGeneric: true isAttribute: false isEnum: true isDataType: false // --------------------------------------------------------------------------------------------------------|| /** * Sets the <code>method-intf</code> element * @param methodIntf the value for the element <code>method-intf</code> * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> methodIntf(MethodIntfType methodIntf); /** * Sets the <code>method-intf</code> element * @param methodIntf the value for the element <code>method-intf</code> * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> methodIntf(String methodIntf); /** * Returns the <code>method-intf</code> element * @return the value found for the element <code>method-intf</code> */ public MethodIntfType getMethodIntf(); /** * Returns the <code>method-intf</code> element * @return the value found for the element <code>method-intf</code> */ public String getMethodIntfAsString(); /** * Removes the <code>method-intf</code> attribute * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> removeMethodIntf(); // --------------------------------------------------------------------------------------------------------|| // ClassName: MethodType ElementName: javaee:string ElementType : method-name // MaxOccurs: - isGeneric: true isAttribute: false isEnum: false isDataType: true // --------------------------------------------------------------------------------------------------------|| /** * Sets the <code>method-name</code> element * @param methodName the value for the element <code>method-name</code> * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> methodName(String methodName); /** * Returns the <code>method-name</code> element * @return the node defined for the element <code>method-name</code> */ public String getMethodName(); /** * Removes the <code>method-name</code> element * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> removeMethodName(); // --------------------------------------------------------------------------------------------------------|| // ClassName: MethodType ElementName: javaee:method-paramsType ElementType : method-params // MaxOccurs: - isGeneric: true isAttribute: false isEnum: false isDataType: false // --------------------------------------------------------------------------------------------------------|| /** * If not already created, a new <code>method-params</code> element with the given value will be created. * Otherwise, the existing <code>method-params</code> element will be returned. * @return a new or existing instance of <code>MethodParamsType<MethodType<T>></code> */ public MethodParamsType<MethodType<T>> getOrCreateMethodParams(); /** * Removes the <code>method-params</code> element * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> removeMethodParams(); // --------------------------------------------------------------------------------------------------------|| // ClassName: MethodType ElementName: xsd:ID ElementType : id // MaxOccurs: - isGeneric: true isAttribute: true isEnum: false isDataType: true // --------------------------------------------------------------------------------------------------------|| /** * Sets the <code>id</code> attribute * @param id the value for the attribute <code>id</code> * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> id(String id); /** * Returns the <code>id</code> attribute * @return the value defined for the attribute <code>id</code> */ public String getId(); /** * Removes the <code>id</code> attribute * @return the current instance of <code>MethodType<T></code> */ public MethodType<T> removeId(); }
epl-1.0
opendaylight/controller
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/InMemorySnapshotStore.java
7911
/* * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.cluster.raft.utils; import akka.dispatch.Futures; import akka.persistence.SelectedSnapshot; import akka.persistence.SnapshotMetadata; import akka.persistence.SnapshotSelectionCriteria; import akka.persistence.snapshot.japi.SnapshotStore; import com.google.common.util.concurrent.Uninterruptibles; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.concurrent.Future; /** * An akka SnapshotStore implementation that stores data in memory. This is intended for testing. * * @author Thomas Pantelis */ public class InMemorySnapshotStore extends SnapshotStore { static final Logger LOG = LoggerFactory.getLogger(InMemorySnapshotStore.class); private static final Map<String, CountDownLatch> SNAPSHOT_SAVED_LATCHES = new ConcurrentHashMap<>(); private static final Map<String, CountDownLatch> SNAPSHOT_DELETED_LATCHES = new ConcurrentHashMap<>(); private static Map<String, List<StoredSnapshot>> snapshots = new ConcurrentHashMap<>(); public static void addSnapshot(final String persistentId, final Object snapshot) { List<StoredSnapshot> snapshotList = snapshots.computeIfAbsent(persistentId, k -> new ArrayList<>()); synchronized (snapshotList) { snapshotList.add(new StoredSnapshot(new SnapshotMetadata(persistentId, snapshotList.size(), System.currentTimeMillis()), snapshot)); } } @SuppressWarnings("unchecked") public static <T> List<T> getSnapshots(final String persistentId, final Class<T> type) { List<StoredSnapshot> stored = snapshots.get(persistentId); if (stored == null) { return Collections.emptyList(); } List<T> retList; synchronized (stored) { retList = new ArrayList<>(stored.size()); for (StoredSnapshot s: stored) { if (type.isInstance(s.data)) { retList.add((T) s.data); } } } return retList; } public static void clearSnapshotsFor(final String persistenceId) { snapshots.remove(persistenceId); } public static void clear() { snapshots.clear(); } public static void addSnapshotSavedLatch(final String persistenceId) { SNAPSHOT_SAVED_LATCHES.put(persistenceId, new CountDownLatch(1)); } public static void addSnapshotDeletedLatch(final String persistenceId) { SNAPSHOT_DELETED_LATCHES.put(persistenceId, new CountDownLatch(1)); } public static <T> T waitForSavedSnapshot(final String persistenceId, final Class<T> type) { if (!Uninterruptibles.awaitUninterruptibly(SNAPSHOT_SAVED_LATCHES.get(persistenceId), 5, TimeUnit.SECONDS)) { throw new AssertionError("Snapshot was not saved"); } return getSnapshots(persistenceId, type).get(0); } public static void waitForDeletedSnapshot(final String persistenceId) { if (!Uninterruptibles.awaitUninterruptibly(SNAPSHOT_DELETED_LATCHES.get(persistenceId), 5, TimeUnit.SECONDS)) { throw new AssertionError("Snapshot was not deleted"); } } @Override public Future<Optional<SelectedSnapshot>> doLoadAsync(final String persistenceId, final SnapshotSelectionCriteria snapshotSelectionCriteria) { List<StoredSnapshot> snapshotList = snapshots.get(persistenceId); if (snapshotList == null) { return Futures.successful(Optional.<SelectedSnapshot>empty()); } synchronized (snapshotList) { for (int i = snapshotList.size() - 1; i >= 0; i--) { StoredSnapshot snapshot = snapshotList.get(i); if (matches(snapshot, snapshotSelectionCriteria)) { return Futures.successful(Optional.of(new SelectedSnapshot(snapshot.metadata, snapshot.data))); } } } return Futures.successful(Optional.<SelectedSnapshot>empty()); } private static boolean matches(final StoredSnapshot snapshot, final SnapshotSelectionCriteria criteria) { return snapshot.metadata.sequenceNr() <= criteria.maxSequenceNr() && snapshot.metadata.timestamp() <= criteria.maxTimestamp(); } @Override public Future<Void> doSaveAsync(final SnapshotMetadata snapshotMetadata, final Object obj) { List<StoredSnapshot> snapshotList = snapshots.get(snapshotMetadata.persistenceId()); LOG.trace("doSaveAsync: persistentId {}: sequenceNr: {}: timestamp {}: {}", snapshotMetadata.persistenceId(), snapshotMetadata.sequenceNr(), snapshotMetadata.timestamp(), obj); if (snapshotList == null) { snapshotList = new ArrayList<>(); snapshots.put(snapshotMetadata.persistenceId(), snapshotList); } synchronized (snapshotList) { snapshotList.add(new StoredSnapshot(snapshotMetadata, obj)); } CountDownLatch latch = SNAPSHOT_SAVED_LATCHES.get(snapshotMetadata.persistenceId()); if (latch != null) { latch.countDown(); } return Futures.successful(null); } @Override public Future<Void> doDeleteAsync(final SnapshotMetadata metadata) { List<StoredSnapshot> snapshotList = snapshots.get(metadata.persistenceId()); if (snapshotList != null) { synchronized (snapshotList) { for (int i = 0; i < snapshotList.size(); i++) { StoredSnapshot snapshot = snapshotList.get(i); if (metadata.equals(snapshot.metadata)) { snapshotList.remove(i); break; } } } } return Futures.successful(null); } @Override public Future<Void> doDeleteAsync(final String persistenceId, final SnapshotSelectionCriteria criteria) { LOG.trace("doDelete: persistentId {}: maxSequenceNr: {}: maxTimestamp {}", persistenceId, criteria.maxSequenceNr(), criteria.maxTimestamp()); List<StoredSnapshot> snapshotList = snapshots.get(persistenceId); if (snapshotList != null) { synchronized (snapshotList) { Iterator<StoredSnapshot> iter = snapshotList.iterator(); while (iter.hasNext()) { StoredSnapshot stored = iter.next(); if (matches(stored, criteria)) { LOG.trace("Deleting snapshot for sequenceNr: {}, timestamp: {}: {}", stored.metadata.sequenceNr(), stored.metadata.timestamp(), stored.data); iter.remove(); } } } } CountDownLatch latch = SNAPSHOT_DELETED_LATCHES.get(persistenceId); if (latch != null) { latch.countDown(); } return Futures.successful(null); } private static final class StoredSnapshot { private final SnapshotMetadata metadata; private final Object data; StoredSnapshot(final SnapshotMetadata metadata, final Object data) { this.metadata = metadata; this.data = data; } } }
epl-1.0
ObeoNetwork/M2Doc
plugins/org.obeonetwork.m2doc.genconf.editor/src/org/obeonetwork/m2doc/genconf/editor/command/LoadInterpreterGenerationHandler.java
2922
/******************************************************************************* * Copyright (c) 2021 Obeo. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v2.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v20.html * * Contributors: * Obeo - initial API and implementation * *******************************************************************************/ package org.obeonetwork.m2doc.genconf.editor.command; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.emf.common.util.URI; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.handlers.HandlerUtil; import org.obeonetwork.m2doc.genconf.GenconfUtils; import org.obeonetwork.m2doc.genconf.Generation; import org.obeonetwork.m2doc.genconf.editor.view.M2DocInterpreterView; import org.obeonetwork.m2doc.ide.ui.dialog.M2DocFileSelectionDialog; /** * Loads the {@link Generation} in the {@link M2DocInterpreterView}. * * @author <a href="mailto:[email protected]">Yvan Lussaud</a> */ public class LoadInterpreterGenerationHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { final IWorkbenchPart activePart = HandlerUtil.getActivePart(event); if (activePart instanceof M2DocInterpreterView) { final M2DocInterpreterView view = (M2DocInterpreterView) activePart; final Shell shell = HandlerUtil.getActiveShell(event); final M2DocFileSelectionDialog dialog = new M2DocFileSelectionDialog(shell, "Select generation file.", getFileName(view.getGenconfURI()), GenconfUtils.GENCONF_EXTENSION_FILE, false); final int dialogResult = dialog.open(); if ((dialogResult == IDialogConstants.OK_ID) && !dialog.getFileName().isEmpty()) { final URI genconfURI = URI.createPlatformResourceURI(dialog.getFileName(), true); view.setGenconfURI(genconfURI); } } return null; } /** * Gets the file name from the given {@link URI}. * * @param uri * the {@link URI} * @return the file name from the given {@link URI} */ private String getFileName(URI uri) { final String res; if (uri != null) { if (uri.isPlatformResource()) { res = uri.toPlatformString(true); } else if (uri.isFile()) { res = uri.path(); } else { res = ""; } } else { res = ""; } return res; } }
epl-1.0
ossmeter/ossmeter
web/org-ossmeter-webapp/app/org/ossmeter/repository/model/googlecode/GoogleCodeProject.java
1622
package org.ossmeter.repository.model.googlecode; import java.util.*; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import org.ossmeter.repository.model.redmine.*; import org.ossmeter.repository.model.vcs.svn.*; import org.ossmeter.repository.model.cc.forum.*; import org.ossmeter.repository.model.bts.bugzilla.*; import org.ossmeter.repository.model.cc.nntp.*; import org.ossmeter.repository.model.vcs.cvs.*; import org.ossmeter.repository.model.eclipse.*; import org.ossmeter.repository.model.googlecode.*; import org.ossmeter.repository.model.vcs.git.*; import org.ossmeter.repository.model.sourceforge.*; import org.ossmeter.repository.model.github.*; import org.ossmeter.repository.model.*; import org.ossmeter.repository.model.cc.wiki.*; import org.ossmeter.repository.model.metrics.*; import org.ossmeter.platform.factoids.*; @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property = "_type") @JsonSubTypes({ @Type(value = GoogleCodeProject.class, name="org.ossmeter.repository.model.googlecode.GoogleCodeProject"), }) @JsonIgnoreProperties(ignoreUnknown = true) public class GoogleCodeProject extends Project { protected List<GoogleDownload> downloads; protected GoogleWiki wiki; protected GoogleForum forum; protected GoogleIssueTracker issueTracker; protected int stars; public int getStars() { return stars; } public List<GoogleDownload> getDownloads() { return downloads; } }
epl-1.0
sathipal/lwm2m_over_mqtt
src/com/ibm/mqttv3/binding/MQTTResource.java
3910
package com.ibm.mqttv3.binding; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MQTTResource implements Resource { /** The logger. */ private static final Logger LOG = LoggerFactory.getLogger(MQTTResource.class); /* The resource id. */ private String id; /* The child resources. * We need a ConcurrentHashMap to have stronger guarantees in a * multi-threaded environment */ private ConcurrentHashMap<String, Resource> children; /* The parent of this resource. */ private Resource parent; /** * Constructs a new resource with the specified id. * * @param id the id */ public MQTTResource(String id) { this.id = id; this.children = new ConcurrentHashMap<String, Resource>(); } /** * Handles the GET request in the given MQTTExchange */ public void handleGET(MQTTExchange exchange) { exchange.respond(ResponseCode.METHOD_NOT_ALLOWED); } /** * Handles the POST request in the given MQTTExchange */ public void handlePOST(MQTTExchange exchange) { exchange.respond(ResponseCode.METHOD_NOT_ALLOWED); } /** * Handles the PUT request in the given MQTTExchange */ public void handlePUT(MQTTExchange exchange) { exchange.respond(ResponseCode.METHOD_NOT_ALLOWED); } /** * Handles the DELETE request in the given MQTTExchange */ public void handleDELETE(MQTTExchange exchange) { exchange.respond(ResponseCode.METHOD_NOT_ALLOWED); } @Override public synchronized void add(Resource child) { if (child.getName() == null) throw new NullPointerException("Child must have a id"); if (child.getParent() != null) child.getParent().remove(child); children.put(child.getName(), child); child.setParent(this); } /** * Adds the specified resource as child. * * @param child the child to add * @return this */ public synchronized MQTTResource add(MQTTResource child) { add( (Resource) child); return this; } /** * Adds the specified resource as child. * * @param children the children to add * @return this */ public synchronized MQTTResource add(MQTTResource... children) { for (MQTTResource child:children) add(child); return this; } @Override public synchronized boolean remove(Resource child) { Resource removed = remove(child.getName()); if (removed == child) { child.setParent(null); return true; } return false; } /** * Removes the child with the specified id and returns it. If no child * with the specified id is found, the return value is null. * * @param id the id * @return the removed resource or null */ public synchronized Resource remove(String id) { return children.remove(id); } /** * Delete this resource from its parent */ public synchronized void delete() { Resource parent = getParent(); if (parent != null) { parent.remove(this); } } /* * * Returns the parent of this resource */ @Override public Resource getParent() { return parent; } /* * Sets the parent of this resource to the given value */ public void setParent(Resource parent) { this.parent = parent; } /* * Returns the child with the given id */ @Override public Resource getChild(String id) { return children.get(id); } /* * Returns the id of this resource */ @Override public String getName() { return id; } public synchronized void setName(String id) { if (id == null) throw new NullPointerException(); String old = this.id; Resource parent = getParent(); synchronized (parent) { parent.remove(this); this.id = id; parent.add(this); } } @Override // should be used for read-only public Collection<Resource> getChildren() { return children.values(); } @Override public void handleRESET(MQTTExchange exchange) { // TODO Auto-generated method stub } }
epl-1.0
lspector/pucks
resources/public/js/development/pucks/agents/swarmer.js
1960
// Compiled by ClojureScript 1.10.520 {} goog.provide('pucks.agents.swarmer'); goog.require('cljs.core'); goog.require('pucks.util'); goog.require('pucks.globals'); goog.require('pucks.vec2D'); goog.require('pucks.agents.active'); pucks.agents.swarmer.rand_direction = (function pucks$agents$swarmer$rand_direction(){ return pucks.util.rotation__GT_relative_position.call(null,(cljs.core.rand.call(null,pucks.globals.two_pi) - pucks.globals.pi)); }); pucks.agents.swarmer.swarmer_proposals = (function pucks$agents$swarmer$swarmer_proposals(p){ return new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"acceleration","acceleration",-1213888421),(1),new cljs.core.Keyword(null,"rotation","rotation",-1728051644),pucks.util.relative_position__GT_rotation.call(null,pucks.vec2D._PLUS_v.call(null,((cljs.core.empty_QMARK_.call(null,cljs.core.filter.call(null,new cljs.core.Keyword(null,"mobile","mobile",1403078170),new cljs.core.Keyword(null,"sensed","sensed",1518013926).cljs$core$IFn$_invoke$arity$1(p))))?pucks.util.rotation__GT_relative_position.call(null,new cljs.core.Keyword(null,"rotation","rotation",-1728051644).cljs$core$IFn$_invoke$arity$1(p)):cljs.core.apply.call(null,pucks.vec2D.avgv,cljs.core.map.call(null,new cljs.core.Keyword(null,"velocity","velocity",-581524355),cljs.core.filter.call(null,new cljs.core.Keyword(null,"mobile","mobile",1403078170),new cljs.core.Keyword(null,"sensed","sensed",1518013926).cljs$core$IFn$_invoke$arity$1(p))))),pucks.agents.swarmer.rand_direction.call(null)))], null); }); pucks.agents.swarmer.swarmer = (function pucks$agents$swarmer$swarmer(){ return cljs.core.merge.call(null,pucks.agents.active.active.call(null),new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"swarmer","swarmer",727916998),true,new cljs.core.Keyword(null,"proposal-function","proposal-function",-646608988),pucks.agents.swarmer.swarmer_proposals], null)); }); //# sourceMappingURL=swarmer.js.map
epl-1.0
NABUCCO/org.nabucco.framework.generator
org.nabucco.framework.generator/conf/nbc/templates/java/service/ServiceRemoteInterfaceTemplate.java
1448
/* * Copyright 2012 PRODYNA AG * * Licensed under the Eclipse Public License (EPL), Version 1.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/eclipse-1.0.php or * http://www.nabucco.org/License.html * * 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 2011 PRODYNA AG * * Licensed under the Eclipse Public License (EPL), Version 1.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/eclipse-1.0.php or * http://nabuccosource.org/License.html * * 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. */ /** * ServiceRemoteInterfaceTemplate * * @author Nicolas Moser, PRODYNA AG */ public interface ServiceRemoteInterfaceTemplate { }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.ui/src/org/eclipse/jdt/ui/text/java/correction/CUCorrectionProposal.java
10726
/******************************************************************************* * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.text.java.correction; import org.eclipse.swt.graphics.Image; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.DocumentChange; import org.eclipse.ltk.core.refactoring.TextChange; import org.eclipse.ltk.core.refactoring.TextFileChange; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.refactoring.CompilationUnitChange; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.util.Resources; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.text.correction.CorrectionMessages; import org.eclipse.jdt.internal.ui.text.correction.proposals.EditAnnotator; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * A proposal for quick fixes and quick assists that work on a single compilation unit. Either a * {@link TextChange text change} is directly passed in the constructor or method * {@link #addEdits(IDocument, TextEdit)} is overridden to provide the text edits that are applied * to the document when the proposal is evaluated. * <p> * The proposal takes care of the preview of the changes as proposal information. * </p> * * @since 3.8 */ public class CUCorrectionProposal extends ChangeCorrectionProposal { private ICompilationUnit fCompilationUnit; private boolean fSwitchedEditor; /** * Constructs a correction proposal working on a compilation unit with a given text change. * * @param name the name that is displayed in the proposal selection dialog * @param cu the compilation unit to which the change can be applied * @param change the change that is executed when the proposal is applied or <code>null</code> * if implementors override {@link #addEdits(IDocument, TextEdit)} to provide the * text edits or {@link #createTextChange()} to provide a text change * @param relevance the relevance of this proposal * @param image the image that is displayed for this proposal or <code>null</code> if no image * is desired */ public CUCorrectionProposal(String name, ICompilationUnit cu, TextChange change, int relevance, Image image) { super(name, change, relevance, image); if (cu == null) { throw new IllegalArgumentException("Compilation unit must not be null"); //$NON-NLS-1$ } fCompilationUnit= cu; } /** * Constructs a correction proposal working on a compilation unit with a given text change. Uses * the default image for this proposal. * * @param name the name that is displayed in the proposal selection dialog * @param cu the compilation unit to which the change can be applied * @param change the change that is executed when the proposal is applied or <code>null</code> * if implementors override {@link #addEdits(IDocument, TextEdit)} to provide the * text edits or {@link #createTextChange()} to provide a text change. * @param relevance the relevance of this proposal */ public CUCorrectionProposal(String name, ICompilationUnit cu, TextChange change, int relevance) { this(name, cu, change, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); } /** * Constructs a correction proposal working on a compilation unit. * <p> * Users have to override {@link #addEdits(IDocument, TextEdit)} to provide the text edits or * {@link #createTextChange()} to provide a text change. * </p> * * @param name the name that is displayed in the proposal selection dialog * @param cu the compilation unit on that the change works * @param relevance the relevance of this proposal * @param image the image that is displayed for this proposal or <code>null</code> if no image * is desired */ protected CUCorrectionProposal(String name, ICompilationUnit cu, int relevance, Image image) { this(name, cu, null, relevance, image); } /** * Called when the {@link CompilationUnitChange} is initialized. Subclasses can override to add * text edits to the root edit of the change. Implementors must not access the proposal, e.g. * not call {@link #getChange()}. * <p> * The default implementation does not add any edits * </p> * * @param document content of the underlying compilation unit. To be accessed read only. * @param editRoot The root edit to add all edits to * @throws CoreException can be thrown if adding the edits is failing. */ protected void addEdits(IDocument document, TextEdit editRoot) throws CoreException { // empty default implementation } @Override public Object getAdditionalProposalInfo(IProgressMonitor monitor) { StringBuffer buf= new StringBuffer(); try { TextChange change= getTextChange(); change.setKeepPreviewEdits(true); IDocument previewDocument= change.getPreviewDocument(monitor); TextEdit rootEdit= change.getPreviewEdit(change.getEdit()); EditAnnotator ea= new EditAnnotator(buf, previewDocument); rootEdit.accept(ea); ea.unchangedUntil(previewDocument.getLength()); // Final pre-existing region } catch (CoreException e) { JavaPlugin.log(e); } return buf.toString(); } @Override public void apply(IDocument document) { try { ICompilationUnit unit= getCompilationUnit(); IEditorPart part= null; if (unit.getResource().exists()) { boolean canEdit= performValidateEdit(unit); if (!canEdit) { return; } part= EditorUtility.isOpenInEditor(unit); if (part == null) { part= JavaUI.openInEditor(unit); if (part != null) { fSwitchedEditor= true; document= JavaUI.getDocumentProvider().getDocument(part.getEditorInput()); } } IWorkbenchPage page= JavaPlugin.getActivePage(); if (page != null && part != null) { page.bringToTop(part); } if (part != null) { part.setFocus(); } } performChange(part, document); } catch (CoreException e) { ExceptionHandler.handle(e, CorrectionMessages.CUCorrectionProposal_error_title, CorrectionMessages.CUCorrectionProposal_error_message); } } private boolean performValidateEdit(ICompilationUnit unit) { IStatus status= Resources.makeCommittable(unit.getResource(), JavaPlugin.getActiveWorkbenchShell()); if (!status.isOK()) { String label= CorrectionMessages.CUCorrectionProposal_error_title; String message= CorrectionMessages.CUCorrectionProposal_error_message; ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), label, message, status); return false; } return true; } /** * Creates the text change for this proposal. * This method is only called once and only when no text change has been passed in * {@link #CUCorrectionProposal(String, ICompilationUnit, TextChange, int, Image)}. * * @return the created text change * @throws CoreException if the creation of the text change failed */ protected TextChange createTextChange() throws CoreException { ICompilationUnit cu= getCompilationUnit(); String name= getName(); TextChange change; if (!cu.getResource().exists()) { String source; try { source= cu.getSource(); } catch (JavaModelException e) { JavaPlugin.log(e); source= new String(); // empty } Document document= new Document(source); document.setInitialLineDelimiter(StubUtility.getLineDelimiterUsed(cu)); change= new DocumentChange(name, document); } else { CompilationUnitChange cuChange = new CompilationUnitChange(name, cu); cuChange.setSaveMode(TextFileChange.LEAVE_DIRTY); change= cuChange; } TextEdit rootEdit= new MultiTextEdit(); change.setEdit(rootEdit); // initialize text change IDocument document= change.getCurrentDocument(new NullProgressMonitor()); addEdits(document, rootEdit); return change; } @Override protected final Change createChange() throws CoreException { return createTextChange(); // make sure that only text changes are allowed here } /** * Returns the text change that is invoked when the change is applied. * * @return the text change that is invoked when the change is applied * @throws CoreException if accessing the change failed */ public final TextChange getTextChange() throws CoreException { return (TextChange) getChange(); } /** * The compilation unit on which the change works. * * @return the compilation unit on which the change works */ public final ICompilationUnit getCompilationUnit() { return fCompilationUnit; } /** * Creates a preview of the content of the compilation unit after applying the change. * * @return the preview of the changed compilation unit * @throws CoreException if the creation of the change failed * * @noreference This method is not intended to be referenced by clients. */ public String getPreviewContent() throws CoreException { return getTextChange().getPreviewContent(new NullProgressMonitor()); } @Override public String toString() { try { return getPreviewContent(); } catch (CoreException e) { // didn't work out } return super.toString(); } /** * Returns whether the changed compilation unit was not previously open in an editor. * * @return <code>true</code> if the changed compilation unit was not previously open in an * editor, <code>false</code> if the changed compilation unit was already open in an * editor * * @noreference This method is not intended to be referenced by clients. */ protected boolean didOpenEditor() { return fSwitchedEditor; } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/eclipselink.extension.oracle.test/src/org/eclipse/persistence/testing/tests/plsqlrecord/PLSQLrecordInOutTestSet.java
19740
// Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved. package org.eclipse.persistence.testing.tests.plsqlrecord; // javase imports import java.io.FileInputStream; import java.io.StringReader; import java.math.BigDecimal; import java.sql.Date; import java.util.Properties; import org.w3c.dom.Document; // JUnit imports import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; // TopLink imports import org.eclipse.persistence.internal.helper.NonSynchronizedVector; import org.eclipse.persistence.internal.sessions.factories.ObjectPersistenceWorkbenchXMLProject; import org.eclipse.persistence.oxm.XMLContext; import org.eclipse.persistence.oxm.XMLMarshaller; import org.eclipse.persistence.platform.database.jdbc.JDBCTypes; import org.eclipse.persistence.platform.database.oracle.plsql.PLSQLStoredProcedureCall; import org.eclipse.persistence.platform.database.oracle.plsql.PLSQLrecord; import org.eclipse.persistence.queries.ReadObjectQuery; import org.eclipse.persistence.sessions.DatabaseSession; import org.eclipse.persistence.sessions.Project; import org.eclipse.persistence.sessions.Session; import org.eclipse.persistence.sessions.factories.XMLProjectReader; // other imports import static org.eclipse.persistence.testing.tests.plsqlrecord.PLSQLrecordTestHelper.CONSTANT_PROJECT_BUILD_VERSION; import static org.eclipse.persistence.testing.tests.plsqlrecord.PLSQLrecordTestHelper.buildTestProject; import static org.eclipse.persistence.testing.tests.plsqlrecord.PLSQLrecordTestHelper.buildWorkbenchXMLProject; import static org.eclipse.persistence.testing.tests.plsqlrecord.PLSQLrecordTestHelper.comparer; import static org.eclipse.persistence.testing.tests.plsqlrecord.PLSQLrecordTestHelper.TEST_DOT_PROPERTIES_KEY; import static org.eclipse.persistence.testing.tests.plsqlrecord.PLSQLrecordTestHelper.xmlParser; public class PLSQLrecordInOutTestSet { // testsuite fixture(s) static ObjectPersistenceWorkbenchXMLProject workbenchXMLProject; static Project project = null; @BeforeClass public static void setUpProjects() { try { Properties p = new Properties(); String testPropertiesPath = System.getProperty(TEST_DOT_PROPERTIES_KEY); p.load(new FileInputStream(testPropertiesPath)); project = buildTestProject(p); workbenchXMLProject = buildWorkbenchXMLProject(); } catch (Exception e) { fail("error setting up Project's database properties " + e.getMessage()); } } @Test public void writeToXml() { PLSQLrecord r1 = new PLSQLrecord(); r1.setTypeName("emp%ROWTYPE"); r1.addField("EMPNO", JDBCTypes.NUMERIC_TYPE, 4, 0); r1.addField("ENAME", JDBCTypes.VARCHAR_TYPE, 10); r1.addField("JOB", JDBCTypes.VARCHAR_TYPE, 9); r1.addField("MGR", JDBCTypes.NUMERIC_TYPE, 4, 0); r1.addField("HIREDATE", JDBCTypes.DATE_TYPE); r1.addField("SAL", JDBCTypes.FLOAT_TYPE, 7, 2); r1.addField("COMM", JDBCTypes.NUMERIC_TYPE, 7, 2); r1.addField("DEPTNO", JDBCTypes.NUMERIC_TYPE, 2, 0); // PROCEDURE REC_TEST_INOUT(Z IN OUT EMP%ROWTYPE) PLSQLStoredProcedureCall call = new PLSQLStoredProcedureCall(); call.setProcedureName("REC_TEST_INOUT"); call.addNamedInOutputArgument("Z", r1); ReadObjectQuery query = new ReadObjectQuery(PLSQLEmployeeType.class); query.addArgument("EMPNO", BigDecimal.class); query.addArgument("ENAME", String.class); query.addArgument("JOB", String.class); query.addArgument("MGR", BigDecimal.class); query.addArgument("HIREDATE", java.sql.Date.class); query.addArgument("SAL", Float.class); query.addArgument("COMM", BigDecimal.class); query.addArgument("DEPTNO", BigDecimal.class); query.doNotCacheQueryResults(); query.dontMaintainCache(); query.setCall(call); project.getDescriptor(PLSQLEmployeeType.class).getQueryManager().addQuery("PLSQLrecordInOut", query); Project projectToXml = (Project)project.clone(); // trim off login 'cause it changes under test - this way, a comparison // can be done to a control document projectToXml.setDatasourceLogin(null); XMLContext context = new XMLContext(workbenchXMLProject); XMLMarshaller marshaller = context.createMarshaller(); Document doc = marshaller.objectToXML(projectToXml); Document controlDoc = xmlParser.parse(new StringReader(PLSQLRECORD_INOUT_PROJECT_XML)); assertTrue("control document not same as instance document", comparer.isNodeEqual(controlDoc, doc)); } public static final String PLSQLRECORD_INOUT_PROJECT_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<eclipselink:object-persistence version=\"" + CONSTANT_PROJECT_BUILD_VERSION + "\"" + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xmlns:eclipselink=\"http://xmlns.oracle.com/ias/xsds/eclipselink\">" + "<eclipselink:name>PLSQLrecordProject</eclipselink:name>" + "<eclipselink:class-mapping-descriptors>" + "<eclipselink:class-mapping-descriptor xsi:type=\"eclipselink:object-relational-class-mapping-descriptor\">" + "<eclipselink:class>org.eclipse.persistence.testing.tests.plsqlrecord.PLSQLEmployeeType</eclipselink:class>" + "<eclipselink:alias>PLSQLEmployeeType</eclipselink:alias>" + "<eclipselink:primary-key>" + "<eclipselink:field name=\"EMPNO\" xsi:type=\"eclipselink:column\"/>" + "</eclipselink:primary-key>" + "<eclipselink:events xsi:type=\"eclipselink:event-policy\"/>" + "<eclipselink:querying xsi:type=\"eclipselink:query-policy\">" + "<eclipselink:queries>" + "<eclipselink:query name=\"PLSQLrecordInOut\" xsi:type=\"eclipselink:read-object-query\">" + "<eclipselink:arguments>" + "<eclipselink:argument name=\"EMPNO\">" + "<eclipselink:type>java.math.BigDecimal</eclipselink:type>" + "</eclipselink:argument>" + "<eclipselink:argument name=\"ENAME\">" + "<eclipselink:type>java.lang.String</eclipselink:type>" + "</eclipselink:argument>" + "<eclipselink:argument name=\"JOB\">" + "<eclipselink:type>java.lang.String</eclipselink:type>" + "</eclipselink:argument>" + "<eclipselink:argument name=\"MGR\">" + "<eclipselink:type>java.math.BigDecimal</eclipselink:type>" + "</eclipselink:argument>" + "<eclipselink:argument name=\"HIREDATE\">" + "<eclipselink:type>java.sql.Date</eclipselink:type>" + "</eclipselink:argument>" + "<eclipselink:argument name=\"SAL\">" + "<eclipselink:type>java.lang.Float</eclipselink:type>" + "</eclipselink:argument>" + "<eclipselink:argument name=\"COMM\">" + "<eclipselink:type>java.math.BigDecimal</eclipselink:type>" + "</eclipselink:argument>" + "<eclipselink:argument name=\"DEPTNO\">" + "<eclipselink:type>java.math.BigDecimal</eclipselink:type>" + "</eclipselink:argument>" + "</eclipselink:arguments>" + "<eclipselink:maintain-cache>false</eclipselink:maintain-cache>" + "<eclipselink:call xsi:type=\"eclipselink:plsql-stored-procedure-call\">" + "<eclipselink:procedure-name>REC_TEST_INOUT</eclipselink:procedure-name>" + "<eclipselink:arguments>" + "<eclipselink:argument xsi:type=\"eclipselink:plsql-record\">" + "<eclipselink:name>Z</eclipselink:name>" + "<eclipselink:index>0</eclipselink:index>" + "<eclipselink:direction>INOUT</eclipselink:direction>" + "<eclipselink:record-name>Z</eclipselink:record-name>" + "<eclipselink:type-name>emp%ROWTYPE</eclipselink:type-name>" + "<eclipselink:fields>" + "<eclipselink:field xsi:type=\"eclipselink:jdbc-type\" type-name=\"NUMERIC_TYPE\">" + "<eclipselink:name>EMPNO</eclipselink:name>" + "<eclipselink:precision>4</eclipselink:precision>" + "<eclipselink:scale>0</eclipselink:scale>" + "</eclipselink:field>" + "<eclipselink:field xsi:type=\"eclipselink:jdbc-type\" type-name=\"VARCHAR_TYPE\">" + "<eclipselink:name>ENAME</eclipselink:name>" + "<eclipselink:length>10</eclipselink:length>" + "</eclipselink:field>" + "<eclipselink:field xsi:type=\"eclipselink:jdbc-type\" type-name=\"VARCHAR_TYPE\">" + "<eclipselink:name>JOB</eclipselink:name>" + "<eclipselink:length>9</eclipselink:length>" + "</eclipselink:field>" + "<eclipselink:field xsi:type=\"eclipselink:jdbc-type\" type-name=\"NUMERIC_TYPE\">" + "<eclipselink:name>MGR</eclipselink:name>" + "<eclipselink:precision>4</eclipselink:precision>" + "<eclipselink:scale>0</eclipselink:scale>" + "</eclipselink:field>" + "<eclipselink:field xsi:type=\"eclipselink:jdbc-type\" type-name=\"DATE_TYPE\">" + "<eclipselink:name>HIREDATE</eclipselink:name>" + "</eclipselink:field>" + "<eclipselink:field xsi:type=\"eclipselink:jdbc-type\" type-name=\"FLOAT_TYPE\">" + "<eclipselink:name>SAL</eclipselink:name>" + "<eclipselink:precision>7</eclipselink:precision>" + "<eclipselink:scale>2</eclipselink:scale>" + "</eclipselink:field>" + "<eclipselink:field xsi:type=\"eclipselink:jdbc-type\" type-name=\"NUMERIC_TYPE\">" + "<eclipselink:name>COMM</eclipselink:name>" + "<eclipselink:precision>7</eclipselink:precision>" + "<eclipselink:scale>2</eclipselink:scale>" + "</eclipselink:field>" + "<eclipselink:field xsi:type=\"eclipselink:jdbc-type\" type-name=\"NUMERIC_TYPE\">" + "<eclipselink:name>DEPTNO</eclipselink:name>" + "<eclipselink:precision>2</eclipselink:precision>" + "<eclipselink:scale>0</eclipselink:scale>" + "</eclipselink:field>" + "</eclipselink:fields>" + "</eclipselink:argument>" + "</eclipselink:arguments>" + "</eclipselink:call>" + "<eclipselink:reference-class>org.eclipse.persistence.testing.tests.plsqlrecord.PLSQLEmployeeType</eclipselink:reference-class>" + "</eclipselink:query>" + "</eclipselink:queries>" + "</eclipselink:querying>" + "<eclipselink:attribute-mappings>" + "<eclipselink:attribute-mapping xsi:type=\"eclipselink:direct-mapping\">" + "<eclipselink:attribute-name>employeeNumber</eclipselink:attribute-name>" + "<eclipselink:field name=\"EMPNO\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:attribute-classification>java.math.BigDecimal</eclipselink:attribute-classification>" + "</eclipselink:attribute-mapping>" + "<eclipselink:attribute-mapping xsi:type=\"eclipselink:direct-mapping\">" + "<eclipselink:attribute-name>name</eclipselink:attribute-name>" + "<eclipselink:field name=\"ENAME\" xsi:type=\"eclipselink:column\"/>" + "</eclipselink:attribute-mapping>" + "<eclipselink:attribute-mapping xsi:type=\"eclipselink:direct-mapping\">" + "<eclipselink:attribute-name>job</eclipselink:attribute-name>" + "<eclipselink:field name=\"JOB\" xsi:type=\"eclipselink:column\"/>" + "</eclipselink:attribute-mapping>" + "<eclipselink:attribute-mapping xsi:type=\"eclipselink:direct-mapping\">" + "<eclipselink:attribute-name>manager</eclipselink:attribute-name>" + "<eclipselink:field name=\"MGR\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:attribute-classification>java.math.BigDecimal</eclipselink:attribute-classification>" + "</eclipselink:attribute-mapping>" + "<eclipselink:attribute-mapping xsi:type=\"eclipselink:direct-mapping\">" + "<eclipselink:attribute-name>hireDate</eclipselink:attribute-name>" + "<eclipselink:field name=\"HIREDATE\" xsi:type=\"eclipselink:column\"/>" + "</eclipselink:attribute-mapping>" + "<eclipselink:attribute-mapping xsi:type=\"eclipselink:direct-mapping\">" + "<eclipselink:attribute-name>salary</eclipselink:attribute-name>" + "<eclipselink:field name=\"SAL\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:attribute-classification>java.lang.Float</eclipselink:attribute-classification>" + "</eclipselink:attribute-mapping>" + "<eclipselink:attribute-mapping xsi:type=\"eclipselink:direct-mapping\">" + "<eclipselink:attribute-name>commission</eclipselink:attribute-name>" + "<eclipselink:field name=\"COMM\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:attribute-classification>java.lang.Float</eclipselink:attribute-classification>" + "</eclipselink:attribute-mapping>" + "<eclipselink:attribute-mapping xsi:type=\"eclipselink:direct-mapping\">" + "<eclipselink:attribute-name>department</eclipselink:attribute-name>" + "<eclipselink:field name=\"DEPTNO\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:attribute-classification>java.math.BigDecimal</eclipselink:attribute-classification>" + "</eclipselink:attribute-mapping>" + "</eclipselink:attribute-mappings>" + "<eclipselink:descriptor-type>independent</eclipselink:descriptor-type>" + "<eclipselink:instantiation/>" + "<eclipselink:copying xsi:type=\"eclipselink:instantiation-copy-policy\"/>" + "<eclipselink:tables>" + "<eclipselink:table name=\"EMP\"/>" + "</eclipselink:tables>" + "<eclipselink:structure>EMP_TYPE</eclipselink:structure>" + "<eclipselink:field-order>" + "<eclipselink:field name=\"EMPNO\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:field name=\"ENAME\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:field name=\"JOB\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:field name=\"MGR\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:field name=\"HIREDATE\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:field name=\"SAL\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:field name=\"COMM\" xsi:type=\"eclipselink:column\"/>" + "<eclipselink:field name=\"DEPTNO\" xsi:type=\"eclipselink:column\"/>" + "</eclipselink:field-order>" + "</eclipselink:class-mapping-descriptor>" + "</eclipselink:class-mapping-descriptors>" + "</eclipselink:object-persistence>"; @Test public void readFromXml() { Project projectFromXML = XMLProjectReader.read(new StringReader(PLSQLRECORD_INOUT_PROJECT_XML), this.getClass().getClassLoader()); projectFromXML.setDatasourceLogin(project.getDatasourceLogin()); project = projectFromXML; } @Test public void runQuery() { Session s = project.createDatabaseSession(); s.dontLogMessages(); ((DatabaseSession)s).login(); NonSynchronizedVector queryArgs = new NonSynchronizedVector(); queryArgs.add(new BigDecimal(10)); queryArgs.add("MikeNorman"); queryArgs.add("Developer"); queryArgs.add(null); queryArgs.add(new Date(System.currentTimeMillis())); queryArgs.add(new BigDecimal(3000)); queryArgs.add(null); queryArgs.add(new BigDecimal(20)); boolean worked = false; String msg = null; PLSQLEmployeeType result = null; try { result = (PLSQLEmployeeType)s.executeQuery("PLSQLrecordInOut", PLSQLEmployeeType.class, queryArgs); worked = true; } catch (Exception e) { msg = e.getMessage(); } assertTrue("invocation rec_test_inout failed: " + msg, worked); assertNotNull("result is supposed to be not-null", result); assertTrue("incorrect EMPNO" , result.employeeNumber.equals(new BigDecimal(1234))); assertTrue("incorrect ENAME" , result.name.equals("GOOFY")); assertTrue("incorrect JOB" , result.job.equals("ACTOR")); assertNull("MGR is supposed to be null", result.manager); assertTrue("incorrect SAL" , result.salary.equals(new Float(3500))); assertNull("COMM is supposed to be null", result.commission); assertTrue("incorrect DEPTNO" , result.department.equals(new BigDecimal(20))); ((DatabaseSession)s).logout(); } }
epl-1.0
sehrgut/minecraft-smp-mocreatures
moCreatures/server/core/sources/net/minecraft/src/EnumMovingObjectType.java
1154
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) braces deadcode package net.minecraft.src; // Referenced classes of package net.minecraft.src: // MovingObjectPosition public enum EnumMovingObjectType { TILE, ENTITY; /* public static EnumMovingObjectType[] values() { return (EnumMovingObjectType[])c.clone(); } public static EnumMovingObjectType valueOf(String s) { return (EnumMovingObjectType)Enum.valueOf(net.minecraft.src.EnumMovingObjectType.class, s); } private EnumMovingObjectType(String s, int i) { //super(s, i); } public static final EnumMovingObjectType TILE; public static final EnumMovingObjectType ENTITY; */ //private static final EnumMovingObjectType c[]; /* synthetic field */ /* static { TILE = new EnumMovingObjectType("TILE", 0); ENTITY = new EnumMovingObjectType("ENTITY", 1); c = (new EnumMovingObjectType[] { TILE, ENTITY }); } */ }
epl-1.0
FraunhoferESK/ernest-eclipse-integration
de.fraunhofer.esk.ernest.core.analysis/src/de/fraunhofer/esk/ernest/core/analysis/analyses/AnalysisUtil.java
4266
/******************************************************************************* * Copyright (c) 2015 Fraunhofer Institute for Embedded Systems and * Communication Technologies ESK * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * This file is part of ERNEST. * * Contributors: * Fraunhofer ESK - initial API and implementation *******************************************************************************/ package de.fraunhofer.esk.ernest.core.analysis.analyses; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.SortedSet; import org.eclipse.emf.common.util.EList; import ernest.Model; import ernest.architecture.Port; import ernest.timingspecification.Constraint; import ernest.tracing.TracingResults; import ernest.util.TraceReader; /** * Class that provides Utility methods for converting ERNEST Ports to TADL * Events. * <p> * Also provides access to specific data in the model. * * */ public class AnalysisUtil { /** * A CseCodeType that is used every time a CseCodeType is needed in the * Plug-In. * <p> * */ public static final Time.CseCodeType TIMEUNIT = Time.CseCodeType.ONE_MSEC; /** * Will convert one {@link Port} into one {@link Event}. * <p> * Iterates over the {@link TracingResults} of a ERNESTModel and stores all * {@link EventOccurrence}, that happened on the given port, as a Event. * * @param port * the port the Event will be created for * @param eventOcc * TracingResults of a model * @return Event for the given Port */ public static Event convertERNESTPortToTADLEvent(Port port, Map<Port,? extends SortedSet<Long>> eventOcc) { Event result = new Event(); SortedSet<Long> eventSet = eventOcc.get(port); for (Long entryValue : eventSet) { result.triggered(new Time(entryValue, AnalysisUtil.TIMEUNIT)); } return result; } /** * Will convert a List of ports into a List of Events. * <p> * Iterates over a List of Ports and uses the convertERNESTPortToTADLEvent * method on every port to create a List of Event objects. * * @param ports * a list of {@link Port} objects * @param eventOcc * TracingResults of a model * @return a list of {@link Event} objects */ public static ArrayList<Event> convertERNESTPortListToTADLEventList( List<Port> ports, Map<Port,? extends SortedSet<Long>> eventOcc) { ArrayList<Event> results = new ArrayList<Event>(); for (Port port : ports) { results.add(convertERNESTPortToTADLEvent(port, eventOcc)); } return results; } /** * Returns the EventOccurrences list of an ERNEST model. * * @param model * the model * @return the list of EventOccurrences */ public static Map<Port, ? extends SortedSet<Long>> getEventOccurrences(Model model) { if (null == model.getTracingResults()) { return null; } TracingResults tracingResults = model.getTracingResults(); if (tracingResults.getTrace() != null) { TraceReader traceReader = tracingResults.getTrace().getTraceReader(); if (traceReader != null) { return traceReader.getEvents(); } } return Collections.emptyMap(); } /** * Returns the Constraint list of an ERNEST model. * * @param model * the model * @return the list of Constraints */ public static EList<Constraint> getConstraints(Model model) { if (null == model.getTimingModel()) { return null; } return model.getTimingModel().getConstraints(); } /** * Returns a new {@link Time} Object with the given time value. * <p> * * @param time * the time value * @return new Time object */ public static Time getTime(float time) { return new Time(time, TIMEUNIT); } /** * Returns a new {@link Time} Object with the given time value. * <p> * double will be converted in float. * * @param time * the time value * @return new Time object */ public static Time getTime(double time) { return new Time((float) time, TIMEUNIT); } }
epl-1.0
debrief/debrief
org.mwc.asset.legacy/src/ASSET/Util/XML/Sensors/NarrowbandHandler.java
3114
package ASSET.Util.XML.Sensors; /******************************************************************************* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2020, Deep Blue C Technology Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *******************************************************************************/ import ASSET.Models.SensorType; import MWC.GenericData.Duration; import MWC.Utilities.ReaderWriter.XML.Util.DurationHandler; public abstract class NarrowbandHandler extends CoreSensorHandler { private final static String type = "NarrowbandSensor"; protected final static String STEADY_TIME = "SteadyTime"; protected final static String AMBIGUOUS = "Ambiguous"; protected final static String SECOND_HARMONIC = "SecondHarmonic"; static public void exportThis(final Object toExport, final org.w3c.dom.Element parent, final org.w3c.dom.Document doc) { // create ourselves final org.w3c.dom.Element thisPart = doc.createElement(type); // get data item final ASSET.Models.Sensor.Initial.NarrowbandSensor bb = (ASSET.Models.Sensor.Initial.NarrowbandSensor) toExport; CoreSensorHandler.exportCoreSensorBits(thisPart, bb); DurationHandler.exportDuration(STEADY_TIME, bb.getSteadyTime(), thisPart, doc); parent.appendChild(thisPart); } protected Duration _mySteadyTime; protected Boolean _hasBearing = false; protected Boolean _secondHarmonic = null; protected Boolean _isAmbiguous = null; public NarrowbandHandler() { this(type); } public NarrowbandHandler(final String myType) { super(myType); super.addHandler(new DurationHandler(STEADY_TIME) { @Override public void setDuration(final Duration res) { _mySteadyTime = res; } }); super.addAttributeHandler(new HandleBooleanAttribute(AMBIGUOUS) { @Override public void setValue(final String name, final boolean val) { _isAmbiguous = val; } }); super.addAttributeHandler(new HandleBooleanAttribute(SECOND_HARMONIC) { @Override public void setValue(final String name, final boolean value) { _secondHarmonic = value; } }); } /** * method for child class to instantiate sensor * * @param myId * @param myName * @return the new sensor */ @Override protected SensorType getSensor(final int myId) { // get this instance final ASSET.Models.Sensor.Initial.NarrowbandSensor bb = new ASSET.Models.Sensor.Initial.NarrowbandSensor(myId); super.configureSensor(bb); bb.setSteadyTime(_mySteadyTime); if (_secondHarmonic != null) { bb.setSecondHarmonic(_secondHarmonic.booleanValue()); } _secondHarmonic = null; _mySteadyTime = null; return bb; } }
epl-1.0
FMCalisto/phonebook
target/generated-sources/dml-maven-plugin/pt/ist/fenixframework/adt/bplustree/InnerNodeArray_Base.java
3358
package pt.ist.fenixframework.adt.bplustree; import pt.ist.fenixframework.backend.jvstmojb.pstm.RelationList; import pt.ist.fenixframework.backend.jvstmojb.ojb.OJBFunctionalSetWrapper; import pt.ist.fenixframework.ValueTypeSerializer; @SuppressWarnings("all") public abstract class InnerNodeArray_Base extends pt.ist.fenixframework.adt.bplustree.AbstractNodeArray { // Static Slots // Slots // Role Slots // Init Instance private void initInstance() { init$Instance(true); } @Override protected void init$Instance(boolean allocateOnly) { super.init$Instance(allocateOnly); } // Constructors protected InnerNodeArray_Base() { super(); } // Getters and Setters public pt.ist.fenixframework.adt.bplustree.DoubleArray<AbstractNodeArray> getSubNodes() { return ((DO_State)this.get$obj$state(false)).subNodes; } public void setSubNodes(pt.ist.fenixframework.adt.bplustree.DoubleArray<AbstractNodeArray> subNodes) { ((DO_State)this.get$obj$state(true)).subNodes = subNodes; } private java.lang.Object get$subNodes() { pt.ist.fenixframework.adt.bplustree.DoubleArray<AbstractNodeArray> value = ((DO_State)this.get$obj$state(false)).subNodes; return (value == null) ? null : pt.ist.fenixframework.backend.jvstmojb.repository.ToSqlConverter.getValueForSerializable(ValueTypeSerializer.serialize$BackingArrays(value)); } private final void set$subNodes(java.io.Serializable value, pt.ist.fenixframework.backend.jvstmojb.pstm.OneBoxDomainObject.DO_State obj$state) { ((DO_State)obj$state).subNodes = (pt.ist.fenixframework.adt.bplustree.DoubleArray<AbstractNodeArray>)((value == null) ? null : ValueTypeSerializer.deSerialize$BackingArrays(value)); } // Role Methods protected void checkDisconnected() { super.checkDisconnected(); DO_State castedState = (DO_State)this.get$obj$state(false); } protected void readStateFromResultSet(java.sql.ResultSet rs, pt.ist.fenixframework.backend.jvstmojb.pstm.OneBoxDomainObject.DO_State state) throws java.sql.SQLException { super.readStateFromResultSet(rs, state); DO_State castedState = (DO_State)state; set$subNodes(pt.ist.fenixframework.backend.jvstmojb.repository.ResultSetReader.readSerializable(rs, "SUB_NODES"), state); } protected pt.ist.fenixframework.dml.runtime.Relation get$$relationFor(String attrName) { return super.get$$relationFor(attrName); } protected pt.ist.fenixframework.backend.jvstmojb.pstm.OneBoxDomainObject.DO_State make$newState() { return new DO_State(); } protected void create$allLists() { super.create$allLists(); } protected static class DO_State extends pt.ist.fenixframework.adt.bplustree.AbstractNodeArray.DO_State { private pt.ist.fenixframework.adt.bplustree.DoubleArray<AbstractNodeArray> subNodes; protected void copyTo(pt.ist.fenixframework.backend.jvstmojb.pstm.OneBoxDomainObject.DO_State newState) { super.copyTo(newState); DO_State newCasted = (DO_State)newState; newCasted.subNodes = this.subNodes; } } }
epl-1.0
sehrgut/minecraft-smp-mocreatures
moCreatures/client - Copie/debug/sources/net/minecraft/src/EntityFlyerMob.java
8172
package net.minecraft.src; // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) braces deadcode import java.util.Random; public class EntityFlyerMob extends EntityMob { public EntityFlyerMob(World world) { super(world); isCollidedVertically = false; speedModifier = 0.029999999999999999D; setSize(1.5F, 1.5F); //entityWalks = false; c = 3; health = 10; } protected void fall(float f) { } public void moveEntityWithHeading(float f, float f1) { if(handleWaterMovement()) { double d = posY; moveFlying(f, f1, 0.02F); moveEntity(motionX, motionY, motionZ); motionX *= 0.80000001192092896D; motionY *= 0.80000001192092896D; motionZ *= 0.80000001192092896D; } else if(handleLavaMovement()) { double d1 = posY; moveFlying(f, f1, 0.02F); moveEntity(motionX, motionY, motionZ); motionX *= 0.5D; motionY *= 0.5D; motionZ *= 0.5D; } else { float f2 = 0.91F; if(onGround) { f2 = 0.5460001F; int i = worldObj.getBlockId(MathHelper.floor_double(posX), MathHelper.floor_double(boundingBox.minY) - 1, MathHelper.floor_double(posZ)); if(i > 0) { f2 = Block.blocksList[i].slipperiness * 0.91F; } } float f3 = 0.162771F / (f2 * f2 * f2); moveFlying(f, f1, onGround ? 0.1F * f3 : 0.02F); f2 = 0.91F; if(onGround) { f2 = 0.5460001F; int j = worldObj.getBlockId(MathHelper.floor_double(posX), MathHelper.floor_double(boundingBox.minY) - 1, MathHelper.floor_double(posZ)); if(j > 0) { f2 = Block.blocksList[j].slipperiness * 0.91F; } } moveEntity(motionX, motionY, motionZ); motionX *= f2; motionY *= f2; motionZ *= f2; if(isCollidedHorizontally) { motionY = 0.20000000000000001D; } if(rand.nextInt(30) == 0) { motionY = -0.25D; } } field_705_Q = field_704_R; double d2 = posX - prevPosX; double d3 = posZ - prevPosZ; float f4 = MathHelper.sqrt_double(d2 * d2 + d3 * d3) * 4F; if(f4 > 1.0F) { f4 = 1.0F; } field_704_R += (f4 - field_704_R) * 0.4F; field_703_S += field_704_R; } public boolean isOnLadder() { return false; } protected Entity findPlayerToAttack() { EntityPlayer entityplayer = worldObj.getClosestPlayerToEntity(this, 20D); if(entityplayer != null && canEntityBeSeen(entityplayer)) { return entityplayer; } else { return null; } } protected void updatePlayerActionState() { hasAttacked = false; float f = 16F; if(playerToAttack == null) { playerToAttack = findPlayerToAttack(); if(playerToAttack != null) { entitypath = worldObj.getPathToEntity(this, playerToAttack, f); } } else if(!playerToAttack.isEntityAlive()) { playerToAttack = null; } else { float f1 = playerToAttack.getDistanceToEntity(this); if(canEntityBeSeen(playerToAttack)) { attackEntity(playerToAttack, f1); } } if(!hasAttacked && playerToAttack != null && (entitypath == null || rand.nextInt(10) == 0)) { entitypath = worldObj.getPathToEntity(this, playerToAttack, f); } else if(entitypath == null && rand.nextInt(80) == 0 || rand.nextInt(80) == 0) { boolean flag = false; int j = -1; int k = -1; int l = -1; float f2 = -99999F; for(int i1 = 0; i1 < 10; i1++) { int j1 = MathHelper.floor_double((posX + (double)rand.nextInt(13)) - 6D); int k1 = MathHelper.floor_double((posY + (double)rand.nextInt(7)) - 3D); int l1 = MathHelper.floor_double((posZ + (double)rand.nextInt(13)) - 6D); float f3 = getBlockPathWeight(j1, k1, l1); if(f3 > f2) { f2 = f3; j = j1; k = k1; l = l1; flag = true; } } if(flag) { entitypath = worldObj.getEntityPathToXYZ(this, j, k, l, 10F); } } int i = MathHelper.floor_double(boundingBox.minY); boolean flag1 = handleWaterMovement(); boolean flag2 = handleLavaMovement(); rotationPitch = 0.0F; if(entitypath == null || rand.nextInt(100) == 0) { super.updatePlayerActionState(); entitypath = null; return; } Vec3D vec3d = entitypath.getPosition(this); for(double d = width * 2.0F; vec3d != null && vec3d.squareDistanceTo(posX, vec3d.yCoord, posZ) < d * d;) { entitypath.incrementPathIndex(); if(entitypath.isFinished()) { vec3d = null; entitypath = null; } else { vec3d = entitypath.getPosition(this); } } isJumping = false; if(vec3d != null) { double d1 = vec3d.xCoord - posX; double d2 = vec3d.zCoord - posZ; double d3 = vec3d.yCoord - (double)i; float f4 = (float)((Math.atan2(d2, d1) * 180D) / 3.1415927410125728D) - 90F; float f5 = f4 - rotationYaw; moveForward = moveSpeed; for(; f5 < -180F; f5 += 360F) { } for(; f5 >= 180F; f5 -= 360F) { } if(f5 > 30F) { f5 = 30F; } if(f5 < -30F) { f5 = -30F; } rotationYaw += f5; if(hasAttacked && playerToAttack != null) { double d4 = playerToAttack.posX - posX; double d5 = playerToAttack.posZ - posZ; float f6 = rotationYaw; rotationYaw = (float)((Math.atan2(d5, d4) * 180D) / 3.1415927410125728D) - 90F; float f7 = (((f6 - rotationYaw) + 90F) * 3.141593F) / 180F; moveStrafing = -MathHelper.sin(f7) * moveForward * 1.0F; moveForward = MathHelper.cos(f7) * moveForward * 1.0F; } if(d3 > 0.0D) { isJumping = true; } } if(playerToAttack != null) { faceEntity(playerToAttack, 30F, 30F); } if(isCollidedHorizontally) { isJumping = true; } if(rand.nextFloat() < 0.8F && (flag1 || flag2)) { isJumping = true; } } protected void attackEntity(Entity entity, float f) { if((double)f < 2.5D && entity.boundingBox.maxY > boundingBox.minY && entity.boundingBox.minY < boundingBox.maxY) { attackTime = 20; entity.attackEntityFrom(this, c); } } public boolean getCanSpawnHere() { return super.getCanSpawnHere(); } protected int c; private PathEntity entitypath; public double speedModifier; }
epl-1.0
ELTE-Soft/xUML-RT-Executor
plugins/hu.eltesoft.modelexecution.examples/src/hu/eltesoft/modelexecution/examples/StateMachineExampleWizard.java
2982
package hu.eltesoft.modelexecution.examples; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import hu.eltesoft.modelexecution.ide.project.ExecutableModelProjectSetup; /** * Creates a new xUML-RT project with a few models added initially. */ public class StateMachineExampleWizard extends ExampleModelWizard { public static final String WIZARD_ID = "hu.eltesoft.modelexecution.examples.helloworld"; //$NON-NLS-1$ public static final String PROJECT_NAME = Messages.StateMachineExampleWizard_projectName; public StateMachineExampleWizard() { setWindowTitle(Messages.StateMachineExampleWizard_title); } @Override public boolean performFinish() { try { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(PROJECT_NAME); if (project.exists()) { return true; } ExecutableModelProjectSetup.createProject(PROJECT_NAME, null); copyModel(project, "Machine"); //$NON-NLS-1$ copyLaunchConfig(project, "Machine"); //$NON-NLS-1$ copyModel(project, "Phone"); //$NON-NLS-1$ copyLaunchConfig(project, "Phone"); //$NON-NLS-1$ copyModel(project, "Loop"); //$NON-NLS-1$ copyLaunchConfig(project, "Loop"); //$NON-NLS-1$ copyModel(project, "HelloWorld"); //$NON-NLS-1$ copyLaunchConfig(project, "HelloWorld"); //$NON-NLS-1$ } catch (CoreException e) { e.printStackTrace(); return false; } return true; } @Override public void addPages() { ExampleWizardPage page = new ExampleWizardPage(""); //$NON-NLS-1$ page.setTitle(Messages.StateMachineExampleWizard_page_title); addPage(page); } private static final class ExampleWizardPage extends WizardPage { private ExampleWizardPage(String pageName) { super(pageName); } @Override public void createControl(Composite parent) { Composite control = new Composite(parent, SWT.NONE); control.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); setControl(control); FormLayout layout = new FormLayout(); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.spacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); control.setLayout(layout); Label label = new Label(control, SWT.WRAP); label.setText(Messages.StateMachineExampleWizard_description); FormData layoutData = new FormData(); layoutData.width = 400; label.setLayoutData(layoutData); } } }
epl-1.0
kdjones/lse
Source/Libraries/SynchrophasorAnalytics/Graphs/IGraphable.cs
1830
//****************************************************************************************************** // IGraphable.cs // // Copyright © 2013, Kevin D. Jones. All Rights Reserved. // // This file is licensed to you under the Eclipse Public License -v 1.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/eclipse-1.0.php // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 06/01/2013 - Kevin D. Jones // Generated original version of source code. // 06/14/2014 - Kevin D. Jones // Updated XML inline documentation. // //****************************************************************************************************** using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SynchrophasorAnalytics.Graphs { /// <summary> /// The interface for classes which can be represented as graph data structures. /// </summary> public interface IGraphable { /// <summary> /// A method which initializes the adjacencly list representation of the data structure. /// </summary> void InitializeAdjacencyList(); /// <summary> /// A method which resolves directly connected adjacencies into a single vertex. /// </summary> void ResolveAdjacencies(); } }
epl-1.0
matthiaszimmermann/jOOQ-and-EclipseScout
application/application.database/src/generated/java/com/acme/application/database/or/sys/tables/Syskeys.java
2475
/* * This file is generated by jOOQ. */ package com.acme.application.database.or.sys.tables; import com.acme.application.database.or.sys.Sys; import com.acme.application.database.or.sys.tables.records.SyskeysRecord; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.impl.TableImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.9.5" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Syskeys extends TableImpl<SyskeysRecord> { private static final long serialVersionUID = -1538576368; /** * The reference instance of <code>SYS.SYSKEYS</code> */ public static final Syskeys SYSKEYS = new Syskeys(); /** * The class holding records for this type */ @Override public Class<SyskeysRecord> getRecordType() { return SyskeysRecord.class; } /** * The column <code>SYS.SYSKEYS.CONSTRAINTID</code>. */ public final TableField<SyskeysRecord, String> CONSTRAINTID = createField("CONSTRAINTID", org.jooq.impl.SQLDataType.CHAR.length(36).nullable(false), this, ""); /** * The column <code>SYS.SYSKEYS.CONGLOMERATEID</code>. */ public final TableField<SyskeysRecord, String> CONGLOMERATEID = createField("CONGLOMERATEID", org.jooq.impl.SQLDataType.CHAR.length(36).nullable(false), this, ""); /** * Create a <code>SYS.SYSKEYS</code> table reference */ public Syskeys() { this("SYSKEYS", null); } /** * Create an aliased <code>SYS.SYSKEYS</code> table reference */ public Syskeys(String alias) { this(alias, SYSKEYS); } private Syskeys(String alias, Table<SyskeysRecord> aliased) { this(alias, aliased, null); } private Syskeys(String alias, Table<SyskeysRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return Sys.SYS; } /** * {@inheritDoc} */ @Override public Syskeys as(String alias) { return new Syskeys(alias, this); } /** * Rename this table */ @Override public Syskeys rename(String name) { return new Syskeys(name, null); } }
epl-1.0
siad007/pdt-php-amqp
de.mehralsnix.php.amqp/src/de/mehralsnix/php/amqp/Activator.java
1032
package de.mehralsnix.php.amqp; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "de.mehralsnix.php.amqp"; //$NON-NLS-1$ // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
epl-1.0
wx5223/fileconvert
src/main/java/com/wx/tohtml/PptConvert.java
3346
package com.wx.tohtml; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Formatter; import javax.imageio.ImageIO; import org.apache.poi.hslf.model.Slide; import org.apache.poi.hslf.model.TextRun; import org.apache.poi.hslf.usermodel.RichTextRun; import org.apache.poi.hslf.usermodel.SlideShow; /** * @Description * @date 2013年12月7日 * @author WangXin */ public class PptConvert implements IHtmlConvert { private String htmlPath = ""; private String realName = ""; private Appendable output; private Formatter out; public void convert(File srcFile, String desPath) { realName = srcFile.getName(); htmlPath = desPath; SlideShow slideShow = null; try { slideShow = new SlideShow(new FileInputStream(srcFile)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } File file = new File(htmlPath + realName + ".html"); file.getParentFile().mkdirs(); try { output = new PrintWriter(new FileWriter(file)); } catch (IOException e) { e.printStackTrace(); } print(slideShow); } private void print(SlideShow slideShow) { out = new Formatter(output); out.format("<?xml version=\"1.0\" encoding=\"utf-8\" ?>%n"); out.format("<html>%n"); out.format("<head>%n"); out.format("</head>%n"); out.format("<body>%n"); out.format("<table>%n"); getPics(slideShow); out.format("</table>"); out.format("</body>%n"); out.format("</html>%n"); out.flush(); out.close(); } private void printImage(String scr) { out.format("<tr>%n"); out.format("<td>%n"); out.format("<img src='" + scr + "'/>"); out.format("</td>%n"); out.format("</tr>%n"); } private void getPics(SlideShow slideShow) { Dimension pgsize = slideShow.getPageSize(); Slide[] slides = slideShow.getSlides(); for (int i = 0; i < slides.length; i++) { TextRun[] truns = slides[i].getTextRuns(); for (int k = 0; k < truns.length; k++) { RichTextRun[] rtruns = truns[k].getRichTextRuns(); for (int j = 0; j < rtruns.length; j++) { rtruns[j].setFontIndex(1); rtruns[j].setFontName("宋体"); } } BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); graphics.setPaint(Color.WHITE); graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); slides[i].draw(graphics); String imgSrcPath = htmlPath + realName + File.separator + i + ".png"; File ff = new File(imgSrcPath); ff.getParentFile().mkdirs(); FileOutputStream fos = null; try { fos = new FileOutputStream(ff); ImageIO.write(img, "png", fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fos != null) fos.close(); } catch (IOException e) { e.printStackTrace(); } } printImage(realName + File.separator + i + ".png"); } } }
epl-1.0
vikpek/SocialWeaver
Social Weaver WS/src/main/java/at/ac/uibk/qe/sowe/SocialElement.java
387
package at.ac.uibk.qe.sowe; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord; import org.springframework.roo.addon.json.RooJson; import org.springframework.roo.addon.tostring.RooToString; @RooJavaBean @RooToString @RooJpaActiveRecord @RooJson public class SocialElement { private String content; }
epl-1.0
debrief/debrief
org.mwc.debrief.lite/src/main/java/org/mwc/debrief/lite/gui/custom/narratives/TrackPanelItemRenderer.java
1604
/******************************************************************************* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2020, Deep Blue C Technology Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *******************************************************************************/ package org.mwc.debrief.lite.gui.custom.narratives; import java.awt.Component; import java.awt.Dimension; import javax.swing.Box; import javax.swing.JCheckBox; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListCellRenderer; public class TrackPanelItemRenderer extends JPanel implements ListCellRenderer<TrackNameColor> { /** * */ private static final long serialVersionUID = 1963635319483966831L; @Override public Component getListCellRendererComponent(final JList<? extends TrackNameColor> list, final TrackNameColor value, final int index, final boolean isSelected, final boolean cellHasFocus) { final Box mainBox = Box.createHorizontalBox(); final JPanel coloredPane = new JPanel(); coloredPane.setBackground(value.getColor()); coloredPane.setPreferredSize(new Dimension(12, 12)); mainBox.add(new JCheckBox(value.getTrackName())); mainBox.add(coloredPane); return mainBox; } }
epl-1.0
Mark-Booth/daq-eclipse
uk.ac.diamond.org.apache.activemq/org/jasypt/commons/CommonUtils.java
8804
/* * ============================================================================= * * Copyright (c) 2007-2010, The JASYPT team (http://www.jasypt.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package org.jasypt.commons; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.jasypt.exceptions.EncryptionOperationNotPossibleException; /** * <p> * Common utils regarding treatment of parameter values and encoding operations. * <b>This class is for internal use only</b>. * </p> * * @since 1.3 * * @author Daniel Fern&aacute;ndez * */ public final class CommonUtils { public static final String STRING_OUTPUT_TYPE_BASE64 = "base64"; public static final String STRING_OUTPUT_TYPE_HEXADECIMAL = "hexadecimal"; private static final List STRING_OUTPUT_TYPE_HEXADECIMAL_NAMES = Arrays.asList( new String[] { "HEXADECIMAL", "HEXA", "0X", "HEX", "HEXADEC" } ); private static char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; public static Boolean getStandardBooleanValue(final String valueStr) { if (valueStr == null) { return null; } final String upperValue = valueStr.toUpperCase(); if ("TRUE".equals(upperValue) || "ON".equals(upperValue) || "YES".equals(upperValue)) { return Boolean.TRUE; } if ("FALSE".equals(upperValue) || "OFF".equals(upperValue) || "NO".equals(upperValue)) { return Boolean.FALSE; } return null; } public static String getStandardStringOutputType(final String valueStr) { if (valueStr == null) { return null; } if (STRING_OUTPUT_TYPE_HEXADECIMAL_NAMES.contains(valueStr.toUpperCase())) { return STRING_OUTPUT_TYPE_HEXADECIMAL; } return STRING_OUTPUT_TYPE_BASE64; } public static String toHexadecimal(final byte[] message) { if (message == null) { return null; } final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < message.length; i++) { int curByte = message[i] & 0xff; buffer.append(hexDigits[(curByte >> 4)]); buffer.append(hexDigits[curByte & 0xf]); } return buffer.toString(); } public static byte[] fromHexadecimal(final String message) { if (message == null) { return null; } if ((message.length() % 2) != 0) { throw new EncryptionOperationNotPossibleException(); } try { final byte[] result = new byte[message.length() / 2]; for (int i = 0; i < message.length(); i = i + 2) { final int first = Integer.parseInt("" + message.charAt(i), 16); final int second = Integer.parseInt("" + message.charAt(i + 1), 16); result[i/2] = (byte) (0x0 + ((first & 0xff) << 4) + (second & 0xff)); } return result; } catch (Exception e) { throw new EncryptionOperationNotPossibleException(); } } public static boolean isEmpty(final String string) { if (string == null || string.length() == 0) { return true; } return false; } public static boolean isNotEmpty(final String string) { if (string == null || string.length() == 0) { return false; } return true; } public static void validateNotNull(final Object object, final String message) { if (object == null) { throw new IllegalArgumentException(message); } } public static void validateNotEmpty(final String string, final String message) { if (isEmpty(string)) { throw new IllegalArgumentException(message); } } public static void validateIsTrue(final boolean expression, final String message) { if (expression == false) { throw new IllegalArgumentException(message); } } public static String[] split(final String string) { // Whitespace will be used as separator return split(string, null); } public static String[] split(final String string, final String separators) { if (string == null) { return null; } final int length = string.length(); if (length == 0) { return new String[0]; } final List results = new ArrayList(); int i = 0; int start = 0; boolean tokenInProgress = false; if (separators == null) { while (i < length) { if (Character.isWhitespace(string.charAt(i))) { if (tokenInProgress) { results.add(string.substring(start, i)); tokenInProgress = false; } start = ++i; continue; } tokenInProgress = true; i++; } } else if (separators.length() == 1) { final char separator = separators.charAt(0); while (i < length) { if (string.charAt(i) == separator) { if (tokenInProgress) { results.add(string.substring(start, i)); tokenInProgress = false; } start = ++i; continue; } tokenInProgress = true; i++; } } else { while (i < length) { if (separators.indexOf(string.charAt(i)) >= 0) { if (tokenInProgress) { results.add(string.substring(start, i)); tokenInProgress = false; } start = ++i; continue; } tokenInProgress = true; i++; } } if (tokenInProgress) { results.add(string.substring(start, i)); } return (String[]) results.toArray(new String[results.size()]); } public static String substringBefore(final String string, final String separator) { if (isEmpty(string) || separator == null) { return string; } if (separator.length() == 0) { return ""; } final int pos = string.indexOf(separator); if (pos == -1) { return string; } return string.substring(0, pos); } public static String substringAfter(final String string, final String separator) { if (isEmpty(string)) { return string; } if (separator == null) { return ""; } final int pos = string.indexOf(separator); if (pos == -1) { return ""; } return string.substring(pos + separator.length()); } public static int nextRandomInt() { return (int)(Math.random() * Integer.MAX_VALUE); } public static byte[] appendArrays(final byte[] firstArray, final byte[] secondArray) { validateNotNull(firstArray, "Appended array cannot be null"); validateNotNull(secondArray, "Appended array cannot be null"); final byte[] result = new byte[firstArray.length + secondArray.length]; System.arraycopy(firstArray, 0, result, 0, firstArray.length); System.arraycopy(secondArray, 0, result, firstArray.length, secondArray.length); return result; } // This class should only be called statically private CommonUtils() { super(); } }
epl-1.0
lhillah/pnmlframework
pnmlFw-PT-HLPNG/src/fr/lip6/move/pnml/pthlpng/hlcorestructure/impl/NodeImpl.java
9015
/** * Copyright 2009-2016 Université Paris Ouest and Sorbonne Universités, Univ. Paris 06 - CNRS UMR 7606 (LIP6) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Project leader / Initial Contributor: * Lom Messan Hillah - <[email protected]> * * Contributors: * ${ocontributors} - <$oemails}> * * Mailing list: * [email protected] */ /** * (C) Sorbonne Universités, UPMC Univ Paris 06, UMR CNRS 7606 (LIP6/MoVe) * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Lom HILLAH (LIP6) - Initial models and implementation * Rachid Alahyane (UPMC) - Infrastructure and continuous integration * Bastien Bouzerau (UPMC) - Architecture * Guillaume Giffo (UPMC) - Code generation refactoring, High-level API */ package fr.lip6.move.pnml.pthlpng.hlcorestructure.impl; import java.util.List; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.DiagnosticChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.InternalEList; import fr.lip6.move.pnml.pthlpng.hlcorestructure.Arc; import fr.lip6.move.pnml.pthlpng.hlcorestructure.HlcorestructurePackage; import fr.lip6.move.pnml.pthlpng.hlcorestructure.Node; import fr.lip6.move.pnml.pthlpng.hlcorestructure.NodeGraphics; /** * <!-- begin-user-doc --> An implementation of the model object * '<em><b>Node</b></em>'. <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.impl.NodeImpl#getInArcs * <em>In Arcs</em>}</li> * <li>{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.impl.NodeImpl#getOutArcs * <em>Out Arcs</em>}</li> * <li>{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.impl.NodeImpl#getNodegraphics * <em>Nodegraphics</em>}</li> * </ul> * </p> * * @generated */ public abstract class NodeImpl extends PnObjectImpl implements Node { /** * The cached value of the '{@link #getInArcs() <em>In Arcs</em>}' reference * list. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getInArcs() * @generated * @ordered */ protected EList<Arc> inArcs; /** * The cached value of the '{@link #getOutArcs() <em>Out Arcs</em>}' reference * list. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getOutArcs() * @generated * @ordered */ protected EList<Arc> outArcs; /** * The cached value of the '{@link #getNodegraphics() <em>Nodegraphics</em>}' * containment reference. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getNodegraphics() * @generated * @ordered */ protected NodeGraphics nodegraphics; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ protected NodeImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return HlcorestructurePackage.Literals.NODE; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public List<Arc> getInArcs() { if (inArcs == null) { inArcs = new EObjectWithInverseResolvingEList<Arc>(Arc.class, this, HlcorestructurePackage.NODE__IN_ARCS, HlcorestructurePackage.ARC__TARGET); } return inArcs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public List<Arc> getOutArcs() { if (outArcs == null) { outArcs = new EObjectWithInverseResolvingEList<Arc>(Arc.class, this, HlcorestructurePackage.NODE__OUT_ARCS, HlcorestructurePackage.ARC__SOURCE); } return outArcs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public NodeGraphics getNodegraphics() { return nodegraphics; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public NotificationChain basicSetNodegraphics(NodeGraphics newNodegraphics, NotificationChain msgs) { NodeGraphics oldNodegraphics = nodegraphics; nodegraphics = newNodegraphics; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, HlcorestructurePackage.NODE__NODEGRAPHICS, oldNodegraphics, newNodegraphics); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void setNodegraphics(NodeGraphics newNodegraphics) { if (newNodegraphics != nodegraphics) { NotificationChain msgs = null; if (nodegraphics != null) msgs = ((InternalEObject) nodegraphics).eInverseRemove(this, HlcorestructurePackage.NODE_GRAPHICS__CONTAINER_NODE, NodeGraphics.class, msgs); if (newNodegraphics != null) msgs = ((InternalEObject) newNodegraphics).eInverseAdd(this, HlcorestructurePackage.NODE_GRAPHICS__CONTAINER_NODE, NodeGraphics.class, msgs); msgs = basicSetNodegraphics(newNodegraphics, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, HlcorestructurePackage.NODE__NODEGRAPHICS, newNodegraphics, newNodegraphics)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case HlcorestructurePackage.NODE__IN_ARCS: return ((InternalEList<InternalEObject>) (InternalEList<?>) getInArcs()).basicAdd(otherEnd, msgs); case HlcorestructurePackage.NODE__OUT_ARCS: return ((InternalEList<InternalEObject>) (InternalEList<?>) getOutArcs()).basicAdd(otherEnd, msgs); case HlcorestructurePackage.NODE__NODEGRAPHICS: if (nodegraphics != null) msgs = ((InternalEObject) nodegraphics).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - HlcorestructurePackage.NODE__NODEGRAPHICS, null, msgs); return basicSetNodegraphics((NodeGraphics) otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case HlcorestructurePackage.NODE__IN_ARCS: return ((InternalEList<?>) getInArcs()).basicRemove(otherEnd, msgs); case HlcorestructurePackage.NODE__OUT_ARCS: return ((InternalEList<?>) getOutArcs()).basicRemove(otherEnd, msgs); case HlcorestructurePackage.NODE__NODEGRAPHICS: return basicSetNodegraphics(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case HlcorestructurePackage.NODE__IN_ARCS: return getInArcs(); case HlcorestructurePackage.NODE__OUT_ARCS: return getOutArcs(); case HlcorestructurePackage.NODE__NODEGRAPHICS: return getNodegraphics(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case HlcorestructurePackage.NODE__NODEGRAPHICS: setNodegraphics((NodeGraphics) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case HlcorestructurePackage.NODE__NODEGRAPHICS: setNodegraphics((NodeGraphics) null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case HlcorestructurePackage.NODE__IN_ARCS: return inArcs != null && !inArcs.isEmpty(); case HlcorestructurePackage.NODE__OUT_ARCS: return outArcs != null && !outArcs.isEmpty(); case HlcorestructurePackage.NODE__NODEGRAPHICS: return nodegraphics != null; } return super.eIsSet(featureID); } @Override public abstract boolean validateOCL(DiagnosticChain diagnostics); } // NodeImpl
epl-1.0
stormc/hawkbit
hawkbit-security-core/src/test/java/org/eclipse/hawkbit/util/IpUtilTest.java
6743
/** * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.hawkbit.util; import static com.google.common.net.HttpHeaders.X_FORWARDED_FOR; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.net.URI; import javax.servlet.http.HttpServletRequest; import org.eclipse.hawkbit.security.HawkbitSecurityProperties; import org.eclipse.hawkbit.security.HawkbitSecurityProperties.Clients; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @RunWith(MockitoJUnitRunner.class) @Features("Unit Tests - Security") @Stories("IP Util Test") public class IpUtilTest { private static final String KNOWN_REQUEST_HEADER = "bumlux"; @Mock private HttpServletRequest requestMock; @Mock private Clients clientMock; @Mock private HawkbitSecurityProperties securityPropertyMock; @Test @Description("Tests create uri from request") public void getRemoteAddrFromRequestIfForwaredHeaderNotPresent() { final URI knownRemoteClientIP = IpUtil.createHttpUri("127.0.0.1"); when(requestMock.getHeader(X_FORWARDED_FOR)).thenReturn(null); when(requestMock.getRemoteAddr()).thenReturn(knownRemoteClientIP.getHost()); final URI remoteAddr = IpUtil.getClientIpFromRequest(requestMock, KNOWN_REQUEST_HEADER); // verify assertThat(remoteAddr).as("The remote address should be as the known client IP address") .isEqualTo(knownRemoteClientIP); verify(requestMock, times(1)).getHeader(KNOWN_REQUEST_HEADER); verify(requestMock, times(1)).getRemoteAddr(); } @Test @Description("Tests create uri from request with masked IP when IP tracking is disabled") public void maskRemoteAddrIfDisabled() { final URI knownRemoteClientIP = IpUtil.createHttpUri("***"); when(requestMock.getHeader(X_FORWARDED_FOR)).thenReturn(null); when(requestMock.getRemoteAddr()).thenReturn(knownRemoteClientIP.getHost()); when(securityPropertyMock.getClients()).thenReturn(clientMock); when(clientMock.getRemoteIpHeader()).thenReturn(KNOWN_REQUEST_HEADER); when(clientMock.isTrackRemoteIp()).thenReturn(false); final URI remoteAddr = IpUtil.getClientIpFromRequest(requestMock, securityPropertyMock); assertThat(remoteAddr).as("The remote address should be as the known client IP address") .isEqualTo(knownRemoteClientIP); verify(requestMock, times(0)).getHeader(KNOWN_REQUEST_HEADER); verify(requestMock, times(0)).getRemoteAddr(); } @Test @Description("Tests create uri from x forward header") public void getRemoteAddrFromXForwardedForHeader() { final URI knownRemoteClientIP = IpUtil.createHttpUri("10.99.99.1"); when(requestMock.getHeader(X_FORWARDED_FOR)).thenReturn(knownRemoteClientIP.getHost()); when(requestMock.getRemoteAddr()).thenReturn(null); final URI remoteAddr = IpUtil.getClientIpFromRequest(requestMock, "X-Forwarded-For"); assertThat(remoteAddr).as("The remote address should be as the known client IP address") .isEqualTo(knownRemoteClientIP); verify(requestMock, times(1)).getHeader(X_FORWARDED_FOR); verify(requestMock, times(0)).getRemoteAddr(); } @Test @Description("Tests create http uri ipv4 and ipv6") public void testCreateHttpUri() { final String ipv4 = "10.99.99.1"; URI httpUri = IpUtil.createHttpUri(ipv4); assertHttpUri(ipv4, httpUri); final String host = "myhost"; httpUri = IpUtil.createHttpUri(host); assertHttpUri(host, httpUri); final String ipv6 = "0:0:0:0:0:0:0:1"; httpUri = IpUtil.createHttpUri(ipv6); assertHttpUri("[" + ipv6 + "]", httpUri); } private void assertHttpUri(final String host, final URI httpUri) { assertTrue("The given URI has an http scheme", IpUtil.isHttpUri(httpUri)); assertFalse("The given URI is not an AMQP scheme", IpUtil.isAmqpUri(httpUri)); assertEquals("The URI hosts matches the given host", host, httpUri.getHost()); assertEquals("The given URI scheme is http", "http", httpUri.getScheme()); } @Test @Description("Tests create amqp uri ipv4 and ipv6") public void testCreateAmqpUri() { final String ipv4 = "10.99.99.1"; URI amqpUri = IpUtil.createAmqpUri(ipv4, "path"); assertAmqpUri(ipv4, amqpUri); final String host = "myhost"; amqpUri = IpUtil.createAmqpUri(host, "path"); assertAmqpUri(host, amqpUri); final String ipv6 = "0:0:0:0:0:0:0:1"; amqpUri = IpUtil.createAmqpUri(ipv6, "path"); assertAmqpUri("[" + ipv6 + "]", amqpUri); } private void assertAmqpUri(final String host, final URI amqpUri) { assertTrue("The given URI is an AMQP scheme", IpUtil.isAmqpUri(amqpUri)); assertFalse("The given URI is not an HTTP scheme", IpUtil.isHttpUri(amqpUri)); assertEquals("The given host matches the URI host", host, amqpUri.getHost()); assertEquals("The given URI has an AMQP scheme", "amqp", amqpUri.getScheme()); assertEquals("The given URI has an AMQP path", "/path", amqpUri.getRawPath()); } @Test @Description("Tests create invalid uri") public void testCreateInvalidUri() { final String host = "10.99.99.1"; final URI testUri = IpUtil.createUri("test", host); assertFalse("The given URI is not an AMQP address", IpUtil.isAmqpUri(testUri)); assertFalse("The given URI is not an HTTP address", IpUtil.isHttpUri(testUri)); assertEquals("The given host matches the URI host", host, testUri.getHost()); try { IpUtil.createUri(":/", host); fail("Missing expected IllegalArgumentException due invalid URI"); } catch (final IllegalArgumentException e) { // expected } } }
epl-1.0
LM25TTD/HopperIDE
Eclipse_Plugin/org.hopper.language.parent/org.hopper.language.ui/xtend-gen/org/hopper/language/ui/labeling/TypeRepresentation.java
237
package org.hopper.language.ui.labeling; import org.hopper.language.portugol.VarType; @SuppressWarnings("all") public class TypeRepresentation { public String representation(final VarType type) { return type.getTypeName(); } }
epl-1.0
FTSRG/viatra-dse-distributed
org.eclipse.viatra.dse.cluster.node/src/org/eclipse/viatra/dse/cluster/node/RemoteAkkaClassloader.java
3810
package org.eclipse.viatra.dse.cluster.node; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import org.apache.log4j.Logger; import org.eclipse.viatra.dse.cluster.interfaces.IProblemServer; /** * This is the classloader on the worker nodes that load the received bytecode * into memory. * * @author Miki * */ public class RemoteAkkaClassloader extends ClassLoader { private static Logger log = Logger.getLogger(RemoteAkkaClassloader.class.getName()); /** * The problem node local stub. */ private IProblemServer remoteClassLoaderActor; /** * The parent classloader. */ private final ClassLoader parent; /** * Default constructor with no specified parent classloader. */ private RemoteAkkaClassloader() { this(null); } /** * Constructor with supplied parent class loader. * * @param parent */ public RemoteAkkaClassloader(ClassLoader parent) { super(parent); this.parent = parent; } public IProblemServer getRemoteClassLoaderActor() { return remoteClassLoaderActor; } public void setRemoteClassLoaderActor(IProblemServer remoteClassLoaderActor) { this.remoteClassLoaderActor = remoteClassLoaderActor; } @Override public URL getResource(String name) { return super.getResource(name); } @Override public InputStream getResourceAsStream(String name) { return super.getResourceAsStream(name); } @Override public Enumeration<URL> getResources(String name) throws IOException { return super.getResources(name); } /** * <p> * This method resolves the requested class. It first tries the default Java * method of classloading, so that it does not try to resolve already loaded * classes. * </p> * * <p> * If this method fails, it first tries to delegate the classloading to the * OSGi container's appropriate classloader. * </p> * * <p> * If both the above methods fail to resolve and load the class defined by * the {@code param} parameter, then an attempt is made to load it from the * remote host (the problem's originating host) via the Akka interface. * </p> * * @exception ClassNotFoundException * This exception is thrown if all three methods of * classloading fail. */ @Override public Class<?> loadClass(String name) throws ClassNotFoundException { try { return super.loadClass(name); } catch (ClassNotFoundException e) { try { return this.getClass().getClassLoader().loadClass(name); } catch (ClassNotFoundException e2) { try { return loadClassFromAkka(name); } catch (ClassNotFoundException e3) { throw (new java.lang.ClassNotFoundException("Local and remote classloading has failed for class: " + name)); } } } } private Class<?> loadClassFromAkka(String name) throws ClassNotFoundException { if (remoteClassLoaderActor == null) { throw (new java.lang.ClassNotFoundException("No remote classloader defined.")); } try { byte[] implementation = remoteClassLoaderActor.loadClass(name); defineClass(name, implementation, 0, implementation.length); log.info("Loaded remote class: " + name); return loadClass(name); } catch (Exception e1) { throw new ClassNotFoundException("Remote classloading has failed."); } } @Override public void setClassAssertionStatus(String className, boolean enabled) { super.setClassAssertionStatus(className, enabled); } @Override public void setDefaultAssertionStatus(boolean enabled) { super.setDefaultAssertionStatus(enabled); } @Override public void setPackageAssertionStatus(String packageName, boolean enabled) { super.setPackageAssertionStatus(packageName, enabled); } @Override public void clearAssertionStatus() { super.clearAssertionStatus(); } }
epl-1.0
piranha/pump
resources/react/module$CompositionEventPlugin.js
5881
goog.provide("module$CompositionEventPlugin"); var module$CompositionEventPlugin = {}; goog.require("module$keyOf"); goog.require("module$getTextContentAccessor"); goog.require("module$SyntheticCompositionEvent"); goog.require("module$ReactInputSelection"); goog.require("module$ExecutionEnvironment"); goog.require("module$EventPropagators"); goog.require("module$EventConstants"); var EventConstants$$module$CompositionEventPlugin = module$EventConstants; var EventPropagators$$module$CompositionEventPlugin = module$EventPropagators; var ExecutionEnvironment$$module$CompositionEventPlugin = module$ExecutionEnvironment; var ReactInputSelection$$module$CompositionEventPlugin = module$ReactInputSelection; var SyntheticCompositionEvent$$module$CompositionEventPlugin = module$SyntheticCompositionEvent; var getTextContentAccessor$$module$CompositionEventPlugin = module$getTextContentAccessor; var keyOf$$module$CompositionEventPlugin = module$keyOf; var END_KEYCODES$$module$CompositionEventPlugin = [9, 13, 27, 32]; var START_KEYCODE$$module$CompositionEventPlugin = 229; var useCompositionEvent$$module$CompositionEventPlugin = ExecutionEnvironment$$module$CompositionEventPlugin.canUseDOM && "CompositionEvent" in window; var topLevelTypes$$module$CompositionEventPlugin = EventConstants$$module$CompositionEventPlugin.topLevelTypes; var currentComposition$$module$CompositionEventPlugin = null; var eventTypes$$module$CompositionEventPlugin = {compositionEnd:{phasedRegistrationNames:{bubbled:keyOf$$module$CompositionEventPlugin({onCompositionEnd:null}), captured:keyOf$$module$CompositionEventPlugin({onCompositionEndCapture:null})}}, compositionStart:{phasedRegistrationNames:{bubbled:keyOf$$module$CompositionEventPlugin({onCompositionStart:null}), captured:keyOf$$module$CompositionEventPlugin({onCompositionStartCapture:null})}}, compositionUpdate:{phasedRegistrationNames:{bubbled:keyOf$$module$CompositionEventPlugin({onCompositionUpdate:null}), captured:keyOf$$module$CompositionEventPlugin({onCompositionUpdateCapture:null})}}}; function getCompositionEventType$$module$CompositionEventPlugin(topLevelType) { switch(topLevelType) { case topLevelTypes$$module$CompositionEventPlugin.topCompositionStart: return eventTypes$$module$CompositionEventPlugin.compositionStart; case topLevelTypes$$module$CompositionEventPlugin.topCompositionEnd: return eventTypes$$module$CompositionEventPlugin.compositionEnd; case topLevelTypes$$module$CompositionEventPlugin.topCompositionUpdate: return eventTypes$$module$CompositionEventPlugin.compositionUpdate } } function isFallbackStart$$module$CompositionEventPlugin(topLevelType, nativeEvent) { return topLevelType === topLevelTypes$$module$CompositionEventPlugin.topKeyDown && nativeEvent.keyCode === START_KEYCODE$$module$CompositionEventPlugin } function isFallbackEnd$$module$CompositionEventPlugin(topLevelType, nativeEvent) { switch(topLevelType) { case topLevelTypes$$module$CompositionEventPlugin.topKeyUp: return END_KEYCODES$$module$CompositionEventPlugin.indexOf(nativeEvent.keyCode) !== -1; case topLevelTypes$$module$CompositionEventPlugin.topKeyDown: return nativeEvent.keyCode !== START_KEYCODE$$module$CompositionEventPlugin; case topLevelTypes$$module$CompositionEventPlugin.topKeyPress: ; case topLevelTypes$$module$CompositionEventPlugin.topMouseDown: ; case topLevelTypes$$module$CompositionEventPlugin.topBlur: return true; default: return false } } function FallbackCompositionState$$module$CompositionEventPlugin(root) { this.root = root; this.startSelection = ReactInputSelection$$module$CompositionEventPlugin.getSelection(root); this.startValue = this.getText() } FallbackCompositionState$$module$CompositionEventPlugin.prototype.getText = function() { return this.root.value || this.root[getTextContentAccessor$$module$CompositionEventPlugin()] }; FallbackCompositionState$$module$CompositionEventPlugin.prototype.getData = function() { var endValue = this.getText(); var prefixLength = this.startSelection.start; var suffixLength = this.startValue.length - this.startSelection.end; return endValue.substr(prefixLength, endValue.length - suffixLength - prefixLength) }; var CompositionEventPlugin$$module$CompositionEventPlugin = {eventTypes:eventTypes$$module$CompositionEventPlugin, extractEvents:function(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var eventType; var data; if(useCompositionEvent$$module$CompositionEventPlugin) { eventType = getCompositionEventType$$module$CompositionEventPlugin(topLevelType) }else { if(!currentComposition$$module$CompositionEventPlugin) { if(isFallbackStart$$module$CompositionEventPlugin(topLevelType, nativeEvent)) { eventType = eventTypes$$module$CompositionEventPlugin.start; currentComposition$$module$CompositionEventPlugin = new FallbackCompositionState$$module$CompositionEventPlugin(topLevelTarget) } }else { if(isFallbackEnd$$module$CompositionEventPlugin(topLevelType, nativeEvent)) { eventType = eventTypes$$module$CompositionEventPlugin.compositionEnd; data = currentComposition$$module$CompositionEventPlugin.getData(); currentComposition$$module$CompositionEventPlugin = null } } } if(eventType) { var event = SyntheticCompositionEvent$$module$CompositionEventPlugin.getPooled(eventType, topLevelTargetID, nativeEvent); if(data) { event.data = data } EventPropagators$$module$CompositionEventPlugin.accumulateTwoPhaseDispatches(event); return event } }}; module$CompositionEventPlugin.module$exports = CompositionEventPlugin$$module$CompositionEventPlugin; if(module$CompositionEventPlugin.module$exports) { module$CompositionEventPlugin = module$CompositionEventPlugin.module$exports } ;
epl-1.0
hammacher/ccs
plugin/src/de/unisb/cs/depend/ccs_sem/plugin/views/simulation/IUndoObservable.java
209
package de.unisb.cs.depend.ccs_sem.plugin.views.simulation; public interface IUndoObservable { public void addUndoListener(IUndoListener listener); public void removeUndoListener(IUndoListener listener); }
epl-1.0
kopl/misc
JaMoPP Performance Test/testcode/argouml-usecase-variant/src/org/argouml/uml/ui/behavior/use_cases/PropPanelInclude.java
5495
//@#$LPS-USECASEDIAGRAM:GranularityType:Package // $Id: PropPanelInclude.java 89 2010-07-31 23:06:12Z marcusvnac $ // Copyright (c) 1996-2008 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.ui.behavior.use_cases; import javax.swing.JList; import org.argouml.model.Model; import org.argouml.uml.ui.ActionNavigateNamespace; import org.argouml.uml.ui.UMLLinkedList; import org.argouml.uml.ui.foundation.core.PropPanelRelationship; import org.argouml.uml.ui.foundation.extension_mechanisms.ActionNewStereotype; /** * Builds the property panel for an Include relationship.<p> * * @author Jeremy Bennett */ public class PropPanelInclude extends PropPanelRelationship { /** * The serial version. */ private static final long serialVersionUID = -8235207258195445477L; /** * Construct a property panel for Include model elements. */ public PropPanelInclude() { super("label.include", lookupIcon("Include")); addField("label.name", getNameTextField()); addField("label.namespace", getNamespaceSelector()); addSeparator(); addField("label.usecase-base", getSingleRowScroll(new UMLIncludeBaseListModel())); addField("label.addition", getSingleRowScroll(new UMLIncludeAdditionListModel())); // Add the toolbar buttons: addAction(new ActionNavigateNamespace()); addAction(new ActionNewStereotype()); addAction(getDeleteAction()); } /** * Get the current base use case of the include relationship.<p> * @return The UseCase that is the base of this include relationship or * <code>null</code> if there is none. */ public Object getBase() { Object base = null; Object target = getTarget(); if (Model.getFacade().isAInclude(target)) { base = Model.getFacade().getBase(target); } return base; } /** * Set the base use case of the include relationship.<p> * @param base The UseCase to set as the base of this include relationship. */ public void setBase(Object/*MUseCase*/ base) { Object target = getTarget(); if (Model.getFacade().isAInclude(target)) { Model.getUseCasesHelper().setBase(target, base); } } /** * Get the current addition use case of the include relationship.<p> * * * @return The UseCase that is the addition of this include * relationship or <code>null</code> if there is none. */ public Object getAddition() { Object addition = null; Object target = getTarget(); if (Model.getFacade().isAInclude(target)) { addition = Model.getFacade().getAddition(target); } return addition; } /** * Set the addition use case of the include relationship.<p> * * * @param addition The UseCase to set as the addition of this * include relationship. */ public void setAddition(Object/*MUseCase*/ addition) { Object target = getTarget(); if (Model.getFacade().isAInclude(target)) { Model.getUseCasesHelper().setAddition(target, addition); } } /** * Predicate to test if a model element may appear in the list of * potential use cases.<p> * * <em>Note</em>. We don't try to prevent the user setting up * circular include relationships. This may be necessary * temporarily, for example while reversing a relationship. It is * up to a critic to track this.<p> * * @param modElem the ModelElement to test. * * @return <code>true</code> if modElem is a use case, * <code>false</code> otherwise. */ public boolean isAcceptableUseCase(Object/*MModelElement*/ modElem) { return Model.getFacade().isAUseCase(modElem); } }
epl-1.0
lhillah/pnmlframework
pnmlFw-Tests/test/fr/lip6/move/pnml/hlpn/hlcorestructure/hlapi/RefPlaceHLAPITest.java
20174
/** * (C) Sorbonne Universités, UPMC Univ Paris 06, UMR CNRS 7606 (LIP6) * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Lom HILLAH (LIP6) - Initial models and implementation * Rachid Alahyane (UPMC) - Infrastructure and continuous integration * Bastien Bouzerau (UPMC) - Architecture * Guillaume Giffo (UPMC) - Code generation refactoring, High-level API * * $Id ggiffo, Thu Feb 11 16:29:58 CET 2016$ */ package fr.lip6.move.pnml.hlpn.hlcorestructure.hlapi; import fr.lip6.move.pnml.hlpn.arbitrarydeclarations.AnySort; import fr.lip6.move.pnml.hlpn.arbitrarydeclarations.ArbitraryOperator; import fr.lip6.move.pnml.hlpn.arbitrarydeclarations.ArbitrarySort; import fr.lip6.move.pnml.hlpn.arbitrarydeclarations.Unparsed; import fr.lip6.move.pnml.hlpn.arbitrarydeclarations.impl.ArbitrarydeclarationsFactoryImpl; import fr.lip6.move.pnml.hlpn.booleans.And; import fr.lip6.move.pnml.hlpn.booleans.Bool; import fr.lip6.move.pnml.hlpn.booleans.BooleanConstant; import fr.lip6.move.pnml.hlpn.booleans.Equality; import fr.lip6.move.pnml.hlpn.booleans.Imply; import fr.lip6.move.pnml.hlpn.booleans.Inequality; import fr.lip6.move.pnml.hlpn.booleans.Not; import fr.lip6.move.pnml.hlpn.booleans.Or; import fr.lip6.move.pnml.hlpn.booleans.impl.BooleansFactoryImpl; import fr.lip6.move.pnml.hlpn.cyclicEnumerations.CyclicEnumeration; import fr.lip6.move.pnml.hlpn.cyclicEnumerations.Predecessor; import fr.lip6.move.pnml.hlpn.cyclicEnumerations.Successor; import fr.lip6.move.pnml.hlpn.cyclicEnumerations.impl.CyclicEnumerationsFactoryImpl; import fr.lip6.move.pnml.hlpn.dots.Dot; import fr.lip6.move.pnml.hlpn.dots.DotConstant; import fr.lip6.move.pnml.hlpn.dots.impl.DotsFactoryImpl; import fr.lip6.move.pnml.hlpn.finiteEnumerations.FEConstant; import fr.lip6.move.pnml.hlpn.finiteEnumerations.FiniteEnumeration; import fr.lip6.move.pnml.hlpn.finiteEnumerations.impl.FiniteEnumerationsFactoryImpl; import fr.lip6.move.pnml.hlpn.finiteIntRanges.FiniteIntRange; import fr.lip6.move.pnml.hlpn.finiteIntRanges.FiniteIntRangeConstant; import fr.lip6.move.pnml.hlpn.finiteIntRanges.GreaterThan; import fr.lip6.move.pnml.hlpn.finiteIntRanges.GreaterThanOrEqual; import fr.lip6.move.pnml.hlpn.finiteIntRanges.LessThan; import fr.lip6.move.pnml.hlpn.finiteIntRanges.LessThanOrEqual; import fr.lip6.move.pnml.hlpn.finiteIntRanges.impl.FiniteIntRangesFactoryImpl; import fr.lip6.move.pnml.hlpn.hlcorestructure.Annotation; import fr.lip6.move.pnml.hlpn.hlcorestructure.AnnotationGraphics; import fr.lip6.move.pnml.hlpn.hlcorestructure.AnyObject; import fr.lip6.move.pnml.hlpn.hlcorestructure.Arc; import fr.lip6.move.pnml.hlpn.hlcorestructure.ArcGraphics; import fr.lip6.move.pnml.hlpn.hlcorestructure.CSS2Color; import fr.lip6.move.pnml.hlpn.hlcorestructure.CSS2FontFamily; import fr.lip6.move.pnml.hlpn.hlcorestructure.CSS2FontSize; import fr.lip6.move.pnml.hlpn.hlcorestructure.CSS2FontStyle; import fr.lip6.move.pnml.hlpn.hlcorestructure.CSS2FontWeight; import fr.lip6.move.pnml.hlpn.hlcorestructure.Condition; import fr.lip6.move.pnml.hlpn.hlcorestructure.Declaration; import fr.lip6.move.pnml.hlpn.hlcorestructure.Dimension; import fr.lip6.move.pnml.hlpn.hlcorestructure.Fill; import fr.lip6.move.pnml.hlpn.hlcorestructure.Font; import fr.lip6.move.pnml.hlpn.hlcorestructure.FontAlign; import fr.lip6.move.pnml.hlpn.hlcorestructure.FontDecoration; import fr.lip6.move.pnml.hlpn.hlcorestructure.Gradient; import fr.lip6.move.pnml.hlpn.hlcorestructure.HLAnnotation; import fr.lip6.move.pnml.hlpn.hlcorestructure.HLMarking; import fr.lip6.move.pnml.hlpn.hlcorestructure.Label; import fr.lip6.move.pnml.hlpn.hlcorestructure.Line; import fr.lip6.move.pnml.hlpn.hlcorestructure.LineShape; import fr.lip6.move.pnml.hlpn.hlcorestructure.LineStyle; import fr.lip6.move.pnml.hlpn.hlcorestructure.Name; import fr.lip6.move.pnml.hlpn.hlcorestructure.Node; import fr.lip6.move.pnml.hlpn.hlcorestructure.NodeGraphics; import fr.lip6.move.pnml.hlpn.hlcorestructure.Offset; import fr.lip6.move.pnml.hlpn.hlcorestructure.PNType; import fr.lip6.move.pnml.hlpn.hlcorestructure.Page; import fr.lip6.move.pnml.hlpn.hlcorestructure.PetriNet; import fr.lip6.move.pnml.hlpn.hlcorestructure.PetriNetDoc; import fr.lip6.move.pnml.hlpn.hlcorestructure.Place; import fr.lip6.move.pnml.hlpn.hlcorestructure.PlaceNode; import fr.lip6.move.pnml.hlpn.hlcorestructure.PnObject; import fr.lip6.move.pnml.hlpn.hlcorestructure.Position; import fr.lip6.move.pnml.hlpn.hlcorestructure.RefPlace; import fr.lip6.move.pnml.hlpn.hlcorestructure.RefTransition; import fr.lip6.move.pnml.hlpn.hlcorestructure.ToolInfo; import fr.lip6.move.pnml.hlpn.hlcorestructure.Transition; import fr.lip6.move.pnml.hlpn.hlcorestructure.TransitionNode; import fr.lip6.move.pnml.hlpn.hlcorestructure.Type; import fr.lip6.move.pnml.hlpn.hlcorestructure.impl.HlcorestructureFactoryImpl; import fr.lip6.move.pnml.hlpn.integers.impl.IntegersFactoryImpl; import fr.lip6.move.pnml.hlpn.lists.EmptyList; import fr.lip6.move.pnml.hlpn.lists.HLPNList; import fr.lip6.move.pnml.hlpn.lists.MakeList; import fr.lip6.move.pnml.hlpn.lists.impl.ListsFactoryImpl; import fr.lip6.move.pnml.hlpn.multisets.All; import fr.lip6.move.pnml.hlpn.multisets.Empty; import fr.lip6.move.pnml.hlpn.multisets.impl.MultisetsFactoryImpl; import fr.lip6.move.pnml.hlpn.partitions.Partition; import fr.lip6.move.pnml.hlpn.partitions.PartitionElement; import fr.lip6.move.pnml.hlpn.partitions.impl.PartitionsFactoryImpl; import fr.lip6.move.pnml.hlpn.strings.impl.StringsFactoryImpl; import fr.lip6.move.pnml.hlpn.terms.Declarations; import fr.lip6.move.pnml.hlpn.terms.MultisetSort; import fr.lip6.move.pnml.hlpn.terms.NamedOperator; import fr.lip6.move.pnml.hlpn.terms.NamedSort; import fr.lip6.move.pnml.hlpn.terms.Operator; import fr.lip6.move.pnml.hlpn.terms.ProductSort; import fr.lip6.move.pnml.hlpn.terms.Sort; import fr.lip6.move.pnml.hlpn.terms.Term; import fr.lip6.move.pnml.hlpn.terms.VariableDecl; import fr.lip6.move.pnml.hlpn.terms.impl.TermsFactoryImpl; import java.math.BigDecimal; import java.net.URI; import java.util.List; import fr.lip6.move.pnml.framework.hlapi.*; import fr.lip6.move.pnml.hlpn.arbitrarydeclarations.hlapi.*; import fr.lip6.move.pnml.hlpn.booleans.hlapi.*; import fr.lip6.move.pnml.hlpn.cyclicEnumerations.hlapi.*; import fr.lip6.move.pnml.hlpn.dots.hlapi.*; import fr.lip6.move.pnml.hlpn.finiteEnumerations.hlapi.*; import fr.lip6.move.pnml.hlpn.finiteIntRanges.hlapi.*; import fr.lip6.move.pnml.hlpn.hlcorestructure.hlapi.*; import fr.lip6.move.pnml.hlpn.integers.hlapi.*; import fr.lip6.move.pnml.hlpn.lists.hlapi.*; import fr.lip6.move.pnml.hlpn.multisets.hlapi.*; import fr.lip6.move.pnml.hlpn.partitions.hlapi.*; import fr.lip6.move.pnml.hlpn.strings.hlapi.*; import fr.lip6.move.pnml.hlpn.terms.hlapi.*; import java.util.ArrayList; import java.util.List; import org.apache.axiom.om.*; import fr.lip6.move.pnml.framework.utils.IdRefLinker; import org.eclipse.emf.common.util.DiagnosticChain; import fr.lip6.move.pnml.hlpn.hlcorestructure.*; import fr.lip6.move.pnml.hlpn.hlcorestructure.impl.*; import fr.lip6.move.pnml.framework.utils.exception.InnerBuildException; import fr.lip6.move.pnml.framework.utils.exception.InvalidIDException; import fr.lip6.move.pnml.framework.utils.exception.VoidRepositoryException; import fr.lip6.move.pnml.framework.utils.IdRepository; import fr.lip6.move.pnml.framework.utils.ModelRepository; import org.testng.annotations.*; public class RefPlaceHLAPITest { private String itemid; private NameHLAPI itemname; private NodeGraphicsHLAPI itemnodegraphics; private PlaceNodeHLAPI itemref; private PageHLAPI itemcontainerPage; @AfterTest(groups = { "RefPlaceHLAPI", "hlapi" }) public void After() { System.out.println("done for "+"RefPlaceHLAPI(hlcorestructure)"); } @BeforeMethod(groups = { "RefPlaceHLAPI", "hlapi" }) public void setup() throws Exception{ //ModelRepository.reset(); ModelRepository.getInstance().createDocumentWorkspace("void"); ModelRepository mr = ModelRepository.getInstance(); mr.createDocumentWorkspace("void"); itemid = new String("unid"); //HlcorestructureFactoryImpl itemname = new NameHLAPI(new HlcorestructureFactoryImpl().createName()); //HlcorestructureFactoryImpl itemnodegraphics = new NodeGraphicsHLAPI(new HlcorestructureFactoryImpl().createNodeGraphics()); itemref = new fr.lip6.move.pnml.hlpn.hlcorestructure.hlapi.PlaceHLAPI( new HlcorestructureFactoryImpl().createPlace() ); itemcontainerPage = new PageHLAPI(new HlcorestructureFactoryImpl().createPage()); } /** * this constructor allows you to set all 'settable' values * excepted container. */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}, dependsOnMethods={"RefPlaceHLAPI_LLAPI"}) public void RefPlaceHLAPI_1() throws InvalidIDException ,VoidRepositoryException {//BEGIN CONSTRUCTOR BODY @SuppressWarnings("unused") RefPlaceHLAPI totest = new RefPlaceHLAPI( itemid , itemname , itemnodegraphics , itemref ); assert totest.getId().equals(itemid); assert totest.getName().equals(itemname.getContainedItem()); assert totest.getNodegraphics().equals(itemnodegraphics.getContainedItem()); assert totest.getRef().equals(itemref.getContainedItem()); } /** * this constructor allows you to set all 'settable' values, including container if any. */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}, dependsOnMethods={"RefPlaceHLAPI_LLAPI"}) public void RefPlaceHLAPI_2_containerPage() throws InvalidIDException ,VoidRepositoryException {//BEGIN CONSTRUCTOR BODY RefPlaceHLAPI totest = new RefPlaceHLAPI( itemid , itemname , itemnodegraphics , itemref , itemcontainerPage ); assert totest.getId().equals(itemid); assert totest.getName().equals(itemname.getContainedItem()); assert totest.getNodegraphics().equals(itemnodegraphics.getContainedItem()); assert totest.getRef().equals(itemref.getContainedItem()); assert totest.getContainerPage().equals(itemcontainerPage.getContainedItem()); } /** * This constructor give access to required stuff only (not container if any) */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}, dependsOnMethods={"RefPlaceHLAPI_LLAPI"}) public void RefPlaceHLAPI_3() throws InvalidIDException ,VoidRepositoryException {//BEGIN CONSTRUCTOR BODY RefPlaceHLAPI totest = new RefPlaceHLAPI( itemid , itemref ); assert totest.getId().equals(itemid); assert totest.getRef().equals(itemref.getContainedItem()); } /** * This constructor give access to required stuff only (and container) */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}, dependsOnMethods={"RefPlaceHLAPI_LLAPI"}) public void RefPlaceHLAPI_4_containerPage() throws InvalidIDException ,VoidRepositoryException {//BEGIN CONSTRUCTOR BODY RefPlaceHLAPI totest = new RefPlaceHLAPI( itemid , itemref , itemcontainerPage ); assert totest.getId().equals(itemid); assert totest.getRef().equals(itemref.getContainedItem()); assert totest.getContainerPage().equals(itemcontainerPage.getContainedItem()); } /** * This constructor encapsulate a low level API object in HLAPI. */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void RefPlaceHLAPI_LLAPI(){ RefPlace llapi = new HlcorestructureFactoryImpl().createRefPlace(); fr.lip6.move.pnml.hlpn.hlcorestructure.hlapi.RefPlaceHLAPI hlapi = new RefPlaceHLAPI(llapi); assert hlapi.getContainedItem().equals(llapi); } //getters giving HLAPI object /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * @return : null if the element is null */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void getNameHLAPITest(){ RefPlaceHLAPI elem = new RefPlaceHLAPI(new HlcorestructureFactoryImpl().createRefPlace()); elem.setNameHLAPI(itemname); NameHLAPI totest = elem.getNameHLAPI(); assert totest.getContainedItem().equals(elem.getName()); } /** * This test add a random number of desired objet in the list or of one of each existing subtypes. * then test how many objet are retuned and if any exist inthe original list. */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void getToolspecificsHLAPITest(){ RefPlace llapi = new HlcorestructureFactoryImpl().createRefPlace(); int howmany; howmany = (int)(Math.random()*10); for(int i =0; i<howmany;i++) llapi.getToolspecifics().add(new HlcorestructureFactoryImpl().createToolInfo()); RefPlaceHLAPI elem = new RefPlaceHLAPI(llapi); List<ToolInfoHLAPI> totest = elem.getToolspecificsHLAPI(); assert totest.size() == howmany; for (ToolInfoHLAPI unit : totest) { assert llapi.getToolspecifics().contains(unit.getContainedItem()) : "missing element"; } } /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * @return : null if the element is null */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void getContainerPageHLAPITest(){ RefPlaceHLAPI elem = new RefPlaceHLAPI(new HlcorestructureFactoryImpl().createRefPlace()); elem.setContainerPageHLAPI(itemcontainerPage); PageHLAPI totest = elem.getContainerPageHLAPI(); assert totest.getContainedItem().equals(elem.getContainerPage()); } /** * This test add a random number of desired objet in the list or of one of each existing subtypes. * then test how many objet are retuned and if any exist inthe original list. */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void getInArcsHLAPITest(){ RefPlace llapi = new HlcorestructureFactoryImpl().createRefPlace(); int howmany; howmany = (int)(Math.random()*10); for(int i =0; i<howmany;i++) llapi.getInArcs().add(new HlcorestructureFactoryImpl().createArc()); RefPlaceHLAPI elem = new RefPlaceHLAPI(llapi); List<ArcHLAPI> totest = elem.getInArcsHLAPI(); assert totest.size() == howmany; for (ArcHLAPI unit : totest) { assert llapi.getInArcs().contains(unit.getContainedItem()) : "missing element"; } } /** * This test add a random number of desired objet in the list or of one of each existing subtypes. * then test how many objet are retuned and if any exist inthe original list. */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void getOutArcsHLAPITest(){ RefPlace llapi = new HlcorestructureFactoryImpl().createRefPlace(); int howmany; howmany = (int)(Math.random()*10); for(int i =0; i<howmany;i++) llapi.getOutArcs().add(new HlcorestructureFactoryImpl().createArc()); RefPlaceHLAPI elem = new RefPlaceHLAPI(llapi); List<ArcHLAPI> totest = elem.getOutArcsHLAPI(); assert totest.size() == howmany; for (ArcHLAPI unit : totest) { assert llapi.getOutArcs().contains(unit.getContainedItem()) : "missing element"; } } /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * @return : null if the element is null */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void getNodegraphicsHLAPITest(){ RefPlaceHLAPI elem = new RefPlaceHLAPI(new HlcorestructureFactoryImpl().createRefPlace()); elem.setNodegraphicsHLAPI(itemnodegraphics); NodeGraphicsHLAPI totest = elem.getNodegraphicsHLAPI(); assert totest.getContainedItem().equals(elem.getNodegraphics()); } /** * This test add a random number of desired objet in the list or of one of each existing subtypes. * then test how many objet are retuned and if any exist inthe original list. */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void getReferencingPlacesHLAPITest(){ RefPlace llapi = new HlcorestructureFactoryImpl().createRefPlace(); int howmany; howmany = (int)(Math.random()*10); for(int i =0; i<howmany;i++) llapi.getReferencingPlaces().add(new HlcorestructureFactoryImpl().createRefPlace()); RefPlaceHLAPI elem = new RefPlaceHLAPI(llapi); List<RefPlaceHLAPI> totest = elem.getReferencingPlacesHLAPI(); assert totest.size() == howmany; for (RefPlaceHLAPI unit : totest) { assert llapi.getReferencingPlaces().contains(unit.getContainedItem()) : "missing element"; } } /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * @return : null if the element is null */ @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void getRefHLAPITest(){ RefPlaceHLAPI elem = new RefPlaceHLAPI(new HlcorestructureFactoryImpl().createRefPlace()); elem.setRefHLAPI(new fr.lip6.move.pnml.hlpn.hlcorestructure.hlapi.PlaceHLAPI(new HlcorestructureFactoryImpl().createPlace())); PlaceNodeHLAPI totest_hlcorestructure_Place = elem.getRefHLAPI(); assert totest_hlcorestructure_Place.getContainedItem().equals(elem.getRef()); elem.setRefHLAPI(new fr.lip6.move.pnml.hlpn.hlcorestructure.hlapi.RefPlaceHLAPI(new HlcorestructureFactoryImpl().createRefPlace())); PlaceNodeHLAPI totest_hlcorestructure_RefPlace = elem.getRefHLAPI(); assert totest_hlcorestructure_RefPlace.getContainedItem().equals(elem.getRef()); } //Special getter for list of generics object, return only one object type. //setters/remover for lists. @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void addToolspecificsHLAPITest(){ RefPlaceHLAPI elem = new RefPlaceHLAPI(new HlcorestructureFactoryImpl().createRefPlace()); int howmany = (int)(Math.random()*10); for(int i =0; i<howmany;i++) elem.addToolspecificsHLAPI(new ToolInfoHLAPI(new HlcorestructureFactoryImpl().createToolInfo())); assert elem.getContainedItem().getToolspecifics().size() == howmany; } @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void removeToolspecificsTest(){ RefPlaceHLAPI elem = new RefPlaceHLAPI(new HlcorestructureFactoryImpl().createRefPlace()); int howmany = (int)(Math.random()*10); int howdiff = (int)(Math.random()*10); ToolInfoHLAPI sav; for(int i =0; i<(howmany);i++) elem.addToolspecificsHLAPI(new ToolInfoHLAPI(new HlcorestructureFactoryImpl().createToolInfo())); sav = new ToolInfoHLAPI(new HlcorestructureFactoryImpl().createToolInfo()); elem.addToolspecificsHLAPI(sav); assert elem.getContainedItem().getToolspecifics().size() == howmany+1; for(int i =0; i<(howdiff);i++) elem.addToolspecificsHLAPI(new ToolInfoHLAPI(new HlcorestructureFactoryImpl().createToolInfo())); elem.removeToolspecificsHLAPI(sav); assert elem.getContainedItem().getToolspecifics().size() == howmany+howdiff; } @Test(groups = { "hlapi", "RefPlaceHLAPI"}) public void equalsTest(){ RefPlace a = new HlcorestructureFactoryImpl().createRefPlace(); RefPlace b = new HlcorestructureFactoryImpl().createRefPlace(); RefPlaceHLAPI aprime = new RefPlaceHLAPI(a); RefPlaceHLAPI asecond = new RefPlaceHLAPI(a); RefPlaceHLAPI bprime = new RefPlaceHLAPI(b); assert aprime.equals(asecond); assert !aprime.equals(bprime); } //cloning method //public RefPlaceHLAPI clone(){ // return new RefPlaceHLAPI(this); //} //PNML /** * return the PNML xml tree for this object. */ //public String toPNML(){ //return item.toPNML(); //} /** * creates an object from the xml nodes.(symetric work of toPNML) */ //public void fromPNML(OMElement subRoot,IdRefLinker idr) throws InnerBuildException, InvalidIDException, VoidRepositoryException{ //item.fromPNML(subRoot,idr); //} }
epl-1.0
SPDSS/adss
eu.aspire_fp7.adss/src/eu/aspire_fp7/adss/l1p/ProtectionEvaluator.java
1172
/******************************************************************************* * Copyright (c) 2016 Politecnico di Torino. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Politecnico di Torino - initial API and implementation *******************************************************************************/ package eu.aspire_fp7.adss.l1p; import eu.aspire_fp7.adss.ADSS; /** * Evaluates a protection. * * @author Daniele Canavese **/ public abstract class ProtectionEvaluator { /** The ADSS. **/ protected ADSS adss; /** * Creates the evaluator. * @param adss * The ADSS. **/ public ProtectionEvaluator(ADSS adss) { this.adss = adss; } /** * Initializes the connector. **/ public void initialize() { } /** * Retrieves the strength for a set of protections. * @param state * The state. * @return The protection strength. **/ public abstract double getStrength(State state); }
epl-1.0
posl/iArch
jp.ac.kyushu_u.iarch.basefunction/src/jp/ac/kyushu_u/iarch/basefunction/reader/XMLreader.java
6418
package jp.ac.kyushu_u.iarch.basefunction.reader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Node; import org.dom4j.io.SAXReader; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; /** * Read an arch configuration file in a Java project * @author Templar */ public class XMLreader { private String ArchfilePath = null; private String ClassDiagramPath = null; private List<String> SequenceDiagramPathes= new ArrayList<String>(); private List<String> SourceCodePathes = new ArrayList<String>(); private String ARXMLPath = null; private IJavaProject JavaProject = null; private boolean succeeded_ = false; public static final String CONFIG_FILEPATH = "Config.xml"; public XMLreader(IProject project){ readXMLContent(project); setJavaProject(JavaCore.create(project)); } public static boolean isConfigFileExist(IProject project){ return project.getFile(XMLreader.CONFIG_FILEPATH).exists(); } public static IFile getConfigFile(IProject project){ return project.getFile(XMLreader.CONFIG_FILEPATH); } public static IResource readIResource(IPath path){ IResource re = ResourcesPlugin.getWorkspace().getRoot().findMember(path); return re; } public void readXMLContent(IProject project) { IFile file = project.getFile(CONFIG_FILEPATH); if (!file.exists()){ try { IMarker marker = project.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.MESSAGE, "Auto-Check failed: Please check the Archface Configuration.(Menu->iArch->Configuration)"); marker.setAttribute(IMarker.DONE, false); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ try{ SAXReader saxReader = new SAXReader(); Document document = saxReader.read(file.getContents()); { @SuppressWarnings("unchecked") List<Node> Archfilelist = document.selectNodes("//Archfile/Path/@Attribute"); Attribute attribute=(Attribute) Archfilelist.get(0); setArchfilePath(attribute.getValue()); } { @SuppressWarnings("unchecked") List<Node> ClassDiagramlist = document.selectNodes("//ClassDiagram/Path/@Attribute"); if(ClassDiagramlist.size()!=0){ Attribute attribute=(Attribute) ClassDiagramlist.get(0); setClassDiagramPath(attribute.getValue()); } } { @SuppressWarnings("unchecked") List<Node> SequenceDiagramlist = document.selectNodes("//SequenceDiagram/Path/@Attribute"); if(SequenceDiagramlist.size()!=0){ for (Iterator<Node> iter = SequenceDiagramlist.iterator(); iter.hasNext(); ) { Attribute attribute = (Attribute) iter.next(); String url = attribute.getValue(); SequenceDiagramPathes.add(url); } } } { @SuppressWarnings("unchecked") List<Node> SourceCodelist = document.selectNodes("//SourceCode/Path/@Attribute"); for (Iterator<Node> iter = SourceCodelist.iterator(); iter.hasNext(); ) { Attribute attribute = (Attribute) iter.next(); String url = attribute.getValue(); SourceCodePathes.add(url); } } { @SuppressWarnings("unchecked") List<Node> ARXMLlist = document.selectNodes("//ARXML/Path/@Attribute"); Attribute attribute=(Attribute) ARXMLlist.get(0); setARXMLPath(attribute.getValue()); } succeeded_ = true; } catch(DocumentException e){ System.out.println(e.getMessage()); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * @return the aRXMLResource */ public IResource getARXMLResource() { if (ARXMLPath == null) { return null; } IPath path = new Path(ARXMLPath); IResource ARXMLResource = readIResource(path); return ARXMLResource; } /** * @param aRXMLPath the aRXMLPath to set */ public void setARXMLPath(String aRXMLPath) { ARXMLPath = aRXMLPath; } /** * @return the classDiagramResource */ public IResource getClassDiagramResource() { if (ClassDiagramPath == null) { return null; } IPath path = new Path(ClassDiagramPath); IResource ClassDiagramResource = readIResource(path); return ClassDiagramResource; } /** * @param classDiagramPath the classDiagramPath to set */ public void setClassDiagramPath(String classDiagramPath) { ClassDiagramPath = classDiagramPath; } /** * @return the archfileResource */ public IResource getArchfileResource() { if (ArchfilePath == null) { return null; } IPath path = new Path(ArchfilePath); IResource Archfile = readIResource(path); return Archfile; } /** * @param archfilePath the archfilePath to set */ public void setArchfilePath(String archfilePath) { ArchfilePath = archfilePath; } /** * @return the SequenceDiagramResources */ public List<IResource> getSequenceDiagramResource(){ List<IResource> SequenceDiagramResources = new ArrayList<IResource>(); for (String SequenceDiagramPath : SequenceDiagramPathes) { IPath path = new Path(SequenceDiagramPath); IResource SequenceDiagramResource = readIResource(path); SequenceDiagramResources.add(SequenceDiagramResource); } return SequenceDiagramResources; } /** * @return the SourceCodeResources */ public List<IResource> getSourceCodeResource(){ List<IResource> SourceCodeResources = new ArrayList<IResource>(); for (String SourceCodePath : SourceCodePathes) { IPath path = new Path(SourceCodePath); IResource SourceCodeResource = readIResource(path); SourceCodeResources.add(SourceCodeResource); } return SourceCodeResources; } /** * @return the javaProject */ public IJavaProject getJavaProject() { return JavaProject; } /** * @param javaProject the javaProject to set */ private void setJavaProject(IJavaProject javaProject) { JavaProject = javaProject; } public boolean succeeded() { return succeeded_; } }
epl-1.0
jeff2001/jenkins-tray
HudsonTrayTracker/UI/Controls/ServerListControl.cs
4432
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using Hudson.TrayTracker.BusinessComponents; using Hudson.TrayTracker.Entities; using DevExpress.XtraBars; using Hudson.TrayTracker.Utils.BackgroundProcessing; using Spring.Context.Support; namespace Hudson.TrayTracker.UI.Controls { public partial class ServerListControl : DevExpress.XtraEditors.XtraUserControl { BindingList<Server> serversDataSource; bool initialized; public ServersSettingsController Controller { get; set; } public ConfigurationService ConfigurationService { get; set; } public ServerListControl() { InitializeComponent(); } public void Initialize() { serversDataSource = new BindingList<Server>(); foreach (Server server in ConfigurationService.Servers) serversDataSource.Add(server); serversGridControl.DataSource = serversDataSource; initialized = true; serversGridView_FocusedRowChanged(null, null); } private void addServerButtonItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { EditServerForm namingForm = new EditServerForm(); if (namingForm.ShowDialog() != DialogResult.OK) return; Server server = ConfigurationService.AddServer( namingForm.ServerAddress, namingForm.ServerName, namingForm.Username, namingForm.Password, namingForm.IgnoreUntrustedCertificate); if (server == null) return; serversDataSource.Add(server); } private void editServerButtonItem_ItemClick(object sender, ItemClickEventArgs e) { EditSelectedServer(); } private void editServerMenuItem_Click(object sender, EventArgs e) { EditSelectedServer(); } private void EditSelectedServer() { Server server = GetSelectedServer(); if (server == null) return; EditServerForm namingForm = new EditServerForm(server); if (namingForm.ShowDialog() != DialogResult.OK) return; ConfigurationService.UpdateServer(server, namingForm.ServerAddress, namingForm.ServerName, namingForm.Username, namingForm.Password, namingForm.IgnoreUntrustedCertificate); serversGridView.RefreshData(); Controller.UpdateProjectList(server); } private void removeServerButtonItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { RemoveSelectedServer(); } private void removeServerMenuItem_Click(object sender, EventArgs e) { RemoveSelectedServer(); } private void RemoveSelectedServer() { Server server = GetSelectedServer(); if (server == null) return; serversDataSource.Remove(server); ConfigurationService.RemoveServer(server); } private void serversGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) { if (initialized == false) return; Server server = GetSelectedServer(); // update the toolbar editServerButtonItem.Enabled = removeServerButtonItem.Enabled = server != null; // update the project list Controller.UpdateProjectList(server); } private Server GetSelectedServer() { object row = serversGridView.GetFocusedRow(); Server server = row as Server; return server; } private void contextMenuStrip_Opening(object sender, CancelEventArgs e) { Server server = GetSelectedServer(); editServerMenuItem.Enabled = removeServerMenuItem.Enabled = (server != null); } } }
epl-1.0
djelinek/reddeer
plugins/org.eclipse.reddeer.workbench/src/org/eclipse/reddeer/workbench/lookup/ViewLookup.java
2504
/******************************************************************************* * Copyright (c) 2017 Red Hat, Inc and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.reddeer.workbench.lookup; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.views.IViewCategory; import org.eclipse.ui.views.IViewDescriptor; import org.hamcrest.Matcher; import org.eclipse.reddeer.workbench.exception.WorkbenchLayerException; /** * View lookup * @author rawagner * */ public class ViewLookup { private static ViewLookup instance; /** * Returns instance of ViewLookup * @return ViewLookup instance */ public static ViewLookup getInstance(){ if(instance == null){ instance = new ViewLookup(); } return instance; } /** * Finds registered view path * @param title of view * @return view path */ public String[] findRegisteredViewPath(Matcher<String> title) { IViewDescriptor viewDescriptor = findView(title); IViewCategory categoryDescriptor = findViewCategory(viewDescriptor); return pathForView(viewDescriptor, categoryDescriptor); } private IViewDescriptor findView(Matcher<String> title) { IViewDescriptor[] views = PlatformUI.getWorkbench().getViewRegistry().getViews(); for (IViewDescriptor view : views) { if (title.matches(view.getLabel())) { return view; } } throw new WorkbenchLayerException("View '" + title+ "' is not registered in workbench"); } private IViewCategory findViewCategory(IViewDescriptor viewDescriptor) { IViewCategory[] categories = PlatformUI.getWorkbench().getViewRegistry().getCategories(); for (IViewCategory category : categories) { for (IViewDescriptor ivd : category.getViews()) { if (ivd.getId().equals(viewDescriptor.getId())) { return category; } } } throw new WorkbenchLayerException("View '" + viewDescriptor.getLabel()+ "' is not registered in any category"); } private String[] pathForView(IViewDescriptor viewDescriptor, IViewCategory categoryDescriptor) { String[] path = new String[2]; path[0] = categoryDescriptor.getLabel(); path[1] = viewDescriptor.getLabel(); return path; } }
epl-1.0
build-canaries/nevergreen
src/client/settings/success/SuccessReducer.test.ts
2147
import {getSuccessMessages, reduce, SUCCESS_ROOT, SuccessState} from './SuccessReducer' import {Actions} from '../../Actions' import {addMessage, removeMessage} from './SuccessActionCreators' import {buildState, testReducer} from '../../testHelpers' import {configurationImported} from '../backup/BackupActionCreators' const reducer = testReducer({ [SUCCESS_ROOT]: reduce }) function state(existing?: SuccessState) { return buildState({[SUCCESS_ROOT]: existing}) } it('should return the state unmodified for an unknown action', () => { const existingState = state(['some-state']) const newState = reducer(existingState, {type: 'not-a-real-action'}) expect(newState).toEqual(existingState) }) describe(Actions.CONFIGURATION_IMPORTED, () => { it('should merge the success data', () => { const existingState = state([]) const action = configurationImported({success: ['some-message']}) const newState = reducer(existingState, action) expect(getSuccessMessages(newState)).toEqual(['some-message']) }) it('should handle no success data', () => { const existingState = state([]) const action = configurationImported({}) const newState = reducer(existingState, action) expect(getSuccessMessages(newState)).toHaveLength(0) }) }) describe(Actions.MESSAGE_ADDED, () => { it('should add the given message', () => { const existingState = state([]) const action = addMessage('some-message') const newState = reducer(existingState, action) expect(getSuccessMessages(newState)).toEqual(['some-message']) }) it('should not add the same message multiple times', () => { const existingState = state(['some-message']) const action = addMessage('some-message') const newState = reducer(existingState, action) expect(getSuccessMessages(newState)).toHaveLength(1) }) }) describe(Actions.MESSAGE_REMOVED, () => { it('should remove the given message', () => { const existingState = state(['a', 'b', 'c']) const action = removeMessage('b') const newState = reducer(existingState, action) expect(getSuccessMessages(newState)).toEqual(['a', 'c']) }) })
epl-1.0
till-f/es-tdk
workspace_main/fzi.mottem.runtime/src/fzi/mottem/runtime/rti/isystem/ISYSTEMXmlContentHandler.java
5244
package fzi.mottem.runtime.rti.isystem; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import fzi.mottem.model.baseelements.ITestReferenceable; import fzi.mottem.ptspec.dsl.common.PTSpecUtils; import fzi.mottem.runtime.TraceDB; import fzi.mottem.runtime.TraceDB.TraceDBEvent; /** * * The ContentHandler that is used by the SAX parser to handle XML files that contain winIDEA profiler variables and function calls * * @author deuchler * */ public class ISYSTEMXmlContentHandler implements ContentHandler { // MAPPING is the beginning of the xml document where variable and function mappings are defined // TIMELINE is the part of the xml document where reads writes and function calls (X for execute, E for exit) are stored // map the "handle" numerical values to the corresponding name of a variable/function private HashMap<String,String> _handleToUIDMap = new HashMap<String,String>(); class Entry { public String name = null; public String value = null; } private Entry entry = new Entry(); // xml entry of the current element private HashMap<String,String> domSubSet = new HashMap<String,String>(); // contains <name>value</name> pairs private final ISYSTEMTraceDriver _traceCtrl; private final TraceDB _traceDB; public ISYSTEMXmlContentHandler(ISYSTEMTraceDriver traceCtrl) throws SQLException { _traceCtrl = traceCtrl; _traceDB = traceCtrl.getTrace().getTraceDB(); } @Override public void characters(char[] arg0, int arg1, int arg2) throws SAXException { //TODO read only between arg1 and arg2 entry.value = new String(arg0, arg1, arg2); if(entry.value.equals("\n") || entry.value.equals("\n\n")) //"TODO regular expression entry.value = null; } @Override public void endElement(String uri,String localName,String qName) throws SAXException { if(entry.value != null && !entry.value.equals("")) { entry.name = localName; domSubSet.put(entry.name, entry.value); entry = new Entry(); } if(localName.equals("AREA")) { String isystemName = domSubSet.get("NAME"); if (_traceCtrl.ISYSTEMNameToElementMap.containsKey(isystemName)) { ITestReferenceable tref = _traceCtrl.ISYSTEMNameToElementMap.get(isystemName); String ptsUID = PTSpecUtils.getElementUID(tref); _handleToUIDMap.put(domSubSet.get("HANDLE"), ptsUID); } else { System.err.println("Unexpected name in ISYSTEM XML: " + isystemName); } domSubSet = new HashMap<String, String>(); } else if(localName.equals("T")) { // TIME Long time = Long.decode(domSubSet.get("TIME")); // EVENT /* * W _W_rite to [ele] * E [ele] is _E_ntered * S in [ele] _S_ubroutine is about to be called * R [ele] has _R_eturnd * X [ele] has e_X_ited function ? */ TraceDBEvent dbEvent; String isystemEventString = domSubSet.get("EVENT"); if (isystemEventString.contains("W")) dbEvent = TraceDBEvent.Write; else if (isystemEventString.contains("E")) dbEvent = TraceDBEvent.Call; else if (isystemEventString.contains("R")) dbEvent = TraceDBEvent.Return; else dbEvent = TraceDBEvent.UNSPECIFIED; // UID String isystemHandle = domSubSet.get("HANDLE"); String uid; if (_handleToUIDMap.containsKey(isystemHandle)) { uid = _handleToUIDMap.get(domSubSet.get("HANDLE")); } else { uid = isystemHandle; System.err.println("No UID for handle " + isystemHandle); } // VALUE String value = domSubSet.get("VALUE"); _traceDB.insertValueMS(time.doubleValue()/1000/1000, dbEvent, uid, value); domSubSet = new HashMap<String, String>(); } } @Override public void endDocument() throws SAXException { // nothing to do } /** * for debugging * @param map */ @SuppressWarnings("unused") private static void printMap(Map<String,String> map) { Collection<java.util.Map.Entry<String, String>> c = map.entrySet(); Iterator<java.util.Map.Entry<String, String>> it = c.iterator(); while(it.hasNext()) { java.util.Map.Entry<String, String> i = it.next(); System.out.println("Key: " + i.getKey() + " Value: " + i.getValue()); } } @Override public void startPrefixMapping(String arg0, String arg1) throws SAXException{} @Override public void endPrefixMapping(String arg0) throws SAXException {} @Override public void ignorableWhitespace(char[] arg0, int arg1, int arg2) throws SAXException {} @Override public void processingInstruction(String arg0, String arg1) throws SAXException {} @Override public void setDocumentLocator(Locator arg0) {} @Override public void skippedEntity(String arg0) throws SAXException {} @Override public void startDocument() throws SAXException {} @Override public void startElement(String uri,String localName,String qName, Attributes atts) throws SAXException {} }
epl-1.0
HundunStar/AutoTransfer
src/main/java/com/BioStace/AutoTransfer/line/Path.java
64
package com.BioStace.AutoTransfer.line; public class Path { }
epl-1.0
DavidGutknecht/elexis-3-base
bundles/ch.docbox.elexis/src/org/hl7/v3/PPDTS.java
2123
package org.hl7.v3; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p> * Java class for PPD_TS complex type. * * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PPD_TS"> * &lt;complexContent> * &lt;extension base="{urn:hl7-org:v3}TS"> * &lt;sequence> * &lt;element name="standardDeviation" type="{urn:hl7-org:v3}PQ" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="distributionType" type="{urn:hl7-org:v3}ProbabilityDistributionType" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PPD_TS", propOrder = { "standardDeviation" }) @XmlSeeAlso({ IVXBPPDTS.class, SXCMPPDTS.class }) public class PPDTS extends TS { /** * */ private static final long serialVersionUID = 1L; protected PQ standardDeviation; @XmlAttribute protected ProbabilityDistributionType distributionType; /** * Gets the value of the standardDeviation property. * * @return possible object is {@link PQ } * */ public PQ getStandardDeviation(){ return standardDeviation; } /** * Sets the value of the standardDeviation property. * * @param value * allowed object is {@link PQ } * */ public void setStandardDeviation(PQ value){ this.standardDeviation = value; } /** * Gets the value of the distributionType property. * * @return possible object is {@link ProbabilityDistributionType } * */ public ProbabilityDistributionType getDistributionType(){ return distributionType; } /** * Sets the value of the distributionType property. * * @param value * allowed object is {@link ProbabilityDistributionType } * */ public void setDistributionType(ProbabilityDistributionType value){ this.distributionType = value; } }
epl-1.0
smadelenat/CapellaModeAutomata
Semantic/Scenario/org.gemoc.scenario.xdsml/src-gen/org/gemoc/scenario/xdsml/functionscenario/adapters/functionscenariomt/la/LogicalContextAdapter.java
72195
package org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.la; import fr.inria.diverse.melange.adapters.EObjectAdapter; import java.util.Collection; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioMTAdaptersFactory; import org.polarsys.capella.core.data.la.LogicalContext; @SuppressWarnings("all") public class LogicalContextAdapter extends EObjectAdapter<LogicalContext> implements org.gemoc.scenario.xdsml.functionscenariomt.la.LogicalContext { private FunctionScenarioMTAdaptersFactory adaptersFactory; public LogicalContextAdapter() { super(org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioMTAdaptersFactory.getInstance()); adaptersFactory = org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioMTAdaptersFactory.getInstance(); } @Override public String getId() { return adaptee.getId(); } @Override public void setId(final String o) { adaptee.setId(o); } @Override public String getSid() { return adaptee.getSid(); } @Override public void setSid(final String o) { adaptee.setSid(o); } @Override public String getName() { return adaptee.getName(); } @Override public void setName(final String o) { adaptee.setName(o); } @Override public boolean isVisibleInDoc() { return adaptee.isVisibleInDoc(); } @Override public void setVisibleInDoc(final boolean o) { adaptee.setVisibleInDoc(o); } @Override public boolean isVisibleInLM() { return adaptee.isVisibleInLM(); } @Override public void setVisibleInLM(final boolean o) { adaptee.setVisibleInLM(o); } @Override public String getSummary() { return adaptee.getSummary(); } @Override public void setSummary(final String o) { adaptee.setSummary(o); } @Override public String getDescription() { return adaptee.getDescription(); } @Override public void setDescription(final String o) { adaptee.setDescription(o); } @Override public String getReview() { return adaptee.getReview(); } @Override public void setReview(final String o) { adaptee.setReview(o); } @Override public boolean isAbstract() { return adaptee.isAbstract(); } @Override public void setAbstract(final boolean o) { adaptee.setAbstract(o); } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.emde.ElementExtension> */Object ownedExtensions_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.emde.ElementExtension> */Object getOwnedExtensions() { if (ownedExtensions_ == null) ownedExtensions_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedExtensions(), adaptersFactory, eResource); return ownedExtensions_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object constraints_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object getConstraints() { if (constraints_ == null) constraints_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getConstraints(), adaptersFactory, eResource); return constraints_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object ownedConstraints_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object getOwnedConstraints() { if (ownedConstraints_ == null) ownedConstraints_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedConstraints(), adaptersFactory, eResource); return ownedConstraints_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTypedElement> */Object abstractTypedElements_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTypedElement> */Object getAbstractTypedElements() { if (abstractTypedElements_ == null) abstractTypedElements_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAbstractTypedElements(), adaptersFactory, eResource); return abstractTypedElements_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object incomingTraces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object getIncomingTraces() { if (incomingTraces_ == null) incomingTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getIncomingTraces(), adaptersFactory, eResource); return incomingTraces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object outgoingTraces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object getOutgoingTraces() { if (outgoingTraces_ == null) outgoingTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOutgoingTraces(), adaptersFactory, eResource); return outgoingTraces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object ownedPropertyValues_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object getOwnedPropertyValues() { if (ownedPropertyValues_ == null) ownedPropertyValues_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPropertyValues(), adaptersFactory, eResource); return ownedPropertyValues_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyType> */Object ownedEnumerationPropertyTypes_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyType> */Object getOwnedEnumerationPropertyTypes() { if (ownedEnumerationPropertyTypes_ == null) ownedEnumerationPropertyTypes_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedEnumerationPropertyTypes(), adaptersFactory, eResource); return ownedEnumerationPropertyTypes_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object appliedPropertyValues_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object getAppliedPropertyValues() { if (appliedPropertyValues_ == null) appliedPropertyValues_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAppliedPropertyValues(), adaptersFactory, eResource); return appliedPropertyValues_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object ownedPropertyValueGroups_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object getOwnedPropertyValueGroups() { if (ownedPropertyValueGroups_ == null) ownedPropertyValueGroups_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPropertyValueGroups(), adaptersFactory, eResource); return ownedPropertyValueGroups_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object appliedPropertyValueGroups_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object getAppliedPropertyValueGroups() { if (appliedPropertyValueGroups_ == null) appliedPropertyValueGroups_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAppliedPropertyValueGroups(), adaptersFactory, eResource); return appliedPropertyValueGroups_; } @Override public org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral getStatus() { return () adaptersFactory.createAdapter(adaptee.getStatus(), eResource); } @Override public void setStatus(final org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral o) { if (o != null) adaptee.setStatus(((org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.capellacore.EnumerationPropertyLiteralAdapter) o).getAdaptee()); else adaptee.setStatus(null); } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral> */Object features_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral> */Object getFeatures() { if (features_ == null) features_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getFeatures(), adaptersFactory, eResource); return features_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.requirement.Requirement> */Object appliedRequirements_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.requirement.Requirement> */Object getAppliedRequirements() { if (appliedRequirements_ == null) appliedRequirements_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAppliedRequirements(), adaptersFactory, eResource); return appliedRequirements_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Trace> */Object ownedTraces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Trace> */Object getOwnedTraces() { if (ownedTraces_ == null) ownedTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedTraces(), adaptersFactory, eResource); return ownedTraces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.GenericTrace> */Object containedGenericTraces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.GenericTrace> */Object getContainedGenericTraces() { if (containedGenericTraces_ == null) containedGenericTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getContainedGenericTraces(), adaptersFactory, eResource); return containedGenericTraces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.requirement.RequirementsTrace> */Object containedRequirementsTraces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.requirement.RequirementsTrace> */Object getContainedRequirementsTraces() { if (containedRequirementsTraces_ == null) containedRequirementsTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getContainedRequirementsTraces(), adaptersFactory, eResource); return containedRequirementsTraces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.NamingRule> */Object namingRules_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.NamingRule> */Object getNamingRules() { if (namingRules_ == null) namingRules_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getNamingRules(), adaptersFactory, eResource); return namingRules_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.TypedElement> */Object typedElements_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.TypedElement> */Object getTypedElements() { if (typedElements_ == null) typedElements_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getTypedElements(), adaptersFactory, eResource); return typedElements_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentFunctionalAllocation> */Object ownedFunctionalAllocation_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentFunctionalAllocation> */Object getOwnedFunctionalAllocation() { if (ownedFunctionalAllocation_ == null) ownedFunctionalAllocation_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedFunctionalAllocation(), adaptersFactory, eResource); return ownedFunctionalAllocation_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentExchange> */Object ownedComponentExchanges_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentExchange> */Object getOwnedComponentExchanges() { if (ownedComponentExchanges_ == null) ownedComponentExchanges_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedComponentExchanges(), adaptersFactory, eResource); return ownedComponentExchanges_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentExchangeCategory> */Object ownedComponentExchangeCategories_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentExchangeCategory> */Object getOwnedComponentExchangeCategories() { if (ownedComponentExchangeCategories_ == null) ownedComponentExchangeCategories_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedComponentExchangeCategories(), adaptersFactory, eResource); return ownedComponentExchangeCategories_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentFunctionalAllocation> */Object functionalAllocations_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentFunctionalAllocation> */Object getFunctionalAllocations() { if (functionalAllocations_ == null) functionalAllocations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getFunctionalAllocations(), adaptersFactory, eResource); return functionalAllocations_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.AbstractFunction> */Object allocatedFunctions_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.AbstractFunction> */Object getAllocatedFunctions() { if (allocatedFunctions_ == null) allocatedFunctions_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAllocatedFunctions(), adaptersFactory, eResource); return allocatedFunctions_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ExchangeLink> */Object inExchangeLinks_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ExchangeLink> */Object getInExchangeLinks() { if (inExchangeLinks_ == null) inExchangeLinks_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getInExchangeLinks(), adaptersFactory, eResource); return inExchangeLinks_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ExchangeLink> */Object outExchangeLinks_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ExchangeLink> */Object getOutExchangeLinks() { if (outExchangeLinks_ == null) outExchangeLinks_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOutExchangeLinks(), adaptersFactory, eResource); return outExchangeLinks_; } @Override public org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.AbstractCapabilityPkg getOwnedAbstractCapabilityPkg() { return () adaptersFactory.createAdapter(adaptee.getOwnedAbstractCapabilityPkg(), eResource); } @Override public void setOwnedAbstractCapabilityPkg(final org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.AbstractCapabilityPkg o) { if (o != null) adaptee.setOwnedAbstractCapabilityPkg(((org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.capellacommon.AbstractCapabilityPkgAdapter) o).getAdaptee()); else adaptee.setOwnedAbstractCapabilityPkg(null); } @Override public org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfacePkg getOwnedInterfacePkg() { return () adaptersFactory.createAdapter(adaptee.getOwnedInterfacePkg(), eResource); } @Override public void setOwnedInterfacePkg(final org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfacePkg o) { if (o != null) adaptee.setOwnedInterfacePkg(((org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.cs.InterfacePkgAdapter) o).getAdaptee()); else adaptee.setOwnedInterfacePkg(null); } @Override public org.gemoc.scenario.xdsml.functionscenariomt.information.DataPkg getOwnedDataPkg() { return () adaptersFactory.createAdapter(adaptee.getOwnedDataPkg(), eResource); } @Override public void setOwnedDataPkg(final org.gemoc.scenario.xdsml.functionscenariomt.information.DataPkg o) { if (o != null) adaptee.setOwnedDataPkg(((org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.information.DataPkgAdapter) o).getAdaptee()); else adaptee.setOwnedDataPkg(null); } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.StateMachine> */Object ownedStateMachines_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.StateMachine> */Object getOwnedStateMachines() { if (ownedStateMachines_ == null) ownedStateMachines_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedStateMachines(), adaptersFactory, eResource); return ownedStateMachines_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Generalization> */Object ownedGeneralizations_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Generalization> */Object getOwnedGeneralizations() { if (ownedGeneralizations_ == null) ownedGeneralizations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedGeneralizations(), adaptersFactory, eResource); return ownedGeneralizations_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Generalization> */Object superGeneralizations_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Generalization> */Object getSuperGeneralizations() { if (superGeneralizations_ == null) superGeneralizations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getSuperGeneralizations(), adaptersFactory, eResource); return superGeneralizations_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Generalization> */Object subGeneralizations_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Generalization> */Object getSubGeneralizations() { if (subGeneralizations_ == null) subGeneralizations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getSubGeneralizations(), adaptersFactory, eResource); return subGeneralizations_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.GeneralizableElement> */Object super_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.GeneralizableElement> */Object getSuper() { if (super_ == null) super_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getSuper(), adaptersFactory, eResource); return super_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.GeneralizableElement> */Object sub_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.GeneralizableElement> */Object getSub() { if (sub_ == null) sub_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getSub(), adaptersFactory, eResource); return sub_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Feature> */Object ownedFeatures_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Feature> */Object getOwnedFeatures() { if (ownedFeatures_ == null) ownedFeatures_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedFeatures(), adaptersFactory, eResource); return ownedFeatures_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.information.Property> */Object containedProperties_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.information.Property> */Object getContainedProperties() { if (containedProperties_ == null) containedProperties_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getContainedProperties(), adaptersFactory, eResource); return containedProperties_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.information.Partition> */Object ownedPartitions_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.information.Partition> */Object getOwnedPartitions() { if (ownedPartitions_ == null) ownedPartitions_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPartitions(), adaptersFactory, eResource); return ownedPartitions_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.information.Partition> */Object representingPartitions_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.information.Partition> */Object getRepresentingPartitions() { if (representingPartitions_ == null) representingPartitions_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getRepresentingPartitions(), adaptersFactory, eResource); return representingPartitions_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceAllocation> */Object ownedInterfaceAllocations_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceAllocation> */Object getOwnedInterfaceAllocations() { if (ownedInterfaceAllocations_ == null) ownedInterfaceAllocations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedInterfaceAllocations(), adaptersFactory, eResource); return ownedInterfaceAllocations_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceAllocation> */Object provisionedInterfaceAllocations_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceAllocation> */Object getProvisionedInterfaceAllocations() { if (provisionedInterfaceAllocations_ == null) provisionedInterfaceAllocations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getProvisionedInterfaceAllocations(), adaptersFactory, eResource); return provisionedInterfaceAllocations_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Interface> */Object allocatedInterfaces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Interface> */Object getAllocatedInterfaces() { if (allocatedInterfaces_ == null) allocatedInterfaces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAllocatedInterfaces(), adaptersFactory, eResource); return allocatedInterfaces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object ownedCommunicationLinks_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getOwnedCommunicationLinks() { if (ownedCommunicationLinks_ == null) ownedCommunicationLinks_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedCommunicationLinks(), adaptersFactory, eResource); return ownedCommunicationLinks_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object produce_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getProduce() { if (produce_ == null) produce_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getProduce(), adaptersFactory, eResource); return produce_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object consume_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getConsume() { if (consume_ == null) consume_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getConsume(), adaptersFactory, eResource); return consume_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object send_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getSend() { if (send_ == null) send_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getSend(), adaptersFactory, eResource); return send_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object receive_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getReceive() { if (receive_ == null) receive_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getReceive(), adaptersFactory, eResource); return receive_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object call_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getCall() { if (call_ == null) call_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getCall(), adaptersFactory, eResource); return call_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object execute_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getExecute() { if (execute_ == null) execute_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getExecute(), adaptersFactory, eResource); return execute_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object write_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getWrite() { if (write_ == null) write_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getWrite(), adaptersFactory, eResource); return write_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object access_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getAccess() { if (access_ == null) access_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAccess(), adaptersFactory, eResource); return access_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object acquire_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getAcquire() { if (acquire_ == null) acquire_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAcquire(), adaptersFactory, eResource); return acquire_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object transmit_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.communication.CommunicationLink> */Object getTransmit() { if (transmit_ == null) transmit_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getTransmit(), adaptersFactory, eResource); return transmit_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceUse> */Object ownedInterfaceUses_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceUse> */Object getOwnedInterfaceUses() { if (ownedInterfaceUses_ == null) ownedInterfaceUses_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedInterfaceUses(), adaptersFactory, eResource); return ownedInterfaceUses_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceUse> */Object usedInterfaceLinks_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceUse> */Object getUsedInterfaceLinks() { if (usedInterfaceLinks_ == null) usedInterfaceLinks_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getUsedInterfaceLinks(), adaptersFactory, eResource); return usedInterfaceLinks_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Interface> */Object usedInterfaces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Interface> */Object getUsedInterfaces() { if (usedInterfaces_ == null) usedInterfaces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getUsedInterfaces(), adaptersFactory, eResource); return usedInterfaces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceImplementation> */Object ownedInterfaceImplementations_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceImplementation> */Object getOwnedInterfaceImplementations() { if (ownedInterfaceImplementations_ == null) ownedInterfaceImplementations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedInterfaceImplementations(), adaptersFactory, eResource); return ownedInterfaceImplementations_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceImplementation> */Object implementedInterfaceLinks_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfaceImplementation> */Object getImplementedInterfaceLinks() { if (implementedInterfaceLinks_ == null) implementedInterfaceLinks_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getImplementedInterfaceLinks(), adaptersFactory, eResource); return implementedInterfaceLinks_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Interface> */Object implementedInterfaces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Interface> */Object getImplementedInterfaces() { if (implementedInterfaces_ == null) implementedInterfaces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getImplementedInterfaces(), adaptersFactory, eResource); return implementedInterfaces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.ComponentAllocation> */Object provisionedComponentAllocations_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.ComponentAllocation> */Object getProvisionedComponentAllocations() { if (provisionedComponentAllocations_ == null) provisionedComponentAllocations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getProvisionedComponentAllocations(), adaptersFactory, eResource); return provisionedComponentAllocations_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.ComponentAllocation> */Object provisioningComponentAllocations_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.ComponentAllocation> */Object getProvisioningComponentAllocations() { if (provisioningComponentAllocations_ == null) provisioningComponentAllocations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getProvisioningComponentAllocations(), adaptersFactory, eResource); return provisioningComponentAllocations_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Component> */Object allocatedComponents_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Component> */Object getAllocatedComponents() { if (allocatedComponents_ == null) allocatedComponents_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAllocatedComponents(), adaptersFactory, eResource); return allocatedComponents_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Component> */Object allocatingComponents_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Component> */Object getAllocatingComponents() { if (allocatingComponents_ == null) allocatingComponents_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAllocatingComponents(), adaptersFactory, eResource); return allocatingComponents_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Interface> */Object providedInterfaces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Interface> */Object getProvidedInterfaces() { if (providedInterfaces_ == null) providedInterfaces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getProvidedInterfaces(), adaptersFactory, eResource); return providedInterfaces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Interface> */Object requiredInterfaces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Interface> */Object getRequiredInterfaces() { if (requiredInterfaces_ == null) requiredInterfaces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getRequiredInterfaces(), adaptersFactory, eResource); return requiredInterfaces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentPort> */Object containedComponentPorts_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentPort> */Object getContainedComponentPorts() { if (containedComponentPorts_ == null) containedComponentPorts_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getContainedComponentPorts(), adaptersFactory, eResource); return containedComponentPorts_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Part> */Object containedParts_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.Part> */Object getContainedParts() { if (containedParts_ == null) containedParts_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getContainedParts(), adaptersFactory, eResource); return containedParts_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.PhysicalPort> */Object containedPhysicalPorts_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.PhysicalPort> */Object getContainedPhysicalPorts() { if (containedPhysicalPorts_ == null) containedPhysicalPorts_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getContainedPhysicalPorts(), adaptersFactory, eResource); return containedPhysicalPorts_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.PhysicalPath> */Object ownedPhysicalPath_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.PhysicalPath> */Object getOwnedPhysicalPath() { if (ownedPhysicalPath_ == null) ownedPhysicalPath_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPhysicalPath(), adaptersFactory, eResource); return ownedPhysicalPath_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.PhysicalLink> */Object ownedPhysicalLinks_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.PhysicalLink> */Object getOwnedPhysicalLinks() { if (ownedPhysicalLinks_ == null) ownedPhysicalLinks_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPhysicalLinks(), adaptersFactory, eResource); return ownedPhysicalLinks_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.PhysicalLinkCategory> */Object ownedPhysicalLinkCategories_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.cs.PhysicalLinkCategory> */Object getOwnedPhysicalLinkCategories() { if (ownedPhysicalLinkCategories_ == null) ownedPhysicalLinkCategories_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPhysicalLinkCategories(), adaptersFactory, eResource); return ownedPhysicalLinkCategories_; } @Override public void destroy() { adaptee.destroy(); } @Override public String getFullLabel() { return adaptee.getFullLabel(); } @Override public String getLabel() { return adaptee.getLabel(); } @Override public boolean hasUnnamedLabel() { return adaptee.hasUnnamedLabel(); } @Override public boolean isDecomposed() { return adaptee.isDecomposed(); } protected final static String ID_EDEFAULT = null; protected final static String SID_EDEFAULT = null; protected final static String NAME_EDEFAULT = null; protected final static boolean VISIBLE_IN_DOC_EDEFAULT = true; protected final static boolean VISIBLE_IN_LM_EDEFAULT = true; protected final static String SUMMARY_EDEFAULT = null; protected final static String DESCRIPTION_EDEFAULT = null; protected final static String REVIEW_EDEFAULT = null; protected final static boolean ABSTRACT_EDEFAULT = false; @Override public EClass eClass() { return org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.eINSTANCE.getLogicalContext(); } @Override public Object eGet(final int featureID, final boolean resolve, final boolean coreType) { switch (featureID) { case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_EXTENSIONS: return getOwnedExtensions(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ID: return getId(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SID: return getSid(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONSTRAINTS: return getConstraints(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_CONSTRAINTS: return getOwnedConstraints(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__NAME: return getName(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ABSTRACT_TYPED_ELEMENTS: return getAbstractTypedElements(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__INCOMING_TRACES: return getIncomingTraces(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OUTGOING_TRACES: return getOutgoingTraces(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__VISIBLE_IN_DOC: return isVisibleInDoc() ? Boolean.TRUE : Boolean.FALSE; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__VISIBLE_IN_LM: return isVisibleInLM() ? Boolean.TRUE : Boolean.FALSE; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUMMARY: return getSummary(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__DESCRIPTION: return getDescription(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__REVIEW: return getReview(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PROPERTY_VALUES: return getOwnedPropertyValues(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_ENUMERATION_PROPERTY_TYPES: return getOwnedEnumerationPropertyTypes(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__APPLIED_PROPERTY_VALUES: return getAppliedPropertyValues(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PROPERTY_VALUE_GROUPS: return getOwnedPropertyValueGroups(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__APPLIED_PROPERTY_VALUE_GROUPS: return getAppliedPropertyValueGroups(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__STATUS: return getStatus(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__FEATURES: return getFeatures(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__APPLIED_REQUIREMENTS: return getAppliedRequirements(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_TRACES: return getOwnedTraces(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_GENERIC_TRACES: return getContainedGenericTraces(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_REQUIREMENTS_TRACES: return getContainedRequirementsTraces(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__NAMING_RULES: return getNamingRules(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__TYPED_ELEMENTS: return getTypedElements(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_FUNCTIONAL_ALLOCATION: return getOwnedFunctionalAllocation(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_COMPONENT_EXCHANGES: return getOwnedComponentExchanges(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_COMPONENT_EXCHANGE_CATEGORIES: return getOwnedComponentExchangeCategories(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__FUNCTIONAL_ALLOCATIONS: return getFunctionalAllocations(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ALLOCATED_FUNCTIONS: return getAllocatedFunctions(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__IN_EXCHANGE_LINKS: return getInExchangeLinks(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OUT_EXCHANGE_LINKS: return getOutExchangeLinks(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_ABSTRACT_CAPABILITY_PKG: return getOwnedAbstractCapabilityPkg(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_PKG: return getOwnedInterfacePkg(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_DATA_PKG: return getOwnedDataPkg(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_STATE_MACHINES: return getOwnedStateMachines(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ABSTRACT: return isAbstract() ? Boolean.TRUE : Boolean.FALSE; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_GENERALIZATIONS: return getOwnedGeneralizations(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUPER_GENERALIZATIONS: return getSuperGeneralizations(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUB_GENERALIZATIONS: return getSubGeneralizations(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUPER: return getSuper(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUB: return getSub(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_FEATURES: return getOwnedFeatures(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_PROPERTIES: return getContainedProperties(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PARTITIONS: return getOwnedPartitions(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__REPRESENTING_PARTITIONS: return getRepresentingPartitions(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_ALLOCATIONS: return getOwnedInterfaceAllocations(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__PROVISIONED_INTERFACE_ALLOCATIONS: return getProvisionedInterfaceAllocations(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ALLOCATED_INTERFACES: return getAllocatedInterfaces(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_COMMUNICATION_LINKS: return getOwnedCommunicationLinks(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__PRODUCE: return getProduce(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONSUME: return getConsume(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SEND: return getSend(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__RECEIVE: return getReceive(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CALL: return getCall(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__EXECUTE: return getExecute(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__WRITE: return getWrite(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ACCESS: return getAccess(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ACQUIRE: return getAcquire(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__TRANSMIT: return getTransmit(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_USES: return getOwnedInterfaceUses(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__USED_INTERFACE_LINKS: return getUsedInterfaceLinks(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__USED_INTERFACES: return getUsedInterfaces(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_IMPLEMENTATIONS: return getOwnedInterfaceImplementations(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__IMPLEMENTED_INTERFACE_LINKS: return getImplementedInterfaceLinks(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__IMPLEMENTED_INTERFACES: return getImplementedInterfaces(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__PROVISIONED_COMPONENT_ALLOCATIONS: return getProvisionedComponentAllocations(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__PROVISIONING_COMPONENT_ALLOCATIONS: return getProvisioningComponentAllocations(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ALLOCATED_COMPONENTS: return getAllocatedComponents(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ALLOCATING_COMPONENTS: return getAllocatingComponents(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__PROVIDED_INTERFACES: return getProvidedInterfaces(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__REQUIRED_INTERFACES: return getRequiredInterfaces(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_COMPONENT_PORTS: return getContainedComponentPorts(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_PARTS: return getContainedParts(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_PHYSICAL_PORTS: return getContainedPhysicalPorts(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PHYSICAL_PATH: return getOwnedPhysicalPath(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PHYSICAL_LINKS: return getOwnedPhysicalLinks(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PHYSICAL_LINK_CATEGORIES: return getOwnedPhysicalLinkCategories(); } return super.eGet(featureID, resolve, coreType); } @Override public boolean eIsSet(final int featureID) { switch (featureID) { case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_EXTENSIONS: return getOwnedExtensions() != null && !getOwnedExtensions().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ID: return getId() != ID_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SID: return getSid() != SID_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONSTRAINTS: return getConstraints() != null && !getConstraints().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_CONSTRAINTS: return getOwnedConstraints() != null && !getOwnedConstraints().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__NAME: return getName() != NAME_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ABSTRACT_TYPED_ELEMENTS: return getAbstractTypedElements() != null && !getAbstractTypedElements().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__INCOMING_TRACES: return getIncomingTraces() != null && !getIncomingTraces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OUTGOING_TRACES: return getOutgoingTraces() != null && !getOutgoingTraces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__VISIBLE_IN_DOC: return isVisibleInDoc() != VISIBLE_IN_DOC_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__VISIBLE_IN_LM: return isVisibleInLM() != VISIBLE_IN_LM_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUMMARY: return getSummary() != SUMMARY_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__DESCRIPTION: return getDescription() != DESCRIPTION_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__REVIEW: return getReview() != REVIEW_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PROPERTY_VALUES: return getOwnedPropertyValues() != null && !getOwnedPropertyValues().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_ENUMERATION_PROPERTY_TYPES: return getOwnedEnumerationPropertyTypes() != null && !getOwnedEnumerationPropertyTypes().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__APPLIED_PROPERTY_VALUES: return getAppliedPropertyValues() != null && !getAppliedPropertyValues().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PROPERTY_VALUE_GROUPS: return getOwnedPropertyValueGroups() != null && !getOwnedPropertyValueGroups().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__APPLIED_PROPERTY_VALUE_GROUPS: return getAppliedPropertyValueGroups() != null && !getAppliedPropertyValueGroups().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__STATUS: return getStatus() != null; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__FEATURES: return getFeatures() != null && !getFeatures().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__APPLIED_REQUIREMENTS: return getAppliedRequirements() != null && !getAppliedRequirements().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_TRACES: return getOwnedTraces() != null && !getOwnedTraces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_GENERIC_TRACES: return getContainedGenericTraces() != null && !getContainedGenericTraces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_REQUIREMENTS_TRACES: return getContainedRequirementsTraces() != null && !getContainedRequirementsTraces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__NAMING_RULES: return getNamingRules() != null && !getNamingRules().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__TYPED_ELEMENTS: return getTypedElements() != null && !getTypedElements().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_FUNCTIONAL_ALLOCATION: return getOwnedFunctionalAllocation() != null && !getOwnedFunctionalAllocation().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_COMPONENT_EXCHANGES: return getOwnedComponentExchanges() != null && !getOwnedComponentExchanges().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_COMPONENT_EXCHANGE_CATEGORIES: return getOwnedComponentExchangeCategories() != null && !getOwnedComponentExchangeCategories().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__FUNCTIONAL_ALLOCATIONS: return getFunctionalAllocations() != null && !getFunctionalAllocations().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ALLOCATED_FUNCTIONS: return getAllocatedFunctions() != null && !getAllocatedFunctions().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__IN_EXCHANGE_LINKS: return getInExchangeLinks() != null && !getInExchangeLinks().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OUT_EXCHANGE_LINKS: return getOutExchangeLinks() != null && !getOutExchangeLinks().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_ABSTRACT_CAPABILITY_PKG: return getOwnedAbstractCapabilityPkg() != null; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_PKG: return getOwnedInterfacePkg() != null; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_DATA_PKG: return getOwnedDataPkg() != null; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_STATE_MACHINES: return getOwnedStateMachines() != null && !getOwnedStateMachines().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ABSTRACT: return isAbstract() != ABSTRACT_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_GENERALIZATIONS: return getOwnedGeneralizations() != null && !getOwnedGeneralizations().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUPER_GENERALIZATIONS: return getSuperGeneralizations() != null && !getSuperGeneralizations().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUB_GENERALIZATIONS: return getSubGeneralizations() != null && !getSubGeneralizations().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUPER: return getSuper() != null && !getSuper().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUB: return getSub() != null && !getSub().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_FEATURES: return getOwnedFeatures() != null && !getOwnedFeatures().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_PROPERTIES: return getContainedProperties() != null && !getContainedProperties().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PARTITIONS: return getOwnedPartitions() != null && !getOwnedPartitions().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__REPRESENTING_PARTITIONS: return getRepresentingPartitions() != null && !getRepresentingPartitions().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_ALLOCATIONS: return getOwnedInterfaceAllocations() != null && !getOwnedInterfaceAllocations().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__PROVISIONED_INTERFACE_ALLOCATIONS: return getProvisionedInterfaceAllocations() != null && !getProvisionedInterfaceAllocations().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ALLOCATED_INTERFACES: return getAllocatedInterfaces() != null && !getAllocatedInterfaces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_COMMUNICATION_LINKS: return getOwnedCommunicationLinks() != null && !getOwnedCommunicationLinks().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__PRODUCE: return getProduce() != null && !getProduce().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONSUME: return getConsume() != null && !getConsume().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SEND: return getSend() != null && !getSend().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__RECEIVE: return getReceive() != null && !getReceive().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CALL: return getCall() != null && !getCall().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__EXECUTE: return getExecute() != null && !getExecute().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__WRITE: return getWrite() != null && !getWrite().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ACCESS: return getAccess() != null && !getAccess().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ACQUIRE: return getAcquire() != null && !getAcquire().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__TRANSMIT: return getTransmit() != null && !getTransmit().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_USES: return getOwnedInterfaceUses() != null && !getOwnedInterfaceUses().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__USED_INTERFACE_LINKS: return getUsedInterfaceLinks() != null && !getUsedInterfaceLinks().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__USED_INTERFACES: return getUsedInterfaces() != null && !getUsedInterfaces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_IMPLEMENTATIONS: return getOwnedInterfaceImplementations() != null && !getOwnedInterfaceImplementations().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__IMPLEMENTED_INTERFACE_LINKS: return getImplementedInterfaceLinks() != null && !getImplementedInterfaceLinks().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__IMPLEMENTED_INTERFACES: return getImplementedInterfaces() != null && !getImplementedInterfaces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__PROVISIONED_COMPONENT_ALLOCATIONS: return getProvisionedComponentAllocations() != null && !getProvisionedComponentAllocations().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__PROVISIONING_COMPONENT_ALLOCATIONS: return getProvisioningComponentAllocations() != null && !getProvisioningComponentAllocations().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ALLOCATED_COMPONENTS: return getAllocatedComponents() != null && !getAllocatedComponents().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ALLOCATING_COMPONENTS: return getAllocatingComponents() != null && !getAllocatingComponents().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__PROVIDED_INTERFACES: return getProvidedInterfaces() != null && !getProvidedInterfaces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__REQUIRED_INTERFACES: return getRequiredInterfaces() != null && !getRequiredInterfaces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_COMPONENT_PORTS: return getContainedComponentPorts() != null && !getContainedComponentPorts().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_PARTS: return getContainedParts() != null && !getContainedParts().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__CONTAINED_PHYSICAL_PORTS: return getContainedPhysicalPorts() != null && !getContainedPhysicalPorts().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PHYSICAL_PATH: return getOwnedPhysicalPath() != null && !getOwnedPhysicalPath().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PHYSICAL_LINKS: return getOwnedPhysicalLinks() != null && !getOwnedPhysicalLinks().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PHYSICAL_LINK_CATEGORIES: return getOwnedPhysicalLinkCategories() != null && !getOwnedPhysicalLinkCategories().isEmpty(); } return super.eIsSet(featureID); } @Override public void eSet(final int featureID, final Object newValue) { switch (featureID) { case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_EXTENSIONS: getOwnedExtensions().clear(); getOwnedExtensions().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ID: setId( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SID: setSid( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_CONSTRAINTS: getOwnedConstraints().clear(); getOwnedConstraints().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__NAME: setName( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__VISIBLE_IN_DOC: setVisibleInDoc(((java.lang.Boolean) newValue).booleanValue()); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__VISIBLE_IN_LM: setVisibleInLM(((java.lang.Boolean) newValue).booleanValue()); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__SUMMARY: setSummary( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__DESCRIPTION: setDescription( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__REVIEW: setReview( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PROPERTY_VALUES: getOwnedPropertyValues().clear(); getOwnedPropertyValues().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_ENUMERATION_PROPERTY_TYPES: getOwnedEnumerationPropertyTypes().clear(); getOwnedEnumerationPropertyTypes().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__APPLIED_PROPERTY_VALUES: getAppliedPropertyValues().clear(); getAppliedPropertyValues().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PROPERTY_VALUE_GROUPS: getOwnedPropertyValueGroups().clear(); getOwnedPropertyValueGroups().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__APPLIED_PROPERTY_VALUE_GROUPS: getAppliedPropertyValueGroups().clear(); getAppliedPropertyValueGroups().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__STATUS: setStatus( (org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__FEATURES: getFeatures().clear(); getFeatures().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_TRACES: getOwnedTraces().clear(); getOwnedTraces().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__NAMING_RULES: getNamingRules().clear(); getNamingRules().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_FUNCTIONAL_ALLOCATION: getOwnedFunctionalAllocation().clear(); getOwnedFunctionalAllocation().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_COMPONENT_EXCHANGES: getOwnedComponentExchanges().clear(); getOwnedComponentExchanges().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_COMPONENT_EXCHANGE_CATEGORIES: getOwnedComponentExchangeCategories().clear(); getOwnedComponentExchangeCategories().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__IN_EXCHANGE_LINKS: getInExchangeLinks().clear(); getInExchangeLinks().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OUT_EXCHANGE_LINKS: getOutExchangeLinks().clear(); getOutExchangeLinks().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_ABSTRACT_CAPABILITY_PKG: setOwnedAbstractCapabilityPkg( (org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.AbstractCapabilityPkg) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_PKG: setOwnedInterfacePkg( (org.gemoc.scenario.xdsml.functionscenariomt.cs.InterfacePkg) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_DATA_PKG: setOwnedDataPkg( (org.gemoc.scenario.xdsml.functionscenariomt.information.DataPkg) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_STATE_MACHINES: getOwnedStateMachines().clear(); getOwnedStateMachines().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__ABSTRACT: setAbstract(((java.lang.Boolean) newValue).booleanValue()); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_GENERALIZATIONS: getOwnedGeneralizations().clear(); getOwnedGeneralizations().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_FEATURES: getOwnedFeatures().clear(); getOwnedFeatures().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_ALLOCATIONS: getOwnedInterfaceAllocations().clear(); getOwnedInterfaceAllocations().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_COMMUNICATION_LINKS: getOwnedCommunicationLinks().clear(); getOwnedCommunicationLinks().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_USES: getOwnedInterfaceUses().clear(); getOwnedInterfaceUses().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_INTERFACE_IMPLEMENTATIONS: getOwnedInterfaceImplementations().clear(); getOwnedInterfaceImplementations().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PHYSICAL_PATH: getOwnedPhysicalPath().clear(); getOwnedPhysicalPath().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PHYSICAL_LINKS: getOwnedPhysicalLinks().clear(); getOwnedPhysicalLinks().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.la.LaPackage.LOGICAL_CONTEXT__OWNED_PHYSICAL_LINK_CATEGORIES: getOwnedPhysicalLinkCategories().clear(); getOwnedPhysicalLinkCategories().addAll((Collection) newValue); return; } super.eSet(featureID, newValue); } }
epl-1.0
DavidGutknecht/elexis-3-base
bundles/ch.elexis.docbox.ws.client/src-gen/org/hl7/v3/RoleClassInvestigationSubject.java
869
package org.hl7.v3; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for RoleClassInvestigationSubject. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="RoleClassInvestigationSubject"> * &lt;restriction base="{urn:hl7-org:v3}cs"> * &lt;enumeration value="INVSBJ"/> * &lt;enumeration value="CASESBJ"/> * &lt;enumeration value="RESBJ"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "RoleClassInvestigationSubject") @XmlEnum public enum RoleClassInvestigationSubject { INVSBJ, CASESBJ, RESBJ; public String value() { return name(); } public static RoleClassInvestigationSubject fromValue(String v) { return valueOf(v); } }
epl-1.0
mark-christiaens/EMF-Statistics-View
EMF-Statistics-View/src/com/sigasi/emfstats/RefreshJob.java
2887
/******************************************************************************* * Copyright (c) 2011 Sigasi N.V. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Sigasi N.V.: Mark Christiaens - initial API and implementation *******************************************************************************/ package com.sigasi.emfstats; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.util.concurrent.IUnitOfWork; import com.google.common.collect.Maps; public class RefreshJob extends Job { private final class RefreshWork implements IUnitOfWork<Map<EClass, EClassStats>, XtextResource> { private final IProgressMonitor monitor; private RefreshWork(IProgressMonitor monitor) { this.monitor = monitor; } public Map<EClass, EClassStats> exec(XtextResource resource) throws Exception { HashMap<EClass, EClassStats> stats = Maps.newHashMap(); if (resource != null) { TreeIterator<EObject> allContents = resource.getAllContents(); long count = 0; while (allContents.hasNext()) { count++; if (count % 10000 == 0 && monitor.isCanceled()) { return stats; } EObject next = allContents.next(); updateStats(stats, next); } } return stats; } private void updateStats(HashMap<EClass, EClassStats> stats, EObject object) { EClass c = object.eClass(); EClassStats counter = null; if (!stats.containsKey(c)) { counter = new EClassStats(c); stats.put(c, counter); } else { counter = stats.get(c); } counter.increment(); } } private StatsPage emfStatsView; public RefreshJob(StatsPage emfStatsView) { super("Refreshing EMF stats"); this.emfStatsView = emfStatsView; } @Override protected IStatus run(IProgressMonitor monitor) { try { Map<EClass, EClassStats> newEmfStats = refreshEmfStats(monitor); if (!monitor.isCanceled()) { emfStatsView.setStats(newEmfStats); } return Status.OK_STATUS; } catch (Throwable t) { return new Status(IStatus.ERROR, "com.sigasi.emfstats", "Error refreshing EMF stats", t); } } protected Map<EClass, EClassStats> refreshEmfStats(final IProgressMonitor monitor) { Map<EClass, EClassStats> newEmfStats = emfStatsView.getXtextDocument() .readOnly(new RefreshWork(monitor)); return newEmfStats; } }
epl-1.0
intuit/Tank
tank_common/src/test/java/com/intuit/tank/util/TimeFormatUtilTest.java
2241
/** * Copyright 2011 Intuit Inc. All Rights Reserved */ package com.intuit.tank.util; /* * #%L * Common * %% * Copyright (C) 2011 - 2015 Intuit Inc. * %% * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * #L% */ import com.intuit.tank.test.TestGroups; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; /** * TimeUtilTest * * @author dangleton * */ public class TimeFormatUtilTest { static Stream<Arguments> data() { return Stream.of( Arguments.of( 60, "00:01:00" ), Arguments.of( 5, "00:00:05" ), Arguments.of( 65, "00:01:05" ), Arguments.of( 3665, "01:01:05" ), Arguments.of( 3600, "01:00:00" ) ); } @ParameterizedTest @Tag(TestGroups.FUNCTIONAL) @MethodSource("data") public void testFormatTime(int seconds, String expected) throws Exception { String result = TimeFormatUtil.formatTime(seconds); assertEquals(expected, result); } /** * Run the String formatTime(int) method test. * * @throws Exception * * @generatedBy CodePro at 9/10/14 10:36 AM */ @Test public void testFormatTime_1() throws Exception { int numSeconds = 1; String result = TimeFormatUtil.formatTime(numSeconds); assertEquals("00:00:01", result); } /** * Run the String getFormattedDuration(int) method test. * * @throws Exception * * @generatedBy CodePro at 9/10/14 10:36 AM */ @Test public void testGetFormattedDuration_1() throws Exception { int simTimeSeconds = 1; String result = TimeFormatUtil.getFormattedDuration(simTimeSeconds); assertEquals("00:00:01", result); } }
epl-1.0
xen-0/dawnsci
org.eclipse.dawnsci.nexus/autogen/org/eclipse/dawnsci/nexus/impl/NXparametersImpl.java
2188
/*- ******************************************************************************* * Copyright (c) 2015 Diamond Light Source Ltd. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * This file was auto-generated from the NXDL XML definition. * Generated at: 2016-09-28T15:24:07.968+01:00 *******************************************************************************/ package org.eclipse.dawnsci.nexus.impl; import java.util.Set; import java.util.EnumSet; import org.eclipse.dawnsci.analysis.api.tree.DataNode; import org.eclipse.january.dataset.IDataset; import org.eclipse.dawnsci.nexus.*; /** * Container for parameters, usually used in processing or analysis. * * @version 1.0 */ public class NXparametersImpl extends NXobjectImpl implements NXparameters { private static final long serialVersionUID = 1L; // no state in this class, so always compatible public static final Set<NexusBaseClass> PERMITTED_CHILD_GROUP_CLASSES = EnumSet.noneOf(NexusBaseClass.class); public NXparametersImpl() { super(); } public NXparametersImpl(final long oid) { super(oid); } @Override public Class<? extends NXobject> getNXclass() { return NXparameters.class; } @Override public NexusBaseClass getNexusBaseClass() { return NexusBaseClass.NX_PARAMETERS; } @Override public Set<NexusBaseClass> getPermittedChildGroupClasses() { return PERMITTED_CHILD_GROUP_CLASSES; } @Override public IDataset getTerm() { return getDataset(NX_TERM); } @Override public String getTermScalar() { return getString(NX_TERM); } @Override public DataNode setTerm(IDataset term) { return setDataset(NX_TERM, term); } @Override public DataNode setTermScalar(String term) { return setString(NX_TERM, term); } @Override public String getTermAttributeUnits() { return getAttrString(NX_TERM, NX_TERM_ATTRIBUTE_UNITS); } @Override public void setTermAttributeUnits(String units) { setAttribute(NX_TERM, NX_TERM_ATTRIBUTE_UNITS, units); } }
epl-1.0
kenijey/harshencastle
src/main/java/kenijey/harshenuniverse/items/HarshenSoulIngot.java
242
package kenijey.harshenuniverse.items; import net.minecraft.item.Item; public class HarshenSoulIngot extends Item { public HarshenSoulIngot() { setUnlocalizedName("harshen_soul_ingot"); setRegistryName("harshen_soul_ingot"); } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
utils/eclipselink.utils.workbench/mappingsplugin/source/org/eclipse/persistence/tools/workbench/mappingsplugin/ui/mapping/xml/MapAsAnyAttributeAction.java
2408
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.tools.workbench.mappingsplugin.ui.mapping.xml; import org.eclipse.persistence.tools.workbench.framework.context.WorkbenchContext; import org.eclipse.persistence.tools.workbench.mappingsmodel.descriptor.MWMappingDescriptor; import org.eclipse.persistence.tools.workbench.mappingsmodel.descriptor.xml.MWOXDescriptor; import org.eclipse.persistence.tools.workbench.mappingsmodel.mapping.MWMapping; import org.eclipse.persistence.tools.workbench.mappingsmodel.mapping.xml.MWAnyAttributeMapping; import org.eclipse.persistence.tools.workbench.mappingsmodel.meta.MWClassAttribute; import org.eclipse.persistence.tools.workbench.mappingsplugin.ui.mapping.ChangeMappingTypeAction; public final class MapAsAnyAttributeAction extends ChangeMappingTypeAction { public MapAsAnyAttributeAction(WorkbenchContext context) { super(context); } @Override protected void initialize() { super.initialize(); this.initializeIcon("mapping.anyAttribute"); this.initializeText("MAP_AS_ANY_ATTRIBUTE_ACTION"); this.initializeMnemonic("MAP_AS_ANY_ATTRIBUTE_ACTION"); this.initializeToolTipText("MAP_AS_ANY_ATTRIBUTE_ACTION.toolTipText"); } // ************ ChangeMappingTypeAction implementation *********** @Override protected MWMapping morphMapping(MWMapping mapping) { return mapping.asMWAnyAttributeMapping(); } @Override protected MWMapping addMapping(MWMappingDescriptor descriptor, MWClassAttribute attribute) { return ((MWOXDescriptor) descriptor).addAnyAttributeMapping(attribute); } @Override protected Class mappingClass() { return MWAnyAttributeMapping.class; } }
epl-1.0
dblock/waffle
Source/JNA/waffle-tests/src/main/java/waffle/mock/MockWindowsIdentity.java
2071
/** * Waffle (https://github.com/Waffle/waffle) * * Copyright (c) 2010-2018 Application Security, Inc. * * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-v10.html. * * Contributors: Application Security, Inc. */ package waffle.mock; import java.util.ArrayList; import java.util.List; import waffle.windows.auth.IWindowsAccount; import waffle.windows.auth.IWindowsIdentity; import waffle.windows.auth.IWindowsImpersonationContext; /** * A Mock windows identity. * * @author dblock[at]dblock[dot]org */ public class MockWindowsIdentity implements IWindowsIdentity { /** The fqn. */ private final String fqn; /** The groups. */ private final List<String> groups; /** * Instantiates a new mock windows identity. * * @param newFqn * the new fqn * @param newGroups * the new groups */ public MockWindowsIdentity(final String newFqn, final List<String> newGroups) { this.fqn = newFqn; this.groups = newGroups; } @Override public String getFqn() { return this.fqn; } @Override public IWindowsAccount[] getGroups() { final List<MockWindowsAccount> groupsList = new ArrayList<>(); for (final String group : this.groups) { groupsList.add(new MockWindowsAccount(group)); } return groupsList.toArray(new IWindowsAccount[0]); } @Override public byte[] getSid() { return new byte[0]; } @Override public String getSidString() { return "S-" + this.fqn.hashCode(); } @Override public void dispose() { // Do Nothing } @Override public boolean isGuest() { return "Guest".equals(this.fqn); } @Override public IWindowsImpersonationContext impersonate() { return new MockWindowsImpersonationContext(); } }
epl-1.0
maraszm/openhab
bundles/binding/org.openhab.binding.ekozefir/src/main/java/org/openhab/binding/ekozefir/internal/ResponseBus.java
988
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.ekozefir.internal; import org.openhab.binding.ekozefir.response.Response; import org.openhab.binding.ekozefir.response.ResponseListener; /** * Interface for posting commands to event bus from ahu. * * @author Michal Marasz * @since 1.6.0 */ public interface ResponseBus { /** * Post response to openhab. * * @param event response from ahu */ void post(Response event); /** * Register listener of response. * * @param listener of response */ void register(ResponseListener listener); /** * Unregister listener of response * * @param listener response listener */ void unregister(ResponseListener listener); }
epl-1.0
debrief/debrief
org.mwc.debrief.pepys/src/main/java/org/mwc/debrief/pepys/model/db/annotation/Transient.java
311
package org.mwc.debrief.pepys.model.db.annotation; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIME) @Target(FIELD) public @interface Transient { }
epl-1.0
Corona-IDE/corona-ide
corona-ide-core-api/src/main/java/com/coronaide/core/service/IWorkspaceService.java
956
/******************************************************************************* * Copyright (c) Nov 17, 2016 Corona IDE. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * romeara - initial API and implementation and/or initial documentation *******************************************************************************/ package com.coronaide.core.service; import com.coronaide.core.model.Workspace; /** * Allows retrieval of development environment information * * @author romeara * @since 0.1 */ public interface IWorkspaceService { /** * @return A representation of the workspace the application is currently using as its development environment * @since 0.1 */ Workspace getActiveWorkspace(); }
epl-1.0
xiaohanz/softcontroller
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/ModuleFactoriesResolver.java
945
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.config.manager.impl.factoriesresolver; import java.util.List; import org.opendaylight.controller.config.spi.ModuleFactory; /** * {@link org.opendaylight.controller.config.manager.impl.ConfigTransactionControllerImpl} * receives list of factories using this interface. For testing, this could be * implemented as hard coded list of objects, for OSGi this would look for all * services in OSGi Service Registry are registered under * {@link org.opendaylight.controller.config.spi.ModuleFactory} name. */ public interface ModuleFactoriesResolver { List<ModuleFactory> getAllFactories(); }
epl-1.0
cbaerikebc/kapua
service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupDAO.java
4640
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech - initial API and implementation * *******************************************************************************/ package org.eclipse.kapua.service.authorization.group.shiro; import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.EntityManager; import org.eclipse.kapua.commons.service.internal.ServiceDAO; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.group.Group; import org.eclipse.kapua.service.authorization.group.GroupCreator; import org.eclipse.kapua.service.authorization.group.GroupListResult; import org.eclipse.kapua.service.authorization.group.GroupQuery; /** * {@link Group} DAO * * @since 1.0.0 */ public class GroupDAO extends ServiceDAO { /** * Creates and returns new {@link Group} * * @param em * The {@link EntityManager} that holds the transaction. * @param creator * The {@link GroupCreator} object from which create the new {@link Group}. * @return The newly created {@link Group}. * @throws KapuaException * @since 1.0.0 */ public static Group create(EntityManager em, GroupCreator creator) throws KapuaException { Group group = new GroupImpl(creator.getScopeId()); group.setName(creator.getName()); return ServiceDAO.create(em, group); } /** * Updates and returns the updated {@link Group} * * @param em * The {@link EntityManager} that holds the transaction. * @param group * The {@link Group} to update * @return The updated {@link Group}. * @throws KapuaEntityNotFoundException * If {@link Group} is not found. */ public static Group update(EntityManager em, Group group) throws KapuaEntityNotFoundException { GroupImpl groupImpl = (GroupImpl) group; return ServiceDAO.update(em, GroupImpl.class, groupImpl); } /** * Finds the {@link Group} by {@link Group} identifier * * @param em * The {@link EntityManager} that holds the transaction. * @param groupId * The {@link Group} id to search. * @return The found {@link Group} or {@code null} if not found. * @since 1.0.0 */ public static Group find(EntityManager em, KapuaId groupId) { return em.find(GroupImpl.class, groupId); } /** * Deletes the {@link Group} by {@link Group} identifier * * @param em * The {@link EntityManager} that holds the transaction. * @param groupId * The {@link Group} id to delete. * @throws KapuaEntityNotFoundException * If {@link Group} is not found. * @since 1.0.0 */ public static void delete(EntityManager em, KapuaId groupId) throws KapuaEntityNotFoundException { ServiceDAO.delete(em, GroupImpl.class, groupId); } /** * Returns the {@link Group} list matching the provided query. * * @param em * The {@link EntityManager} that holds the transaction. * @param groupQuery * The {@link GroupQuery} used to filter results. * @return The list of {@link Group}s that matches the given query. * @throws KapuaException * @since 1.0.0 */ public static GroupListResult query(EntityManager em, KapuaQuery<Group> groupQuery) throws KapuaException { return ServiceDAO.query(em, Group.class, GroupImpl.class, new GroupListResultImpl(), groupQuery); } /** * Return the {@link Group} count matching the provided query * * @param em * The {@link EntityManager} that holds the transaction. * @param groupQuery * The {@link GroupQuery} used to filter results. * @return * @throws KapuaException * @since 1.0.0 */ public static long count(EntityManager em, KapuaQuery<Group> groupQuery) throws KapuaException { return ServiceDAO.count(em, Group.class, GroupImpl.class, groupQuery); } }
epl-1.0
vertig/tempo
security/src/main/java/org/intalio/tempo/security/ldap/LDAPRBACProvider.java
25966
/** * Copyright (C) 2003, Intalio Inc. * * The program(s) herein may be used and/or copied only with the * written permission of Intalio Inc. or in accordance with the terms * and conditions stipulated in the agreement/contract under which the * program(s) have been supplied. * * $Id: LDAPRBACProvider.java,v 1.13 2005/02/24 18:14:12 boisvert Exp $ */ package org.intalio.tempo.security.ldap; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import org.intalio.tempo.security.Property; import org.intalio.tempo.security.rbac.ObjectNotFoundException; import org.intalio.tempo.security.rbac.RBACAdmin; import org.intalio.tempo.security.rbac.RBACException; import org.intalio.tempo.security.rbac.RBACQuery; import org.intalio.tempo.security.rbac.RBACRuntime; import org.intalio.tempo.security.rbac.RoleNotFoundException; import org.intalio.tempo.security.rbac.UserNotFoundException; import org.intalio.tempo.security.rbac.provider.RBACProvider; import org.intalio.tempo.security.util.IdentifierUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * LDAP RBAC Provider * * @author <a href="http://www.intalio.com">&copy; Intalio Inc.</a> */ class LDAPRBACProvider implements RBACProvider, LDAPProperties { final static Logger LOG = LoggerFactory.getLogger("tempo.security"); private final static String[] EMPTY_STRINGS = new String[0]; private String _realm; private LDAPRBACQuery _query; private LDAPQueryEngine _engine; /** * Constructor * */ public LDAPRBACProvider(String realm, LDAPQueryEngine engine, String baseDN) { super(); _realm = realm; _engine = engine; } /** * @param config * @throws RBACException */ public void initialize(Object config) throws RBACException { if ( !(config instanceof Map ) ) throw new IllegalArgumentException("Configuration is expected to be a Map"); _query = new LDAPRBACQuery((Map)config); } /** * @throws RBACException */ public String getName() throws RBACException { return "LDAP RBAC Provider"; } /** * @see org.intalio.tempo.security.rbac.provider.RBACProvider#getAdmin() */ public RBACAdmin getAdmin() throws RBACException { throw new RuntimeException("Method not implemented"); } /** * @see org.intalio.tempo.security.rbac.provider.RBACProvider#getQuery() */ public RBACQuery getQuery() throws RBACException { return _query; } /** * @see org.intalio.tempo.security.rbac.provider.RBACProvider#getRuntime() */ public RBACRuntime getRuntime() throws RBACException { throw new RuntimeException("Method not implemented"); } public void dispose() throws RBACException { return; } static Map<String,String> readProperties(String keyRoot, Map source) throws IllegalArgumentException { Map<String,String> result = null; for (int i=0; true; i++) { String key = keyRoot+'.'+i; String value = (String)source.get(key); if (value==null) break; int colon = value.indexOf(':'); String front, back; if (colon==-1 ) { front = back = value; } else if ( colon==0 ) { front = value.substring(1); back = front; } else if ( colon==value.length()-1 ) { front = value.substring(0, colon); back = front; } else { front = value.substring(0, colon).trim(); back = value.substring(colon+1).trim(); } if (front.length()==0 || back.length()==0) throw new IllegalArgumentException("Format is not reconized! key: "+key+" value: "+value); if (result==null) result = new TreeMap<String,String>(); result.put(back, front); } return result; } static String getNonNull(String key, Map map) throws IllegalArgumentException { Object res = map.get(key); if (res!=null) return res.toString(); StringBuffer sb = new StringBuffer(); sb.append(key); sb.append(" cannot be null!"); throw new IllegalArgumentException(sb.toString()); } private String[] prefix( Collection<String> col ) { String[] result = new String[col.size()]; col.toArray(result); return prefix(result); } private String[] prefix( String[] result ) { for (int i = 0; i < result.length; i++) { result[i] = _realm+"\\"+result[i]; } return result; } class LDAPRBACQuery implements RBACQuery, LDAPProperties { private String _permObjects; private String _permId; private String _permBase; private String _rolePerms; private String _permRoles; private String _roleBase; private String _roleId; private String _userBase; private String _userId; private String _userRoles; private Map<String,String> _userProp; private String _userAllroles; private String _roleUsers; private Map<String,String> _roleProp; private String _roleAscen; private String _roleDescen; /** * Constructor * @param map contains all configuration */ LDAPRBACQuery( Map map ) { _roleBase = getNonNull(SECURITY_LDAP_ROLE_BASE, map); _roleId = getNonNull(SECURITY_LDAP_ROLE_ID, map); _userBase = getNonNull(SECURITY_LDAP_USER_BASE, map); _userId = getNonNull(SECURITY_LDAP_USER_ID, map); _userRoles = (String)map.get(SECURITY_LDAP_USER_ROLES); _roleUsers = (String)map.get(SECURITY_LDAP_ROLE_USERS); _userAllroles = (String)map.get(SECURITY_LDAP_USER_ALLROLES); if (_userRoles==null && _roleUsers==null) { StringBuffer sb = new StringBuffer(); sb.append(SECURITY_LDAP_ROLE_USERS); sb.append(" and "); sb.append(SECURITY_LDAP_USER_ROLES); sb.append(" cannot be both null!"); throw new IllegalArgumentException(sb.toString()); } else if (_userRoles!=null && _roleUsers!=null) { StringBuffer sb = new StringBuffer(); sb.append(SECURITY_LDAP_ROLE_USERS); sb.append(" and "); sb.append(SECURITY_LDAP_USER_ROLES); sb.append(" is mutal exclusive!"); throw new IllegalArgumentException(sb.toString()); } _roleAscen = (String)map.get(SECURITY_LDAP_ROLE_ASCEN); _roleDescen = (String)map.get(SECURITY_LDAP_ROLE_DESCEN); _permId = getNonNull(SECURITY_LDAP_PERM_ID, map); _permBase = getNonNull(SECURITY_LDAP_PERM_BASE, map); _permObjects= getNonNull(SECURITY_LDAP_PERM_OBJECTS, map); _permRoles = (String)map.get(SECURITY_LDAP_PERM_ROLES); _rolePerms = (String)map.get(SECURITY_LDAP_ROLE_PERMS); if (_permRoles==null && _rolePerms==null) { StringBuffer sb = new StringBuffer(); sb.append(SECURITY_LDAP_PERM_ROLES); sb.append(" and "); sb.append(SECURITY_LDAP_ROLE_PERMS); sb.append(" cannot be both null!"); throw new IllegalArgumentException(sb.toString()); } _userProp = readProperties(SECURITY_LDAP_USER_PROP, map); _roleProp = readProperties(SECURITY_LDAP_ROLE_PROP, map); } /** * @see org.intalio.tempo.security.rbac.RBACQuery#assignedUsers(java.lang.String) */ public String[] assignedUsers(String role) throws RoleNotFoundException, RBACException, RemoteException { try { role = IdentifierUtils.stripRealm(role); ArrayList<String> list = new ArrayList<String>(); short found; if (_userRoles!=null) { // foreign key on the user boolean checkRole = true; found = _engine.queryRelations(role, _roleBase, _roleId, _userBase, _userRoles, checkRole, list); } else { // _roleUsers!=null, foreign key on the role found = _engine.queryFilteredFields(role, _roleBase, _roleId, _roleUsers, _userBase, list); } if (found==LDAPQueryEngine.SUBJECT_NOT_FOUND) throw new RoleNotFoundException("Role, "+role+", is not found!"); if (found==LDAPQueryEngine.RELATION_NOT_FOUND) return EMPTY_STRINGS; return prefix(list); } catch ( NameNotFoundException nnfe ) { if (LOG.isInfoEnabled()) LOG.info("Role, "+role+", is not found!"); throw new RoleNotFoundException("Role, "+role+", is not found!", nnfe); } catch ( NamingException ne ) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } /** * @see org.intalio.tempo.security.rbac.RBACQuery#authorizedUsers(java.lang.String) */ public String[] authorizedUsers(String role) throws RoleNotFoundException, RBACException, RemoteException { if (_roleDescen==null && _roleAscen==null) // no inherit role support, same as the "flat" method return assignedUsers(role); role = IdentifierUtils.stripRealm(role); try { // get all sub roles TreeSet<String> list = new TreeSet<String>(); list.add(role); short found; if (_roleAscen!=null) found = _engine.queryInheritRelation(_roleBase, _roleId, _roleAscen, list); else found = _engine.queryInheritReference(_roleBase, _roleId, _roleDescen, list); if (found==LDAPQueryEngine.SUBJECT_NOT_FOUND) throw new RoleNotFoundException("Role, "+role+", is not found!"); if (LOG.isDebugEnabled()) LOG.debug("roles: "+list); TreeSet<String> result = new TreeSet<String>(); if (_userRoles!=null) { // foreign key on the user _engine.queryRelations(list, _roleBase, _roleId, _userBase, _userRoles, result); } else { //if (_roleUsers!=null) // foreign key on the role _engine.queryFilteredFields(list, _roleBase, _roleId, _roleUsers, _userBase, result); } return prefix(result); } catch ( NamingException ne ) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } /** * @see org.intalio.tempo.security.rbac.RBACQuery#assignedRoles(java.lang.String) */ public String[] assignedRoles(String user) throws UserNotFoundException, RBACException, RemoteException { user = IdentifierUtils.stripRealm(user); try { ArrayList<String> list = new ArrayList<String>(); short result; if (_userRoles!=null) { result = _engine.queryFields(user, _userBase, _userId, _userRoles, list); } else { boolean checkUser = true; result = _engine.queryRelations(user, _userBase, _userId, _roleBase, _roleUsers, checkUser, list); } if (result==LDAPQueryEngine.SUBJECT_NOT_FOUND) throw new UserNotFoundException("User, "+user+", is not found!"); if (result==LDAPQueryEngine.RELATION_NOT_FOUND) return EMPTY_STRINGS; return prefix(list); } catch (NamingException ne) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } /** * @see org.intalio.tempo.security.rbac.RBACQuery#authorizedRoles(java.lang.String) */ public String[] authorizedRoles(String user) throws UserNotFoundException, RBACException, RemoteException { if (_roleDescen==null && _roleAscen==null) // no inherit role support, same as the "flat" method return assignedRoles(user); user = IdentifierUtils.stripRealm(user); try { ArrayList<String> list = new ArrayList<String>(); short result; if (_userAllroles!=null) { // server support the shortcut result = _engine.queryFields(user, _userBase, _userId, _userAllroles, list); } else if (_userRoles!=null) { result = _engine.queryFields(user, _userBase, _userId, _userRoles, list); } else { boolean checkUser = true; result = _engine.queryRelations(user, _userBase, _userId, _roleBase, _roleUsers, checkUser, list); } if (result==LDAPQueryEngine.SUBJECT_NOT_FOUND) throw new UserNotFoundException("User '"+user+"' is not found!"); if (result==LDAPQueryEngine.RELATION_NOT_FOUND) return EMPTY_STRINGS; if (result==LDAPQueryEngine.FIELD_NOT_FOUND) return EMPTY_STRINGS; // include all super roles if (_roleAscen!=null) _engine.queryInheritReference(_roleBase, _roleId, _roleAscen, list); else _engine.queryInheritRelation(_roleBase, _roleId, _roleDescen, list); if ( LOG.isDebugEnabled() ) { LOG.debug( "user '" + user + "' authorizedRoles: " + list ); } return prefix(list); } catch (NamingException ne) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } /** * @see org.intalio.tempo.security.rbac.RBACQuery#topRoles(java.lang.String) */ public String[] topRoles( String realm ) throws RBACException, RemoteException { if (!_realm.equals(realm)) throw new RBACException("Unsupported realm, "+realm); try { ArrayList<String> list = new ArrayList<String>(); if (_roleAscen==null&&_roleDescen==null) { // return all roles _engine.queryExtent(_roleBase, _roleId, list); } else if (_roleAscen!=null ) { // record contains no reference of ascendants _engine.queryNoRelation(_roleBase, _roleAscen, list); } else { // warning, operation here is very expensive, we // basically iterate all records of role twice // record contains the reference of ascendants // we find all tops role by sustract all roles by // roles that contains in the descendant list _engine.queryExtent(_roleBase, _roleId, list); TreeSet<String> descen = new TreeSet<String>(); _engine.queryExistRelation(_roleBase, _roleId, _roleDescen, _roleBase, descen); list.removeAll(descen); } return prefix(list); } catch ( NamingException ne ) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } /** */ /* public String[] allRoles( String realm ) throws RBACException, RemoteException { if (!_realm.equals(realm)) throw new RBACException("Unsupported realm, "+realm); try { ArrayList list = new ArrayList(); // return all roles _engine.queryExtent(_roleBase, _roleId, list); return prefix(list); } catch ( NamingException ne ) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } }*/ /** * @see org.intalio.tempo.security.rbac.RBACQuery#descendantRoles(java.lang.String) */ public String[] descendantRoles(String role) throws RoleNotFoundException, RBACException, RemoteException { role = IdentifierUtils.stripRealm(role); try { TreeSet<String> result = new TreeSet<String>(); result.add(role); short found; if (_roleAscen!=null) found = _engine.queryInheritRelation(_roleBase, _roleId, _roleAscen, result); else found = _engine.queryInheritReference(_roleBase, _roleId, _roleDescen, result); if (found==LDAPQueryEngine.SUBJECT_NOT_FOUND) throw new RoleNotFoundException("Role, "+role+", is not found!"); if (result.size()==0) return EMPTY_STRINGS; else { result.remove(role); return prefix(result); } } catch (NamingException ne) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } /** * @see org.intalio.tempo.security.rbac.RBACQuery#ascendantRoles(java.lang.String) */ public String[] ascendantRoles(String role) throws RoleNotFoundException, RBACException, RemoteException { role = IdentifierUtils.stripRealm(role); try { TreeSet<String> result = new TreeSet<String>(); result.add(role); short found; if (_roleAscen!=null) found = _engine.queryInheritReference(_roleBase, _roleId, _roleAscen, result); else found = _engine.queryInheritRelation(_roleBase, _roleId, _roleDescen, result); if (found==LDAPQueryEngine.SUBJECT_NOT_FOUND) throw new RoleNotFoundException("Role, "+role+", is not found!"); if (result.size()==0) return EMPTY_STRINGS; else { result.remove(role); return prefix(result); } } catch (NamingException ne) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } /** * @see org.intalio.tempo.security.rbac.RBACQuery#roleOperationsOnObject(java.lang.String, java.lang.String) */ public String[] roleOperationsOnObject(String role, String object) throws RoleNotFoundException, ObjectNotFoundException, RBACException, RemoteException { role = IdentifierUtils.stripRealm(role); object = IdentifierUtils.stripRealm(object); try { // first, find all authroizedRoles ArrayList<String> roles = new ArrayList<String>(); if (_roleAscen!=null) _engine.queryInheritReference(_roleBase, _roleId, _roleAscen, roles); else _engine.queryInheritRelation(_roleBase, _roleId, _roleDescen, roles); // then, find the permission objects TreeSet<String> perms = new TreeSet<String>(); if (_permRoles!=null) { // get all the permission from role _engine.queryRelations(roles, _roleBase, _roleId, _permBase, _permRoles, perms); } else { // if (_rolePerms!=null) _engine.queryFields(roles, _roleBase, _roleId, _rolePerms, perms); } // @TODO throws the ObjectNotFoundException, RoleNotFoundException properly TreeSet<String> result = new TreeSet<String>(); _engine.queryFields(perms, _permBase, _permId, _permObjects, result); return (String[])result.toArray(new String[result.size()]); } catch (NamingException ne) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } /** * @see org.intalio.tempo.security.rbac.RBACQuery#userOperationsOnObject(java.lang.String, java.lang.String) */ public String[] userOperationsOnObject(String user, String object) throws UserNotFoundException, ObjectNotFoundException, RBACException, RemoteException { user = IdentifierUtils.stripRealm(user); object = IdentifierUtils.stripRealm(object); try { // first, find all assigned roles of a user ArrayList<String> roles = new ArrayList<String>(); short found; if (_userRoles!=null) { found = _engine.queryFields(user, _userBase, _userId, _userRoles, roles); } else { boolean checkUser = true; found = _engine.queryRelations(user, _userBase, _userId, _roleBase, _roleUsers, checkUser, roles); } if (found==LDAPQueryEngine.SUBJECT_NOT_FOUND) throw new RoleNotFoundException("User, "+user+", is not found!"); if (found==LDAPQueryEngine.RELATION_NOT_FOUND) return EMPTY_STRINGS; // then, find all authorizedRoles if (_roleAscen!=null) _engine.queryInheritReference(_roleBase, _roleId, _roleAscen, roles); else _engine.queryInheritRelation(_roleBase, _roleId, _roleDescen, roles); // then, find permission object TreeSet<String> perms = new TreeSet<String>(); if (_permRoles!=null) { // get all the permission from role _engine.queryRelations(roles, _roleBase, _roleId, _permBase, _permRoles, perms); } else { // if (_rolePerms!=null) _engine.queryFields(roles, _roleBase, _roleId, _rolePerms, perms); } // @TODO throws the ObjectNotFoundException, RoleNotFoundException properly TreeSet<String> result = new TreeSet<String>(); _engine.queryFields(perms, _permBase, _permId, _permObjects, result); return (String[])result.toArray(new String[result.size()]); } catch (NamingException ne) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } /** * @see org.intalio.tempo.security.rbac.RBACQuery#userProperties(java.lang.String) */ public Property[] userProperties(String user) throws UserNotFoundException, RBACException, RemoteException { user = IdentifierUtils.stripRealm(user); try { HashMap<String,Property> result = new HashMap<String,Property>(); _engine.queryProperties(user, _userBase, _userId, _userProp, result); return (Property[])result.values().toArray(new Property[result.size()]); } catch (NamingException ne) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } /** * @see org.intalio.tempo.security.rbac.RBACQuery#roleProperties(java.lang.String) */ public Property[] roleProperties(String role) throws RoleNotFoundException, RBACException, RemoteException { role = IdentifierUtils.stripRealm(role); try { HashMap<String,Property> result = new HashMap<String,Property>(); _engine.queryProperties(role, _roleBase, _roleId, _roleProp, result); return (Property[])result.values().toArray(new Property[result.size()]); } catch (NamingException ne) { if (LOG.isInfoEnabled()) LOG.info(ne.getMessage(),ne); throw new RBACException(ne); } } } }
epl-1.0
gnodet/wikitext
org.eclipse.mylyn.wikitext.tracwiki.core/src/org/eclipse/mylyn/internal/wikitext/tracwiki/core/phrase/EscapePhraseModifier.java
1808
/******************************************************************************* * Copyright (c) 2007, 2008 David Green and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David Green - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.wikitext.tracwiki.core.phrase; import org.eclipse.mylyn.wikitext.core.parser.Attributes; import org.eclipse.mylyn.wikitext.core.parser.DocumentBuilder.SpanType; import org.eclipse.mylyn.wikitext.core.parser.markup.PatternBasedElement; import org.eclipse.mylyn.wikitext.core.parser.markup.PatternBasedElementProcessor; /** * * * @author David Green */ public class EscapePhraseModifier extends PatternBasedElement { @Override protected String getPattern(int groupOffset) { String escapedContent = "(\\S(?:.*?\\S)?)"; //$NON-NLS-1$ return "(?:(?:`" + escapedContent + // content //$NON-NLS-1$ "`)|(?:\\{\\{" + escapedContent + // content //$NON-NLS-1$ "\\}\\}))"; //$NON-NLS-1$ } @Override protected int getPatternGroupCount() { return 2; } @Override protected PatternBasedElementProcessor newProcessor() { return new EscapeProcessor(); } private static class EscapeProcessor extends PatternBasedElementProcessor { private EscapeProcessor() { } @Override public void emit() { getBuilder().beginSpan(SpanType.MONOSPACE, new Attributes()); String group = group(1); if (group == null) { group = group(2); } getBuilder().characters(group); getBuilder().endSpan(); } } }
epl-1.0
zamberjo/hesidohackeadobot
setup.py
1106
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup( name='HeSidoHackeadoBot', packages=['hesidohackeadobot'], version='1.0', description='Bot telegram para uso de la API de www.hesidohackeado.com', url='https://github.com/zamberjo/hesidohackeadobot', author='Jose Zambudio Bernabeu', author_email='[email protected]', license='LGPL-3', scripts=['hshbot.py'], install_requires=[ 'pyTelegramBotAPI >= 0.3.9', 'pymongo >= 3.0.3', 'python-crontab >= 1.9.3', 'ndg-httpsclient >= 0.4.0', 'pyasn1 >= 0.1.9', 'pyOpenSSL >= 0.13', 'configparser', ], # classifiers=[ # 'Programming Language :: Python', # 'Programming Language :: Python :: 2.7', # 'License :: OSI Approved :: GNU General Public License (GPL)', # 'Operating System :: OS Independent', # 'Development Status :: 1 - Planning', # 'Environment :: Console', # 'Intended Audience :: Science/Research', # 'Topic :: Scientific/Engineering :: GIS' # ] )
gpl-2.0
Fotonicamente/fotonicamente-wp-theme
xin-magazine-fotonicamente/pages/portfolio.php
2559
<?php /** * Template Name: Portfolio * * @package xinmag * @since 1.0.2 */ get_header(); if ( get_query_var('paged') ) $paged = get_query_var('paged'); elseif ( get_query_var('page') ) $paged = get_query_var('page'); else $paged = 1; global $xinwp_thumbnail, $xinwp_display_excerpt, $xinwp_entry_meta; if ( have_posts() && is_page()) { the_post(); $pt_category = get_post_meta($post->ID, '_xinmag_category', true); $column = get_post_meta($post->ID, '_xinmag_column', true); if ('' == $column) $column = 3; $postperpage = get_post_meta($post->ID, '_xinmag_postperpage', true); if ($postperpage < $column) $postperpage = 12; $pt_thumbnail = get_post_meta($post->ID, '_xinmag_thumbnail', true); $pt_size_x = get_post_meta($post->ID, '_xinmag_size_x', true); $pt_size_y = get_post_meta($post->ID, '_xinmag_size_y', true); $xinwp_thumbnail = xinwp_thumbnail_size($pt_thumbnail, $pt_size_x, $pt_size_y); $xinwp_display_excerpt = get_post_meta($post->ID, '_xinmag_intro', true); if ('' == $xinwp_display_excerpt) $xinwp_display_excerpt = 1; $xinwp_entry_meta = get_post_meta($post->ID, '_xinmag_disp_meta', true); $sidebar = get_post_meta($post->ID, '_xinmag_sidebar', true); xinmag_template_intro(); } else { $pt_category = ''; $xinwp_display_excerpt = 1; $column = 1; $postperpage = 0; $xinwp_thumbnail = 'thumbnail'; $xinwp_entry_meta = 1; $sidebar = 1; } ?> <div id="content" class="<?php echo $sidebar ? xinwp_content_class() : xinwp_grid_full(); ?>" role="main"> <div class="xinwp_recent_post portfolio column-<?php echo $column; ?>"> <input type="hidden" id="portfolio-column" value="<?php echo $column; ?>"> <?php $blog_args = array( 'post_type' => 'post', 'post_status' => 'publish', 'paged' => $paged, 'posts_per_page' => $postperpage, // 'ignore_sticky_posts' => 1, ); if ($pt_category) { $blog_args['category__in'] = $pt_category; } $blog = new WP_Query( $blog_args ); if ( $blog->have_posts() ) : // xinmag_content_nav_link( $blog->max_num_pages, 'nav-above' ); $col = 0; while ( $blog->have_posts() ) : $blog->the_post(); if (is_sticky() && $paged == 1) echo '<div class="item sticky">'; else echo '<div class="item">'; get_template_part( 'content', 'summary' ); echo '</div>'; endwhile; xinmag_content_nav_link( $blog->max_num_pages, 'nav-below' ); wp_reset_postdata(); endif; ?> </div> </div> <?php if ($sidebar) get_sidebar(); ?> <?php get_footer(); ?>
gpl-2.0
vaanwizard/ablator
python/models/solution.py
4557
#trida, ktera bude uchovavat solution #atributy: # name - jmeno solutionu, podle nej vznikne adresar ve slozce solutions # init_data - prirazeny soubor init_data # mat_data - prirazeny soubor mat_data # opac_data - prirazeny soubor opac_data # ablator_exe - prirazena binarka, ktera provede vypocet #metody: # load - pro nacteni solutionu # save - pro ulozeni solutionu do slozky solutions import os, shutil from models.init_data import InitData from models.mat_data import MatData class Solution: def __init__(self, name = None, init_data = None, mat_data = "", opac_data = "", ablator_exe = "Ablator.exe"): self.name = name #zatim necham jen nacist soubor, v budoucnu se do nej bude zapisovat a bude mit vlastni tridu #self.init_data = InitData(init_data) #self.mat_data = MatData(mat_data) #self.opac_data = opac_data self.init_data = None self.mat_data = None self.opac_data = None self.ablator_exe = ablator_exe def set_init_data(self, value): self.init_data = InitData(value,self.ablator_exe) def get_init_data(self): return self.init_data def set_mat_data(self, value): self.mat_data = MatData(value, self.ablator_exe) def get_mat_data(self): return self.mat_data def set_opac_data(self, value): self.opac_data = value def set_ablator_exe(self, value): self.ablator_exe = value def set_name(self,value): self.name = value #nacteni solutiony bude probihat jednoduse ze souboru solution.txt: # -prvni radek souboru nazev(cesta) init_data # -druhy radek souboru nazev(cesta) mat_data # -treti radek souboru nazev(cesta) opac_data def load(self): if(self.name == ""): raise "Nezadano reseni" try: solution_file = open(self.name, "r") except IOError as e: raise ('Nemohu otevrit soubor: solutions/' + self.name + "/solution.txt") self.name = solution_file.readline().replace("\n","") self.ablator_exe = solution_file.readline().replace("\n","") self.init_data = InitData(solution_file.readline().replace("\n",""), self.ablator_exe) self.mat_data = MatData(solution_file.readline().replace("\n",""), self.ablator_exe) self.opac_data = solution_file.readline().replace("\n","") solution_file.close() #ulozeni struktura solution.txt stejna jako def save(self): directory = "solutions/" + self.name if(os.path.exists(directory) == False): os.makedirs(directory) path = ("solutions/" + self.name + "/solution.txt") if(os.path.exists(path)): try: os.remove(path) except: print("nemohu odstranit path") solution_file = open(path, "w") solution_file.write(self.name + "\n") solution_file.write(self.ablator_exe + "\n") solution_file.write(self.init_data.filepath + "\n") solution_file.write(self.mat_data.filepath + "\n") solution_file.write(self.opac_data) solution_file.close() def copy_solution_to(self,target): #shutil.copy("bin/Ablator.exe", target) shutil.copy("bin/" + self.ablator_exe, target) shutil.copyfile(self.init_data.filepath,target+"/initdata") shutil.copyfile(self.mat_data.filepath,target+"/matdata") shutil.copyfile(self.opac_data,target+"/opacdata") def prepared_to_run(self): if(os.path.exists(self.init_data.filepath) == False): return False if(os.path.exists(self.mat_data.filepath) == False): return False if(os.path.exists(self.opac_data) == False): return False return True #otevre slozku s resenimi v exploreru def open_folder(self): os.system("explorer " + "solutions\\" + self.name) def run(self): if(self.name == None): raise "Nebylo zadano jmeno" self.save() self.copy_solution_to("temp") if(self.prepared_to_run()): os.chdir("temp") i = os.system(self.ablator_exe) os.system("del " + self.ablator_exe) os.system("del initdata") os.system("del matdata") os.system("del opacdata") os.system("copy *.* " + "..\\solutions\\" + self.name) os.chdir("..") os.system("del /Q temp")
gpl-2.0
jeffgdotorg/opennms
features/graph/provider/legacy/src/main/java/org/opennms/netmgt/graph/provider/legacy/LegacyVertex.java
2287
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2019-2019 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2019 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.graph.provider.legacy; import org.opennms.features.topology.api.topo.Vertex; import org.opennms.netmgt.graph.api.generic.GenericVertex; import org.opennms.netmgt.graph.domain.AbstractDomainVertex; public class LegacyVertex extends AbstractDomainVertex { public LegacyVertex(GenericVertex genericVertex) { super(genericVertex); } public LegacyVertex(Vertex legacyVertex) { super(GenericVertex.builder() .id(legacyVertex.getId()) .label(legacyVertex.getLabel()) .namespace(legacyVertex.getNamespace()) .property("nodeID", legacyVertex.getNodeID()) .property("iconKey", legacyVertex.getIconKey()) .property("ipAddress", legacyVertex.getIpAddress()) .property("styleName", legacyVertex.getStyleName()) .property("tooltipText", legacyVertex.getTooltipText()) .property("x", legacyVertex.getX()) .property("y", legacyVertex.getY()) .build()); } }
gpl-2.0
cleitonalmeida1/EstagioAZ
assets/vendor/kendoui/src/js/cultures/kendo.culture.af-ZA.js
2676
/* * Kendo UI v2015.2.805 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["af-ZA"] = { name: "af-ZA", numberFormat: { pattern: ["-n"], decimals: 2, ",": " ", ".": ",", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["$-n","$ n"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "R" } }, calendars: { standard: { days: { names: ["Sondag","Maandag","Dinsdag","Woensdag","Donderdag","Vrydag","Saterdag"], namesAbbr: ["Son","Maan","Dins","Woen","Dond","Vry","Sat"], namesShort: ["So","Ma","Di","Wo","Do","Vr","Sa"] }, months: { names: ["Januarie","Februarie","Maart","April","Mei","Junie","Julie","Augustus","September","Oktober","November","Desember"], namesAbbr: ["Jan","Feb","Mar","Apr","Mei","Jun","Jul","Aug","Sep","Okt","Nov","Des"] }, AM: ["VM.","vm.","VM."], PM: ["NM.","nm.","NM."], patterns: { d: "yyyy/MM/dd", D: "dd MMMM yyyy", F: "dd MMMM yyyy hh:mm:ss tt", g: "yyyy/MM/dd hh:mm tt", G: "yyyy/MM/dd hh:mm:ss tt", m: "d MMMM", M: "d MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "hh:mm tt", T: "hh:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 0 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
gpl-2.0
nowshad-sust/ImageMatching-pHash
src/distance/LevenshteinDistance.java
1844
package distance; /** * http://en.wikipedia.org/wiki/Levenshtein_distance */ public class LevenshteinDistance implements Distance { @Override public int getDistance(Object object1, Object object2) { String string1 = (String) object1; String string2 = (String) object2; int distance[][]; // distance matrix int n; // length of first string int m; // length of second string int i; // iterates through first string int j; // iterates through second string char s_i; // ith character of first string char t_j; // jth character of second string int cost; // cost // Step 1 n = string1.length(); m = string2.length(); if (n == 0) return m; if (m == 0) return n; distance = new int[n+1][m+1]; // Step 2 for (i = 0; i <= n; i++) distance[i][0] = i; for (j = 0; j <= m; j++) distance[0][j] = j; // Step 3 for (i = 1; i <= n; i++) { s_i = string1.charAt (i - 1); // Step 4 for (j = 1; j <= m; j++) { t_j = string2.charAt(j - 1); // Step 5 if (s_i == t_j) cost = 0; else cost = 1; // Step 6 distance[i][j] = findMinimum(distance[i-1][j]+1, distance[i][j-1]+1, distance[i-1][j-1] + cost); } } // Step 7 return distance[n][m]; } private int findMinimum(int a, int b, int c) { int min = a; if (b < min) { min = b; } if (c < min) { min = c; } return min; } }
gpl-2.0
pobbes/gambio
admin/includes/modules/security_check.php
5295
<?php /* -------------------------------------------------------------- security_check.php 2011-05-12 mb Gambio GmbH http://www.gambio.de Copyright (c) 2011 Gambio GmbH Released under the GNU General Public License (Version 2) [http://www.gnu.org/licenses/gpl-2.0.html] -------------------------------------------------------------- based on: (c) 2003 nextcommerce (security_check.php,v 1.2 2003/08/23); www.nextcommerce.org (c) 2003 XT-Commerce - community made shopping http://www.xt-commerce.com ($Id: security_check.php 1221 2005-09-20 16:44:09Z mz $) Released under the GNU General Public License --------------------------------------------------------------*/ defined('_VALID_XTC') or die('Direct Access to this location is not allowed.'); $file_warning = ''; $obsolete_warning = ''; if (@is_writable(DIR_FS_CATALOG.'includes/configure.php')) { $file_warning .= '<br>'.DIR_FS_CATALOG.'includes/configure.php'; } if (@is_writable(DIR_FS_CATALOG.'includes/configure.org.php')) { $file_warning .= '<br>'.DIR_FS_CATALOG.'includes/configure.org.php'; } if (@is_writable(DIR_FS_ADMIN.'includes/configure.php')) { $file_warning .= '<br>'.DIR_FS_ADMIN.'includes/configure.php'; } if (@is_writable(DIR_FS_ADMIN.'includes/configure.org.php')) { $file_warning .= '<br>'.DIR_FS_ADMIN.'includes/configure.org.php'; } if (!@is_writable(DIR_FS_CATALOG.'templates_c/')) { $folder_warning .= '<br>'.DIR_FS_CATALOG.'templates_c/'; } if (!@is_writable(DIR_FS_CATALOG.'cache/')) { $folder_warning .= '<br>'.DIR_FS_CATALOG.'cache/'; } if (!@is_writable(DIR_FS_CATALOG.'media/')) { $folder_warning .= '<br>'.DIR_FS_CATALOG.'media/'; } if (!@is_writable(DIR_FS_CATALOG.'media/content/')) { $folder_warning .= '<br>'.DIR_FS_CATALOG.'media/content/'; } // check if robots.txt obsolete require_once(DIR_FS_CATALOG.'gm/inc/get_robots.php'); $check_robots_result = check_robots(DIR_WS_CATALOG); if(!$check_robots_result) { $obsolete_warning .= '<br>'.HTTP_SERVER.'/robots.txt - <a href="'.DIR_WS_ADMIN.'robots_download.php">download robots.txt</a>'; } $t_db_update_not_installed = false; if(file_exists(DIR_FS_CATALOG . 'gm_updater.php') && file_exists(DIR_FS_CATALOG . 'gm_updater_sql.php')) { include_once(DIR_FS_CATALOG . 'release_info.php'); $t_db_shop_version = gm_get_conf('GM_UPDATER_VERSION'); if($t_db_shop_version != $gx_version) { $t_db_update_not_installed = true; } } if ($file_warning != '' or $folder_warning != '' or $obsolete_warning != '' or $t_db_update_not_installed === true) { ?> <table style="border: 1px solid; border-color: #ff0000;" bgcolor="#FDAC00" border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td><div class="main"> <table width="100%" border="0"> <tr> <td width="1"><?php echo xtc_image(DIR_WS_ICONS.'big_warning.gif'); ?></td> <td class="main"><?php if ($file_warning != '') { echo TEXT_FILE_WARNING; echo '<b>'.$file_warning.'</b><br>'; } if ($folder_warning != '') { echo TEXT_FOLDER_WARNING; echo '<b>'.$folder_warning.'</b>'; } // if any file obsolete if ($obsolete_warning != '') { echo TEXT_OBSOLETE_WARNING; echo '<b>'.$obsolete_warning.'</b><br />'; } // DB not up to date if($t_db_update_not_installed) { echo TEXT_DB_UPDATE_WARNING; } $payment_query = xtc_db_query("SELECT * FROM ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_PAYMENT_INSTALLED'"); while ($payment_data = xtc_db_fetch_array($payment_query)) { $installed_payment = $payment_data['configuration_value']; } if ($installed_payment == '') { echo '<br>'.TEXT_PAYMENT_ERROR; } $shipping_query = xtc_db_query("SELECT * FROM ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_SHIPPING_INSTALLED'"); while ($shipping_data = xtc_db_fetch_array($shipping_query)) { $installed_shipping = $shipping_data['configuration_value']; } if ($installed_shipping == '') { echo '<br>'.TEXT_SHIPPING_ERROR; } ?></td> </tr> </table> </div> </td> </tr> </table> <?php } else { $payment_query = xtc_db_query("SELECT * FROM ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_PAYMENT_INSTALLED'"); while ($payment_data = xtc_db_fetch_array($payment_query)) { $installed_payment = $payment_data['configuration_value']; } $shipping_query = xtc_db_query("SELECT * FROM ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_SHIPPING_INSTALLED'"); while ($shipping_data = xtc_db_fetch_array($shipping_query)) { $installed_shipping = $shipping_data['configuration_value']; } if($installed_payment == '' || $installed_shipping == '') { ?> <table style="border: 1px solid; border-color: #ff0000;" bgcolor="#FDAC00" border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td><divclass"main"> <table width="100%" border="0"> <tr> <td width="1"><?php echo xtc_image(DIR_WS_ICONS.'big_warning.gif'); ?></td> <td class="main"><?php if ($installed_payment == '') { echo TEXT_PAYMENT_ERROR; } if ($installed_shipping == '') { echo '<br>'.TEXT_SHIPPING_ERROR; } ?></td> </tr> </table> </div> </td> </tr> </table> <?php } } ?>
gpl-2.0
ftalbrecht/dune-grid
dune/grid/test/checktwists.cc
6342
// -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- // vi: set et ts=4 sw=2 sts=2: int applyTwist ( const int twist, const int i, const int numCorners ) { return (twist < 0 ? (2*numCorners + 1 - i + twist) : i + twist) % numCorners; } int inverseTwist ( const int twist, const int numCorners ) { return (twist <= 0 ? twist : numCorners - twist); } struct NoMapTwist { int operator() ( const int twist ) const { return twist; } }; template< class Intersection, class MapTwist > int checkTwistOnIntersection ( const Intersection &intersection, const MapTwist &mapTwist ) { typedef typename Intersection::ctype ctype; const int dimension = Intersection::dimension; typedef typename Intersection::EntityPointer EntityPointer; typedef typename Intersection::Entity Entity; typedef typename Entity::Geometry Geometry; typedef typename Intersection::LocalGeometry LocalGeometry; typedef Dune::ReferenceElement< ctype, dimension > ReferenceElement; typedef Dune::ReferenceElements< ctype, dimension > ReferenceElements; typedef Dune::FieldVector< typename Geometry::ctype, Geometry::coorddimension > WorldVector; typedef Dune::FieldVector< typename LocalGeometry::ctype, LocalGeometry::coorddimension > LocalVector; if( !intersection.neighbor() || intersection.boundary() || !intersection.conforming() ) return 0; int errors = 0; const int tIn = mapTwist( intersection.twistInInside() ); const int tOut = mapTwist( intersection.twistInOutside() ); const EntityPointer ptrIn = intersection.inside(); const EntityPointer ptrOut = intersection.outside(); const Entity &entityIn = *ptrIn; const Entity &entityOut = *ptrOut; const Geometry &geoIn = entityIn.geometry(); const Geometry &geoOut = entityOut.geometry(); const int nIn = intersection.indexInInside(); const int nOut = intersection.indexInOutside(); const ReferenceElement &refIn = ReferenceElements::general( geoIn.type() ); const ReferenceElement &refOut = ReferenceElements::general( geoOut.type() ); const int numCorners = refIn.size( nIn, 1, dimension ); assert( refOut.size( nOut, 1, dimension ) == numCorners ); for( int i = 0; i < numCorners; ++i ) { const int iIn = applyTwist( inverseTwist( tIn, numCorners ), i, numCorners ); const int iOut = applyTwist( inverseTwist( tOut, numCorners ), i, numCorners ); WorldVector xIn = geoIn.corner( refIn.subEntity( nIn, 1, iIn, dimension ) ); WorldVector xOut = geoOut.corner( refOut.subEntity( nOut, 1, iOut, dimension ) ); if( (xIn - xOut).two_norm() < 1e-12 ) continue; std::cout << "Error: corner( " << iIn << " ) = " << xIn << " != " << xOut << " = corner( " << iOut << " )." << std::endl; ++errors; } const LocalGeometry &lGeoIn = intersection.geometryInInside(); const LocalGeometry &lGeoOut = intersection.geometryInOutside(); bool twistInside = true ; bool twistOutside = true; for( int i = 0; i < numCorners; ++i ) { const int gi = i; const int iIn = applyTwist( inverseTwist( tIn, numCorners ), i, numCorners ); LocalVector xIn = refIn.position( refIn.subEntity( nIn, 1, iIn, dimension ), dimension ); if( (xIn - lGeoIn.corner( gi )).two_norm() >= 1e-12 ) { std::cout << "Error: twisted inside reference corner( " << iIn << " ) = " << xIn << " != " << lGeoIn.corner( gi ) << " = local corner( " << i << " )." << std::endl; twistInside = false ; ++errors; } const int iOut = applyTwist( inverseTwist( tOut, numCorners ), i, numCorners ); LocalVector xOut = refOut.position( refOut.subEntity( nOut, 1, iOut, dimension ), dimension ); if( (xOut - lGeoOut.corner( gi )).two_norm() >= 1e-12 ) { std::cout << "Error: twisted outside reference corner( " << iOut << " ) = " << xOut << " != " << lGeoOut.corner( gi ) << " = local corner( " << i << " )." << std::endl; twistOutside = false; ++errors; } } // calculate inside twist if( ! twistInside ) { for( int nTwist = numCorners-1; nTwist>= -numCorners; --nTwist ) { twistInside = true ; for( int i = 0; i < numCorners; ++i ) { const int gi = i; const int iIn = applyTwist( inverseTwist( nTwist, numCorners ), i, numCorners ); LocalVector xIn = refIn.position( refIn.subEntity( nIn, 1, iIn, dimension ), dimension ); if( (xIn - lGeoIn.corner( gi )).two_norm() >= 1e-12 ) { twistInside = false ; } } if( twistInside ) { std::cout << "\ninside " << nIn << "\n"; std::cout << "twist " << tIn << " should be replaced by " << nTwist << "\n"; break ; } } } // calculate outside twist if( ! twistOutside ) { for( int nTwist = numCorners-1; nTwist>=-numCorners; --nTwist ) { twistOutside = true ; for( int i = 0; i < numCorners; ++i ) { const int gi = i; const int iOut = applyTwist( inverseTwist( nTwist, numCorners ), i, numCorners ); LocalVector xOut = refOut.position( refOut.subEntity( nOut, 1, iOut, dimension ), dimension ); if( (xOut - lGeoOut.corner( gi )).two_norm() >= 1e-12 ) { twistOutside = false; } } if( twistOutside ) { std::cout << "\noutside " << nOut << " (inside = " << nIn << ")\n"; std::cout << "twist " << tOut << " should be replaced by " << nTwist << "\n"; break ; } } } return errors; } template< class GridView, class MapTwist > void checkTwists ( const GridView &gridView, const MapTwist &mapTwist ) { typedef typename GridView::template Codim< 0 >::Iterator Iterator; typedef typename GridView::IntersectionIterator IntersectionIterator; int errors = 0; const Iterator end = gridView.template end< 0 >(); for( Iterator it = gridView.template begin< 0 >(); it != end; ++it ) { const IntersectionIterator iend = gridView.iend( *it ); for( IntersectionIterator iit = gridView.ibegin( *it ); iit != iend; ++iit ) errors += checkTwistOnIntersection( gridView.grid().getRealIntersection( *iit ), mapTwist ); } if( errors > 0 ) std::cerr << "Error: Intersection twists contain errors." << std::endl; }
gpl-2.0
alx/SimplePress
wp-content/plugins/wp-e-commerce/wpsc-admin/includes/settings-pages/presentation.php
42296
<?php function options_categorylist() { global $wpdb; $current_default = get_option('wpsc_default_category'); $group_sql = "SELECT * FROM `".WPSC_TABLE_CATEGORISATION_GROUPS."` WHERE `active`='1'"; $group_data = $wpdb->get_results($group_sql,ARRAY_A); $categorylist .= "<select name='wpsc_options[wpsc_default_category]'>"; if(get_option('wpsc_default_category') == 'all') { $selected = "selected='selected'"; } else { $selected = ''; } $categorylist .= "<option value='all' ".$selected." >".TXT_WPSC_SELECTALLCATEGORIES."</option>"; if(get_option('wpsc_default_category') == 'list') { $selected = "selected='selected'"; } else { $selected = ''; } $categorylist .= "<option value='list' ".$selected." >".TXT_WPSC_CATEGORY_LIST."</option>"; if(get_option('wpsc_default_category') == 'all+list') { $selected = "selected='selected'"; } else { $selected = ''; } $categorylist .= "<option value='all+list' ".$selected." >".TXT_WPSC_ALL_PRODUCTS_AND_CATEGORY_LIST."</option>"; foreach($group_data as $group) { $cat_sql = "SELECT * FROM `".WPSC_TABLE_PRODUCT_CATEGORIES."` WHERE `group_id` IN ({$group['id']}) AND `active`='1'"; $category_data = $wpdb->get_results($cat_sql,ARRAY_A); if($category_data != null) { $categorylist .= "<optgroup label='{$group['name']}'>";; foreach((array)$category_data as $category) { if(get_option('wpsc_default_category') == $category['id']) { $selected = "selected='selected'"; } else { $selected = ""; } $categorylist .= "<option value='".$category['id']."' ".$selected." >".$category['name']."</option>"; } $categorylist .= "</optgroup>"; } } $categorylist .= "</select>"; return $categorylist; } function wpsc_options_presentation(){ global $wpdb; ?> <form name='cart_options' id='cart_options' method='post' action=''> <div id="options_presentation"> <h2><?php echo TXT_WPSC_OPTIONS_PRESENTATION_HEADER; ?></h2> <?php /* wpsc_setting_page_update_notification displays the wordpress styled notifications */ wpsc_settings_page_update_notification(); ?> <div class='product_and_button_settings'> <h3 class="form_group"><?php echo TXT_WPSC_BUTTON_SETTINGS;?></h3> <table class='wpsc_options form-table'> <tr> <th scope="row"><?php echo TXT_WPSC_BUTTONTYPE;?>:</th> <td> <?php $addtocart_or_buynow = get_option('addtocart_or_buynow'); $addtocart_or_buynow1 = ""; $addtocart_or_buynow2 = ""; switch($addtocart_or_buynow) { case 0: $addtocart_or_buynow1 = "checked ='checked'"; break; case 1: $addtocart_or_buynow2 = "checked ='checked'"; break; } ?> <input type='radio' value='0' name='wpsc_options[addtocart_or_buynow]' id='addtocart_or_buynow1' <?php echo $addtocart_or_buynow1; ?> /> <label for='addtocart_or_buynow1'><?php echo TXT_WPSC_ADDTOCART;?></label> &nbsp;<br /> <input type='radio' value='1' name='wpsc_options[addtocart_or_buynow]' id='addtocart_or_buynow2' <?php echo $addtocart_or_buynow2; ?> /> <label for='addtocart_or_buynow2'><?php echo TXT_WPSC_BUYNOW;?></label> </td> </tr> <tr> <th scope="row"><?php echo TXT_WPSC_HIDEADDTOCARTBUTTON;?>: </th> <td> <?php $hide_addtocart_button = get_option('hide_addtocart_button'); $hide_addtocart_button1 = ""; $hide_addtocart_button2 = ""; switch($hide_addtocart_button) { case 0: $hide_addtocart_button2 = "checked ='checked'"; break; case 1: $hide_addtocart_button1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[hide_addtocart_button]' id='hide_addtocart_button1' <?php echo $hide_addtocart_button1; ?> /> <label for='hide_addtocart_button1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[hide_addtocart_button]' id='hide_addtocart_button2' <?php echo $hide_addtocart_button2; ?> /> <label for='hide_addtocart_button2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> </table> <h3 class="form_group"><?php echo TXT_WPSC_PRODUCT_DISPLAY_SETTINGS;?></h3> <table class='wpsc_options form-table'> <tr> <th scope="row"><?php echo TXT_WPSC_SHOWPRODUCTRATINGS;?>:</th> <td> <?php $display_pnp = get_option('product_ratings'); $product_ratings1 = ""; $product_ratings2 = ""; switch($display_pnp) { case 0: $product_ratings2 = "checked ='checked'"; break; case 1: $product_ratings1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[product_ratings]' id='product_ratings1' <?php echo $product_ratings1; ?> /> <label for='product_ratings1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[product_ratings]' id='product_ratings2' <?php echo $product_ratings2; ?> /> <label for='product_ratings2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <tr> <th scope="row"> <?php echo TXT_WPSC_DISPLAY_FANCY_NOTIFICATIONS;?>: </th> <td> <?php $fancy_notifications = get_option('fancy_notifications'); $fancy_notifications1 = ""; $fancy_notifications2 = ""; switch($fancy_notifications) { case 0: $fancy_notifications2 = "checked ='checked'"; break; case 1: $fancy_notifications1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[fancy_notifications]' id='fancy_notifications1' <?php echo $fancy_notifications1; ?> /> <label for='fancy_notifications1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[fancy_notifications]' id='fancy_notifications2' <?php echo $fancy_notifications2; ?> /> <label for='fancy_notifications2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <tr> <th scope="row"><?php echo TXT_WPSC_SHOWPOSTAGEANDPACKAGING;?>:</th> <td> <?php $display_pnp = get_option('display_pnp'); $display_pnp1 = ""; $display_pnp2 = ""; switch($display_pnp) { case 0: $display_pnp2 = "checked ='checked'"; break; case 1: $display_pnp1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[display_pnp]' id='display_pnp1' <?php echo $display_pnp1; ?> /> <label for='display_pnp1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[display_pnp]' id='display_pnp2' <?php echo $display_pnp2; ?> /> <label for='display_pnp2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <tr> <th scope="row"><?php echo TXT_WPSC_HIDEADDNAMELINK;?>: </th> <td> <?php $hide_name_link = get_option('hide_name_link'); $hide_name_link1 = ""; $hide_name_link2 = ""; switch($hide_name_link) { case 0: $hide_name_link2 = "checked ='checked'"; break; case 1: $hide_name_link1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[hide_name_link]' id='hide_name_link1' <?php echo $hide_name_link1; ?> /> <label for='hide_name_link1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[hide_name_link]' id='hide_name_link2' <?php echo $hide_name_link2; ?> /> <label for='hide_name_link2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <tr> <th scope="row"><?php echo TXT_WPSC_MULTIPLE_ADDING_PRODUCTS;?>:</th> <td> <?php $multi_adding = get_option('multi_add'); switch($multi_adding) { case 1: $multi_adding1 = "checked ='checked'"; break; case 0: $multi_adding2 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[multi_add]' id='multi_adding1' <?php echo $multi_adding1; ?> /> <label for='multi_adding1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[multi_add]' id='multi_adding2' <?php echo $multi_adding2; ?> /> <label for='multi_adding2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> </table> </div> <div class='themes_and_appearance'> <h4><?php _e("Theme Customisation", 'wpsc'); ?></h4> <?php if($_SESSION['wpsc_themes_copied'] == true) { ?> <div class="updated fade below-h2" id="message" style="background-color: rgb(255, 251, 204);"> <p><?php _e("Thanks, the themes have been copied."); ?></p> </div> <?php $_SESSION['wpsc_themes_copied'] = false; } ?> <?php if(wpsc_count_themes_in_uploads_directory() > 0) { ?> <p><?php _e("Theming your stores appearance is easy.");?></p> <p> <?php _e("You just need to edit the appropriate files in the following location.", 'wpsc'); ?><br /><br /> <span class='display-path'><strong><?php _e("Path:", 'wpsc'); ?></strong> <?php echo str_replace(ABSPATH, "", WPSC_THEMES_PATH).WPSC_THEME_DIR."/"; ?> </span> </p> <p><strong><?php _e("To create a new theme:", 'wpsc'); ?></strong></p> <ol> <li><?php _e("Copy the default directory and rename it 'newTheme'"); ?></li> <li><?php _e("Rename the default.css file inside the 'newTheme' directory to 'newTheme.css'"); ?></li> </ol> <?php } else if(!is_writable(WPSC_THEMES_PATH)) { ?> <p><?php _e("The permissions on your themes directory are incorrect.", 'wpsc'); ?> </p> <p><?php _e("Please set the permissions to 775 on the following directory.", 'wpsc'); ?><br /><br /> <span class='display-path'><strong><?php _e("Path:", 'wpsc'); ?></strong> <?php echo str_replace(ABSPATH, "", WPSC_THEMES_PATH).WPSC_THEME_DIR."/"; ?> </span></p> <?php } else { ?> <p><?php _e("Your theme files have not been moved. Until your theme files have been moved, we have disabled automatic upgrades.", 'wpsc');?> <p><?php printf(__("Click here to <a href='%s'>Move your files</a> to a safe place", 'wpsc'), wp_nonce_url("admin.php?wpsc_admin_action=copy_themes", 'copy_themes') ); ?> </p> <?php } ?> <p><a href='http://www.instinct.co.nz/e-commerce/docs/'><?php _e("Read Tutorials", 'wpsc'); ?></a></p> </div> <div style='clear:both;'></div> <h3 class="form_group"><?php echo TXT_WPSC_PRODUCTS_PAGE_SETTINGS;?></h3> <table class='wpsc_options form-table'> <tr> <th scope="row"><?php echo TXT_WPSC_PRODUCT_DISPLAY;?>:</th> <td> <?php $display_pnp = get_option('product_view'); $product_view1 = null; $product_view2 = null; $product_view3 = null; switch($display_pnp) { case "grid": if(function_exists('product_display_grid')) { $product_view3 = "selected ='selected'"; break; } case "list": if(function_exists('product_display_list')) { $product_view2 = "selected ='selected'"; break; } default: $product_view1 = "selected ='selected'"; break; } if(get_option('list_view_quantity') == 1) { $list_view_quantity_value = "checked='checked'"; } else { $list_view_quantity_value = ''; } if(get_option('show_images_only') == 1) { $show_images_only_value = "checked='checked'"; } else { $show_images_only_value = ''; } if(get_option('display_variations') == 1) { $display_variations = "checked='checked'"; } else { $display_variations = ''; } if(get_option('display_description') == 1) { $display_description = "checked='checked'"; } else { $display_description = ''; } if(get_option('display_addtocart') == 1) { $display_addtocart = "checked='checked'"; } else { $display_addtocart = ''; } if(get_option('display_moredetails') == 1) { $display_moredetails= "checked='checked'"; } else { $display_moredetails = ''; } ?> <select name='wpsc_options[product_view]' onchange="toggle_display_options(this.options[this.selectedIndex].value)"> <option value='default' <?php echo $product_view1; ?>><?php echo TXT_WPSC_DEFAULT;?></option> <?php if(function_exists('product_display_list')) { ?> <option value='list' <?php echo $product_view2; ?>><?php echo TXT_WPSC_LIST;?></option> <?php } else { ?> <option value='list' disabled='disabled' <?php echo $product_view2; ?>><?php echo TXT_WPSC_LIST;?></option> <?php } if(function_exists('product_display_grid')) { ?> <option value='grid' <?php echo $product_view3; ?>><?php echo TXT_WPSC_GRID;?></option> <?php } else { ?> <option value='grid' disabled='disabled' <?php echo $product_view3; ?>><?php echo TXT_WPSC_GRID;?></option> <?php } ?> </select> <?php if(!function_exists('product_display_grid')) { ?><a href='http://www.instinct.co.nz/e-commerce/shop/'><?php echo TXT_WPSC_PURCHASE_UNAVAILABLE; ?></a> <?php } ?> <div id='list_view_options' <?php if(is_null($product_view2)) { echo "style='display:none;'";} ?> > <input type='checkbox' value='1' name='wpsc_options[list_view_quantity]' id='list_view_quantity' <?php echo $list_view_quantity_value;?> /> <label for='list_view_options'><?php echo TXT_WPSC_ADJUSTABLE_QUANTITY;?></label> </div> <div id='grid_view_options' <?php echo $list_view_quantity_style;?> <?php if(is_null($product_view3)) { echo "style='display:none;'";} ?>> <input type='text' name='wpsc_options[grid_number_per_row]' id='grid_number_per_row' size='1' value='<?php echo get_option('grid_number_per_row');?>' /> <label for='grid_number_per_row'><?php echo TXT_SHOW_GRID_PER_ROW;?></label><br /> <input type='hidden' value='0' name='wpsc_options[show_images_only]' /> <input type='checkbox' value='1' name='wpsc_options[show_images_only]' id='show_images_only' <?php echo $show_images_only_value;?> /> <label for='show_images_only'><?php echo TXT_SHOW_IMAGES_ONLY;?></label><br /> <input type='hidden' value='0' name='wpsc_options[display_variations]' /> <input type='checkbox' value='1' name='wpsc_options[display_variations]' id='display_variations' <?php echo $display_variations;?> /> <label for='display_variations'><?php echo TXT_DISPLAY_VARIATIONS;?></label><br /> <input type='hidden' value='0' name='wpsc_options[display_description]' /> <input type='checkbox' value='1' name='wpsc_options[display_description]' id='display_description' <?php echo $display_description;?> /> <label for='display_description'><?php echo TXT_DISPLAY_DESCRIPTION;?></label><br /> <input type='hidden' value='0' name='wpsc_options[display_addtocart]' /> <input type='checkbox' value='1' name='wpsc_options[display_addtocart]' id='display_addtocart' <?php echo $display_addtocart;?> /> <label for='display_addtocart'><?php echo TXT_DISPLAY_ADDTOCART;?></label><br /> <input type='hidden' value='0' name='wpsc_options[display_moredetails]' /> <input type='checkbox' value='1' name='wpsc_options[display_moredetails]' id='display_moredetails' <?php echo $display_moredetails;?> /> <label for='display_moredetails'><?php echo TXT_DISPLAY_MOREDETAILS;?></label> </div> </td> </tr> <?php // } ?> <tr> <th scope="row"><?php echo TXT_WPSC_SELECT_THEME;?>:</th> <td> <?php echo wpsc_list_product_themes(); ?> </td> </tr> <tr> <th scope="row"><?php echo TXT_WPSC_DEFAULTCATEGORY; ?>:</th> <td> <?php echo options_categorylist(); ?> </td> </tr> <?php $wpsc_sort_by = get_option('wpsc_sort_by'); switch($wpsc_sort_by) { case 'name': $wpsc_sort_by1 = "selected ='selected'"; break; case 'price': $wpsc_sort_by2 = "selected ='selected'"; break; case 'id': default: $wpsc_sort_by3 = "selected ='selected'"; break; } ?> <tr> <th scope="row"> <?php echo TXT_WPSC_SORT_PRODUCT_BY;?>: </th> <td> <select name='wpsc_options[wpsc_sort_by]'> <option <?php echo $wpsc_sort_by1; ?> value='name'><?php echo TXT_WPSC_NAME;?></option> <option <?php echo $wpsc_sort_by2; ?> value='price'><?php echo TXT_WPSC_PRICE;?></option> <option <?php echo $wpsc_sort_by3; ?> value='id'><?php echo TXT_WPSC_TIME_UPLOADED;?></option> </select> </td> </tr> <tr> <th scope="row"><?php echo TXT_WPSC_SHOW_BREADCRUMBS;?>:</th> <td> <?php $show_breadcrumbs = get_option('show_breadcrumbs'); $show_breadcrumbs1 = ""; $show_breadcrumbs2 = ""; switch($show_breadcrumbs) { case 0: $show_breadcrumbs2 = "checked ='checked'"; break; case 1: $show_breadcrumbs1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[show_breadcrumbs]' id='show_breadcrumbs1' <?php echo $show_breadcrumbs1; ?> /> <label for='show_breadcrumbs1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[show_breadcrumbs]' id='show_breadcrumbs2' <?php echo $show_breadcrumbs2; ?> /> <label for='show_breadcrumbs2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <tr> <th scope="row"> <?php echo TXT_WPSC_CATSPRODS_DISPLAY_TYPE;?>: </th> <td> <?php $display_pnp = get_option('catsprods_display_type'); $catsprods_display_type1 = ""; $catsprods_display_type2 = ""; switch($display_pnp) { case 0: $catsprods_display_type1 = "checked ='checked'"; break; case 1: $catsprods_display_type2 = "checked ='checked'"; break; } ?> <input type='radio' value='0' name='wpsc_options[catsprods_display_type]' id='catsprods_display_type1' <?php echo $catsprods_display_type1; ?> /> <label for='catsprods_display_type1'><?php echo TXT_WPSC_CATSPRODS_TYPE_CATONLY;?></label> &nbsp; <input type='radio' value='1' name='wpsc_options[catsprods_display_type]' id='catsprods_display_type2' <?php echo $catsprods_display_type2; ?> /> <label for='catsprods_display_type2'><?php echo TXT_WPSC_CATSPRODS_TYPE_SLIDEPRODS;?></label> </td> </tr> <?php if(function_exists('gold_shpcrt_search_form')) { ?> <tr> <th scope="row"><?php echo TXT_WPSC_SHOW_SEARCH;?>:</th> <td> <?php $display_pnp = get_option('show_search'); $show_search1 = ""; $show_search2 = ""; switch($display_pnp) { case 0: $show_search2 = "checked ='checked'"; break; case 1: $show_search1 = "checked ='checked'"; break; } $display_advanced_search = get_option('show_advanced_search'); $show_advanced_search = ""; if($display_advanced_search == 1) { $show_advanced_search = "checked ='checked'"; } $display_live_search = get_option('show_live_search'); if($display_live_search == 1) { $show_live_search = "checked ='checked'"; } if ($show_search1 != "checked ='checked'") { $dis = "style='display:none;'"; } ?> <input type='radio' onclick='jQuery("#wpsc_advanced_search").show()' value='1' name='wpsc_options[show_search]' id='show_search1' <?php echo $show_search1; ?> /> <label for='show_search1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' onclick='jQuery("#wpsc_advanced_search").hide()' value='0' name='wpsc_options[show_search]' id='show_search2' <?php echo $show_search2; ?> /> <label for='show_search2'><?php echo TXT_WPSC_NO;?></label> <div <?php echo $dis;?> id='wpsc_advanced_search'> <input type='hidden' name='wpsc_options[show_advanced_search]' value='0' /> <input type='checkbox' name='wpsc_options[show_advanced_search]' id='show_advanced_search' <?php echo $show_advanced_search; ?> value='1' /> <?php echo TXT_WPSC_SHOWADVANCEDSEARCH;?><br /> <input type='hidden' name='wpsc_options[show_live_search]' value='0' /> <input type='checkbox' name='wpsc_options[show_live_search]' id='show_live_search' <?php echo $show_live_search; ?> value='1' /> <?php echo TXT_WPSC_SHOWLIVESEARCH;?> </div> </td> </tr> <?php } ?> <tr> <th scope="row"><?php echo TXT_WPSC_REPLACE_PAGE_TITLE;?>:</th> <td> <?php $wpsc_replace_page_title = get_option('wpsc_replace_page_title'); $wpsc_replace_page_title1 = ""; $wpsc_replace_page_title2 = ""; switch($wpsc_replace_page_title) { case 0: $wpsc_replace_page_title2 = "checked ='checked'"; break; case 1: $wpsc_replace_page_title1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[wpsc_replace_page_title]' id='wpsc_replace_page_title1' <?php echo $wpsc_replace_page_title1; ?> /> <label for='wpsc_replace_page_title1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[wpsc_replace_page_title]' id='wpsc_replace_page_title2' <?php echo $wpsc_replace_page_title2; ?> /> <label for='wpsc_replace_page_title2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> </table> <h3 class="form_group"><?php echo TXT_WPSC_CARTSETTINGS;?></h3> <table class='wpsc_options form-table'> <tr> <th scope="row"><?php echo TXT_WPSC_CARTLOCATION;?>:</th> <td> <?php $cart_location = get_option('cart_location'); $cart1 = ""; $cart2 = ""; switch($cart_location) { case 1: $cart1 = "checked ='checked'"; break; case 2: $cart2 = "checked ='checked'"; break; case 3: $cart3 = "checked ='checked'"; break; case 4: $cart4 = "checked ='checked'"; break; case 5: $cart5 = "checked ='checked'"; break; } if(function_exists('register_sidebar_widget')) { ?> <input type='radio' value='1' onclick='hideelement1("dropshop_option", this.value)' disabled='disabled' name='wpsc_options[cart_location]' id='cart1' <?php echo $cart1; ?> /> <label style='color: #666666;' for='cart1'><?php echo TXT_WPSC_SIDEBAR;?></label> &nbsp; <?php } else { ?> <input type='radio' value='1' name='wpsc_options[cart_location]' id='cart1' <?php echo $cart1; ?> /> <label for='cart1'><?php echo TXT_WPSC_SIDEBAR;?></label> &nbsp; <?php } ?> <input type='radio' onclick='hideelement1("dropshop_option", this.value)' value='2' name='wpsc_options[cart_location]' id='cart2' <?php echo $cart2; ?> /> <label for='cart2'><?php echo TXT_WPSC_PAGE;?></label> &nbsp; <?php if(function_exists('register_sidebar_widget')) { ?> <input type='radio' value='4' onclick='hideelement1("dropshop_option", this.value)' name='wpsc_options[cart_location]' id='cart4' <?php echo $cart4; ?> /> <label for='cart4'><?php echo TXT_WPSC_WIDGET;?></label> &nbsp; <?php } else { ?> <input type='radio' disabled='disabled' value='4' name='wpsc_options[cart_location]' id='cart4' alt='<?php echo TXT_WPSC_NEEDTOENABLEWIDGET;?>' title='<?php echo TXT_WPSC_NEEDTOENABLEWIDGET;?>' <?php echo $cart4; ?> /> <label style='color: #666666;' for='cart4' title='<?php echo TXT_WPSC_NEEDTOENABLEWIDGET;?>'><?php echo TXT_WPSC_WIDGET;?></label> &nbsp; <?php } if(function_exists('drag_and_drop_cart')) { ?> <input type='radio' onclick='hideelement1("dropshop_option", this.value)' value='5' name='wpsc_options[cart_location]' id='cart5' <?php echo $cart5; ?> /> <label for='cart5'><?php echo TXT_WPSC_GOLD_DROPSHOP;?></label> &nbsp; <?php } else { ?> <input type='radio' disabled='disabled' value='5' name='wpsc_options[cart_location]' id='cart5' alt='<?php echo TXT_WPSC_NEEDTOENABLEWIDGET;?>' title='<?php echo TXT_WPSC_NEEDTOENABLEDROPSHOP;?>' <?php echo $cart5; ?> /> <label style='color: #666666;' for='cart5' title='<?php echo TXT_WPSC_NEEDTOENABLEDROPSHOP;?>'><?php echo TXT_WPSC_GOLD_DROPSHOP;?></label> &nbsp; <?php } ?> <input type='radio' onclick='hideelement1("dropshop_option", this.value)' value='3' name='wpsc_options[cart_location]' id='cart3' <?php echo $cart3; ?> /> <label for='cart3'><?php echo TXT_WPSC_MANUAL;?> <span style='font-size: 7pt;'>(PHP code: &lt;?php echo nzshpcrt_shopping_basket(); ?&gt; )</span></label> <div style='display: <?php if (isset($cart5)) { echo "block"; } else { echo "none"; } ?>;' id='dropshop_option'> <p> <input type="radio" id="drop1" value="all" <?php if (get_option('dropshop_display') == 'all') { echo "checked='checked'"; } ?> name="wpsc_options[dropshop_display]" /><label for="drop1"><?php echo TXT_WPSC_SHOW_DROPSHOP_ALL;?></label> <input type="radio" id="drop2" value="product" <?php if (get_option('dropshop_display') == 'product') { echo "checked='checked'"; } ?> name="wpsc_options[dropshop_display]"/><label for="drop2"><?php echo TXT_WPSC_SHOW_DROPSHOP_PRODUCT;?></label> </p> <p> <input type="radio" id="wpsc_dropshop_theme1" value="light" <?php if (get_option('wpsc_dropshop_theme') != 'dark') { echo "checked='checked'"; } ?> name="wpsc_options[wpsc_dropshop_theme]" /><label for="wpsc_dropshop_theme1"><?php echo TXT_WPSC_DROPSHOP_LIGHT;?></label> <input type="radio" id="wpsc_dropshop_theme2" value="dark" <?php if (get_option('wpsc_dropshop_theme') == 'dark') { echo "checked='checked'"; } ?> name="wpsc_options[wpsc_dropshop_theme]"/><label for="wpsc_dropshop_theme2"><?php echo TXT_WPSC_DROPSHOP_DARK;?></label> <input type="radio" id="wpsc_dropshop_theme3" value="craftyc" <?php if (get_option('wpsc_dropshop_theme') == 'craftyc') { echo "checked='checked'"; } ?> name="wpsc_options[wpsc_dropshop_theme]"/><label for="wpsc_dropshop_theme2"><?php echo TXT_WPSC_DROPSHOP_CRAFTYC;?></label> </p> </div> </td> </tr> <tr> <th scope="row"> <?php echo TXT_WPSC_SHOW_SLIDING_CART;?>: </th> <td> <?php $display_pnp = get_option('show_sliding_cart'); $show_sliding_cart1 = ""; $show_sliding_cart2 = ""; switch($display_pnp) { case 0: $show_sliding_cart2 = "checked ='checked'"; break; case 1: $show_sliding_cart1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[show_sliding_cart]' id='show_sliding_cart1' <?php echo $show_sliding_cart1; ?> /> <label for='show_sliding_cart1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[show_sliding_cart]' id='show_sliding_cart2' <?php echo $show_sliding_cart2; ?> /> <label for='show_sliding_cart2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <tr> <th scope="row"> <?php echo TXT_WPSC_DISPLAY_PLUSTAX;?>: </th> <td> <?php $add_plustax = get_option('add_plustax'); $add_plustax1 = ""; $add_plustax2 = ""; switch($add_plustax) { case 0: $add_plustax2 = "checked ='checked'"; break; case 1: $add_plustax1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[add_plustax]' id='add_plustax1' <?php echo $add_plustax1; ?> /> <label for='add_plustax1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[add_plustax]' id='add_plustax2' <?php echo $add_plustax2; ?> /> <label for='add_plustax2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> </table> <h3 class="form_group"><?php echo TXT_WPSC_GROUP_SETTINGS;?></h3> <table class='wpsc_options form-table'> <tr> <th scope="row"><?php echo TXT_WPSC_SHOW_CATEGORY_DESCRIPTION;?>:</th> <td> <?php $wpsc_category_description = get_option('wpsc_category_description'); $wpsc_category_description1 = ""; $wpsc_category_description2 = ""; switch($wpsc_category_description) { case '1': $wpsc_category_description1 = "checked ='checked'"; break; case '0': default: $wpsc_category_description2 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[wpsc_category_description]' id='wpsc_category_description1' <?php echo $wpsc_category_description1; ?> /> <label for='wpsc_category_description1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[wpsc_category_description]' id='wpsc_category_description2' <?php echo $wpsc_category_description2; ?> /> <label for='wpsc_category_description2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <tr> <th scope="row"> <?php echo TXT_WPSC_SHOWCATEGORYTHUMBNAILS;?>: </th> <td> <?php $show_category_thumbnails = get_option('show_category_thumbnails'); $show_category_thumbnails1 = ""; $show_category_thumbnails2 = ""; switch($show_category_thumbnails) { case 0: $show_category_thumbnails2 = "checked ='checked'"; break; case 1: $show_category_thumbnails1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[show_category_thumbnails]' id='show_category_thumbnails1' <?php echo $show_category_thumbnails1; ?> /> <label for='show_category_thumbnails1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[show_category_thumbnails]' id='show_category_thumbnails2' <?php echo $show_category_thumbnails2; ?> /> <label for='show_category_thumbnails2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <!-- // Adrian - options for displaying number of products per category --> <tr> <th scope="row"> <?php echo TXT_WPSC_SHOW_CATEGORY_COUNT;?>: </th> <td> <?php $display_pnp = get_option('show_category_count'); $show_category_count1 = ""; $show_category_count2 = ""; switch($display_pnp) { case 0: $show_category_count2 = "checked ='checked'"; break; case 1: $show_category_count1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[show_category_count]' id='show_category_count1' <?php echo $show_category_count1; ?> /> <label for='show_category_count1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[show_category_count]' id='show_category_count2' <?php echo $show_category_count2; ?> /> <label for='show_category_count2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <!-- // Adrian - options for displaying category display type --> <tr> <th scope="row"><?php _e("Use Category Grid View",'wpsc');?>:</th> <td> <?php $wpsc_category_grid_view = get_option('wpsc_category_grid_view'); $wpsc_category_grid_view1 = ""; $wpsc_category_grid_view2 = ""; switch($wpsc_category_grid_view) { case '1': $wpsc_category_grid_view1 = "checked ='checked'"; break; case '0': default: $wpsc_category_grid_view2 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[wpsc_category_grid_view]' id='wpsc_category_grid_view1' <?php echo $wpsc_category_grid_view1; ?> /> <label for='wpsc_category_grid_view1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[wpsc_category_grid_view]' id='wpsc_category_grid_view2' <?php echo $wpsc_category_grid_view2; ?> /> <label for='wpsc_category_grid_view2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> </table> <h3 class="form_group"><a name='thumb_settings'><?php echo TXT_WPSC_THUMBNAILSETTINGS;?></a></h3> <table class='wpsc_options form-table'> <?php if(function_exists("getimagesize")) { ?> <tr> <th scope="row"><?php echo TXT_WPSC_PRODUCTTHUMBNAILSIZE;?>:</th> <td> <?php echo TXT_WPSC_HEIGHT;?>:<input type='text' size='6' name='wpsc_options[product_image_height]' class='wpsc_prod_thumb_option' value='<?php echo get_option('product_image_height'); ?>' /> <?php echo TXT_WPSC_WIDTH;?>:<input type='text' size='6' name='wpsc_options[product_image_width]' class='wpsc_prod_thumb_option' value='<?php echo get_option('product_image_width'); ?>' /> <a href="<?php echo wp_nonce_url("admin.php?wpsc_admin_action=mass_resize_thumbnails", 'mass_resize'); ?>" style='visibility:hidden;' class='wpsc_mass_resize' ><?php _e("Resize Existing Thumbnails",'wpsc'); ?></a> <br /> </td> </tr> <tr> <th scope="row"> <?php echo TXT_WPSC_CATEGORYTHUMBNAILSIZE;?>: </th> <td> <?php echo TXT_WPSC_HEIGHT;?>:<input type='text' size='6' name='wpsc_options[category_image_height]' value='<?php echo get_option('category_image_height'); ?>' /> <?php echo TXT_WPSC_WIDTH;?>:<input type='text' size='6' name='wpsc_options[category_image_width]' value='<?php echo get_option('category_image_width'); ?>' /> </td> </tr> <tr> <th scope="row"> <?php echo TXT_WPSC_SINGLE_PRODUCTTHUMBNAILSIZE;?>: </th> <td> <?php echo TXT_WPSC_HEIGHT;?>:<input type='text' size='6' name='wpsc_options[single_view_image_height]' value='<?php echo get_option('single_view_image_height'); ?>' /> <?php echo TXT_WPSC_WIDTH;?>:<input type='text' size='6' name='wpsc_options[single_view_image_width]' value='<?php echo get_option('single_view_image_width'); ?>' /> </td> </tr> <?php } ?> <tr> <th scope="row"><?php echo TXT_WPSC_SHOWTHUMBNAILS;?>:</th> <td> <?php $show_thumbnails = get_option('show_thumbnails'); $show_thumbnails1 = ""; $show_thumbnails2 = ""; switch($show_thumbnails) { case 0: $show_thumbnails2 = "checked ='checked'"; break; case 1: $show_thumbnails1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[show_thumbnails]' id='show_thumbnails1' <?php echo $show_thumbnails1; ?> /> <label for='show_thumbnails1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[show_thumbnails]' id='show_thumbnails2' <?php echo $show_thumbnails2; ?> /> <label for='show_thumbnails2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <?php if(function_exists('gold_shpcrt_display_gallery')) { ?> <tr> <th scope="row"> <?php echo TXT_WPSC_SHOW_GALLERY;?>: </th> <td> <?php $display_pnp = get_option('show_gallery'); $show_gallery1 = ""; $show_gallery2 = ""; switch($display_pnp) { case 0: $show_gallery2 = "checked ='checked'"; break; case 1: $show_gallery1 = "checked ='checked'"; break; } ?> <input type='radio' value='1' name='wpsc_options[show_gallery]' id='show_gallery1' <?php echo $show_gallery1; ?> /> <label for='show_gallery1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input type='radio' value='0' name='wpsc_options[show_gallery]' id='show_gallery2' <?php echo $show_gallery2; ?> /> <label for='show_gallery2'><?php echo TXT_WPSC_NO;?></label> </td> </tr> <tr> <th scope="row"> <?php _e("Gallery Thumbnail Image Size");?>: </th> <td> <?php echo TXT_WPSC_HEIGHT;?>:<input type='text' size='6' name='wpsc_options[wpsc_gallery_image_height]' value='<?php echo get_option('wpsc_gallery_image_height'); ?>' /> <?php echo TXT_WPSC_WIDTH;?>:<input type='text' size='6' name='wpsc_options[wpsc_gallery_image_width]' value='<?php echo get_option('wpsc_gallery_image_width'); ?>' /> <br /> </td> </tr> <?php } ?> </table> <h3 class="form_group"><?php echo TXT_WPSC_PAGESETTINGS;?></h3> <table class='wpsc_options form-table'> <tr> <th scope="row"> <?php echo TXT_WPSC_USE_PAGINATION;?>: </th> <td> <?php $use_pagination = get_option('use_pagination'); $use_pagination1 = ""; $use_pagination2 = ""; switch($use_pagination) { case 0: $use_pagination2 = "checked ='checked'"; $page_count_display_state = 'style=\'display: none;\''; break; case 1: $use_pagination1 = "checked ='checked'"; $page_count_display_state = ''; break; } ?> <input onclick='jQuery("#wpsc_products_per_page").show()' type='radio' value='1' name='wpsc_options[use_pagination]' id='use_pagination1' <?php echo $use_pagination1; ?> /> <label for='use_pagination1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input onclick='jQuery("#wpsc_products_per_page").hide()' type='radio' value='0' name='wpsc_options[use_pagination]' id='use_pagination2' <?php echo $use_pagination2; ?> /> <label for='use_pagination2'><?php echo TXT_WPSC_NO;?></label><br /> <div id='wpsc_products_per_page' <?php echo $page_count_display_state; ?> > <input type='text' size='6' name='wpsc_options[wpsc_products_per_page]' value='<?php echo get_option('wpsc_products_per_page'); ?>' /> <?php echo TXT_WPSC_OPTION_PRODUCTS_PER_PAGE; ?> </div> </td> </tr> <tr> <th scope="row"> <?php echo TXT_WPSC_PAGE_NUMBER_POSITION;?>: </th> <td> <input type='radio' value='1' name='wpsc_options[wpsc_page_number_position]' id='wpsc_page_number_position1' <?php if (get_option('wpsc_page_number_position') == 1) { echo "checked='checked'"; } ?> /><label for='wpsc_page_number_position1'><?php echo TXT_WPSC_PAGENUMBER_POSITION_TOP; ?></label>&nbsp; <input type='radio' value='2' name='wpsc_options[wpsc_page_number_position]' id='wpsc_page_number_position2' <?php if (get_option('wpsc_page_number_position') == 2) { echo "checked='checked'"; } ?> /><label for='wpsc_page_number_position2'><?php echo TXT_WPSC_PAGENUMBER_POSITION_BOTTOM; ?></label>&nbsp; <input type='radio' value='3' name='wpsc_options[wpsc_page_number_position]' id='wpsc_page_number_position3' <?php if (get_option('wpsc_page_number_position') == 3) { echo "checked='checked'"; } ?> /><label for='wpsc_page_number_position3'><?php echo TXT_WPSC_PAGENUMBER_POSITION_BOTH; ?></label> <br /> </td> </tr> </table> <h3 class="form_group"><?php echo TXT_WPSC_COMMENTSETTINGS;?></h3> <table class='wpsc_options form-table'> <tr> <th scope="row"> <?php echo TXT_WPSC_ENABLE_COMMENTS;?>: <a href="http://intensedebate.com/" title="IntenseDebate comments enhance and encourage conversation on your blog or website" target="_blank"><img src="<?php echo WPSC_URL; ?>/images/intensedebate-logo.png" alt="intensedebate-logo" title="IntenseDebate"/></a> </th> <td> <?php $enable_comments = get_option('wpsc_enable_comments'); $enable_comments1 = ""; $enable_comments2 = ""; switch($enable_comments) { case 1: $enable_comments1 = "checked ='checked'"; $intense_debate_account_id_display_state = ''; break; default: case 0: $enable_comments2 = "checked ='checked'"; $intense_debate_account_id_display_state = 'style=\'display: none;\''; break; } ?> <input onclick='jQuery("#wpsc_enable_comments,.wpsc_comments_details").show()' type='radio' value='1' name='wpsc_options[wpsc_enable_comments]' id='wpsc_enable_comments1' <?php echo $enable_comments1; ?> /> <label for='wpsc_enable_comments1'><?php echo TXT_WPSC_YES;?></label> &nbsp; <input onclick='jQuery("#wpsc_enable_comments,.wpsc_comments_details").hide()' type='radio' value='0' name='wpsc_options[wpsc_enable_comments]' id='wpsc_enable_comments2' <?php echo $enable_comments2; ?> /> <label for='wpsc_enable_comments1'><?php echo TXT_WPSC_NO;?></label><br /> <div id='wpsc_enable_comments' <?php echo $intense_debate_account_id_display_state; ?> > <?php echo TXT_WPSC_INTENSE_DEBATE_ACCOUNT_ID; ?>:<br/> <input type='text' size='30' name='wpsc_options[wpsc_intense_debate_account_id]' value='<?php echo get_option('wpsc_intense_debate_account_id'); ?>' /><br/> <small><a href='http://intensedebate.com/sitekey/' title='Help finding the Account ID'><?php _e('Help on finding the Account ID'); ?></a></small> </div> </td> </tr> <tr> <th scope="row"> <div class='wpsc_comments_details' <?php echo $intense_debate_account_id_display_state ?> > <?php echo TXT_WPSC_COMMENTS_WHICH_PRODUCTS;?>: </div> </th> <td> <div class='wpsc_comments_details' <?php echo $intense_debate_account_id_display_state ?> > <input type='radio' value='1' name='wpsc_options[wpsc_comments_which_products]' id='wpsc_comments_which_products1' <?php if (get_option('wpsc_comments_which_products') == 1 || !get_option('wpsc_comments_which_products')) { echo "checked='checked'"; } ?> /><label for='wpsc_comments_which_products1'>All Products</label>&nbsp; <input type='radio' value='2' name='wpsc_options[wpsc_comments_which_products]' id='wpsc_comments_which_products2' <?php if (get_option('wpsc_comments_which_products') == 2) { echo "checked='checked'"; } ?> /><label for='wpsc_comments_which_products2'>Per Product</label>&nbsp; <br /> </div> </td> </tr> </table> <?php /* here end the presentation options */ ?> <div class="submit"> <input type='hidden' name='wpsc_admin_action' value='submit_options' /> <?php wp_nonce_field('update-options', 'wpsc-update-options'); ?> <input type="submit" value="<?php echo TXT_WPSC_UPDATE_BUTTON;?>" name="updateoption" /> </div> </div> </form> <?php } ?>
gpl-2.0
AweSamNet/Sdl-Community-Legacy-Support
Post Edit Compare/Sdl.Community.PostEdit.Compare.Core/Comparison/Comparer.cs
34868
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Sdl.Community.PostEdit.Compare.Core.Comparison.Text; using Sdl.Community.PostEdit.Compare.Core.Reports; using Sdl.Community.PostEdit.Compare.Core.SDLXLIFF; namespace Sdl.Community.PostEdit.Compare.Core.Comparison { public partial class Comparer : TextComparer { internal delegate void ChangedEventHandler(int maximum, int current, int percent, string message); internal event ChangedEventHandler Progress; private Dictionary<string, ParagraphUnit> GetUpdatedParagraphsIds(Dictionary<string, ParagraphUnit> original, Dictionary<string, ParagraphUnit> updated) { var updatedUnit = new Dictionary<string, ParagraphUnit>(); var indexOriginal = 0; foreach (var kvpOriginal in original) { var indexUpdated = 0; foreach (var kvpUpdated in updated) { if (indexOriginal == indexUpdated) { updatedUnit.Add(kvpOriginal.Key, kvpUpdated.Value); break; } indexUpdated++; } indexOriginal++; } return updatedUnit; } internal Dictionary<string, Dictionary<string, ComparisonParagraphUnit>> GetComparisonParagraphUnits(Dictionary<string, Dictionary<string, ParagraphUnit>> xFileParagraphUnitsOriginal , Dictionary<string, Dictionary<string, ParagraphUnit>> xFileParagraphUnitsUpdated) { var comparisonFileParagraphUnits = new Dictionary<string, Dictionary<string, ComparisonParagraphUnit>>(); var iProgressCurrent = 0; var iProgressMaximum = xFileParagraphUnitsOriginal.Sum(xFileParagraphUnits => xFileParagraphUnits.Value.Count()); var errorMatchingFileLevel01 = false; var errorMatchingFileLevel = false; var errorMatchingFileLevelMessage = string.Empty; var errorMatchingParagraphLevel = false; #region | check for initial errors | foreach (var fileParagraphUnitOriginal in xFileParagraphUnitsOriginal) { if (!xFileParagraphUnitsUpdated.ContainsKey(fileParagraphUnitOriginal.Key)) { errorMatchingFileLevel = true; errorMatchingFileLevelMessage = string.Format( "Error: Structure mismatch; unable to locate the corresponding file : '{0}' in the updated file", fileParagraphUnitOriginal.Key); var fileNameOriginal = Path.GetFileName(fileParagraphUnitOriginal.Key); errorMatchingFileLevel01 = xFileParagraphUnitsUpdated.Select(kvp => Path.GetFileName(kvp.Key)).All(fileNameUpdated => string.Compare(fileNameOriginal, fileNameUpdated, StringComparison.OrdinalIgnoreCase) != 0); break; } var fileParagraphUnitUpdated = xFileParagraphUnitsUpdated[fileParagraphUnitOriginal.Key]; if ((from paragraphUnitOriginalPair in fileParagraphUnitOriginal.Value select paragraphUnitOriginalPair.Value into paragraphUnitOriginal let paragraphUnitUpdated = new ParagraphUnit(paragraphUnitOriginal.ParagraphUnitId, new List<SegmentPair>()) select paragraphUnitOriginal).Any(paragraphUnitOriginal => !fileParagraphUnitUpdated.ContainsKey(paragraphUnitOriginal.ParagraphUnitId))) { errorMatchingParagraphLevel = true; } } #endregion if (errorMatchingFileLevel01) { //not possible to compare these files; excluding the file path information, the file names are different... throw new Exception(errorMatchingFileLevelMessage); } if (errorMatchingFileLevel || errorMatchingParagraphLevel) { #region | compare structure missmatch | foreach (var fileParagraphUnitOriginal in xFileParagraphUnitsOriginal) { var fileName = Path.GetFileName(fileParagraphUnitOriginal.Key); var comparisonParagraphUnits = new Dictionary<string, ComparisonParagraphUnit>(); var fileParagraphUnitOriginalTmp = fileParagraphUnitOriginal.Value; var nameOriginal = Path.GetFileName(fileParagraphUnitOriginal.Key); var fileParagraphUnitUpdated = (from kvp in xFileParagraphUnitsUpdated let fileNameUpdated = Path.GetFileName(kvp.Key) where string.Compare(nameOriginal, fileNameUpdated, StringComparison.OrdinalIgnoreCase) == 0 select kvp.Value).FirstOrDefault(); if (fileParagraphUnitUpdated == null) { throw new Exception( string.Format( "Error: Structure mismatch; unable to locate the corresponding file : '{0}' in the updated file", fileParagraphUnitOriginal.Key)); } //update paragraph ids in the updated object xFileParagraphUnit_updated fileParagraphUnitUpdated = GetUpdatedParagraphsIds(fileParagraphUnitOriginalTmp, fileParagraphUnitUpdated); foreach (var paragraphUnitOriginalPair in fileParagraphUnitOriginalTmp) { OnProgress(iProgressMaximum, iProgressCurrent++, fileName); var comparisonParagraphUnit = new ComparisonParagraphUnit { ParagraphId = paragraphUnitOriginalPair.Key, ParagraphIsUpdated = false, ParagraphStatusChanged = false, ParagraphHasComments = false }; var paragraphUnitOriginal = paragraphUnitOriginalPair.Value; var paragraphUnitUpdated = new ParagraphUnit(paragraphUnitOriginal.ParagraphUnitId, new List<SegmentPair>()); if (fileParagraphUnitUpdated.ContainsKey(paragraphUnitOriginal.ParagraphUnitId)) paragraphUnitUpdated = fileParagraphUnitUpdated[paragraphUnitOriginal.ParagraphUnitId]; if (paragraphUnitUpdated != null) { if (paragraphUnitOriginal.SegmentPairs.Count >= paragraphUnitUpdated.SegmentPairs.Count) { #region | xParagraphUnit_original.xSegmentPairs.Count >= xParagraphUnit_updated.xSegmentPairs.Count | //if segment count has not changed (or greater than the segment count in the updated file) for (var i = 0; i < paragraphUnitOriginal.SegmentPairs.Count; i++) { var segmentPairOriginal = paragraphUnitOriginal.SegmentPairs[i]; var segmentPairUpdated = new SegmentPair(); if (paragraphUnitUpdated.SegmentPairs.Count > i) segmentPairUpdated = paragraphUnitUpdated.SegmentPairs[i]; var comparisonSegmentUnit = new ComparisonSegmentUnit(segmentPairOriginal.Id, segmentPairOriginal.SourceSections, segmentPairOriginal.TargetSections, segmentPairUpdated.TargetSections, segmentPairOriginal.IsLocked); AddToComparision(ref comparisonParagraphUnit, comparisonSegmentUnit, segmentPairOriginal, segmentPairUpdated); } #endregion } else if (paragraphUnitOriginal.SegmentPairs.Count < paragraphUnitUpdated.SegmentPairs.Count) { #region | xParagraphUnit_original.xSegmentPairs.Count < xParagraphUnit_updated.xSegmentPairs.Count | //if more segments now exist in the updated file for (var i = 0; i < paragraphUnitUpdated.SegmentPairs.Count; i++) { var segmentPairOriginal = new SegmentPair(); if (paragraphUnitOriginal.SegmentPairs.Count > i) segmentPairOriginal = paragraphUnitOriginal.SegmentPairs[i]; var segmentPairUpdated = paragraphUnitUpdated.SegmentPairs[i]; var comparisonSegmentUnit = new ComparisonSegmentUnit(segmentPairUpdated.Id, segmentPairOriginal.SourceSections, segmentPairOriginal.TargetSections, segmentPairUpdated.TargetSections, segmentPairOriginal.IsLocked); AddToComparision(ref comparisonParagraphUnit, comparisonSegmentUnit, segmentPairOriginal, segmentPairUpdated); } #endregion } } else { #region | else | foreach (var segmentPairOriginal in paragraphUnitOriginal.SegmentPairs) { var segmentPairUpdated = new SegmentPair(); var comparisonSegmentUnit = new ComparisonSegmentUnit(segmentPairOriginal.Id, segmentPairOriginal.SourceSections, segmentPairOriginal.TargetSections, segmentPairUpdated.TargetSections, segmentPairOriginal.IsLocked); AddToComparision(ref comparisonParagraphUnit, comparisonSegmentUnit, segmentPairOriginal, segmentPairUpdated); } #endregion } comparisonParagraphUnits.Add(comparisonParagraphUnit.ParagraphId, comparisonParagraphUnit); } comparisonFileParagraphUnits.Add(fileParagraphUnitOriginal.Key, comparisonParagraphUnits); } #endregion } else { #region | compare normal | foreach (var fileParagraphUnitOriginal in xFileParagraphUnitsOriginal) { var fileName = Path.GetFileName(fileParagraphUnitOriginal.Key); var comparisonParagraphUnits = new Dictionary<string, ComparisonParagraphUnit>(); if (!xFileParagraphUnitsUpdated.ContainsKey(fileParagraphUnitOriginal.Key)) throw new Exception( string.Format( "Error: Structure mismatch; unable to locate the corresponding file : '{0}' in the updated file", fileParagraphUnitOriginal.Key)); var fileParagraphUnitUpdated = xFileParagraphUnitsUpdated[fileParagraphUnitOriginal.Key]; foreach (var paragraphUnitOriginalPair in fileParagraphUnitOriginal.Value) { OnProgress(iProgressMaximum, iProgressCurrent++, fileName); var comparisonParagraphUnit = new ComparisonParagraphUnit { ParagraphId = paragraphUnitOriginalPair.Key, ParagraphIsUpdated = false, ParagraphStatusChanged = false, ParagraphHasComments = false }; var paragraphUnitOriginal = paragraphUnitOriginalPair.Value; ParagraphUnit paragraphUnitUpdated; if (fileParagraphUnitUpdated.ContainsKey(paragraphUnitOriginal.ParagraphUnitId)) paragraphUnitUpdated = fileParagraphUnitUpdated[paragraphUnitOriginal.ParagraphUnitId]; else throw new Exception( string.Format( "Error: Structure mismatch; unable to locate the corresponding paragraph ID: '{0}' in the updated file", paragraphUnitOriginal.ParagraphUnitId)); if (paragraphUnitOriginal.SegmentPairs.Count >= paragraphUnitUpdated.SegmentPairs.Count) { #region | xParagraphUnit_original.xSegmentPairs.Count >= xParagraphUnit_updated.xSegmentPairs.Count | //if segment count has not changed (or greater than the segment count in the updated file) for (var i = 0; i < paragraphUnitOriginal.SegmentPairs.Count; i++) { var segmentPairOriginal = paragraphUnitOriginal.SegmentPairs[i]; var segmentPairUpdated = new SegmentPair(); if (paragraphUnitUpdated.SegmentPairs.Count > i) segmentPairUpdated = paragraphUnitUpdated.SegmentPairs[i]; var comparisonSegmentUnit = new ComparisonSegmentUnit(segmentPairOriginal.Id, segmentPairOriginal.SourceSections, segmentPairOriginal.TargetSections, segmentPairUpdated.TargetSections, segmentPairOriginal.IsLocked); AddToComparision(ref comparisonParagraphUnit, comparisonSegmentUnit, segmentPairOriginal, segmentPairUpdated); } #endregion } else if (paragraphUnitOriginal.SegmentPairs.Count < paragraphUnitUpdated.SegmentPairs.Count) { #region | xParagraphUnit_original.xSegmentPairs.Count < xParagraphUnit_updated.xSegmentPairs.Count | //if more segments now exist in the updated file for (var i = 0; i < paragraphUnitUpdated.SegmentPairs.Count; i++) { var segmentPairOriginal = new SegmentPair(); if (paragraphUnitOriginal.SegmentPairs.Count > i) segmentPairOriginal = paragraphUnitOriginal.SegmentPairs[i]; var segmentPairUpdated = paragraphUnitUpdated.SegmentPairs[i]; var comparisonSegmentUnit = new ComparisonSegmentUnit(segmentPairUpdated.Id, segmentPairOriginal.SourceSections, segmentPairOriginal.TargetSections, segmentPairUpdated.TargetSections, segmentPairOriginal.IsLocked); AddToComparision(ref comparisonParagraphUnit, comparisonSegmentUnit, segmentPairOriginal, segmentPairUpdated); } #endregion } comparisonParagraphUnits.Add(comparisonParagraphUnit.ParagraphId, comparisonParagraphUnit); } comparisonFileParagraphUnits.Add(fileParagraphUnitOriginal.Key, comparisonParagraphUnits); } #endregion } return comparisonFileParagraphUnits; } public static int CalculateWordsForPercentage(SegmentSection segmentSection, ref int placeables, ref string updatedContent) { var wordCounter = 0; var placeablecounter = 0; var strWords = new List<string>(); if (segmentSection.Content == null || segmentSection.Type != SegmentSection.ContentType.Text) return wordCounter; if (segmentSection.RevisionMarker != null && segmentSection.RevisionMarker.Type == RevisionMarker.RevisionType.Delete) { //ignore } else { var content = segmentSection.Content; //date {and time?} if (content.IndexOfAny(new[] { '-', '/', ':', '.', '\\' }) > -1) { content = Regex.Replace(content, @"(?<b1>\b)(?<xdf>\d{2,4}[\/\-\\]\d{1,2}[\/\-\\]\d{2,4})(?<b2>\b)", delegate(Match match) { placeablecounter++; var b1 = match.Groups["b1"].Value; var xdf = match.Groups["xdf"].Value; var b2 = match.Groups["b2"].Value; return b1 + "-_-_-_date_-_-_-" + b2; }); } content = content.Replace("-_-_-_date_-_-_-", string.Empty); //url if (content.ToLower().IndexOf("http", StringComparison.Ordinal) > -1 || content.ToLower().IndexOf("https", StringComparison.Ordinal) > -1 || content.ToLower().IndexOf("ftp", StringComparison.Ordinal) > -1) { content = Regex.Replace(content, @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$", delegate { placeablecounter++; return "-_-_-_webpage_-_-_-"; }); } content = content.Replace("-_-_-_webpage_-_-_-", string.Empty); //curr and digit if (content.IndexOfAny(new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }) > -1) { content = Regex.Replace(content, @"(p{Sc}|)\d+[\.\,\d]*", delegate { placeablecounter++; return "-_-_-_number_-_-_-"; }); } content = content.Replace("-_-_-_number_-_-_-", string.Empty); placeables = placeablecounter; updatedContent = content; var charArray = content.ToCharArray(); var strWord = string.Empty; foreach (var chr in charArray) { if (char.IsControl(chr) || char.IsWhiteSpace(chr) || Encoding.UTF8.GetByteCount(chr.ToString()) > 2) { strWords.Add(strWord); strWord = string.Empty; } else if (chr == '/' || chr == '\\') { if (strWord.Trim() != string.Empty) { strWords.Add(strWord); strWord = string.Empty; } else { strWord += chr.ToString(); } } else //if (!char.IsPunctuation(chr)) { strWord += chr.ToString(); } } if (strWord.Trim() != string.Empty) { strWords.Add(strWord); strWord = string.Empty; } foreach (var word in strWords) { if (word.Length == 1) { var _char = Convert.ToChar(word); //var b1 = char.IsControl(_char); //var b2 = char.IsWhiteSpace(_char); //var b3 = char.IsPunctuation(_char); //var b4 = char.IsSeparator(_char); if (!char.IsControl(_char) && !char.IsWhiteSpace(_char) && !char.IsPunctuation(_char)) { wordCounter++; } } else if (word.Trim() != string.Empty) { wordCounter++; } } } return wordCounter; } public static void GetStatisticalContentCounts(List<SegmentSection> segmentSections, ref int words, ref int chars, ref int tags, ref int placeholders) { foreach (var segmentSection in segmentSections) { if (segmentSection.Type == SegmentSection.ContentType.Text) { if (segmentSection.RevisionMarker != null && segmentSection.RevisionMarker.Type == RevisionMarker.RevisionType.Delete) { //ignore from the comparison process } else { var placeables = 0; var updatedContent = segmentSection.Content; words += CalculateWordsForPercentage(segmentSection, ref placeables, ref updatedContent); placeholders += placeables; chars += updatedContent.ToCharArray().Length; } } else { if (segmentSection.RevisionMarker != null && segmentSection.RevisionMarker.Type == RevisionMarker.RevisionType.Delete) { //ignore from the comparison process } else { if (segmentSection.Type == SegmentSection.ContentType.Placeholder) placeholders++; else tags++; } } } } private void AddToComparision(ref ComparisonParagraphUnit comparisonParagraphUnit , ComparisonSegmentUnit comparisonSegmentUnit , SegmentPair segmentPairOriginal , SegmentPair segmentPairUpdated) { comparisonSegmentUnit.SegmentStatusOriginal = segmentPairOriginal.SegmentStatus; comparisonSegmentUnit.SegmentStatusUpdated = segmentPairUpdated.SegmentStatus; comparisonSegmentUnit.TranslationStatusOriginal = GetTranslationStatus(segmentPairOriginal); comparisonSegmentUnit.TranslationStatusUpdated = GetTranslationStatus(segmentPairUpdated); if (segmentPairOriginal.TranslationOrigin != null) comparisonSegmentUnit.TranslationOriginTypeOriginal = segmentPairOriginal.TranslationOrigin.OriginType; if (segmentPairUpdated.TranslationOrigin != null) comparisonSegmentUnit.TranslationOriginTypeUpdated = segmentPairUpdated.TranslationOrigin.OriginType; if (string.CompareOrdinal(segmentPairOriginal.Target, segmentPairUpdated.Target) != 0) { comparisonSegmentUnit.ComparisonTextUnits = GetComparisonTextUnits(segmentPairOriginal.TargetSections, segmentPairUpdated.TargetSections); comparisonSegmentUnit.SegmentTextUpdated = true; comparisonParagraphUnit.ParagraphIsUpdated = true; } comparisonSegmentUnit.SourceWordsOriginal = segmentPairOriginal.SourceWords; comparisonSegmentUnit.SourceCharsOriginal = segmentPairOriginal.SourceChars; comparisonSegmentUnit.SourceTagsOriginal = segmentPairOriginal.SourceTags; comparisonSegmentUnit.SourceWordsUpdated = segmentPairUpdated.SourceWords; comparisonSegmentUnit.SourceCharsUpdated = segmentPairUpdated.SourceChars; comparisonSegmentUnit.SourceTagsUpdated = segmentPairUpdated.SourceTags; if (string.Compare(comparisonSegmentUnit.SegmentStatusOriginal, comparisonSegmentUnit.SegmentStatusUpdated, StringComparison.OrdinalIgnoreCase) != 0) { comparisonSegmentUnit.SegmentSegmentStatusUpdated = true; comparisonParagraphUnit.ParagraphStatusChanged = true; } if (segmentPairUpdated.Comments != null && segmentPairUpdated.Comments.Count > 0) { comparisonSegmentUnit.Comments = segmentPairUpdated.Comments; comparisonSegmentUnit.SegmentHasComments = true; comparisonParagraphUnit.ParagraphHasComments = true; } comparisonSegmentUnit.TargetOriginalRevisionMarkers = new List<SegmentSection>(); foreach (var section in segmentPairOriginal.TargetSections) { if (section.RevisionMarker != null) { comparisonSegmentUnit.TargetOriginalRevisionMarkers.Add(section); } } comparisonSegmentUnit.TargetUpdatedRevisionMarkers = new List<SegmentSection>(); foreach (var section in segmentPairUpdated.TargetSections) { if (section.RevisionMarker != null) { comparisonSegmentUnit.TargetUpdatedRevisionMarkers.Add(section); } } comparisonParagraphUnit.ComparisonSegmentUnits.Add(comparisonSegmentUnit); } private static string GetTranslationStatus(SegmentPair segmentPair) { var match = string.Empty; if (segmentPair.TranslationOrigin == null) return match; if (segmentPair.TranslationOrigin.MatchPercentage >= 100) { if (string.Compare(segmentPair.TranslationOrigin.OriginType, "document-match", StringComparison.OrdinalIgnoreCase) == 0) { match = "PM"; } else if (string.Compare(segmentPair.TranslationOrigin.TextContextMatchLevel, "SourceAndTarget", StringComparison.OrdinalIgnoreCase) == 0) { match = "CM"; } else if (string.Compare(segmentPair.TranslationOrigin.OriginType, "mt", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(segmentPair.TranslationOrigin.OriginType, "amt", StringComparison.OrdinalIgnoreCase) == 0) { match = "AT"; } else { match = segmentPair.TranslationOrigin.MatchPercentage + "%"; } } else if (string.Compare(segmentPair.TranslationOrigin.OriginType, "mt", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(segmentPair.TranslationOrigin.OriginType, "amt", StringComparison.OrdinalIgnoreCase) == 0) { match = "AT"; } else if (segmentPair.TranslationOrigin.MatchPercentage > 0) { match = segmentPair.TranslationOrigin.MatchPercentage + "%"; } else { match = ""; } return match; } internal void OnProgress(int maximum, int current, string message) { if (Progress == null) return; var percent = Convert.ToInt32(current <= maximum && maximum > 0 ? Convert.ToDecimal(current) / Convert.ToDecimal(maximum) * Convert.ToDecimal(100) : maximum); Progress(maximum, current, percent, message); } internal static int LevenshteinDistance(string s, string t) { // degenerate cases if (s == t) return 0; if (s.Length == 0) return t.Length; if (t.Length == 0) return s.Length; // create two work vectors of integer distances var v0 = new int[t.Length + 1]; var v1 = new int[t.Length + 1]; // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t for (var i = 0; i < v0.Length; i++) v0[i] = i; for (var i = 0; i < s.Length; i++) { // calculate v1 (current row distances) from the previous row v0 // first element of v1 is A[i+1][0] // edit distance is delete (i+1) chars from s to match empty t v1[0] = i + 1; // use formula to fill in the rest of the row for (var j = 0; j < t.Length; j++) { var cost = s[i] == t[j] ? 0 : 1; //v1[j + 1] = minimumn(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost); v1[j + 1] = Math.Min(v1[j] + 1, Math.Min(v0[j + 1] + 1, v0[j] + cost)) + 1; } // copy v1 (current row) to v0 (previous row) for next interation for (var j = 0; j < v0.Length; j++) v0[j] = v1[j]; } return v1[t.Length]; } private static List<string> GetSectionsList(IReadOnlyList<SegmentSection> segmentSections, ref int charsLength) { var items = new List<string>(); foreach (var section in segmentSections) { if (section.RevisionMarker != null && section.RevisionMarker.Type == RevisionMarker.RevisionType.Delete) { //ignore from the comparison process } else { if (section.Type == SegmentSection.ContentType.Text) { var strLists = ReportUtils.GetTextSections(section.Content); foreach (var part in strLists) { foreach (var letter in part) { items.Add(letter.ToString()); charsLength++; } } } else { charsLength++; items.Add(section.Content); } } } return items; } internal static int DamerauLevenshteinDistanceFromObject(List<SegmentSection> source, List<SegmentSection> target) { var sourceLen = 0; var sourceItems = GetSectionsList(source, ref sourceLen); var targetLen = 0; var targetItems = GetSectionsList(target, ref targetLen); if (sourceLen == 0) return targetLen == 0 ? 0 : targetLen; if (targetLen == 0) return sourceLen; var score = new int[sourceLen + 2, targetLen + 2]; var inf = sourceLen + targetLen; score[0, 0] = inf; for (var i = 0; i <= sourceLen; i++) { score[i + 1, 1] = i; score[i + 1, 0] = inf; } for (var j = 0; j <= targetLen; j++) { score[1, j + 1] = j; score[0, j + 1] = inf; } var sd = new SortedDictionary<string, int>(); var fullList = new List<string>(); fullList.AddRange(sourceItems); fullList.AddRange(targetItems); foreach (var item in fullList) { if (!sd.ContainsKey(item)) sd.Add(item, 0); } for (var i = 1; i <= sourceLen; i++) { var db = 0; for (var j = 1; j <= targetLen; j++) { var i1 = sd[targetItems[j - 1]]; var j1 = db; if (sourceItems[i - 1] == targetItems[j - 1]) { score[i + 1, j + 1] = score[i, j]; db = j; } else { score[i + 1, j + 1] = Math.Min(score[i, j], Math.Min(score[i + 1, j], score[i, j + 1])) + 1; } score[i + 1, j + 1] = Math.Min(score[i + 1, j + 1], score[i1, j1] + (i - i1 - 1) + 1 + (j - j1 - 1)); } sd[sourceItems[i - 1]] = i; } return score[sourceLen + 1, targetLen + 1]; } public static int DamerauLevenshteinDistance(string source, string target) { if (string.IsNullOrEmpty(source)) { return string.IsNullOrEmpty(target) ? 0 : target.Length; } if (string.IsNullOrEmpty(target)) { return source.Length; } var score = new int[source.Length + 2, target.Length + 2]; var inf = source.Length + target.Length; score[0, 0] = inf; for (var i = 0; i <= source.Length; i++) { score[i + 1, 1] = i; score[i + 1, 0] = inf; } for (var j = 0; j <= target.Length; j++) { score[1, j + 1] = j; score[0, j + 1] = inf; } var sd = new SortedDictionary<char, int>(); foreach (var letter in source + target) { if (!sd.ContainsKey(letter)) sd.Add(letter, 0); } for (var i = 1; i <= source.Length; i++) { var db = 0; for (var j = 1; j <= target.Length; j++) { var i1 = sd[target[j - 1]]; var j1 = db; if (source[i - 1] == target[j - 1]) { score[i + 1, j + 1] = score[i, j]; db = j; } else { score[i + 1, j + 1] = Math.Min(score[i, j], Math.Min(score[i + 1, j], score[i, j + 1])) + 1; } score[i + 1, j + 1] = Math.Min(score[i + 1, j + 1], score[i1, j1] + (i - i1 - 1) + 1 + (j - j1 - 1)); } sd[source[i - 1]] = i; } return score[source.Length + 1, target.Length + 1]; } } }
gpl-2.0
BunnyWei/truffle-llvmir
graal/com.oracle.graal.java/src/com/oracle/graal/java/AbstractFrameStateBuilder.java
13424
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.java; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.java.BciBlockMapping.BciBlock; public abstract class AbstractFrameStateBuilder<T extends KindProvider, S extends AbstractFrameStateBuilder<T, S>> { protected final ResolvedJavaMethod method; protected int stackSize; protected final T[] locals; protected final T[] stack; protected T[] lockedObjects; /** * Specifies if asserting type checks are enabled. */ protected final boolean checkTypes; /** * @see BytecodeFrame#rethrowException */ protected boolean rethrowException; public AbstractFrameStateBuilder(ResolvedJavaMethod method, boolean checkTypes) { this.method = method; this.locals = allocateArray(method.getMaxLocals()); this.stack = allocateArray(Math.max(1, method.getMaxStackSize())); this.lockedObjects = allocateArray(0); this.checkTypes = checkTypes; } protected AbstractFrameStateBuilder(S other) { this.method = other.method; this.stackSize = other.stackSize; this.locals = other.locals.clone(); this.stack = other.stack.clone(); this.lockedObjects = other.lockedObjects.length == 0 ? other.lockedObjects : other.lockedObjects.clone(); this.rethrowException = other.rethrowException; this.checkTypes = other.checkTypes; assert locals.length == method.getMaxLocals(); assert stack.length == Math.max(1, method.getMaxStackSize()); } public abstract S copy(); protected abstract T[] allocateArray(int length); public abstract boolean isCompatibleWith(S other); public void clearNonLiveLocals(BciBlock block, LocalLiveness liveness, boolean liveIn) { /* * (lstadler) if somebody is tempted to remove/disable this clearing code: it's possible to * remove it for normal compilations, but not for OSR compilations - otherwise dead object * slots at the OSR entry aren't cleared. it is also not enough to rely on PiNodes with * Kind.Illegal, because the conflicting branch might not have been parsed. */ if (liveness == null) { return; } if (liveIn) { for (int i = 0; i < locals.length; i++) { if (!liveness.localIsLiveIn(block, i)) { locals[i] = null; } } } else { for (int i = 0; i < locals.length; i++) { if (!liveness.localIsLiveOut(block, i)) { locals[i] = null; } } } } /** * @see BytecodeFrame#rethrowException */ public boolean rethrowException() { return rethrowException; } /** * @see BytecodeFrame#rethrowException */ public void setRethrowException(boolean b) { rethrowException = b; } /** * Returns the size of the local variables. * * @return the size of the local variables */ public int localsSize() { return locals.length; } /** * Gets the current size (height) of the stack. */ public int stackSize() { return stackSize; } /** * @return the current lock depth */ public int lockDepth() { return lockedObjects.length; } /** * Gets the value in the local variables at the specified index, without any sanity checking. * * @param i the index into the locals * @return the instruction that produced the value for the specified local */ public T localAt(int i) { return locals[i]; } /** * Get the value on the stack at the specified stack index. * * @param i the index into the stack, with {@code 0} being the bottom of the stack * @return the instruction at the specified position in the stack */ public T stackAt(int i) { return stack[i]; } /** * Gets the value in the lock at the specified index, without any sanity checking. * * @param i the index into the lock * @return the instruction that produced the value for the specified lock */ public T lockAt(int i) { return lockedObjects[i]; } public void storeLock(int i, T lock) { lockedObjects[i] = lock; } /** * Loads the local variable at the specified index, checking that the returned value is non-null * and that two-stack values are properly handled. * * @param i the index of the local variable to load * @return the instruction that produced the specified local */ public T loadLocal(int i) { T x = locals[i]; assert x != null : i; assert !checkTypes || (x.getKind().getSlotCount() == 1 || locals[i + 1] == null); assert !checkTypes || (i == 0 || locals[i - 1] == null || locals[i - 1].getKind().getSlotCount() == 1); return x; } /** * Stores a given local variable at the specified index. If the value occupies two slots, then * the next local variable index is also overwritten. * * @param i the index at which to store * @param x the instruction which produces the value for the local */ public void storeLocal(int i, T x) { assert x == null || !checkTypes || (x.getKind() != Kind.Void && x.getKind() != Kind.Illegal) : "unexpected value: " + x; locals[i] = x; if (x != null && x.getKind().needsTwoSlots()) { // if this is a double word, then kill i+1 locals[i + 1] = null; } if (x != null && i > 0) { T p = locals[i - 1]; if (p != null && p.getKind().needsTwoSlots()) { // if there was a double word at i - 1, then kill it locals[i - 1] = null; } } } public void storeStack(int i, T x) { assert x == null || (stack[i] == null || x.getKind() == stack[i].getKind()) : "Method does not handle changes from one-slot to two-slot values or non-alive values"; stack[i] = x; } /** * Pushes an instruction onto the stack with the expected type. * * @param kind the type expected for this instruction * @param x the instruction to push onto the stack */ public void push(Kind kind, T x) { assert !checkTypes || (x.getKind() != Kind.Void && x.getKind() != Kind.Illegal) : x; xpush(assertKind(kind, x)); if (kind.needsTwoSlots()) { xpush(null); } } /** * Pushes a value onto the stack without checking the type. * * @param x the instruction to push onto the stack */ public void xpush(T x) { assert !checkTypes || (x == null || (x.getKind() != Kind.Void && x.getKind() != Kind.Illegal)); stack[stackSize++] = x; } /** * Pushes a value onto the stack and checks that it is an int. * * @param x the instruction to push onto the stack */ public void ipush(T x) { xpush(assertInt(x)); } /** * Pushes a value onto the stack and checks that it is a float. * * @param x the instruction to push onto the stack */ public void fpush(T x) { xpush(assertFloat(x)); } /** * Pushes a value onto the stack and checks that it is an object. * * @param x the instruction to push onto the stack */ public void apush(T x) { xpush(assertObject(x)); } /** * Pushes a value onto the stack and checks that it is a long. * * @param x the instruction to push onto the stack */ public void lpush(T x) { xpush(assertLong(x)); xpush(null); } /** * Pushes a value onto the stack and checks that it is a double. * * @param x the instruction to push onto the stack */ public void dpush(T x) { xpush(assertDouble(x)); xpush(null); } public void pushReturn(Kind kind, T x) { if (kind != Kind.Void) { push(kind.getStackKind(), x); } } /** * Pops an instruction off the stack with the expected type. * * @param kind the expected type * @return the instruction on the top of the stack */ public T pop(Kind kind) { assert kind != Kind.Void; if (kind.needsTwoSlots()) { xpop(); } return assertKind(kind, xpop()); } /** * Pops a value off of the stack without checking the type. * * @return x the instruction popped off the stack */ public T xpop() { T result = stack[--stackSize]; return result; } /** * Pops a value off of the stack and checks that it is an int. * * @return x the instruction popped off the stack */ public T ipop() { return assertInt(xpop()); } /** * Pops a value off of the stack and checks that it is a float. * * @return x the instruction popped off the stack */ public T fpop() { return assertFloat(xpop()); } /** * Pops a value off of the stack and checks that it is an object. * * @return x the instruction popped off the stack */ public T apop() { return assertObject(xpop()); } /** * Pops a value off of the stack and checks that it is a long. * * @return x the instruction popped off the stack */ public T lpop() { assertHigh(xpop()); return assertLong(xpop()); } /** * Pops a value off of the stack and checks that it is a double. * * @return x the instruction popped off the stack */ public T dpop() { assertHigh(xpop()); return assertDouble(xpop()); } /** * Pop the specified number of slots off of this stack and return them as an array of * instructions. * * @return an array containing the arguments off of the stack */ public T[] popArguments(int argSize) { T[] result = allocateArray(argSize); int newStackSize = stackSize; for (int i = argSize - 1; i >= 0; i--) { newStackSize--; if (stack[newStackSize] == null) { /* Two-slot value. */ newStackSize--; assert stack[newStackSize].getKind().needsTwoSlots(); } else { assert !checkTypes || (stack[newStackSize].getKind().getSlotCount() == 1); } result[i] = stack[newStackSize]; } stackSize = newStackSize; return result; } /** * Peeks an element from the operand stack. * * @param argumentNumber The number of the argument, relative from the top of the stack (0 = * top). Long and double arguments only count as one argument, i.e., null-slots are * ignored. * @return The peeked argument. */ public T peek(int argumentNumber) { int idx = stackSize() - 1; for (int i = 0; i < argumentNumber; i++) { if (stackAt(idx) == null) { idx--; assert stackAt(idx).getKind().needsTwoSlots(); } idx--; } return stackAt(idx); } /** * Clears all values on this stack. */ public void clearStack() { stackSize = 0; } private T assertKind(Kind kind, T x) { assert x != null && (!checkTypes || x.getKind() == kind) : "kind=" + kind + ", value=" + x + ((x == null) ? "" : ", value.kind=" + x.getKind()); return x; } private T assertLong(T x) { assert x != null && (x.getKind() == Kind.Long); return x; } private T assertInt(T x) { assert x != null && (x.getKind() == Kind.Int); return x; } private T assertFloat(T x) { assert x != null && (x.getKind() == Kind.Float); return x; } private T assertObject(T x) { assert x != null && (!checkTypes || (x.getKind() == Kind.Object)); return x; } private T assertDouble(T x) { assert x != null && (x.getKind() == Kind.Double); return x; } private void assertHigh(T x) { assert x == null; } }
gpl-2.0
jeffwright13/unittest_tutorial
test_notequal.py
356
import unittest class InequalityTest(unittest.TestCase): def testEqual(self): self.assertEqual(1, 5-4) def testNotEqual(self): self.assertNotEqual(0, 0.1) def testEqual2(self): self.assertEqual(-1, 5-4) def testNotEqual2(self): self.assertNotEqual(0, 100-100) if __name__ == '__main__': unittest.main()
gpl-2.0
minkwankim/OP2A
OP2A/Common/src/Exception.cpp
2854
/* * Open-source multi-Physics Phenomena Analyzer (OP2A) ver. 0.1 * * Copyright (c) 2015 MINKWAN KIM * * Initial Developed Date: May 11, 2015 * Author: Minkwan Kim * * Exception.cpp * - * */ #include "Common/include/Exception.hpp" namespace OP2A{ namespace Common{ /* Exception Manager class * * @author Minkwan Kim * @version 1.0 20/05/2015 */ ExceptionManager::ExceptionManager() { ExceptionOutputs = true; ExceptionDumps = true; ExceptionAborts = false; } ExceptionManager& ExceptionManager::getInstance() { static ExceptionManager exception_manager; return exception_manager; } Exception::~Exception() throw () { } /* Exception class * * @author Minkwan Kim * @version 1.0 20/05/2015 */ Exception::Exception (Code_location where, std::string msg, std::string className) throw (): m_where(where), m_msg(msg), m_class_name(className) { m_what = full_description(); // Exception output if (ExceptionManager::getInstance().ExceptionOutputs) { std::cout << "======================================" << std::endl; std::cout << "+++ Exception thrown +++++++++++++++++" << std::endl; std::cout << m_what << std::endl; std::cout << "======================================" << std::endl; } // Abort exception if (ExceptionManager::getInstance().ExceptionAborts ) { std::cout << "+++ Exception aborting ... " << std::endl; abort(); } // Dump exception if (ExceptionManager::getInstance().ExceptionDumps ) { //std::string backtrace = OSystem::getInstance().getProcessInfo()->getBackTrace(); std::cout << "+++ Exception backtrace ++++++++++++++" << std::endl; //std::cout << backtrace << std::endl; std::cout << "======================================" << std::endl; } } // Append additional description into m_what void Exception::append(const std::string& add) throw () { m_what += add; } // Get contents of description (m_what) const std::string& Exception::str () const throw () { return m_what; } // Get contents of description (m_what) [char] const char* Exception::what() const throw() { return str().c_str(); } // Show full description of exception std::string Exception::full_description () const throw () { std::string desc; desc += "+++ Exception thrown ++++++++++++++++ \n"; desc += "From : \'"; desc += m_where.str(); desc += "\'\n"; desc += "Type : \'"; desc += m_class_name; desc += "\'\n"; desc += "Message :\n"; desc += m_msg; desc += "\n+++++++++++++++++++++++++++++++++++++\n"; return desc; } /////////////////////////////////////////////////////////////////////////// // Overloading std::ostream& operator<<(std::ostream& output, OP2A::Common::Exception& exc) { output << exc.str(); return output; } std::ostream& operator<<(std::ostream& output, OP2A::Common::Exception* exc) { return output << *exc; } } }
gpl-2.0
bruno-barros/w.eloquent
src/bootstrap/testing.php
1443
<?php /** * ---------------------------------------------------- * Testing config environment * ---------------------------------------------------- */ // Database define('DB_NAME', getenv('DB_NAME')); define('DB_USER', getenv('DB_USER')); define('DB_PASSWORD', getenv('DB_PASSWORD')); define('DB_HOST', getenv('DB_HOST') ? getenv('DB_HOST') : 'localhost'); // WordPress URLs define('WP_HOME', getenv('WP_HOME')); define('WP_SITEURL', getenv('WP_SITEURL')); // Development define('WP_DEBUG', true); /** * SCRIPT_DEBUG is a related constant that will force WordPress to use the "dev" versions of core CSS and Javascript files rather than the minified versions that are normally loaded. */ define('SCRIPT_DEBUG', true); /** * WP_DEBUG_DISPLAY is another companion to WP_DEBUG that controls whether * debug messages are shown inside the HTML of pages or not. The default is 'true' */ define('WP_DEBUG_DISPLAY', true); @ini_set('display_errors', 1); /** * WP_DEBUG_LOG is a companion to WP_DEBUG that causes all errors to also * be saved to a debug.log log file inside the /src/ directory. */ define('WP_DEBUG_LOG', true); /** * The SAVEQUERIES definition saves the database queries to an array and that * array can be displayed to help analyze those queries. The constant defined * as true causes each query to be saved, how long that query took to execute, * and what function called it. */ define('SAVEQUERIES', true);
gpl-2.0
InuSasha/xbmc
xbmc/peripherals/bus/virtual/PeripheralBusAddon.cpp
14254
/* * Copyright (C) 2014-2016 Team Kodi * http://kodi.tv * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this Program; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "PeripheralBusAddon.h" #include "addons/Addon.h" #include "addons/AddonManager.h" #include "messaging/helpers/DialogHelper.h" #include "peripherals/Peripherals.h" #include "peripherals/addons/PeripheralAddon.h" #include "peripherals/devices/PeripheralJoystick.h" #include "threads/SingleLock.h" #include "utils/log.h" #include <algorithm> #include <memory> using namespace KODI; using namespace PERIPHERALS; CPeripheralBusAddon::CPeripheralBusAddon(CPeripherals *manager) : CPeripheralBus("PeripBusAddon", manager, PERIPHERAL_BUS_ADDON) { using namespace ADDON; CAddonMgr::GetInstance().RegisterAddonMgrCallback(ADDON_PERIPHERALDLL, this); CAddonMgr::GetInstance().Events().Subscribe(this, &CPeripheralBusAddon::OnEvent); UpdateAddons(); } CPeripheralBusAddon::~CPeripheralBusAddon() { using namespace ADDON; CAddonMgr::GetInstance().Events().Unsubscribe(this); CAddonMgr::GetInstance().UnregisterAddonMgrCallback(ADDON_PERIPHERALDLL); // stop everything before destroying any (loaded) addons Clear(); // destroy any (loaded) addons m_failedAddons.clear(); m_addons.clear(); } bool CPeripheralBusAddon::GetAddon(const std::string &strId, ADDON::AddonPtr &addon) const { CSingleLock lock(m_critSection); for (const auto& addonIt : m_addons) { if (addonIt->ID() == strId) { addon = addonIt; return true; } } for (const auto& addonIt : m_failedAddons) { if (addonIt->ID() == strId) { addon = addonIt; return true; } } return false; } bool CPeripheralBusAddon::GetAddonWithButtonMap(PeripheralAddonPtr &addon) const { CSingleLock lock(m_critSection); auto it = std::find_if(m_addons.begin(), m_addons.end(), [](const PeripheralAddonPtr& addon) { return addon->HasButtonMaps(); }); if (it != m_addons.end()) { addon = *it; return true; } return false; } bool CPeripheralBusAddon::GetAddonWithButtonMap(const CPeripheral* device, PeripheralAddonPtr &addon) const { CSingleLock lock(m_critSection); // If device is from an add-on, try to use that add-on if (device && device->GetBusType() == PERIPHERAL_BUS_ADDON) { PeripheralAddonPtr addonWithButtonMap; unsigned int index; if (SplitLocation(device->Location(), addonWithButtonMap, index)) { if (addonWithButtonMap->HasButtonMaps()) addon = std::move(addonWithButtonMap); else CLog::Log(LOGDEBUG, "Add-on %s doesn't provide button maps for its controllers", addonWithButtonMap->ID().c_str()); } } if (!addon) { auto it = std::find_if(m_addons.begin(), m_addons.end(), [](const PeripheralAddonPtr& addon) { return addon->HasButtonMaps(); }); if (it != m_addons.end()) addon = *it; } return addon.get() != nullptr; } bool CPeripheralBusAddon::PerformDeviceScan(PeripheralScanResults &results) { PeripheralAddonVector addons; { CSingleLock lock(m_critSection); addons = m_addons; } for (const auto& addon : addons) addon->PerformDeviceScan(results); // Scan during bus initialization must return true or bus gets deleted return true; } bool CPeripheralBusAddon::InitializeProperties(CPeripheral& peripheral) { if (!CPeripheralBus::InitializeProperties(peripheral)) return false; bool bSuccess = false; PeripheralAddonPtr addon; unsigned int index; if (SplitLocation(peripheral.Location(), addon, index)) { switch (peripheral.Type()) { case PERIPHERAL_JOYSTICK: bSuccess = addon->GetJoystickProperties(index, static_cast<CPeripheralJoystick&>(peripheral)); break; default: break; } } return bSuccess; } bool CPeripheralBusAddon::SendRumbleEvent(const std::string& strLocation, unsigned int motorIndex, float magnitude) { bool bHandled = false; PeripheralAddonPtr addon; unsigned int peripheralIndex; if (SplitLocation(strLocation, addon, peripheralIndex)) bHandled = addon->SendRumbleEvent(peripheralIndex, motorIndex, magnitude); return bHandled; } void CPeripheralBusAddon::ProcessEvents(void) { PeripheralAddonVector addons; { CSingleLock lock(m_critSection); addons = m_addons; } for (const auto& addon : addons) addon->ProcessEvents(); } bool CPeripheralBusAddon::EnableButtonMapping() { using namespace ADDON; bool bEnabled = false; CSingleLock lock(m_critSection); PeripheralAddonPtr dummy; if (GetAddonWithButtonMap(dummy)) bEnabled = true; else { VECADDONS disabledAddons; if (CAddonMgr::GetInstance().GetDisabledAddons(disabledAddons, ADDON_PERIPHERALDLL)) bEnabled = PromptEnableAddons(disabledAddons); } return bEnabled; } void CPeripheralBusAddon::UnregisterRemovedDevices(const PeripheralScanResults &results) { CSingleLock lock(m_critSection); PeripheralVector removedPeripherals; for (const auto& addon : m_addons) addon->UnregisterRemovedDevices(results, removedPeripherals); for (const auto& peripheral : removedPeripherals) m_manager->OnDeviceDeleted(*this, *peripheral); } void CPeripheralBusAddon::Register(const PeripheralPtr& peripheral) { if (!peripheral) return; PeripheralAddonPtr addon; unsigned int peripheralIndex; CSingleLock lock(m_critSection); if (SplitLocation(peripheral->Location(), addon, peripheralIndex)) { if (addon->Register(peripheralIndex, peripheral)) m_manager->OnDeviceAdded(*this, *peripheral); } } void CPeripheralBusAddon::GetFeatures(std::vector<PeripheralFeature> &features) const { CSingleLock lock(m_critSection); for (const auto& addon : m_addons) addon->GetFeatures(features); } bool CPeripheralBusAddon::HasFeature(const PeripheralFeature feature) const { bool bReturn(false); CSingleLock lock(m_critSection); for (const auto& addon : m_addons) bReturn = bReturn || addon->HasFeature(feature); return bReturn; } PeripheralPtr CPeripheralBusAddon::GetPeripheral(const std::string &strLocation) const { PeripheralPtr peripheral; PeripheralAddonPtr addon; unsigned int peripheralIndex; CSingleLock lock(m_critSection); if (SplitLocation(strLocation, addon, peripheralIndex)) peripheral = addon->GetPeripheral(peripheralIndex); return peripheral; } PeripheralPtr CPeripheralBusAddon::GetByPath(const std::string &strPath) const { PeripheralPtr result; CSingleLock lock(m_critSection); for (const auto& addon : m_addons) { PeripheralPtr peripheral = addon->GetByPath(strPath); if (peripheral) { result = peripheral; break; } } return result; } int CPeripheralBusAddon::GetPeripheralsWithFeature(PeripheralVector &results, const PeripheralFeature feature) const { int iReturn(0); CSingleLock lock(m_critSection); for (const auto& addon : m_addons) iReturn += addon->GetPeripheralsWithFeature(results, feature); return iReturn; } size_t CPeripheralBusAddon::GetNumberOfPeripherals(void) const { size_t iReturn(0); CSingleLock lock(m_critSection); for (const auto& addon : m_addons) iReturn += addon->GetNumberOfPeripherals(); return iReturn; } size_t CPeripheralBusAddon::GetNumberOfPeripheralsWithId(const int iVendorId, const int iProductId) const { size_t iReturn(0); CSingleLock lock(m_critSection); for (const auto& addon : m_addons) iReturn += addon->GetNumberOfPeripheralsWithId(iVendorId, iProductId); return iReturn; } void CPeripheralBusAddon::GetDirectory(const std::string &strPath, CFileItemList &items) const { CSingleLock lock(m_critSection); for (const auto& addon : m_addons) addon->GetDirectory(strPath, items); } bool CPeripheralBusAddon::RequestRestart(ADDON::AddonPtr addon, bool datachanged) { // make sure this is a peripheral addon PeripheralAddonPtr peripheralAddon = std::dynamic_pointer_cast<CPeripheralAddon>(addon); if (peripheralAddon == nullptr) return false; if (peripheralAddon->CreateAddon() != ADDON_STATUS_OK) { CSingleLock lock(m_critSection); m_addons.erase(std::remove(m_addons.begin(), m_addons.end(), peripheralAddon), m_addons.end()); m_failedAddons.push_back(peripheralAddon); } return true; } bool CPeripheralBusAddon::RequestRemoval(ADDON::AddonPtr addon) { // make sure this is a peripheral addon PeripheralAddonPtr peripheralAddon = std::dynamic_pointer_cast<CPeripheralAddon>(addon); if (peripheralAddon == nullptr) return false; CSingleLock lock(m_critSection); // destroy the peripheral addon peripheralAddon->Destroy(); // remove the peripheral addon from the list of addons m_addons.erase(std::remove(m_addons.begin(), m_addons.end(), peripheralAddon), m_addons.end()); return true; } void CPeripheralBusAddon::OnEvent(const ADDON::AddonEvent& event) { if (typeid(event) == typeid(ADDON::AddonEvents::Enabled) || typeid(event) == typeid(ADDON::AddonEvents::Disabled) || typeid(event) == typeid(ADDON::AddonEvents::InstalledChanged)) UpdateAddons(); } bool CPeripheralBusAddon::SplitLocation(const std::string& strLocation, PeripheralAddonPtr& addon, unsigned int& peripheralIndex) const { std::vector<std::string> parts = StringUtils::Split(strLocation, "/"); if (parts.size() == 2) { addon.reset(); CSingleLock lock(m_critSection); const std::string& strAddonId = parts[0]; for (const auto& addonIt : m_addons) { if (addonIt->ID() == strAddonId) { addon = addonIt; break; } } if (addon) { const char* strJoystickIndex = parts[1].c_str(); char* p = NULL; peripheralIndex = strtol(strJoystickIndex, &p, 10); if (strJoystickIndex != p) return true; } } return false; } void CPeripheralBusAddon::UpdateAddons(void) { using namespace ADDON; auto GetPeripheralAddonID = [](const PeripheralAddonPtr& addon) { return addon->ID(); }; auto GetAddonID = [](const AddonPtr& addon) { return addon->ID(); }; std::set<std::string> currentIds; std::set<std::string> newIds; std::set<std::string> added; std::set<std::string> removed; // Get new add-ons VECADDONS newAddons; CAddonMgr::GetInstance().GetAddons(newAddons, ADDON_PERIPHERALDLL); std::transform(newAddons.begin(), newAddons.end(), std::inserter(newIds, newIds.end()), GetAddonID); CSingleLock lock(m_critSection); // Get current add-ons std::transform(m_addons.begin(), m_addons.end(), std::inserter(currentIds, currentIds.end()), GetPeripheralAddonID); std::transform(m_failedAddons.begin(), m_failedAddons.end(), std::inserter(currentIds, currentIds.end()), GetPeripheralAddonID); // Differences std::set_difference(newIds.begin(), newIds.end(), currentIds.begin(), currentIds.end(), std::inserter(added, added.end())); std::set_difference(currentIds.begin(), currentIds.end(), newIds.begin(), newIds.end(), std::inserter(removed, removed.end())); // Register new add-ons for (const std::string& addonId : added) { CLog::Log(LOGDEBUG, "Add-on bus: Registering add-on %s", addonId.c_str()); auto GetAddon = [addonId](const AddonPtr& addon) { return addon->ID() == addonId; }; VECADDONS::iterator it = std::find_if(newAddons.begin(), newAddons.end(), GetAddon); if (it != newAddons.end()) { PeripheralAddonPtr newAddon = std::dynamic_pointer_cast<CPeripheralAddon>(*it); if (newAddon) { bool bCreated; { CSingleExit exit(m_critSection); bCreated = (newAddon->CreateAddon() == ADDON_STATUS_OK); } if (bCreated) m_addons.push_back(newAddon); else m_failedAddons.push_back(newAddon); } } } // Destroy removed add-ons for (const std::string& addonId : removed) { CLog::Log(LOGDEBUG, "Add-on bus: Unregistering add-on %s", addonId.c_str()); PeripheralAddonPtr erased; auto ErasePeripheralAddon = [&addonId, &erased](const PeripheralAddonPtr& addon) { if (addon->ID() == addonId) { erased = addon; return true; } return false; }; m_addons.erase(std::remove_if(m_addons.begin(), m_addons.end(), ErasePeripheralAddon), m_addons.end()); if (!erased) m_failedAddons.erase(std::remove_if(m_failedAddons.begin(), m_failedAddons.end(), ErasePeripheralAddon), m_failedAddons.end()); if (erased) { CSingleExit exit(m_critSection); erased->Destroy(); } } } bool CPeripheralBusAddon::PromptEnableAddons(const ADDON::VECADDONS& disabledAddons) { using namespace ADDON; using namespace MESSAGING::HELPERS; // True if the user confirms enabling the disabled peripheral add-on bool bAccepted = false; auto itAddon = std::find_if(disabledAddons.begin(), disabledAddons.end(), [](const AddonPtr& addon) { return std::static_pointer_cast<CPeripheralAddon>(addon)->HasButtonMaps(); }); if (itAddon != disabledAddons.end()) { // "Unable to configure controllers" // "Controller configuration depends on a disabled add-on. Would you like to enable it?" bAccepted = (ShowYesNoDialogLines(CVariant{ 35017 }, CVariant{ 35018 }) == DialogResponse::YES); } if (bAccepted) { for (const AddonPtr& addon : disabledAddons) { if (std::static_pointer_cast<CPeripheralAddon>(addon)->HasButtonMaps()) CAddonMgr::GetInstance().EnableAddon(addon->ID()); } } PeripheralAddonPtr dummy; return GetAddonWithButtonMap(dummy); }
gpl-2.0
dennymorrison/moviefantasyleague
MovieFantasyLeague/MFL.Data/Season.cs
1387
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MFL.Data { using System; using System.Collections.Generic; public partial class Season { public Season() { this.Movies = new HashSet<Movie>(); this.Teams = new HashSet<Team>(); } public System.Guid SeasonId { get; set; } public string Name { get; set; } public System.DateTime StartDate { get; set; } public System.DateTime EndDate { get; set; } public System.DateTime LastUpdateDate { get; set; } public System.DateTime StartEdits { get; set; } public System.DateTime EndEdits { get; set; } public string Note { get; set; } public int Budget { get; set; } public Nullable<System.Guid> ChampionTeamId { get; set; } public virtual ICollection<Movie> Movies { get; set; } public virtual Team Team { get; set; } public virtual ICollection<Team> Teams { get; set; } } }
gpl-2.0
Excito/kronolith
index.php
813
<?php /** * $Horde: kronolith/index.php,v 1.28.10.3 2009/01/06 15:24:43 jan Exp $ * * Copyright 1999-2009 The Horde Project (http://www.horde.org/) * * See the enclosed file COPYING for license information (GPL). If you * not receive such a file, see also http://www.fsf.org/copyleft/gpl.html. */ @define('KRONOLITH_BASE', dirname(__FILE__)); $kronolith_configured = (is_readable(KRONOLITH_BASE . '/config/conf.php') && is_readable(KRONOLITH_BASE . '/config/prefs.php')); if (!$kronolith_configured) { require KRONOLITH_BASE . '/../lib/Test.php'; Horde_Test::configFilesMissing('Kronolith', KRONOLITH_BASE, array('conf.php', 'prefs.php')); } require_once KRONOLITH_BASE . '/lib/base.php'; require KRONOLITH_BASE . '/' . $prefs->getValue('defaultview') . '.php';
gpl-2.0
crosslink/huai-joomla3
administrator/components/com_jxtc/views/files/tmpl/list_footer.php
2510
<?php /*********************************************************************************** ************************************************************************************ *** *** *** XTC Template Framework helper 1.3.1 *** *** *** *** Copyright (c) 2010, 2011, 2012, 2013, 2014 *** *** Monev Software LLC, All Rights Reserved *** *** *** *** This program is free software; you can redistribute it and/or modify *** *** it under the terms of the GNU General Public License as published by *** *** the Free Software Foundation; either version 2 of the License, or *** *** (at your option) any later version. *** *** *** *** This program is distributed in the hope that it will be useful, *** *** but WITHOUT ANY WARRANTY; without even the implied warranty of *** *** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *** *** GNU General Public License for more details. *** *** *** *** You should have received a copy of the GNU General Public License *** *** along with this program; if not, write to the Free Software *** *** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *** *** *** *** See COPYRIGHT.txt for more information. *** *** See LICENSE.txt for more information. *** *** *** *** www.joomlaxtc.com *** *** *** ************************************************************************************ ***********************************************************************************/ defined('_JEXEC') or die; ?> </table>
gpl-2.0
Gambiit/pmb-on-docker
web_appli/pmb/catalog/caddie/pointage/main.inc.php
1718
<?php // +-------------------------------------------------+ // © 2002-2004 PMB Services / www.sigb.net [email protected] et contributeurs (voir www.sigb.net) // +-------------------------------------------------+ // $Id: main.inc.php,v 1.9.4.1 2014-06-05 09:51:36 dgoron Exp $ if (stristr($_SERVER['REQUEST_URI'], ".inc.php")) die("no access"); switch ($moyen) { case 'raz': $catalog_layout = str_replace('<!--!!sous_menu_choisi!! -->', $msg["caddie_menu_pointage_raz"], $catalog_layout); print $catalog_layout ; include ("./catalog/caddie/pointage/raz.inc.php"); break; case 'selection': $catalog_layout = str_replace('<!--!!sous_menu_choisi!! -->', $msg["caddie_menu_pointage_selection"], $catalog_layout); print $catalog_layout ; include ("./catalog/caddie/pointage/selection.inc.php"); break; case 'douchette': $catalog_layout = str_replace('<!--!!sous_menu_choisi!! -->', $msg["caddie_menu_pointage_cb"], $catalog_layout); print $catalog_layout ; include ("./catalog/caddie/pointage/douchette.inc.php"); break; case 'panier': $catalog_layout = str_replace('<!--!!sous_menu_choisi!! -->', $msg["caddie_menu_pointage_panier"], $catalog_layout); print $catalog_layout ; include ("./catalog/caddie/pointage/panier.inc.php"); break; case 'search_history': $catalog_layout = str_replace('<!--!!sous_menu_choisi!! -->', $msg["caddie_menu_pointage_search_history"], $catalog_layout); print $catalog_layout ; include ("./catalog/caddie/pointage/search_history.inc.php"); break; default: $catalog_layout = str_replace('<!--!!sous_menu_choisi!! -->', "?", $catalog_layout); print $catalog_layout ; print "<br /><br /><b>".$msg["caddie_select_pointage"]."</b>" ; break; }
gpl-2.0
MESH-Dev/MESH
wp-admin/includes/schema.php
33562
<?php /** * WordPress Administration Scheme API * * Here we keep the DB structure and option values. * * @package WordPress * @subpackage Administration */ // Declare these as global in case schema.php is included from a function. global $wpdb, $wp_queries, $charset_collate; /** * The database character collate. * @var string * @global string * @name $charset_collate */ $charset_collate = $wpdb->get_charset_collate(); /** * Retrieve the SQL for creating database tables. * * @since 3.3.0 * * @param string $scope Optional. The tables for which to retrieve SQL. Can be all, global, ms_global, or blog tables. Defaults to all. * @param int $blog_id Optional. The blog ID for which to retrieve SQL. Default is the current blog ID. * @return string The SQL needed to create the requested tables. */ function wp_get_db_schema( $scope = 'all', $blog_id = null ) { global $wpdb; $charset_collate = ''; if ( ! empty($wpdb->charset) ) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; if ( ! empty($wpdb->collate) ) $charset_collate .= " COLLATE $wpdb->collate"; if ( $blog_id && $blog_id != $wpdb->blogid ) $old_blog_id = $wpdb->set_blog_id( $blog_id ); // Engage multisite if in the middle of turning it on from network.php. $is_multisite = is_multisite() || ( defined( 'WP_INSTALLING_NETWORK' ) && WP_INSTALLING_NETWORK ); // Blog specific tables. $blog_tables = "CREATE TABLE $wpdb->terms ( term_id bigint(20) unsigned NOT NULL auto_increment, name varchar(200) NOT NULL default '', slug varchar(200) NOT NULL default '', term_group bigint(10) NOT NULL default 0, PRIMARY KEY (term_id), UNIQUE KEY slug (slug), KEY name (name) ) $charset_collate; CREATE TABLE $wpdb->term_taxonomy ( term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment, term_id bigint(20) unsigned NOT NULL default 0, taxonomy varchar(32) NOT NULL default '', description longtext NOT NULL, parent bigint(20) unsigned NOT NULL default 0, count bigint(20) NOT NULL default 0, PRIMARY KEY (term_taxonomy_id), UNIQUE KEY term_id_taxonomy (term_id,taxonomy), KEY taxonomy (taxonomy) ) $charset_collate; CREATE TABLE $wpdb->term_relationships ( object_id bigint(20) unsigned NOT NULL default 0, term_taxonomy_id bigint(20) unsigned NOT NULL default 0, term_order int(11) NOT NULL default 0, PRIMARY KEY (object_id,term_taxonomy_id), KEY term_taxonomy_id (term_taxonomy_id) ) $charset_collate; CREATE TABLE $wpdb->commentmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, comment_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY comment_id (comment_id), KEY meta_key (meta_key) ) $charset_collate; CREATE TABLE $wpdb->comments ( comment_ID bigint(20) unsigned NOT NULL auto_increment, comment_post_ID bigint(20) unsigned NOT NULL default '0', comment_author tinytext NOT NULL, comment_author_email varchar(100) NOT NULL default '', comment_author_url varchar(200) NOT NULL default '', comment_author_IP varchar(100) NOT NULL default '', comment_date datetime NOT NULL default '0000-00-00 00:00:00', comment_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', comment_content text NOT NULL, comment_karma int(11) NOT NULL default '0', comment_approved varchar(20) NOT NULL default '1', comment_agent varchar(255) NOT NULL default '', comment_type varchar(20) NOT NULL default '', comment_parent bigint(20) unsigned NOT NULL default '0', user_id bigint(20) unsigned NOT NULL default '0', PRIMARY KEY (comment_ID), KEY comment_post_ID (comment_post_ID), KEY comment_approved_date_gmt (comment_approved,comment_date_gmt), KEY comment_date_gmt (comment_date_gmt), KEY comment_parent (comment_parent) ) $charset_collate; CREATE TABLE $wpdb->links ( link_id bigint(20) unsigned NOT NULL auto_increment, link_url varchar(255) NOT NULL default '', link_name varchar(255) NOT NULL default '', link_image varchar(255) NOT NULL default '', link_target varchar(25) NOT NULL default '', link_description varchar(255) NOT NULL default '', link_visible varchar(20) NOT NULL default 'Y', link_owner bigint(20) unsigned NOT NULL default '1', link_rating int(11) NOT NULL default '0', link_updated datetime NOT NULL default '0000-00-00 00:00:00', link_rel varchar(255) NOT NULL default '', link_notes mediumtext NOT NULL, link_rss varchar(255) NOT NULL default '', PRIMARY KEY (link_id), KEY link_visible (link_visible) ) $charset_collate; CREATE TABLE $wpdb->options ( option_id bigint(20) unsigned NOT NULL auto_increment, option_name varchar(64) NOT NULL default '', option_value longtext NOT NULL, autoload varchar(20) NOT NULL default 'yes', PRIMARY KEY (option_id), UNIQUE KEY option_name (option_name) ) $charset_collate; CREATE TABLE $wpdb->postmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, post_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY post_id (post_id), KEY meta_key (meta_key) ) $charset_collate; CREATE TABLE $wpdb->posts ( ID bigint(20) unsigned NOT NULL auto_increment, post_author bigint(20) unsigned NOT NULL default '0', post_date datetime NOT NULL default '0000-00-00 00:00:00', post_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content longtext NOT NULL, post_title text NOT NULL, post_excerpt text NOT NULL, post_status varchar(20) NOT NULL default 'publish', comment_status varchar(20) NOT NULL default 'open', ping_status varchar(20) NOT NULL default 'open', post_password varchar(20) NOT NULL default '', post_name varchar(200) NOT NULL default '', to_ping text NOT NULL, pinged text NOT NULL, post_modified datetime NOT NULL default '0000-00-00 00:00:00', post_modified_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content_filtered longtext NOT NULL, post_parent bigint(20) unsigned NOT NULL default '0', guid varchar(255) NOT NULL default '', menu_order int(11) NOT NULL default '0', post_type varchar(20) NOT NULL default 'post', post_mime_type varchar(100) NOT NULL default '', comment_count bigint(20) NOT NULL default '0', PRIMARY KEY (ID), KEY post_name (post_name), KEY type_status_date (post_type,post_status,post_date,ID), KEY post_parent (post_parent), KEY post_author (post_author) ) $charset_collate;\n"; // Single site users table. The multisite flavor of the users table is handled below. $users_single_table = "CREATE TABLE $wpdb->users ( ID bigint(20) unsigned NOT NULL auto_increment, user_login varchar(60) NOT NULL default '', user_pass varchar(64) NOT NULL default '', user_nicename varchar(50) NOT NULL default '', user_email varchar(100) NOT NULL default '', user_url varchar(100) NOT NULL default '', user_registered datetime NOT NULL default '0000-00-00 00:00:00', user_activation_key varchar(60) NOT NULL default '', user_status int(11) NOT NULL default '0', display_name varchar(250) NOT NULL default '', PRIMARY KEY (ID), KEY user_login_key (user_login), KEY user_nicename (user_nicename) ) $charset_collate;\n"; // Multisite users table $users_multi_table = "CREATE TABLE $wpdb->users ( ID bigint(20) unsigned NOT NULL auto_increment, user_login varchar(60) NOT NULL default '', user_pass varchar(64) NOT NULL default '', user_nicename varchar(50) NOT NULL default '', user_email varchar(100) NOT NULL default '', user_url varchar(100) NOT NULL default '', user_registered datetime NOT NULL default '0000-00-00 00:00:00', user_activation_key varchar(60) NOT NULL default '', user_status int(11) NOT NULL default '0', display_name varchar(250) NOT NULL default '', spam tinyint(2) NOT NULL default '0', deleted tinyint(2) NOT NULL default '0', PRIMARY KEY (ID), KEY user_login_key (user_login), KEY user_nicename (user_nicename) ) $charset_collate;\n"; // usermeta $usermeta_table = "CREATE TABLE $wpdb->usermeta ( umeta_id bigint(20) unsigned NOT NULL auto_increment, user_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (umeta_id), KEY user_id (user_id), KEY meta_key (meta_key) ) $charset_collate;\n"; // Global tables if ( $is_multisite ) $global_tables = $users_multi_table . $usermeta_table; else $global_tables = $users_single_table . $usermeta_table; // Multisite global tables. $ms_global_tables = "CREATE TABLE $wpdb->blogs ( blog_id bigint(20) NOT NULL auto_increment, site_id bigint(20) NOT NULL default '0', domain varchar(200) NOT NULL default '', path varchar(100) NOT NULL default '', registered datetime NOT NULL default '0000-00-00 00:00:00', last_updated datetime NOT NULL default '0000-00-00 00:00:00', public tinyint(2) NOT NULL default '1', archived tinyint(2) NOT NULL default '0', mature tinyint(2) NOT NULL default '0', spam tinyint(2) NOT NULL default '0', deleted tinyint(2) NOT NULL default '0', lang_id int(11) NOT NULL default '0', PRIMARY KEY (blog_id), KEY domain (domain(50),path(5)), KEY lang_id (lang_id) ) $charset_collate; CREATE TABLE $wpdb->blog_versions ( blog_id bigint(20) NOT NULL default '0', db_version varchar(20) NOT NULL default '', last_updated datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (blog_id), KEY db_version (db_version) ) $charset_collate; CREATE TABLE $wpdb->registration_log ( ID bigint(20) NOT NULL auto_increment, email varchar(255) NOT NULL default '', IP varchar(30) NOT NULL default '', blog_id bigint(20) NOT NULL default '0', date_registered datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (ID), KEY IP (IP) ) $charset_collate; CREATE TABLE $wpdb->site ( id bigint(20) NOT NULL auto_increment, domain varchar(200) NOT NULL default '', path varchar(100) NOT NULL default '', PRIMARY KEY (id), KEY domain (domain,path) ) $charset_collate; CREATE TABLE $wpdb->sitemeta ( meta_id bigint(20) NOT NULL auto_increment, site_id bigint(20) NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY meta_key (meta_key), KEY site_id (site_id) ) $charset_collate; CREATE TABLE $wpdb->signups ( signup_id bigint(20) NOT NULL auto_increment, domain varchar(200) NOT NULL default '', path varchar(100) NOT NULL default '', title longtext NOT NULL, user_login varchar(60) NOT NULL default '', user_email varchar(100) NOT NULL default '', registered datetime NOT NULL default '0000-00-00 00:00:00', activated datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '0', activation_key varchar(50) NOT NULL default '', meta longtext, PRIMARY KEY (signup_id), KEY activation_key (activation_key), KEY user_email (user_email), KEY user_login_email (user_login,user_email), KEY domain_path (domain,path) ) $charset_collate;"; switch ( $scope ) { case 'blog' : $queries = $blog_tables; break; case 'global' : $queries = $global_tables; if ( $is_multisite ) $queries .= $ms_global_tables; break; case 'ms_global' : $queries = $ms_global_tables; break; default: case 'all' : $queries = $global_tables . $blog_tables; if ( $is_multisite ) $queries .= $ms_global_tables; break; } if ( isset( $old_blog_id ) ) $wpdb->set_blog_id( $old_blog_id ); return $queries; } // Populate for back compat. $wp_queries = wp_get_db_schema( 'all' ); /** * Create WordPress options and set the default values. * * @since 1.5.0 * @uses $wpdb * @uses $wp_db_version */ function populate_options() { global $wpdb, $wp_db_version, $wp_current_db_version; $guessurl = wp_guess_url(); /** * Fires before creating WordPress options and populating their default values. * * @since 2.6.0 */ do_action( 'populate_options' ); if ( ini_get('safe_mode') ) { // Safe mode can break mkdir() so use a flat structure by default. $uploads_use_yearmonth_folders = 0; } else { $uploads_use_yearmonth_folders = 1; } $template = WP_DEFAULT_THEME; // If default theme is a child theme, we need to get its template $theme = wp_get_theme( $template ); if ( ! $theme->errors() ) $template = $theme->get_template(); $timezone_string = ''; $gmt_offset = 0; /* translators: default GMT offset or timezone string. Must be either a valid offset (-12 to 14) or a valid timezone string (America/New_York). See http://us3.php.net/manual/en/timezones.php for all timezone strings supported by PHP. */ $offset_or_tz = _x( '0', 'default GMT offset or timezone string' ); if ( is_numeric( $offset_or_tz ) ) $gmt_offset = $offset_or_tz; elseif ( $offset_or_tz && in_array( $offset_or_tz, timezone_identifiers_list() ) ) $timezone_string = $offset_or_tz; $options = array( 'siteurl' => $guessurl, 'blogname' => __('My Site'), /* translators: blog tagline */ 'blogdescription' => __('Just another WordPress site'), 'users_can_register' => 0, 'admin_email' => '[email protected]', /* translators: default start of the week. 0 = Sunday, 1 = Monday */ 'start_of_week' => _x( '1', 'start of week' ), 'use_balanceTags' => 0, 'use_smilies' => 1, 'require_name_email' => 1, 'comments_notify' => 1, 'posts_per_rss' => 10, 'rss_use_excerpt' => 0, 'mailserver_url' => 'mail.example.com', 'mailserver_login' => '[email protected]', 'mailserver_pass' => 'password', 'mailserver_port' => 110, 'default_category' => 1, 'default_comment_status' => 'open', 'default_ping_status' => 'open', 'default_pingback_flag' => 1, 'posts_per_page' => 10, /* translators: default date format, see http://php.net/date */ 'date_format' => __('F j, Y'), /* translators: default time format, see http://php.net/date */ 'time_format' => __('g:i a'), /* translators: links last updated date format, see http://php.net/date */ 'links_updated_date_format' => __('F j, Y g:i a'), 'links_recently_updated_prepend' => '<em>', 'links_recently_updated_append' => '</em>', 'links_recently_updated_time' => 120, 'comment_moderation' => 0, 'moderation_notify' => 1, 'permalink_structure' => '', 'gzipcompression' => 0, 'hack_file' => 0, 'blog_charset' => 'UTF-8', 'moderation_keys' => '', 'active_plugins' => array(), 'home' => $guessurl, 'category_base' => '', 'ping_sites' => 'http://rpc.pingomatic.com/', 'advanced_edit' => 0, 'comment_max_links' => 2, 'gmt_offset' => $gmt_offset, // 1.5 'default_email_category' => 1, 'recently_edited' => '', 'template' => $template, 'stylesheet' => WP_DEFAULT_THEME, 'comment_whitelist' => 1, 'blacklist_keys' => '', 'comment_registration' => 0, 'html_type' => 'text/html', // 1.5.1 'use_trackback' => 0, // 2.0 'default_role' => 'subscriber', 'db_version' => $wp_db_version, // 2.0.1 'uploads_use_yearmonth_folders' => $uploads_use_yearmonth_folders, 'upload_path' => '', // 2.1 'blog_public' => '1', 'default_link_category' => 2, 'show_on_front' => 'posts', // 2.2 'tag_base' => '', // 2.5 'show_avatars' => '1', 'avatar_rating' => 'G', 'upload_url_path' => '', 'thumbnail_size_w' => 150, 'thumbnail_size_h' => 150, 'thumbnail_crop' => 1, 'medium_size_w' => 300, 'medium_size_h' => 300, // 2.6 'avatar_default' => 'mystery', // 2.7 'large_size_w' => 1024, 'large_size_h' => 1024, 'image_default_link_type' => 'file', 'image_default_size' => '', 'image_default_align' => '', 'close_comments_for_old_posts' => 0, 'close_comments_days_old' => 14, 'thread_comments' => 1, 'thread_comments_depth' => 5, 'page_comments' => 0, 'comments_per_page' => 50, 'default_comments_page' => 'newest', 'comment_order' => 'asc', 'sticky_posts' => array(), 'widget_categories' => array(), 'widget_text' => array(), 'widget_rss' => array(), 'uninstall_plugins' => array(), // 2.8 'timezone_string' => $timezone_string, // 3.0 'page_for_posts' => 0, 'page_on_front' => 0, // 3.1 'default_post_format' => 0, // 3.5 'link_manager_enabled' => 0, ); // 3.3 if ( ! is_multisite() ) { $options['initial_db_version'] = ! empty( $wp_current_db_version ) && $wp_current_db_version < $wp_db_version ? $wp_current_db_version : $wp_db_version; } // 3.0 multisite if ( is_multisite() ) { /* translators: blog tagline */ $options[ 'blogdescription' ] = sprintf(__('Just another %s site'), get_current_site()->site_name ); $options[ 'permalink_structure' ] = '/%year%/%monthnum%/%day%/%postname%/'; } // Set autoload to no for these options $fat_options = array( 'moderation_keys', 'recently_edited', 'blacklist_keys', 'uninstall_plugins' ); $keys = "'" . implode( "', '", array_keys( $options ) ) . "'"; $existing_options = $wpdb->get_col( "SELECT option_name FROM $wpdb->options WHERE option_name in ( $keys )" ); $insert = ''; foreach ( $options as $option => $value ) { if ( in_array($option, $existing_options) ) continue; if ( in_array($option, $fat_options) ) $autoload = 'no'; else $autoload = 'yes'; if ( is_array($value) ) $value = serialize($value); if ( !empty($insert) ) $insert .= ', '; $insert .= $wpdb->prepare( "(%s, %s, %s)", $option, $value, $autoload ); } if ( !empty($insert) ) $wpdb->query("INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES " . $insert); // in case it is set, but blank, update "home" if ( !__get_option('home') ) update_option('home', $guessurl); // Delete unused options $unusedoptions = array( 'blodotgsping_url', 'bodyterminator', 'emailtestonly', 'phoneemail_separator', 'smilies_directory', 'subjectprefix', 'use_bbcode', 'use_blodotgsping', 'use_phoneemail', 'use_quicktags', 'use_weblogsping', 'weblogs_cache_file', 'use_preview', 'use_htmltrans', 'smilies_directory', 'fileupload_allowedusers', 'use_phoneemail', 'default_post_status', 'default_post_category', 'archive_mode', 'time_difference', 'links_minadminlevel', 'links_use_adminlevels', 'links_rating_type', 'links_rating_char', 'links_rating_ignore_zero', 'links_rating_single_image', 'links_rating_image0', 'links_rating_image1', 'links_rating_image2', 'links_rating_image3', 'links_rating_image4', 'links_rating_image5', 'links_rating_image6', 'links_rating_image7', 'links_rating_image8', 'links_rating_image9', 'weblogs_cacheminutes', 'comment_allowed_tags', 'search_engine_friendly_urls', 'default_geourl_lat', 'default_geourl_lon', 'use_default_geourl', 'weblogs_xml_url', 'new_users_can_blog', '_wpnonce', '_wp_http_referer', 'Update', 'action', 'rich_editing', 'autosave_interval', 'deactivated_plugins', 'can_compress_scripts', 'page_uris', 'update_core', 'update_plugins', 'update_themes', 'doing_cron', 'random_seed', 'rss_excerpt_length', 'secret', 'use_linksupdate', 'default_comment_status_page', 'wporg_popular_tags', 'what_to_show', 'rss_language', 'language', 'enable_xmlrpc', 'enable_app', 'embed_autourls', 'default_post_edit_rows', ); foreach ( $unusedoptions as $option ) delete_option($option); // delete obsolete magpie stuff $wpdb->query("DELETE FROM $wpdb->options WHERE option_name REGEXP '^rss_[0-9a-f]{32}(_ts)?$'"); // Deletes all expired transients. // The multi-table delete syntax is used to delete the transient record from table a, // and the corresponding transient_timeout record from table b. $time = time(); $wpdb->query("DELETE a, b FROM $wpdb->options a, $wpdb->options b WHERE a.option_name LIKE '\_transient\_%' AND a.option_name NOT LIKE '\_transient\_timeout\_%' AND b.option_name = CONCAT( '_transient_timeout_', SUBSTRING( a.option_name, 12 ) ) AND b.option_value < $time"); if ( is_main_site() && is_main_network() ) { $wpdb->query("DELETE a, b FROM $wpdb->options a, $wpdb->options b WHERE a.option_name LIKE '\_site\_transient\_%' AND a.option_name NOT LIKE '\_site\_transient\_timeout\_%' AND b.option_name = CONCAT( '_site_transient_timeout_', SUBSTRING( a.option_name, 17 ) ) AND b.option_value < $time"); } } /** * Execute WordPress role creation for the various WordPress versions. * * @since 2.0.0 */ function populate_roles() { populate_roles_160(); populate_roles_210(); populate_roles_230(); populate_roles_250(); populate_roles_260(); populate_roles_270(); populate_roles_280(); populate_roles_300(); } /** * Create the roles for WordPress 2.0 * * @since 2.0.0 */ function populate_roles_160() { // Add roles // Dummy gettext calls to get strings in the catalog. /* translators: user role */ _x('Administrator', 'User role'); /* translators: user role */ _x('Editor', 'User role'); /* translators: user role */ _x('Author', 'User role'); /* translators: user role */ _x('Contributor', 'User role'); /* translators: user role */ _x('Subscriber', 'User role'); add_role('administrator', 'Administrator'); add_role('editor', 'Editor'); add_role('author', 'Author'); add_role('contributor', 'Contributor'); add_role('subscriber', 'Subscriber'); // Add caps for Administrator role $role = get_role('administrator'); $role->add_cap('switch_themes'); $role->add_cap('edit_themes'); $role->add_cap('activate_plugins'); $role->add_cap('edit_plugins'); $role->add_cap('edit_users'); $role->add_cap('edit_files'); $role->add_cap('manage_options'); $role->add_cap('moderate_comments'); $role->add_cap('manage_categories'); $role->add_cap('manage_links'); $role->add_cap('upload_files'); $role->add_cap('import'); $role->add_cap('unfiltered_html'); $role->add_cap('edit_posts'); $role->add_cap('edit_others_posts'); $role->add_cap('edit_published_posts'); $role->add_cap('publish_posts'); $role->add_cap('edit_pages'); $role->add_cap('read'); $role->add_cap('level_10'); $role->add_cap('level_9'); $role->add_cap('level_8'); $role->add_cap('level_7'); $role->add_cap('level_6'); $role->add_cap('level_5'); $role->add_cap('level_4'); $role->add_cap('level_3'); $role->add_cap('level_2'); $role->add_cap('level_1'); $role->add_cap('level_0'); // Add caps for Editor role $role = get_role('editor'); $role->add_cap('moderate_comments'); $role->add_cap('manage_categories'); $role->add_cap('manage_links'); $role->add_cap('upload_files'); $role->add_cap('unfiltered_html'); $role->add_cap('edit_posts'); $role->add_cap('edit_others_posts'); $role->add_cap('edit_published_posts'); $role->add_cap('publish_posts'); $role->add_cap('edit_pages'); $role->add_cap('read'); $role->add_cap('level_7'); $role->add_cap('level_6'); $role->add_cap('level_5'); $role->add_cap('level_4'); $role->add_cap('level_3'); $role->add_cap('level_2'); $role->add_cap('level_1'); $role->add_cap('level_0'); // Add caps for Author role $role = get_role('author'); $role->add_cap('upload_files'); $role->add_cap('edit_posts'); $role->add_cap('edit_published_posts'); $role->add_cap('publish_posts'); $role->add_cap('read'); $role->add_cap('level_2'); $role->add_cap('level_1'); $role->add_cap('level_0'); // Add caps for Contributor role $role = get_role('contributor'); $role->add_cap('edit_posts'); $role->add_cap('read'); $role->add_cap('level_1'); $role->add_cap('level_0'); // Add caps for Subscriber role $role = get_role('subscriber'); $role->add_cap('read'); $role->add_cap('level_0'); } /** * Create and modify WordPress roles for WordPress 2.1. * * @since 2.1.0 */ function populate_roles_210() { $roles = array('administrator', 'editor'); foreach ($roles as $role) { $role = get_role($role); if ( empty($role) ) continue; $role->add_cap('edit_others_pages'); $role->add_cap('edit_published_pages'); $role->add_cap('publish_pages'); $role->add_cap('delete_pages'); $role->add_cap('delete_others_pages'); $role->add_cap('delete_published_pages'); $role->add_cap('delete_posts'); $role->add_cap('delete_others_posts'); $role->add_cap('delete_published_posts'); $role->add_cap('delete_private_posts'); $role->add_cap('edit_private_posts'); $role->add_cap('read_private_posts'); $role->add_cap('delete_private_pages'); $role->add_cap('edit_private_pages'); $role->add_cap('read_private_pages'); } $role = get_role('administrator'); if ( ! empty($role) ) { $role->add_cap('delete_users'); $role->add_cap('create_users'); } $role = get_role('author'); if ( ! empty($role) ) { $role->add_cap('delete_posts'); $role->add_cap('delete_published_posts'); } $role = get_role('contributor'); if ( ! empty($role) ) { $role->add_cap('delete_posts'); } } /** * Create and modify WordPress roles for WordPress 2.3. * * @since 2.3.0 */ function populate_roles_230() { $role = get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'unfiltered_upload' ); } } /** * Create and modify WordPress roles for WordPress 2.5. * * @since 2.5.0 */ function populate_roles_250() { $role = get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'edit_dashboard' ); } } /** * Create and modify WordPress roles for WordPress 2.6. * * @since 2.6.0 */ function populate_roles_260() { $role = get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'update_plugins' ); $role->add_cap( 'delete_plugins' ); } } /** * Create and modify WordPress roles for WordPress 2.7. * * @since 2.7.0 */ function populate_roles_270() { $role = get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'install_plugins' ); $role->add_cap( 'update_themes' ); } } /** * Create and modify WordPress roles for WordPress 2.8. * * @since 2.8.0 */ function populate_roles_280() { $role = get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'install_themes' ); } } /** * Create and modify WordPress roles for WordPress 3.0. * * @since 3.0.0 */ function populate_roles_300() { $role = get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'update_core' ); $role->add_cap( 'list_users' ); $role->add_cap( 'remove_users' ); // Never used, will be removed. create_users or // promote_users is the capability you're looking for. $role->add_cap( 'add_users' ); $role->add_cap( 'promote_users' ); $role->add_cap( 'edit_theme_options' ); $role->add_cap( 'delete_themes' ); $role->add_cap( 'export' ); } } /** * Install Network. * * @since 3.0.0 * */ if ( !function_exists( 'install_network' ) ) : function install_network() { if ( ! defined( 'WP_INSTALLING_NETWORK' ) ) define( 'WP_INSTALLING_NETWORK', true ); dbDelta( wp_get_db_schema( 'global' ) ); } endif; /** * Populate network settings. * * @since 3.0.0 * * @param int $network_id ID of network to populate. * @return bool|WP_Error True on success, or WP_Error on warning (with the install otherwise successful, * so the error code must be checked) or failure. */ function populate_network( $network_id = 1, $domain = '', $email = '', $site_name = '', $path = '/', $subdomain_install = false ) { global $wpdb, $current_site, $wp_db_version, $wp_rewrite; $errors = new WP_Error(); if ( '' == $domain ) $errors->add( 'empty_domain', __( 'You must provide a domain name.' ) ); if ( '' == $site_name ) $errors->add( 'empty_sitename', __( 'You must provide a name for your network of sites.' ) ); // check for network collision if ( $network_id == $wpdb->get_var( $wpdb->prepare( "SELECT id FROM $wpdb->site WHERE id = %d", $network_id ) ) ) $errors->add( 'siteid_exists', __( 'The network already exists.' ) ); $site_user = get_user_by( 'email', $email ); if ( ! is_email( $email ) ) $errors->add( 'invalid_email', __( 'You must provide a valid e-mail address.' ) ); if ( $errors->get_error_code() ) return $errors; // set up site tables $template = get_option( 'template' ); $stylesheet = get_option( 'stylesheet' ); $allowed_themes = array( $stylesheet => true ); if ( $template != $stylesheet ) $allowed_themes[ $template ] = true; if ( WP_DEFAULT_THEME != $stylesheet && WP_DEFAULT_THEME != $template ) $allowed_themes[ WP_DEFAULT_THEME ] = true; if ( 1 == $network_id ) { $wpdb->insert( $wpdb->site, array( 'domain' => $domain, 'path' => $path ) ); $network_id = $wpdb->insert_id; } else { $wpdb->insert( $wpdb->site, array( 'domain' => $domain, 'path' => $path, 'id' => $network_id ) ); } if ( !is_multisite() ) { $site_admins = array( $site_user->user_login ); $users = get_users( array( 'fields' => array( 'ID', 'user_login' ) ) ); if ( $users ) { foreach ( $users as $user ) { if ( is_super_admin( $user->ID ) && !in_array( $user->user_login, $site_admins ) ) $site_admins[] = $user->user_login; } } } else { $site_admins = get_site_option( 'site_admins' ); } $welcome_email = __( 'Dear User, Your new SITE_NAME site has been successfully set up at: BLOG_URL You can log in to the administrator account with the following information: Username: USERNAME Password: PASSWORD Log in here: BLOG_URLwp-login.php We hope you enjoy your new site. Thanks! --The Team @ SITE_NAME' ); $sitemeta = array( 'site_name' => $site_name, 'admin_email' => $site_user->user_email, 'admin_user_id' => $site_user->ID, 'registration' => 'none', 'upload_filetypes' => 'jpg jpeg png gif mp3 mov avi wmv midi mid pdf', 'blog_upload_space' => 100, 'fileupload_maxk' => 1500, 'site_admins' => $site_admins, 'allowedthemes' => $allowed_themes, 'illegal_names' => array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator', 'files' ), 'wpmu_upgrade_site' => $wp_db_version, 'welcome_email' => $welcome_email, 'first_post' => __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' ), // @todo - network admins should have a method of editing the network siteurl (used for cookie hash) 'siteurl' => get_option( 'siteurl' ) . '/', 'add_new_users' => '0', 'upload_space_check_disabled' => is_multisite() ? get_site_option( 'upload_space_check_disabled' ) : '1', 'subdomain_install' => intval( $subdomain_install ), 'global_terms_enabled' => global_terms_enabled() ? '1' : '0', 'ms_files_rewriting' => is_multisite() ? get_site_option( 'ms_files_rewriting' ) : '0', 'initial_db_version' => get_option( 'initial_db_version' ), 'active_sitewide_plugins' => array(), 'WPLANG' => get_locale(), ); if ( ! $subdomain_install ) $sitemeta['illegal_names'][] = 'blog'; /** * Filter meta for a network on creation. * * @since 3.7.0 * * @param array $sitemeta Associative array of network meta keys and values to be inserted. * @param int $network_id ID of network to populate. */ $sitemeta = apply_filters( 'populate_network_meta', $sitemeta, $network_id ); $insert = ''; foreach ( $sitemeta as $meta_key => $meta_value ) { if ( is_array( $meta_value ) ) $meta_value = serialize( $meta_value ); if ( !empty( $insert ) ) $insert .= ', '; $insert .= $wpdb->prepare( "( %d, %s, %s)", $network_id, $meta_key, $meta_value ); } $wpdb->query( "INSERT INTO $wpdb->sitemeta ( site_id, meta_key, meta_value ) VALUES " . $insert ); // When upgrading from single to multisite, assume the current site will become the main site of the network. // When using populate_network() to create another network in an existing multisite environment, // skip these steps since the main site of the new network has not yet been created. if ( ! is_multisite() ) { $current_site = new stdClass; $current_site->domain = $domain; $current_site->path = $path; $current_site->site_name = ucfirst( $domain ); $wpdb->insert( $wpdb->blogs, array( 'site_id' => $network_id, 'blog_id' => 1, 'domain' => $domain, 'path' => $path, 'registered' => current_time( 'mysql' ) ) ); $current_site->blog_id = $blog_id = $wpdb->insert_id; update_user_meta( $site_user->ID, 'source_domain', $domain ); update_user_meta( $site_user->ID, 'primary_blog', $blog_id ); if ( $subdomain_install ) $wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%day%/%postname%/' ); else $wp_rewrite->set_permalink_structure( '/blog/%year%/%monthnum%/%day%/%postname%/' ); flush_rewrite_rules(); if ( ! $subdomain_install ) return true; $vhost_ok = false; $errstr = ''; $hostname = substr( md5( time() ), 0, 6 ) . '.' . $domain; // Very random hostname! $page = wp_remote_get( 'http://' . $hostname, array( 'timeout' => 5, 'httpversion' => '1.1' ) ); if ( is_wp_error( $page ) ) $errstr = $page->get_error_message(); elseif ( 200 == wp_remote_retrieve_response_code( $page ) ) $vhost_ok = true; if ( ! $vhost_ok ) { $msg = '<p><strong>' . __( 'Warning! Wildcard DNS may not be configured correctly!' ) . '</strong></p>'; $msg .= '<p>' . sprintf( __( 'The installer attempted to contact a random hostname (<code>%1$s</code>) on your domain.' ), $hostname ); if ( ! empty ( $errstr ) ) $msg .= ' ' . sprintf( __( 'This resulted in an error message: %s' ), '<code>' . $errstr . '</code>' ); $msg .= '</p>'; $msg .= '<p>' . __( 'To use a subdomain configuration, you must have a wildcard entry in your DNS. This usually means adding a <code>*</code> hostname record pointing at your web server in your DNS configuration tool.' ) . '</p>'; $msg .= '<p>' . __( 'You can still use your site but any subdomain you create may not be accessible. If you know your DNS is correct, ignore this message.' ) . '</p>'; return new WP_Error( 'no_wildcard_dns', $msg ); } } return true; }
gpl-2.0
sam-suresh/joomla-cms
layouts/joomla/edit/associations.php
703
<?php /** * @package Joomla.Site * @subpackage Layout * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; // JLayout for standard handling of associations fields in the administrator items edit screens. $fields = $displayData->get('form')->getFieldset('item_associations'); ?> <fieldset> <?php foreach ($fields as $field) : ?> <div class="control-group"> <div class="control-label"> <?php echo $field->label; ?> </div> <div class="controls"> <?php echo $field->input; ?> </div> </div> <?php endforeach; ?> </fieldset>
gpl-2.0
panhainan/fire
src/org/phn/dao/impl/UserDaoImpl.java
1211
package org.phn.dao.impl; import java.util.List; import org.phn.bean.User; import org.phn.dao.IUserDao; /** * @author phn * @date 2015-4-8 * @TODO */ public class UserDaoImpl extends JDBCDaoSupport<User> implements IUserDao { public int save(User user) { String insertSql = "insert into t_user(uname,upass) values(?,?)"; return super.executeInsert(insertSql, user.getUname(),user.getUpass()); } public int update(User user) { String updateSql = "update t_user set uname=?,upass=? where id=?"; return super.executeUpdateAndDelete(updateSql, user.getUname(),user.getUpass(),user.getId()); } public int delete(int userId) { String deleteSql = "delete from t_user where id=?"; return super.executeUpdateAndDelete(deleteSql,userId); } public User get(int userId) { String getSql = "select * from t_user where id=?"; return super.executeGet(getSql, userId, User.class); } public List<User> list(int pageSize,int startRecord){ String listSql = "select * from t_user limit ?,?"; return super.executeList(listSql,User.class,startRecord,pageSize); } public int countRow() { String getCountSql = "select count(*) from t_user"; return super.getCountRow(getCountSql); } }
gpl-2.0
tatsuhirosatou/JMdictDB
web/cgi/updates.py
8396
#!/usr/bin/env python3 ####################################################################### # This file is part of JMdictDB. # Copyright (c) 2010 Stuart McGraw # # JMdictDB is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published # by the Free Software Foundation; either version 2 of the License, # or (at your option) any later version. # # JMdictDB is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with JMdictDB; if not, write to the Free Software Foundation, # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA ####################################################################### # Display entries that were added or updated on a given date (that # is, have a history entry with that date) or alternately, an index # page that shows date links to pages for the entries updated on that # date. # # URL parameters: # i -- Display an index page listing dates for which there # are undates. Each date is a link which when clicked # will display the actual updates made on that date. # Only one year of dates is shown; the year is specified # with the 'y' parameter. If 'i' is not present, a page # showing the actual entries updated on the date given # by 'y', 'm', 'd' will be shown with the entr.tal template. # y, m, d -- The year, month (1-12) and day (1-31) giving a # date. If 'i' was not given, the updates made on this # date will be shown. If 'i' was given, 'm' and 'd' are # ignored and an index page for the year 'y' is shown. # If any of 'y', 'm' or 'd' are missing, its value will # be taken from the current date. # n -- A integer greater than 0 that is a number of days that # will be subtracted from the date given with the other # parameters. This is primarily used with the value 1 # to get "yesterday's" updates but will work consistently # with other values. # [other] -- The standard jmdictdb cgi parameters like 'svc', # 'sid', etc. See python/lib/jmcgi.py. import sys, cgi, datetime sys.path.extend (['../lib','../../python/lib','../python/lib']) import logger; from logger import L; logger.enable() import jdb, jmcgi def main (args, opts): jdb.reset_encoding (sys.stdout, 'utf-8') try: form, svc, dbg, cur, sid, sess, parms, cfg = jmcgi.parseform() except Exception as e: jmcgi.err_page ([str (e)]) formvalues = form, svc, dbg, cur, sid, sess, parms, cfg fv = form.getfirst; fl = form.getlist t = datetime.date.today() # Will supply default value of y, m, d. # y, m, and d below are used to construct sql string and *must* # be forced to int()'s to eliminate possibiliy of sql injection. try: y = int (fv ('y') or t.year) except Exception as e: jmcgi.err_page ("Bad 'y' url parameter."); return show_index = bool (fv ('i')) if show_index: render_year_index (y, formvalues) else: try: m = int (fv ('m') or t.month) d = int (fv ('d') or t.day) n = int (fv ('n') or 0) except Exception as e: jmcgi.err_page ("Bad 'm', 'd' or 'n' url parameter."); return render_day_updates (y, m, d, n, formvalues) def render_day_updates (y, m, d, n, formvalues): # If we have a specific date, we will show the actual entries that # were modified on that date. We do this by retrieving Entr's for # any entries that have a 'hist' row with a 'dt' date on that day. # The Entr's are displayed using the standard entr.tal template # that is also used for displaying other "list of entries" results # (such as from the Search Results page). cur = formvalues[3] sql = '''SELECT DISTINCT e.id FROM entr e JOIN hist h on h.entr=e.id WHERE h.dt BETWEEN %s::timestamp AND %s::timestamp + interval '1 day' ''' day = datetime.date (y, m, d) if n: # 'n' is used to adjust the given date backwards by 'n' days. # Most frequently it is used with a value of 1 in conjuction # with "today's" date to get entries updated "yesterday" but # for consistency we make it work for any date and any value # of 'n'. day = day - datetime.timedelta (n) y, m, d = day.year, day.month, day.day entries = jdb.entrList (cur, sql, (day,day,), 'x.src,x.seq,x.id') # Prepare the entries for display... Augment the xrefs (so that # the xref seq# and kanji/reading texts can be shown rather than # just an entry id number. Do same for sounds. for e in entries: for s in e._sens: if hasattr (s, '_xref'): jdb.augment_xrefs (cur, s._xref) if hasattr (s, '_xrer'): jdb.augment_xrefs (cur, s._xrer, 1) if hasattr (e, '_snd'): jdb.augment_snds (cur, e._snd) cur.close() jmcgi.htmlprep (entries) jmcgi.add_filtered_xrefs (entries, rem_unap=True) form, svc, dbg, cur, sid, sess, parms, cfg = formvalues jmcgi.jinja_page ('entr.jinja', entries=zip(entries, [None]*len(entries)), disp=None, svc=svc, dbg=dbg, sid=sid, session=sess, cfg=cfg, parms=parms, this_page='updates.py') def render_year_index (y, formvalues): # If 'i' was given in the URL params we will generate an index # page showing dates, with each date being a link back to this # script with the result that clicking it will show the updates # (viw render_day_update() above) for that date. The range of # the dates are limited to one year. # Also on the page we generate links for each year for which # there are updates in the database. Those links also points # back to this script but with 'i' and a year, so that when # clicked, they will generate a daily index for that year. cur = formvalues[3] # Get a list of dates (in the form: year, month, day, count) # for year = 'y' for with there are hist records. 'count' is # the number of number of hist records with the coresponding # date. # Following can by simplified when using postgresql-9.4: # see changeset jm:b930b6fd1e3b (2015-08-19) start_of_year = '%d-01-01' % y end_of_year = '%d-12-31' % y sql = '''SELECT EXTRACT(YEAR FROM dt)::INT AS y, EXTRACT(MONTH FROM dt)::INT AS m, EXTRACT(DAY FROM dt)::INT AS d, COUNT(*) FROM hist h WHERE dt BETWEEN '%s'::DATE AND '%s'::DATE GROUP BY EXTRACT(YEAR FROM dt)::INT,EXTRACT(MONTH FROM dt)::INT,EXTRACT(DAY FROM dt)::INT ORDER BY EXTRACT(YEAR FROM dt)::INT,EXTRACT(MONTH FROM dt)::INT,EXTRACT(DAY FROM dt)::INT ''' % (start_of_year, end_of_year) cur.execute (sql, (y,y)) days = cur.fetchall() # Get a list of years (in the form: year, count) for which there # are history records. 'count' is the total number in the year. sql = '''SELECT EXTRACT(YEAR FROM dt)::INT AS y, COUNT(*) FROM hist h GROUP BY EXTRACT(YEAR FROM dt)::INT ORDER BY EXTRACT(YEAR FROM dt)::INT DESC;''' cur.execute (sql, ()) years = cur.fetchall() form, svc, dbg, cur, sid, sess, parms, cfg = formvalues jmcgi.jinja_page ('updates.jinja', years=years, year=y, days=days, disp=None, svc=svc, dbg=dbg, sid=sid, session=sess, cfg=cfg, parms=parms, this_page='updates.py') if __name__ == '__main__': args, opts = jmcgi.args() main (args, opts)
gpl-2.0
gremp/xza
wp-content/themes/colorbow/lib/php/tools.class.php
5282
<?php class tools{ function primary_class( $post_id , $template, $return_just_class = false ){ if($return_just_class){ return layout::length( $post_id , $template , true ); }else{ echo 'class="' . layout::length( $post_id , $template , true ) . '"'; } } function content_class( $post_id , $template , $side = '' , $with_grid = true ){ $grid = self::is_grid( $template , $side ); echo 'class="w_' . layout::length( $post_id , $template ) . ' ' . str_replace( '_' , '-' , $template ) . ' '; if( $with_grid ){ if( $grid ){ echo 'grid-view'; }else{ echo 'list-view'; } } echo '"'; } function entry_class( $post_id , $template , $classes = '' ){ ob_start(); ob_clean(); $left = layout::side( 'left' , $post_id , $template ); if( layout::length( $post_id , $template ) == layout::$size['large'] ){ $classes .= ' b w_290'; }else{ if( $left ){ $classes .= ' w_610'; }else{ $classes .= ' w_610'; } } ob_get_clean(); echo 'class="' . $classes . '"'; } static function login_attr( $post_id , $type , $url = '' ){ if( strlen( $url) ){ $result = 'href="' . $url . '"'; }else{ $result = ''; } return $result; } static function is_grid( $template , $side = '' ){ $grid = false; if( isset( $_COOKIE[ZIP_NAME.'_grid_' . $template . $side ] ) ){ if( $_COOKIE[ZIP_NAME.'_grid_' . $template . $side ] == 'grid' ){ $grid = true; }else{ $grid = false; } }else{ if( strlen( $side ) ){ if( options::logic( 'front_page' , 'v' . $side ) ){ $grid = false; }else{ $grid = true; } }else{ if( options::logic( 'layout' , 'v_' . $template ) ){ $grid = false; }else{ $grid = true; } } } return $grid; } static function tour( $pos , $location , $id , $type , $title , $body , $nr , $next = true ){ $nrs = explode('/' , $nr ); /* stap */ if( isset( $_COOKIE[ ZIP_NAME.'_tour_stap_' . $location . '_' . $id ] ) && (int)$_COOKIE[ ZIP_NAME.'_tour_stap_' . $location . '_' . $id ] > 0 ){ $k = $_COOKIE[ ZIP_NAME.'_tour_stap_' . $location . '_' . $id ] + 1; }else{ $k = 1; } if( $nrs[0] == $k ){ $classes = ''; }else{ $classes = 'hidden'; } ?> <div class="demo-tooltip <?php echo $classes; ?>" index="<?php echo $nrs[0] - 1; ?>" rel="<?php echo $location . '_' . $id; ?>" style="top: <?php echo $pos[0]; ?>px; left: <?php echo $pos[1]; ?>px; "><!--Virtual guide starts here. Set coordinates top and left--> <span class="arrow <?php echo $type; ?>">&nbsp;</span><!--Available arrow position: left, right, top --> <header class="demo-steps"> <strong class="fl"><?php echo stripslashes($title); ?></strong> <span class="fr"><?php echo $nr; ?></span><!--Step number from--> </header> <div class="demo-content"> <?php echo stripslashes( $body ); ?> <?php if( $next ){ ?> <p class="fr close"><a href="#" class="close"><?php _e( 'Do not show hints anymore' , 'cosmotheme' ); ?></a></p> <?php } ?> </div> <footer class="demo-buttons"> <?php if( $next ){ ?> <p class="fl button-small gray"><a href="javascript:void(0)" class="next"><?php _e( 'Next feature' , 'cosmotheme' ); ?></a></p> <p class="fr button-small blue"><a href="javascript:void(0)" class="skip"><?php _e( 'Skip' , 'cosmotheme' ); ?></a></p> <?php }else{ ?><p class="fr button-small red"><a href="javascript:void(0)" class="close"><?php _e( 'Close' , 'cosmotheme' ); ?></a></p><?php } ?> </footer> </div> <?php } } ?>
gpl-2.0
shatu/FOX
src/main/java/org/aksw/fox/utils/FoxJena.java
12649
package org.aksw.fox.utils; import java.io.StringWriter; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.aksw.fox.data.Entity; import org.aksw.fox.data.Relation; import org.apache.commons.validator.routines.UrlValidator; import org.apache.jena.riot.Lang; import org.apache.jena.riot.RDFDataMgr; import org.apache.jena.riot.RDFLanguages; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.XSD; // for future: http://www.w3.org/ns/oa# /** * * * @author rspeck * */ public class FoxJena { public static Logger LOG = LogManager.getLogger(FoxJena.class); public static final List<String> prints = Arrays.asList( Lang.RDFXML.getName(), /* FileUtils.langXMLAbbrev,*/ Lang.TURTLE.getName(), Lang.NTRIPLES.getName(), // Lang.N3.getName(), Lang.RDFJSON.getName(), Lang.JSONLD.getName(), Lang.TRIG.getName(), Lang.NQUADS.getName() ); /* public static enum RelationEnum { employeeOf("employeeOf"), hasPosition("hasPosition"), hasDegree("hasDegree"); public final String label; RelationEnum(String label) { this.label = label; } }; */ /* namespace */ public static final String nsDBpediaOwl = "http://dbpedia.org/ontology/"; public static final String nsDBpedia = "http://dbpedia.org/resource/"; public static final String nsAnn = "http://www.w3.org/2000/10/annotation-ns#"; public static final String nsCTag = "http://commontag.org/ns#"; public static final String nsScms = "http://ns.aksw.org/scms/"; public static final String nsScmsann = "http://ns.aksw.org/scms/annotations/"; public static final String nsScmsannStanford = "http://ns.aksw.org/scms/annotations/stanford/"; public static final String nsScmssource = "http://ns.aksw.org/scms/tools/"; /* properties */ protected Property annotation, beginIndex, endIndex, means, source, body, ctagLabel, ctagMeans, ctagAutoTag, relationProperty, relationTypeProperty, s, t; protected Property[] scmsRelationLabels; /* model */ protected Model graph = null; protected UrlValidator urlValidator = new UrlValidator(); public void initGraph() { graph = ModelFactory.createDefaultModel(); // create namespace prefix // graph.setNsPrefix("dbpedia-owl", nsDBpediaOwl); graph.setNsPrefix("dbpedia", nsDBpedia); graph.setNsPrefix("ann", nsAnn); graph.setNsPrefix("scms", nsScms); // graph.setNsPrefix("rdf", RDF.getURI()); // graph.setNsPrefix("ctag", nsCTag); graph.setNsPrefix("xsd", XSD.getURI()); graph.setNsPrefix("scmsann", nsScmsann); graph.setNsPrefix("stanford", nsScmsannStanford); graph.setNsPrefix("source", nsScmssource); // NER properties annotation = graph.createProperty(nsAnn + "Annotation"); beginIndex = graph.createProperty(nsScms + "beginIndex"); endIndex = graph.createProperty(nsScms + "endIndex"); means = graph.createProperty(nsScms + "means"); source = graph.createProperty(nsScms + "source"); body = graph.createProperty(nsAnn + "body"); s = graph.createProperty(nsScms + "s"); t = graph.createProperty(nsScms + "t"); // KE properties ctagLabel = graph.createProperty(nsCTag + "label"); ctagMeans = graph.createProperty(nsCTag + "means"); ctagAutoTag = graph.createProperty(nsCTag + "AutoTag"); // RE relationProperty = graph.createProperty(nsScms + "relation"); relationTypeProperty = graph.createProperty(nsScms + "relationType"); /* RelationEnum[] relationEnum = RelationEnum.values(); scmsRelationLabels = new Property[relationEnum.length]; for (int i = 0; i < scmsRelationLabels.length; i++) scmsRelationLabels[relationEnum[i].ordinal()] = graph.createProperty(nsScms + relationEnum[i].label); */ } public void clearGraph() { initGraph(); } public Model getGraph() { return graph; } /** * Adds entities to graph. */ public void setAnnotations(Set<Entity> set) { if (graph == null) initGraph(); if (set == null) return; for (Entity entity : set) if (!urlValidator.isValid(entity.uri)) LOG.error("uri isn't valid: " + entity.uri); else { Resource resource = graph.createResource(); resource.addProperty(RDF.type, annotation); resource.addProperty(RDF.type, graph.createProperty(nsScmsann + entity.getType())); for (Integer index : entity.getIndices()) { resource.addLiteral(beginIndex, graph.createTypedLiteral(new Integer(index))); resource.addLiteral(endIndex, graph.createTypedLiteral(new Integer(index + entity.getText().length()))); } resource.addProperty(means, graph.createResource(entity.uri)); resource.addProperty(source, graph.createResource(nsScmssource + entity.getTool())); resource.addLiteral(body, entity.getText()); } } /* public void setRelations2(Set<Relation> relations) { if (graph == null) initGraph(); if (relations == null || relations.isEmpty()) return; for (Relation relation : relations) { Entity oe = relation.getObjectEntity(); Entity se = relation.getSubjectEntity(); Resource roe = null; Resource rse = null; ResIterator iterEntities = graph.listSubjectsWithProperty(RDF.type, annotation); while (iterEntities.hasNext()) { Resource resource = iterEntities.nextResource(); int index = resource.getProperty(beginIndex).getLiteral().getInt(); if (oe.getIndices().contains(index)) { roe = resource; } else if (se.getIndices().contains(index)) { rse = resource; } } if (roe != null && rse != null) { Resource resRel = graph.createResource(rse.getProperty(means).getObject().toString()); Property proBlank = graph.createProperty(""); Resource blank = graph.createResource(); resRel.addProperty(proBlank, blank); for (URI uri : relation.getRelation()) { blank.addProperty(relationTypeProperty, graph.createResource(uri.toString())); } blank.addProperty(relationProperty, roe.getPropertyResourceValue(means)); } } } */ /** * Adds relations to graph. * * @param relations */ public void setRelations(Set<Relation> relations) { if (graph == null) initGraph(); if (relations == null || relations.isEmpty()) return; Set<Relation> nofound = new HashSet<>(); for (Relation relation : relations) { Entity oe = relation.getObjectEntity(); Entity se = relation.getSubjectEntity(); Resource roe = null; Resource rse = null; ResIterator iterEntities = graph.listSubjectsWithProperty(RDF.type, annotation); while (iterEntities.hasNext()) { Resource resource = iterEntities.nextResource(); for (Statement indicies : resource.listProperties(beginIndex).toSet()) { int index = indicies.getInt(); if (oe.getIndices().contains(index)) { roe = resource; } else if (se.getIndices().contains(index)) { rse = resource; } } } if (roe != null && rse != null) { Resource resRel = graph.createResource(rse.getProperty(means).getObject().toString()); for (URI uri : relation.getRelation()) { resRel.addProperty(graph.createProperty(uri.toString()), roe.getPropertyResourceValue(means)); } } else { nofound.add(relation); if (LOG.isDebugEnabled()) { LOG.debug("not found: "); LOG.debug(relation); } } } relations.removeAll(nofound); } /** * Prints the model in a given format. * * @param kind * output format * @param nif * true to use nif * @param wholeText * the used text * * @return result in a string */ public String print(String kind, boolean nif, String wholeText) { if (graph == null) return null; StringWriter sw = new StringWriter(); if (FoxJena.prints.contains(kind)) { RDFDataMgr.write(sw, graph, RDFLanguages.nameToLang(kind)); } else { try { graph.write(sw, kind); } catch (Exception e) { LOG.error("\n Output format " + kind + " is not supported.", e); } } return sw.toString(); } public static void main(String args[]) { // test data DataTestFactory dtf = new DataTestFactory(); Set<Entity> entities = new ArrayList<Set<Entity>>(dtf.getTestEntities().values()).get(0); Set<Relation> relations = dtf.getTestRelations().entrySet().iterator().next().getValue(); String input = dtf.getTestEntities().entrySet().iterator().next().getKey(); // test FoxJena fj = new FoxJena(); fj.setAnnotations(entities); fj.setRelations(relations); String out = fj.print(FoxJena.prints.get(1), false, input); System.out.println(out); } /* public static void main(String args[]) { // create an empty graph Model graph = ModelFactory.createDefaultModel(); // create the resource Resource resource = graph.createResource(); // add the property resource .addProperty(RDFS.label, graph.createLiteral("chat", "en")) .addProperty(RDFS.label, graph.createLiteral("chat", "fr")) .addProperty(RDFS.label, graph.createLiteral("<em>chat</em>", true)); // write out the graph graph.write(new PrintWriter(System.out)); System.out.println(); // create an empty graph graph = ModelFactory.createDefaultModel(); // create the resource resource = graph.createResource(); // add the property resource .addProperty(RDFS.label, "11") .addLiteral(RDFS.label, 11); // write out the graph graph.write(System.out, FoxJena.prints.get(3)); } */ }
gpl-2.0
zapster/cacao-travis
src/vm/jit/mips/uclinux/md-os.cpp
2345
/* src/vm/jit/mips/uclinux/md-os.cpp - machine dependent MIPS uClinux functions Copyright (C) 1996-2013 CACAOVM - Verein zur Foerderung der freien virtuellen Maschine CACAO This file is part of CACAO. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include <signal.h> #include <ucontext.h> #include "vm/types.hpp" #include "vm/vm.hpp" /* md_init ********************************************************************* Do some machine dependent initialization. *******************************************************************************/ void md_init(void) { } /* md_signal_handler_sigsegv *************************************************** NullPointerException signal handler for hardware null pointer check. *******************************************************************************/ void md_signal_handler_sigsegv(int sig, siginfo_t *siginfo, void *_p) { vm_abort("md_signal_handler_sigsegv: IMPLEMENT ME!"); } /* md_signal_handler_sigusr2 *************************************************** DOCUMENT ME *******************************************************************************/ void md_signal_handler_sigusr2(int sig, siginfo_t *siginfo, void *_p) { vm_abort("md_signal_handler_sigusr2: IMPLEMENT ME!"); } /* * These are local overrides for various environment variables in Emacs. * Please do not remove this and leave it at the end of the file, where * Emacs will automagically detect them. * --------------------------------------------------------------------- * Local variables: * mode: c * indent-tabs-mode: t * c-basic-offset: 4 * tab-width: 4 * End: * vim:noexpandtab:sw=4:ts=4: */
gpl-2.0
npag/JarVIs-Server
Jarvis/Jarvis/Webinterface/js/jarvis_api.js
819
function httpGetAsync(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { //alert("RESPONSE: " + xmlHttp.responseText); } } xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.send(null); } function lightOn(code) { httpGetAsync("http://" + window.location.host + "/?j=%5B%7B%22Type%22%3A0%2C%22JobJsonString%22%3A%22%7B%5C%22Subjects%5C%22%3A%5B%7B%5C%22SwitchCode%5C%22%3A%5C%22" + code + "%5C%22%7D%5D%7D%22%7D%5D"); } function lightOff(code) { httpGetAsync("http://" + window.location.host + "/?j=%5B%7B%22Type%22%3A1%2C%22JobJsonString%22%3A%22%7B%5C%22Subjects%5C%22%3A%5B%7B%5C%22SwitchCode%5C%22%3A%5C%22" + code + "%5C%22%7D%5D%7D%22%7D%5D"); }
gpl-2.0
vzwingma/automationManager
automationCommons/src/main/java/com/terrier/utilities/automation/bundles/communs/utils/replace/IReplacePattern.java
429
/** * */ package com.terrier.utilities.automation.bundles.communs.utils.replace; /** * Interface de patterns de remplacement * @author vzwingma * */ public interface IReplacePattern { /** * @param chaineSource * @return chaine transformée par le pattern */ String replace(String chaineSource, String pattern); /** * @return la description du pattern */ String toString(); }
gpl-2.0
Myvar/eStd
eStd/System.Statemachine/ParameterConversionResources.Designer.cs
3899
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Stateless { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class ParameterConversionResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal ParameterConversionResources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Stateless.ParameterConversionResources", typeof(ParameterConversionResources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to An argument of type {0} is required in position {1}.. /// </summary> internal static string ArgOfTypeRequiredInPosition { get { return ResourceManager.GetString("ArgOfTypeRequiredInPosition", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Too many parameters have been supplied. Expecting {0} but got {1}.. /// </summary> internal static string TooManyParameters { get { return ResourceManager.GetString("TooManyParameters", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The argument in position {0} is of type {1} but must be of type {2}.. /// </summary> internal static string WrongArgType { get { return ResourceManager.GetString("WrongArgType", resourceCulture); } } } }
gpl-2.0
jessi1411/hallo
wp-content/themes/hallo/content.php
1022
<?php /** * @package hallo */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( sprintf( '<h1 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h1>' ); ?> <?php if ( 'post' == get_post_type() ) : ?> <div class="entry-meta"> <?php hallo_posted_on(); ?> </div><!-- .entry-meta --> <?php endif; ?> </header><!-- .entry-header --> <div class="entry-content"> <?php /* translators: %s: Name of current post */ the_content( sprintf( __( 'Continue reading %s <span class="meta-nav">&rarr;</span>', 'hallo' ), the_title( '<span class="screen-reader-text">"', '"</span>', false ) ) ); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'hallo' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <?php hallo_entry_footer(); ?> </footer><!-- .entry-footer --> </article><!-- #post-## -->
gpl-2.0
wskm/deruv
i18n/zh-CN/tool.php
136
<?php return [ 'Generate target' => '生成目标', 'Generate content' => '生成内容', 'Save Dir' => '保存目录', ];
gpl-2.0
creasyw/IMTAphy
modules/dll/glue/src/arqfsm/stopandwait/FSMFU.cpp
2645
/****************************************************************************** * WNS (Wireless Network Simulator) * * __________________________________________________________________________ * * * * Copyright (C) 2004-2006 * * Chair of Communication Networks (ComNets) * * Kopernikusstr. 16, D-52074 Aachen, Germany * * phone: ++49-241-80-27910 (phone), fax: ++49-241-80-22242 * * email: [email protected] * * www: http://wns.comnets.rwth-aachen.de * ******************************************************************************/ #include <GLUE/arqfsm/stopandwait/FSMFU.hpp> #include <GLUE/arqfsm/stopandwait/ReadyForTransmission.hpp> using namespace glue::arqfsm::stopandwait; using namespace wns::ldk; STATIC_FACTORY_REGISTER_WITH_CREATOR(FSMFU, FunctionalUnit, "glue.arqfsm.stopandwait.FSMFU", FUNConfigCreator); FSMFU::FSMFU(fun::FUN* fun, const wns::pyconfig::View& _config) : MyFUInterface(Variables(_config)), wns::ldk::CommandTypeSpecifier<StopAndWaitCommand>(fun), wns::ldk::HasReceptor<>(), wns::ldk::HasConnector<>(), wns::ldk::HasDeliverer<>(), wns::ldk::SuspendSupport(fun, _config), wns::Cloneable<FSMFU>(), config(_config), bitsPerIFrame(config.get<int>("bitsPerIFrame")), bitsPerRRFrame(config.get<int>("bitsPerRRFrame")) { changeState(createState<ReadyForTransmission>()); } // FSMFU void FSMFU::calculateSizes(const CommandPool* commandPool, Bit& commandPoolSize, Bit& sduSize) const { // What are the sizes in the upper FUs? getFUN()->calculateSizes(commandPool, commandPoolSize, sduSize, this); StopAndWaitCommand* command = getCommand(commandPool); switch(command->peer.type) { case StopAndWaitCommand::I: commandPoolSize += bitsPerIFrame; break; case StopAndWaitCommand::ACK: commandPoolSize += bitsPerRRFrame; break; } } // calculateSizes void FSMFU::onTimeout() { assureType(this->getState(), BaseState*); BaseState* bs = dynamic_cast<BaseState*>(this->getState()); do { ++inAction; BaseFSM::StateInterface* stateInterface = bs->onTimeout(); --inAction; this->changeState(stateInterface); } while (linkHandler()); return; } // onTimeout bool FSMFU::onSuspend() const { return getStateName() == std::string("glue_arqfsm_stopandwait_ReadyForTransmission"); } // onSuspend
gpl-2.0
Open-Transport/synthese
server/src/34_road/Address.cpp
2854
/** Address class implementation. @file Address.cpp This file belongs to the SYNTHESE project (public transportation specialized software) Copyright (C) 2002 Hugues Romain - RCSmobility <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Address.h" #include "AccessParameters.h" #include "Crossing.h" #include "Road.h" #include "RoadChunkEdge.hpp" #include "RoadModule.h" #include "VertexAccessMap.h" using namespace std; using namespace boost; using namespace boost::posix_time; using namespace geos::geom; namespace synthese { using namespace geography; using namespace graph; using namespace road; using namespace util; namespace road { Address::Address ( RoadChunk& roadChunk, double metricOffset, optional<HouseNumber> houseNumber ): WithGeometry<Point>( roadChunk.getGeometry().get() ? roadChunk.getPointFromOffset(metricOffset) : boost::shared_ptr<geos::geom::Point>() ), _roadChunk(&roadChunk), _metricOffset(metricOffset), _houseNumber(houseNumber) { } Address::Address() : _roadChunk(NULL), _metricOffset(0) { } Address::~Address() { } void Address::getVertexAccessMap( graph::VertexAccessMap& result, const graph::AccessParameters& accessParameters, const Place::GraphTypes& whatToSearch ) const { // RULE-109 if(whatToSearch.find(RoadModule::GRAPH_ID) != whatToSearch.end()) { // Chunk linked with the house { double distance(_metricOffset); result.insert( _roadChunk->getFromCrossing(), VertexAccess( seconds(static_cast<long>(distance / accessParameters.getApproachSpeed())), distance ) ); } // Reverse chunk if(_roadChunk->getForwardEdge().getNext()) { assert(static_cast<RoadChunkEdge*>(_roadChunk->getForwardEdge().getNext())); double distance(_roadChunk->getForwardEdge().getEndMetricOffset() - _roadChunk->getMetricOffset() - _metricOffset); result.insert( _roadChunk->getForwardEdge().getNext()->getFromVertex(), VertexAccess( seconds(static_cast<long>(distance / accessParameters.getApproachSpeed())), distance ) ); } } } } }
gpl-2.0
poulson/plink
sets.cpp
26320
////////////////////////////////////////////////////////////////// // // // PLINK (c) 2005-2008 Shaun Purcell // // (c) 2014 Jack Poulson // // // This file is distributed under the GNU General Public // // License, Version 2. Please see the file COPYING for more // // details // // // ////////////////////////////////////////////////////////////////// #include <iostream> #include <algorithm> #include "plink.h" #include "sets.h" #include "options.h" #include "helper.h" #include "model.h" #include "stats.h" #include "phase.h" extern Plink * PP; Set::Set(vector<vector<int> > & ss) : snpset(ss) { sizeSets(); } void Set::sizeSets() { cur.resize(snpset.size()); for(int s=0;s<snpset.size();s++) cur[s].resize(snpset[s].size(),true); // Specific to SET-based tests if ( (par::assoc_test || par::TDT_test ) && par::set_test && !par::hotel) { s_min.resize(snpset.size()); s_max.resize(snpset.size()); stat_set.resize(snpset.size()); pv_set.resize(snpset.size()); pv_maxG_set.resize(snpset.size()); pv_maxE_set.resize(snpset.size()); for(int i=0;i<snpset.size();i++) { // If no constraints given, then the // number of tests == size of set if (par::set_min==-1 ) s_min[i] = 0; else if (par::set_min > snpset[i].size() ) s_min[i] = snpset[i].size(); else s_min[i] = par::set_min-1; if (par::set_max==-1 || par::set_max > snpset[i].size() ) s_max[i] = snpset[i].size(); else s_max[i] = par::set_max; if (s_min>s_max) s_min[i]=s_max[i]; int s = (s_max[i] - s_min[i]); stat_set[i].resize(s); pv_set[i].resize(s); pv_maxG_set[i].resize(s); pv_maxE_set[i].resize(s); if ( ! par::set_score ) { for (int j=0; j<s; j++) stat_set[i][j].resize(par::replicates+1); } for (int j=0; j<s; j++) pv_set[i][j].resize(par::replicates+1); } } } ////////////////////////////////////////////////////// // // // Remove 0-sized sets // // // ////////////////////////////////////////////////////// void Set::pruneSets(Plink & P) { int pruned=0; for(int i=0;i<snpset.size();i++) { if (snpset[i].size() == 0) { snpset.erase(snpset.begin()+i); P.setname.erase(P.setname.begin()+i); i--; pruned++; } } P.printLOG(int2str(pruned)+" sets removed (0 valid SNPs)\n"); // Resize all the other set arrays sizeSets(); } ////////////////////////////////////////////////////// // // // Prune sets based on multi-collinearity // // // ////////////////////////////////////////////////////// void Set::pruneMC(Plink & P, bool disp,double VIF_threshold) { P.printLOG("Pruning sets based on variance inflation factor\n"); for (int s=0; s<snpset.size(); s++) { if (!par::silent) cout << s+1 << " of " << snpset.size() << " sets pruned \r"; int nss = snpset[s].size(); vector<double> mean; // Sample mean vector<vector<double> > var; // Covariance matrix vector<int> nSNP(0); for (int j=0; j<nss; j++) { nSNP.push_back( snpset[s][j] ); } // Calculate covariance matrix (full sample) // (sizes and populates mean and var) // this routine uses the 'flag' variable var = calcSetCovarianceMatrix(nSNP); // Perform VIF pruning, setting filters (S.cur[][]) vector<bool> p = vif_prune(var,VIF_threshold,nSNP); for (int i=0; i<nss; i++) if (!p[i]) cur[s][i]=false; } if (!par::silent) cout << "\n"; if (disp) { ofstream SET1, SET2; string f = par::output_file_name + ".set.in"; P.printLOG("Writing pruned-in set file to [ " + f + " ]\n"); SET1.open(f.c_str(),ios::out); f = par::output_file_name + ".set.out"; P.printLOG("Writing pruned-out set file to [ " + f + " ]\n"); SET2.open(f.c_str(),ios::out); for (int s=0; s<snpset.size(); s++) { int nss = snpset[s].size(); SET1 << P.setname[s] << "\n"; SET2 << P.setname[s] << "\n"; for (int j=0; j<nss; j++) { if (cur[s][j]) SET1 << P.locus[snpset[s][j]]->name << "\n"; else SET2 << P.locus[snpset[s][j]]->name << "\n"; } SET1 << "END\n\n"; SET2 << "END\n\n"; } SET1.close(); SET2.close(); } } ////////////////////////////////////////////////////// // // // Remove SNPs not in any set // // // ////////////////////////////////////////////////////// void Set::dropNotSet(Plink & P) { ///////////////////////////////////////////// // Drop any SNPs that do not belong in a set vector<bool> drop(P.nl_all,true); for (int i=0;i<snpset.size();i++) { for (int j=0; j < snpset[i].size(); j++) { drop[snpset[i][j]] = false; } } map<int,int> nmap; int cnt = 0; for (int l=0; l<P.nl_all; l++) if ( ! drop[l] ) nmap.insert( make_pair( l , cnt++ ) ); P.deleteSNPs(drop); // We now need to update SNP codes for (int i=0;i<snpset.size();i++) for (int j=0; j < snpset[i].size(); j++) { int t = snpset[i][j]; snpset[i][j] = nmap.find(t)->second; } } ////////////////////////////////////////////////////// // // // Create LD map within each set // // // ////////////////////////////////////////////////////// void Set::makeLDSets() { ldSet.clear(); ldSet.resize( snpset.size() ); ////////////////////////////////////////////////////// // If pre-calculated, we can read a .ldset file if ( par::set_r2_read ) { // checkFileExists(par::set_r2_read_file); // PP->printLOG("Read LD set information from [ " + par::set_r2_read_file + " ]\n"); // map<string,int> mlocus; // makeLocusMap(*PP,mlocus); // ifstream SIN; // SIN.open( par::set_r2_read_file.c_str() , ios::in ); // while ( ! SIN.eof() ) // { // vector<string> l = tokenizeLine( SIN ); // if ( SIN.eof() ) // break; // if ( l.size() < 2 ) // continue; // // SET ISNP PROXIES... // int nprox = l.size() - 2; // // Lookup SNP names // int isnp = // for ( int j = 0; j < nprox; j++) // { // int l1 = snpset[i][j]; // int l2 = snpset[i][k]; // double rsq = -1; // if ( par::set_r2_phase ) // rsq = PP->haplo->rsq(l1,l2); // else // rsq = PP->correlation2SNP(l1,l2,true,false); // if ( rsq >= par::set_r2_val ) // { // ldSet[i][j].insert(k); // ldSet[i][k].insert(j); // } // } // return; } ////////////////////////////////////////////////////// // Otherwise, calculate LD based on raw genotype data for (int i=0;i<snpset.size();i++) { // Is this SNP pair in LD? ldSet[i].resize( snpset[i].size() ); for (int j=0; j < snpset[i].size(); j++) ldSet[i][j].clear(); // Consider each unique pair of SNPs // in this set for (int j=0; j < snpset[i].size(); j++) { for (int k=j+1; k < snpset[i].size(); k++) { int l1 = snpset[i][j]; int l2 = snpset[i][k]; double rsq = -1; if ( PP->locus[l1]->chr == PP->locus[l2]->chr ) { if ( par::set_r2_phase ) rsq = PP->haplo->rsq(l1,l2); else rsq = PP->correlation2SNP(l1,l2,true,false); } if ( rsq >= par::set_r2_val ) { ldSet[i][j].insert(k); ldSet[i][k].insert(j); } } } } // Output LD sets? if ( par::set_r2_write ) { PP->printLOG("Writing LD sets to [ " + par::output_file_name + ".ldset ]\n"); ofstream SOUT; SOUT.open( ( par::output_file_name + ".ldset").c_str() , ios::out); for (int i=0;i<snpset.size();i++) { for (int j=0; j < snpset[i].size(); j++) { Locus * loc = PP->locus[ snpset[i][j] ]; set<int> & lset = ldSet[i][j]; if ( lset.size() > 0 ) { SOUT << PP->setname[i] << " "; SOUT << loc->name << " "; //SOUT << lset.size() << " "; set<int>::iterator k = lset.begin(); while ( k != lset.end() ) { int l = snpset[i][*k]; SOUT << PP->locus[l]->name << " "; ++k; } SOUT << "\n"; } } } SOUT.close(); } } ////////////////////////////////////////////////////// // // // Create map of SNP number of set codes // // // ////////////////////////////////////////////////////// void Set::initialiseSetMapping() { setMapping.clear(); for (int i=0;i<snpset.size();i++) for (int j=0; j < snpset[i].size(); j++) { int l = snpset[i][j]; map<int,set<int> >::iterator si = setMapping.find(l); // Either we haven't yet seen the SNP... if ( si == setMapping.end() ) { set<int> t; t.insert(i); setMapping.insert(make_pair(l,t)); } else { // ... or we have si->second.insert(i); } // Next SNP } } ////////////////////////////////////////////////////// // // // Sum-statistic scoring (original) // // // ////////////////////////////////////////////////////// void Set::cumulativeSetSum_WITHLABELS(Plink & P, vector<double> & original) { // // Consider each set // for (int i=0;i<snpset.size();i++) // { // vector<SetSortedSNP> t; // // Gather set of all chi-sqs (map sorts them automatically) // for (int j=0; j < snpset[i].size(); j++) // { // SetSortedSNP s; // s.chisq = original[snpset[i][j]]; // s.name = P.locus[snpset[i][j]]->name; // s.locus = snpset[i][j]; // t.push_back(s); // } // // Sort t // sort(t.begin(),t.end()); // // Store results for s_min through s_max // double s=0; // int j=0; // vector<string> t2; // for( vector<SetSortedSNP>::reverse_iterator p = t.rbegin(); p!=t.rend(); p++) // { // // //////////////////////////////// // // // Using an r-sq threshold also? // // double max_r2 = 0; // // if ( par::set_r2 ) // // { // // int l0 = p->locus; // // for (int l=0; l< inSet.size(); l++) // // { // // double r = PP->haplo->rsq( l0, inSet[l] ); // // if ( r > max_r2 ) // // max_r2 = r; // // } // // } // //////////////////////////////// // // Add this SNP to the set? // // if ( (!par::set_r2) || // // max_r2 <= par::set_r2_val ) // // { // s += p->chisq; // if (j>=s_min[i] && j<s_max[i]) // { // stat_set[i][j-s_min[i]][0] = s/(double)(j+1); // t2.push_back(p->name); // // inSet.push_back(p->locus); // } // j++; // // } // } // // And save // setsort.push_back(t2); // } } ////////////////////////////////////////////////////// // // // Sum-statistic scoring (permutation) // // // ////////////////////////////////////////////////////// void Set::cumulativeSetSum_WITHOUTLABELS(vector<double> & perm, int p) { // vector<double> t; // // Consider each set // for (int i=0;i<snpset.size();i++) // { // t.resize(0); // // Gather set of chi-sqs // for (int j=0;j<snpset[i].size();j++) // t.push_back(perm[snpset[i][j]]); // ///////////////////////////// // // Sort them // sort(t.begin(),t.end()); // ///////////////////////////// // // Store // // vector<int> inSet; // double s=0; // for (int j=0;j<s_max[i];j++) // { // //////////////////////////////// // // Add this SNP to the set? // // double max_r2 = 0; // // if ( par::set_r2 ) // // { // // int l0 = p->locus; // // for (int l=0; l< inSet.size(); l++) // // { // // double r = PP->haplo->rsq( l0, inSet[l] ); // // if ( r > max_r2 ) // // max_r2 = r; // // } // // } // //////////////////////////////// // // Add this SNP to the set? // // if ( (!par::set_r2) || // // max_r2 <= par::set_r2_val ) // // { // s += t[t.size()-1-j]; // if (j>=s_min[i] && j<s_max[i]) // { // stat_set[i][j-s_min[i]][p] = s/(double)(j+1); // } // // } // } // } } ////////////////////////////////////////////////////// // // // Sum-statistic empircal p-value calculation // // // ////////////////////////////////////////////////////// void Set::empiricalSetPValues() { int R = par::replicates; ////////////////////////////////////////////////// // Basic p-values, for original and each replicate // For the j'th SNP of the i'th SET, calculate how many times // the other permutations exceed it (permutations 0 to R, where // 0 is the original result) for (int p0=0;p0<=R;p0++) // index for (int p1=0;p1<=R;p1++) // all other perms (including self) for (int i=0;i<stat_set.size();i++) for (int j=0;j<stat_set[i].size();j++) if (stat_set[i][j][p1] >= stat_set[i][j][p0] ) pv_set[i][j][p0]++; // Find best p-values per rep (overall, per set) for (int p=0;p<=R;p++) { double maxE_set = 1; vector<double> maxG_set(pv_set.size(),1); // Consider each score for (int i=0;i<pv_set.size();i++) for (int j=0;j<pv_set[i].size();j++) { // Make into p-value (will include self: i.e. N+1) pv_set[i][j][p] /= R+1; if (pv_set[i][j][p] < maxG_set[i]) maxG_set[i] = pv_set[i][j][p]; if (pv_set[i][j][p] < maxE_set) maxE_set = pv_set[i][j][p]; } // Score max values for (int i=0;i<pv_set.size();i++) for (int j=0;j<pv_set[i].size();j++) { if (maxG_set[i] <= pv_set[i][j][0]) pv_maxG_set[i][j]++; if (maxE_set <= pv_set[i][j][0]) pv_maxE_set[i][j]++; } } } //////////////////////////////////////////////////////////////////// // // // Score-profile based test // // // //////////////////////////////////////////////////////////////////// void Set::profileTestSNPInformation(int l, double odds) { // If we are passed a SNP here, it is because it significant at the // specified par::set_score_p threshold // We have to ask: does this SNP belong to one or more sets? If so, // store the SNP number and odds ratio, for each set (i.e. build up // a profile to score; we do not need to save allele, as it is // always with reference to the minor one map<int, set<int> >::iterator si = setMapping.find(l); if ( si == setMapping.end() ) { return; } set<int>::iterator li = si->second.begin(); while ( li != si->second.end() ) { profileSNPs[ *li ].push_back( l ); profileScore[ *li ].push_back( odds ); ++li; } } vector_t Set::profileTestScore() { /////////////////////////////////////////////////// // For each set, calculate per-individual scores, then // regress this on the phenotype, then save a Wald // test statistic vector_t results; for (int i=0; i<snpset.size(); i++) { vector_t profile; vector<int> count; vector<int> acount; map<int,double> scores; map<int,bool> allele1; for (int j=0; j<profileSNPs[i].size(); j++) { scores.insert(make_pair( profileSNPs[i][j], profileScore[i][j] )); allele1.insert(make_pair( profileSNPs[i][j], false )); } // Record set size (# significant SNPs; use set_min to store this) s_min[i] = profileSNPs[i].size(); /////////////////////////////// // Any significant SNPs? if ( scores.size() == 0 ) { // Record a null score results.push_back( 0 ); continue; } //////////////////////////////// // Calculate actual profile matrix_t dummy; PP->calculateProfile(scores, allele1, profile, dummy , count, acount); /////////////////////////////////////////////// // Save as the covariate, the mean score (i.e. // average by number of seen SNPs) for (int k=0; k < PP->n; k++) { Individual * person = PP->sample[k]; if ( count[k] == 0 || person->flag ) person->missing = true; else { person->clist[0] = profile[k] / (double)count[k]; person->missing = false; } } //////////////////////////////// // Regress phenotype on profil PP->glmAssoc(false,*PP->pperm); ////////////////////////////////////////////// // Reset original missing status vector<Individual*>::iterator iter = PP->sample.begin(); while ( iter != PP->sample.end() ) { (*iter)->missing = (*iter)->flag; ++iter; } //////////////////////////////////////////////// // Save test statistic for permutation purposes double statistic = PP->model->getStatistic(); PP->model->validParameters(); if ( ! PP->model->isValid() ) statistic = -1; results.push_back( statistic ); //////////////////////////////////////////////// // Clear up GLM model delete PP->model; } // Finally, important to clear the profile scores now, // so that the next permutation starts from scratch profileSNPs.clear(); profileScore.clear(); profileSNPs.resize( snpset.size() ); profileScore.resize( snpset.size() ); return results; } void Set::profileTestInitialise() { PP->printLOG("Initalising profile-based set test\n"); // Set up the mapping to determine which set(s) // a given SNP is in initialiseSetMapping(); // Clear the scores profileSNPs.clear(); profileScore.clear(); profileSNPs.resize( snpset.size() ); profileScore.resize( snpset.size() ); /////////////////////////////////////////////////// // Set-up for use of the Linear or Logistic Models par::assoc_glm_without_main_snp = true; if ( PP->clistname.size() > 0 ) error("Cannot specify covariates with --set-score"); ////////////////////////////////////////////// // Use flag to store original missing status vector<Individual*>::iterator i = PP->sample.begin(); while ( i != PP->sample.end() ) { (*i)->flag = (*i)->missing; ++i; } ///////////////////////////////// // Pretend we have covariates par::clist = true; par::clist_number = 1; PP->clistname.resize(1); PP->clistname[0] = "PROFILE"; for (int i=0; i< PP->n; i++) { Individual * person = PP->sample[i]; person->clist.resize(1); } } vector_t Set::fitLDSetTest( vector_t & singleSNP, bool save ) { int ns = snpset.size(); vector_t results(ns,0); if ( save ) { numSig.resize(ns,0); selectedSNPs.resize(ns); } /////////////////////////////////////////// // Down-weight under true model? if ( save && par::fix_lambda ) { PP->printLOG("Downweighting observed statistics in set-test by a factor of " + dbl2str( par::lambda ) + "\n"); vector_t::iterator i = singleSNP.begin(); while ( i != singleSNP.end() ) { *i = (*i) / par::lambda; ++i; } } /////////////////////////////////////////// // Consider each set for (int i=0; i<snpset.size(); i++) { int nss = snpset[i].size(); /////////////////////////////////////////// // Extract all single SNP statistics for // this set vector<SetSortedSNP> t(nss); for (int j=0;j<nss;j++) { t[j].chisq = singleSNP[ snpset[i][j] ] ; t[j].l = j; } //////////////////////////////////////////// // Sort them (by decreasing chisq statistic) sort(t.begin(),t.end()); ///////////////////////////// // Extract a score from this // set double score = 0; int inSet = 0; int isSig = 0; vector<int> selected(0); // Step through SNPs sequentially, adding to score for( vector<SetSortedSNP>::reverse_iterator p = t.rbegin(); p!=t.rend(); p++) { // Is this score already too large? if ( inSet == par::set_max ) { break; } // Get SET-centric SNP code int j = p->l; // Are there any SNPs worth adding? if ( p->chisq < par::set_chisq_threshold ) { break; } // Record this SNP as significant if ( save ) ++isSig; // Is this SNP correlated to a SNP already in the list? set<int> & ls = ldSet[i][j]; bool hasProxy = false; for (int k=0; k<selected.size(); k++) { set<int>::iterator d = ls.find(selected[k]); if ( d != ls.end() ) { hasProxy = true; break; } } // Advance to next potential SNP if ( hasProxy ) continue; // Otherwise, add this SNP to the score score += p->chisq; ++inSet; selected.push_back( j ); } /////////////////////////////////////////// // Do we want to save anything here? if ( save ) { numSig[i] = isSig; selectedSNPs[i] = selected; } /////////////////////////////////////////// // Statistic is the mean test statistic per // selected SNP results[i] = inSet>0 ? score/(double)inSet : 0 ; } return results; } vector_t Set::fitStepwiseModel() { if ( par::SNP_major ) PP->SNP2Ind(); par::assoc_glm_without_main_snp = true; // We are using the conditioning SNPs list to swap // in and out the effects par::conditioning_snps = true; // Put a set of SNPs into the model // Allow // Fixed covariates, as usual // Handle all SNPs as conditioning SNPs // but have a boolean vector that allows some to be fixed // vector_t results; for (int i=0; i<snpset.size(); i++) { cout << "considering SET " << PP->setname[i] << "\n"; int ns = snpset[i].size(); vector<bool> fixed(ns,false); vector<bool> inModel(ns,false); // Scan all SNPs not in the model, and add the best if above // threshold bool done = false; Model * bestModel = NULL; while ( ! done ) { int bestSNP = -1; double lowestP = 1; for (int j=0; j<ns; j++) { if ( fixed[j] || inModel[j] ) continue; PP->conditioner.clear(); // And now add this SNP PP->conditioner.push_back( snpset[i][j] ); for (int j2=0; j2<ns; j2++) { if ( fixed[j2] || inModel[j2] ) PP->conditioner.push_back( snpset[i][j2] ); } // cout << "Testing model: "; // for (int j2=0; j2<PP->conditioner.size(); j2++) // cout << PP->locus[ PP->conditioner[j2] ]->name << " "; PP->glmAssoc(false,*PP->pperm); // Conditioning test SNP will always be the first // This function skips the intercept vector_t pv = PP->model->getPVals(); double pval = pv[0]; if ( pval < lowestP && realnum(pval) ) { // cout << "Selecting this marker..." << pval << "\n"; // But do we really want to accept this based // on the absolute threshold? if ( pval < par::set_step_in ) { if ( bestModel != NULL ) delete bestModel; bestModel = PP->model; } else delete PP->model; lowestP = pval; bestSNP = j; } else { delete PP->model; } } if ( lowestP < par::set_step_in ) { inModel[bestSNP] = true; } else { done = true; } // Do we need this still? if ( bestSNP == -1 ) done = true; } // Conintue the stepwise procedure? // The final model is stored in bestModel // Or perhaps we did not find a model? if ( bestModel == NULL ) continue; // Note: skips intercept vector_t pval = bestModel->getPVals(); // But, annoyingly..., this includes intercept... // hmm, should sort this out vector_t coef = bestModel->getCoefs(); // Skip intercept for (int t = 1; t < bestModel->getNP(); t++) { cout << "fcoef " << bestModel->label[t] << " " << coef[t] << "\t" << pval[t-1] << "\n"; } cout << "--------\n"; // for (int j2=0; j2<ns; j2++) // { // if ( inModel[j2] ) // cout << PP->locus[ snpset[i][j2] ]->name << " (selected) \n"; // if ( fixed[j2] ) // cout << PP->locus[ snpset[i][j2] ]->name << " (fixed) \n"; // } // cout << "\n"; // cout << "-----------\n"; // Obtain full model p-valie // results.push_back( bestModel->getStatistic() ); // PLACE ALL THIS IN CONTEXT OF PERMTATION ALSO... if ( bestModel != NULL ) delete bestModel; // Next set } return results; }
gpl-2.0
CaracalDB/CaracalDB
simulator/src/main/java/se/sics/kompics/p2p/experiment/dsl/events/PeriodicSimulatorEvent.java
1630
/** * This file is part of the Kompics P2P Framework. * * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) * Copyright (C) 2009 Royal Institute of Technology (KTH) * * Kompics is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package se.sics.kompics.p2p.experiment.dsl.events; import se.sics.kompics.KompicsEvent; /** * The <code>PeriodicSimulatorEvent</code> class. * * @author Cosmin Arad {@literal <[email protected]>} * @version $Id$ */ public class PeriodicSimulatorEvent extends KompicsSimulatorEvent { /** * */ private static final long serialVersionUID = -1740286333656694634L; private final long period; public PeriodicSimulatorEvent(KompicsEvent event, long time, long period) { super(event, time); this.period = period; } public final long getPeriod() { return period; } public final void setTime(long time) { super.setTime(time); } public final void setEvent(KompicsEvent event) { this.event = event; } }
gpl-2.0
PatelUtkarsh/rtbiz
templates/acl-settings.php
2958
<?php /* * 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. */ $department = rt_biz_get_department(); $modules = rt_biz_get_modules(); $permissions = rt_biz_get_acl_permissions(); $module_permissions = get_site_option( 'rt_biz_module_permissions' ); $settings = biz_get_redux_settings(); $menu_label = $settings['menu_label']; ?> <div class="wrap"> <div id="icon-options-general" class="icon32"><br></div><h2><?php echo $menu_label . __( ' Access Control' ); ?></h2> <?php if ( empty( $department ) ){ ?> <div id="message" class="error"><p><?php echo 'No departments found, please add a department first to manage ACL'; ?></p></div> <?php } ?> <div class="rt-biz-container"> <ul class="rt_biz_acl_other_option subsubsub"> <strong>Department:</strong> <?php foreach ( $department as $ug ){ ?> <li><a href="<?php echo admin_url( 'edit-tags.php?action=edit&taxonomy=' . RT_Departments::$slug . '&tag_ID=' . $ug->term_id . '&post_type=' . rt_biz_get_contact_post_type() ) ?>" class=""><?php echo $ug->name; ?></a></li> | <?php } ?> <li><a href="<?php echo admin_url( 'edit-tags.php?taxonomy=' . RT_Departments::$slug . '&post_type=' . rt_biz_get_contact_post_type() ); ?>">Add New</a></li> </ul> <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post"> <input type="hidden" name="rt_biz_acl_permissions" value="1" /> <table class="wp-list-table widefat" cellspacing="0"> <thead> <tr> <th scope="col" class="manage-column">&nbsp;</th> <?php foreach ( $department as $ug ) { ?> <th scope="col" class="manage-column"><strong><?php echo $ug->name; ?></strong></th> <?php } ?> </tr> </thead> <tbody id="the-list"> <?php foreach ( $modules as $mkey => $m ) { ?> <tr> <td><strong><?php echo $m['label']; ?></strong></td> <?php foreach ( $department as $ug ) { ?> <td> <select name="rt_biz_module_permissions[<?php echo $mkey ?>][<?php echo $ug->term_id; ?>]"> <?php foreach ( $permissions as $pkey => $p ) { ?> <option title="<?php echo $p['tooltip']; ?>" value="<?php echo $p['value']; ?>" <?php echo ( isset( $module_permissions[ $mkey ][ $ug->term_id ] ) && intval( $module_permissions[ $mkey ][ $ug->term_id ] ) == $p['value'] ) ? 'selected="selected"' : ''; ?>><?php echo $p['name']; ?></option>; <?php } ?> </select> </td> <?php } ?> </tr> <?php } ?> </tbody> <tfoot> <tr> <th scope="col" class="manage-column">&nbsp;</th> <?php foreach ( $department as $ug ) { ?> <th scope="col" class="manage-column"><strong><?php echo $ug->name; ?></strong></th> <?php } ?> </tr> </tfoot> </table> <br /> <input type="submit" class="button-primary" value="Save Settings" /> </form> </div> </div>
gpl-2.0
opieproject/opie
i18n/da/mindbreaker.ts
959
<!DOCTYPE TS><TS> <context> <name>MindBreaker</name> <message> <source>New Game</source> <translation>Nyt spil</translation> </message> <message> <source>win avg: %1 turns (%2 games)</source> <translation type="unfinished"></translation> </message> <message> <source>Mind Breaker</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MindBreakerBoard</name> <message> <source>Reset Statistics</source> <translation>Nulstil statistik</translation> </message> <message> <source>Reset the win ratio?</source> <translation>Vil du nulstille statistikken?</translation> </message> <message> <source>OK</source> <translation>OK</translation> </message> <message> <source>Cancel</source> <translation>Annuller</translation> </message> </context> </TS>
gpl-2.0
Umitay/n
src/main/java/com/umi/common/action/ArticleAdminServlet.java
6248
package com.umi.common.action; import java.io.IOException; import java.util.Collections; import java.util.List; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; 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.MediaType; import javax.ws.rs.core.Response.Status; import lombok.extern.java.Log; import com.google.appengine.repackaged.com.google.api.client.util.Lists; import com.umi.common.data.Article; import com.umi.common.data.Category; import com.umi.common.data.Item; import com.umi.common.data.X_CategoryItem; import com.umi.common.services.ArticleService; import com.umi.common.services.CategoryService; import com.umi.common.services.ItemService; import com.umi.common.utils.CustomException; import com.umi.common.utils.StringUtil; import com.umi.common.data.persist.EnvironmentConfig; @Path("/n/article") @Log @PermitAll public class ArticleAdminServlet { @Context HttpServletRequest request; @Context HttpServletResponse response; ArticleService articleService = new ArticleService(); @Path("/list") @GET public void list( ) { log.info("Start list"); CategoryService categoryService = new CategoryService(); List<Category> categories = categoryService.loadTopCategories(); ArticleService articleService = new ArticleService(); List<Article> articles = articleService.loadArticles(false); try { request.setAttribute("articles", articles); request.setAttribute("categories", categories); request.getRequestDispatcher("/n/article.jsp").forward(request, response); } catch (ServletException | IOException e) { log.severe(e.getMessage()); throw new CustomException(Status.NOT_FOUND, "Something went wrong."); } log.info("End view"); } @Path("/e/{slug}") @GET @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({"ADMIN", "API"}) public void edit( @DefaultValue("") @PathParam("slug") String slug ) throws IOException { response.setContentType("text/html; charset=utf-8"); Article article = articleService.loadArticle(slug); CategoryService categoryService = new CategoryService(); List<Category> categories = categoryService.loadAllCategories(); try { request.setAttribute("article", article); request.setAttribute("categories", categories); request.getRequestDispatcher("/n/article_form.jsp").forward(request, response); } catch (ServletException | IOException e) { log.severe(e.getMessage()); response.sendRedirect("/n"); throw new CustomException(Status.NOT_FOUND, "Something went wrong."); } } @Path("/save") @POST @Consumes("application/x-www-form-urlencoded") @RolesAllowed({"ADMIN", "API"}) public void save ( @DefaultValue("") @FormParam("slug") String slug, @DefaultValue("") @FormParam("name") String name, @DefaultValue("") @FormParam("alt") String alt, @DefaultValue("") @FormParam("thumbnailUrl") String thumbnailUrl, @DefaultValue("") @FormParam("about") String about, @DefaultValue("false") @FormParam("active") Boolean active, @DefaultValue("") @FormParam("description") String description, @DefaultValue("") @FormParam("link_title") String link_title, @DefaultValue("") @FormParam("meta_title") String meta_title, @DefaultValue("") @FormParam("meta_keywords") String meta_keywords, @DefaultValue("") @FormParam("meta_description") String meta_description, @DefaultValue("") @FormParam("ads_horizont1") String ads_horizont1, @DefaultValue("") @FormParam("ads_horizont2") String ads_horizont2, @DefaultValue("") @FormParam("ads_side1") String ads_side1, @DefaultValue("") @FormParam("ads_side2") String ads_side2 ) throws IOException { log.info("Start save "); if(name.length() <=0 ){ response.sendRedirect("/n"); throw new CustomException(Status.BAD_REQUEST, "Field 'name' is missing."); } if(slug.length() >0 ){ Article article = articleService.loadArticle(slug); if(article != null && !article.getName().equals(name) ){ log.info(" Found an Item by given slug, but name of the Item was changed, therefor will be deleted and than will created with new generated slug."); articleService.delete(article); } } slug = StringUtil.generateSlug(name); Article newarticle = articleService.loadArticle(slug); if( newarticle == null ){ newarticle = new Article(); } newarticle.setDescription(description.trim()); newarticle.setName(name.trim()); newarticle.setSlug(slug.trim()); newarticle.setThumbnailUrl(thumbnailUrl.trim()); newarticle.setAbout(about.trim()); newarticle.setActive(active); newarticle.setAlt(alt.trim()); newarticle.setLink_title(link_title.trim()); newarticle.setMeta_title(meta_title.trim()); newarticle.setMeta_keywords(meta_keywords.trim()); newarticle.setMeta_description(meta_description.trim()); newarticle.setAds_horizont1(ads_horizont1); newarticle.setAds_horizont2(ads_horizont2); newarticle.setAds_side1(ads_side1); newarticle.setAds_side2(ads_side2); articleService.saveArticle(newarticle); response.sendRedirect("/n/article/list"); log.info("End save "); } @Path("/update") @GET @RolesAllowed({"ADMIN", "API"}) public void edit( ) { List<Article> articles = articleService.loadAll(Article.class); /*for(Article article:articles){ article.setMeta_title(EnvironmentConfig.getInstance().getMeta_link_title()+ article.getName()); article.setAlt(EnvironmentConfig.getInstance().getMeta_icon() + article.getName() ); article.setMeta_title(article.getName()+EnvironmentConfig.getInstance().getMeta_title()); article.setMeta_keywords(EnvironmentConfig.getInstance().getMeta_keywords()+ article.getName() ); article.setMeta_description(article.getAbout() + EnvironmentConfig.getInstance().getMeta_description()); }*/ articleService.save(articles); } }
gpl-2.0
manuviswam/ReactJsNetSample
ReactJSNetSample/Controllers/HomeController.cs
244
using System.Web.Mvc; namespace ReactJSNetSample.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } } }
gpl-2.0
sslab-gatech/avpass
src/strp.py
12989
#!/usr/bin/env python2 ''' String and Variable encryption 1. string obfuscation ex) python strp.py -f netr.apk string -c yes -f filename -c cleanup (yes: leave the extracted directory, no : remove dir after obfuscation) 2. variable obfuscation ex) python strp.py -f netr.apk variable -c yes -f filename -c cleanup (yes: leave the extracted directory, no : remove dir after obfuscation) ''' from random import randint from StringIO import StringIO import xml.etree.ElementTree as ET import os, sys import fileinput import argparse import fnmatch, re import string sys.path.append('./modules') from conf import * import smali_tool from common import * from strputil import * from template_api import * def array_to_string(arr, delimit): "RETURN item in array to string" output = delimit.join([str(x) for x in arr]) return output # TODO. what if string already obfuscated? we can't change name correctly def obfuscate_assets_names(): """ 1. change assets files 2. change strings referencing """ pass def mod_name_manifest(filename): "Modify AndroidManifest.xml file by user request" manifestFile = ET.parse(filename + '/AndroidManifest.xml') root = manifestFile.getroot() # get package name package = root.attrib['package'] old_package = package.split('.') num_pack_words = len(old_package) words = ret_random_words(num_pack_words) #print words new_package = array_to_string(words, ".") root.attrib['package'] = new_package return old_package, words def variable_mod_chunk(chunk): "Modify any variable in chunk" lines_chunk = ret_lined_list(chunk) output = "" should_modify = False for line in lines_chunk: if ".source " in line or ".param " in line or ".local " in line \ or ".end local" in line or "name =" in line : line = caesar_str(line) should_modify = True output = output + line +"\n" return output, should_modify def scan_smali_all(smali): "scan smali files and return list" smali_path = [] smali_file = [] caesar_file = [] num = 0 #excludes = smali+"/android/" #excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.' for root, dirs, files in os.walk(smali): for file in files: if file.endswith(".smali"): num = num + 1 path = root smali_path.append(path.replace(smali, '')) smali_file.append(file) return smali_path, smali_file, num def extract_smali(target): "extract apk to smali" if not os.path.exists(target): print ( "[*] Decoding apk file to smali") os.system('tools/apktool d ./'+target+'.apk -o' + target) # TODO. scan_smali and others # what if target application uses package starts with android? def scan_smali(smali): "scan smali file list" smali_path = [] smali_file = [] excludes = smali+"/android/" excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.' for root, dirs, files in os.walk(smali): for file in files: if file.endswith(".smali"): if "android" not in root: smali_path.append(root+"/") smali_file.append(file) continue return smali_path, smali_file def return_local(line): "return number of locals" return int(line.split('locals ')[1]) def get_locals(chunk): "return maximum registers" lines_chunk = ret_lined_list(chunk) for line in lines_chunk: if ".locals" in line: return return_local(line) def null_string_chunk(chunk): "Nullify all string in chunk" lines_chunk = ret_lined_list(chunk) output = "" for line in lines_chunk: if "const-string" in line: line = null_str(line)+"\n" # base64 output = output + line +"\n" return output class Strp(object): def __init__(self, apk, api_name, per_num, wantCleanup): self.target = apk.split('.')[0] self.smali = self.target + "/smali" self.tree = "" self.root = "" self.output_name = self.target + '_pert.apk' self.should_cleanup = wantCleanup self.smali_file = [] self.smali_filename = [] self.smali_path = [] self.keys = [] self.current_key = 0 self.assets_filename = None def gen_encryptor(self, num_encryptor): """ Generate number of encryptor with different keys """ package_name = ret_package_name(self.target+'/AndroidManifest.xml', self.target) enc_filename = package_name.split('.')[len(package_name.split('.'))-1] package_dir = self.smali + "/" + package_name.replace(".", "/") + "/" self.keys = random_string_arr(num_encryptor) encryptors = gen_classnames(package_dir, enc_filename, \ num_encryptor, CLASS_POSTFIX) gen_enc_class_files(encryptors, self.keys) def process_asset(self): self.assets_filename = load_filelist_from_dir(self.target+"/assets") #print self.assets_filename obfuscate_assets_names() def get_filename(self, item): len_items = len(item.split("/")) if len_items is 2: fname = item.split("/")[1] else: fname = item return fname def find_smalifiles(self, smali_file, smali): file_num = 0 smali_filename= [] caesar_smali_filename= [] smali_path = [] for item in smali_file: item = item.replace(".", "/") len_items = len(item.split("/")) file_num = file_num + 1 # if more than two Activities => scan if len_items <= 2: # only file name here if len_items is 2: fname = item.split("/")[1] else: fname = item found = check_smali(smali, fname) if found is True: smali_filename.append(fname) smali_path.append(scan_smali(smali, fname)[0]) # else : add one file else: temp_path = "" items = item.split("/") fname = items[len(items)-1] found = check_smali(smali, fname) if found is True: smali_filename.append(fname) smali_path.append(scan_smali(smali, fname)[0]) return smali_path, smali_filename, file_num # read_manifest file and return smali files' name def read_manifest(self, target, root): temp_smali_file = [] for child_1 in root: if child_1.tag == 'application': for child_2 in child_1: if child_2.tag != "meta-data": i = child_2.attrib.items() for item in i: if '}name' in item[0]: #manually handle namespace temp_smali_file.append(item[1]) return temp_smali_file def load_source(self, findall): extract_smali(self.target) self.tree = ET.parse(self.target + '/AndroidManifest.xml') self.root = self.tree.getroot() self.smali_file = self.read_manifest(self.target, self.root) if findall is False: print "Loading Smali[if]" self.smali_path, self.smali_filename, self.file_num = \ self.find_smalifiles(self.smali_file, self.smali) else: print "Loading Smali[else]" self.smali_path, self.smali_filename, self.file_num = \ scan_smali_all(self.smali) def read_content(self, index): current_file = self.smali+"/"+self.smali_path[index] + "/"+self.smali_filename[index] #full path current_con = "" if os.path.exists(current_file): current_con = open(current_file).readlines() #read file => lines return current_con def cleanUp(self, should_cleanup): if should_cleanup == "yes" or should_cleanup == "Yes": print "[*] Packing APK..." os.system('tools/apktool b '+self.target+ " -o " + self.target + "_out.apk") os.system("rm -rf "+self.target) print "[*] Everything done now" else: print "[*] Everything done now" def string_enc_base(self): "Encrypt string using base64" print "[*] Start string encoding (base64)" count = 0 for index in range(0, len(self.smali_filename)): current_con = self.read_content(index) current_file = self.smali_path[index] +"/"+ self.smali_filename[index] #full path if process_string(self.smali, current_file) is True: count = count + 1 print "[*] Done processing %d files => modified %d files" % (len(self.smali_filename), count) self.cleanUp(self.should_cleanup) def field_encryption(self): """ Encrypt field /java/lang/String "defined" and its reference e.g., .field public static final SENDER_ID:Ljava/lang/String; = "[email protected]" """ pass def string_enc_all(self): """ Encrypt string using xor-string encryptor different for each string. We do this by inserting massive number of getStr() functions => benefit: we don't need to insert any register """ print "[*] Start string encoding (all different encryption)" count = 0 for index in range(0, len(self.smali_filename)): current_con = self.read_content(index) current_file = self.smali_path[index] +"/"+ self.smali_filename[index] #full path if process_string_all(self.smali, current_file, \ self.assets_filename, BLACKLIST_STRING) is True: count = count + 1 print "[*] Done processing %d files => modified %d files" % (len(self.smali_filename), count) self.cleanUp(self.should_cleanup) def process_variable(self, filename): "Encrypt variables in file" smali_file = open(filename,'r') smali_code = smali_file.read() func_array = smali_code.split('.method') mark = False chunk_array = [] for chunk in func_array: chunk2, should_modify = variable_mod_chunk(chunk) if should_modify is True: mark = True chunk_array.append(chunk2) output = '\n.method'.join([str(x) for x in chunk_array]) ofile = open(filename, 'w') ofile.write(output) ofile.close() return mark # variables including .field def variable_enc_caesar(self): "Variable encryption using caesar" print "[*] Start variable encryption (simple caesar)" count = 0 #print len(self.smali_filename) for index in range(0, len(self.smali_filename)): current_con = self.read_content(index) current_file = self.smali+"/"+self.smali_path[index] +"/" + self.smali_filename[index] #full path if self.process_variable(current_file) is True: count = count + 1 print "[*] Done processing %d files => modified %d files" % (len(self.smali_filename), count) self.cleanUp(self.should_cleanup) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", dest="apk_filename", type=str, default=None, help="This is the name of APK") # Create the subparser group subparsers = parser.add_subparsers(title='arguments') # Random obfuscation sp = subparsers.add_parser('string', help='Random obfuscation', add_help=False) sp.add_argument("-c", "--cleanup", dest="cleanup", type=str, default=None, choices=['yes', 'no'], required=True) sp.set_defaults(action='string') vp = subparsers.add_parser('variable', help='Variable Name obfuscation', add_help=False) vp.add_argument("-c", "--cleanup", dest="cleanup", type=str, default=None, choices=['yes', 'no'], required=True) vp.set_defaults(action='variable') # Parse the arguments args = parser.parse_args() # Do the right action if args.action == "string": print "Perturb this APK file" strp = Strp(args.apk_filename, "", 0, args.cleanup) strp.load_source(True) #strp.string_enc_base() strp.process_asset() strp.string_enc_all() strp.field_encryption() elif args.action == "variable": print "Change variable name" strp = Strp(args.apk_filename, "", 0, args.cleanup) strp.load_source(True) strp.variable_enc_caesar()
gpl-2.0
litwicki/chargify-bundle
Entity/Charge.php
6397
<?php namespace Litwicki\Bundle\ChargifyBundle\Entity; use JMS\Serializer\Annotation as Serializer; use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Expose; use JMS\Serializer\Annotation\Type; use JMS\Serializer\Annotation\VirtualProperty; use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\MaxDepth; use JMS\Serializer\Annotation\SerializedName; use Litwicki\Common\Common; use Litwicki\Bundle\ChargifyBundle\Model\Entity\ChargifyEntity; use Litwicki\Bundle\ChargifyBundle\Model\Entity\ChargifyEntityInterface; /** * Class Charge * * @package Litwicki\Bundle\ChargifyBundle\Entity */ class Charge extends ChargifyEntity implements ChargifyEntityInterface { /** * @Type("string") * @Groups({"api"}) * @Expose */ protected $success; /** * @Type("float") * @Groups({"api"}) * @Expose */ protected $amount; /** * @Type("string") * @Groups({"api"}) * @Expose */ protected $memo; /** * @Type("integer") * @Groups({"api"}) * @Expose */ protected $amount_in_cents; /** * @Type("integer") * @Groups({"api"}) * @Expose */ protected $ending_balance_in_cents; /** * @Type("string") * @Groups({"api"}) * @Expose */ protected $type; /** * @Type("integer") * @Groups({"api"}) * @Expose */ protected $subscription_id; /** * @Type("integer") * @Groups({"api"}) * @Expose */ protected $product_id; /** * @Type("datetime") * @Groups({"api"}) * @Expose */ protected $created_at; /** * @Type("integer") * @Groups({"api"}) * @Expose */ protected $payment_id; /** * @Type("boolean") * @Groups({"api"}) * @Expose */ protected $use_negative_balance; /** * @Type("boolean") * @Groups({"api"}) * @Expose */ protected $delay_capture; /** * @Type("boolean") * @Groups({"api"}) * @Expose */ protected $taxable; /** * @Type("string") * @Groups({"api"}) * @Expose */ protected $payment_collection_method; /** * @return mixed */ public function getDelayCapture() { return $this->delay_capture; } /** * @param mixed $delay_capture */ public function setDelayCapture($delay_capture) { $this->delay_capture = $delay_capture; } /** * @return mixed */ public function getPaymentCollectionMethod() { return $this->payment_collection_method; } /** * @param mixed $payment_collection_method */ public function setPaymentCollectionMethod($payment_collection_method) { $this->payment_collection_method = $payment_collection_method; } /** * @return mixed */ public function getTaxable() { return $this->taxable; } /** * @param mixed $taxable */ public function setTaxable($taxable) { $this->taxable = $taxable; } /** * @return mixed */ public function getUseNegativeBalance() { return $this->use_negative_balance; } /** * @param mixed $use_negative_balance */ public function setUseNegativeBalance($use_negative_balance) { $this->use_negative_balance = $use_negative_balance; } /** * @param $subscription_id */ public function __construct($subscription_id) { $this->subscription_id = $subscription_id; } /** * @return mixed */ public function getAmount() { return $this->amount; } /** * @param mixed $amount */ public function setAmount($amount) { $this->amount = $amount; } /** * @return mixed */ public function getAmountInCents() { return $this->amount_in_cents; } /** * @param mixed $amount_in_cents */ public function setAmountInCents($amount_in_cents) { $this->amount_in_cents = $amount_in_cents; } /** * @return mixed */ public function getCreatedAt() { return $this->created_at; } /** * @param mixed $created_at */ public function setCreatedAt($created_at) { $this->created_at = $created_at; } /** * @return mixed */ public function getEndingBalanceInCents() { return $this->ending_balance_in_cents; } /** * @param mixed $ending_balance_in_cents */ public function setEndingBalanceInCents($ending_balance_in_cents) { $this->ending_balance_in_cents = $ending_balance_in_cents; } /** * @return mixed */ public function getId() { return $this->id; } /** * @return mixed */ public function getMemo() { return $this->memo; } /** * @param mixed $memo */ public function setMemo($memo) { $this->memo = $memo; } /** * @return mixed */ public function getPaymentId() { return $this->payment_id; } /** * @param mixed $payment_id */ public function setPaymentId($payment_id) { $this->payment_id = $payment_id; } /** * @return mixed */ public function getProductId() { return $this->product_id; } /** * @param mixed $product_id */ public function setProductId($product_id) { $this->product_id = $product_id; } /** * @return mixed */ public function getSubscriptionId() { return $this->subscription_id; } /** * @param mixed $subscription_id */ public function setSubscriptionId($subscription_id) { $this->subscription_id = $subscription_id; } /** * @return mixed */ public function getSuccess() { return $this->success; } /** * @param mixed $success */ public function setSuccess($success) { $this->success = $success; } /** * @return mixed */ public function getType() { return $this->type; } /** * @param mixed $type */ public function setType($type) { $this->type = $type; } }
gpl-2.0
reparosemlagrima/producao
components/com_jcart/admin/controller/module/latest.php
5800
<?php /** * @package jCart * @copyright Copyright (C) 2009 - 2016 softPHP,http://www.soft-php.com * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); class ControllerModuleLatest extends Controller { private $error = array(); public function index() { $this->load->language('module/latest'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('extension/module'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { if (!isset($this->request->get['module_id'])) { $this->model_extension_module->addModule('latest', $this->request->post); } else { $this->model_extension_module->editModule($this->request->get['module_id'], $this->request->post); } $this->cache->delete('product'); $this->session->data['success'] = $this->language->get('text_success'); $this->response->redirect($this->url->link('extension/module', 'token=' . $this->session->data['token'], true)); } $data['heading_title'] = $this->language->get('heading_title'); $data['text_edit'] = $this->language->get('text_edit'); $data['text_enabled'] = $this->language->get('text_enabled'); $data['text_disabled'] = $this->language->get('text_disabled'); $data['entry_name'] = $this->language->get('entry_name'); $data['entry_limit'] = $this->language->get('entry_limit'); $data['entry_width'] = $this->language->get('entry_width'); $data['entry_height'] = $this->language->get('entry_height'); $data['entry_status'] = $this->language->get('entry_status'); $data['button_save'] = $this->language->get('button_save'); $data['button_cancel'] = $this->language->get('button_cancel'); if (isset($this->error['warning'])) { $data['error_warning'] = $this->error['warning']; } else { $data['error_warning'] = ''; } if (isset($this->error['name'])) { $data['error_name'] = $this->error['name']; } else { $data['error_name'] = ''; } if (isset($this->error['width'])) { $data['error_width'] = $this->error['width']; } else { $data['error_width'] = ''; } if (isset($this->error['height'])) { $data['error_height'] = $this->error['height']; } else { $data['error_height'] = ''; } $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true) ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_module'), 'href' => $this->url->link('extension/module', 'token=' . $this->session->data['token'], true) ); if (!isset($this->request->get['module_id'])) { $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('module/latest', 'token=' . $this->session->data['token'], true) ); } else { $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('module/latest', 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], true) ); } if (!isset($this->request->get['module_id'])) { $data['action'] = $this->url->link('module/latest', 'token=' . $this->session->data['token'], true); } else { $data['action'] = $this->url->link('module/latest', 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], true); } $data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], true); if (isset($this->request->get['module_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) { $module_info = $this->model_extension_module->getModule($this->request->get['module_id']); } if (isset($this->request->post['name'])) { $data['name'] = $this->request->post['name']; } elseif (!empty($module_info)) { $data['name'] = $module_info['name']; } else { $data['name'] = ''; } if (isset($this->request->post['limit'])) { $data['limit'] = $this->request->post['limit']; } elseif (!empty($module_info)) { $data['limit'] = $module_info['limit']; } else { $data['limit'] = 5; } if (isset($this->request->post['width'])) { $data['width'] = $this->request->post['width']; } elseif (!empty($module_info)) { $data['width'] = $module_info['width']; } else { $data['width'] = 200; } if (isset($this->request->post['height'])) { $data['height'] = $this->request->post['height']; } elseif (!empty($module_info)) { $data['height'] = $module_info['height']; } else { $data['height'] = 200; } if (isset($this->request->post['status'])) { $data['status'] = $this->request->post['status']; } elseif (!empty($module_info)) { $data['status'] = $module_info['status']; } else { $data['status'] = ''; } $data['header'] = $this->load->controller('common/header'); $data['column_left'] = $this->load->controller('common/column_left'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view('module/latest', $data)); } protected function validate() { if (!$this->user->hasPermission('modify', 'module/latest')) { $this->error['warning'] = $this->language->get('error_permission'); } if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 64)) { $this->error['name'] = $this->language->get('error_name'); } if (!$this->request->post['width']) { $this->error['width'] = $this->language->get('error_width'); } if (!$this->request->post['height']) { $this->error['height'] = $this->language->get('error_height'); } return !$this->error; } }
gpl-2.0