code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/******************************************************************************* * Copyright (c) 2012, 2014 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.core.tests.compiler.parser; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Locale; import org.eclipse.jdt.core.compiler.CategorizedProblem; import org.eclipse.jdt.core.tests.util.AbstractCompilerTest; import org.eclipse.jdt.core.tests.util.Util; import org.eclipse.jdt.internal.codeassist.complete.CompletionParser; import org.eclipse.jdt.internal.codeassist.select.SelectionParser; import org.eclipse.jdt.internal.compiler.ASTVisitor; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.eclipse.jdt.internal.compiler.DocumentElementParser; import org.eclipse.jdt.internal.compiler.IDocumentElementRequestor; import org.eclipse.jdt.internal.compiler.ISourceElementRequestor; import org.eclipse.jdt.internal.compiler.SourceElementParser; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.ImportReference; import org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.eclipse.jdt.internal.compiler.parser.Parser; import org.eclipse.jdt.internal.compiler.problem.DefaultProblem; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.eclipse.jdt.internal.core.search.indexing.IndexingParser; import org.eclipse.jdt.internal.core.util.CommentRecorderParser; public class AbstractSyntaxTreeTest extends AbstractCompilerTest implements IDocumentElementRequestor, ISourceElementRequestor { protected static final int CHECK_PARSER = 0x1; protected static final int CHECK_COMPLETION_PARSER = 0x2; protected static final int CHECK_SELECTION_PARSER = 0x4; protected static final int CHECK_DOCUMENT_ELEMENT_PARSER = 0x8; protected static final int CHECK_COMMENT_RECORDER_PARSER = 0x10; protected static final int CHECK_SOURCE_ELEMENT_PARSER = 0x20; protected static final int CHECK_INDEXING_PARSER = 0x40; protected static final int CHECK_JAVAC_PARSER = 0x80; protected static int CHECK_ALL = (CHECK_PARSER | CHECK_COMPLETION_PARSER | CHECK_SELECTION_PARSER | CHECK_DOCUMENT_ELEMENT_PARSER | CHECK_COMMENT_RECORDER_PARSER | CHECK_SOURCE_ELEMENT_PARSER | CHECK_INDEXING_PARSER); public static boolean optimizeStringLiterals = false; private String referenceCompiler; private String referenceCompilerTestsScratchArea; public AbstractSyntaxTreeTest(String name, String referenceCompiler, String referenceCompilerTestsScratchArea) { super(name); this.referenceCompiler = referenceCompiler; this.referenceCompilerTestsScratchArea = referenceCompilerTestsScratchArea; } public void checkParse(int parserToCheck, char[] source, String expectedSyntaxErrorDiagnosis, String testName, String expectedUnitToString, ASTVisitor visitor) throws IOException { CompilerOptions options = new CompilerOptions(getCompilerOptions()); options.complianceLevel = ClassFileConstants.JDK1_8; options.sourceLevel = ClassFileConstants.JDK1_8; options.targetJDK = ClassFileConstants.JDK1_8; ICompilationUnit sourceUnit = null; CompilationResult compilationResult = null; CompilationUnitDeclaration unit = null; if (this.referenceCompiler != null && (parserToCheck & CHECK_JAVAC_PARSER) != 0) { String javaFilePath = this.referenceCompilerTestsScratchArea + "\\Xyz.java"; File f = new File(javaFilePath); FileOutputStream o = new FileOutputStream(f); OutputStreamWriter w = new OutputStreamWriter(o); w.write(source); w.close(); Process p = Runtime.getRuntime().exec (new String[] { this.referenceCompiler, "-sourcepath", this.referenceCompilerTestsScratchArea, javaFilePath }, null, new File(this.referenceCompilerTestsScratchArea)); try { BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; while ((line = stderr.readLine())!= null) System.out.println(line); while ((line = stdout.readLine())!= null) System.out.println(line); assertTrue("javac unhappy", p.waitFor() == 0); } catch (InterruptedException e) { System.err.println("Skipped javac behavior check due to interrupt..."); } } if ((parserToCheck & CHECK_PARSER) != 0) { Parser parser1 = new Parser( new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), options, new DefaultProblemFactory(Locale.getDefault())), optimizeStringLiterals); sourceUnit = new CompilationUnit(source, testName, null); compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); unit = parser1.parse(sourceUnit, compilationResult); parser1.getMethodBodies(unit); assertDianosticEquals(expectedSyntaxErrorDiagnosis, testName, compilationResult); assertParseTreeEquals(expectedUnitToString, unit.toString()); if (visitor != null) { unit.traverse(visitor, (CompilationUnitScope) null); } parser1 = null; } if ((parserToCheck & CHECK_COMPLETION_PARSER) != 0) { CompletionParser parser2 = new CompletionParser( new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), options, new DefaultProblemFactory(Locale.getDefault())), false); compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); unit = parser2.parse(sourceUnit, compilationResult, Integer.MAX_VALUE); parser2.getMethodBodies(unit); assertDianosticEquals(expectedSyntaxErrorDiagnosis, testName, compilationResult); assertParseTreeEquals(expectedUnitToString, unit.toString()); parser2 = null; } if ((parserToCheck & CHECK_SELECTION_PARSER) != 0) { SelectionParser parser3 = new SelectionParser( new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), options, new DefaultProblemFactory(Locale.getDefault()))); compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); unit = parser3.parse(sourceUnit, compilationResult, Integer.MAX_VALUE, Integer.MAX_VALUE); parser3.getMethodBodies(unit); assertDianosticEquals(expectedSyntaxErrorDiagnosis, testName, compilationResult); assertParseTreeEquals(expectedUnitToString, unit.toString()); parser3 = null; } if ((parserToCheck & CHECK_DOCUMENT_ELEMENT_PARSER) != 0) { DocumentElementParser parser4 = new DocumentElementParser( this, new DefaultProblemFactory(Locale.getDefault()), options); compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); unit = parser4.parse(sourceUnit, compilationResult); parser4.getMethodBodies(unit); assertDianosticEquals(expectedSyntaxErrorDiagnosis, testName, compilationResult); assertParseTreeEquals(expectedUnitToString, unit.toString()); parser4 = null; } if ((parserToCheck & CHECK_COMMENT_RECORDER_PARSER) != 0) { CommentRecorderParser parser5 = new CommentRecorderParser( new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), options, new DefaultProblemFactory(Locale.getDefault())), optimizeStringLiterals); compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); unit = parser5.parse(sourceUnit, compilationResult); parser5.getMethodBodies(unit); assertDianosticEquals(expectedSyntaxErrorDiagnosis, testName, compilationResult); assertParseTreeEquals(expectedUnitToString, unit.toString()); parser5 = null; } if ((parserToCheck & CHECK_SOURCE_ELEMENT_PARSER) != 0) { SourceElementParser parser6 = new SourceElementParser(this, new DefaultProblemFactory(Locale.getDefault()), options, true, optimizeStringLiterals); compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); unit = parser6.parse(sourceUnit, compilationResult); parser6.getMethodBodies(unit); assertDianosticEquals(expectedSyntaxErrorDiagnosis, testName, compilationResult); assertParseTreeEquals(expectedUnitToString, unit.toString()); parser6 = null; } if ((parserToCheck & CHECK_INDEXING_PARSER) != 0) { IndexingParser parser7 = new IndexingParser(this, new DefaultProblemFactory(Locale.getDefault()), options, true, optimizeStringLiterals, false); compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); unit = parser7.parse(sourceUnit, compilationResult); parser7.getMethodBodies(unit); assertDianosticEquals(expectedSyntaxErrorDiagnosis, testName, compilationResult); assertParseTreeEquals(expectedUnitToString, unit.toString()); parser7 = null; } } public void checkParse(int parserToCheck, char[] source, String expectedSyntaxErrorDiagnosis, String testName, String expectedUnitToString) throws IOException { checkParse(parserToCheck, source, expectedSyntaxErrorDiagnosis, testName, expectedUnitToString, null); } public void checkParse(char[] source, String expectedSyntaxErrorDiagnosis, String testName, String expectedUnitToString) throws IOException { checkParse(CHECK_ALL, source, expectedSyntaxErrorDiagnosis, testName, expectedUnitToString); } public void checkParse(char[] source, String expectedSyntaxErrorDiagnosis, String testName, String expectedUnitToString, ASTVisitor visitor) throws IOException { checkParse(CHECK_ALL, source, expectedSyntaxErrorDiagnosis, testName, expectedUnitToString, visitor); } private void assertParseTreeEquals(String expectedUnitToString, String computedUnitToString) { if (expectedUnitToString == null) { // just checking that we are able to digest. return; } if (!expectedUnitToString.equals(computedUnitToString)) { System.out.println(Util.displayString(computedUnitToString)); } assertEquals("Parse Tree is wrong", Util.convertToIndependantLineDelimiter(expectedUnitToString), Util.convertToIndependantLineDelimiter(computedUnitToString)); } private void assertDianosticEquals(String expectedSyntaxErrorDiagnosis, String testName, CompilationResult compilationResult) { String computedSyntaxErrorDiagnosis = getCompilerMessages(compilationResult); assertEquals( "Invalid syntax error diagnosis" + testName, Util.convertToIndependantLineDelimiter(expectedSyntaxErrorDiagnosis), Util.convertToIndependantLineDelimiter(computedSyntaxErrorDiagnosis)); } private String getCompilerMessages(CompilationResult compilationResult) { StringBuffer buffer = new StringBuffer(100); if (compilationResult.hasProblems() || compilationResult.hasTasks()) { CategorizedProblem[] problems = compilationResult.getAllProblems(); int count = problems.length; int problemCount = 0; char[] unitSource = compilationResult.compilationUnit.getContents(); for (int i = 0; i < count; i++) { if (problems[i] != null) { if (problemCount == 0) buffer.append("----------\n"); problemCount++; buffer.append(problemCount + (problems[i].isError() ? ". ERROR" : ". WARNING")); buffer.append(" in " + new String(problems[i].getOriginatingFileName()).replace('/', '\\')); try { buffer.append(((DefaultProblem)problems[i]).errorReportSource(unitSource)); buffer.append("\n"); buffer.append(problems[i].getMessage()); buffer.append("\n"); } catch (Exception e) { } buffer.append("----------\n"); } } } String computedSyntaxErrorDiagnosis = buffer.toString(); return computedSyntaxErrorDiagnosis; } public void acceptImport(int declarationStart, int declarationEnd, int[] javaDocPositions, char[] name, int nameStartPosition, boolean onDemand, int modifiers) { } public void acceptInitializer(int declarationStart, int declarationEnd, int[] javaDocPositions, int modifiers, int modifiersStart, int bodyStart, int bodyEnd) { } public void acceptLineSeparatorPositions(int[] positions) { } public void acceptPackage(int declarationStart, int declarationEnd, int[] javaDocPositions, char[] name, int nameStartPosition) { } public void acceptProblem(CategorizedProblem problem) { } public void enterClass(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, int classStart, char[] name, int nameStart, int nameEnd, char[] superclass, int superclassStart, int superclassEnd, char[][] superinterfaces, int[] superinterfaceStarts, int[] superinterfaceEnds, int bodyStart) { } public void enterCompilationUnit() { } public void enterConstructor(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, char[] name, int nameStart, int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts, int[] parameterTypeEnds, char[][] parameterNames, int[] parameterNameStarts, int[] parameterNameEnds, int parametersEnd, char[][] exceptionTypes, int[] exceptionTypeStarts, int[] exceptionTypeEnds, int bodyStart) { } public void enterField(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, char[] type, int typeStart, int typeEnd, int typeDimensionCount, char[] name, int nameStart, int nameEnd, int extendedTypeDimensionCount, int extendedTypeDimensionEnd) { } public void enterInterface(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, int interfaceStart, char[] name, int nameStart, int nameEnd, char[][] superinterfaces, int[] superinterfaceStarts, int[] superinterfaceEnds, int bodyStart) { } public void enterMethod(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, char[] returnType, int returnTypeStart, int returnTypeEnd, int returnTypeDimensionCount, char[] name, int nameStart, int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts, int[] parameterTypeEnds, char[][] parameterNames, int[] parameterNameStarts, int[] parameterNameEnds, int parametersEnd, int extendedReturnTypeDimensionCount, int extendedReturnTypeDimensionEnd, char[][] exceptionTypes, int[] exceptionTypeStarts, int[] exceptionTypeEnds, int bodyStart) { } public void exitClass(int bodyEnd, int declarationEnd) { } public void exitCompilationUnit(int declarationEnd) { } public void exitConstructor(int bodyEnd, int declarationEnd) { } public void exitField(int bodyEnd, int declarationEnd) { } public void exitInterface(int bodyEnd, int declarationEnd) { } public void exitMethod(int bodyEnd, int declarationEnd) { } public void acceptAnnotationTypeReference(char[][] annotation, int sourceStart, int sourceEnd) { } public void acceptAnnotationTypeReference(char[] annotation, int sourcePosition) { } public void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition) { } public void acceptFieldReference(char[] fieldName, int sourcePosition) { } public void acceptImport(int declarationStart, int declarationEnd, int nameStart, int nameEnd, char[][] tokens, boolean onDemand, int modifiers) { } public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) { } public void acceptPackage(ImportReference importReference) { } public void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd) { } public void acceptTypeReference(char[] typeName, int sourcePosition) { } public void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd) { } public void acceptUnknownReference(char[] name, int sourcePosition) { } public void enterConstructor(MethodInfo methodInfo) { } public void enterField(FieldInfo fieldInfo) { } public void enterInitializer(int declarationStart, int modifiers) { } public void enterMethod(MethodInfo methodInfo) { } public void enterType(TypeInfo typeInfo) { } public void exitConstructor(int declarationEnd) { } public void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd) { } public void exitInitializer(int declarationEnd) { } public void exitMethod(int declarationEnd, Expression defaultValue) { } public void exitType(int declarationEnd) { } }
maxeler/eclipse
eclipse.jdt.core/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/parser/AbstractSyntaxTreeTest.java
Java
epl-1.0
17,569
/* * 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.ide.editor.preferences.editorproperties.propertiessection; import com.google.gwt.core.client.GWT; import com.google.gwt.json.client.JSONValue; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import java.util.HashMap; import java.util.Map; import javax.validation.constraints.NotNull; import org.eclipse.che.commons.annotation.Nullable; import org.eclipse.che.ide.editor.preferences.EditorPreferencesManager; import org.eclipse.che.ide.editor.preferences.editorproperties.property.EditorPropertyWidget; import org.eclipse.che.ide.editor.preferences.editorproperties.property.EditorPropertyWidgetFactory; /** * The class provides special panel to store and control editor's properties. * * @author Roman Nikitenko */ public class EditorPropertiesSectionViewImpl extends Composite implements EditorPropertiesSectionView, EditorPropertyWidget.ActionDelegate { private static final EditorPropertiesSectionViewImplUiBinder UI_BINDER = GWT.create(EditorPropertiesSectionViewImplUiBinder.class); @UiField FlowPanel propertiesPanel; @UiField Label sectionTitle; private final EditorPropertyWidgetFactory editorPropertyWidgetFactory; private final EditorPreferencesManager editorPreferencesManager; private ActionDelegate delegate; private Map<String, EditorPropertyWidget> properties = new HashMap<>(); @Inject public EditorPropertiesSectionViewImpl( EditorPropertyWidgetFactory editorPropertyWidgetFactory, EditorPreferencesManager editorPreferencesManager) { this.editorPropertyWidgetFactory = editorPropertyWidgetFactory; this.editorPreferencesManager = editorPreferencesManager; initWidget(UI_BINDER.createAndBindUi(this)); } @Override public void onPropertyChanged() { delegate.onPropertyChanged(); } @Override public void setDelegate(ActionDelegate delegate) { this.delegate = delegate; } @Nullable @Override public JSONValue getPropertyValueById(@NotNull String propertyId) { EditorPropertyWidget propertyWidget = properties.get(propertyId); if (propertyWidget != null) { return propertyWidget.getValue(); } return null; } @Override public void setSectionTitle(String title) { sectionTitle.setText(title); propertiesPanel.ensureDebugId("editorPropertiesSection-" + title); // for selenium tests } @Override public void addProperty(@NotNull String propertyId, JSONValue value) { EditorPropertyWidget propertyWidget = properties.get(propertyId); if (propertyWidget != null) { propertyWidget.setValue(value); return; } String propertyName = editorPreferencesManager.getPropertyNameById(propertyId); if (propertyName == null) { return; } propertyWidget = editorPropertyWidgetFactory.create(propertyName, value); propertyWidget.setDelegate(this); propertiesPanel.add(propertyWidget); properties.put(propertyId, propertyWidget); } interface EditorPropertiesSectionViewImplUiBinder extends UiBinder<Widget, EditorPropertiesSectionViewImpl> {} }
sleshchenko/che
ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/editor/preferences/editorproperties/propertiessection/EditorPropertiesSectionViewImpl.java
Java
epl-1.0
3,701
/** * Copyright (c) 2014-2016 IncQuery Labs 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 * * Contributors: * Akos Horvath, Abel Hegedus, Tamas Borbas, Zoltan Ujhelyi, Istvan David - initial API and implementation */ package org.eclipse.viatra.examples.cps.deployment.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.ResourceLocator; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ItemProviderAdapter; import org.eclipse.emf.edit.provider.ViewerNotification; import org.eclipse.viatra.examples.cps.deployment.DeploymentBehavior; import org.eclipse.viatra.examples.cps.deployment.DeploymentFactory; import org.eclipse.viatra.examples.cps.deployment.DeploymentPackage; /** * This is the item provider adapter for a {@link org.eclipse.viatra.examples.cps.deployment.DeploymentBehavior} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class DeploymentBehaviorItemProvider extends ItemProviderAdapter implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DeploymentBehaviorItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addDescriptionPropertyDescriptor(object); addCurrentPropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Description feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addDescriptionPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_DeploymentElement_description_feature"), getString("_UI_PropertyDescriptor_description", "_UI_DeploymentElement_description_feature", "_UI_DeploymentElement_type"), DeploymentPackage.Literals.DEPLOYMENT_ELEMENT__DESCRIPTION, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Current feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addCurrentPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_DeploymentBehavior_current_feature"), getString("_UI_PropertyDescriptor_description", "_UI_DeploymentBehavior_current_feature", "_UI_DeploymentBehavior_type"), DeploymentPackage.Literals.DEPLOYMENT_BEHAVIOR__CURRENT, true, false, true, null, null, null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(DeploymentPackage.Literals.DEPLOYMENT_BEHAVIOR__STATES); childrenFeatures.add(DeploymentPackage.Literals.DEPLOYMENT_BEHAVIOR__TRANSITIONS); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns DeploymentBehavior.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/DeploymentBehavior")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((DeploymentBehavior)object).getDescription(); return label == null || label.length() == 0 ? getString("_UI_DeploymentBehavior_type") : getString("_UI_DeploymentBehavior_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(DeploymentBehavior.class)) { case DeploymentPackage.DEPLOYMENT_BEHAVIOR__DESCRIPTION: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; case DeploymentPackage.DEPLOYMENT_BEHAVIOR__STATES: case DeploymentPackage.DEPLOYMENT_BEHAVIOR__TRANSITIONS: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add (createChildParameter (DeploymentPackage.Literals.DEPLOYMENT_BEHAVIOR__STATES, DeploymentFactory.eINSTANCE.createBehaviorState())); newChildDescriptors.add (createChildParameter (DeploymentPackage.Literals.DEPLOYMENT_BEHAVIOR__TRANSITIONS, DeploymentFactory.eINSTANCE.createBehaviorTransition())); } /** * Return the resource locator for this item provider's resources. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ResourceLocator getResourceLocator() { return DeploymentEditPlugin.INSTANCE; } }
IncQueryLabs/incquery-examples-cps
domains/org.eclipse.viatra.examples.cps.deployment.edit/src/org/eclipse/viatra/examples/cps/deployment/provider/DeploymentBehaviorItemProvider.java
Java
epl-1.0
7,782
/******************************************************************************* * Copyright (c) 2016, 2018 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.hono.service.auth; import static org.eclipse.hono.util.AuthenticationConstants.MECHANISM_EXTERNAL; import static org.eclipse.hono.util.AuthenticationConstants.MECHANISM_PLAIN; import java.util.Objects; import javax.net.ssl.SSLPeerUnverifiedException; import javax.security.cert.X509Certificate; import org.apache.qpid.proton.engine.Sasl; import org.apache.qpid.proton.engine.Sasl.SaslOutcome; import org.apache.qpid.proton.engine.Transport; import org.eclipse.hono.auth.HonoUser; import org.eclipse.hono.util.AuthenticationConstants; import org.eclipse.hono.util.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.core.net.NetSocket; import io.vertx.proton.ProtonConnection; import io.vertx.proton.sasl.ProtonSaslAuthenticator; /** * A SASL authenticator that supports the PLAIN and EXTERNAL mechanisms for authenticating clients. * <p> * On successful authentication a {@link HonoUser} reflecting the client's * <em>authorization id</em> and granted authorities is attached to the {@code ProtonConnection} under key * {@link Constants#KEY_CLIENT_PRINCIPAL}. * <p> * Verification of credentials is delegated to the {@code AuthenticationService} by means of sending a * message to {@link AuthenticationConstants#EVENT_BUS_ADDRESS_AUTHENTICATION_IN}. * <p> * Client certificate validation is done by Vert.x' {@code NetServer} during the TLS handshake, * so this class merely extracts the subject <em>Distinguished Name</em> (DN) from the client certificate * and uses it as the authorization id. */ public final class HonoSaslAuthenticator implements ProtonSaslAuthenticator { private static final Logger LOG = LoggerFactory.getLogger(HonoSaslAuthenticator.class); private final AuthenticationService authenticationService; private Sasl sasl; private boolean succeeded; private ProtonConnection protonConnection; private X509Certificate[] peerCertificateChain; /** * Creates a new authenticator. * * @param authService The service to use for authenticating client. * @throws NullPointerException if any of the parameters is {@code null}. */ public HonoSaslAuthenticator(final AuthenticationService authService) { this.authenticationService = Objects.requireNonNull(authService); } @Override public void init(final NetSocket socket, final ProtonConnection protonConnection, final Transport transport) { LOG.debug("initializing SASL authenticator"); this.protonConnection = protonConnection; this.sasl = transport.sasl(); // TODO determine supported mechanisms dynamically based on registered AuthenticationService implementations sasl.server(); sasl.allowSkip(false); sasl.setMechanisms(MECHANISM_EXTERNAL, MECHANISM_PLAIN); if (socket.isSsl()) { LOG.debug("client connected using TLS, extracting client certificate chain"); try { peerCertificateChain = socket.peerCertificateChain(); LOG.debug("found valid client certificate DN [{}]", peerCertificateChain[0].getSubjectDN()); } catch (final SSLPeerUnverifiedException e) { LOG.debug("could not extract client certificate chain, maybe TLS based client auth is not required"); } } } @Override public void process(final Handler<Boolean> completionHandler) { final String[] remoteMechanisms = sasl.getRemoteMechanisms(); if (remoteMechanisms.length == 0) { LOG.debug("client provided an empty list of SASL mechanisms [hostname: {}, state: {}]", sasl.getHostname(), sasl.getState().name()); completionHandler.handle(false); } else { final String chosenMechanism = remoteMechanisms[0]; LOG.debug("client wants to authenticate using SASL [mechanism: {}, host: {}, state: {}]", chosenMechanism, sasl.getHostname(), sasl.getState().name()); final Future<HonoUser> authTracker = Future.future(); authTracker.setHandler(s -> { if (s.succeeded()) { final HonoUser user = s.result(); LOG.debug("authentication of client [authorization ID: {}] succeeded", user.getName()); Constants.setClientPrincipal(protonConnection, user); succeeded = true; sasl.done(SaslOutcome.PN_SASL_OK); } else { LOG.debug("authentication failed: " + s.cause().getMessage()); sasl.done(SaslOutcome.PN_SASL_AUTH); } completionHandler.handle(Boolean.TRUE); }); final byte[] saslResponse = new byte[sasl.pending()]; sasl.recv(saslResponse, 0, saslResponse.length); verify(chosenMechanism, saslResponse, authTracker.completer()); } } @Override public boolean succeeded() { return succeeded; } private void verify(final String mechanism, final byte[] saslResponse, final Handler<AsyncResult<HonoUser>> authResultHandler) { final JsonObject authRequest = AuthenticationConstants.getAuthenticationRequest(mechanism, saslResponse); if (peerCertificateChain != null) { authRequest.put(AuthenticationConstants.FIELD_SUBJECT_DN, peerCertificateChain[0].getSubjectDN().getName()); } authenticationService.authenticate(authRequest, authResultHandler); } }
dejanb/hono
service-base/src/main/java/org/eclipse/hono/service/auth/HonoSaslAuthenticator.java
Java
epl-1.0
6,317
/** * 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 - <lom-messan.hillah@lip6.fr> * * Contributors: * ${ocontributors} - <$oemails}> * * Mailing list: * lom-messan.hillah@lip6.fr */ /** * (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.hlpn.dots.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import fr.lip6.move.pnml.hlpn.dots.Dot; import fr.lip6.move.pnml.hlpn.dots.DotConstant; import fr.lip6.move.pnml.hlpn.dots.DotsFactory; import fr.lip6.move.pnml.hlpn.dots.DotsPackage; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class DotsFactoryImpl extends EFactoryImpl implements DotsFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static DotsFactory init() { try { DotsFactory theDotsFactory = (DotsFactory) EPackage.Registry.INSTANCE.getEFactory(DotsPackage.eNS_URI); if (theDotsFactory != null) { return theDotsFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new DotsFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DotsFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case DotsPackage.DOT: return createDot(); case DotsPackage.DOT_CONSTANT: return createDotConstant(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Dot createDot() { DotImpl dot = new DotImpl(); return dot; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public DotConstant createDotConstant() { DotConstantImpl dotConstant = new DotConstantImpl(); return dotConstant; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public DotsPackage getDotsPackage() { return (DotsPackage) getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static DotsPackage getPackage() { return DotsPackage.eINSTANCE; } } //DotsFactoryImpl
lhillah/pnmlframework
pnmlFw-HLPN/src/fr/lip6/move/pnml/hlpn/dots/impl/DotsFactoryImpl.java
Java
epl-1.0
3,619
/* * This file is part of the Jikes RVM project (http://jikesrvm.org). * * This file is licensed to You under the Eclipse Public License (EPL); * 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 * * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. */ package org.vmmagic.unboxed; import org.vmmagic.pragma.*; import org.jikesrvm.VM; import org.jikesrvm.objectmodel.RuntimeTable; /** * The VM front end is not capable of correct handling an array of Address, Word, .... * In the boot image writer we provide special types to handle these situations. */ @Uninterruptible public final class OffsetArray implements RuntimeTable<Offset> { private final Offset[] data; @Interruptible public static OffsetArray create(int size) { if (VM.runningVM) VM._assert(VM.NOT_REACHED); // should be hijacked return new OffsetArray(size); } private OffsetArray(int size) { data = new Offset[size]; Offset zero = Offset.zero(); for (int i=0; i<size; i++) { data[i] = zero; } } @Inline public Offset get(int index) { if (VM.VerifyAssertions && (VM.runningVM || VM.writingImage)) VM._assert(VM.NOT_REACHED); // should be hijacked return data[index]; } @Inline public void set(int index, Offset v) { if (VM.VerifyAssertions && (VM.runningVM || VM.writingImage)) VM._assert(VM.NOT_REACHED); // should be hijacked data[index] = v; } @Inline public int length() { if (VM.VerifyAssertions && (VM.runningVM || VM.writingImage)) VM._assert(VM.NOT_REACHED); // should be hijacked return data.length; } @Inline public Offset[] getBacking() { if (!VM.writingImage) VM.sysFail("OffsetArray.getBacking called when not writing boot image"); return data; } }
CodeOffloading/JikesRVM-CCO
jikesrvm-3.1.3/tools/bootImageWriter/vmmagic/src/org/vmmagic/unboxed/OffsetArray.java
Java
epl-1.0
1,934
/******************************************************************************* * Copyright (c) 2013 Tasktop Technologies 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.wikitext.core.parser.builder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.eclipse.mylyn.wikitext.core.parser.Attributes; import org.eclipse.mylyn.wikitext.core.parser.DocumentBuilder.BlockType; import org.eclipse.mylyn.wikitext.core.parser.DocumentBuilder.SpanType; import org.eclipse.mylyn.wikitext.core.parser.HeadingAttributes; import org.eclipse.mylyn.wikitext.core.parser.ImageAttributes; import org.eclipse.mylyn.wikitext.core.parser.LinkAttributes; import org.eclipse.mylyn.wikitext.core.parser.builder.event.AcronymEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.BeginBlockEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.BeginDocumentEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.BeginHeadingEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.BeginSpanEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.CharactersEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.CharactersUnescapedEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.DocumentBuilderEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.DocumentBuilderEvents; import org.eclipse.mylyn.wikitext.core.parser.builder.event.EndBlockEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.EndDocumentEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.EndHeadingEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.EndSpanEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.EntityReferenceEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.ImageEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.ImageLinkEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.LineBreakEvent; import org.eclipse.mylyn.wikitext.core.parser.builder.event.LinkEvent; import org.junit.Test; public class EventDocumentBuilderTest { private final EventDocumentBuilder builder = new EventDocumentBuilder(); @Test public void create() { DocumentBuilderEvents events = builder.getDocumentBuilderEvents(); assertNotNull(events); assertTrue(events.getEvents().isEmpty()); } @Test public void beginDocument() { builder.beginDocument(); assertEvents(new BeginDocumentEvent()); } @Test public void endDocument() { builder.endDocument(); assertEvents(new EndDocumentEvent()); } @Test public void beginBlock() { builder.beginBlock(BlockType.PREFORMATTED, new Attributes()); assertEvents(new BeginBlockEvent(BlockType.PREFORMATTED, new Attributes())); } @Test public void endBlock() { builder.endBlock(); assertEvents(new EndBlockEvent()); } @Test public void beginSpan() { builder.beginSpan(SpanType.DELETED, new Attributes()); assertEvents(new BeginSpanEvent(SpanType.DELETED, new Attributes())); } @Test public void endSpan() { builder.endSpan(); assertEvents(new EndSpanEvent()); } @Test public void beginHeading() { builder.beginHeading(3, new HeadingAttributes()); assertEvents(new BeginHeadingEvent(3, new HeadingAttributes())); } @Test public void endHeading() { builder.endHeading(); assertEvents(new EndHeadingEvent()); } @Test public void characters() { builder.characters("test 123"); assertEvents(new CharactersEvent("test 123")); } @Test public void charactersUnescaped() { builder.charactersUnescaped("test 123"); assertEvents(new CharactersUnescapedEvent("test 123")); } @Test public void acronym() { builder.acronym("one", "two"); assertEvents(new AcronymEvent("one", "two")); } @Test public void entityReference() { builder.entityReference("amp"); assertEvents(new EntityReferenceEvent("amp")); } @Test public void image() { builder.image(new ImageAttributes(), "http://example.com/foo.png"); assertEvents(new ImageEvent(new ImageAttributes(), "http://example.com/foo.png")); } @Test public void imageLink() { builder.imageLink(new LinkAttributes(), new ImageAttributes(), "https://example.com", "http://example.com/foo.png"); assertEvents(new ImageLinkEvent(new LinkAttributes(), new ImageAttributes(), "https://example.com", "http://example.com/foo.png")); } @Test public void link() { builder.link(new LinkAttributes(), "https://example.com", "test"); assertEvents(new LinkEvent(new LinkAttributes(), "https://example.com", "test")); } @Test public void lineBreak() { builder.lineBreak(); assertEvents(new LineBreakEvent()); } private void assertEvents(DocumentBuilderEvent... events) { List<DocumentBuilderEvent> expectedEvents = Arrays.asList(events); assertEquals(expectedEvents, builder.getDocumentBuilderEvents().getEvents()); EventDocumentBuilder builder2 = new EventDocumentBuilder(); for (DocumentBuilderEvent event : events) { event.invoke(builder2); } assertEquals(expectedEvents, builder2.getDocumentBuilderEvents().getEvents()); } }
elelpublic/wikitext-all
src/org.eclipse.mylyn.wikitext.core.tests/src/org/eclipse/mylyn/wikitext/core/parser/builder/EventDocumentBuilderTest.java
Java
epl-1.0
5,620
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2010-2014 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * http://glassfish.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package org.glassfish.jersey.server.model; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.ws.rs.Path; import org.glassfish.jersey.Severity; import org.glassfish.jersey.internal.Errors; import org.glassfish.jersey.internal.util.collection.Value; import org.glassfish.jersey.internal.util.collection.Values; import org.glassfish.jersey.server.internal.LocalizationMessages; import org.glassfish.jersey.server.model.internal.ModelHelper; import org.glassfish.jersey.uri.PathPattern; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Sets; /** * Model of a single resource component. * <p> * Resource component model represents a collection of {@link ResourceMethod methods} * grouped under the same parent request path template. {@code Resource} class is also * the main entry point to the programmatic resource modeling API that provides ability * to programmatically extend the existing JAX-RS annotated resource classes or build * new resource models that may be utilized by Jersey runtime. * </p> * <p> * For example: * <pre> * &#64;Path("hello") * public class HelloResource { * &#64;GET * &#64;Produces("text/plain") * public String sayHello() { * return "Hello!"; * } * } * * ... * * // Register the annotated resource. * ResourceConfig resourceConfig = new ResourceConfig(HelloResource.class); * * // Add new "hello2" resource using the annotated resource class * // and overriding the resource path. * Resource.Builder resourceBuilder = * Resource.builder(HelloResource.class, new LinkedList&lt;ResourceModelIssue&gt;()) * .path("hello2"); * * // Add a new (virtual) sub-resource method to the "hello2" resource. * resourceBuilder.addChildResource("world").addMethod("GET") * .produces("text/plain") * .handledBy(new Inflector&lt;Request, String&gt;() { * &#64;Override * public String apply(Request request) { * return "Hello World!"; * } * }); * * // Register the new programmatic resource in the application's configuration. * resourceConfig.registerResources(resourceBuilder.build()); * </pre> * The following table illustrates the supported requests and provided responses * for the application configured in the example above. * <table> * <tr> * <th>Request</th><th>Response</th><th>Method invoked</th> * </tr> * <tr> * <td>{@code "GET /hello"}</td><td>{@code "Hello!"}</td><td>{@code HelloResource.sayHello()}</td> * </tr> * <tr> * <td>{@code "GET /hello2"}</td><td>{@code "Hello!"}</td><td>{@code HelloResource.sayHello()}</td> * </tr> * <tr> * <td>{@code "GET /hello2/world"}</td><td>{@code "Hello World!"}</td><td>{@code Inflector.apply()}</td> * </tr> * </table> * </p> * * @author Marek Potociar (marek.potociar at oracle.com) * @author Miroslav Fuksa (miroslav.fuksa at oracle.com) */ public final class Resource implements Routed, ResourceModelComponent { /** * Immutable resource data holder. */ private static class Data { private final List<String> names; private final String path; private final PathPattern pathPattern; private final List<ResourceMethod.Data> resourceMethods; private final ResourceMethod.Data locator; private final List<Resource.Data> childResources; private final Set<Class<?>> handlerClasses; private final Set<Object> handlerInstances; private final boolean extended; /** * Create a new immutable resource data holder from the supplied parameters. * * @param names resource names. * @param path resource path. * @param resourceMethods child resource methods. * @param locator child resource locator. * @param childResources child sub-resources. * @param handlerClasses handler classes handling the resource methods. * @param handlerInstances handler instances handling the resource methods. * @param extended */ private Data( final List<String> names, final String path, final List<ResourceMethod.Data> resourceMethods, final ResourceMethod.Data locator, final List<Data> childResources, final Set<Class<?>> handlerClasses, final Set<Object> handlerInstances, boolean extended) { this.extended = extended; this.names = immutableCopy(names); this.path = path; this.pathPattern = (path == null || path.isEmpty()) ? PathPattern.OPEN_ROOT_PATH_PATTERN : new PathPattern(path, PathPattern.RightHandPath.capturingZeroOrMoreSegments); this.resourceMethods = Resource.immutableCopy(resourceMethods); this.locator = locator; this.childResources = Collections.unmodifiableList(childResources); // no need to deep-copy the list this.handlerClasses = Resource.immutableCopy(handlerClasses); this.handlerInstances = Resource.immutableCopy(handlerInstances); } @Override public String toString() { return "Resource{" + ((path == null) ? "[unbound], " : "\"" + path + "\", ") + childResources.size() + " child resources, " + resourceMethods.size() + " resource methods, " + (locator == null ? "0" : "1") + " sub-resource locator, " + handlerClasses.size() + " method handler classes, " + handlerInstances.size() + " method handler instances" + '}'; } } /** * Resource model component builder. */ public static final class Builder { private List<String> names; private String path; private final Set<ResourceMethod.Builder> methodBuilders; private final Set<Resource.Builder> childResourceBuilders; private final List<Resource.Data> childResources; private final List<ResourceMethod.Data> resourceMethods; private ResourceMethod.Data resourceLocator; private final Set<Class<?>> handlerClasses; private final Set<Object> handlerInstances; private final Resource.Builder parentResource; private boolean extended; private Builder(final Resource.Builder parentResource) { this.methodBuilders = Sets.newIdentityHashSet(); this.childResourceBuilders = Sets.newIdentityHashSet(); this.childResources = Lists.newLinkedList(); this.resourceMethods = Lists.newLinkedList(); this.handlerClasses = Sets.newIdentityHashSet(); this.handlerInstances = Sets.newIdentityHashSet(); this.parentResource = parentResource; name("[unnamed]"); } private Builder(final String path) { this((Resource.Builder) null); path(path); } private Builder(final String path, final Resource.Builder parentResource) { this(parentResource); this.path = path; } private Builder() { this((Resource.Builder) null); } private boolean isEmpty() { return this.path == null && methodBuilders.isEmpty() && childResourceBuilders.isEmpty() && resourceMethods.isEmpty() && childResources.isEmpty() && resourceLocator == null; } /** * Define a new name of the built resource. * <p/> * The resource model name is typically used for reporting * purposes (e.g. validation etc.). * * @param name new name of the resource. * @return updated builder object. * @see org.glassfish.jersey.server.model.Resource#getName() */ public Builder name(final String name) { this.names = Lists.newArrayList(name); return this; } /** * Define a new path for the built resource. * <p/> * NOTE: Invoking this method marks a resource as a root resource. * * @param path new path for the resource. * @return updated builder object. */ public Builder path(final String path) { this.path = path; return this; } /** * Add a new method model to the resource for processing requests of * the specified HTTP method. * <p/> * The returned builder is automatically bound to the the resource. It is * not necessary to invoke the {@link ResourceMethod.Builder#build() build()} * method on the method builder after setting all the data. This will be * done automatically when the resource is built. * * @param httpMethod HTTP method that will be processed by the method. * @return a new resource method builder. */ public ResourceMethod.Builder addMethod(final String httpMethod) { ResourceMethod.Builder builder = new ResourceMethod.Builder(this); methodBuilders.add(builder); return builder.httpMethod(httpMethod); } /** * Add a new arbitrary method model to the resource. * <p/> * The returned builder is automatically bound to the the resource. It is * not necessary to invoke the {@link ResourceMethod.Builder#build() build()} * method on the method builder after setting all the data. This will be * done automatically when the resource is built. * * @return a new resource method builder. */ public ResourceMethod.Builder addMethod() { ResourceMethod.Builder builder = new ResourceMethod.Builder(this); methodBuilders.add(builder); return builder; } /** * Add a new method model that is a copy of the given {@code resourceMethod}. * <p/> * The returned builder is automatically bound to the the resource. It is * not necessary to invoke the {@link ResourceMethod.Builder#build() build()} * method on the method builder after setting all the data. This will be * done automatically when the resource is built. * * @param resourceMethod The resource method based on which the new method builder * should be created. * * @return a new resource method builder. */ public ResourceMethod.Builder addMethod(ResourceMethod resourceMethod) { ResourceMethod.Builder builder = new ResourceMethod.Builder(this, resourceMethod); methodBuilders.add(builder); return builder; } /** * Add a new child resource to the resource. * <p/> * The returned builder is automatically bound to the the resource. It is * not necessary to invoke the {@link Resource.Builder#build() build()} * method on the resource builder after setting all the data. This will be * done automatically when the resource is built. * * @param relativePath The path of the new child resource relative to this resource. * @return child resource builder. */ public Builder addChildResource(String relativePath) { if (this.parentResource != null) { throw new IllegalStateException(LocalizationMessages.RESOURCE_ADD_CHILD_ALREADY_CHILD()); } final Builder resourceBuilder = new Builder(relativePath, this); childResourceBuilders.add(resourceBuilder); return resourceBuilder; } /** * Add an existing Resource as a child resource of current resource. * * @param resource Resource to be added as child resource. */ public void addChildResource(Resource resource) { this.childResources.add(resource.data); } /** * Merge methods from a given resource model into this resource model builder. * * @param resource to be merged into this resource model builder. * @return updated builder object. */ public Builder mergeWith(final Resource resource) { mergeWith(resource.data); return this; } /** * Set the flag indicating whether the resource is extended or is a core of exposed RESTful API. * The method defines the * flag available at {@link org.glassfish.jersey.server.model.Resource#isExtended()}. * <p> * Extended resource model components are helper components that are not considered as a core of a * RESTful API. These can be for example {@code OPTIONS} {@link ResourceMethod resource methods} * added by {@link org.glassfish.jersey.server.model.ModelProcessor model processors} * or {@code application.wadl} resource producing the WADL. Both resource are rather supportive * than the core of RESTful API. * </p> * <p> * If not set the resource will not be defined as extended by default. * </p> * * @param extended If {@code true} then resource is marked as extended. * @return updated builder object. * @see org.glassfish.jersey.server.model.ExtendedResource * * @since 2.5.1 */ public Builder extended(boolean extended) { this.extended = extended; return this; } /** * Get the flag indicating whether the resource method is extended or is a core of exposed RESTful API. * * @return {@code true} if the method is extended. */ /* package */ boolean isExtended() { return extended; } private Builder mergeWith(final Resource.Data resourceData) { this.resourceMethods.addAll(resourceData.resourceMethods); this.childResources.addAll(resourceData.childResources); if (resourceLocator != null && resourceData.locator != null) { Errors.processWithException(new Runnable() { @Override public void run() { Errors.error( this, LocalizationMessages.RESOURCE_MERGE_CONFLICT_LOCATORS(Builder.this, resourceData, path), Severity.FATAL); } }); } else if (resourceData.locator != null) { this.resourceLocator = resourceData.locator; } this.handlerClasses.addAll(resourceData.handlerClasses); this.handlerInstances.addAll(resourceData.handlerInstances); this.names.addAll(resourceData.names); return this; } /** * Merge methods from a given resource model builder into this resource model * builder. * <p> * NOTE: Any "open" method builders in the supplied {@code resourceBuilder} that have * not been {@link org.glassfish.jersey.server.model.ResourceMethod.Builder#build() * explicitly converted to method models} will be closed as part of this merge operation * before merging the resource builder instances. * </p> * * @param resourceBuilder to be merged into this resource model builder. * @return updated builder object. */ public Builder mergeWith(final Builder resourceBuilder) { resourceBuilder.processMethodBuilders(); this.resourceMethods.addAll(resourceBuilder.resourceMethods); this.childResources.addAll(resourceBuilder.childResources); if (Resource.Builder.this.resourceLocator != null && resourceBuilder.resourceLocator != null) { Errors.processWithException(new Runnable() { @Override public void run() { Errors.warning(this, LocalizationMessages.RESOURCE_MERGE_CONFLICT_LOCATORS(Resource.Builder.this, resourceBuilder, path)); } }); } else if (resourceBuilder.resourceLocator != null) { this.resourceLocator = resourceBuilder.resourceLocator; } this.handlerClasses.addAll(resourceBuilder.handlerClasses); this.handlerInstances.addAll(resourceBuilder.handlerInstances); this.names.addAll(resourceBuilder.names); return this; } /** * Called when a new resource, sub-resource and sub-resource locator method * was built and should be registered with the resource builder. * <p> * This is a friend call-back API exposed for a use by a {@link ResourceMethod.Builder * ResourceMethod.Builder}. * </p> * * @param builder builder instance that built the method. * @param methodData new resource, sub-resource or sub-resource locator */ void onBuildMethod(ResourceMethod.Builder builder, ResourceMethod.Data methodData) { Preconditions.checkState(methodBuilders.remove(builder), "Resource.Builder.onBuildMethod() invoked from a resource method builder " + "that is not registered in the resource builder instance."); switch (methodData.getType()) { case RESOURCE_METHOD: resourceMethods.add(methodData); break; case SUB_RESOURCE_LOCATOR: if (resourceLocator != null) { Errors.processWithException(new Runnable() { @Override public void run() { Errors.error( this, LocalizationMessages.AMBIGUOUS_SRLS(this, path), Severity.FATAL); } }); } resourceLocator = methodData; break; } final MethodHandler methodHandler = methodData.getInvocable().getHandler(); if (methodHandler.isClassBased()) { handlerClasses.add(methodHandler.getHandlerClass()); } else { handlerInstances.add(methodHandler.getHandlerInstance()); } } private void onBuildChildResource(Builder childResourceBuilder, Resource.Data childResourceData) { Preconditions.checkState(childResourceBuilders.remove(childResourceBuilder), "Resource.Builder.onBuildChildResource() invoked from a resource builder " + "that is not registered in the resource builder instance as a child resource builder."); childResources.add(childResourceData); } private List<Resource.Data> mergeResources(List<Resource.Data> resources) { List<Resource.Data> mergedResources = Lists.newArrayList(); for (int i = 0; i < resources.size(); i++) { Resource.Data outer = resources.get(i); Resource.Builder builder = null; for (int j = i + 1; j < resources.size(); j++) { Resource.Data inner = resources.get(j); if (outer.path.equals(inner.path)) { if (builder == null) { builder = Resource.builder(outer); } builder.mergeWith(inner); resources.remove(j); j--; } } if (builder == null) { mergedResources.add(outer); } else { mergedResources.add(builder.buildResourceData()); } } return mergedResources; } private Data buildResourceData() { if (parentResource != null && parentResource.isExtended()) { this.extended = true; } processMethodBuilders(); processChildResourceBuilders(); final List<Data> mergedChildResources = mergeResources(childResources); Set<Class<?>> classes = Sets.newHashSet(handlerClasses); Set<Object> instances = Sets.newHashSet(handlerInstances); for (Data childResource : mergedChildResources) { classes.addAll(childResource.handlerClasses); instances.addAll(childResource.handlerInstances); } if (areAllMembersExtended(mergedChildResources)) { extended = true; } final Data resourceData = new Data( names, path, resourceMethods, resourceLocator, mergedChildResources, classes, instances, extended); if (parentResource != null) { parentResource.onBuildChildResource(this, resourceData); } return resourceData; } private boolean areAllMembersExtended(List<Data> mergedChildResources) { boolean allExtended = true; for (ResourceMethod.Data resourceMethod : resourceMethods) { if (!resourceMethod.isExtended()) { allExtended = false; } } if (resourceLocator != null && !resourceLocator.isExtended()) { allExtended = false; } for (Data childResource : mergedChildResources) { if (!childResource.extended) { allExtended = false; } } return allExtended; } /** * Build a new resource model. * * @return new (immutable) resource model. */ public Resource build() { final Data resourceData = buildResourceData(); return new Resource(null, resourceData); } private void processMethodBuilders() { // We have to iterate the set this way to prevent ConcurrentModificationExceptions // caused by the nested invocation of Set.remove(...) in Resource.Builder.onBuildMethod(...). while (!methodBuilders.isEmpty()) { methodBuilders.iterator().next().build(); } } private void processChildResourceBuilders() { // We have to iterate the set this way to prevent ConcurrentModificationExceptions // caused by the nested invocation of Set.remove(...) in Resource.Builder.onBuildChildResource(...). while (!childResourceBuilders.isEmpty()) { childResourceBuilders.iterator().next().build(); } } } /** * Get a new unbound resource model builder. * * @return new unbound resource model builder. * @see Resource.Builder#path(java.lang.String) */ public static Builder builder() { return new Builder(); } /** * Get a new resource model builder for a resource bound to a given path. * * @param path resource path. * @return new resource model builder. * @see Resource.Builder#path(java.lang.String) */ public static Builder builder(final String path) { return new Builder(path); } /** * Creates a {@link Builder resource builder} instance from the list of {@code resource} which can be merged * into a single resource. It must be possible to merge the {@code resources} into a single valid resource. * For example all resources must have the same {@link Resource#getPath() path}, they cannot have ambiguous methods * on the same path, etc. * * @param resources Resources with the same path. * @return Resource builder initialized from merged resources. */ public static Builder builder(List<Resource> resources) { if (resources == null || resources.isEmpty()) { return builder(); } final Iterator<Resource> it = resources.iterator(); Resource.Data resourceData = it.next().data; Builder builder = Resource.builder(resourceData); String path = resourceData.path; while (it.hasNext()) { resourceData = it.next().data; if ((resourceData.path == null && path == null) || (path != null && path.equals(resourceData.path))) { builder.mergeWith(resourceData); } else { throw new IllegalArgumentException(LocalizationMessages.ERROR_RESOURCES_CANNOT_MERGE()); } } return builder; } /** * Create a resource model builder initialized by introspecting an annotated * JAX-RS resource class. * * @param resourceClass resource class to be modelled. * @return resource model builder initialized by the class or {@code null} if the * class does not represent a resource. */ public static Builder builder(Class<?> resourceClass) { return builder(resourceClass, false); } /** * Create a resource model builder initialized by introspecting an annotated * JAX-RS resource class. * * @param resourceClass resource class to be modelled. * @param disableValidation if set to {@code true}, then any model validation checks will be disabled. * @return resource model builder initialized by the class or {@code null} if the * class does not represent a resource. */ public static Builder builder(Class<?> resourceClass, boolean disableValidation) { final Builder builder = new IntrospectionModeller(resourceClass, disableValidation).createResourceBuilder(); return builder.isEmpty() ? null : builder; } /** * Create a resource model initialized by introspecting an annotated * JAX-RS resource class. * * @param resourceClass resource class to be modelled. * @return resource model initialized by the class or {@code null} if the * class does not represent a resource. */ public static Resource from(Class<?> resourceClass) { return from(resourceClass, false); } /** * Create a resource model initialized by introspecting an annotated * JAX-RS resource class. * * @param resourceClass resource class to be modelled. * @param disableValidation if set to {@code true}, then any model validation checks will be disabled. * @return resource model initialized by the class or {@code null} if the * class does not represent a resource. */ public static Resource from(Class<?> resourceClass, boolean disableValidation) { final Builder builder = new IntrospectionModeller(resourceClass, disableValidation).createResourceBuilder(); return builder.isEmpty() ? null : builder.build(); } /** * Check if the class is acceptable as a JAX-RS provider or resource. * <p/> * Method returns {@code false} if the class is either * <ul> * <li>abstract</li> * <li>interface</li> * <li>annotation</li> * <li>primitive</li> * <li>local class</li> * <li>non-static member class</li> * </ul> * * @param c class to be checked. * @return {@code true} if the class is an acceptable JAX-RS provider or * resource, {@code false} otherwise. */ public static boolean isAcceptable(Class<?> c) { return !((c.getModifiers() & Modifier.ABSTRACT) != 0 || c.isPrimitive() || c.isAnnotation() || c.isInterface() || c.isLocalClass() || (c.isMemberClass() && (c.getModifiers() & Modifier.STATIC) == 0)); } /** * Get the resource class {@link Path @Path} annotation. * <p/> * May return {@code null} in case there is no {@code @Path} annotation on the resource. * * @param resourceClass resource class. * @return {@code @Path} annotation instance if present on the resource class (i.e. * the class is a root resource class), or {@code null} otherwise. */ public static Path getPath(Class<?> resourceClass) { return ModelHelper.getAnnotatedResourceClass(resourceClass).getAnnotation(Path.class); } /** * Get a new resource model builder initialized from a given resource model. * * @param resource resource model initializing the resource builder. * @return new resource model builder. */ public static Builder builder(Resource resource) { return builder(resource.data); } private static Builder builder(Resource.Data resourceData) { final Builder b; if (resourceData.path == null) { b = new Builder(); } else { b = new Builder(resourceData.path); } b.resourceMethods.addAll(resourceData.resourceMethods); b.childResources.addAll(resourceData.childResources); b.resourceLocator = resourceData.locator; b.handlerClasses.addAll(resourceData.handlerClasses); b.handlerInstances.addAll(resourceData.handlerInstances); b.names.addAll(resourceData.names); return b; } private static List<Resource> transform(final Resource parent, final List<Data> list) { return Lists.transform(list, new Function<Data, Resource>() { @Override public Resource apply(Data data) { return new Resource(parent, data); } }); } private static <T> List<T> immutableCopy(List<T> list) { return list.isEmpty() ? Collections.<T>emptyList() : Collections.unmodifiableList(Lists.newArrayList(list)); } private static <T> Set<T> immutableCopy(Set<T> set) { if (set.isEmpty()) { return Collections.emptySet(); } final Set<T> result = Sets.newIdentityHashSet(); result.addAll(set); return set; } private final Resource parent; private final Data data; private final Value<String> name; private final List<ResourceMethod> resourceMethods; private final ResourceMethod locator; private final List<Resource> childResources; private Resource(final Resource parent, final Data data) { this.parent = parent; this.data = data; this.name = Values.lazy(new Value<String>() { @Override public String get() { if (data.names.size() == 1) { return data.names.get(0); } else { // return merged name StringBuilder nameBuilder = new StringBuilder("Merge of "); nameBuilder.append(data.names.toString()); return nameBuilder.toString(); } } }); this.resourceMethods = immutableCopy(ResourceMethod.transform(Resource.this, data.resourceMethods)); this.locator = data.locator == null ? null : new ResourceMethod(Resource.this, data.locator); this.childResources = immutableCopy(Resource.transform(Resource.this, data.childResources)); } @Override public String getPath() { return data.path; } @Override public PathPattern getPathPattern() { return data.pathPattern; } /** * Get the parent resource for this resource model or {@code null} in case this * resource is a top-level resource and does not have a parent. * * @return parent resource or {@code null} if the resource does not have a parent. * @since 2.1 */ public Resource getParent() { return parent; } /** * Get the resource name. * <p/> * If the resource was constructed from a JAX-RS annotated resource class, * the resource name will be set to the {@link Class#getName() fully-qualified name} * of the resource class. * * @return reference JAX-RS resource handler class. */ public String getName() { return name.get(); } /** * Return a list of resource names. * * @return a list of resource names. */ public List<String> getNames() { return data.names; } /** * Provides a non-null list of resource methods available on the resource. * * @return non-null abstract resource method list. */ public List<ResourceMethod> getResourceMethods() { return resourceMethods; } /** * Provides a resource locator available on the resource. * * @return Resource locator if it is present, null otherwise. */ public ResourceMethod getResourceLocator() { return locator; } /** * Provides resource methods and resource locator are available on the resource. The list is ordered so that resource * methods are positioned first before resource locator. * * @return List of resource methods and resource locator. */ public List<ResourceMethod> getAllMethods() { final LinkedList<ResourceMethod> methodsAndLocators = Lists.newLinkedList(getResourceMethods()); final ResourceMethod loc = getResourceLocator(); if (loc != null) { methodsAndLocators.add(loc); } return methodsAndLocators; } /** * Returns the list of child resources available on this resource. * * @return Non-null list of child resources (may be empty). */ public List<Resource> getChildResources() { return childResources; } /** * Get the method handler classes for the resource methods registered on the resource. * * @return resource method handler classes. */ public Set<Class<?>> getHandlerClasses() { return data.handlerClasses; } /** * Get the method handler (singleton) instances for the resource methods registered * on the resource. * * @return resource method handler instances. */ public Set<Object> getHandlerInstances() { return data.handlerInstances; } @Override public void accept(ResourceModelVisitor visitor) { if (getParent() == null) { visitor.visitResource(this); } else { visitor.visitChildResource(this); } } /** * Get the flag indicating whether the resource is extended or is a core of exposed RESTful API. * <p> * Extended resource model components are helper components that are not considered as a core of a * RESTful API. These can be for example {@code OPTIONS} {@link ResourceMethod resource methods} * added by {@link org.glassfish.jersey.server.model.ModelProcessor model processors} * or {@code application.wadl} resource producing the WADL. Both resource are rather supportive * than the core of RESTful API. * </p> * * @return {@code true} if the resource is extended. * @see org.glassfish.jersey.server.model.ExtendedResource * * @since 2.5.1 */ public boolean isExtended() { return data.extended; } @Override public String toString() { return data.toString(); } @Override public List<? extends ResourceModelComponent> getComponents() { List<ResourceModelComponent> components = new LinkedList<ResourceModelComponent>(); components.addAll(getChildResources()); components.addAll(getResourceMethods()); final ResourceMethod resourceLocator = getResourceLocator(); if (resourceLocator != null) { components.add(resourceLocator); } return components; } }
agentlab/org.glassfish.jersey
plugins/org.glassfish.jersey.server/src/main/java/org/glassfish/jersey/server/model/Resource.java
Java
epl-1.0
38,723
/******************************************************************************* * Copyright (c) Emil Crumhorn - Hexapixel.com - emil.crumhorn@gmail.com * 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: * emil.crumhorn@gmail.com - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.ganttchart; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Monitor; import org.eclipse.swt.widgets.Shell; public class Utils { /** * Takes a font and gives it a bold typeface. * * @param font Font to modify * @return Font with bold typeface */ public static Font applyBoldFont(final Font font) { if (font == null) { return null; } final FontData[] fontDataArray = font.getFontData(); if (fontDataArray == null) { return null; } for (int index = 0; index < fontDataArray.length; index++) { final FontData fData = fontDataArray[index]; fData.setStyle(SWT.BOLD); } return new Font(Display.getDefault(), fontDataArray); } /** * Applies a certain font size to a font. * * @param font Font to modify * @param size New font size * @return Font with new font size */ public static Font applyFontSize(final Font font, final int size) { if (font == null) { return null; } final FontData[] fontDataArray = font.getFontData(); if (fontDataArray == null) { return null; } for (int index = 0; index < fontDataArray.length; index++) { final FontData fData = fontDataArray[index]; fData.setHeight(size); } return new Font(Display.getDefault(), fontDataArray); } /** * Centers a dialog (Shell) on the <b>primary</b> (active) display. * * @param shell Shell to center on screen * @see Shell */ public static void centerDialogOnScreen(final Shell shell) { // do it by monitor to support dual-head cards and still center things correctly onto the screen people are on. final Monitor monitor = Display.getDefault().getPrimaryMonitor(); final Rectangle bounds = monitor.getBounds(); final int screen_x = bounds.width; final int screen_y = bounds.height; shell.setLocation(screen_x / 2 - (shell.getBounds().width / 2), screen_y / 2 - (shell.getBounds().height / 2)); } }
FranColmenero/Nebula
src/org/eclipse/nebula/widgets/ganttchart/Utils.java
Java
epl-1.0
2,667
/* * 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.api.workspace.server.event; import static org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_STATUS_CHANGED_METHOD; import java.util.Map; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Singleton; import org.eclipse.che.api.core.notification.RemoteSubscriptionManager; import org.eclipse.che.api.workspace.shared.dto.event.WorkspaceStatusEvent; /** Send workspace events using JSON RPC to the clients */ @Singleton public class WorkspaceJsonRpcMessenger { private final RemoteSubscriptionManager remoteSubscriptionManager; @Inject public WorkspaceJsonRpcMessenger(RemoteSubscriptionManager remoteSubscriptionManager) { this.remoteSubscriptionManager = remoteSubscriptionManager; } @PostConstruct private void postConstruct() { remoteSubscriptionManager.register( WORKSPACE_STATUS_CHANGED_METHOD, WorkspaceStatusEvent.class, this::predicate); } private boolean predicate(WorkspaceStatusEvent event, Map<String, String> scope) { return event.getWorkspaceId().equals(scope.get("workspaceId")); } }
sleshchenko/che
wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/event/WorkspaceJsonRpcMessenger.java
Java
epl-1.0
1,474
/******************************************************************************* * Copyright (c) 2006, 2013 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 * ******************************************************************************/ package org.eclipse.persistence.jpa.tests.jpql.parser; import org.junit.Test; import static org.eclipse.persistence.jpa.tests.jpql.parser.JPQLParserTester.*; @SuppressWarnings("nls") public final class ObjectExpressionTest extends JPQLParserTest { @Test public void test_JPQLQuery_01() { String query = "SELECT OBJECT(e) FROM Employee e"; SelectStatementTester selectStatement = selectStatement( select(object("e")), from("Employee", "e") ); testQuery(query, selectStatement); } @Test public void test_JPQLQuery_02() { String query = "SELECT OBJECT FROM Employee e"; ObjectExpressionTester objectExpression = object(nullExpression()); objectExpression.hasLeftParenthesis = false; objectExpression.hasRightParenthesis = false; SelectStatementTester selectStatement = selectStatement( select(objectExpression), from("Employee", "e") ); testInvalidQuery(query, selectStatement); } @Test public void test_JPQLQuery_03() { String query = "SELECT OBJECT( FROM Employee e"; ObjectExpressionTester objectExpression = object(nullExpression()); objectExpression.hasLeftParenthesis = true; objectExpression.hasRightParenthesis = false; SelectStatementTester selectStatement = selectStatement( select(objectExpression), from("Employee", "e") ); testInvalidQuery(query, selectStatement); } @Test public void test_JPQLQuery_04() { String query = "SELECT OBJECT() FROM Employee e"; ObjectExpressionTester objectExpression = object(nullExpression()); objectExpression.hasLeftParenthesis = true; objectExpression.hasRightParenthesis = true; SelectStatementTester selectStatement = selectStatement( select(object(nullExpression())), from("Employee", "e") ); testInvalidQuery(query, selectStatement); } @Test public void test_JPQLQuery_05() { String query = "SELECT OBJECT, e FROM Employee e"; ObjectExpressionTester objectExpression = object(nullExpression()); objectExpression.hasLeftParenthesis = false; objectExpression.hasRightParenthesis = false; SelectStatementTester selectStatement = selectStatement( select(objectExpression, variable("e")), from("Employee", "e") ); testInvalidQuery(query, selectStatement); } @Test public void test_JPQLQuery_06() { String query = "SELECT OBJECT(, e FROM Employee e"; ObjectExpressionTester objectExpression = object(nullExpression()); objectExpression.hasLeftParenthesis = true; objectExpression.hasRightParenthesis = false; SelectStatementTester selectStatement = selectStatement( select(objectExpression, variable("e")), from("Employee", "e") ); testInvalidQuery(query, selectStatement); } @Test public void test_JPQLQuery_07() { String query = "SELECT OBJECT), e FROM Employee e"; ObjectExpressionTester objectExpression = object(nullExpression()); objectExpression.hasLeftParenthesis = false; objectExpression.hasRightParenthesis = true; SelectStatementTester selectStatement = selectStatement( select(objectExpression, variable("e")), from("Employee", "e") ); testInvalidQuery(query, selectStatement); } }
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
jpa/org.eclipse.persistence.jpa.jpql.test/src/org/eclipse/persistence/jpa/tests/jpql/parser/ObjectExpressionTest.java
Java
epl-1.0
3,976
/* * Copyright (c) 2010-2012 Research In Motion Limited. All rights reserved. * * This program and the accompanying materials are made available * under the terms of the Eclipse Public License, Version 1.0, * which accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html * */ package net.rim.ejde.internal.ui.editors.locale; /** * IDisplayable interface * * @author jkeshavarzi * */ interface IDisplayable { public void display(); }
blackberry/Eclipse-JDE
net.rim.ejde/src/net/rim/ejde/internal/ui/editors/locale/IDisplayable.java
Java
epl-1.0
504
/******************************************************************************* * Copyright (c) 2012-2015 Codenvy, S.A. * 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: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.ext.github.client; import org.eclipse.che.ide.collections.Array; import org.eclipse.che.ide.collections.StringMap; import org.eclipse.che.ide.ext.github.shared.Collaborators; import org.eclipse.che.ide.ext.github.shared.GitHubIssueComment; import org.eclipse.che.ide.ext.github.shared.GitHubIssueCommentInput; import org.eclipse.che.ide.ext.github.shared.GitHubPullRequest; import org.eclipse.che.ide.ext.github.shared.GitHubPullRequestCreationInput; import org.eclipse.che.ide.ext.github.shared.GitHubPullRequestList; import org.eclipse.che.ide.ext.github.shared.GitHubRepository; import org.eclipse.che.ide.ext.github.shared.GitHubRepositoryList; import org.eclipse.che.ide.ext.github.shared.GitHubUser; import org.eclipse.che.ide.rest.AsyncRequestCallback; import javax.annotation.Nonnull; import java.util.List; /** * Client service for Samples. * * @author Oksana Vereshchaka * @author Kevin Pollet */ public interface GitHubClientService { /** * Get given repository information. * * @param user * the owner of the repository. * @param repository * the repository name. * @param callback * callback called when operation is done. */ void getRepository(@Nonnull String user, @Nonnull String repository, @Nonnull AsyncRequestCallback<GitHubRepository> callback); /** * Get list of available public and private repositories of the authorized user. * * @param callback * callback called when operation is done. */ void getRepositoriesList(@Nonnull AsyncRequestCallback<GitHubRepositoryList> callback); /** * Get list of forks for given repository * * @param user * the owner of the repository. * @param repository * the repository name. * @param callback * callback called when operation is done. */ void getForks(@Nonnull String user, @Nonnull String repository, @Nonnull AsyncRequestCallback<GitHubRepositoryList> callback); /** * Fork the given repository for the authorized user. * * @param user * the owner of the repository to fork. * @param repository * the repository name. * @param callback * callback called when operation is done. */ void fork(@Nonnull String user, @Nonnull String repository, @Nonnull AsyncRequestCallback<GitHubRepository> callback); /** * Add a comment to the issue on the given repository. * * @param user * the owner of the repository. * @param repository * the repository name. * @param issue * the issue number. * @param input * the comment. * @param callback * callback called when operation is done. */ void commentIssue(@Nonnull String user, @Nonnull String repository, @Nonnull String issue, @Nonnull GitHubIssueCommentInput input, @Nonnull AsyncRequestCallback<GitHubIssueComment> callback); /** * Get pull requests for given repository. * * @param owner * the repository owner. * @param repository * the repository name. * @param callback * callback called when operation is done. */ void getPullRequests(@Nonnull String owner, @Nonnull String repository, @Nonnull AsyncRequestCallback<GitHubPullRequestList> callback); /** * Get a pull request by id for a given repository. * * @param owner the owner of the target repository * @param repository the target repository * @param pullRequestId the Id of the pull request * @param callback the callback with either the pull request as argument or null if it doesn't exist */ void getPullRequest(@Nonnull String owner, @Nonnull String repository, @Nonnull String pullRequestId, @Nonnull AsyncRequestCallback<GitHubPullRequest> callback); /** * Create a pull request on origin repository * * @param user * the owner of the repository. * @param repository * the repository name. * @param input * the pull request information. * @param callback * callback called when operation is done. */ void createPullRequest(@Nonnull String user, @Nonnull String repository, @Nonnull GitHubPullRequestCreationInput input, @Nonnull AsyncRequestCallback<GitHubPullRequest> callback); /** * Get the list of available public repositories for a GitHub user. * * @param userName * the name of GitHub User * @param callback * callback called when operation is done. */ void getRepositoriesByUser(String userName, @Nonnull AsyncRequestCallback<GitHubRepositoryList> callback); /** * Get the list of available repositories by GitHub organization. * * @param organization * the name of GitHub organization. * @param callback * callback called when operation is done. */ void getRepositoriesByOrganization(String organization, @Nonnull AsyncRequestCallback<GitHubRepositoryList> callback); /** * Get list of available public repositories for GitHub account. * * @param account * the GitHub account. * @param callback * callback called when operation is done. */ void getRepositoriesByAccount(String account, @Nonnull AsyncRequestCallback<GitHubRepositoryList> callback); /** * Get list of collaborators of GitHub repository. For detail see GitHub REST API http://developer.github.com/v3/repos/collaborators/. * * @param user * the owner of the repository. * @param repository * the repository name. * @param callback * callback called when operation is done. */ void getCollaborators(@Nonnull String user, @Nonnull String repository, @Nonnull AsyncRequestCallback<Collaborators> callback); /** * Get the GitHub oAuth token for the pointed user. * * @param user * user's id * @param callback * callback called when operation is done. */ void getUserToken(@Nonnull String user, @Nonnull AsyncRequestCallback<String> callback); /** * Get the map of available public and private repositories of the authorized user and organizations he exists in. * * @param callback * callback called when operation is done. */ void getAllRepositories(@Nonnull AsyncRequestCallback<StringMap<Array<GitHubRepository>>> callback); /** * Get the list of the organizations, where authorized user is a member. * * @param callback * callback called when operation is done. */ void getOrganizations(@Nonnull AsyncRequestCallback<List<String>> callback); /** * Get authorized user information. * * @param callback * callback called when operation is done. */ void getUserInfo(@Nonnull AsyncRequestCallback<GitHubUser> callback); /** * Generate and upload new public key if not exist on github.com. * * @param callback * callback called when operation is done. */ void updatePublicKey(@Nonnull AsyncRequestCallback<Void> callback); }
sunix/che-plugins
plugin-github/che-plugin-github-ext-github/src/main/java/org/eclipse/che/ide/ext/github/client/GitHubClientService.java
Java
epl-1.0
8,040
/** * Copyright (c) 2012, 2016 Sme.UP 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.smeup.sys.il.expr.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.smeup.sys.il.expr.ExpressionType; import org.smeup.sys.il.expr.QBooleanExpression; import org.smeup.sys.il.expr.QExpression; import org.smeup.sys.il.expr.QExpressionVisitor; import org.smeup.sys.il.expr.QIntegratedLanguageExpressionPackage; /** * <!-- begin-user-doc --> An implementation of the model object ' * <em><b>Boolean Expression</b></em>'. <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.smeup.sys.il.expr.impl.BooleanExpressionImpl#getOperand <em>Operand</em>}</li> * </ul> * * @generated */ public class BooleanExpressionImpl extends PredicateExpressionImpl implements QBooleanExpression { /** * */ private static final long serialVersionUID = 1L; /** * The cached value of the '{@link #getOperand() <em>Operand</em>}' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getOperand() * @generated * @ordered */ protected QExpression operand; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ protected BooleanExpressionImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return QIntegratedLanguageExpressionPackage.Literals.BOOLEAN_EXPRESSION; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public QExpression getOperand() { return operand; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public NotificationChain basicSetOperand(QExpression newOperand, NotificationChain msgs) { QExpression oldOperand = operand; operand = newOperand; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, QIntegratedLanguageExpressionPackage.BOOLEAN_EXPRESSION__OPERAND, oldOperand, newOperand); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void setOperand(QExpression newOperand) { if (newOperand != operand) { NotificationChain msgs = null; if (operand != null) msgs = ((InternalEObject)operand).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - QIntegratedLanguageExpressionPackage.BOOLEAN_EXPRESSION__OPERAND, null, msgs); if (newOperand != null) msgs = ((InternalEObject)newOperand).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - QIntegratedLanguageExpressionPackage.BOOLEAN_EXPRESSION__OPERAND, null, msgs); msgs = basicSetOperand(newOperand, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, QIntegratedLanguageExpressionPackage.BOOLEAN_EXPRESSION__OPERAND, newOperand, newOperand)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case QIntegratedLanguageExpressionPackage.BOOLEAN_EXPRESSION__OPERAND: return basicSetOperand(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 QIntegratedLanguageExpressionPackage.BOOLEAN_EXPRESSION__OPERAND: return getOperand(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case QIntegratedLanguageExpressionPackage.BOOLEAN_EXPRESSION__OPERAND: setOperand((QExpression)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case QIntegratedLanguageExpressionPackage.BOOLEAN_EXPRESSION__OPERAND: setOperand((QExpression)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case QIntegratedLanguageExpressionPackage.BOOLEAN_EXPRESSION__OPERAND: return operand != null; } return super.eIsSet(featureID); } @Override public ExpressionType getExpressionType() { return ExpressionType.BOOLEAN; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void accept(QExpressionVisitor visitor) { if (visitor.visit(this)) if (getOperand() != null) getOperand().accept(visitor); visitor.endVisit(this); } } // BooleanExpressionImpl
smeup/asup
org.smeup.sys.il.expr/src/org/smeup/sys/il/expr/impl/BooleanExpressionImpl.java
Java
epl-1.0
5,458
package gov.nih.nlm.uts.webservice.content; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for getTermStrings complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="getTermStrings"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="ticket" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="version" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="termId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="psf" type="{http://webservice.uts.umls.nlm.nih.gov/}psf" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getTermStrings", propOrder = { "ticket", "version", "termId", "psf" }) public class GetTermStrings { protected String ticket; protected String version; protected String termId; protected Psf psf; /** * Gets the value of the ticket property. * * @return * possible object is * {@link String } * */ public String getTicket() { return ticket; } /** * Sets the value of the ticket property. * * @param value * allowed object is * {@link String } * */ public void setTicket(String value) { this.ticket = value; } /** * Gets the value of the version property. * * @return * possible object is * {@link String } * */ public String getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the termId property. * * @return * possible object is * {@link String } * */ public String getTermId() { return termId; } /** * Sets the value of the termId property. * * @param value * allowed object is * {@link String } * */ public void setTermId(String value) { this.termId = value; } /** * Gets the value of the psf property. * * @return * possible object is * {@link Psf } * */ public Psf getPsf() { return psf; } /** * Sets the value of the psf property. * * @param value * allowed object is * {@link Psf } * */ public void setPsf(Psf value) { this.psf = value; } }
dkincaid/clumcl
src/generated/java/gov/nih/nlm/uts/webservice/content/GetTermStrings.java
Java
epl-1.0
3,113
package org.allmyinfo.word.search.impl; import org.allmyinfo.coordinator.Coordinator; import org.allmyinfo.meaning.word.WordMeaning; import org.allmyinfo.meaning.wordparent.WordParentMeaning; import org.allmyinfo.util.osgi.EqFilter; import org.allmyinfo.util.osgi.activator.BaseActivator; import org.allmyinfo.util.osgi.activator.RequiredService; import org.allmyinfo.word.index.cp.WordIndexContextProvider; import org.allmyinfo.word.parser.WordParser; import org.allmyinfo.word.search.WordSearch; import org.eclipse.jdt.annotation.NonNull; import org.osgi.framework.BundleContext; public class Activator extends BaseActivator { public Activator() { final RequiredService wordMeaningRS = addRequiredService(WordMeaning.class.getName(), null); final RequiredService wordParentMeaningRS = addRequiredService( WordParentMeaning.class.getName(), null); final RequiredService coordinatorRS = addRequiredService(Coordinator.class.getName(), null); final RequiredService wicpRS = addRequiredService(WordIndexContextProvider.class.getName(), null); final RequiredService wpRS = addRequiredService(WordParser.class.getName(), new EqFilter( "mime-type", "text/plain")); addListener(new Listener() { @Override public void startService(final @NonNull BundleContext context) { final WordSearch service = new WordSearchImpl( context, // new WordMeaning.Reactor(context, (WordMeaning) wordMeaningRS.getInstance()), // new WordParentMeaning.Reactor(context, (WordParentMeaning) wordParentMeaningRS.getInstance()), // new Coordinator.Reactor(context, (Coordinator) coordinatorRS.getInstance()), // new WordIndexContextProvider.Reactor(context, (WordIndexContextProvider) wicpRS.getInstance()), new WordParser.Reactor(context, (WordParser) wpRS.getInstance())); Activator.this.addRegistration(context.registerService(WordSearch.class, service, null)); } @Override public void stopService(final @NonNull BundleContext context) { } @Override public String getName() { return Activator.class.getPackage().getName(); } }); } }
sschafer/atomic
org.allmyinfo.word.search.impl/src/org/allmyinfo/word/search/impl/Activator.java
Java
epl-1.0
2,131
package org.apache.wicket.markup.html.image.resource; import java.util.*; import org.apache.wicket.request.resource.*; import org.apache.wicket.*; import org.apache.wicket.util.parse.metapattern.parsers.*; import org.apache.wicket.util.parse.metapattern.*; public class DefaultButtonImageResourceFactory implements IResourceFactory{ public IResource newResource(final String specification,final Locale locale,final String style,final String variation){ final Parser parser=new Parser((CharSequence)specification); if(parser.matches()){ return new DefaultButtonImageResource(parser.getWidth(),parser.getHeight(),parser.getLabel()); } throw new WicketRuntimeException("DefaultButtonImageResourceFactory does not recognized the specification "+specification); } private static final class Parser extends MetaPatternParser{ private static final IntegerGroup width; private static final IntegerGroup height; private static final Group label; private static final MetaPattern pattern; public Parser(final CharSequence input){ super(Parser.pattern,input); } public String getLabel(){ return Parser.label.get(this.matcher()); } public int getWidth(){ return Parser.width.getInt(this.matcher(),-1); } public int getHeight(){ return Parser.height.getInt(this.matcher(),-1); } static{ width=new IntegerGroup(); height=new IntegerGroup(); label=new Group(MetaPattern.ANYTHING); pattern=new MetaPattern(new MetaPattern[] { new OptionalMetaPattern(new MetaPattern[] { Parser.width,MetaPattern.COMMA,Parser.height,MetaPattern.COLON }),Parser.label }); } } }
windup/windup-sample-apps
test-files/src_example/org/apache/wicket/markup/html/image/resource/DefaultButtonImageResourceFactory.java
Java
epl-1.0
1,813
/** * Copyright (c) 2016 Deutsche Telekom AG 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.smarthome.core.thing.binding.firmware; /** * The {@link ProgressCallback} is injected into the * {@link FirmwareUpdateHandler#updateFirmware(Firmware, ProgressCallback)} operation in order to post progress * information about the firmware update process. * * @author Thomas Höfer - Initial contribution */ public interface ProgressCallback { /** * Callback operation to define the {@link ProgressStep}s for the sequence of the firmware update. So if the * operation is invoked with the following progress steps * <ul> * <li>{@link ProgressStep#DOWNLOADING}</li> * <li>{@link ProgressStep#TRANSFERRING}</li> * <li>{@link ProgressStep#UPDATING}</li> * </ul> * then this will mean that the firmware update implementation will initially download the firmware, then * it will transfer the firmware to the actual device and in a final step it will trigger the update. * * @param sequence the progress steps describing the sequence of the firmware update process (must not be null * or empty) * * @throws IllegalArgumentException if given sequence is null or empty */ void defineSequence(ProgressStep... sequence); /** * Callback operation to indicate that the next progress step is going to be executed. Following the example of the * {@link ProgressCallback#defineSequence(ProgressStep...)} operation then the first invocation of this operation * will indicate that firmware update handler is going to download the firmware, the second invocation will indicate * that the handler is going to transfer the firmware to the device and consequently the third invocation will * indicate that the handler is going to trigger the update. * * @throws IllegalStateException if * <ul> * <li>there is no further step to be executed</li> * <li>if no sequence was defined</li> * </ul> */ void next(); /** * Callback operation to indicate that the firmware update has failed. * * @param errorMessageKey the key of the error message to be internationalized (must not be null or empty) * @param arguments the arguments to be injected into the internationalized error message (can be null) * * @throws IllegalArgumentException if given error message key is null or empty */ void failed(String errorMessageKey, Object... arguments); /** * Callback operation to indicate that the firmware update was successful. */ void success(); }
adimova/smarthome
bundles/core/org.eclipse.smarthome.core.thing/src/main/java/org/eclipse/smarthome/core/thing/binding/firmware/ProgressCallback.java
Java
epl-1.0
2,920
/** * <copyright> * </copyright> * * $Id: AmetamodelFactory.java,v 1.1 2010/02/04 09:24:53 sefftinge Exp $ */ package org.eclipse.xtext.grammarinheritance.ametamodel; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see org.eclipse.xtext.grammarinheritance.ametamodel.AmetamodelPackage * @generated */ public interface AmetamodelFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ AmetamodelFactory eINSTANCE = org.eclipse.xtext.grammarinheritance.ametamodel.impl.AmetamodelFactoryImpl.init(); /** * Returns a new object of class '<em>AType</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>AType</em>'. * @generated */ AType createAType(); /** * Returns a new object of class '<em>AModel</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>AModel</em>'. * @generated */ AModel createAModel(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ AmetamodelPackage getAmetamodelPackage(); } //AmetamodelFactory
miklossy/xtext-core
org.eclipse.xtext.tests/emf-gen/org/eclipse/xtext/grammarinheritance/ametamodel/AmetamodelFactory.java
Java
epl-1.0
1,425
/** * Copyright (c) 2016 NumberFour AG. * 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: * NumberFour AG - Initial API and implementation */ package org.eclipse.n4js.n4JS; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>This Target</b></em>'. * <!-- end-user-doc --> * * <!-- begin-model-doc --> * Possible target to which a this expression may be bound. This is used in the type inferrer. * Note that this is not bound by local scoping, as \'this\' is not a variable (or cross reference)! * <!-- end-model-doc --> * * * @see org.eclipse.n4js.n4JS.N4JSPackage#getThisTarget() * @model abstract="true" * @generated */ public interface ThisTarget extends EObject { } // ThisTarget
lbeurerkellner/n4js
plugins/org.eclipse.n4js.model/emf-gen/org/eclipse/n4js/n4JS/ThisTarget.java
Java
epl-1.0
986
/************************************************************************************************/ /* i-Code CNES is a static code analyzer. */ /* This software is a free software, under the terms of the Eclipse Public License version 1.0. */ /* http://www.eclipse.org/legal/epl-v10.html */ /************************************************************************************************/ package fr.cnes.analysis.tools.ui.preferences; import fr.cnes.analysis.tools.ui.Activator; import fr.cnes.icode.logger.ICodeLogger; import org.eclipse.jface.preference.IPreferenceStore; /** * Container for Checker preferences used by {@link UserPreferencesService} */ public class CheckerPreferencesContainer { /** * Class name */ private static final String CLASS = CheckerPreferencesContainer.class.getName(); /** * Checker's identifier */ private String id; /** * Checker's name */ private String name; /** * Checker's enabling */ private boolean checked; /** * Checker's severity */ private String severity; /** * Checker's max value */ private Float maxValue; /** * Checker's min value */ private Float minValue; /** * Checker is a metric */ private boolean isMetric; /** * Checker language's name */ private String languageName; /** * Checker language's id */ private String languageId; /** * @param pLanguageId Checker language's id * @param pLanguageName Checker language's name * @param pId Checker's identifier * @param pName Checker's name * @param pChecked Checker's enabling * @param pSeverity Checker's severity * @param pIsMetric Checker is a metric */ public CheckerPreferencesContainer(final String pLanguageId, final String pLanguageName, final String pId, final String pName, final boolean pChecked, final String pSeverity, final boolean pIsMetric) { final String method = "CheckerPreferencesContainer"; ICodeLogger.entering(CLASS, method, new Object[]{ pLanguageId, pLanguageName, pId, pName, Boolean.valueOf(pChecked), pSeverity, Boolean.valueOf(pIsMetric) }); this.languageId = pLanguageId; this.languageName = pLanguageName; this.id = pId; this.name = pName; this.checked = pChecked; this.severity = pSeverity; this.minValue = Float.valueOf(Float.NaN); this.maxValue = Float.valueOf(Float.NaN); this.isMetric = pIsMetric; ICodeLogger.exiting(CLASS, method); } /** * @param pLanguageId Checker language's id * @param pLanguageName Checker language's name * @param pId Checker's identifier * @param pName Checker's name * @param pChecked Checker's enabling * @param pSeverity Checker's severity * @param pMinValue Checker's min value * @param pMaxValue Checker's max value * @param pIsMetric Checker is a metric */ public CheckerPreferencesContainer(final String pLanguageId, final String pLanguageName, final String pId, final String pName, final boolean pChecked, final String pSeverity, final Float pMinValue, final Float pMaxValue, final boolean pIsMetric) { final String method = "CheckerPreferencesContainer"; ICodeLogger.entering(CLASS, method, new Object[]{ pLanguageId, pLanguageName, pId, pName, Boolean.valueOf(pChecked), pSeverity, pMinValue, pMaxValue, Boolean.valueOf(pIsMetric) }); this.languageId = pLanguageId; this.languageName = pLanguageName; this.id = pId; this.name = pName; this.checked = pChecked; this.severity = pSeverity; this.minValue = pMinValue; this.maxValue = pMaxValue; this.isMetric = pIsMetric; ICodeLogger.exiting(CLASS, method); } /** * @return the id */ public final String getId() { final String method = "getId"; ICodeLogger.entering(CLASS, method); ICodeLogger.exiting(CLASS, method, id); return id; } /** * @param pId the id to set */ public final void setId(final String pId) { final String method = "setId"; ICodeLogger.entering(CLASS, method, pId); this.id = pId; ICodeLogger.exiting(CLASS, method); } /** * @return the name */ public final String getName() { final String method = "getName"; ICodeLogger.entering(CLASS, method); ICodeLogger.exiting(CLASS, method, name); return name; } /** * @param pName the name to set */ public final void setName(final String pName) { final String method = "setName"; ICodeLogger.entering(CLASS, method, pName); this.name = pName; ICodeLogger.exiting(CLASS, method); } /** * @return the checked */ public final boolean isChecked() { final String method = "isChecked"; ICodeLogger.entering(CLASS, method); ICodeLogger.exiting(CLASS, method, Boolean.valueOf(checked)); return checked; } /** * @param pChecked the checked to set */ public final void setChecked(final boolean pChecked) { final String method = "setChecked"; ICodeLogger.entering(CLASS, method, Boolean.valueOf(pChecked)); this.checked = pChecked; ICodeLogger.exiting(CLASS, method); } /** * @return the severity */ public final String getSeverity() { final String method = "getSeverity"; ICodeLogger.entering(CLASS, method); ICodeLogger.exiting(CLASS, method, severity); return severity; } /** * @param pSeverity the severity to set */ public final void setSeverity(final String pSeverity) { final String method = "setSeverity"; ICodeLogger.entering(CLASS, method, pSeverity); this.severity = pSeverity; ICodeLogger.exiting(CLASS, method); } /** * @return the maxValue */ public final Float getMaxValue() { final String method = "getMaxValue"; ICodeLogger.entering(CLASS, method); ICodeLogger.exiting(CLASS, method, maxValue); return maxValue; } /** * @param pMaxValue the maxValue to set */ public final void setMaxValue(final float pMaxValue) { final String method = "setMaxValue"; ICodeLogger.entering(CLASS, method); this.maxValue = Float.valueOf(pMaxValue); ICodeLogger.exiting(CLASS, method); } /** * @return the minValue */ public final Float getMinValue() { final String method = "getMinValue"; ICodeLogger.entering(CLASS, method); ICodeLogger.exiting(CLASS, method, minValue); return minValue; } /** * @param pMinValue the minValue to set */ public final void setMinValue(final float pMinValue) { final String method = "setMinValue"; ICodeLogger.entering(CLASS, method, Float.valueOf(pMinValue)); this.minValue = Float.valueOf(pMinValue); ICodeLogger.exiting(CLASS, method); } /** * @param languageId */ public void savePreferences() { final String method = "savePreferences"; ICodeLogger.entering(CLASS, method); final IPreferenceStore store = Activator.getDefault().getPreferenceStore(); store.setValue(this.getId(), checked); store.setValue(this.getId() + UserPreferencesService.PREF_SEVERITY_KEY, this.severity); if (!this.maxValue.isNaN()) { store.setValue(this.getId() + UserPreferencesService.PREF_MAX_VALUE_KEY, this.maxValue.floatValue()); } if (!this.minValue.isNaN()) { store.setValue(this.getId() + UserPreferencesService.PREF_MIN_VALUE_KEY, this.minValue.floatValue()); } ICodeLogger.exiting(CLASS, method); } /** * Set preferences to default. */ public void setToDefault() { final String method = "setToDefault"; ICodeLogger.entering(CLASS, method); final IPreferenceStore store = Activator.getDefault().getPreferenceStore(); this.checked = store.getDefaultBoolean(this.getId()); store.setToDefault(this.getId()); this.severity = store .getDefaultString(this.getId() + UserPreferencesService.PREF_SEVERITY_KEY); store.setToDefault(this.getId() + UserPreferencesService.PREF_SEVERITY_KEY); if (this.isMetric) { this.maxValue = Float.valueOf(store.getDefaultFloat( this.getId() + UserPreferencesService.PREF_MAX_VALUE_KEY)); store.setToDefault(this.getId() + UserPreferencesService.PREF_MAX_VALUE_KEY); } if (this.isMetric) { this.minValue = Float.valueOf(store.getDefaultFloat( this.getId() + UserPreferencesService.PREF_MAX_VALUE_KEY)); store.setToDefault(this.getId() + UserPreferencesService.PREF_MIN_VALUE_KEY); } ICodeLogger.exiting(CLASS, method); } /** * Update preferences store with current values of attributes. */ public void update() { final String method = "update"; ICodeLogger.entering(CLASS, method); final IPreferenceStore store = Activator.getDefault().getPreferenceStore(); if (!store.contains(this.getId())) { this.checked = true; } else { this.checked = store.getBoolean(this.getId()); } if (!store.contains(this.getId() + UserPreferencesService.PREF_SEVERITY_KEY)) { this.severity = UserPreferencesService.PREF_SEVERITY_ERROR_VALUE; } else { this.severity = store .getString(this.getId() + UserPreferencesService.PREF_SEVERITY_KEY); } if (this.isMetric) { this.maxValue = Float.valueOf(store .getFloat(this.getId() + UserPreferencesService.PREF_MAX_VALUE_KEY)); } if (this.isMetric) { this.minValue = Float.valueOf(store .getFloat(this.getId() + UserPreferencesService.PREF_MIN_VALUE_KEY)); } ICodeLogger.exiting(CLASS, method); } /** * @return the isMetric */ public final boolean isMetric() { final String method = "isMetric"; ICodeLogger.entering(CLASS, method); ICodeLogger.exiting(CLASS, method, Boolean.valueOf(isMetric)); return isMetric; } /** * @param pIsMetric the isMetric to set */ public final void setMetric(final boolean pIsMetric) { final String method = "setMetric"; ICodeLogger.entering(CLASS, method, Boolean.valueOf(pIsMetric)); this.isMetric = pIsMetric; ICodeLogger.exiting(CLASS, method); } /** * @param pMaxValue the maxValue to set */ public final void setMaxValue(final Float pMaxValue) { final String method = "setMaxValue"; ICodeLogger.entering(CLASS, method, pMaxValue); this.maxValue = pMaxValue; ICodeLogger.exiting(CLASS, method); } /** * @param pMinValue the minValue to set */ public final void setMinValue(final Float pMinValue) { final String method = "setMinValue"; ICodeLogger.entering(CLASS, method, pMinValue); this.minValue = pMinValue; ICodeLogger.exiting(CLASS, method); } /** * @return the languageId */ public final String getLanguageId() { final String method = "getLanguageId"; ICodeLogger.entering(CLASS, method); ICodeLogger.exiting(CLASS, method, languageId); return languageId; } /** * @param pLanguageId the languageId to set */ public final void setLanguageId(final String pLanguageId) { final String method = "setLanguageId"; ICodeLogger.entering(CLASS, method, pLanguageId); this.languageId = pLanguageId; ICodeLogger.exiting(CLASS, method); } /** * @param pLanguageName the languageName to set */ public final void setLanguageName(final String pLanguageName) { final String method = "setLanguageName"; ICodeLogger.entering(CLASS, method, pLanguageName); this.languageName = pLanguageName; ICodeLogger.exiting(CLASS, method); } /** * @return the languageName */ public final String getLanguageName() { final String method = "getLanguageName"; ICodeLogger.entering(CLASS, method); ICodeLogger.exiting(CLASS, method, languageName); return languageName; } }
dupuisa/i-CodeCNES
icode-ide/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/preferences/CheckerPreferencesContainer.java
Java
epl-1.0
13,616
package org.botlibre.test; import java.util.HashMap; import java.util.Map; import org.botlibre.util.Utils; public class GoogleTest { static String clientId = ""; static String clientSecret = ""; static String redirectUri= ""; static String accessToken = ""; static String refreshtoken = ""; static int step = 3; /** A new token is require per request. */ static String authCode = ""; public static void main(String[] args) throws Exception { if (step == 0) { System.out.println("open this link in a web browser"); System.out.println("https://accounts.google.com/o/oauth2/auth?client_id=" + clientId + "&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/calendar.readonly&response_type=code"); } else if (step == 1) { Map<String, String> params = new HashMap<String, String>(); params.put("code", authCode); params.put("client_id", clientId); params.put("client_secret", clientSecret); params.put("redirect_uri", "urn:ietf:wg:oauth:2.0:oob"); params.put("grant_type", "authorization_code"); String result = Utils.httpPOST("https://accounts.google.com/o/oauth2/token", params); System.out.println(result); } else if (step == 2) { Map<String, String> params = new HashMap<String, String>(); params.put("refresh_token", refreshtoken); params.put("client_id", clientId); params.put("client_secret", clientSecret); //params.put("redirect_uri", "urn:ietf:wg:oauth:2.0:oob"); params.put("grant_type", "refresh_token"); String result = Utils.httpPOST("https://accounts.google.com/o/oauth2/token", params); System.out.println(result); } else if (step == 3) { //String result = Utils.httpGET("https://www.googleapis.com/calendar/v3/calendars/primary?access_token=" + accessToken); String result = Utils.httpGET("https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMax=2016-10-05T00%3A00%3A00-07%3A00&timeMin=2016-10-06T00%3A00%3A00-07%3A00&access_token=" + accessToken); System.out.println(result); } } }
BOTlibre/BOTlibre
ai-engine-test/source/org/botlibre/test/GoogleTest.java
Java
epl-1.0
2,231
/* COPYRIGHT-ENEA-SRC-R2 * ************************************************************************** * Copyright (C) 2005-2007 by Enea Software AB. * All rights reserved. * * This Software is furnished under a software license agreement and * may be used only in accordance with the terms of such agreement. * Any other use or reproduction is prohibited. No title to and * ownership of the Software is hereby transferred. * * PROPRIETARY NOTICE * This Software consists of confidential information. * Trade secret law and copyright law protect this Software. * The above notice of copyright on this Software does not indicate * any actual or intended publication of such Software. ************************************************************************** * COPYRIGHT-END */ package com.ose.system.ui.views.system; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import com.ose.system.ui.SystemBrowserPlugin; public class AddGateDialog extends Dialog { private String address; private int port; private Text addressText; private Text portText; private CLabel errorMessageLabel; public AddGateDialog(Shell parent) { super(parent); } protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText("Add Gate"); } protected Control createContents(Composite parent) { Control contents = super.createContents(parent); loadDialogSettings(); return contents; } protected Control createDialogArea(Composite parent) { Composite comp; Composite subcomp; ModifyHandler modifyHandler; GridData gd; Label addressLabel; Label portLabel; comp = (Composite) super.createDialogArea(parent); subcomp = new Composite(comp, SWT.NONE); subcomp.setLayout(new GridLayout(2, false)); modifyHandler = new ModifyHandler(); addressLabel = new Label(subcomp, SWT.NONE); addressLabel.setText("Address:"); addressText = new Text(subcomp, SWT.SINGLE | SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); gd.widthHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH); addressText.setLayoutData(gd); addressText.addModifyListener(modifyHandler); portLabel = new Label(subcomp, SWT.NONE); portLabel.setText("Port:"); portText = new Text(subcomp, SWT.SINGLE | SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); portText.setLayoutData(gd); portText.addModifyListener(modifyHandler); errorMessageLabel = new CLabel(subcomp, SWT.NONE); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; errorMessageLabel.setLayoutData(gd); applyDialogFont(comp); return comp; } private void loadDialogSettings() { IDialogSettings settings; IDialogSettings section; settings = SystemBrowserPlugin.getDefault().getDialogSettings(); section = settings.getSection("AddGateDialog"); if (section == null) { addressText.setText(""); portText.setText("21768"); } else { addressText.setText(section.get("address")); portText.setText(section.get("port")); addressText.selectAll(); } } private void saveDialogSettings() { IDialogSettings settings; IDialogSettings section; settings = SystemBrowserPlugin.getDefault().getDialogSettings(); section = settings.addNewSection("AddGateDialog"); section.put("address", addressText.getText().trim()); section.put("port", portText.getText().trim()); } protected void okPressed() { address = addressText.getText().trim(); try { port = Integer.parseInt(portText.getText().trim()); } catch (NumberFormatException ignore) {} saveDialogSettings(); super.okPressed(); } private void updateDialog() { String errorMessage = isAddressValid(addressText.getText()); if (errorMessage == null) { errorMessage = isPortValid(portText.getText()); } setErrorMessage(errorMessage); } private void setErrorMessage(String errorMessage) { errorMessageLabel.setText((errorMessage == null) ? "" : errorMessage); errorMessageLabel.setImage((errorMessage == null) ? null : PlatformUI.getWorkbench().getSharedImages() .getImage(ISharedImages.IMG_OBJS_ERROR_TSK)); getButton(IDialogConstants.OK_ID).setEnabled(errorMessage == null); getShell().update(); } private String isAddressValid(String text) { String errorMessage = null; if (text.trim().length() == 0) { errorMessage = "Address not specified"; } return errorMessage; } private String isPortValid(String text) { String errorMessage = null; if (text.trim().length() == 0) { errorMessage = "Port not specified"; } else { try { Integer.parseInt(text); } catch (NumberFormatException e) { errorMessage = "Invalid port number"; } } return errorMessage; } public String getAddress() { return address; } public int getPort() { return port; } class ModifyHandler implements ModifyListener { public void modifyText(ModifyEvent event) { updateDialog(); } } }
debabratahazra/OptimaLA
Optima/com.ose.system.ui/src/com/ose/system/ui/views/system/AddGateDialog.java
Java
epl-1.0
6,128
/** * Copyright (c) 2010-2013, 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.io.habmin.repository; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openhab.io.habmin.services.rule.RuleTemplateBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.StaxDriver; /** * * @author Chris Jackson * @since 1.4.0 * */ public class HabminConfigDatabase { private static final Logger logger = LoggerFactory.getLogger(HabminConfigDatabase.class); static private final String HABMIN_DATABASE_FILE = "webapps/habmin/openhab/configuration_database.xml"; static private HabminConfigDatabaseBean configDb = null; /** * Loads the database into memory. Once in memory, it isn't re-read - this * speeds up subsequent operations. * * @return true if the database is open */ static private boolean loadDatabase() { if (configDb != null) return true; logger.debug("Loading HABmin database."); FileInputStream fin; try { long timerStart = System.currentTimeMillis(); fin = new FileInputStream(HABMIN_DATABASE_FILE); XStream xstream = new XStream(new StaxDriver()); xstream.alias("HABminDatabase", HabminConfigDatabaseBean.class); xstream.processAnnotations(HabminConfigDatabaseBean.class); configDb = (HabminConfigDatabaseBean) xstream.fromXML(fin); fin.close(); long timerStop = System.currentTimeMillis(); logger.debug("HABmin database loaded in {}ms.", timerStop - timerStart); return true; } catch (FileNotFoundException e) { logger.debug("HABmin database not found - reinitialising."); configDb = new HabminConfigDatabaseBean(); if(configDb == null) return false; configDb.items = new ArrayList<HabminItemBean>(); if(configDb.items == null) { configDb = null; return false; } return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } static public boolean saveDatabase() { // This possibly should be moved to a separate thread so that it can be // deferred to avoid multiple calls if (loadDatabase() == false) return false; FileOutputStream fout; try { long timerStart = System.currentTimeMillis(); fout = new FileOutputStream(HABMIN_DATABASE_FILE); XStream xstream = new XStream(new StaxDriver()); xstream.alias("HABminDatabase", HabminConfigDatabaseBean.class); xstream.processAnnotations(HabminConfigDatabaseBean.class); xstream.toXML(configDb, fout); fout.close(); long timerStop = System.currentTimeMillis(); logger.debug("HABmin database saved in {}ms.", timerStop - timerStart); } catch (FileNotFoundException e) { logger.debug("Unable to open HABmin database for SAVE - ", e); return false; } catch (IOException e) { logger.debug("Unable to write HABmin database for SAVE - ", e); return false; } return true; } /** * Reads the Habmin configuration "database" and returns the item requested * by the item parameter. * * @param item * name of the item to return * @return HabminItemBean or null if not found */ synchronized static public HabminItemBean getItemConfig(String itemName) { if (loadDatabase() == false) return null; if(configDb.items == null) return null; HabminItemBean item = null; for (HabminItemBean bean : configDb.items) { if (bean.name == null) continue; if (bean.name.equals(itemName)) { item = bean; break; } } // If not found, create the new item if(item == null) { item = new HabminItemBean(); item.name = itemName; configDb.items.add(item); } // Make sure rules is initialised if(item.rules == null) item.rules = new ArrayList<RuleTemplateBean>(); if(item.rules == null) return null; // Not found return item; } /** * Reads the Habmin configuration "database" and returns the item requested * by the item parameter. * * @param item * name of the item to return * @return HabminItemBean or null if not found */ synchronized static public boolean existsItemConfig(String item) { if (loadDatabase() == false) return false; if(configDb.items == null) return false; for (HabminItemBean bean : configDb.items) { if (bean.name == null) continue; if (bean.name.equals(item)) return true; } // Not found return false; } /** * Saves item data in the Habmin "database" file. This will overwrite the * existing data for this item * * @param item * HabminItemBean with the item data * @return true if item data saved successfully */ synchronized static public boolean setItemConfig(HabminItemBean item) { if (loadDatabase() == false) return false; HabminItemBean foundItem = null; // Find the required item for (HabminItemBean bean : configDb.items) { if (bean.name == null) continue; if (bean.name.equals(item)) foundItem = bean; } if (foundItem != null) { // Found this item in the database, remove it configDb.items.remove(foundItem); } // Add the new data into the database configDb.items.add(item); saveDatabase(); // Success return true; } synchronized static public List<HabminItemBean> getItems() { if (loadDatabase() == false) return null; return configDb.items; } }
jenskastensson/openhab
bundles/io/org.openhab.io.habmin/src/main/java/org/openhab/io/habmin/repository/HabminConfigDatabase.java
Java
epl-1.0
5,795
<?php /******************************************************************************* * Copyright (c) 2011, 2014 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 *******************************************************************************/ use_stylesheet('/opMICExtPlugin/css/embedvis.css', 'last'); include("_embedVislinkTimeline_core.php"); ?>
kentarou-fukuda/CFEL
opMICExtPlugin/apps/pc_frontend/modules/stats/templates/_embedVislinkTimeline.php
PHP
epl-1.0
650
/******************************************************************************* * Copyright (c) 2011 4DIAC - consortium. * 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 * *******************************************************************************/ #include <cyg/kernel/kapi.h> #include <fortealloc.h> #include <EMB_RMT_DEV.h> #include "L_LED.h" #include "L_S_PORT.h" #include "avrctl.h" #include "LMSUSBLayer.h" externC void cyg_user_start(void); void delay(unsigned int i){ while(i){ --i; } } const char * const g_acId = "fbdk[].usb[1]"; void cyg_user_start(void){ FORTE_L_S_PORT::lmsInit1Port(1); FORTE_L_LED::lmsLtLedOff(0); CL_AVR_ctl::initAVR(); // Blink to show booting int i = 3; while(i--){ delay(3000000); FORTE_L_LED::lmsLtLedOn(0); delay(3000000); FORTE_L_LED::lmsLtLedOff(0); } EMB_RMT_DEV *poDev = new EMB_RMT_DEV(g_acId); poDev->startDevice(); } //get the stuff that fixes some ecos cpp problems which have to be near the main #include "../../arch/ecos/ecoscppinit.cpp" //we removed clib style startup but the cleanup of the singleton expects somehow an atexit func TODO find out how to avoid this externC int atexit(void (*func)(void)){ (void) func; //Suppress compiler warning return 0; } //currently we have no logging facility on LMS so we provide an empty implementation void logMessage(E_MsgLevel , const char *pa_acMessage, ...){ //TODO chekc if this is possible on lms // va_list pstArgPtr; // va_start(pstArgPtr, pa_acMessage); // vsnprintf(sm_acMsgBuf, scm_nMsgBufSize, pa_acMessage, pstArgPtr); // va_end(pstArgPtr); CLMSUSBLayer::sendUSBData(0, pa_acMessage, strlen(pa_acMessage)); }
EstebanQuerol/Black_FORTE
src/modules/lms/lmsmain.cpp
C++
epl-1.0
1,878
package com.temenos.t24.tools.eclipse.basic.protocols; import org.junit.Assert; import org.junit.Test; import com.temenos.t24.tools.eclipse.basic.protocols.actions.ActionCommon; public class ActionCommonTest { @Test public void testGetErrorMsg(){ Assert.assertTrue("".equals(ActionCommon.getMsgError(null))); Assert.assertTrue("SECURITY.VIOLATION".equals(ActionCommon.getMsgError("SECURITY.VIOLATION"))); Assert.assertTrue("OF.RTN.SECURITY.VIOLATION".equals(ActionCommon.getMsgError("OF.RTN.SECURITY.VIOLATION"))); } @Test public void testIsRawResponseOK(){ Assert.assertFalse(ActionCommon.isRawResponseOK(null)); Assert.assertFalse(ActionCommon.isRawResponseOK("null")); Assert.assertFalse(ActionCommon.isRawResponseOK("OFSERROR_TIMEOUT")); Assert.assertFalse(ActionCommon.isRawResponseOK("OFSERROR_PROCESS")); Assert.assertTrue(ActionCommon.isRawResponseOK("<xml>other</xml>")); } }
debabratahazra/DS
designstudio/components/basic/tests/com.odcgroup.basic.tests/src/test/java/com/temenos/t24/tools/eclipse/basic/protocols/ActionCommonTest.java
Java
epl-1.0
988
/****************************************************************************** * Copyright (c) 2000-2016 Ericsson Telecom AB * 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.titan.designer.AST.TTCN3.values.expressions; import java.util.List; import org.eclipse.titan.designer.AST.ASTVisitor; import org.eclipse.titan.designer.AST.INamedNode; import org.eclipse.titan.designer.AST.IReferenceChain; import org.eclipse.titan.designer.AST.IValue; import org.eclipse.titan.designer.AST.ReferenceFinder; import org.eclipse.titan.designer.AST.Scope; import org.eclipse.titan.designer.AST.Value; import org.eclipse.titan.designer.AST.IType.Type_type; import org.eclipse.titan.designer.AST.ReferenceFinder.Hit; import org.eclipse.titan.designer.AST.TTCN3.Expected_Value_type; import org.eclipse.titan.designer.AST.TTCN3.values.Boolean_Value; import org.eclipse.titan.designer.AST.TTCN3.values.Expression_Value; import org.eclipse.titan.designer.parsers.CompilationTimeStamp; import org.eclipse.titan.designer.parsers.ttcn3parser.ReParseException; import org.eclipse.titan.designer.parsers.ttcn3parser.TTCN3ReparseUpdater; /** * @author Kristof Szabados * */ public final class NotExpression extends Expression_Value { private static final String OPERANDERROR = "The operand of the `not' operation should be a boolean value"; private final Value value; public NotExpression(final Value value) { this.value = value; if (value != null) { value.setFullNameParent(this); } } @Override public Operation_type getOperationType() { return Operation_type.NOT_OPERATION; } @Override public String createStringRepresentation() { final StringBuilder builder = new StringBuilder(); builder.append("not(").append(value.createStringRepresentation()).append(')'); return builder.toString(); } @Override public void setMyScope(final Scope scope) { super.setMyScope(scope); if (value != null) { value.setMyScope(scope); } } @Override public StringBuilder getFullName(final INamedNode child) { final StringBuilder builder = super.getFullName(child); if (value == child) { return builder.append(OPERAND); } return builder; } @Override public Type_type getExpressionReturntype(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue) { return Type_type.TYPE_BOOL; } @Override public boolean isUnfoldable(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue, final IReferenceChain referenceChain) { if (value == null) { return true; } return value.isUnfoldable(timestamp, expectedValue, referenceChain); } /** * Checks the parameters of the expression and if they are valid in * their position in the expression or not. * * @param timestamp * the timestamp of the actual semantic check cycle. * @param expectedValue * the kind of value expected. * @param referenceChain * a reference chain to detect cyclic references. * */ private void checkExpressionOperands(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue, final IReferenceChain referenceChain) { if (value == null) { return; } value.setLoweridToReference(timestamp); Type_type temp = value.getExpressionReturntype(timestamp, expectedValue); switch (temp) { case TYPE_BOOL: value.getValueRefdLast(timestamp, expectedValue, referenceChain); break; case TYPE_UNDEFINED: setIsErroneous(true); break; default: location.reportSemanticError(OPERANDERROR); setIsErroneous(true); break; } } @Override public IValue evaluateValue(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue, final IReferenceChain referenceChain) { if (lastTimeChecked != null && !lastTimeChecked.isLess(timestamp)) { return lastValue; } isErroneous = false; lastTimeChecked = timestamp; lastValue = this; if (value == null) { setIsErroneous(true); return lastValue; } checkExpressionOperands(timestamp, expectedValue, referenceChain); if (getIsErroneous(timestamp)) { return lastValue; } if (isUnfoldable(timestamp, referenceChain)) { return lastValue; } IValue last = value.getValueRefdLast(timestamp, referenceChain); if (last.getIsErroneous(timestamp)) { setIsErroneous(true); return lastValue; } switch (last.getValuetype()) { case BOOLEAN_VALUE: boolean b = ((Boolean_Value) last).getValue(); lastValue = new Boolean_Value(!b); lastValue.copyGeneralProperties(this); break; default: setIsErroneous(true); break; } return lastValue; } @Override public void checkRecursions(final CompilationTimeStamp timestamp, final IReferenceChain referenceChain) { if (referenceChain.add(this) && value != null) { referenceChain.markState(); value.checkRecursions(timestamp, referenceChain); referenceChain.previousState(); } } @Override public void updateSyntax(final TTCN3ReparseUpdater reparser, final boolean isDamaged) throws ReParseException { if (isDamaged) { throw new ReParseException(); } if (value != null) { value.updateSyntax(reparser, false); reparser.updateLocation(value.getLocation()); } } @Override public void findReferences(final ReferenceFinder referenceFinder, final List<Hit> foundIdentifiers) { if (value == null) { return; } value.findReferences(referenceFinder, foundIdentifiers); } @Override protected boolean memberAccept(final ASTVisitor v) { if (value != null && !value.accept(v)) { return false; } return true; } }
eroslevi/titan.EclipsePlug-ins
org.eclipse.titan.designer/src/org/eclipse/titan/designer/AST/TTCN3/values/expressions/NotExpression.java
Java
epl-1.0
5,894
/******************************************************************************* * Copyright (c) 2008 Andrei Loskutov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the BSD License * which accompanies this distribution, and is available at * http://www.opensource.org/licenses/bsd-license.php * Contributor: Andrei Loskutov - initial API and implementation *******************************************************************************/ package de.loskutov.eclipseskins.sessions; import java.util.List; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.events.MenuAdapter; import org.eclipse.swt.events.MenuEvent; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowPulldownDelegate2; import org.eclipse.ui.PlatformUI; public class SaveSessionsPulldownMenu implements IWorkbenchWindowPulldownDelegate2 { private Menu menu; public SaveSessionsPulldownMenu() { super(); } public Menu getMenu(Control parent) { setMenu(new Menu(parent)); fillMenu(menu); initMenu(); return menu; } public Menu getMenu(Menu parent) { setMenu(new Menu(parent)); fillMenu(menu); initMenu(); return menu; } private void setMenu(Menu newMenu) { if (menu != null) { menu.dispose(); } menu = newMenu; } private void fillMenu(Menu menu2) { Sessions sessions = Sessions.getInstance(); List sessionsList = sessions.getSessions(false); addSessionToMenu(menu2, null); Separator sep = new Separator(); sep.fill(menu2, -1); EditingSession lastUsed = sessions.getSession(Sessions.RECENTLY_CLOSED); if (lastUsed != null) { sessionsList.remove(lastUsed); } for (int i = 0; i < sessionsList.size(); i++) { EditingSession session = (EditingSession) sessionsList.get(i); addSessionToMenu(menu2, session.getName()); } } private void addSessionToMenu(Menu menu2, String name) { Action action = new SaveSessionAction(name); ActionContributionItem item = new ActionContributionItem(action); item.fill(menu2, -1); } protected void initMenu() { menu.addMenuListener(new MenuAdapter() { public void menuShown(MenuEvent e) { Menu m = (Menu) e.widget; MenuItem[] items = m.getItems(); for (int i = 0; i < items.length; i++) { items[i].dispose(); } fillMenu(m); } }); } public void dispose() { if (menu != null) { menu.dispose(); } } public void init(IWorkbenchWindow window) { // } public void run(IAction action) { // } public void selectionChanged(IAction action, ISelection selection) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); action.setEnabled(window.getActivePage().getEditorReferences().length > 0); } }
iloveeclipse/skin4eclipse
EclipseSkins/src/de/loskutov/eclipseskins/sessions/SaveSessionsPulldownMenu.java
Java
epl-1.0
3,589
/** * Copyright (c) 2011 committers of YAKINDU 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: * committers of YAKINDU - initial API and implementation * */ package org.yakindu.sct.ui.editor.editparts; import org.eclipse.draw2d.IFigure; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.graphics.FontData; import org.yakindu.base.base.BasePackage; import org.yakindu.base.gmf.runtime.editparts.TextAwareLabelEditPart; import org.yakindu.sct.ui.editor.DiagramActivator; import org.yakindu.sct.ui.editor.preferences.StatechartPreferenceConstants; import org.yakindu.sct.ui.editor.utils.FontScalingUtil; /** * * @author andreas muelder - Initial contribution and API * */ public class StatechartNameEditPart extends TextAwareLabelEditPart implements IPropertyChangeListener { public StatechartNameEditPart(View view) { super(view, BasePackage.Literals.NAMED_ELEMENT__NAME, DiagramActivator.PLUGIN_ID); } public void setLabel(IFigure label) { setFigure(label); } @Override protected IFigure createFigure() { // Figure is set from parent addChild return null; } @Override protected void setFont(FontData fontData) { super.setFont(FontScalingUtil.scaleFont(fontData)); } @Override public void activate() { super.activate(); DiagramActivator.getDefault().getPreferenceStore().addPropertyChangeListener(this); } @Override public void deactivate() { super.deactivate(); DiagramActivator.getDefault().getPreferenceStore().removePropertyChangeListener(this); } @Override public void propertyChange(PropertyChangeEvent event) { if (StatechartPreferenceConstants.PREF_FONT_SCALING.equals(event.getProperty())) { refreshVisuals(); } } }
Yakindu/statecharts
plugins/org.yakindu.sct.ui.editor/src/org/yakindu/sct/ui/editor/editparts/StatechartNameEditPart.java
Java
epl-1.0
2,041
/******************************************************************************* * Copyright (c) 2002, 2010 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 * Jens Lukowski/Innoopract - initial renaming/restructuring * *******************************************************************************/ package org.eclipse.wst.xml.core.internal.catalog.provisional; /** * * <p> * This interface is not intended to be implemented by clients. * </p> * */ public interface ICatalogEntry extends ICatalogElement { /** The PUBLIC Catalog Entry type. */ public static final int ENTRY_TYPE_PUBLIC = 2; /** The SYSTEM Catalog Entry type. */ public static final int ENTRY_TYPE_SYSTEM = 3; /** The URI Catalog Entry type. */ public static final int ENTRY_TYPE_URI = 4; /** Attribute name for Web address of catalog entry */ public static final String ATTR_WEB_URL = "webURL"; //$NON-NLS-1$ /** * * @param entryType */ public void setEntryType(int entryType); /** * * @return */ public int getEntryType(); /** * * @param key */ public void setKey(String key); /** * * @return */ public String getKey(); /** * * @return */ public String getURI(); /** * * @param uri */ public void setURI(String uri); }
ttimbul/eclipse.wst
bundles/org.eclipse.wst.xml.core/src-catalog/org/eclipse/wst/xml/core/internal/catalog/provisional/ICatalogEntry.java
Java
epl-1.0
1,696
/******************************************************************************* * Copyright (c) 2010-2019 ITER Organization. * 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.csstudio.utility.batik.util; import org.apache.batik.anim.timing.TimedDocumentRoot; import org.apache.batik.bridge.DocumentLoader; import org.apache.batik.bridge.UserAgent; import org.apache.batik.script.InterpreterPool; /** * Extension of standard {@link org.apache.batik.bridge.BridgeContext} which uses the extended * {@link SVGAnimationEngine} in order to access {@link TimedDocumentRoot}. * * @author Fred Arnaud (Sopra Steria Group) - ITER */ public class BridgeContext extends org.apache.batik.bridge.BridgeContext { /** * By default we share a unique instance of InterpreterPool. */ private static InterpreterPool sharedPool = new InterpreterPool(); /** * Constructs a new bridge context. * * @param userAgent the user agent * @param loader document loader */ public BridgeContext(UserAgent userAgent, DocumentLoader loader) { super(userAgent, sharedPool, loader); } /** * Returns the AnimationEngine for the document. Creates one if it doesn't exist. */ public org.apache.batik.bridge.SVGAnimationEngine getAnimationEngine() { if (animationEngine == null) { animationEngine = new SVGAnimationEngine(document, this); setAnimationLimitingMode(); } return (org.apache.batik.bridge.SVGAnimationEngine) animationEngine; } }
css-iter/cs-studio
core/utility/utility-plugins/org.csstudio.utility.batik/src/org/csstudio/utility/batik/util/BridgeContext.java
Java
epl-1.0
1,838
/** * Copyright (c) 2013-2014 Angelo ZERR. * 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: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.wst.html.webresources.core; public enum WebResourceType { css, js, img; public static WebResourceType get(String value) { WebResourceType[] types = WebResourceType.values(); WebResourceType type; for (int i = 0; i < types.length; i++) { type = types[i]; if (type.name().equalsIgnoreCase(value)) { return type; } } return null; } }
angelozerr/eclipse-wtp-webresources
org.eclipse.a.wst.html.webresources.core/src/org/eclipse/wst/html/webresources/core/WebResourceType.java
Java
epl-1.0
805
<div> <form action="index.php?index=add_host_type" method="post"> <table> <tr> <td>Name</td> <td><input name="name" type="text" /></td> </tr> <tr> <td>Default CPU</td> <td><input name="default_cpu" type="text" /></td> </tr> <tr> <td>Default HDD</td> <td><input name="default_hdd" type="text" /></td> </tr> <tr> <td>Default Memory</td> <td><input name="default_memory" type="text" /></td> </tr> </table> <input type="submit" value="Create Host Type"> </form> </div>
FTSRG/decps
cps/hu.bme.mit.inf.cps.web/layout/host_form.php
PHP
epl-1.0
765
// The MIT License (MIT) // // Copyright (c) 2015, 2018 Arian Fornaris // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: The above copyright notice and this permission // notice shall be included in all copies or substantial portions of the // Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. package phasereditor.scene.core; import phasereditor.assetpack.core.AssetFinder; import phasereditor.assetpack.core.BitmapFontAssetModel; /** * @author arian * */ @SuppressWarnings("boxing") public interface BitmapTextComponent { // fontSize static String fontSize_name = "fontSize"; static int fontSize_default = 0; static int get_fontSize(ObjectModel obj) { return (int) obj.get("fontSize"); } static void set_fontSize(ObjectModel obj, int fontSize) { obj.put("fontSize", fontSize); } // align static final int ALIGN_LEFT = 0; static final int ALIGN_MIDDLE = 1; static final int ALIGN_RIGHT = 2; static String align_name = "align"; static int align_default = ALIGN_LEFT; static int get_align(ObjectModel obj) { return (int) obj.get("align"); } static void set_align(ObjectModel obj, int align) { obj.put("align", align); } // letterSpacing static String letterSpacing_name = "letterSpacing"; static float letterSpacing_default = 0; static float get_letterSpacing(ObjectModel obj) { return (float) obj.get("letterSpacing"); } static void set_letterSpacing(ObjectModel obj, float letterSpacing) { obj.put("letterSpacing", letterSpacing); } // fontAssetKey static String fontAssetKey_name = "fontAssetKey"; static String fontAssetKey_default = null; static String get_fontAssetKey(ObjectModel obj) { return (String) obj.get("fontAssetKey"); } static void set_fontAssetKey(ObjectModel obj, String fontAssetKey) { obj.put("fontAssetKey", fontAssetKey); } // utils static BitmapFontAssetModel utils_getFont(ObjectModel obj, AssetFinder finder) { var key = get_fontAssetKey(obj); var asset = finder.findAssetKey(key); if (asset instanceof BitmapFontAssetModel) { return (BitmapFontAssetModel) asset; } return null; } static void utils_setFont(ObjectModel obj, BitmapFontAssetModel fontAsset) { set_fontAssetKey(obj, fontAsset.getKey()); } static boolean is(Object model) { return model instanceof BitmapTextComponent; } static void init(BitmapTextModel obj) { set_fontAssetKey(obj, fontAssetKey_default); set_fontSize(obj, fontSize_default); set_align(obj, align_default); set_letterSpacing(obj, letterSpacing_default); } }
boniatillo-com/PhaserEditor
source/v2/phasereditor/phasereditor.scene.core/src/phasereditor/scene/core/BitmapTextComponent.java
Java
epl-1.0
3,382
package ch.elexis.core.ui.eigenartikel; import java.text.MessageFormat; import javax.inject.Inject; import javax.inject.Named; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.ui.di.UIEventTopic; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.ui.IViewSite; import ch.elexis.core.common.ElexisEventTopics; import ch.elexis.core.data.service.ContextServiceHolder; import ch.elexis.core.data.service.CoreModelServiceHolder; import ch.elexis.core.data.service.LocalLockServiceHolder; import ch.elexis.core.lock.types.LockResponse; import ch.elexis.core.model.IArticle; import ch.elexis.core.services.IElexisServerService.ConnectionStatus; import ch.elexis.core.services.holder.ElexisServerServiceHolder; import ch.elexis.core.types.ArticleTyp; import ch.elexis.core.ui.actions.RestrictedAction; import ch.elexis.core.ui.eigenartikel.acl.ACLContributor; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.locks.LockRequestingRestrictedAction; import ch.elexis.core.ui.locks.LockResponseHelper; import ch.elexis.core.ui.views.IDetailDisplay; public class EigenartikelDetailDisplay implements IDetailDisplay { private IViewSite site; private EigenartikelProductComposite epc; private EigenartikelComposite ec; private IArticle selectedObject; private IArticle currentLock; private StackLayout layout; private Composite container; private Composite compProduct; private Composite compArticle; private RestrictedAction createAction = new RestrictedAction(ACLContributor.EIGENARTIKEL_MODIFY, ch.elexis.core.ui.views.artikel.Messages.ArtikelContextMenu_newAction) { { setImageDescriptor(Images.IMG_NEW.getImageDescriptor()); setToolTipText( ch.elexis.core.ui.views.artikel.Messages.ArtikelContextMenu_createProductToolTipText); } @Override public void doRun(){ IArticle ea = CoreModelServiceHolder.get().create(IArticle.class); ea.setTyp(ArticleTyp.EIGENARTIKEL); ea.setName("Neues Produkt"); CoreModelServiceHolder.get().save(ea); ContextServiceHolder.get().postEvent(ElexisEventTopics.EVENT_RELOAD, IArticle.class); selection(ea); } }; private RestrictedAction toggleLockAction = new RestrictedAction(ACLContributor.EIGENARTIKEL_MODIFY, "lock", SWT.TOGGLE) { { setImageDescriptor(Images.IMG_LOCK_CLOSED.getImageDescriptor()); } @Override public void setChecked(boolean checked){ if (checked) { setImageDescriptor(Images.IMG_LOCK_OPEN.getImageDescriptor()); } else { setImageDescriptor(Images.IMG_LOCK_CLOSED.getImageDescriptor()); } super.setChecked(checked); } @Override public void doRun(){ if (selectedObject != null) { if (LocalLockServiceHolder.get().isLocked(selectedObject)) { LocalLockServiceHolder.get().releaseLock(selectedObject); ContextServiceHolder.get().postEvent(ElexisEventTopics.EVENT_RELOAD, IArticle.class); currentLock = null; } else { LockResponse lr = LocalLockServiceHolder.get().acquireLock(selectedObject); if (lr.isOk()) { currentLock = selectedObject; } else { LockResponseHelper.showInfo(lr, selectedObject, null); } } } setChecked(LocalLockServiceHolder.get().isLocked(currentLock)); } }; private RestrictedAction deleteAction = new LockRequestingRestrictedAction<IArticle>(ACLContributor.EIGENARTIKEL_MODIFY, ch.elexis.core.ui.views.artikel.Messages.ArtikelContextMenu_deleteAction) { { setImageDescriptor(Images.IMG_DELETE.getImageDescriptor()); setToolTipText( ch.elexis.core.ui.views.artikel.Messages.ArtikelContextMenu_deleteProductToolTipText); } @Override public IArticle getTargetedObject(){ java.util.Optional<?> selected = ContextServiceHolder.get().getRootContext() .getNamed("ch.elexis.core.ui.eigenartikel.selection"); return (IArticle) selected.orElse(null); } @Override public void doRun(IArticle act){ if (MessageDialog.openConfirm(site.getShell(), ch.elexis.core.ui.views.artikel.Messages.ArtikelContextMenu_deleteActionConfirmCaption, MessageFormat.format( ch.elexis.core.ui.views.artikel.Messages.ArtikelContextMenu_deleteConfirmBody, act.getName()))) { CoreModelServiceHolder.get().delete(act); if (epc != null) { epc.setProductEigenartikel(null); } } ContextServiceHolder.get().postEvent(ElexisEventTopics.EVENT_RELOAD, IArticle.class); } }; @Inject @Optional public void lockAquired( @UIEventTopic(ElexisEventTopics.EVENT_LOCK_AQUIRED) IArticle typedArticle){ if (epc != null && !epc.isDisposed() && typedArticle.getId().equals(selectedObject.getId())) { epc.setUnlocked(true); } } @Inject @Optional public void lockReleased( @UIEventTopic(ElexisEventTopics.EVENT_LOCK_RELEASED) IArticle typedArticle){ if (epc != null && !epc.isDisposed() && typedArticle.getId().equals(selectedObject.getId())) { epc.setUnlocked(false); } } @Inject public void selection( @Optional @Named("ch.elexis.core.ui.eigenartikel.selection") IArticle typedArticle){ if (epc != null && !epc.isDisposed()) { display(typedArticle); } } /** * @wbp.parser.entryPoint */ @Override public Composite createDisplay(Composite parent, IViewSite site){ this.site = site; container = new Composite(parent, SWT.NONE); // parent.setLayoutData(new GridData(GridData.FILL_BOTH)); layout = new StackLayout(); container.setLayout(layout); compProduct = new Composite(container, SWT.None); compProduct.setLayout(new GridLayout(1, false)); ToolBar toolBar = new ToolBar(compProduct, SWT.BORDER | SWT.FLAT | SWT.RIGHT); toolBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); final ToolBarManager manager = new ToolBarManager(toolBar); manager.add(createAction); if (ElexisServerServiceHolder.get().getConnectionStatus() != ConnectionStatus.STANDALONE) { manager.add(toggleLockAction); } manager.add(deleteAction); manager.update(true); toolBar.pack(); epc = new EigenartikelProductComposite(compProduct, SWT.None); epc.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); epc.setUnlocked(ElexisServerServiceHolder.get().getConnectionStatus() == ConnectionStatus.STANDALONE); compArticle = new Composite(container, SWT.None); compArticle.setLayout(new GridLayout(1, false)); ec = new EigenartikelComposite(compArticle, SWT.None, false, null); ec.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); ec.setUnlocked(ElexisServerServiceHolder.get().getConnectionStatus() == ConnectionStatus.STANDALONE); layout.topControl = compProduct; container.layout(); return container; } @Override public Class<?> getElementClass(){ return IArticle.class; } @Override public void display(Object obj){ toggleLockAction.reflectRight(); createAction.reflectRight(); deleteAction.reflectRight(); if (obj instanceof IArticle) { selectedObject = (IArticle) obj; if (currentLock != null) { LocalLockServiceHolder.get().releaseLock(currentLock); toggleLockAction.setChecked(false); currentLock = null; } IArticle article = (IArticle) obj; toggleLockAction.setEnabled(article.isProduct()); if(article.isProduct()) { layout.topControl = compProduct; epc.setProductEigenartikel(article); } else { layout.topControl = compArticle; ec.setEigenartikel(article); } } else { selectedObject = null; toggleLockAction.setEnabled(false); epc.setProductEigenartikel(null); ec.setEigenartikel(null); layout.topControl = compProduct; } container.layout(); } @Override public String getTitle(){ return Messages.EigenartikelDisplay_displayTitle; } }
elexis/elexis-3-core
bundles/ch.elexis.core.ui.eigenartikel/src/ch/elexis/core/ui/eigenartikel/EigenartikelDetailDisplay.java
Java
epl-1.0
8,128
package InheritanceChapter; public class InheritanceDemo { public static void main(String[] args) { Person[] people = new Person[4]; people[0] = new Undergraduate("Cot, Man", 49, 2); people[1] = new Undergraduate("Lick, ani", 9456, 1); people[2] = new Student("raj, swap",3); people[3] = new Undergraduate("jan, mah", 4367, 4); for (Person p : people) { p.writeOutput(); System.out.println(); } //Student s = new Student(); //s.setName("Warren Peace"); //s.setStudentNumber(1234); //s.writeOutput(); } }
ShubhankarRaj/JavaCodingFolder
Eclipse Workspace/myProject/src/InheritanceChapter/InheritanceDemo.java
Java
epl-1.0
515
/** */ package org.example.entities.entities.util; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; import org.example.entities.entities.*; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see org.example.entities.entities.EntitiesPackage * @generated */ public class EntitiesAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static EntitiesPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EntitiesAdapterFactory() { if (modelPackage == null) { modelPackage = EntitiesPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EntitiesSwitch<Adapter> modelSwitch = new EntitiesSwitch<Adapter>() { @Override public Adapter caseModel(Model object) { return createModelAdapter(); } @Override public Adapter caseEntity(Entity object) { return createEntityAdapter(); } @Override public Adapter caseAttribute(Attribute object) { return createAttributeAdapter(); } @Override public Adapter caseAttributeType(AttributeType object) { return createAttributeTypeAdapter(); } @Override public Adapter caseElementType(ElementType object) { return createElementTypeAdapter(); } @Override public Adapter caseBasicType(BasicType object) { return createBasicTypeAdapter(); } @Override public Adapter caseEntityType(EntityType object) { return createEntityTypeAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link org.example.entities.entities.Model <em>Model</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.example.entities.entities.Model * @generated */ public Adapter createModelAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.example.entities.entities.Entity <em>Entity</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.example.entities.entities.Entity * @generated */ public Adapter createEntityAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.example.entities.entities.Attribute <em>Attribute</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.example.entities.entities.Attribute * @generated */ public Adapter createAttributeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.example.entities.entities.AttributeType <em>Attribute Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.example.entities.entities.AttributeType * @generated */ public Adapter createAttributeTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.example.entities.entities.ElementType <em>Element Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.example.entities.entities.ElementType * @generated */ public Adapter createElementTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.example.entities.entities.BasicType <em>Basic Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.example.entities.entities.BasicType * @generated */ public Adapter createBasicTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.example.entities.entities.EntityType <em>Entity Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.example.entities.entities.EntityType * @generated */ public Adapter createEntityTypeAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //EntitiesAdapterFactory
LorenzoBettini/packtpub-xtext-book-examples
org.example.entities/src-gen/org/example/entities/entities/util/EntitiesAdapterFactory.java
Java
epl-1.0
7,221
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _lib = require('../../lib'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function CommentMetadata(props) { var className = props.className, children = props.children; var classes = (0, _classnames2.default)('metadata', className); var rest = (0, _lib.getUnhandledProps)(CommentMetadata, props); var ElementType = (0, _lib.getElementType)(CommentMetadata, props); return _react2.default.createElement( ElementType, (0, _extends3.default)({}, rest, { className: classes }), children ); } CommentMetadata.handledProps = ['as', 'children', 'className']; CommentMetadata._meta = { name: 'CommentMetadata', parent: 'Comment', type: _lib.META.TYPES.VIEW }; process.env.NODE_ENV !== "production" ? CommentMetadata.propTypes = { /** An element type to render as (string or function). */ as: _lib.customPropTypes.as, /** Primary content. */ children: _react.PropTypes.node, /** Additional classes. */ className: _react.PropTypes.string } : void 0; exports.default = CommentMetadata;
jessicaappelbaum/cljs-update
node_modules/semantic-ui-react/dist/commonjs/views/Comment/CommentMetadata.js
JavaScript
epl-1.0
1,455
// Compiled by ClojureScript 0.0-3165 {} goog.provide('om.core'); goog.require('cljs.core'); goog.require('goog.ui.IdGenerator'); goog.require('goog.dom'); goog.require('om.dom'); goog.require('cljsjs.react'); om.core._STAR_parent_STAR_ = null; om.core._STAR_instrument_STAR_ = null; om.core._STAR_descriptor_STAR_ = null; om.core._STAR_state_STAR_ = null; om.core._STAR_root_key_STAR_ = null; om.core.IDisplayName = (function (){var obj20070 = {}; return obj20070; })(); om.core.display_name = (function om$core$display_name(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IDisplayName$display_name$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IDisplayName$display_name$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.display_name[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.display_name["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IDisplayName.display-name",this$); } } })().call(null,this$); } }); om.core.IInitState = (function (){var obj20072 = {}; return obj20072; })(); om.core.init_state = (function om$core$init_state(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IInitState$init_state$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IInitState$init_state$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.init_state[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.init_state["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IInitState.init-state",this$); } } })().call(null,this$); } }); om.core.IShouldUpdate = (function (){var obj20074 = {}; return obj20074; })(); om.core.should_update = (function om$core$should_update(this$,next_props,next_state){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IShouldUpdate$should_update$arity$3; } else { return and__17844__auto__; } })()){ return this$.om$core$IShouldUpdate$should_update$arity$3(this$,next_props,next_state); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.should_update[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.should_update["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IShouldUpdate.should-update",this$); } } })().call(null,this$,next_props,next_state); } }); om.core.IWillMount = (function (){var obj20076 = {}; return obj20076; })(); om.core.will_mount = (function om$core$will_mount(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IWillMount$will_mount$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IWillMount$will_mount$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.will_mount[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.will_mount["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IWillMount.will-mount",this$); } } })().call(null,this$); } }); om.core.IDidMount = (function (){var obj20078 = {}; return obj20078; })(); om.core.did_mount = (function om$core$did_mount(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IDidMount$did_mount$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IDidMount$did_mount$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.did_mount[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.did_mount["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IDidMount.did-mount",this$); } } })().call(null,this$); } }); om.core.IWillUnmount = (function (){var obj20080 = {}; return obj20080; })(); om.core.will_unmount = (function om$core$will_unmount(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IWillUnmount$will_unmount$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IWillUnmount$will_unmount$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.will_unmount[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.will_unmount["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IWillUnmount.will-unmount",this$); } } })().call(null,this$); } }); om.core.IWillUpdate = (function (){var obj20082 = {}; return obj20082; })(); om.core.will_update = (function om$core$will_update(this$,next_props,next_state){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IWillUpdate$will_update$arity$3; } else { return and__17844__auto__; } })()){ return this$.om$core$IWillUpdate$will_update$arity$3(this$,next_props,next_state); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.will_update[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.will_update["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IWillUpdate.will-update",this$); } } })().call(null,this$,next_props,next_state); } }); om.core.IDidUpdate = (function (){var obj20084 = {}; return obj20084; })(); om.core.did_update = (function om$core$did_update(this$,prev_props,prev_state){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IDidUpdate$did_update$arity$3; } else { return and__17844__auto__; } })()){ return this$.om$core$IDidUpdate$did_update$arity$3(this$,prev_props,prev_state); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.did_update[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.did_update["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IDidUpdate.did-update",this$); } } })().call(null,this$,prev_props,prev_state); } }); om.core.IWillReceiveProps = (function (){var obj20086 = {}; return obj20086; })(); om.core.will_receive_props = (function om$core$will_receive_props(this$,next_props){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IWillReceiveProps$will_receive_props$arity$2; } else { return and__17844__auto__; } })()){ return this$.om$core$IWillReceiveProps$will_receive_props$arity$2(this$,next_props); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.will_receive_props[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.will_receive_props["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IWillReceiveProps.will-receive-props",this$); } } })().call(null,this$,next_props); } }); om.core.IRender = (function (){var obj20088 = {}; return obj20088; })(); om.core.render = (function om$core$render(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IRender$render$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IRender$render$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.render[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.render["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRender.render",this$); } } })().call(null,this$); } }); om.core.IRenderProps = (function (){var obj20090 = {}; return obj20090; })(); om.core.render_props = (function om$core$render_props(this$,props,state){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IRenderProps$render_props$arity$3; } else { return and__17844__auto__; } })()){ return this$.om$core$IRenderProps$render_props$arity$3(this$,props,state); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.render_props[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.render_props["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRenderProps.render-props",this$); } } })().call(null,this$,props,state); } }); om.core.IRenderState = (function (){var obj20092 = {}; return obj20092; })(); om.core.render_state = (function om$core$render_state(this$,state){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IRenderState$render_state$arity$2; } else { return and__17844__auto__; } })()){ return this$.om$core$IRenderState$render_state$arity$2(this$,state); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core.render_state[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core.render_state["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRenderState.render-state",this$); } } })().call(null,this$,state); } }); om.core.ICheckState = (function (){var obj20094 = {}; return obj20094; })(); om.core.IOmSwap = (function (){var obj20096 = {}; return obj20096; })(); om.core._om_swap_BANG_ = (function om$core$_om_swap_BANG_(this$,cursor,korks,f,tag){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IOmSwap$_om_swap_BANG_$arity$5; } else { return and__17844__auto__; } })()){ return this$.om$core$IOmSwap$_om_swap_BANG_$arity$5(this$,cursor,korks,f,tag); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._om_swap_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._om_swap_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IOmSwap.-om-swap!",this$); } } })().call(null,this$,cursor,korks,f,tag); } }); om.core.IGetState = (function (){var obj20098 = {}; return obj20098; })(); om.core._get_state = (function() { var om$core$_get_state = null; var om$core$_get_state__1 = (function (this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IGetState$_get_state$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IGetState$_get_state$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._get_state[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._get_state["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IGetState.-get-state",this$); } } })().call(null,this$); } }); var om$core$_get_state__2 = (function (this$,ks){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IGetState$_get_state$arity$2; } else { return and__17844__auto__; } })()){ return this$.om$core$IGetState$_get_state$arity$2(this$,ks); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._get_state[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._get_state["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IGetState.-get-state",this$); } } })().call(null,this$,ks); } }); om$core$_get_state = function(this$,ks){ switch(arguments.length){ case 1: return om$core$_get_state__1.call(this,this$); case 2: return om$core$_get_state__2.call(this,this$,ks); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$_get_state.cljs$core$IFn$_invoke$arity$1 = om$core$_get_state__1; om$core$_get_state.cljs$core$IFn$_invoke$arity$2 = om$core$_get_state__2; return om$core$_get_state; })() ; om.core.IGetRenderState = (function (){var obj20100 = {}; return obj20100; })(); om.core._get_render_state = (function() { var om$core$_get_render_state = null; var om$core$_get_render_state__1 = (function (this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IGetRenderState$_get_render_state$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IGetRenderState$_get_render_state$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._get_render_state[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._get_render_state["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IGetRenderState.-get-render-state",this$); } } })().call(null,this$); } }); var om$core$_get_render_state__2 = (function (this$,ks){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IGetRenderState$_get_render_state$arity$2; } else { return and__17844__auto__; } })()){ return this$.om$core$IGetRenderState$_get_render_state$arity$2(this$,ks); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._get_render_state[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._get_render_state["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IGetRenderState.-get-render-state",this$); } } })().call(null,this$,ks); } }); om$core$_get_render_state = function(this$,ks){ switch(arguments.length){ case 1: return om$core$_get_render_state__1.call(this,this$); case 2: return om$core$_get_render_state__2.call(this,this$,ks); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$_get_render_state.cljs$core$IFn$_invoke$arity$1 = om$core$_get_render_state__1; om$core$_get_render_state.cljs$core$IFn$_invoke$arity$2 = om$core$_get_render_state__2; return om$core$_get_render_state; })() ; om.core.ISetState = (function (){var obj20102 = {}; return obj20102; })(); om.core._set_state_BANG_ = (function() { var om$core$_set_state_BANG_ = null; var om$core$_set_state_BANG___3 = (function (this$,val,render){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$ISetState$_set_state_BANG_$arity$3; } else { return and__17844__auto__; } })()){ return this$.om$core$ISetState$_set_state_BANG_$arity$3(this$,val,render); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._set_state_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._set_state_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"ISetState.-set-state!",this$); } } })().call(null,this$,val,render); } }); var om$core$_set_state_BANG___4 = (function (this$,ks,val,render){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$ISetState$_set_state_BANG_$arity$4; } else { return and__17844__auto__; } })()){ return this$.om$core$ISetState$_set_state_BANG_$arity$4(this$,ks,val,render); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._set_state_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._set_state_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"ISetState.-set-state!",this$); } } })().call(null,this$,ks,val,render); } }); om$core$_set_state_BANG_ = function(this$,ks,val,render){ switch(arguments.length){ case 3: return om$core$_set_state_BANG___3.call(this,this$,ks,val); case 4: return om$core$_set_state_BANG___4.call(this,this$,ks,val,render); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$_set_state_BANG_.cljs$core$IFn$_invoke$arity$3 = om$core$_set_state_BANG___3; om$core$_set_state_BANG_.cljs$core$IFn$_invoke$arity$4 = om$core$_set_state_BANG___4; return om$core$_set_state_BANG_; })() ; om.core.IRenderQueue = (function (){var obj20104 = {}; return obj20104; })(); om.core._get_queue = (function om$core$_get_queue(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IRenderQueue$_get_queue$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IRenderQueue$_get_queue$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._get_queue[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._get_queue["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRenderQueue.-get-queue",this$); } } })().call(null,this$); } }); om.core._queue_render_BANG_ = (function om$core$_queue_render_BANG_(this$,c){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IRenderQueue$_queue_render_BANG_$arity$2; } else { return and__17844__auto__; } })()){ return this$.om$core$IRenderQueue$_queue_render_BANG_$arity$2(this$,c); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._queue_render_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._queue_render_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRenderQueue.-queue-render!",this$); } } })().call(null,this$,c); } }); om.core._empty_queue_BANG_ = (function om$core$_empty_queue_BANG_(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IRenderQueue$_empty_queue_BANG_$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IRenderQueue$_empty_queue_BANG_$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._empty_queue_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._empty_queue_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRenderQueue.-empty-queue!",this$); } } })().call(null,this$); } }); om.core.IValue = (function (){var obj20106 = {}; return obj20106; })(); om.core._value = (function om$core$_value(x){ if((function (){var and__17844__auto__ = x; if(and__17844__auto__){ return x.om$core$IValue$_value$arity$1; } else { return and__17844__auto__; } })()){ return x.om$core$IValue$_value$arity$1(x); } else { var x__18492__auto__ = (((x == null))?null:x); return (function (){var or__17856__auto__ = (om.core._value[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._value["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IValue.-value",x); } } })().call(null,x); } }); (om.core.IValue["_"] = true); (om.core._value["_"] = (function (x){ return x; })); om.core.ICursor = (function (){var obj20108 = {}; return obj20108; })(); om.core._path = (function om$core$_path(cursor){ if((function (){var and__17844__auto__ = cursor; if(and__17844__auto__){ return cursor.om$core$ICursor$_path$arity$1; } else { return and__17844__auto__; } })()){ return cursor.om$core$ICursor$_path$arity$1(cursor); } else { var x__18492__auto__ = (((cursor == null))?null:cursor); return (function (){var or__17856__auto__ = (om.core._path[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._path["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"ICursor.-path",cursor); } } })().call(null,cursor); } }); om.core._state = (function om$core$_state(cursor){ if((function (){var and__17844__auto__ = cursor; if(and__17844__auto__){ return cursor.om$core$ICursor$_state$arity$1; } else { return and__17844__auto__; } })()){ return cursor.om$core$ICursor$_state$arity$1(cursor); } else { var x__18492__auto__ = (((cursor == null))?null:cursor); return (function (){var or__17856__auto__ = (om.core._state[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._state["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"ICursor.-state",cursor); } } })().call(null,cursor); } }); om.core.IToCursor = (function (){var obj20110 = {}; return obj20110; })(); om.core._to_cursor = (function() { var om$core$_to_cursor = null; var om$core$_to_cursor__2 = (function (value,state){ if((function (){var and__17844__auto__ = value; if(and__17844__auto__){ return value.om$core$IToCursor$_to_cursor$arity$2; } else { return and__17844__auto__; } })()){ return value.om$core$IToCursor$_to_cursor$arity$2(value,state); } else { var x__18492__auto__ = (((value == null))?null:value); return (function (){var or__17856__auto__ = (om.core._to_cursor[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._to_cursor["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IToCursor.-to-cursor",value); } } })().call(null,value,state); } }); var om$core$_to_cursor__3 = (function (value,state,path){ if((function (){var and__17844__auto__ = value; if(and__17844__auto__){ return value.om$core$IToCursor$_to_cursor$arity$3; } else { return and__17844__auto__; } })()){ return value.om$core$IToCursor$_to_cursor$arity$3(value,state,path); } else { var x__18492__auto__ = (((value == null))?null:value); return (function (){var or__17856__auto__ = (om.core._to_cursor[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._to_cursor["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IToCursor.-to-cursor",value); } } })().call(null,value,state,path); } }); om$core$_to_cursor = function(value,state,path){ switch(arguments.length){ case 2: return om$core$_to_cursor__2.call(this,value,state); case 3: return om$core$_to_cursor__3.call(this,value,state,path); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$_to_cursor.cljs$core$IFn$_invoke$arity$2 = om$core$_to_cursor__2; om$core$_to_cursor.cljs$core$IFn$_invoke$arity$3 = om$core$_to_cursor__3; return om$core$_to_cursor; })() ; om.core.ICursorDerive = (function (){var obj20112 = {}; return obj20112; })(); om.core._derive = (function om$core$_derive(cursor,derived,state,path){ if((function (){var and__17844__auto__ = cursor; if(and__17844__auto__){ return cursor.om$core$ICursorDerive$_derive$arity$4; } else { return and__17844__auto__; } })()){ return cursor.om$core$ICursorDerive$_derive$arity$4(cursor,derived,state,path); } else { var x__18492__auto__ = (((cursor == null))?null:cursor); return (function (){var or__17856__auto__ = (om.core._derive[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._derive["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"ICursorDerive.-derive",cursor); } } })().call(null,cursor,derived,state,path); } }); (om.core.ICursorDerive["_"] = true); (om.core._derive["_"] = (function (this$,derived,state,path){ return om.core.to_cursor.call(null,derived,state,path); })); om.core.path = (function om$core$path(cursor){ return om.core._path.call(null,cursor); }); om.core.value = (function om$core$value(cursor){ return om.core._value.call(null,cursor); }); om.core.state = (function om$core$state(cursor){ return om.core._state.call(null,cursor); }); om.core.ITransact = (function (){var obj20114 = {}; return obj20114; })(); om.core._transact_BANG_ = (function om$core$_transact_BANG_(cursor,korks,f,tag){ if((function (){var and__17844__auto__ = cursor; if(and__17844__auto__){ return cursor.om$core$ITransact$_transact_BANG_$arity$4; } else { return and__17844__auto__; } })()){ return cursor.om$core$ITransact$_transact_BANG_$arity$4(cursor,korks,f,tag); } else { var x__18492__auto__ = (((cursor == null))?null:cursor); return (function (){var or__17856__auto__ = (om.core._transact_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._transact_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"ITransact.-transact!",cursor); } } })().call(null,cursor,korks,f,tag); } }); om.core.INotify = (function (){var obj20116 = {}; return obj20116; })(); om.core._listen_BANG_ = (function om$core$_listen_BANG_(x,key,tx_listen){ if((function (){var and__17844__auto__ = x; if(and__17844__auto__){ return x.om$core$INotify$_listen_BANG_$arity$3; } else { return and__17844__auto__; } })()){ return x.om$core$INotify$_listen_BANG_$arity$3(x,key,tx_listen); } else { var x__18492__auto__ = (((x == null))?null:x); return (function (){var or__17856__auto__ = (om.core._listen_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._listen_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"INotify.-listen!",x); } } })().call(null,x,key,tx_listen); } }); om.core._unlisten_BANG_ = (function om$core$_unlisten_BANG_(x,key){ if((function (){var and__17844__auto__ = x; if(and__17844__auto__){ return x.om$core$INotify$_unlisten_BANG_$arity$2; } else { return and__17844__auto__; } })()){ return x.om$core$INotify$_unlisten_BANG_$arity$2(x,key); } else { var x__18492__auto__ = (((x == null))?null:x); return (function (){var or__17856__auto__ = (om.core._unlisten_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._unlisten_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"INotify.-unlisten!",x); } } })().call(null,x,key); } }); om.core._notify_BANG_ = (function om$core$_notify_BANG_(x,tx_data,root_cursor){ if((function (){var and__17844__auto__ = x; if(and__17844__auto__){ return x.om$core$INotify$_notify_BANG_$arity$3; } else { return and__17844__auto__; } })()){ return x.om$core$INotify$_notify_BANG_$arity$3(x,tx_data,root_cursor); } else { var x__18492__auto__ = (((x == null))?null:x); return (function (){var or__17856__auto__ = (om.core._notify_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._notify_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"INotify.-notify!",x); } } })().call(null,x,tx_data,root_cursor); } }); om.core.IRootProperties = (function (){var obj20118 = {}; return obj20118; })(); om.core._set_property_BANG_ = (function om$core$_set_property_BANG_(this$,id,p,val){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IRootProperties$_set_property_BANG_$arity$4; } else { return and__17844__auto__; } })()){ return this$.om$core$IRootProperties$_set_property_BANG_$arity$4(this$,id,p,val); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._set_property_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._set_property_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRootProperties.-set-property!",this$); } } })().call(null,this$,id,p,val); } }); om.core._remove_property_BANG_ = (function om$core$_remove_property_BANG_(this$,id,p){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IRootProperties$_remove_property_BANG_$arity$3; } else { return and__17844__auto__; } })()){ return this$.om$core$IRootProperties$_remove_property_BANG_$arity$3(this$,id,p); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._remove_property_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._remove_property_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRootProperties.-remove-property!",this$); } } })().call(null,this$,id,p); } }); om.core._remove_properties_BANG_ = (function om$core$_remove_properties_BANG_(this$,id){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IRootProperties$_remove_properties_BANG_$arity$2; } else { return and__17844__auto__; } })()){ return this$.om$core$IRootProperties$_remove_properties_BANG_$arity$2(this$,id); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._remove_properties_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._remove_properties_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRootProperties.-remove-properties!",this$); } } })().call(null,this$,id); } }); om.core._get_property = (function om$core$_get_property(this$,id,p){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IRootProperties$_get_property$arity$3; } else { return and__17844__auto__; } })()){ return this$.om$core$IRootProperties$_get_property$arity$3(this$,id,p); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._get_property[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._get_property["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRootProperties.-get-property",this$); } } })().call(null,this$,id,p); } }); om.core.IRootKey = (function (){var obj20120 = {}; return obj20120; })(); om.core._root_key = (function om$core$_root_key(cursor){ if((function (){var and__17844__auto__ = cursor; if(and__17844__auto__){ return cursor.om$core$IRootKey$_root_key$arity$1; } else { return and__17844__auto__; } })()){ return cursor.om$core$IRootKey$_root_key$arity$1(cursor); } else { var x__18492__auto__ = (((cursor == null))?null:cursor); return (function (){var or__17856__auto__ = (om.core._root_key[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._root_key["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IRootKey.-root-key",cursor); } } })().call(null,cursor); } }); om.core.IAdapt = (function (){var obj20122 = {}; return obj20122; })(); om.core._adapt = (function om$core$_adapt(this$,other){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IAdapt$_adapt$arity$2; } else { return and__17844__auto__; } })()){ return this$.om$core$IAdapt$_adapt$arity$2(this$,other); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._adapt[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._adapt["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IAdapt.-adapt",this$); } } })().call(null,this$,other); } }); (om.core.IAdapt["_"] = true); (om.core._adapt["_"] = (function (_,other){ return other; })); om.core.adapt = (function om$core$adapt(x,other){ return om.core._adapt.call(null,x,other); }); om.core.IOmRef = (function (){var obj20124 = {}; return obj20124; })(); om.core._add_dep_BANG_ = (function om$core$_add_dep_BANG_(this$,c){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IOmRef$_add_dep_BANG_$arity$2; } else { return and__17844__auto__; } })()){ return this$.om$core$IOmRef$_add_dep_BANG_$arity$2(this$,c); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._add_dep_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._add_dep_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IOmRef.-add-dep!",this$); } } })().call(null,this$,c); } }); om.core._remove_dep_BANG_ = (function om$core$_remove_dep_BANG_(this$,c){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IOmRef$_remove_dep_BANG_$arity$2; } else { return and__17844__auto__; } })()){ return this$.om$core$IOmRef$_remove_dep_BANG_$arity$2(this$,c); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._remove_dep_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._remove_dep_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IOmRef.-remove-dep!",this$); } } })().call(null,this$,c); } }); om.core._refresh_deps_BANG_ = (function om$core$_refresh_deps_BANG_(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IOmRef$_refresh_deps_BANG_$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IOmRef$_refresh_deps_BANG_$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._refresh_deps_BANG_[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._refresh_deps_BANG_["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IOmRef.-refresh-deps!",this$); } } })().call(null,this$); } }); om.core._get_deps = (function om$core$_get_deps(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.om$core$IOmRef$_get_deps$arity$1; } else { return and__17844__auto__; } })()){ return this$.om$core$IOmRef$_get_deps$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (om.core._get_deps[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (om.core._get_deps["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"IOmRef.-get-deps",this$); } } })().call(null,this$); } }); om.core.transact_STAR_ = (function om$core$transact_STAR_(state,cursor,korks,f,tag){ var old_state = cljs.core.deref.call(null,state); var path = cljs.core.into.call(null,om.core.path.call(null,cursor),korks); var ret = (((function (){var G__20126 = state; if(G__20126){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20126.om$core$IOmSwap$; } })())){ return true; } else { if((!G__20126.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IOmSwap,G__20126); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IOmSwap,G__20126); } })())?om.core._om_swap_BANG_.call(null,state,cursor,korks,f,tag):((cljs.core.empty_QMARK_.call(null,path))?cljs.core.swap_BANG_.call(null,state,f):cljs.core.swap_BANG_.call(null,state,cljs.core.update_in,path,f) )); if(cljs.core._EQ_.call(null,ret,new cljs.core.Keyword("om.core","defer","om.core/defer",-1038866178))){ return null; } else { var tx_data = new cljs.core.PersistentArrayMap(null, 5, [new cljs.core.Keyword(null,"path","path",-188191168),path,new cljs.core.Keyword(null,"old-value","old-value",862546795),cljs.core.get_in.call(null,old_state,path),new cljs.core.Keyword(null,"new-value","new-value",1087038368),cljs.core.get_in.call(null,cljs.core.deref.call(null,state),path),new cljs.core.Keyword(null,"old-state","old-state",1039580704),old_state,new cljs.core.Keyword(null,"new-state","new-state",-490349212),cljs.core.deref.call(null,state)], null); if(!((tag == null))){ return om.core.notify_STAR_.call(null,cursor,cljs.core.assoc.call(null,tx_data,new cljs.core.Keyword(null,"tag","tag",-1290361223),tag)); } else { return om.core.notify_STAR_.call(null,cursor,tx_data); } } }); om.core.cursor_QMARK_ = (function om$core$cursor_QMARK_(x){ var G__20128 = x; if(G__20128){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20128.om$core$ICursor$; } })())){ return true; } else { if((!G__20128.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.ICursor,G__20128); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.ICursor,G__20128); } }); om.core.component_QMARK_ = (function om$core$component_QMARK_(x){ return (x["isOmComponent"]); }); om.core.children = (function om$core$children(node){ var c = node.props.children; if(cljs.core.ifn_QMARK_.call(null,c)){ return node.props.children = c.call(null,node); } else { return c; } }); /** * Given an owning Pure node return the Om props. Analogous to React * component props. */ om.core.get_props = (function() { var om$core$get_props = null; var om$core$get_props__1 = (function (x){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,x))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"x","x",-555367584,null))))].join(''))); } return (x.props["__om_cursor"]); }); var om$core$get_props__2 = (function (x,korks){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,x))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"x","x",-555367584,null))))].join(''))); } var korks__$1 = ((cljs.core.sequential_QMARK_.call(null,korks))?korks:new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [korks], null)); var G__20130 = (x.props["__om_cursor"]); var G__20130__$1 = ((cljs.core.seq.call(null,korks__$1))?cljs.core.get_in.call(null,G__20130,korks__$1):G__20130); return G__20130__$1; }); om$core$get_props = function(x,korks){ switch(arguments.length){ case 1: return om$core$get_props__1.call(this,x); case 2: return om$core$get_props__2.call(this,x,korks); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$get_props.cljs$core$IFn$_invoke$arity$1 = om$core$get_props__1; om$core$get_props.cljs$core$IFn$_invoke$arity$2 = om$core$get_props__2; return om$core$get_props; })() ; /** * Returns the component local state of an owning component. owner is * the component. An optional key or sequence of keys may be given to * extract a specific value. Always returns pending state. */ om.core.get_state = (function() { var om$core$get_state = null; var om$core$get_state__1 = (function (owner){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } return om.core._get_state.call(null,owner); }); var om$core$get_state__2 = (function (owner,korks){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } var ks = ((cljs.core.sequential_QMARK_.call(null,korks))?korks:new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [korks], null)); return om.core._get_state.call(null,owner,ks); }); om$core$get_state = function(owner,korks){ switch(arguments.length){ case 1: return om$core$get_state__1.call(this,owner); case 2: return om$core$get_state__2.call(this,owner,korks); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$get_state.cljs$core$IFn$_invoke$arity$1 = om$core$get_state__1; om$core$get_state.cljs$core$IFn$_invoke$arity$2 = om$core$get_state__2; return om$core$get_state; })() ; /** * Takes an owner and returns a map of global shared values for a * render loop. An optional key or sequence of keys may be given to * extract a specific value. */ om.core.get_shared = (function() { var om$core$get_shared = null; var om$core$get_shared__1 = (function (owner){ if((owner == null)){ return null; } else { return (owner.props["__om_shared"]); } }); var om$core$get_shared__2 = (function (owner,korks){ if(!(cljs.core.sequential_QMARK_.call(null,korks))){ return cljs.core.get.call(null,om$core$get_shared.call(null,owner),korks); } else { if(cljs.core.empty_QMARK_.call(null,korks)){ return om$core$get_shared.call(null,owner); } else { return cljs.core.get_in.call(null,om$core$get_shared.call(null,owner),korks); } } }); om$core$get_shared = function(owner,korks){ switch(arguments.length){ case 1: return om$core$get_shared__1.call(this,owner); case 2: return om$core$get_shared__2.call(this,owner,korks); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$get_shared.cljs$core$IFn$_invoke$arity$1 = om$core$get_shared__1; om$core$get_shared.cljs$core$IFn$_invoke$arity$2 = om$core$get_shared__2; return om$core$get_shared; })() ; om.core.merge_pending_state = (function om$core$merge_pending_state(owner){ var state = owner.state; var temp__4126__auto__ = (state["__om_pending_state"]); if(cljs.core.truth_(temp__4126__auto__)){ var pending_state = temp__4126__auto__; var G__20132 = state; (G__20132["__om_prev_state"] = (state["__om_state"])); (G__20132["__om_state"] = pending_state); (G__20132["__om_pending_state"] = null); return G__20132; } else { return null; } }); om.core.merge_props_state = (function() { var om$core$merge_props_state = null; var om$core$merge_props_state__1 = (function (owner){ return om$core$merge_props_state.call(null,owner,null); }); var om$core$merge_props_state__2 = (function (owner,props){ var props__$1 = (function (){var or__17856__auto__ = props; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return owner.props; } })(); var temp__4126__auto__ = (props__$1["__om_state"]); if(cljs.core.truth_(temp__4126__auto__)){ var props_state = temp__4126__auto__; var state = owner.state; (state["__om_pending_state"] = cljs.core.merge.call(null,(function (){var or__17856__auto__ = (state["__om_pending_state"]); if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return (state["__om_state"]); } })(),props_state)); return (props__$1["__om_state"] = null); } else { return null; } }); om$core$merge_props_state = function(owner,props){ switch(arguments.length){ case 1: return om$core$merge_props_state__1.call(this,owner); case 2: return om$core$merge_props_state__2.call(this,owner,props); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$merge_props_state.cljs$core$IFn$_invoke$arity$1 = om$core$merge_props_state__1; om$core$merge_props_state.cljs$core$IFn$_invoke$arity$2 = om$core$merge_props_state__2; return om$core$merge_props_state; })() ; om.core.ref_changed_QMARK_ = (function om$core$ref_changed_QMARK_(ref){ var val = om.core.value.call(null,ref); var val_SINGLEQUOTE_ = cljs.core.get_in.call(null,cljs.core.deref.call(null,om.core.state.call(null,ref)),om.core.path.call(null,ref),new cljs.core.Keyword("om.core","not-found","om.core/not-found",1869894275)); return cljs.core.not_EQ_.call(null,val,val_SINGLEQUOTE_); }); om.core.update_refs = (function om$core$update_refs(c){ var cstate = c.state; var refs = (cstate["__om_refs"]); if((cljs.core.count.call(null,refs) === (0))){ return null; } else { return (cstate["__om_refs"] = cljs.core.into.call(null,cljs.core.PersistentHashSet.EMPTY,cljs.core.filter.call(null,cljs.core.nil_QMARK_,cljs.core.map.call(null,((function (cstate,refs){ return (function (ref){ var ref_val = om.core.value.call(null,ref); var ref_state = om.core.state.call(null,ref); var ref_path = om.core.path.call(null,ref); var ref_val_SINGLEQUOTE_ = cljs.core.get_in.call(null,cljs.core.deref.call(null,ref_state),ref_path,new cljs.core.Keyword("om.core","not-found","om.core/not-found",1869894275)); if(cljs.core.not_EQ_.call(null,ref_val,new cljs.core.Keyword("om.core","not-found","om.core/not-found",1869894275))){ if(cljs.core.not_EQ_.call(null,ref_val,ref_val_SINGLEQUOTE_)){ return om.core.adapt.call(null,ref,om.core.to_cursor.call(null,ref_val_SINGLEQUOTE_,ref_state,ref_path)); } else { return ref; } } else { return null; } });})(cstate,refs)) ,refs)))); } }); om.core.pure_methods = cljs.core.PersistentHashMap.fromArrays([new cljs.core.Keyword(null,"componentDidUpdate","componentDidUpdate",-1983477981),new cljs.core.Keyword(null,"isOmComponent","isOmComponent",-2070015162),new cljs.core.Keyword(null,"componentWillUnmount","componentWillUnmount",1573788814),new cljs.core.Keyword(null,"componentWillReceiveProps","componentWillReceiveProps",559988974),new cljs.core.Keyword(null,"shouldComponentUpdate","shouldComponentUpdate",1795750960),new cljs.core.Keyword(null,"render","render",-1408033454),new cljs.core.Keyword(null,"componentWillUpdate","componentWillUpdate",657390932),new cljs.core.Keyword(null,"getInitialState","getInitialState",1541760916),new cljs.core.Keyword(null,"componentDidMount","componentDidMount",955710936),new cljs.core.Keyword(null,"getDisplayName","getDisplayName",1324429466),new cljs.core.Keyword(null,"componentWillMount","componentWillMount",-285327619)],[(function (prev_props,prev_state){ var this$ = this; var c = om.core.children.call(null,this$); if((function (){var G__20134 = c; if(G__20134){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20134.om$core$IDidUpdate$; } })())){ return true; } else { if((!G__20134.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IDidUpdate,G__20134); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IDidUpdate,G__20134); } })()){ var state_20155 = this$.state; om.core.did_update.call(null,c,om.core.get_props.call(null,{"isOmComponent": true, "props": prev_props}),(function (){var or__17856__auto__ = (state_20155["__om_prev_state"]); if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return (state_20155["__om_state"]); } })()); } else { } return (this$.state["__om_prev_state"] = null); }),true,(function (){ var this$ = this; var c = om.core.children.call(null,this$); var cursor = (this$.props["__om_cursor"]); if((function (){var G__20135 = c; if(G__20135){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20135.om$core$IWillUnmount$; } })())){ return true; } else { if((!G__20135.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillUnmount,G__20135); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillUnmount,G__20135); } })()){ om.core.will_unmount.call(null,c); } else { } var temp__4126__auto__ = cljs.core.seq.call(null,(this$.state["__om_refs"])); if(temp__4126__auto__){ var refs = temp__4126__auto__; var seq__20136 = cljs.core.seq.call(null,refs); var chunk__20137 = null; var count__20138 = (0); var i__20139 = (0); while(true){ if((i__20139 < count__20138)){ var ref = cljs.core._nth.call(null,chunk__20137,i__20139); om.core.unobserve.call(null,this$,ref); var G__20156 = seq__20136; var G__20157 = chunk__20137; var G__20158 = count__20138; var G__20159 = (i__20139 + (1)); seq__20136 = G__20156; chunk__20137 = G__20157; count__20138 = G__20158; i__20139 = G__20159; continue; } else { var temp__4126__auto____$1 = cljs.core.seq.call(null,seq__20136); if(temp__4126__auto____$1){ var seq__20136__$1 = temp__4126__auto____$1; if(cljs.core.chunked_seq_QMARK_.call(null,seq__20136__$1)){ var c__18641__auto__ = cljs.core.chunk_first.call(null,seq__20136__$1); var G__20160 = cljs.core.chunk_rest.call(null,seq__20136__$1); var G__20161 = c__18641__auto__; var G__20162 = cljs.core.count.call(null,c__18641__auto__); var G__20163 = (0); seq__20136 = G__20160; chunk__20137 = G__20161; count__20138 = G__20162; i__20139 = G__20163; continue; } else { var ref = cljs.core.first.call(null,seq__20136__$1); om.core.unobserve.call(null,this$,ref); var G__20164 = cljs.core.next.call(null,seq__20136__$1); var G__20165 = null; var G__20166 = (0); var G__20167 = (0); seq__20136 = G__20164; chunk__20137 = G__20165; count__20138 = G__20166; i__20139 = G__20167; continue; } } else { return null; } } break; } } else { return null; } }),(function (next_props){ var this$ = this; var c = om.core.children.call(null,this$); if((function (){var G__20140 = c; if(G__20140){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20140.om$core$IWillReceiveProps$; } })())){ return true; } else { if((!G__20140.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillReceiveProps,G__20140); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillReceiveProps,G__20140); } })()){ return om.core.will_receive_props.call(null,c,om.core.get_props.call(null,{"isOmComponent": true, "props": next_props})); } else { return null; } }),(function (next_props,next_state){ var this$ = this; var props = this$.props; var state = this$.state; var c = om.core.children.call(null,this$); om.core.merge_props_state.call(null,this$,next_props); if((function (){var G__20141 = c; if(G__20141){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20141.om$core$IShouldUpdate$; } })())){ return true; } else { if((!G__20141.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IShouldUpdate,G__20141); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IShouldUpdate,G__20141); } })()){ return om.core.should_update.call(null,c,om.core.get_props.call(null,{"isOmComponent": true, "props": next_props}),om.core._get_state.call(null,this$)); } else { var cursor = (props["__om_cursor"]); var next_cursor = (next_props["__om_cursor"]); if(cljs.core.not_EQ_.call(null,om.core._value.call(null,cursor),om.core._value.call(null,next_cursor))){ return true; } else { if((om.core.cursor_QMARK_.call(null,cursor)) && (om.core.cursor_QMARK_.call(null,next_cursor)) && (cljs.core.not_EQ_.call(null,om.core._path.call(null,cursor),om.core._path.call(null,next_cursor)))){ return true; } else { if(cljs.core.not_EQ_.call(null,om.core._get_state.call(null,this$),om.core._get_render_state.call(null,this$))){ return true; } else { if(cljs.core.truth_((function (){var and__17844__auto__ = !((cljs.core.count.call(null,(state["__om_refs"])) === (0))); if(and__17844__auto__){ return cljs.core.some.call(null,((function (and__17844__auto__,cursor,next_cursor,props,state,c,this$){ return (function (p1__20133_SHARP_){ return om.core.ref_changed_QMARK_.call(null,p1__20133_SHARP_); });})(and__17844__auto__,cursor,next_cursor,props,state,c,this$)) ,(state["__om_refs"])); } else { return and__17844__auto__; } })())){ return true; } else { if(!(((props["__om_index"]) === (next_props["__om_index"])))){ return true; } else { return false; } } } } } } }),(function (){ var this$ = this; var c = om.core.children.call(null,this$); var props = this$.props; var _STAR_parent_STAR_20142 = om.core._STAR_parent_STAR_; var _STAR_state_STAR_20143 = om.core._STAR_state_STAR_; var _STAR_instrument_STAR_20144 = om.core._STAR_instrument_STAR_; var _STAR_descriptor_STAR_20145 = om.core._STAR_descriptor_STAR_; var _STAR_root_key_STAR_20146 = om.core._STAR_root_key_STAR_; om.core._STAR_parent_STAR_ = this$; om.core._STAR_state_STAR_ = (props["__om_app_state"]); om.core._STAR_instrument_STAR_ = (props["__om_instrument"]); om.core._STAR_descriptor_STAR_ = (props["__om_descriptor"]); om.core._STAR_root_key_STAR_ = (props["__om_root_key"]); try{if((function (){var G__20147 = c; if(G__20147){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20147.om$core$IRender$; } })())){ return true; } else { if((!G__20147.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRender,G__20147); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRender,G__20147); } })()){ return om.core.render.call(null,c); } else { if((function (){var G__20148 = c; if(G__20148){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20148.om$core$IRenderProps$; } })())){ return true; } else { if((!G__20148.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRenderProps,G__20148); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRenderProps,G__20148); } })()){ return om.core.render_props.call(null,c,(props["__om_cursor"]),om.core.get_state.call(null,this$)); } else { if((function (){var G__20149 = c; if(G__20149){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20149.om$core$IRenderState$; } })())){ return true; } else { if((!G__20149.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRenderState,G__20149); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRenderState,G__20149); } })()){ return om.core.render_state.call(null,c,om.core.get_state.call(null,this$)); } else { return c; } } } }finally {om.core._STAR_root_key_STAR_ = _STAR_root_key_STAR_20146; om.core._STAR_descriptor_STAR_ = _STAR_descriptor_STAR_20145; om.core._STAR_instrument_STAR_ = _STAR_instrument_STAR_20144; om.core._STAR_state_STAR_ = _STAR_state_STAR_20143; om.core._STAR_parent_STAR_ = _STAR_parent_STAR_20142; }}),(function (next_props,next_state){ var this$ = this; var c_20168 = om.core.children.call(null,this$); if((function (){var G__20150 = c_20168; if(G__20150){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20150.om$core$IWillUpdate$; } })())){ return true; } else { if((!G__20150.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillUpdate,G__20150); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillUpdate,G__20150); } })()){ var state_20169 = this$.state; om.core.will_update.call(null,c_20168,om.core.get_props.call(null,{"isOmComponent": true, "props": next_props}),om.core._get_state.call(null,this$)); } else { } om.core.merge_pending_state.call(null,this$); return om.core.update_refs.call(null,this$); }),(function (){ var this$ = this; var c = om.core.children.call(null,this$); var props = this$.props; var istate = (function (){var or__17856__auto__ = (props["__om_init_state"]); if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return cljs.core.PersistentArrayMap.EMPTY; } })(); var id = new cljs.core.Keyword("om.core","id","om.core/id",299074693).cljs$core$IFn$_invoke$arity$1(istate); var ret = {"__om_state": cljs.core.merge.call(null,(((function (){var G__20151 = c; if(G__20151){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20151.om$core$IInitState$; } })())){ return true; } else { if((!G__20151.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IInitState,G__20151); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IInitState,G__20151); } })())?om.core.init_state.call(null,c):null),cljs.core.dissoc.call(null,istate,new cljs.core.Keyword("om.core","id","om.core/id",299074693))), "__om_id": (function (){var or__17856__auto__ = id; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return goog.ui.IdGenerator.getInstance().getNextUniqueId(); } })()}; (props["__om_init_state"] = null); return ret; }),(function (){ var this$ = this; var c = om.core.children.call(null,this$); var cursor = (this$.props["__om_cursor"]); if((function (){var G__20152 = c; if(G__20152){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20152.om$core$IDidMount$; } })())){ return true; } else { if((!G__20152.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IDidMount,G__20152); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IDidMount,G__20152); } })()){ return om.core.did_mount.call(null,c); } else { return null; } }),(function (){ var this$ = this; var c = om.core.children.call(null,this$); if((function (){var G__20153 = c; if(G__20153){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20153.om$core$IDisplayName$; } })())){ return true; } else { if((!G__20153.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IDisplayName,G__20153); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IDisplayName,G__20153); } })()){ return om.core.display_name.call(null,c); } else { return null; } }),(function (){ var this$ = this; om.core.merge_props_state.call(null,this$); var c_20170 = om.core.children.call(null,this$); if((function (){var G__20154 = c_20170; if(G__20154){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20154.om$core$IWillMount$; } })())){ return true; } else { if((!G__20154.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillMount,G__20154); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillMount,G__20154); } })()){ om.core.will_mount.call(null,c_20170); } else { } return om.core.merge_pending_state.call(null,this$); })]); om.core.specify_state_methods_BANG_ = (function om$core$specify_state_methods_BANG_(obj){ var x20172 = obj; x20172.om$core$IGetState$ = true; x20172.om$core$IGetState$_get_state$arity$1 = ((function (x20172){ return (function (this$){ var this$__$1 = this; var state = this$__$1.state; var or__17856__auto__ = (state["__om_pending_state"]); if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return (state["__om_state"]); } });})(x20172)) ; x20172.om$core$IGetState$_get_state$arity$2 = ((function (x20172){ return (function (this$,ks){ var this$__$1 = this; return cljs.core.get_in.call(null,om.core._get_state.call(null,this$__$1),ks); });})(x20172)) ; x20172.om$core$IGetRenderState$ = true; x20172.om$core$IGetRenderState$_get_render_state$arity$1 = ((function (x20172){ return (function (this$){ var this$__$1 = this; return (this$__$1.state["__om_state"]); });})(x20172)) ; x20172.om$core$IGetRenderState$_get_render_state$arity$2 = ((function (x20172){ return (function (this$,ks){ var this$__$1 = this; return cljs.core.get_in.call(null,om.core._get_render_state.call(null,this$__$1),ks); });})(x20172)) ; x20172.om$core$ISetState$ = true; x20172.om$core$ISetState$_set_state_BANG_$arity$3 = ((function (x20172){ return (function (this$,val,render){ var this$__$1 = this; var props = this$__$1.props; var app_state = (props["__om_app_state"]); (this$__$1.state["__om_pending_state"] = val); if(cljs.core.truth_((function (){var and__17844__auto__ = !((app_state == null)); if(and__17844__auto__){ return render; } else { return and__17844__auto__; } })())){ return om.core._queue_render_BANG_.call(null,app_state,this$__$1); } else { return null; } });})(x20172)) ; x20172.om$core$ISetState$_set_state_BANG_$arity$4 = ((function (x20172){ return (function (this$,ks,val,render){ var this$__$1 = this; var props = this$__$1.props; var state = this$__$1.state; var pstate = om.core._get_state.call(null,this$__$1); var app_state = (props["__om_app_state"]); (state["__om_pending_state"] = cljs.core.assoc_in.call(null,pstate,ks,val)); if(cljs.core.truth_((function (){var and__17844__auto__ = !((app_state == null)); if(and__17844__auto__){ return render; } else { return and__17844__auto__; } })())){ return om.core._queue_render_BANG_.call(null,app_state,this$__$1); } else { return null; } });})(x20172)) ; return x20172; }); om.core.pure_descriptor = om.core.specify_state_methods_BANG_.call(null,cljs.core.clj__GT_js.call(null,om.core.pure_methods)); om.core.react_id = (function om$core$react_id(x){ var id = (x["_rootNodeID"]); if(cljs.core.truth_(id)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,new cljs.core.Symbol(null,"id","id",252129435,null)))].join(''))); } return id; }); om.core.get_gstate = (function om$core$get_gstate(owner){ return (owner.props["__om_app_state"]); }); om.core.no_local_merge_pending_state = (function om$core$no_local_merge_pending_state(owner){ var gstate = om.core.get_gstate.call(null,owner); var spath = new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"state-map","state-map",-1313872128),om.core.react_id.call(null,owner)], null); var states = cljs.core.get_in.call(null,cljs.core.deref.call(null,gstate),spath); if(cljs.core.truth_(new cljs.core.Keyword(null,"pending-state","pending-state",1525896973).cljs$core$IFn$_invoke$arity$1(states))){ return cljs.core.swap_BANG_.call(null,gstate,cljs.core.update_in,spath,((function (gstate,spath,states){ return (function (states__$1){ return cljs.core.dissoc.call(null,cljs.core.assoc.call(null,cljs.core.assoc.call(null,states__$1,new cljs.core.Keyword(null,"previous-state","previous-state",1888227923),new cljs.core.Keyword(null,"render-state","render-state",2053902270).cljs$core$IFn$_invoke$arity$1(states__$1)),new cljs.core.Keyword(null,"render-state","render-state",2053902270),cljs.core.merge.call(null,new cljs.core.Keyword(null,"render-state","render-state",2053902270).cljs$core$IFn$_invoke$arity$1(states__$1),new cljs.core.Keyword(null,"pending-state","pending-state",1525896973).cljs$core$IFn$_invoke$arity$1(states__$1))),new cljs.core.Keyword(null,"pending-state","pending-state",1525896973)); });})(gstate,spath,states)) ); } else { return null; } }); om.core.no_local_state_methods = cljs.core.assoc.call(null,om.core.pure_methods,new cljs.core.Keyword(null,"getInitialState","getInitialState",1541760916),(function (){ var this$ = this; var c = om.core.children.call(null,this$); var props = this$.props; var istate = (function (){var or__17856__auto__ = (props["__om_init_state"]); if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return cljs.core.PersistentArrayMap.EMPTY; } })(); var om_id = (function (){var or__17856__auto__ = new cljs.core.Keyword("om.core","id","om.core/id",299074693).cljs$core$IFn$_invoke$arity$1(istate); if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return goog.ui.IdGenerator.getInstance().getNextUniqueId(); } })(); var state = cljs.core.merge.call(null,cljs.core.dissoc.call(null,istate,new cljs.core.Keyword("om.core","id","om.core/id",299074693)),(((function (){var G__20173 = c; if(G__20173){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20173.om$core$IInitState$; } })())){ return true; } else { if((!G__20173.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IInitState,G__20173); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IInitState,G__20173); } })())?om.core.init_state.call(null,c):null)); var spath = new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"state-map","state-map",-1313872128),om.core.react_id.call(null,this$),new cljs.core.Keyword(null,"render-state","render-state",2053902270)], null); (props["__om_init_state"] = null); cljs.core.swap_BANG_.call(null,om.core.get_gstate.call(null,this$),cljs.core.assoc_in,spath,state); return {"__om_id": om_id}; }),new cljs.core.Keyword(null,"componentWillMount","componentWillMount",-285327619),(function (){ var this$ = this; om.core.merge_props_state.call(null,this$); var c_20182 = om.core.children.call(null,this$); if((function (){var G__20174 = c_20182; if(G__20174){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20174.om$core$IWillMount$; } })())){ return true; } else { if((!G__20174.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillMount,G__20174); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillMount,G__20174); } })()){ om.core.will_mount.call(null,c_20182); } else { } return om.core.no_local_merge_pending_state.call(null,this$); }),new cljs.core.Keyword(null,"componentWillUnmount","componentWillUnmount",1573788814),(function (){ var this$ = this; var c = om.core.children.call(null,this$); if((function (){var G__20175 = c; if(G__20175){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20175.om$core$IWillUnmount$; } })())){ return true; } else { if((!G__20175.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillUnmount,G__20175); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillUnmount,G__20175); } })()){ om.core.will_unmount.call(null,c); } else { } cljs.core.swap_BANG_.call(null,om.core.get_gstate.call(null,this$),cljs.core.update_in,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"state-map","state-map",-1313872128)], null),cljs.core.dissoc,om.core.react_id.call(null,this$)); var temp__4126__auto__ = cljs.core.seq.call(null,(this$.state["__om_refs"])); if(temp__4126__auto__){ var refs = temp__4126__auto__; var seq__20176 = cljs.core.seq.call(null,refs); var chunk__20177 = null; var count__20178 = (0); var i__20179 = (0); while(true){ if((i__20179 < count__20178)){ var ref = cljs.core._nth.call(null,chunk__20177,i__20179); om.core.unobserve.call(null,this$,ref); var G__20183 = seq__20176; var G__20184 = chunk__20177; var G__20185 = count__20178; var G__20186 = (i__20179 + (1)); seq__20176 = G__20183; chunk__20177 = G__20184; count__20178 = G__20185; i__20179 = G__20186; continue; } else { var temp__4126__auto____$1 = cljs.core.seq.call(null,seq__20176); if(temp__4126__auto____$1){ var seq__20176__$1 = temp__4126__auto____$1; if(cljs.core.chunked_seq_QMARK_.call(null,seq__20176__$1)){ var c__18641__auto__ = cljs.core.chunk_first.call(null,seq__20176__$1); var G__20187 = cljs.core.chunk_rest.call(null,seq__20176__$1); var G__20188 = c__18641__auto__; var G__20189 = cljs.core.count.call(null,c__18641__auto__); var G__20190 = (0); seq__20176 = G__20187; chunk__20177 = G__20188; count__20178 = G__20189; i__20179 = G__20190; continue; } else { var ref = cljs.core.first.call(null,seq__20176__$1); om.core.unobserve.call(null,this$,ref); var G__20191 = cljs.core.next.call(null,seq__20176__$1); var G__20192 = null; var G__20193 = (0); var G__20194 = (0); seq__20176 = G__20191; chunk__20177 = G__20192; count__20178 = G__20193; i__20179 = G__20194; continue; } } else { return null; } } break; } } else { return null; } }),new cljs.core.Keyword(null,"componentWillUpdate","componentWillUpdate",657390932),(function (next_props,next_state){ var this$ = this; var props_20195 = this$.props; var c_20196 = om.core.children.call(null,this$); if((function (){var G__20180 = c_20196; if(G__20180){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20180.om$core$IWillUpdate$; } })())){ return true; } else { if((!G__20180.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillUpdate,G__20180); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IWillUpdate,G__20180); } })()){ var state_20197 = this$.state; om.core.will_update.call(null,c_20196,om.core.get_props.call(null,{"isOmComponent": true, "props": next_props}),om.core._get_state.call(null,this$)); } else { } om.core.no_local_merge_pending_state.call(null,this$); return om.core.update_refs.call(null,this$); }),new cljs.core.Keyword(null,"componentDidUpdate","componentDidUpdate",-1983477981),(function (prev_props,prev_state){ var this$ = this; var c = om.core.children.call(null,this$); var gstate = om.core.get_gstate.call(null,this$); var states = cljs.core.get_in.call(null,cljs.core.deref.call(null,gstate),new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"state-map","state-map",-1313872128),om.core.react_id.call(null,this$)], null)); var spath = new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"state-map","state-map",-1313872128),om.core.react_id.call(null,this$)], null); if((function (){var G__20181 = c; if(G__20181){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20181.om$core$IDidUpdate$; } })())){ return true; } else { if((!G__20181.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IDidUpdate,G__20181); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IDidUpdate,G__20181); } })()){ var state_20198 = this$.state; om.core.did_update.call(null,c,om.core.get_props.call(null,{"isOmComponent": true, "props": prev_props}),(function (){var or__17856__auto__ = new cljs.core.Keyword(null,"previous-state","previous-state",1888227923).cljs$core$IFn$_invoke$arity$1(states); if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return new cljs.core.Keyword(null,"render-state","render-state",2053902270).cljs$core$IFn$_invoke$arity$1(states); } })()); } else { } if(cljs.core.truth_(new cljs.core.Keyword(null,"previous-state","previous-state",1888227923).cljs$core$IFn$_invoke$arity$1(states))){ return cljs.core.swap_BANG_.call(null,gstate,cljs.core.update_in,spath,cljs.core.dissoc,new cljs.core.Keyword(null,"previous-state","previous-state",1888227923)); } else { return null; } })); om.core.no_local_descriptor = (function om$core$no_local_descriptor(methods$){ var x20200 = cljs.core.clj__GT_js.call(null,methods$); x20200.om$core$IGetState$ = true; x20200.om$core$IGetState$_get_state$arity$1 = ((function (x20200){ return (function (this$){ var this$__$1 = this; var spath = new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"state-map","state-map",-1313872128),om.core.react_id.call(null,this$__$1)], null); var states = cljs.core.get_in.call(null,cljs.core.deref.call(null,om.core.get_gstate.call(null,this$__$1)),spath); var or__17856__auto__ = new cljs.core.Keyword(null,"pending-state","pending-state",1525896973).cljs$core$IFn$_invoke$arity$1(states); if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return new cljs.core.Keyword(null,"render-state","render-state",2053902270).cljs$core$IFn$_invoke$arity$1(states); } });})(x20200)) ; x20200.om$core$IGetState$_get_state$arity$2 = ((function (x20200){ return (function (this$,ks){ var this$__$1 = this; return cljs.core.get_in.call(null,om.core._get_state.call(null,this$__$1),ks); });})(x20200)) ; x20200.om$core$IGetRenderState$ = true; x20200.om$core$IGetRenderState$_get_render_state$arity$1 = ((function (x20200){ return (function (this$){ var this$__$1 = this; var spath = new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"state-map","state-map",-1313872128),om.core.react_id.call(null,this$__$1),new cljs.core.Keyword(null,"render-state","render-state",2053902270)], null); return cljs.core.get_in.call(null,cljs.core.deref.call(null,om.core.get_gstate.call(null,this$__$1)),spath); });})(x20200)) ; x20200.om$core$IGetRenderState$_get_render_state$arity$2 = ((function (x20200){ return (function (this$,ks){ var this$__$1 = this; return cljs.core.get_in.call(null,om.core._get_render_state.call(null,this$__$1),ks); });})(x20200)) ; x20200.om$core$ISetState$ = true; x20200.om$core$ISetState$_set_state_BANG_$arity$3 = ((function (x20200){ return (function (this$,val,render){ var this$__$1 = this; var gstate = om.core.get_gstate.call(null,this$__$1); var spath = new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"state-map","state-map",-1313872128),om.core.react_id.call(null,this$__$1),new cljs.core.Keyword(null,"pending-state","pending-state",1525896973)], null); cljs.core.swap_BANG_.call(null,om.core.get_gstate.call(null,this$__$1),cljs.core.assoc_in,spath,val); if(cljs.core.truth_((function (){var and__17844__auto__ = !((gstate == null)); if(and__17844__auto__){ return render; } else { return and__17844__auto__; } })())){ return om.core._queue_render_BANG_.call(null,gstate,this$__$1); } else { return null; } });})(x20200)) ; x20200.om$core$ISetState$_set_state_BANG_$arity$4 = ((function (x20200){ return (function (this$,ks,val,render){ var this$__$1 = this; return om.core._set_state_BANG_.call(null,this$__$1,cljs.core.assoc_in.call(null,om.core._get_state.call(null,this$__$1),ks,val),render); });})(x20200)) ; return x20200; }); om.core.valid_QMARK_ = (function om$core$valid_QMARK_(x){ if((function (){var G__20202 = x; if(G__20202){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20202.om$core$ICursor$; } })())){ return true; } else { if((!G__20202.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.ICursor,G__20202); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.ICursor,G__20202); } })()){ return !(cljs.core.keyword_identical_QMARK_.call(null,cljs.core.deref.call(null,x),new cljs.core.Keyword("om.core","invalid","om.core/invalid",1948827993))); } else { return true; } }); /** * @constructor */ om.core.MapCursor = (function (value,state,path){ this.value = value; this.state = state; this.path = path; this.cljs$lang$protocol_mask$partition0$ = 2163640079; this.cljs$lang$protocol_mask$partition1$ = 8192; }) om.core.MapCursor.prototype.cljs$core$ILookup$_lookup$arity$2 = (function (this$,k){ var self__ = this; var this$__$1 = this; return cljs.core._lookup.call(null,this$__$1,k,null); }); om.core.MapCursor.prototype.cljs$core$ILookup$_lookup$arity$3 = (function (this$,k,not_found){ var self__ = this; var this$__$1 = this; var v = cljs.core._lookup.call(null,self__.value,k,new cljs.core.Keyword("om.core","not-found","om.core/not-found",1869894275)); if(!(cljs.core._EQ_.call(null,v,new cljs.core.Keyword("om.core","not-found","om.core/not-found",1869894275)))){ return om.core._derive.call(null,this$__$1,v,self__.state,cljs.core.conj.call(null,self__.path,k)); } else { return not_found; } }); om.core.MapCursor.prototype.cljs$core$IKVReduce$_kv_reduce$arity$3 = (function (_,f,init){ var self__ = this; var ___$1 = this; return cljs.core._kv_reduce.call(null,self__.value,f,init); }); om.core.MapCursor.prototype.cljs$core$IPrintWithWriter$_pr_writer$arity$3 = (function (_,writer,opts){ var self__ = this; var ___$1 = this; return cljs.core._pr_writer.call(null,self__.value,writer,opts); }); om.core.MapCursor.prototype.om$core$ICursor$ = true; om.core.MapCursor.prototype.om$core$ICursor$_path$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.path; }); om.core.MapCursor.prototype.om$core$ICursor$_state$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.state; }); om.core.MapCursor.prototype.cljs$core$IMeta$_meta$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core.meta.call(null,self__.value); }); om.core.MapCursor.prototype.cljs$core$ICloneable$_clone$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new om.core.MapCursor(self__.value,self__.state,self__.path)); }); om.core.MapCursor.prototype.cljs$core$ICounted$_count$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core._count.call(null,self__.value); }); om.core.MapCursor.prototype.cljs$core$IHash$_hash$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core.hash.call(null,self__.value); }); om.core.MapCursor.prototype.cljs$core$IEquiv$_equiv$arity$2 = (function (_,other){ var self__ = this; var ___$1 = this; if(om.core.cursor_QMARK_.call(null,other)){ return cljs.core._EQ_.call(null,self__.value,om.core._value.call(null,other)); } else { return cljs.core._EQ_.call(null,self__.value,other); } }); om.core.MapCursor.prototype.om$core$IValue$ = true; om.core.MapCursor.prototype.om$core$IValue$_value$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.value; }); om.core.MapCursor.prototype.cljs$core$IEmptyableCollection$_empty$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new om.core.MapCursor(cljs.core.empty.call(null,self__.value),self__.state,self__.path)); }); om.core.MapCursor.prototype.cljs$core$IMap$_dissoc$arity$2 = (function (_,k){ var self__ = this; var ___$1 = this; return (new om.core.MapCursor(cljs.core._dissoc.call(null,self__.value,k),self__.state,self__.path)); }); om.core.MapCursor.prototype.om$core$ITransact$ = true; om.core.MapCursor.prototype.om$core$ITransact$_transact_BANG_$arity$4 = (function (this$,korks,f,tag){ var self__ = this; var this$__$1 = this; return om.core.transact_STAR_.call(null,self__.state,this$__$1,korks,f,tag); }); om.core.MapCursor.prototype.cljs$core$IAssociative$_contains_key_QMARK_$arity$2 = (function (_,k){ var self__ = this; var ___$1 = this; return cljs.core._contains_key_QMARK_.call(null,self__.value,k); }); om.core.MapCursor.prototype.cljs$core$IAssociative$_assoc$arity$3 = (function (_,k,v){ var self__ = this; var ___$1 = this; return (new om.core.MapCursor(cljs.core._assoc.call(null,self__.value,k,v),self__.state,self__.path)); }); om.core.MapCursor.prototype.cljs$core$ISeqable$_seq$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; if((cljs.core.count.call(null,self__.value) > (0))){ return cljs.core.map.call(null,((function (this$__$1){ return (function (p__20204){ var vec__20205 = p__20204; var k = cljs.core.nth.call(null,vec__20205,(0),null); var v = cljs.core.nth.call(null,vec__20205,(1),null); return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [k,om.core._derive.call(null,this$__$1,v,self__.state,cljs.core.conj.call(null,self__.path,k))], null); });})(this$__$1)) ,self__.value); } else { return null; } }); om.core.MapCursor.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (_,new_meta){ var self__ = this; var ___$1 = this; return (new om.core.MapCursor(cljs.core.with_meta.call(null,self__.value,new_meta),self__.state,self__.path)); }); om.core.MapCursor.prototype.cljs$core$ICollection$_conj$arity$2 = (function (_,o){ var self__ = this; var ___$1 = this; return (new om.core.MapCursor(cljs.core._conj.call(null,self__.value,o),self__.state,self__.path)); }); om.core.MapCursor.prototype.call = (function() { var G__20206 = null; var G__20206__2 = (function (self__,k){ var self__ = this; var self____$1 = this; var this$ = self____$1; return cljs.core._lookup.call(null,this$,k); }); var G__20206__3 = (function (self__,k,not_found){ var self__ = this; var self____$1 = this; var this$ = self____$1; return cljs.core._lookup.call(null,this$,k,not_found); }); G__20206 = function(self__,k,not_found){ switch(arguments.length){ case 2: return G__20206__2.call(this,self__,k); case 3: return G__20206__3.call(this,self__,k,not_found); } throw(new Error('Invalid arity: ' + arguments.length)); }; G__20206.cljs$core$IFn$_invoke$arity$2 = G__20206__2; G__20206.cljs$core$IFn$_invoke$arity$3 = G__20206__3; return G__20206; })() ; om.core.MapCursor.prototype.apply = (function (self__,args20203){ var self__ = this; var self____$1 = this; return self____$1.call.apply(self____$1,[self____$1].concat(cljs.core.aclone.call(null,args20203))); }); om.core.MapCursor.prototype.cljs$core$IFn$_invoke$arity$1 = (function (k){ var self__ = this; var this$ = this; return cljs.core._lookup.call(null,this$,k); }); om.core.MapCursor.prototype.cljs$core$IFn$_invoke$arity$2 = (function (k,not_found){ var self__ = this; var this$ = this; return cljs.core._lookup.call(null,this$,k,not_found); }); om.core.MapCursor.prototype.cljs$core$IDeref$_deref$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return cljs.core.get_in.call(null,cljs.core.deref.call(null,self__.state),self__.path,new cljs.core.Keyword("om.core","invalid","om.core/invalid",1948827993)); }); om.core.MapCursor.cljs$lang$type = true; om.core.MapCursor.cljs$lang$ctorStr = "om.core/MapCursor"; om.core.MapCursor.cljs$lang$ctorPrWriter = (function (this__18435__auto__,writer__18436__auto__,opt__18437__auto__){ return cljs.core._write.call(null,writer__18436__auto__,"om.core/MapCursor"); }); om.core.__GT_MapCursor = (function om$core$__GT_MapCursor(value,state,path){ return (new om.core.MapCursor(value,state,path)); }); /** * @constructor */ om.core.IndexedCursor = (function (value,state,path){ this.value = value; this.state = state; this.path = path; this.cljs$lang$protocol_mask$partition0$ = 2180424479; this.cljs$lang$protocol_mask$partition1$ = 8192; }) om.core.IndexedCursor.prototype.cljs$core$ILookup$_lookup$arity$2 = (function (this$,n){ var self__ = this; var this$__$1 = this; return cljs.core._nth.call(null,this$__$1,n,null); }); om.core.IndexedCursor.prototype.cljs$core$ILookup$_lookup$arity$3 = (function (this$,n,not_found){ var self__ = this; var this$__$1 = this; return cljs.core._nth.call(null,this$__$1,n,not_found); }); om.core.IndexedCursor.prototype.cljs$core$IKVReduce$_kv_reduce$arity$3 = (function (_,f,init){ var self__ = this; var ___$1 = this; return cljs.core._kv_reduce.call(null,self__.value,f,init); }); om.core.IndexedCursor.prototype.cljs$core$IIndexed$_nth$arity$2 = (function (this$,n){ var self__ = this; var this$__$1 = this; return om.core._derive.call(null,this$__$1,cljs.core._nth.call(null,self__.value,n),self__.state,cljs.core.conj.call(null,self__.path,n)); }); om.core.IndexedCursor.prototype.cljs$core$IIndexed$_nth$arity$3 = (function (this$,n,not_found){ var self__ = this; var this$__$1 = this; if((n < cljs.core._count.call(null,self__.value))){ return om.core._derive.call(null,this$__$1,cljs.core._nth.call(null,self__.value,n,not_found),self__.state,cljs.core.conj.call(null,self__.path,n)); } else { return not_found; } }); om.core.IndexedCursor.prototype.cljs$core$IPrintWithWriter$_pr_writer$arity$3 = (function (_,writer,opts){ var self__ = this; var ___$1 = this; return cljs.core._pr_writer.call(null,self__.value,writer,opts); }); om.core.IndexedCursor.prototype.om$core$ICursor$ = true; om.core.IndexedCursor.prototype.om$core$ICursor$_path$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.path; }); om.core.IndexedCursor.prototype.om$core$ICursor$_state$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.state; }); om.core.IndexedCursor.prototype.cljs$core$IMeta$_meta$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core.meta.call(null,self__.value); }); om.core.IndexedCursor.prototype.cljs$core$ICloneable$_clone$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new om.core.IndexedCursor(self__.value,self__.state,self__.path)); }); om.core.IndexedCursor.prototype.cljs$core$ICounted$_count$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core._count.call(null,self__.value); }); om.core.IndexedCursor.prototype.cljs$core$IStack$_peek$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return om.core._derive.call(null,this$__$1,cljs.core._peek.call(null,self__.value),self__.state,self__.path); }); om.core.IndexedCursor.prototype.cljs$core$IStack$_pop$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return om.core._derive.call(null,this$__$1,cljs.core._pop.call(null,self__.value),self__.state,self__.path); }); om.core.IndexedCursor.prototype.cljs$core$IHash$_hash$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core.hash.call(null,self__.value); }); om.core.IndexedCursor.prototype.cljs$core$IEquiv$_equiv$arity$2 = (function (_,other){ var self__ = this; var ___$1 = this; if(om.core.cursor_QMARK_.call(null,other)){ return cljs.core._EQ_.call(null,self__.value,om.core._value.call(null,other)); } else { return cljs.core._EQ_.call(null,self__.value,other); } }); om.core.IndexedCursor.prototype.om$core$IValue$ = true; om.core.IndexedCursor.prototype.om$core$IValue$_value$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.value; }); om.core.IndexedCursor.prototype.cljs$core$IEmptyableCollection$_empty$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new om.core.IndexedCursor(cljs.core.empty.call(null,self__.value),self__.state,self__.path)); }); om.core.IndexedCursor.prototype.om$core$ITransact$ = true; om.core.IndexedCursor.prototype.om$core$ITransact$_transact_BANG_$arity$4 = (function (this$,korks,f,tag){ var self__ = this; var this$__$1 = this; return om.core.transact_STAR_.call(null,self__.state,this$__$1,korks,f,tag); }); om.core.IndexedCursor.prototype.cljs$core$IAssociative$_contains_key_QMARK_$arity$2 = (function (_,k){ var self__ = this; var ___$1 = this; return cljs.core._contains_key_QMARK_.call(null,self__.value,k); }); om.core.IndexedCursor.prototype.cljs$core$IAssociative$_assoc$arity$3 = (function (this$,n,v){ var self__ = this; var this$__$1 = this; return om.core._derive.call(null,this$__$1,cljs.core._assoc_n.call(null,self__.value,n,v),self__.state,self__.path); }); om.core.IndexedCursor.prototype.cljs$core$ISeqable$_seq$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; if((cljs.core.count.call(null,self__.value) > (0))){ return cljs.core.map.call(null,((function (this$__$1){ return (function (v,i){ return om.core._derive.call(null,this$__$1,v,self__.state,cljs.core.conj.call(null,self__.path,i)); });})(this$__$1)) ,self__.value,cljs.core.range.call(null)); } else { return null; } }); om.core.IndexedCursor.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (_,new_meta){ var self__ = this; var ___$1 = this; return (new om.core.IndexedCursor(cljs.core.with_meta.call(null,self__.value,new_meta),self__.state,self__.path)); }); om.core.IndexedCursor.prototype.cljs$core$ICollection$_conj$arity$2 = (function (_,o){ var self__ = this; var ___$1 = this; return (new om.core.IndexedCursor(cljs.core._conj.call(null,self__.value,o),self__.state,self__.path)); }); om.core.IndexedCursor.prototype.call = (function() { var G__20208 = null; var G__20208__2 = (function (self__,k){ var self__ = this; var self____$1 = this; var this$ = self____$1; return cljs.core._lookup.call(null,this$,k); }); var G__20208__3 = (function (self__,k,not_found){ var self__ = this; var self____$1 = this; var this$ = self____$1; return cljs.core._lookup.call(null,this$,k,not_found); }); G__20208 = function(self__,k,not_found){ switch(arguments.length){ case 2: return G__20208__2.call(this,self__,k); case 3: return G__20208__3.call(this,self__,k,not_found); } throw(new Error('Invalid arity: ' + arguments.length)); }; G__20208.cljs$core$IFn$_invoke$arity$2 = G__20208__2; G__20208.cljs$core$IFn$_invoke$arity$3 = G__20208__3; return G__20208; })() ; om.core.IndexedCursor.prototype.apply = (function (self__,args20207){ var self__ = this; var self____$1 = this; return self____$1.call.apply(self____$1,[self____$1].concat(cljs.core.aclone.call(null,args20207))); }); om.core.IndexedCursor.prototype.cljs$core$IFn$_invoke$arity$1 = (function (k){ var self__ = this; var this$ = this; return cljs.core._lookup.call(null,this$,k); }); om.core.IndexedCursor.prototype.cljs$core$IFn$_invoke$arity$2 = (function (k,not_found){ var self__ = this; var this$ = this; return cljs.core._lookup.call(null,this$,k,not_found); }); om.core.IndexedCursor.prototype.cljs$core$IDeref$_deref$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return cljs.core.get_in.call(null,cljs.core.deref.call(null,self__.state),self__.path,new cljs.core.Keyword("om.core","invalid","om.core/invalid",1948827993)); }); om.core.IndexedCursor.cljs$lang$type = true; om.core.IndexedCursor.cljs$lang$ctorStr = "om.core/IndexedCursor"; om.core.IndexedCursor.cljs$lang$ctorPrWriter = (function (this__18435__auto__,writer__18436__auto__,opt__18437__auto__){ return cljs.core._write.call(null,writer__18436__auto__,"om.core/IndexedCursor"); }); om.core.__GT_IndexedCursor = (function om$core$__GT_IndexedCursor(value,state,path){ return (new om.core.IndexedCursor(value,state,path)); }); om.core.to_cursor_STAR_ = (function om$core$to_cursor_STAR_(val,state,path){ var x20210 = cljs.core.clone.call(null,val); x20210.cljs$core$IEquiv$ = true; x20210.cljs$core$IEquiv$_equiv$arity$2 = ((function (x20210){ return (function (_,other){ var ___$1 = this; if(om.core.cursor_QMARK_.call(null,other)){ return cljs.core._EQ_.call(null,val,om.core._value.call(null,other)); } else { return cljs.core._EQ_.call(null,val,other); } });})(x20210)) ; x20210.om$core$ITransact$ = true; x20210.om$core$ITransact$_transact_BANG_$arity$4 = ((function (x20210){ return (function (this$,korks,f,tag){ var this$__$1 = this; return om.core.transact_STAR_.call(null,state,this$__$1,korks,f,tag); });})(x20210)) ; x20210.om$core$ICursor$ = true; x20210.om$core$ICursor$_path$arity$1 = ((function (x20210){ return (function (_){ var ___$1 = this; return path; });})(x20210)) ; x20210.om$core$ICursor$_state$arity$1 = ((function (x20210){ return (function (_){ var ___$1 = this; return state; });})(x20210)) ; x20210.cljs$core$IDeref$ = true; x20210.cljs$core$IDeref$_deref$arity$1 = ((function (x20210){ return (function (this$){ var this$__$1 = this; return cljs.core.get_in.call(null,cljs.core.deref.call(null,state),path,new cljs.core.Keyword("om.core","invalid","om.core/invalid",1948827993)); });})(x20210)) ; return x20210; }); om.core.to_cursor = (function() { var om$core$to_cursor = null; var om$core$to_cursor__1 = (function (val){ return om$core$to_cursor.call(null,val,null,cljs.core.PersistentVector.EMPTY); }); var om$core$to_cursor__2 = (function (val,state){ return om$core$to_cursor.call(null,val,state,cljs.core.PersistentVector.EMPTY); }); var om$core$to_cursor__3 = (function (val,state,path){ if(om.core.cursor_QMARK_.call(null,val)){ return val; } else { if((function (){var G__20213 = val; if(G__20213){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20213.om$core$IToCursor$; } })())){ return true; } else { if((!G__20213.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IToCursor,G__20213); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IToCursor,G__20213); } })()){ return om.core._to_cursor.call(null,val,state,path); } else { if(cljs.core.indexed_QMARK_.call(null,val)){ return (new om.core.IndexedCursor(val,state,path)); } else { if(cljs.core.map_QMARK_.call(null,val)){ return (new om.core.MapCursor(val,state,path)); } else { if((function (){var G__20214 = val; if(G__20214){ var bit__18530__auto__ = (G__20214.cljs$lang$protocol_mask$partition1$ & (8192)); if((bit__18530__auto__) || (G__20214.cljs$core$ICloneable$)){ return true; } else { if((!G__20214.cljs$lang$protocol_mask$partition1$)){ return cljs.core.native_satisfies_QMARK_.call(null,cljs.core.ICloneable,G__20214); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,cljs.core.ICloneable,G__20214); } })()){ return om.core.to_cursor_STAR_.call(null,val,state,path); } else { return val; } } } } } }); om$core$to_cursor = function(val,state,path){ switch(arguments.length){ case 1: return om$core$to_cursor__1.call(this,val); case 2: return om$core$to_cursor__2.call(this,val,state); case 3: return om$core$to_cursor__3.call(this,val,state,path); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$to_cursor.cljs$core$IFn$_invoke$arity$1 = om$core$to_cursor__1; om$core$to_cursor.cljs$core$IFn$_invoke$arity$2 = om$core$to_cursor__2; om$core$to_cursor.cljs$core$IFn$_invoke$arity$3 = om$core$to_cursor__3; return om$core$to_cursor; })() ; om.core.notify_STAR_ = (function om$core$notify_STAR_(cursor,tx_data){ var state = om.core._state.call(null,cursor); return om.core._notify_BANG_.call(null,state,tx_data,om.core.to_cursor.call(null,cljs.core.deref.call(null,state),state)); }); /** * Given an application state atom return a root cursor for it. */ om.core.root_cursor = (function om$core$root_cursor(atom){ if((function (){var G__20216 = atom; if(G__20216){ var bit__18530__auto__ = (G__20216.cljs$lang$protocol_mask$partition0$ & (32768)); if((bit__18530__auto__) || (G__20216.cljs$core$IDeref$)){ return true; } else { if((!G__20216.cljs$lang$protocol_mask$partition0$)){ return cljs.core.native_satisfies_QMARK_.call(null,cljs.core.IDeref,G__20216); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,cljs.core.IDeref,G__20216); } })()){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"satisfies?","satisfies?",-433227199,null),new cljs.core.Symbol(null,"IDeref","IDeref",1738423197,null),new cljs.core.Symbol(null,"atom","atom",1243487874,null))))].join(''))); } return om.core.to_cursor.call(null,cljs.core.deref.call(null,atom),atom,cljs.core.PersistentVector.EMPTY); }); om.core._refs = cljs.core.atom.call(null,cljs.core.PersistentArrayMap.EMPTY); om.core.ref_sub_cursor = (function om$core$ref_sub_cursor(x,parent){ var x20218 = cljs.core.clone.call(null,x); x20218.om$core$ITransact$ = true; x20218.om$core$ITransact$_transact_BANG_$arity$4 = ((function (x20218){ return (function (cursor,korks,f,tag){ var cursor__$1 = this; om.core.commit_BANG_.call(null,cursor__$1,korks,f); return om.core._refresh_deps_BANG_.call(null,parent); });})(x20218)) ; x20218.om$core$ICursorDerive$ = true; x20218.om$core$ICursorDerive$_derive$arity$4 = ((function (x20218){ return (function (this$,derived,state,path){ var this$__$1 = this; var cursor_SINGLEQUOTE_ = om.core.to_cursor.call(null,derived,state,path); if(om.core.cursor_QMARK_.call(null,cursor_SINGLEQUOTE_)){ return om.core.adapt.call(null,this$__$1,cursor_SINGLEQUOTE_); } else { return cursor_SINGLEQUOTE_; } });})(x20218)) ; x20218.om$core$IAdapt$ = true; x20218.om$core$IAdapt$_adapt$arity$2 = ((function (x20218){ return (function (this$,other){ var this$__$1 = this; return om$core$ref_sub_cursor.call(null,om.core.adapt.call(null,x,other),parent); });})(x20218)) ; x20218.cljs$core$ICloneable$ = true; x20218.cljs$core$ICloneable$_clone$arity$1 = ((function (x20218){ return (function (this$){ var this$__$1 = this; return om$core$ref_sub_cursor.call(null,cljs.core.clone.call(null,x),parent); });})(x20218)) ; return x20218; }); /** * Given a cursor return a reference cursor that inherits all of the * properties and methods of the cursor. Reference cursors may be * observed via om.core/observe. */ om.core.ref_cursor = (function om$core$ref_cursor(cursor){ if(om.core.cursor_QMARK_.call(null,cursor)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"cursor?","cursor?",-648342688,null),new cljs.core.Symbol(null,"cursor","cursor",-1642498285,null))))].join(''))); } if((function (){var G__20225 = cursor; if(G__20225){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20225.om$core$IOmRef$; } })())){ return true; } else { if((!G__20225.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IOmRef,G__20225); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IOmRef,G__20225); } })()){ return cursor; } else { var path = om.core.path.call(null,cursor); var storage = cljs.core.get.call(null,cljs.core.swap_BANG_.call(null,om.core._refs,cljs.core.update_in,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [path], null),cljs.core.fnil.call(null,cljs.core.identity,cljs.core.atom.call(null,cljs.core.PersistentArrayMap.EMPTY))),path); var x20226 = cljs.core.clone.call(null,cursor); x20226.om$core$ITransact$ = true; x20226.om$core$ITransact$_transact_BANG_$arity$4 = ((function (x20226,path,storage){ return (function (cursor__$1,korks,f,tag){ var cursor__$2 = this; om.core.commit_BANG_.call(null,cursor__$2,korks,f); return om.core._refresh_deps_BANG_.call(null,cursor__$2); });})(x20226,path,storage)) ; x20226.om$core$IOmRef$ = true; x20226.om$core$IOmRef$_add_dep_BANG_$arity$2 = ((function (x20226,path,storage){ return (function (_,c){ var ___$1 = this; return cljs.core.swap_BANG_.call(null,storage,cljs.core.assoc,om.core.id.call(null,c),c); });})(x20226,path,storage)) ; x20226.om$core$IOmRef$_remove_dep_BANG_$arity$2 = ((function (x20226,path,storage){ return (function (_,c){ var ___$1 = this; var m = cljs.core.swap_BANG_.call(null,storage,cljs.core.dissoc,om.core.id.call(null,c)); if((cljs.core.count.call(null,m) === (0))){ return cljs.core.swap_BANG_.call(null,om.core._refs,cljs.core.dissoc,path); } else { return null; } });})(x20226,path,storage)) ; x20226.om$core$IOmRef$_refresh_deps_BANG_$arity$1 = ((function (x20226,path,storage){ return (function (_){ var ___$1 = this; var seq__20227 = cljs.core.seq.call(null,cljs.core.vals.call(null,cljs.core.deref.call(null,storage))); var chunk__20228 = null; var count__20229 = (0); var i__20230 = (0); while(true){ if((i__20230 < count__20229)){ var c = cljs.core._nth.call(null,chunk__20228,i__20230); om.core._queue_render_BANG_.call(null,om.core.state.call(null,cursor),c); var G__20231 = seq__20227; var G__20232 = chunk__20228; var G__20233 = count__20229; var G__20234 = (i__20230 + (1)); seq__20227 = G__20231; chunk__20228 = G__20232; count__20229 = G__20233; i__20230 = G__20234; continue; } else { var temp__4126__auto__ = cljs.core.seq.call(null,seq__20227); if(temp__4126__auto__){ var seq__20227__$1 = temp__4126__auto__; if(cljs.core.chunked_seq_QMARK_.call(null,seq__20227__$1)){ var c__18641__auto__ = cljs.core.chunk_first.call(null,seq__20227__$1); var G__20235 = cljs.core.chunk_rest.call(null,seq__20227__$1); var G__20236 = c__18641__auto__; var G__20237 = cljs.core.count.call(null,c__18641__auto__); var G__20238 = (0); seq__20227 = G__20235; chunk__20228 = G__20236; count__20229 = G__20237; i__20230 = G__20238; continue; } else { var c = cljs.core.first.call(null,seq__20227__$1); om.core._queue_render_BANG_.call(null,om.core.state.call(null,cursor),c); var G__20239 = cljs.core.next.call(null,seq__20227__$1); var G__20240 = null; var G__20241 = (0); var G__20242 = (0); seq__20227 = G__20239; chunk__20228 = G__20240; count__20229 = G__20241; i__20230 = G__20242; continue; } } else { return null; } } break; } });})(x20226,path,storage)) ; x20226.om$core$IOmRef$_get_deps$arity$1 = ((function (x20226,path,storage){ return (function (_){ var ___$1 = this; return cljs.core.deref.call(null,storage); });})(x20226,path,storage)) ; x20226.om$core$ICursorDerive$ = true; x20226.om$core$ICursorDerive$_derive$arity$4 = ((function (x20226,path,storage){ return (function (this$,derived,state,path__$1){ var this$__$1 = this; var cursor_SINGLEQUOTE_ = om.core.to_cursor.call(null,derived,state,path__$1); if(om.core.cursor_QMARK_.call(null,cursor_SINGLEQUOTE_)){ return om.core.ref_sub_cursor.call(null,cursor_SINGLEQUOTE_,this$__$1); } else { return cursor_SINGLEQUOTE_; } });})(x20226,path,storage)) ; return x20226; } }); om.core.add_ref_to_component_BANG_ = (function om$core$add_ref_to_component_BANG_(c,ref){ var state = c.state; var refs = (function (){var or__17856__auto__ = (state["__om_refs"]); if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return cljs.core.PersistentHashSet.EMPTY; } })(); if(cljs.core.contains_QMARK_.call(null,refs,ref)){ return null; } else { return (state["__om_refs"] = cljs.core.conj.call(null,refs,ref)); } }); om.core.remove_ref_from_component_BANG_ = (function om$core$remove_ref_from_component_BANG_(c,ref){ var state = c.state; var refs = (state["__om_refs"]); if(cljs.core.contains_QMARK_.call(null,refs,ref)){ return (state["__om_refs"] = cljs.core.disj.call(null,refs,ref)); } else { return null; } }); /** * Given a component and a reference cursor have the component observe * the reference cursor for any data changes. */ om.core.observe = (function om$core$observe(c,ref){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,c))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"c","c",-122660552,null))))].join(''))); } if(om.core.cursor_QMARK_.call(null,ref)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"cursor?","cursor?",-648342688,null),new cljs.core.Symbol(null,"ref","ref",-1364538802,null))))].join(''))); } om.core.add_ref_to_component_BANG_.call(null,c,ref); om.core._add_dep_BANG_.call(null,ref,c); return ref; }); om.core.unobserve = (function om$core$unobserve(c,ref){ om.core.remove_ref_from_component_BANG_.call(null,c,ref); om.core._remove_dep_BANG_.call(null,ref,c); return ref; }); om.core.refresh_queued = false; om.core.refresh_set = cljs.core.atom.call(null,cljs.core.PersistentHashSet.EMPTY); om.core.get_renderT = (function om$core$get_renderT(state){ var or__17856__auto__ = state.om$render$T; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return (0); } }); /** * Force a render of *all* roots. Usage of this function is almost * never recommended. */ om.core.render_all = (function() { var om$core$render_all = null; var om$core$render_all__0 = (function (){ return om$core$render_all.call(null,null); }); var om$core$render_all__1 = (function (state){ om.core.refresh_queued = false; var seq__20247_20251 = cljs.core.seq.call(null,cljs.core.deref.call(null,om.core.refresh_set)); var chunk__20248_20252 = null; var count__20249_20253 = (0); var i__20250_20254 = (0); while(true){ if((i__20250_20254 < count__20249_20253)){ var f_20255 = cljs.core._nth.call(null,chunk__20248_20252,i__20250_20254); f_20255.call(null); var G__20256 = seq__20247_20251; var G__20257 = chunk__20248_20252; var G__20258 = count__20249_20253; var G__20259 = (i__20250_20254 + (1)); seq__20247_20251 = G__20256; chunk__20248_20252 = G__20257; count__20249_20253 = G__20258; i__20250_20254 = G__20259; continue; } else { var temp__4126__auto___20260 = cljs.core.seq.call(null,seq__20247_20251); if(temp__4126__auto___20260){ var seq__20247_20261__$1 = temp__4126__auto___20260; if(cljs.core.chunked_seq_QMARK_.call(null,seq__20247_20261__$1)){ var c__18641__auto___20262 = cljs.core.chunk_first.call(null,seq__20247_20261__$1); var G__20263 = cljs.core.chunk_rest.call(null,seq__20247_20261__$1); var G__20264 = c__18641__auto___20262; var G__20265 = cljs.core.count.call(null,c__18641__auto___20262); var G__20266 = (0); seq__20247_20251 = G__20263; chunk__20248_20252 = G__20264; count__20249_20253 = G__20265; i__20250_20254 = G__20266; continue; } else { var f_20267 = cljs.core.first.call(null,seq__20247_20261__$1); f_20267.call(null); var G__20268 = cljs.core.next.call(null,seq__20247_20261__$1); var G__20269 = null; var G__20270 = (0); var G__20271 = (0); seq__20247_20251 = G__20268; chunk__20248_20252 = G__20269; count__20249_20253 = G__20270; i__20250_20254 = G__20271; continue; } } else { } } break; } if((state == null)){ return null; } else { return state.om$render$T = (om.core.get_renderT.call(null,state) + (1)); } }); om$core$render_all = function(state){ switch(arguments.length){ case 0: return om$core$render_all__0.call(this); case 1: return om$core$render_all__1.call(this,state); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$render_all.cljs$core$IFn$_invoke$arity$0 = om$core$render_all__0; om$core$render_all.cljs$core$IFn$_invoke$arity$1 = om$core$render_all__1; return om$core$render_all; })() ; om.core.roots = cljs.core.atom.call(null,cljs.core.PersistentArrayMap.EMPTY); om.core.valid_component_QMARK_ = (function om$core$valid_component_QMARK_(x,f){ if((function (){var or__17856__auto__ = (function (){var G__20278 = x; if(G__20278){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20278.om$core$IRender$; } })())){ return true; } else { if((!G__20278.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRender,G__20278); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRender,G__20278); } })(); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (function (){var G__20280 = x; if(G__20280){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto____$1 = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto____$1)){ return or__17856__auto____$1; } else { return G__20280.om$core$IRenderProps$; } })())){ return true; } else { if((!G__20280.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRenderProps,G__20280); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRenderProps,G__20280); } })(); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { var G__20281 = x; if(G__20281){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto____$2 = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto____$2)){ return or__17856__auto____$2; } else { return G__20281.om$core$IRenderState$; } })())){ return true; } else { if((!G__20281.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRenderState,G__20281); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRenderState,G__20281); } } } })()){ return null; } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str([cljs.core.str("Invalid Om component fn, "),cljs.core.str(f.name),cljs.core.str(" does not return valid instance")].join('')),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"or","or",1876275696,null),cljs.core.list(new cljs.core.Symbol(null,"satisfies?","satisfies?",-433227199,null),new cljs.core.Symbol(null,"IRender","IRender",590822196,null),new cljs.core.Symbol(null,"x","x",-555367584,null)),cljs.core.list(new cljs.core.Symbol(null,"satisfies?","satisfies?",-433227199,null),new cljs.core.Symbol(null,"IRenderProps","IRenderProps",2115139472,null),new cljs.core.Symbol(null,"x","x",-555367584,null)),cljs.core.list(new cljs.core.Symbol(null,"satisfies?","satisfies?",-433227199,null),new cljs.core.Symbol(null,"IRenderState","IRenderState",-897673898,null),new cljs.core.Symbol(null,"x","x",-555367584,null)))))].join(''))); } }); om.core.valid_opts_QMARK_ = (function om$core$valid_opts_QMARK_(m){ return cljs.core.every_QMARK_.call(null,new cljs.core.PersistentHashSet(null, new cljs.core.PersistentArrayMap(null, 11, [new cljs.core.Keyword(null,"descriptor","descriptor",76122018),null,new cljs.core.Keyword(null,"fn","fn",-1175266204),null,new cljs.core.Keyword(null,"instrument","instrument",-960698844),null,new cljs.core.Keyword(null,"react-key","react-key",1337881348),null,new cljs.core.Keyword(null,"key","key",-1516042587),null,new cljs.core.Keyword(null,"init-state","init-state",1450863212),null,new cljs.core.Keyword(null,"state","state",-1988618099),null,new cljs.core.Keyword(null,"key-fn","key-fn",-636154479),null,new cljs.core.Keyword(null,"opts","opts",155075701),null,new cljs.core.Keyword("om.core","index","om.core/index",-1724175434),null,new cljs.core.Keyword(null,"shared","shared",-384145993),null], null), null),cljs.core.keys.call(null,m)); }); om.core.id = (function om$core$id(owner){ return (owner.state["__om_id"]); }); om.core.get_descriptor = (function() { var om$core$get_descriptor = null; var om$core$get_descriptor__1 = (function (f){ return om$core$get_descriptor.call(null,f,null); }); var om$core$get_descriptor__2 = (function (f,descriptor){ if(((f["om$descriptor"]) == null)){ (f["om$descriptor"] = React.createFactory(React.createClass((function (){var or__17856__auto__ = descriptor; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { var or__17856__auto____$1 = om.core._STAR_descriptor_STAR_; if(cljs.core.truth_(or__17856__auto____$1)){ return or__17856__auto____$1; } else { return om.core.pure_descriptor; } } })()))); } else { } return (f["om$descriptor"]); }); om$core$get_descriptor = function(f,descriptor){ switch(arguments.length){ case 1: return om$core$get_descriptor__1.call(this,f); case 2: return om$core$get_descriptor__2.call(this,f,descriptor); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$get_descriptor.cljs$core$IFn$_invoke$arity$1 = om$core$get_descriptor__1; om$core$get_descriptor.cljs$core$IFn$_invoke$arity$2 = om$core$get_descriptor__2; return om$core$get_descriptor; })() ; om.core.getf = (function() { var om$core$getf = null; var om$core$getf__2 = (function (f,cursor){ if((f instanceof cljs.core.MultiFn)){ var dv = f.dispatch_fn.call(null,cursor,null); return cljs.core.get_method.call(null,f,dv); } else { return f; } }); var om$core$getf__3 = (function (f,cursor,opts){ if((f instanceof cljs.core.MultiFn)){ var dv = f.dispatch_fn.call(null,cursor,null,opts); return cljs.core.get_method.call(null,f,dv); } else { return f; } }); om$core$getf = function(f,cursor,opts){ switch(arguments.length){ case 2: return om$core$getf__2.call(this,f,cursor); case 3: return om$core$getf__3.call(this,f,cursor,opts); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$getf.cljs$core$IFn$_invoke$arity$2 = om$core$getf__2; om$core$getf.cljs$core$IFn$_invoke$arity$3 = om$core$getf__3; return om$core$getf; })() ; om.core.build_STAR_ = (function() { var om$core$build_STAR_ = null; var om$core$build_STAR___2 = (function (f,cursor){ return om$core$build_STAR_.call(null,f,cursor,null); }); var om$core$build_STAR___3 = (function (f,cursor,m){ if(cljs.core.ifn_QMARK_.call(null,f)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"f","f",43394975,null))))].join(''))); } if(((m == null)) || (cljs.core.map_QMARK_.call(null,m))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"or","or",1876275696,null),cljs.core.list(new cljs.core.Symbol(null,"nil?","nil?",1612038930,null),new cljs.core.Symbol(null,"m","m",-1021758608,null)),cljs.core.list(new cljs.core.Symbol(null,"map?","map?",-1780568534,null),new cljs.core.Symbol(null,"m","m",-1021758608,null)))))].join(''))); } if(om.core.valid_opts_QMARK_.call(null,m)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.apply.call(null,cljs.core.str,"build options contains invalid keys, only :key, :key-fn :react-key, ",":fn, :init-state, :state, and :opts allowed, given ",cljs.core.interpose.call(null,", ",cljs.core.keys.call(null,m)))),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"valid-opts?","valid-opts?",1000038576,null),new cljs.core.Symbol(null,"m","m",-1021758608,null))))].join(''))); } if((m == null)){ var shared = om.core.get_shared.call(null,om.core._STAR_parent_STAR_); var ctor = om.core.get_descriptor.call(null,om.core.getf.call(null,f,cursor)); return ctor.call(null,{"children": ((function (shared,ctor){ return (function (this$){ var ret = f.call(null,cursor,this$); om.core.valid_component_QMARK_.call(null,ret,f); return ret; });})(shared,ctor)) , "__om_instrument": om.core._STAR_instrument_STAR_, "__om_descriptor": om.core._STAR_descriptor_STAR_, "__om_app_state": om.core._STAR_state_STAR_, "__om_root_key": om.core._STAR_root_key_STAR_, "__om_shared": shared, "__om_cursor": cursor}); } else { var map__20283 = m; var map__20283__$1 = ((cljs.core.seq_QMARK_.call(null,map__20283))?cljs.core.apply.call(null,cljs.core.hash_map,map__20283):map__20283); var opts = cljs.core.get.call(null,map__20283__$1,new cljs.core.Keyword(null,"opts","opts",155075701)); var init_state = cljs.core.get.call(null,map__20283__$1,new cljs.core.Keyword(null,"init-state","init-state",1450863212)); var state = cljs.core.get.call(null,map__20283__$1,new cljs.core.Keyword(null,"state","state",-1988618099)); var key_fn = cljs.core.get.call(null,map__20283__$1,new cljs.core.Keyword(null,"key-fn","key-fn",-636154479)); var key = cljs.core.get.call(null,map__20283__$1,new cljs.core.Keyword(null,"key","key",-1516042587)); var dataf = cljs.core.get.call(null,m,new cljs.core.Keyword(null,"fn","fn",-1175266204)); var cursor_SINGLEQUOTE_ = ((!((dataf == null)))?(function (){var temp__4124__auto__ = new cljs.core.Keyword("om.core","index","om.core/index",-1724175434).cljs$core$IFn$_invoke$arity$1(m); if(cljs.core.truth_(temp__4124__auto__)){ var i = temp__4124__auto__; return dataf.call(null,cursor,i); } else { return dataf.call(null,cursor); } })():cursor); var rkey = ((!((key == null)))?cljs.core.get.call(null,cursor_SINGLEQUOTE_,key):((!((key_fn == null)))?key_fn.call(null,cursor_SINGLEQUOTE_):cljs.core.get.call(null,m,new cljs.core.Keyword(null,"react-key","react-key",1337881348)) )); var shared = (function (){var or__17856__auto__ = new cljs.core.Keyword(null,"shared","shared",-384145993).cljs$core$IFn$_invoke$arity$1(m); if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return om.core.get_shared.call(null,om.core._STAR_parent_STAR_); } })(); var ctor = om.core.get_descriptor.call(null,om.core.getf.call(null,f,cursor_SINGLEQUOTE_,opts),new cljs.core.Keyword(null,"descriptor","descriptor",76122018).cljs$core$IFn$_invoke$arity$1(m)); return ctor.call(null,{"__om_state": state, "__om_instrument": om.core._STAR_instrument_STAR_, "children": (((opts == null))?((function (map__20283,map__20283__$1,opts,init_state,state,key_fn,key,dataf,cursor_SINGLEQUOTE_,rkey,shared,ctor){ return (function (this$){ var ret = f.call(null,cursor_SINGLEQUOTE_,this$); om.core.valid_component_QMARK_.call(null,ret,f); return ret; });})(map__20283,map__20283__$1,opts,init_state,state,key_fn,key,dataf,cursor_SINGLEQUOTE_,rkey,shared,ctor)) :((function (map__20283,map__20283__$1,opts,init_state,state,key_fn,key,dataf,cursor_SINGLEQUOTE_,rkey,shared,ctor){ return (function (this$){ var ret = f.call(null,cursor_SINGLEQUOTE_,this$,opts); om.core.valid_component_QMARK_.call(null,ret,f); return ret; });})(map__20283,map__20283__$1,opts,init_state,state,key_fn,key,dataf,cursor_SINGLEQUOTE_,rkey,shared,ctor)) ), "__om_init_state": init_state, "key": (function (){var or__17856__auto__ = rkey; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return undefined; } })(), "__om_app_state": om.core._STAR_state_STAR_, "__om_cursor": cursor_SINGLEQUOTE_, "__om_index": new cljs.core.Keyword("om.core","index","om.core/index",-1724175434).cljs$core$IFn$_invoke$arity$1(m), "__om_shared": shared, "__om_descriptor": om.core._STAR_descriptor_STAR_, "__om_root_key": om.core._STAR_root_key_STAR_}); } }); om$core$build_STAR_ = function(f,cursor,m){ switch(arguments.length){ case 2: return om$core$build_STAR___2.call(this,f,cursor); case 3: return om$core$build_STAR___3.call(this,f,cursor,m); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$build_STAR_.cljs$core$IFn$_invoke$arity$2 = om$core$build_STAR___2; om$core$build_STAR_.cljs$core$IFn$_invoke$arity$3 = om$core$build_STAR___3; return om$core$build_STAR_; })() ; /** * Builds an Om component. Takes an IRender/IRenderState instance * returning function f, a value, and an optional third argument * which may be a map of build specifications. * * f - is a function of 2 or 3 arguments. The first argument can be * any value and the second argument will be the owning pure node. * If a map of options m is passed in this will be the third * argument. f must return at a minimum an IRender or IRenderState * instance, this instance may implement other React life cycle * protocols. * * x - any value * * m - a map the following keys are allowed: * * :key - a keyword that should be used to look up the key used by * React itself when rendering sequential things. * :react-key - an explicit react key * :fn - a function to apply to the data before invoking f. * :init-state - a map of initial state to pass to the component. * :state - a map of state to pass to the component, will be merged in. * :opts - a map of values. Can be used to pass side information down * the render tree. * :descriptor - a JS object of React methods, will be used to * construct a React class per Om component function * encountered. defaults to pure-descriptor. * * Example: * * (build list-of-gadgets x * {:init-state {:event-chan ... * :narble ...}}) * */ om.core.build = (function() { var om$core$build = null; var om$core$build__2 = (function (f,x){ return om$core$build.call(null,f,x,null); }); var om$core$build__3 = (function (f,x,m){ if(cljs.core.ifn_QMARK_.call(null,f)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"f","f",43394975,null))))].join(''))); } if(((m == null)) || (cljs.core.map_QMARK_.call(null,m))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"or","or",1876275696,null),cljs.core.list(new cljs.core.Symbol(null,"nil?","nil?",1612038930,null),new cljs.core.Symbol(null,"m","m",-1021758608,null)),cljs.core.list(new cljs.core.Symbol(null,"map?","map?",-1780568534,null),new cljs.core.Symbol(null,"m","m",-1021758608,null)))))].join(''))); } if(!((om.core._STAR_instrument_STAR_ == null))){ var ret = om.core._STAR_instrument_STAR_.call(null,f,x,m); if(cljs.core._EQ_.call(null,ret,new cljs.core.Keyword("om.core","pass","om.core/pass",-1453289268))){ return om.core.build_STAR_.call(null,f,x,m); } else { return ret; } } else { return om.core.build_STAR_.call(null,f,x,m); } }); om$core$build = function(f,x,m){ switch(arguments.length){ case 2: return om$core$build__2.call(this,f,x); case 3: return om$core$build__3.call(this,f,x,m); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$build.cljs$core$IFn$_invoke$arity$2 = om$core$build__2; om$core$build.cljs$core$IFn$_invoke$arity$3 = om$core$build__3; return om$core$build; })() ; /** * Build a sequence of components. f is the component constructor * function, xs a sequence of values, and m a map of options the * same as provided to om.core/build. */ om.core.build_all = (function() { var om$core$build_all = null; var om$core$build_all__2 = (function (f,xs){ return om$core$build_all.call(null,f,xs,null); }); var om$core$build_all__3 = (function (f,xs,m){ if(cljs.core.ifn_QMARK_.call(null,f)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"f","f",43394975,null))))].join(''))); } if(((m == null)) || (cljs.core.map_QMARK_.call(null,m))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"or","or",1876275696,null),cljs.core.list(new cljs.core.Symbol(null,"nil?","nil?",1612038930,null),new cljs.core.Symbol(null,"m","m",-1021758608,null)),cljs.core.list(new cljs.core.Symbol(null,"map?","map?",-1780568534,null),new cljs.core.Symbol(null,"m","m",-1021758608,null)))))].join(''))); } return cljs.core.map.call(null,(function (x,i){ return om.core.build.call(null,f,x,cljs.core.assoc.call(null,m,new cljs.core.Keyword("om.core","index","om.core/index",-1724175434),i)); }),xs,cljs.core.range.call(null)); }); om$core$build_all = function(f,xs,m){ switch(arguments.length){ case 2: return om$core$build_all__2.call(this,f,xs); case 3: return om$core$build_all__3.call(this,f,xs,m); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$build_all.cljs$core$IFn$_invoke$arity$2 = om$core$build_all__2; om$core$build_all.cljs$core$IFn$_invoke$arity$3 = om$core$build_all__3; return om$core$build_all; })() ; om.core.setup = (function om$core$setup(state,key,tx_listen){ if((function (){var G__20292 = state; if(G__20292){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20292.om$core$INotify$; } })())){ return true; } else { if((!G__20292.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.INotify,G__20292); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.INotify,G__20292); } })()){ } else { var properties_20300 = cljs.core.atom.call(null,cljs.core.PersistentArrayMap.EMPTY); var listeners_20301 = cljs.core.atom.call(null,cljs.core.PersistentArrayMap.EMPTY); var render_queue_20302 = cljs.core.atom.call(null,cljs.core.PersistentHashSet.EMPTY); var x20293_20303 = state; x20293_20303.om$core$IRenderQueue$ = true; x20293_20303.om$core$IRenderQueue$_get_queue$arity$1 = ((function (x20293_20303,properties_20300,listeners_20301,render_queue_20302){ return (function (this$){ var this$__$1 = this; return cljs.core.deref.call(null,render_queue_20302); });})(x20293_20303,properties_20300,listeners_20301,render_queue_20302)) ; x20293_20303.om$core$IRenderQueue$_queue_render_BANG_$arity$2 = ((function (x20293_20303,properties_20300,listeners_20301,render_queue_20302){ return (function (this$,c){ var this$__$1 = this; if(cljs.core.contains_QMARK_.call(null,cljs.core.deref.call(null,render_queue_20302),c)){ return null; } else { cljs.core.swap_BANG_.call(null,render_queue_20302,cljs.core.conj,c); return cljs.core.swap_BANG_.call(null,this$__$1,cljs.core.identity); } });})(x20293_20303,properties_20300,listeners_20301,render_queue_20302)) ; x20293_20303.om$core$IRenderQueue$_empty_queue_BANG_$arity$1 = ((function (x20293_20303,properties_20300,listeners_20301,render_queue_20302){ return (function (this$){ var this$__$1 = this; return cljs.core.swap_BANG_.call(null,render_queue_20302,cljs.core.empty); });})(x20293_20303,properties_20300,listeners_20301,render_queue_20302)) ; x20293_20303.om$core$INotify$ = true; x20293_20303.om$core$INotify$_listen_BANG_$arity$3 = ((function (x20293_20303,properties_20300,listeners_20301,render_queue_20302){ return (function (this$,key__$1,tx_listen__$1){ var this$__$1 = this; if((tx_listen__$1 == null)){ } else { cljs.core.swap_BANG_.call(null,listeners_20301,cljs.core.assoc,key__$1,tx_listen__$1); } return this$__$1; });})(x20293_20303,properties_20300,listeners_20301,render_queue_20302)) ; x20293_20303.om$core$INotify$_unlisten_BANG_$arity$2 = ((function (x20293_20303,properties_20300,listeners_20301,render_queue_20302){ return (function (this$,key__$1){ var this$__$1 = this; cljs.core.swap_BANG_.call(null,listeners_20301,cljs.core.dissoc,key__$1); return this$__$1; });})(x20293_20303,properties_20300,listeners_20301,render_queue_20302)) ; x20293_20303.om$core$INotify$_notify_BANG_$arity$3 = ((function (x20293_20303,properties_20300,listeners_20301,render_queue_20302){ return (function (this$,tx_data,root_cursor){ var this$__$1 = this; var seq__20294_20304 = cljs.core.seq.call(null,cljs.core.deref.call(null,listeners_20301)); var chunk__20295_20305 = null; var count__20296_20306 = (0); var i__20297_20307 = (0); while(true){ if((i__20297_20307 < count__20296_20306)){ var vec__20298_20308 = cljs.core._nth.call(null,chunk__20295_20305,i__20297_20307); var __20309 = cljs.core.nth.call(null,vec__20298_20308,(0),null); var f_20310 = cljs.core.nth.call(null,vec__20298_20308,(1),null); f_20310.call(null,tx_data,root_cursor); var G__20311 = seq__20294_20304; var G__20312 = chunk__20295_20305; var G__20313 = count__20296_20306; var G__20314 = (i__20297_20307 + (1)); seq__20294_20304 = G__20311; chunk__20295_20305 = G__20312; count__20296_20306 = G__20313; i__20297_20307 = G__20314; continue; } else { var temp__4126__auto___20315 = cljs.core.seq.call(null,seq__20294_20304); if(temp__4126__auto___20315){ var seq__20294_20316__$1 = temp__4126__auto___20315; if(cljs.core.chunked_seq_QMARK_.call(null,seq__20294_20316__$1)){ var c__18641__auto___20317 = cljs.core.chunk_first.call(null,seq__20294_20316__$1); var G__20318 = cljs.core.chunk_rest.call(null,seq__20294_20316__$1); var G__20319 = c__18641__auto___20317; var G__20320 = cljs.core.count.call(null,c__18641__auto___20317); var G__20321 = (0); seq__20294_20304 = G__20318; chunk__20295_20305 = G__20319; count__20296_20306 = G__20320; i__20297_20307 = G__20321; continue; } else { var vec__20299_20322 = cljs.core.first.call(null,seq__20294_20316__$1); var __20323 = cljs.core.nth.call(null,vec__20299_20322,(0),null); var f_20324 = cljs.core.nth.call(null,vec__20299_20322,(1),null); f_20324.call(null,tx_data,root_cursor); var G__20325 = cljs.core.next.call(null,seq__20294_20316__$1); var G__20326 = null; var G__20327 = (0); var G__20328 = (0); seq__20294_20304 = G__20325; chunk__20295_20305 = G__20326; count__20296_20306 = G__20327; i__20297_20307 = G__20328; continue; } } else { } } break; } return this$__$1; });})(x20293_20303,properties_20300,listeners_20301,render_queue_20302)) ; x20293_20303.om$core$IRootProperties$ = true; x20293_20303.om$core$IRootProperties$_set_property_BANG_$arity$4 = ((function (x20293_20303,properties_20300,listeners_20301,render_queue_20302){ return (function (_,id,k,v){ var ___$1 = this; return cljs.core.swap_BANG_.call(null,properties_20300,cljs.core.assoc_in,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [id,k], null),v); });})(x20293_20303,properties_20300,listeners_20301,render_queue_20302)) ; x20293_20303.om$core$IRootProperties$_remove_property_BANG_$arity$3 = ((function (x20293_20303,properties_20300,listeners_20301,render_queue_20302){ return (function (_,id,k){ var ___$1 = this; return cljs.core.swap_BANG_.call(null,properties_20300,cljs.core.dissoc,id,k); });})(x20293_20303,properties_20300,listeners_20301,render_queue_20302)) ; x20293_20303.om$core$IRootProperties$_remove_properties_BANG_$arity$2 = ((function (x20293_20303,properties_20300,listeners_20301,render_queue_20302){ return (function (_,id){ var ___$1 = this; return cljs.core.swap_BANG_.call(null,properties_20300,cljs.core.dissoc,id); });})(x20293_20303,properties_20300,listeners_20301,render_queue_20302)) ; x20293_20303.om$core$IRootProperties$_get_property$arity$3 = ((function (x20293_20303,properties_20300,listeners_20301,render_queue_20302){ return (function (_,id,k){ var ___$1 = this; return cljs.core.get_in.call(null,cljs.core.deref.call(null,properties_20300),new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [id,k], null)); });})(x20293_20303,properties_20300,listeners_20301,render_queue_20302)) ; } return om.core._listen_BANG_.call(null,state,key,tx_listen); }); om.core.tear_down = (function om$core$tear_down(state,key){ return om.core._unlisten_BANG_.call(null,state,key); }); om.core.tag_root_key = (function om$core$tag_root_key(cursor,root_key){ if(om.core.cursor_QMARK_.call(null,cursor)){ var x20330 = cljs.core.clone.call(null,cursor); x20330.om$core$IRootKey$ = true; x20330.om$core$IRootKey$_root_key$arity$1 = ((function (x20330){ return (function (this$){ var this$__$1 = this; return root_key; });})(x20330)) ; x20330.om$core$IAdapt$ = true; x20330.om$core$IAdapt$_adapt$arity$2 = ((function (x20330){ return (function (this$,other){ var this$__$1 = this; return om$core$tag_root_key.call(null,om.core.adapt.call(null,cursor,other),root_key); });})(x20330)) ; x20330.cljs$core$ICloneable$ = true; x20330.cljs$core$ICloneable$_clone$arity$1 = ((function (x20330){ return (function (this$){ var this$__$1 = this; return om$core$tag_root_key.call(null,cljs.core.clone.call(null,cursor),root_key); });})(x20330)) ; return x20330; } else { return cursor; } }); /** * Take a component constructor function f, value an immutable tree of * associative data structures optionally an wrapped in an IAtom * instance, and a map of options and installs an Om/React render * loop. * * f must return an instance that at a minimum implements IRender or * IRenderState (it may implement other React life cycle protocols). f * must take at least two arguments, the root cursor and the owning pure * node. A cursor is just the original data wrapped in an ICursor * instance which maintains path information. Only one root render * loop allowed per target element. om.core/root is idempotent, if * called again on the same target element the previous render loop * will be replaced. * * Options may also include any key allowed by om.core/build to * customize f. In addition om.core/root supports the following * special options: * * :target - (required) a DOM element. * :shared - data to be shared by all components, see om.core/get-shared * :tx-listen - a function that will listen in in transactions, should * take 2 arguments - the first a map containing the * path, old and new state at path, old and new global * state, and transaction tag if provided. * :instrument - a function of three arguments that if provided will * intercept all calls to om.core/build. This function should * correspond to the three arity version of om.core/build. * :adapt - a function to adapt the root cursor * :raf - override requestAnimationFrame based rendering. If * false setTimeout will be use. If given a function * will be invoked instead. * * Example: * * (root * (fn [data owner] * ...) * {:message :hello} * {:target js/document.body}) */ om.core.root = (function om$core$root(f,value,p__20331){ var map__20394 = p__20331; var map__20394__$1 = ((cljs.core.seq_QMARK_.call(null,map__20394))?cljs.core.apply.call(null,cljs.core.hash_map,map__20394):map__20394); var options = map__20394__$1; var raf = cljs.core.get.call(null,map__20394__$1,new cljs.core.Keyword(null,"raf","raf",-1295410152)); var adapt = cljs.core.get.call(null,map__20394__$1,new cljs.core.Keyword(null,"adapt","adapt",-1817022327)); var descriptor = cljs.core.get.call(null,map__20394__$1,new cljs.core.Keyword(null,"descriptor","descriptor",76122018)); var instrument = cljs.core.get.call(null,map__20394__$1,new cljs.core.Keyword(null,"instrument","instrument",-960698844)); var path = cljs.core.get.call(null,map__20394__$1,new cljs.core.Keyword(null,"path","path",-188191168)); var tx_listen = cljs.core.get.call(null,map__20394__$1,new cljs.core.Keyword(null,"tx-listen","tx-listen",119130367)); var target = cljs.core.get.call(null,map__20394__$1,new cljs.core.Keyword(null,"target","target",253001721)); if(cljs.core.ifn_QMARK_.call(null,f)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str("First argument must be a function"),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"f","f",43394975,null))))].join(''))); } if(!((target == null))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str("No target specified to om.core/root"),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"not","not",1044554643,null),cljs.core.list(new cljs.core.Symbol(null,"nil?","nil?",1612038930,null),new cljs.core.Symbol(null,"target","target",1893533248,null)))))].join(''))); } var roots_SINGLEQUOTE__20456 = cljs.core.deref.call(null,om.core.roots); if(cljs.core.contains_QMARK_.call(null,roots_SINGLEQUOTE__20456,target)){ cljs.core.get.call(null,roots_SINGLEQUOTE__20456,target).call(null); } else { } var watch_key = cljs.core.gensym.call(null); var state = (((function (){var G__20395 = value; if(G__20395){ var bit__18530__auto__ = (G__20395.cljs$lang$protocol_mask$partition1$ & (16384)); if((bit__18530__auto__) || (G__20395.cljs$core$IAtom$)){ return true; } else { if((!G__20395.cljs$lang$protocol_mask$partition1$)){ return cljs.core.native_satisfies_QMARK_.call(null,cljs.core.IAtom,G__20395); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,cljs.core.IAtom,G__20395); } })())?value:cljs.core.atom.call(null,value)); var state__$1 = om.core.setup.call(null,state,watch_key,tx_listen); var adapt__$1 = (function (){var or__17856__auto__ = adapt; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return cljs.core.identity; } })(); var m = cljs.core.dissoc.call(null,options,new cljs.core.Keyword(null,"target","target",253001721),new cljs.core.Keyword(null,"tx-listen","tx-listen",119130367),new cljs.core.Keyword(null,"path","path",-188191168),new cljs.core.Keyword(null,"adapt","adapt",-1817022327),new cljs.core.Keyword(null,"raf","raf",-1295410152)); var ret = cljs.core.atom.call(null,null); var rootf = ((function (watch_key,state,state__$1,adapt__$1,m,ret,map__20394,map__20394__$1,options,raf,adapt,descriptor,instrument,path,tx_listen,target){ return (function om$core$root_$_rootf(){ cljs.core.swap_BANG_.call(null,om.core.refresh_set,cljs.core.disj,om$core$root_$_rootf); var value__$1 = cljs.core.deref.call(null,state__$1); var cursor = adapt__$1.call(null,om.core.tag_root_key.call(null,(((path == null))?om.core.to_cursor.call(null,value__$1,state__$1,cljs.core.PersistentVector.EMPTY):om.core.to_cursor.call(null,cljs.core.get_in.call(null,value__$1,path),state__$1,path)),watch_key)); if(cljs.core.truth_(om.core._get_property.call(null,state__$1,watch_key,new cljs.core.Keyword(null,"skip-render-root","skip-render-root",-5219643)))){ } else { var c_20457 = om.dom.render.call(null,(function (){var _STAR_descriptor_STAR_20426 = om.core._STAR_descriptor_STAR_; var _STAR_instrument_STAR_20427 = om.core._STAR_instrument_STAR_; var _STAR_state_STAR_20428 = om.core._STAR_state_STAR_; var _STAR_root_key_STAR_20429 = om.core._STAR_root_key_STAR_; om.core._STAR_descriptor_STAR_ = descriptor; om.core._STAR_instrument_STAR_ = instrument; om.core._STAR_state_STAR_ = state__$1; om.core._STAR_root_key_STAR_ = watch_key; try{return om.core.build.call(null,f,cursor,m); }finally {om.core._STAR_root_key_STAR_ = _STAR_root_key_STAR_20429; om.core._STAR_state_STAR_ = _STAR_state_STAR_20428; om.core._STAR_instrument_STAR_ = _STAR_instrument_STAR_20427; om.core._STAR_descriptor_STAR_ = _STAR_descriptor_STAR_20426; }})(),target); if((cljs.core.deref.call(null,ret) == null)){ cljs.core.reset_BANG_.call(null,ret,c_20457); } else { } } var queue_20458 = om.core._get_queue.call(null,state__$1); om.core._empty_queue_BANG_.call(null,state__$1); if(cljs.core.empty_QMARK_.call(null,queue_20458)){ } else { var seq__20430_20459 = cljs.core.seq.call(null,queue_20458); var chunk__20431_20460 = null; var count__20432_20461 = (0); var i__20433_20462 = (0); while(true){ if((i__20433_20462 < count__20432_20461)){ var c_20463 = cljs.core._nth.call(null,chunk__20431_20460,i__20433_20462); if(cljs.core.truth_(c_20463.isMounted())){ var temp__4126__auto___20464 = (c_20463.state["__om_next_cursor"]); if(cljs.core.truth_(temp__4126__auto___20464)){ var next_props_20465 = temp__4126__auto___20464; (c_20463.props["__om_cursor"] = next_props_20465); (c_20463.state["__om_next_cursor"] = null); } else { } if(cljs.core.truth_((function (){var or__17856__auto__ = !((function (){var G__20435 = om.core.children.call(null,c_20463); if(G__20435){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20435.om$core$ICheckState$; } })())){ return true; } else { if((!G__20435.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.ICheckState,G__20435); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.ICheckState,G__20435); } })()); if(or__17856__auto__){ return or__17856__auto__; } else { return c_20463.shouldComponentUpdate(c_20463.props,c_20463.state); } })())){ c_20463.forceUpdate(); } else { } } else { } var G__20466 = seq__20430_20459; var G__20467 = chunk__20431_20460; var G__20468 = count__20432_20461; var G__20469 = (i__20433_20462 + (1)); seq__20430_20459 = G__20466; chunk__20431_20460 = G__20467; count__20432_20461 = G__20468; i__20433_20462 = G__20469; continue; } else { var temp__4126__auto___20470 = cljs.core.seq.call(null,seq__20430_20459); if(temp__4126__auto___20470){ var seq__20430_20471__$1 = temp__4126__auto___20470; if(cljs.core.chunked_seq_QMARK_.call(null,seq__20430_20471__$1)){ var c__18641__auto___20472 = cljs.core.chunk_first.call(null,seq__20430_20471__$1); var G__20473 = cljs.core.chunk_rest.call(null,seq__20430_20471__$1); var G__20474 = c__18641__auto___20472; var G__20475 = cljs.core.count.call(null,c__18641__auto___20472); var G__20476 = (0); seq__20430_20459 = G__20473; chunk__20431_20460 = G__20474; count__20432_20461 = G__20475; i__20433_20462 = G__20476; continue; } else { var c_20477 = cljs.core.first.call(null,seq__20430_20471__$1); if(cljs.core.truth_(c_20477.isMounted())){ var temp__4126__auto___20478__$1 = (c_20477.state["__om_next_cursor"]); if(cljs.core.truth_(temp__4126__auto___20478__$1)){ var next_props_20479 = temp__4126__auto___20478__$1; (c_20477.props["__om_cursor"] = next_props_20479); (c_20477.state["__om_next_cursor"] = null); } else { } if(cljs.core.truth_((function (){var or__17856__auto__ = !((function (){var G__20437 = om.core.children.call(null,c_20477); if(G__20437){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20437.om$core$ICheckState$; } })())){ return true; } else { if((!G__20437.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.ICheckState,G__20437); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.ICheckState,G__20437); } })()); if(or__17856__auto__){ return or__17856__auto__; } else { return c_20477.shouldComponentUpdate(c_20477.props,c_20477.state); } })())){ c_20477.forceUpdate(); } else { } } else { } var G__20480 = cljs.core.next.call(null,seq__20430_20471__$1); var G__20481 = null; var G__20482 = (0); var G__20483 = (0); seq__20430_20459 = G__20480; chunk__20431_20460 = G__20481; count__20432_20461 = G__20482; i__20433_20462 = G__20483; continue; } } else { } } break; } } var _refs_20484 = cljs.core.deref.call(null,om.core._refs); if(cljs.core.empty_QMARK_.call(null,_refs_20484)){ } else { var seq__20438_20485 = cljs.core.seq.call(null,_refs_20484); var chunk__20439_20486 = null; var count__20440_20487 = (0); var i__20441_20488 = (0); while(true){ if((i__20441_20488 < count__20440_20487)){ var vec__20442_20489 = cljs.core._nth.call(null,chunk__20439_20486,i__20441_20488); var path_20490__$1 = cljs.core.nth.call(null,vec__20442_20489,(0),null); var cs_20491 = cljs.core.nth.call(null,vec__20442_20489,(1),null); var cs_20492__$1 = cljs.core.deref.call(null,cs_20491); var seq__20443_20493 = cljs.core.seq.call(null,cs_20492__$1); var chunk__20444_20494 = null; var count__20445_20495 = (0); var i__20446_20496 = (0); while(true){ if((i__20446_20496 < count__20445_20495)){ var vec__20447_20497 = cljs.core._nth.call(null,chunk__20444_20494,i__20446_20496); var id_20498 = cljs.core.nth.call(null,vec__20447_20497,(0),null); var c_20499 = cljs.core.nth.call(null,vec__20447_20497,(1),null); if(cljs.core.truth_(c_20499.shouldComponentUpdate(c_20499.props,c_20499.state))){ c_20499.forceUpdate(); } else { } var G__20500 = seq__20443_20493; var G__20501 = chunk__20444_20494; var G__20502 = count__20445_20495; var G__20503 = (i__20446_20496 + (1)); seq__20443_20493 = G__20500; chunk__20444_20494 = G__20501; count__20445_20495 = G__20502; i__20446_20496 = G__20503; continue; } else { var temp__4126__auto___20504 = cljs.core.seq.call(null,seq__20443_20493); if(temp__4126__auto___20504){ var seq__20443_20505__$1 = temp__4126__auto___20504; if(cljs.core.chunked_seq_QMARK_.call(null,seq__20443_20505__$1)){ var c__18641__auto___20506 = cljs.core.chunk_first.call(null,seq__20443_20505__$1); var G__20507 = cljs.core.chunk_rest.call(null,seq__20443_20505__$1); var G__20508 = c__18641__auto___20506; var G__20509 = cljs.core.count.call(null,c__18641__auto___20506); var G__20510 = (0); seq__20443_20493 = G__20507; chunk__20444_20494 = G__20508; count__20445_20495 = G__20509; i__20446_20496 = G__20510; continue; } else { var vec__20448_20511 = cljs.core.first.call(null,seq__20443_20505__$1); var id_20512 = cljs.core.nth.call(null,vec__20448_20511,(0),null); var c_20513 = cljs.core.nth.call(null,vec__20448_20511,(1),null); if(cljs.core.truth_(c_20513.shouldComponentUpdate(c_20513.props,c_20513.state))){ c_20513.forceUpdate(); } else { } var G__20514 = cljs.core.next.call(null,seq__20443_20505__$1); var G__20515 = null; var G__20516 = (0); var G__20517 = (0); seq__20443_20493 = G__20514; chunk__20444_20494 = G__20515; count__20445_20495 = G__20516; i__20446_20496 = G__20517; continue; } } else { } } break; } var G__20518 = seq__20438_20485; var G__20519 = chunk__20439_20486; var G__20520 = count__20440_20487; var G__20521 = (i__20441_20488 + (1)); seq__20438_20485 = G__20518; chunk__20439_20486 = G__20519; count__20440_20487 = G__20520; i__20441_20488 = G__20521; continue; } else { var temp__4126__auto___20522 = cljs.core.seq.call(null,seq__20438_20485); if(temp__4126__auto___20522){ var seq__20438_20523__$1 = temp__4126__auto___20522; if(cljs.core.chunked_seq_QMARK_.call(null,seq__20438_20523__$1)){ var c__18641__auto___20524 = cljs.core.chunk_first.call(null,seq__20438_20523__$1); var G__20525 = cljs.core.chunk_rest.call(null,seq__20438_20523__$1); var G__20526 = c__18641__auto___20524; var G__20527 = cljs.core.count.call(null,c__18641__auto___20524); var G__20528 = (0); seq__20438_20485 = G__20525; chunk__20439_20486 = G__20526; count__20440_20487 = G__20527; i__20441_20488 = G__20528; continue; } else { var vec__20449_20529 = cljs.core.first.call(null,seq__20438_20523__$1); var path_20530__$1 = cljs.core.nth.call(null,vec__20449_20529,(0),null); var cs_20531 = cljs.core.nth.call(null,vec__20449_20529,(1),null); var cs_20532__$1 = cljs.core.deref.call(null,cs_20531); var seq__20450_20533 = cljs.core.seq.call(null,cs_20532__$1); var chunk__20451_20534 = null; var count__20452_20535 = (0); var i__20453_20536 = (0); while(true){ if((i__20453_20536 < count__20452_20535)){ var vec__20454_20537 = cljs.core._nth.call(null,chunk__20451_20534,i__20453_20536); var id_20538 = cljs.core.nth.call(null,vec__20454_20537,(0),null); var c_20539 = cljs.core.nth.call(null,vec__20454_20537,(1),null); if(cljs.core.truth_(c_20539.shouldComponentUpdate(c_20539.props,c_20539.state))){ c_20539.forceUpdate(); } else { } var G__20540 = seq__20450_20533; var G__20541 = chunk__20451_20534; var G__20542 = count__20452_20535; var G__20543 = (i__20453_20536 + (1)); seq__20450_20533 = G__20540; chunk__20451_20534 = G__20541; count__20452_20535 = G__20542; i__20453_20536 = G__20543; continue; } else { var temp__4126__auto___20544__$1 = cljs.core.seq.call(null,seq__20450_20533); if(temp__4126__auto___20544__$1){ var seq__20450_20545__$1 = temp__4126__auto___20544__$1; if(cljs.core.chunked_seq_QMARK_.call(null,seq__20450_20545__$1)){ var c__18641__auto___20546 = cljs.core.chunk_first.call(null,seq__20450_20545__$1); var G__20547 = cljs.core.chunk_rest.call(null,seq__20450_20545__$1); var G__20548 = c__18641__auto___20546; var G__20549 = cljs.core.count.call(null,c__18641__auto___20546); var G__20550 = (0); seq__20450_20533 = G__20547; chunk__20451_20534 = G__20548; count__20452_20535 = G__20549; i__20453_20536 = G__20550; continue; } else { var vec__20455_20551 = cljs.core.first.call(null,seq__20450_20545__$1); var id_20552 = cljs.core.nth.call(null,vec__20455_20551,(0),null); var c_20553 = cljs.core.nth.call(null,vec__20455_20551,(1),null); if(cljs.core.truth_(c_20553.shouldComponentUpdate(c_20553.props,c_20553.state))){ c_20553.forceUpdate(); } else { } var G__20554 = cljs.core.next.call(null,seq__20450_20545__$1); var G__20555 = null; var G__20556 = (0); var G__20557 = (0); seq__20450_20533 = G__20554; chunk__20451_20534 = G__20555; count__20452_20535 = G__20556; i__20453_20536 = G__20557; continue; } } else { } } break; } var G__20558 = cljs.core.next.call(null,seq__20438_20523__$1); var G__20559 = null; var G__20560 = (0); var G__20561 = (0); seq__20438_20485 = G__20558; chunk__20439_20486 = G__20559; count__20440_20487 = G__20560; i__20441_20488 = G__20561; continue; } } else { } } break; } } om.core._set_property_BANG_.call(null,state__$1,watch_key,new cljs.core.Keyword(null,"skip-render-root","skip-render-root",-5219643),true); return cljs.core.deref.call(null,ret); });})(watch_key,state,state__$1,adapt__$1,m,ret,map__20394,map__20394__$1,options,raf,adapt,descriptor,instrument,path,tx_listen,target)) ; cljs.core.add_watch.call(null,state__$1,watch_key,((function (watch_key,state,state__$1,adapt__$1,m,ret,rootf,map__20394,map__20394__$1,options,raf,adapt,descriptor,instrument,path,tx_listen,target){ return (function (_,___$1,o,n){ if((cljs.core.not.call(null,om.core._get_property.call(null,state__$1,watch_key,new cljs.core.Keyword(null,"ignore","ignore",-1631542033)))) && (!((o === n)))){ om.core._set_property_BANG_.call(null,state__$1,watch_key,new cljs.core.Keyword(null,"skip-render-root","skip-render-root",-5219643),false); } else { } om.core._set_property_BANG_.call(null,state__$1,watch_key,new cljs.core.Keyword(null,"ignore","ignore",-1631542033),false); if(cljs.core.contains_QMARK_.call(null,cljs.core.deref.call(null,om.core.refresh_set),rootf)){ } else { cljs.core.swap_BANG_.call(null,om.core.refresh_set,cljs.core.conj,rootf); } if(cljs.core.truth_(om.core.refresh_queued)){ return null; } else { om.core.refresh_queued = true; if((raf === false) || (!(typeof requestAnimationFrame !== 'undefined'))){ return setTimeout(((function (watch_key,state,state__$1,adapt__$1,m,ret,rootf,map__20394,map__20394__$1,options,raf,adapt,descriptor,instrument,path,tx_listen,target){ return (function (){ return om.core.render_all.call(null,state__$1); });})(watch_key,state,state__$1,adapt__$1,m,ret,rootf,map__20394,map__20394__$1,options,raf,adapt,descriptor,instrument,path,tx_listen,target)) ,(16)); } else { if(cljs.core.fn_QMARK_.call(null,raf)){ return raf.call(null); } else { return requestAnimationFrame(((function (watch_key,state,state__$1,adapt__$1,m,ret,rootf,map__20394,map__20394__$1,options,raf,adapt,descriptor,instrument,path,tx_listen,target){ return (function (){ return om.core.render_all.call(null,state__$1); });})(watch_key,state,state__$1,adapt__$1,m,ret,rootf,map__20394,map__20394__$1,options,raf,adapt,descriptor,instrument,path,tx_listen,target)) ); } } } });})(watch_key,state,state__$1,adapt__$1,m,ret,rootf,map__20394,map__20394__$1,options,raf,adapt,descriptor,instrument,path,tx_listen,target)) ); cljs.core.swap_BANG_.call(null,om.core.roots,cljs.core.assoc,target,((function (watch_key,state,state__$1,adapt__$1,m,ret,rootf,map__20394,map__20394__$1,options,raf,adapt,descriptor,instrument,path,tx_listen,target){ return (function (){ om.core._remove_properties_BANG_.call(null,state__$1,watch_key); cljs.core.remove_watch.call(null,state__$1,watch_key); om.core.tear_down.call(null,state__$1,watch_key); cljs.core.swap_BANG_.call(null,om.core.refresh_set,cljs.core.disj,rootf); cljs.core.swap_BANG_.call(null,om.core.roots,cljs.core.dissoc,target); return React.unmountComponentAtNode(target); });})(watch_key,state,state__$1,adapt__$1,m,ret,rootf,map__20394,map__20394__$1,options,raf,adapt,descriptor,instrument,path,tx_listen,target)) ); return rootf.call(null); }); /** * Given a DOM target remove its render loop if one exists. */ om.core.detach_root = (function om$core$detach_root(target){ if(cljs.core.truth_(goog.dom.isElement(target))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol("gdom","isElement","gdom/isElement",465934354,null),new cljs.core.Symbol(null,"target","target",1893533248,null))))].join(''))); } var temp__4126__auto__ = cljs.core.get.call(null,cljs.core.deref.call(null,om.core.roots),target); if(cljs.core.truth_(temp__4126__auto__)){ var f = temp__4126__auto__; return f.call(null); } else { return null; } }); om.core.transactable_QMARK_ = (function om$core$transactable_QMARK_(x){ var G__20563 = x; if(G__20563){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20563.om$core$ITransact$; } })())){ return true; } else { if((!G__20563.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.ITransact,G__20563); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.ITransact,G__20563); } }); /** * Given a tag, a cursor, an optional list of keys ks, mutate the tree * at the path specified by the cursor + the optional keys by applying * f to the specified value in the tree. An Om re-render will be * triggered. */ om.core.transact_BANG_ = (function() { var om$core$transact_BANG_ = null; var om$core$transact_BANG___2 = (function (cursor,f){ return om$core$transact_BANG_.call(null,cursor,cljs.core.PersistentVector.EMPTY,f,null); }); var om$core$transact_BANG___3 = (function (cursor,korks,f){ return om$core$transact_BANG_.call(null,cursor,korks,f,null); }); var om$core$transact_BANG___4 = (function (cursor,korks,f,tag){ if(om.core.transactable_QMARK_.call(null,cursor)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"transactable?","transactable?",780536292,null),new cljs.core.Symbol(null,"cursor","cursor",-1642498285,null))))].join(''))); } if(cljs.core.ifn_QMARK_.call(null,f)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"f","f",43394975,null))))].join(''))); } var korks__$1 = (((korks == null))?cljs.core.PersistentVector.EMPTY:((cljs.core.sequential_QMARK_.call(null,korks))?korks:new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [korks], null) )); return om.core._transact_BANG_.call(null,cursor,korks__$1,f,tag); }); om$core$transact_BANG_ = function(cursor,korks,f,tag){ switch(arguments.length){ case 2: return om$core$transact_BANG___2.call(this,cursor,korks); case 3: return om$core$transact_BANG___3.call(this,cursor,korks,f); case 4: return om$core$transact_BANG___4.call(this,cursor,korks,f,tag); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$transact_BANG_.cljs$core$IFn$_invoke$arity$2 = om$core$transact_BANG___2; om$core$transact_BANG_.cljs$core$IFn$_invoke$arity$3 = om$core$transact_BANG___3; om$core$transact_BANG_.cljs$core$IFn$_invoke$arity$4 = om$core$transact_BANG___4; return om$core$transact_BANG_; })() ; /** * Like transact! but no function provided, instead a replacement * value is given. */ om.core.update_BANG_ = (function() { var om$core$update_BANG_ = null; var om$core$update_BANG___2 = (function (cursor,v){ if(om.core.cursor_QMARK_.call(null,cursor)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"cursor?","cursor?",-648342688,null),new cljs.core.Symbol(null,"cursor","cursor",-1642498285,null))))].join(''))); } return om.core.transact_BANG_.call(null,cursor,cljs.core.PersistentVector.EMPTY,(function (_){ return v; }),null); }); var om$core$update_BANG___3 = (function (cursor,korks,v){ if(om.core.cursor_QMARK_.call(null,cursor)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"cursor?","cursor?",-648342688,null),new cljs.core.Symbol(null,"cursor","cursor",-1642498285,null))))].join(''))); } return om.core.transact_BANG_.call(null,cursor,korks,(function (_){ return v; }),null); }); var om$core$update_BANG___4 = (function (cursor,korks,v,tag){ if(om.core.cursor_QMARK_.call(null,cursor)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"cursor?","cursor?",-648342688,null),new cljs.core.Symbol(null,"cursor","cursor",-1642498285,null))))].join(''))); } return om.core.transact_BANG_.call(null,cursor,korks,(function (_){ return v; }),tag); }); om$core$update_BANG_ = function(cursor,korks,v,tag){ switch(arguments.length){ case 2: return om$core$update_BANG___2.call(this,cursor,korks); case 3: return om$core$update_BANG___3.call(this,cursor,korks,v); case 4: return om$core$update_BANG___4.call(this,cursor,korks,v,tag); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$update_BANG_.cljs$core$IFn$_invoke$arity$2 = om$core$update_BANG___2; om$core$update_BANG_.cljs$core$IFn$_invoke$arity$3 = om$core$update_BANG___3; om$core$update_BANG_.cljs$core$IFn$_invoke$arity$4 = om$core$update_BANG___4; return om$core$update_BANG_; })() ; /** * EXPERIMENTAL: Like transact! but does not schedule a re-render or * create a transact event. */ om.core.commit_BANG_ = (function om$core$commit_BANG_(cursor,korks,f){ if(om.core.cursor_QMARK_.call(null,cursor)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"cursor?","cursor?",-648342688,null),new cljs.core.Symbol(null,"cursor","cursor",-1642498285,null))))].join(''))); } if(cljs.core.ifn_QMARK_.call(null,f)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"f","f",43394975,null))))].join(''))); } var key = (((function (){var G__20565 = cursor; if(G__20565){ var bit__18530__auto__ = null; if(cljs.core.truth_((function (){var or__17856__auto__ = bit__18530__auto__; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return G__20565.om$core$IRootKey$; } })())){ return true; } else { if((!G__20565.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRootKey,G__20565); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_.call(null,om.core.IRootKey,G__20565); } })())?om.core._root_key.call(null,cursor):null); var app_state = om.core.state.call(null,cursor); var korks__$1 = (((korks == null))?cljs.core.PersistentVector.EMPTY:((cljs.core.sequential_QMARK_.call(null,korks))?korks:new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [korks], null) )); var cpath = om.core.path.call(null,cursor); var rpath = cljs.core.into.call(null,cpath,korks__$1); if(cljs.core.truth_(key)){ om.core._set_property_BANG_.call(null,app_state,key,new cljs.core.Keyword(null,"ignore","ignore",-1631542033),true); } else { } if(cljs.core.empty_QMARK_.call(null,rpath)){ return cljs.core.swap_BANG_.call(null,app_state,f); } else { return cljs.core.swap_BANG_.call(null,app_state,cljs.core.update_in,rpath,f); } }); /** * A helper function to get at React refs. Given a owning pure node * extract the ref specified by name. */ om.core.get_node = (function() { var om$core$get_node = null; var om$core$get_node__1 = (function (owner){ return owner.getDOMNode(); }); var om$core$get_node__2 = (function (owner,name){ if(typeof name === 'string'){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"string?","string?",-1129175764,null),new cljs.core.Symbol(null,"name","name",-810760592,null))))].join(''))); } var temp__4126__auto__ = owner.refs; if(cljs.core.truth_(temp__4126__auto__)){ var refs = temp__4126__auto__; return (refs[name]).getDOMNode(); } else { return null; } }); om$core$get_node = function(owner,name){ switch(arguments.length){ case 1: return om$core$get_node__1.call(this,owner); case 2: return om$core$get_node__2.call(this,owner,name); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$get_node.cljs$core$IFn$_invoke$arity$1 = om$core$get_node__1; om$core$get_node.cljs$core$IFn$_invoke$arity$2 = om$core$get_node__2; return om$core$get_node; })() ; /** * Return true if the backing React component is mounted into the DOM. */ om.core.mounted_QMARK_ = (function om$core$mounted_QMARK_(owner){ return owner.isMounted(); }); /** * Takes a pure owning component, a sequential list of keys and value and * sets the state of the component. Conceptually analagous to React * setState. Will schedule an Om re-render. */ om.core.set_state_BANG_ = (function() { var om$core$set_state_BANG_ = null; var om$core$set_state_BANG___2 = (function (owner,v){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } return om.core._set_state_BANG_.call(null,owner,v,true); }); var om$core$set_state_BANG___3 = (function (owner,korks,v){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } var ks = ((cljs.core.sequential_QMARK_.call(null,korks))?korks:new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [korks], null)); return om.core._set_state_BANG_.call(null,owner,ks,v,true); }); om$core$set_state_BANG_ = function(owner,korks,v){ switch(arguments.length){ case 2: return om$core$set_state_BANG___2.call(this,owner,korks); case 3: return om$core$set_state_BANG___3.call(this,owner,korks,v); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$set_state_BANG_.cljs$core$IFn$_invoke$arity$2 = om$core$set_state_BANG___2; om$core$set_state_BANG_.cljs$core$IFn$_invoke$arity$3 = om$core$set_state_BANG___3; return om$core$set_state_BANG_; })() ; /** * EXPERIMENTAL: Same as set-state! but does not trigger re-render. */ om.core.set_state_nr_BANG_ = (function() { var om$core$set_state_nr_BANG_ = null; var om$core$set_state_nr_BANG___2 = (function (owner,v){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } return om.core._set_state_BANG_.call(null,owner,v,false); }); var om$core$set_state_nr_BANG___3 = (function (owner,korks,v){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } var ks = ((cljs.core.sequential_QMARK_.call(null,korks))?korks:new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [korks], null)); return om.core._set_state_BANG_.call(null,owner,ks,v,false); }); om$core$set_state_nr_BANG_ = function(owner,korks,v){ switch(arguments.length){ case 2: return om$core$set_state_nr_BANG___2.call(this,owner,korks); case 3: return om$core$set_state_nr_BANG___3.call(this,owner,korks,v); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$set_state_nr_BANG_.cljs$core$IFn$_invoke$arity$2 = om$core$set_state_nr_BANG___2; om$core$set_state_nr_BANG_.cljs$core$IFn$_invoke$arity$3 = om$core$set_state_nr_BANG___3; return om$core$set_state_nr_BANG_; })() ; /** * Takes a pure owning component, a sequential list of keys and a * function to transition the state of the component. Conceptually * analagous to React setState. Will schedule an Om re-render. */ om.core.update_state_BANG_ = (function() { var om$core$update_state_BANG_ = null; var om$core$update_state_BANG___2 = (function (owner,f){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } if(cljs.core.ifn_QMARK_.call(null,f)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"f","f",43394975,null))))].join(''))); } return om.core.set_state_BANG_.call(null,owner,f.call(null,om.core.get_state.call(null,owner))); }); var om$core$update_state_BANG___3 = (function (owner,korks,f){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } if(cljs.core.ifn_QMARK_.call(null,f)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"f","f",43394975,null))))].join(''))); } return om.core.set_state_BANG_.call(null,owner,korks,f.call(null,om.core.get_state.call(null,owner,korks))); }); om$core$update_state_BANG_ = function(owner,korks,f){ switch(arguments.length){ case 2: return om$core$update_state_BANG___2.call(this,owner,korks); case 3: return om$core$update_state_BANG___3.call(this,owner,korks,f); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$update_state_BANG_.cljs$core$IFn$_invoke$arity$2 = om$core$update_state_BANG___2; om$core$update_state_BANG_.cljs$core$IFn$_invoke$arity$3 = om$core$update_state_BANG___3; return om$core$update_state_BANG_; })() ; /** * EXPERIMENTAL: Same as update-state! but does not trigger re-render. */ om.core.update_state_nr_BANG_ = (function() { var om$core$update_state_nr_BANG_ = null; var om$core$update_state_nr_BANG___2 = (function (owner,f){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } if(cljs.core.ifn_QMARK_.call(null,f)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"f","f",43394975,null))))].join(''))); } return om.core.set_state_nr_BANG_.call(null,owner,f.call(null,om.core.get_state.call(null,owner))); }); var om$core$update_state_nr_BANG___3 = (function (owner,korks,f){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } if(cljs.core.ifn_QMARK_.call(null,f)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"f","f",43394975,null))))].join(''))); } return om.core.set_state_nr_BANG_.call(null,owner,korks,f.call(null,om.core.get_state.call(null,owner,korks))); }); om$core$update_state_nr_BANG_ = function(owner,korks,f){ switch(arguments.length){ case 2: return om$core$update_state_nr_BANG___2.call(this,owner,korks); case 3: return om$core$update_state_nr_BANG___3.call(this,owner,korks,f); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$update_state_nr_BANG_.cljs$core$IFn$_invoke$arity$2 = om$core$update_state_nr_BANG___2; om$core$update_state_nr_BANG_.cljs$core$IFn$_invoke$arity$3 = om$core$update_state_nr_BANG___3; return om$core$update_state_nr_BANG_; })() ; /** * Utility to re-render an owner. */ om.core.refresh_BANG_ = (function om$core$refresh_BANG_(owner){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } return om.core.update_state_BANG_.call(null,owner,cljs.core.identity); }); /** * Takes a pure owning component and an optional key or sequential * list of keys and returns a property in the component local state if * it exists. Always returns the rendered state, not the pending * state. */ om.core.get_render_state = (function() { var om$core$get_render_state = null; var om$core$get_render_state__1 = (function (owner){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } return om.core._get_render_state.call(null,owner); }); var om$core$get_render_state__2 = (function (owner,korks){ if(cljs.core.truth_(om.core.component_QMARK_.call(null,owner))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"component?","component?",2048315517,null),new cljs.core.Symbol(null,"owner","owner",1247919588,null))))].join(''))); } var ks = ((cljs.core.sequential_QMARK_.call(null,korks))?korks:new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [korks], null)); return om.core._get_render_state.call(null,owner,ks); }); om$core$get_render_state = function(owner,korks){ switch(arguments.length){ case 1: return om$core$get_render_state__1.call(this,owner); case 2: return om$core$get_render_state__2.call(this,owner,korks); } throw(new Error('Invalid arity: ' + arguments.length)); }; om$core$get_render_state.cljs$core$IFn$_invoke$arity$1 = om$core$get_render_state__1; om$core$get_render_state.cljs$core$IFn$_invoke$arity$2 = om$core$get_render_state__2; return om$core$get_render_state; })() ; //# sourceMappingURL=core.js.map?rel=1430425795115
snackycracky/equilibrium
frontend/om-tut/resources/public/js/compiled/out/om/core.js
JavaScript
epl-1.0
174,840
/* * This file is part of the Jikes RVM project (http://jikesrvm.org). * * This file is licensed to You under the Eclipse Public License (EPL); * 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 * * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. */ package org.jikesrvm.compilers.opt.regalloc; import org.jikesrvm.compilers.opt.ir.IR; /** * An object that returns an estimate of the relative cost of spilling a * symbolic register. * <p> * This implementation returns a cost of zero for all registers. */ class BrainDeadSpillCost extends SpillCostEstimator { BrainDeadSpillCost(IR ir) { calculate(ir); } /** * Calculate the estimated cost for each register. * This brain-dead version does nothing. */ @Override void calculate(IR ir) { } }
CodeOffloading/JikesRVM-CCO
jikesrvm-3.1.3/rvm/src/org/jikesrvm/compilers/opt/regalloc/BrainDeadSpillCost.java
Java
epl-1.0
964
public class Main { /** * @param args */ public static void main(String[] args) { Almacen a = new Almacen(); Mounstruo m1 = new Mounstruo(a, "Monstruo 1"); Mounstruo m2 = new Mounstruo(a, "Monstruo 2"); // Mounstruo m3 = new Mounstruo(a, "Monstruo 3"); // Mounstruo m4 = new Mounstruo(a, "Monstruo 4"); // Mounstruo m5 = new Mounstruo(a, "Monstruo 5"); // Mounstruo m6 = new Mounstruo(a, "Monstruo 6"); Almecenero al = new Almecenero(a); m1.start(); m2.start(); // m3.start(); // m4.start(); // m5.start(); // m6.start(); al.start(); } }
davidhmhernandez/ServiciosyProcesos
Concurrencia3Act1/src/Main.java
Java
epl-1.0
574
/** */ package org.nasdanika.amur.it.js.foundation; import org.eclipse.emf.common.util.EList; import org.nasdanika.amur.it.js.AbstractNode; import org.nasdanika.amur.it.js.Parameter; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Top Level Flow Function Output Port</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.nasdanika.amur.it.js.foundation.FunctionOutputPort#getParameters <em>Parameters</em>}</li> * </ul> * </p> * * @see org.nasdanika.amur.it.js.foundation.FoundationPackage#getFunctionOutputPort() * @model * @generated */ public interface FunctionOutputPort extends AbstractNode { /** * Returns the value of the '<em><b>Parameters</b></em>' containment reference list. * The list contents are of type {@link org.nasdanika.amur.it.js.Parameter}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Parameters</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Parameters</em>' containment reference list. * @see org.nasdanika.amur.it.js.foundation.FoundationPackage#getFunctionOutputPort_Parameters() * @model containment="true" * @generated */ EList<Parameter> getParameters(); } // FunctionOutputPort
Nasdanika/amur-it-js
org.nasdanika.amur.it.js.foundation/src/org/nasdanika/amur/it/js/foundation/FunctionOutputPort.java
Java
epl-1.0
1,372
/* * Copyright (c) 2015-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 */ 'use strict'; interface IUniqueTeamNameValidatorAttributes { uniqueTeamName: string; parentAccount: string; } /** * Defines a directive for checking whether team name already exists. * * @author Ann Shumilova */ export class UniqueTeamNameValidator { /** * Team interection API. */ private cheTeam: che.api.ICheTeam; /** * Promises service. */ private $q: ng.IQService; private restrict: string; private require: string; /** * Default constructor that is using resource * @ngInject for Dependency injection */ constructor (cheTeam: che.api.ICheTeam, $q: ng.IQService) { this.cheTeam = cheTeam; this.$q = $q; this.restrict = 'A'; this.require = 'ngModel'; } /** * Check that the name of team is unique */ link($scope: ng.IScope, element: ng.IAugmentedJQuery, attributes: IUniqueTeamNameValidatorAttributes, ngModel: any) { // validate only input element if ('input' === element[0].localName) { ngModel.$asyncValidators.uniqueTeamName = (modelValue: any) => { // parent scope ? let scopingTest = $scope.$parent; if (!scopingTest) { scopingTest = $scope; } let deferred = this.$q.defer(); let currentTeamName = scopingTest.$eval(attributes.uniqueTeamName), parentAccount = scopingTest.$eval(attributes.parentAccount), teams = this.cheTeam.getTeams(); if (teams.length) { for (let i = 0; i < teams.length; i++) { if (teams[i].qualifiedName === parentAccount + '/' + currentTeamName) { continue; } if (teams[i].qualifiedName === parentAccount + '/' + modelValue) { deferred.reject(false); } } deferred.resolve(true); } else { deferred.resolve(true); } return deferred.promise; }; } } }
sleshchenko/che
dashboard/src/components/validator/unique-team-name-validator.directive.ts
TypeScript
epl-1.0
2,281
package anatlyzer.atl.editor.quickfix.errors; import org.eclipse.emf.common.util.EList; import org.eclipse.jface.text.IDocument; import org.eclipse.swt.graphics.Image; import anatlyzer.atl.editor.quickfix.AbstractAtlQuickfix; import anatlyzer.atl.editor.quickfix.QuickfixImages; import anatlyzer.atl.quickfixast.ASTUtils; import anatlyzer.atl.quickfixast.InDocumentSerializer; import anatlyzer.atl.quickfixast.QuickfixApplication; import anatlyzer.atl.types.ThisModuleType; import anatlyzer.atl.types.Type; import anatlyzer.atl.util.ATLUtils; import anatlyzer.atlext.ATL.ATLFactory; import anatlyzer.atlext.ATL.ContextHelper; import anatlyzer.atlext.ATL.InPattern; import anatlyzer.atlext.ATL.InPatternElement; import anatlyzer.atlext.ATL.LazyRule; import anatlyzer.atlext.ATL.ModuleElement; import anatlyzer.atlext.ATL.OutPattern; import anatlyzer.atlext.ATL.OutPatternElement; import anatlyzer.atlext.OCL.OclExpression; import anatlyzer.atlext.OCL.OperationCallExp; public abstract class AbstractOperationQuickfix_CreateHelper extends AbstractAtlQuickfix { public AbstractOperationQuickfix_CreateHelper() { super(); } @Override public void resetCache() { } @Override public void apply(IDocument document) { QuickfixApplication qfa = getQuickfixApplication(); new InDocumentSerializer(qfa, document).serialize(); } @Override public String getAdditionalProposalInfo() { return "Create operation " + getNewOperationName((OperationCallExp)getProblematicElement()); } @Override public String getDisplayString() { return "Create operation " + getNewOperationName((OperationCallExp)getProblematicElement()); } @Override public Image getImage() { return QuickfixImages.create_helper.createImage(); } @Override public QuickfixApplication getQuickfixApplication() { OperationCallExp operationCall = (OperationCallExp)getProblematicElement(); Type receptorType = operationCall.getSource().getInferredType(); Type returnType = operationCall.getInferredType(); ModuleElement anchor = ATLUtils.getContainer(operationCall, ModuleElement.class); QuickfixApplication qfa = new QuickfixApplication(this); if (receptorType instanceof ThisModuleType) qfa.insertAfter(anchor, () -> { return buildNewContextLazyRule (operationCall.getOperationName(), receptorType, returnType, operationCall.getArguments()); }); else qfa.insertAfter(anchor, () -> { return buildNewContextOperation(operationCall.getOperationName(), receptorType, returnType, operationCall.getArguments()); }); return qfa; } private String getNewOperationName(OperationCallExp operation) { String context = operation.getSource().getInferredType()!=null? ATLUtils.getTypeName(operation.getSource().getInferredType()) + "." : ""; String arguments = ""; for (OclExpression argument : operation.getArguments()) arguments += ", " + ATLUtils.getTypeName(argument.getInferredType()); return context + operation.getOperationName() + "(" + arguments.replaceFirst(",", "") + " )"; } private ContextHelper buildNewContextOperation(String name, Type receptorType, Type returnType, EList<OclExpression> arguments) { return ASTUtils.buildNewContextOperation(name, receptorType, returnType, arguments); } private LazyRule buildNewContextLazyRule (String name, Type receptorType, Type returnType, EList<OclExpression> arguments) { InPattern ipattern = ATLFactory.eINSTANCE.createInPattern(); OutPattern opattern = ATLFactory.eINSTANCE.createOutPattern(); int i=0; for (OclExpression argument : arguments) { InPatternElement element = ATLFactory.eINSTANCE.createSimpleInPatternElement(); element.setVarName( "param" + (i++)); element.setType ( ATLUtils.getOclType(argument.getInferredType()) ); ipattern.getElements().add(element); } OutPatternElement element = ATLFactory.eINSTANCE.createSimpleOutPatternElement(); element.setVarName( "param" + (i++)); element.setType ( ATLUtils.getOclType(returnType) ); opattern.getElements().add(element); LazyRule rule = ATLFactory.eINSTANCE.createLazyRule(); rule.setName(name); rule.setInPattern (ipattern); rule.setOutPattern(opattern); return rule; } }
gomezabajo/Wodel
anatlyzer.atl.editor.quickfix/src/anatlyzer/atl/editor/quickfix/errors/AbstractOperationQuickfix_CreateHelper.java
Java
epl-1.0
4,227
/******************************************************************************* * Copyright (c) 2010, 2012 David A Carlson 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 A Carlson (XMLmodeling.com) - initial API and implementation * Kenn Hussey - adding support for restoring defaults * Christian W. Damus - implement handling of live validation roll-back (artf3318) * *******************************************************************************/ package org.openhealthtools.mdht.uml.term.ui.properties; import org.eclipse.core.commands.operations.IUndoableOperation; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.impl.NotificationImpl; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.transaction.TransactionalEditingDomain; import org.eclipse.emf.transaction.util.TransactionUtil; import org.eclipse.emf.workspace.AbstractEMFOperation; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.views.properties.tabbed.ITabbedPropertyConstants; import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage; import org.eclipse.uml2.uml.Element; import org.eclipse.uml2.uml.Enumeration; import org.eclipse.uml2.uml.EnumerationLiteral; import org.eclipse.uml2.uml.NamedElement; import org.eclipse.uml2.uml.Profile; import org.eclipse.uml2.uml.Property; import org.eclipse.uml2.uml.Stereotype; import org.eclipse.uml2.uml.UMLPackage; import org.openhealthtools.mdht.uml.common.ui.dialogs.DialogLaunchUtil; import org.openhealthtools.mdht.uml.common.ui.search.IElementFilter; import org.openhealthtools.mdht.uml.term.core.profile.BindingKind; import org.openhealthtools.mdht.uml.term.core.profile.TermPackage; import org.openhealthtools.mdht.uml.term.core.profile.ValueSetConstraint; import org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion; import org.openhealthtools.mdht.uml.term.core.util.ITermProfileConstants; import org.openhealthtools.mdht.uml.term.core.util.TermProfileUtil; import org.openhealthtools.mdht.uml.ui.properties.sections.ResettableModelerPropertySection; /** * The profile properties section for Value Set Constraint. */ public class ValueSetConstraintSection extends ResettableModelerPropertySection { private Property property; private Text idText; private boolean idModified = false; private Text nameText; private boolean nameModified = false; private Text versionText; private boolean versionModified = false; private CCombo bindingCombo; private boolean bindingModified = false; private CLabel valueSetRefLabel; private Button valueSetRefButton; private Button valueSetRefDeleteButton; private ModifyListener modifyListener = new ModifyListener() { public void modifyText(final ModifyEvent event) { if (idText == event.getSource()) { idModified = true; } if (nameText == event.getSource()) { nameModified = true; } if (versionText == event.getSource()) { versionModified = true; } } }; private KeyListener keyListener = new KeyListener() { public void keyPressed(KeyEvent e) { // do nothing } public void keyReleased(KeyEvent e) { if (SWT.CR == e.character || SWT.KEYPAD_CR == e.character) { modifyFields(); } } }; private FocusListener focusListener = new FocusListener() { public void focusGained(FocusEvent e) { // do nothing } public void focusLost(FocusEvent event) { modifyFields(); } }; private void modifyFields() { if (!(idModified || nameModified || versionModified || bindingModified)) { return; } try { TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(property); IUndoableOperation operation = new AbstractEMFOperation(editingDomain, "temp") { @Override protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) { Profile ctsProfile = TermProfileUtil.getTerminologyProfile(property.eResource().getResourceSet()); if (ctsProfile == null) { return Status.CANCEL_STATUS; } Enumeration bindingKind = (Enumeration) ctsProfile.getOwnedType(ITermProfileConstants.BINDING_KIND); Stereotype stereotype = TermProfileUtil.getAppliedStereotype( property, ITermProfileConstants.VALUE_SET_CONSTRAINT); if (stereotype == null) { return Status.CANCEL_STATUS; } else if (idModified) { idModified = false; this.setLabel("Set Value Set ID"); if (stereotype != null) { String value = idText.getText().trim(); property.setValue( stereotype, ITermProfileConstants.VALUE_SET_CONSTRAINT_ID, value.length() > 0 ? value : null); } } else if (nameModified) { nameModified = false; this.setLabel("Set Value Set Name"); if (stereotype != null) { String value = nameText.getText().trim(); property.setValue( stereotype, ITermProfileConstants.VALUE_SET_CONSTRAINT_NAME, value.length() > 0 ? value : null); } } else if (versionModified) { versionModified = false; this.setLabel("Set Value Set Version"); if (stereotype != null) { String value = versionText.getText().trim(); property.setValue( stereotype, ITermProfileConstants.VALUE_SET_CONSTRAINT_VERSION, value.length() > 0 ? value : null); } } else if (bindingModified) { bindingModified = false; this.setLabel("Set Binding"); if (stereotype != null && bindingKind != null) { if (bindingCombo.getSelectionIndex() == 0) { // remove stereotype property property.setValue(stereotype, ITermProfileConstants.VALUE_SET_CONSTRAINT_BINDING, null); } else { EnumerationLiteral literal = bindingKind.getOwnedLiterals().get( bindingCombo.getSelectionIndex()); property.setValue( stereotype, ITermProfileConstants.VALUE_SET_CONSTRAINT_BINDING, literal); } } } else { return Status.CANCEL_STATUS; } updateViews(); return Status.OK_STATUS; } }; execute(operation); } catch (Exception e) { throw new RuntimeException(e.getCause()); } } @Override protected void resetFields() { try { TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(property); IUndoableOperation operation = new AbstractEMFOperation(editingDomain, "Restore Default Values") { @Override protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) { ValueSetConstraint valueSetConstraint = TermProfileUtil.getValueSetConstraint(property); if (valueSetConstraint == null) { return Status.CANCEL_STATUS; } valueSetConstraint.eUnset(TermPackage.Literals.VALUE_SET_CONSTRAINT__IDENTIFIER); valueSetConstraint.eUnset(TermPackage.Literals.VALUE_SET_CONSTRAINT__NAME); valueSetConstraint.eUnset(TermPackage.Literals.VALUE_SET_CONSTRAINT__VERSION); valueSetConstraint.eUnset(TermPackage.Literals.VALUE_SET_CONSTRAINT__BINDING); updateViews(); refresh(); return Status.OK_STATUS; } }; execute(operation); } catch (Exception e) { throw new RuntimeException(e.getCause()); } } private void addValueSetReference() { Profile ctsProfile = TermProfileUtil.getTerminologyProfile(property.eResource().getResourceSet()); if (ctsProfile == null) { return; } final Stereotype valueSetVersionStereotype = (Stereotype) ctsProfile.getOwnedType(ITermProfileConstants.VALUE_SET_VERSION); IElementFilter filter = new IElementFilter() { public boolean accept(Element element) { return (element instanceof Enumeration) && element.isStereotypeApplied(valueSetVersionStereotype); } }; final Enumeration valueSetEnum = (Enumeration) DialogLaunchUtil.chooseElement( filter, property.eResource().getResourceSet(), getPart().getSite().getShell(), null, "Select a Value Set"); if (valueSetEnum == null) { return; } final Stereotype valueSetStereotype = TermProfileUtil.getAppliedStereotype( valueSetEnum, ITermProfileConstants.VALUE_SET_VERSION); if (valueSetStereotype == null) { MessageDialog.openError( getPart().getSite().getShell(), "Invalid Enumeration", "The selected Enumertion must be a <<ValueSetVersion>>"); return; } final ValueSetVersion valueSet = (ValueSetVersion) valueSetEnum.getStereotypeApplication(valueSetStereotype); try { TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(property); IUndoableOperation operation = new AbstractEMFOperation(editingDomain, "temp") { @Override protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) { ValueSetConstraint valueSetConstraint = TermProfileUtil.getValueSetConstraint(property); if (valueSetConstraint == null) { return Status.CANCEL_STATUS; } this.setLabel("Set ValueSet reference"); valueSetConstraint.setReference(valueSet); valueSetConstraint.setIdentifier(null); valueSetConstraint.setName(null); valueSetConstraint.setVersion(null); valueSetConstraint.setBinding(null); refresh(); return Status.OK_STATUS; } }; execute(operation); } catch (Exception e) { throw new RuntimeException(e.getCause()); } } private void deleteValueSetReference() { try { TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(property); IUndoableOperation operation = new AbstractEMFOperation(editingDomain, "temp") { @Override protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) { ValueSetConstraint valueSetConstraint = TermProfileUtil.getValueSetConstraint(property); if (valueSetConstraint == null || valueSetConstraint.getReference() == null) { return Status.CANCEL_STATUS; } this.setLabel("Remove ValueSet reference"); valueSetConstraint.setReference(null); valueSetConstraint.setIdentifier(null); valueSetConstraint.setName(null); valueSetConstraint.setVersion(null); valueSetConstraint.setBinding(null); refresh(); return Status.OK_STATUS; } }; execute(operation); } catch (Exception e) { throw new RuntimeException(e.getCause()); } } @Override public void createControls(final Composite parent, final TabbedPropertySheetPage aTabbedPropertySheetPage) { super.createControls(parent, aTabbedPropertySheetPage); Shell shell = new Shell(); GC gc = new GC(shell); gc.setFont(shell.getFont()); Point point = gc.textExtent("");//$NON-NLS-1$ int buttonHeight = point.y + 10; gc.dispose(); shell.dispose(); Composite composite = getWidgetFactory().createGroup(parent, "Value Set"); FormLayout layout = new FormLayout(); layout.marginWidth = ITabbedPropertyConstants.HSPACE + 2; layout.marginHeight = ITabbedPropertyConstants.VSPACE; layout.spacing = ITabbedPropertyConstants.VMARGIN + 1; composite.setLayout(layout); int numberOfRows = 3; FormData data = null; /* ------ ValueSet reference ------ */ valueSetRefLabel = getWidgetFactory().createCLabel(composite, ""); //$NON-NLS-1$ valueSetRefButton = getWidgetFactory().createButton(composite, "Select Value Set...", SWT.PUSH); //$NON-NLS-1$ valueSetRefButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { addValueSetReference(); } }); valueSetRefDeleteButton = getWidgetFactory().createButton(composite, "X", SWT.PUSH); //$NON-NLS-1$ valueSetRefDeleteButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { deleteValueSetReference(); } }); data = new FormData(); data.left = new FormAttachment(0, 0); data.height = buttonHeight; data.top = new FormAttachment(0, numberOfRows); valueSetRefButton.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(valueSetRefButton, 0); data.height = buttonHeight; data.top = new FormAttachment(valueSetRefButton, 0, SWT.CENTER); valueSetRefDeleteButton.setLayoutData(data); /* ---- Restore Defaults button ---- */ createRestoreDefaultsButton(composite); data = new FormData(); data.right = new FormAttachment(100, 0); data.top = new FormAttachment(valueSetRefLabel, 0, SWT.CENTER); restoreDefaultsButton.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(valueSetRefDeleteButton, 0); data.right = new FormAttachment(restoreDefaultsButton, ITabbedPropertyConstants.HSPACE); data.top = new FormAttachment(valueSetRefButton, 0, SWT.CENTER); valueSetRefLabel.setLayoutData(data); /* ------ Name field ------ */ nameText = getWidgetFactory().createText(composite, ""); //$NON-NLS-1$ CLabel nameLabel = getWidgetFactory().createCLabel(composite, "Name:"); //$NON-NLS-1$ data = new FormData(); data.left = new FormAttachment(0, 0); data.top = new FormAttachment(nameText, 0, SWT.CENTER); nameLabel.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(nameLabel, 0); data.right = new FormAttachment(50, 0); data.top = new FormAttachment(1, numberOfRows, ITabbedPropertyConstants.VSPACE); nameText.setLayoutData(data); /* ------ ID field ------ */ idText = getWidgetFactory().createText(composite, ""); //$NON-NLS-1$ CLabel idLabel = getWidgetFactory().createCLabel(composite, "ID:"); //$NON-NLS-1$ data = new FormData(); data.left = new FormAttachment(nameText, ITabbedPropertyConstants.HSPACE); data.top = new FormAttachment(nameText, 0, SWT.CENTER); idLabel.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(idLabel, 0); data.right = new FormAttachment(100, 0); data.top = new FormAttachment(1, numberOfRows, ITabbedPropertyConstants.VSPACE); idText.setLayoutData(data); /* ---- binding combo ---- */ bindingCombo = getWidgetFactory().createCCombo(composite, SWT.FLAT | SWT.READ_ONLY | SWT.BORDER); bindingCombo.setItems(new String[] { "Static", "Dynamic" }); bindingCombo.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { bindingModified = true; modifyFields(); } public void widgetSelected(SelectionEvent e) { bindingModified = true; modifyFields(); } }); CLabel bindingLabel = getWidgetFactory().createCLabel(composite, "Binding:"); //$NON-NLS-1$ data = new FormData(); data.left = new FormAttachment(0, 0); data.top = new FormAttachment(bindingCombo, 0, SWT.CENTER); bindingLabel.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(bindingLabel, 0); data.top = new FormAttachment(2, numberOfRows, ITabbedPropertyConstants.VSPACE); bindingCombo.setLayoutData(data); /* ------ Version field ------ */ versionText = getWidgetFactory().createText(composite, ""); //$NON-NLS-1$ CLabel versionLabel = getWidgetFactory().createCLabel(composite, "Version:"); //$NON-NLS-1$ data = new FormData(); data.left = new FormAttachment(bindingCombo, ITabbedPropertyConstants.HSPACE); data.top = new FormAttachment(versionText, 0, SWT.CENTER); versionLabel.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(versionLabel, 0); data.right = new FormAttachment(50, 0); data.top = new FormAttachment(2, numberOfRows, ITabbedPropertyConstants.VSPACE); versionText.setLayoutData(data); } @Override protected boolean isReadOnly() { if (property != null) { TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(property); if (editingDomain != null && editingDomain.isReadOnly(property.eResource())) { return true; } } return super.isReadOnly(); } /* * Override super implementation to allow for objects that are not IAdaptable. * * (non-Javadoc) * * @see org.eclipse.gmf.runtime.diagram.ui.properties.sections.AbstractModelerPropertySection#addToEObjectList(java.lang.Object) */ @Override protected boolean addToEObjectList(Object object) { boolean added = super.addToEObjectList(object); if (!added && object instanceof Element) { getEObjectList().add(object); added = true; } return added; } @Override public void setInput(IWorkbenchPart part, ISelection selection) { super.setInput(part, selection); EObject element = getEObject(); Assert.isTrue(element instanceof NamedElement); this.property = (Property) element; } @Override public void dispose() { super.dispose(); } @Override public void refresh() { Profile ctsProfile = TermProfileUtil.getTerminologyProfile(property.eResource().getResourceSet()); if (ctsProfile == null) { return; } Enumeration bindingKind = (Enumeration) ctsProfile.getOwnedType(ITermProfileConstants.BINDING_KIND); ValueSetConstraint valueSetConstraint = TermProfileUtil.getValueSetConstraint(property); ValueSetVersion valueSet = null; Enumeration referenceEnum = null; if (valueSetConstraint != null && valueSetConstraint.getReference() != null) { valueSet = valueSetConstraint.getReference(); referenceEnum = valueSet.getBase_Enumeration(); valueSetRefLabel.setText(valueSet.getEnumerationQualifiedName()); valueSetRefLabel.layout(); } else { valueSetRefLabel.setText(""); } idText.removeModifyListener(modifyListener); idText.removeKeyListener(keyListener); idText.removeFocusListener(focusListener); if (valueSetConstraint != null) { String id = valueSet == null ? valueSetConstraint.getIdentifier() : valueSet.getIdentifier(); idText.setText(id != null ? id : ""); } else { idText.setText(""); } idText.addModifyListener(modifyListener); idText.addKeyListener(keyListener); idText.addFocusListener(focusListener); nameText.removeModifyListener(modifyListener); nameText.removeKeyListener(keyListener); nameText.removeFocusListener(focusListener); if (valueSetConstraint != null) { String name = valueSet == null ? valueSetConstraint.getName() : valueSet.getEnumerationName(); nameText.setText(name != null ? name : ""); } else { nameText.setText(""); } nameText.addModifyListener(modifyListener); nameText.addKeyListener(keyListener); nameText.addFocusListener(focusListener); versionText.removeModifyListener(modifyListener); versionText.removeKeyListener(keyListener); versionText.removeFocusListener(focusListener); if (valueSetConstraint != null) { String version = valueSet == null ? valueSetConstraint.getVersion() : valueSet.getVersion(); versionText.setText(version != null ? version : ""); } else { versionText.setText(""); } versionText.addModifyListener(modifyListener); versionText.addKeyListener(keyListener); versionText.addFocusListener(focusListener); bindingCombo.select(0); if (valueSetConstraint != null) { BindingKind binding = valueSet == null ? valueSetConstraint.getBinding() : valueSet.getBinding(); if (bindingKind != null && binding != null) { EnumerationLiteral literal = bindingKind.getOwnedLiteral(binding.getName()); int index = bindingKind.getOwnedLiterals().indexOf(literal); bindingCombo.select(index); } } if (isReadOnly()) { valueSetRefLabel.setEnabled(false); idText.setEnabled(false); nameText.setEnabled(false); versionText.setEnabled(false); bindingCombo.setEnabled(false); } else { valueSetRefLabel.setEnabled(true); idText.setEnabled(referenceEnum == null); nameText.setEnabled(referenceEnum == null); versionText.setEnabled(referenceEnum == null); bindingCombo.setEnabled(referenceEnum == null); restoreDefaultsButton.setEnabled(valueSetConstraint != null); } } /** * Update if necessary, upon receiving the model event. * * @see #aboutToBeShown() * @see #aboutToBeHidden() * @param notification * - * even notification * @param element * - * element that has changed */ @Override public void update(final Notification notification, EObject element) { if (!isDisposed()) { postUpdateRequest(new Runnable() { public void run() { // widget not disposed and UML element is not deleted if (!isDisposed() && property.eResource() != null) { refresh(); } } }); } } protected void updateViews() { // fire notification for any stereotype property changes to update views // this is a bogus notification of change to property name, but can't find a better option Notification notification = new NotificationImpl(Notification.SET, null, property.getName()) { @Override public Object getNotifier() { return property; } @Override public int getFeatureID(Class expectedClass) { return UMLPackage.PROPERTY__NAME; } }; property.eNotify(notification); } }
sarpkayanehta/mdht
core/plugins/org.openhealthtools.mdht.uml.term.ui/src/org/openhealthtools/mdht/uml/term/ui/properties/ValueSetConstraintSection.java
Java
epl-1.0
22,969
/* -*-C++-*- ImgSVC_impl.cpp Copyright (c) 2011 AIST All Rights Reserved. Eclipse Public License v1.0 (http://www.eclipse.org/legal/epl-v10.html) */ /*! * @file ImgSVC_impl.cpp * @brief Service implementation code of Img.idl * */ #include "ImgSVC_impl.h" #include "MultiCamera.h" /* * Example implementational code for IDL interface Img::CameraCaptureService */ CameraCaptureServiceSVC_impl::CameraCaptureServiceSVC_impl(MultiCamera& mc) : m_parent(mc) { // Please add extra constructor code here. } CameraCaptureServiceSVC_impl::~CameraCaptureServiceSVC_impl() { // Please add extra destructor code here. } /* * Methods corresponding to IDL attributes and operations */ void CameraCaptureServiceSVC_impl::take_one_frame() { // Please insert your code here and remove the following warning pragma m_parent.m_trigger_mode = MultiCamera::trigger_mode_one_shot; m_parent.capture(); m_parent.m_imagesOut.write(); } void CameraCaptureServiceSVC_impl::take_multi_frames(CORBA::Long num) { m_parent.m_num_required_images = num; m_parent.m_trigger_mode = MultiCamera::trigger_mode_multi_shot; } void CameraCaptureServiceSVC_impl::start_continuous() { m_parent.m_trigger_mode = MultiCamera::trigger_mode_continuous; } void CameraCaptureServiceSVC_impl::stop_continuous() { m_parent.m_trigger_mode = MultiCamera::trigger_mode_one_shot; } // End of example implementational code
nagyistoce/openvgr
src/module/component/MultiCamera/ImgSVC_impl.cpp
C++
epl-1.0
1,420
package de.hanoi; /** * This class provides an auto solving algorithm for the game. It does that in the fewest steps possible. * To do the solving in a pace the user can follow, there is a delay, which can be set to a value greater than 1. * 1 second is also the default delay. * @author phillip.goellner */ public class AutoSolver implements Runnable { /** * The value for a preset delay. This value is set before any instance of this class exists, which is why this field is static. */ private static int preDelay; private int delay; private GamePad gamePad; private boolean abort; /** * Initializes a new AutoSolver for the given {@link GamePad} and with either the default delay or the preset one. * @param gamePad the GamePad for which this solver is meant */ public AutoSolver(GamePad gamePad) { delay = (preDelay == 0) ? 1 : preDelay; abort = false; this.gamePad = gamePad; } /** * This function is the one used by the visualizing parts of the program. * It simply calls the real (private) solve function with the right parameters. * @throws IllegalMovementException */ public void solve() throws IllegalMovementException { solve(0,1,2,gamePad.getPegSize(0)); } /** * Solves the given Hanoi board recursively with the fewest steps possible. * Because of it's recursive nature, this function needs more space than an iterative approach would need. * It was designed this way, because of its simplicity and its good readability. * @param start the peg from which the disk will be taken * @param help the peg used for help * @param target the peg the disk is supposed to go * @param size the size of the current stack of disks on start * @throws IllegalMovementException only if the algorithm is corrupted or something unexpected happens */ private void solve(int start, int help, int target, int size) throws IllegalMovementException { if(abort) { return; } if(size == 1) { try { Thread.sleep(delay*1000L); } catch (InterruptedException e) { // if this happens we have bigger problems than a dormant Thread... e.printStackTrace(); } if(abort) { return; } gamePad.move(start, target); } else { solve(start, target, help, size-1); try { Thread.sleep(delay*1000L); } catch (InterruptedException e) { // if this happens we have bigger problems than a dormant Thread... e.printStackTrace(); } if(abort) { return; } gamePad.move(start, target); if(abort) { return; } solve(help, start, target, size-1); } } /** * The starting point for the separate auto solving thread. Called by the GUI or another UI. */ public void run() { try { solve(); } catch (IllegalMovementException e) { // If this happens, we screwed up the algorithm. // Of course it won't. e.printStackTrace(); } } /** * Cancels a running solving process. */ public void cancel() { abort = true; } /** * Presets the delay for each following instance of AutoSolver. * Used by {@link Main}. Guarantees the right delay even if the solving process is aborted and restated. * @param i the delay each new instance will be initialized with. */ public static void presetDelay(int i) { preDelay = i; } }
DHBWFN2016/Hanoi
Hanoi/src/de/hanoi/AutoSolver.java
Java
epl-1.0
3,327
/* * (C) Copyright 2015 Netcentric AG. * * 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 biz.netcentric.cq.tools.actool.helper; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Constants { private Constants() { } public static final String GLOBAL_CONFIGURATION_KEY = "global_config"; public static final String GROUP_CONFIGURATION_KEY = "group_config"; public static final String USER_CONFIGURATION_KEY = "user_config"; public static final String ACE_CONFIGURATION_KEY = "ace_config"; public static final String OBSOLETE_AUTHORIZABLES_KEY = "obsolete_authorizables"; public static final Set<String> VALID_CONFIG_SECTION_IDENTIFIERS = new HashSet<String>(Arrays.asList( GLOBAL_CONFIGURATION_KEY, GROUP_CONFIGURATION_KEY, USER_CONFIGURATION_KEY, ACE_CONFIGURATION_KEY, OBSOLETE_AUTHORIZABLES_KEY)); public static final String USER_ANONYMOUS = "anonymous"; public static final String PRINCIPAL_EVERYONE = "everyone"; public static final String GROUPS_ROOT = "/home/groups"; public static final String USERS_ROOT = "/home/users"; public static final String REPO_POLICY_NODE = "rep:repoPolicy"; }
Netcentric/accesscontroltool
accesscontroltool-bundle/src/main/java/biz/netcentric/cq/tools/actool/helper/Constants.java
Java
epl-1.0
1,468
/** * 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.ui.artifacts.event; import java.io.Serializable; import org.eclipse.hawkbit.repository.model.SoftwareModule; /** * * Holds file and upload status details.Meta data sent with upload events. * */ public class UploadFileStatus implements Serializable { private static final long serialVersionUID = -3599629192216760811L; private final String fileName; private long contentLength; private long bytesRead; private String failureReason; private SoftwareModule softwareModule; /** * constructor for UploadFileStatus * * @param fileName * name of the file to be uploaded */ public UploadFileStatus(final String fileName) { this.fileName = fileName; } /** * constructor for UploadFileStatus * * @param fileName * name of the file to be uploaded * @param bytesRead * number of bytes * @param contentLength * length of the content (stream) * @param softwareModule * softwareModule */ public UploadFileStatus(final String fileName, final long bytesRead, final long contentLength, final SoftwareModule softwareModule) { this.fileName = fileName; this.contentLength = contentLength; this.bytesRead = bytesRead; this.softwareModule = softwareModule; } /** * constructor for UploadFileStatus * * @param fileName * name of the file to be uploaded * @param failureReason * reason of failure * @param selectedSw * the selected softwareModule */ public UploadFileStatus(final String fileName, final String failureReason, final SoftwareModule selectedSw) { this.failureReason = failureReason; this.fileName = fileName; this.softwareModule = selectedSw; } public String getFileName() { return fileName; } public long getContentLength() { return contentLength; } public long getBytesRead() { return bytesRead; } public String getFailureReason() { return failureReason; } public SoftwareModule getSoftwareModule() { return softwareModule; } }
stormc/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadFileStatus.java
Java
epl-1.0
2,624
/* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Eclipse Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin fabs.cpp$$ $spell fabs abs $$ $section AD Absolute Value Function: Example and Test$$ $mindex abs fabs$$ $code $srcfile%example/general/fabs.cpp%0%// BEGIN C++%// END C++%1%$$ $$ $end */ // BEGIN C++ # include <cppad/cppad.hpp> bool fabs(void) { bool ok = true; using CppAD::AD; using CppAD::NearEqual; double eps99 = 99.0 * std::numeric_limits<double>::epsilon(); // domain space vector size_t n = 1; CPPAD_TESTVECTOR(AD<double>) x(n); x[0] = 0.; // declare independent variables and start tape recording CppAD::Independent(x); // range space vector size_t m = 6; CPPAD_TESTVECTOR(AD<double>) y(m); y[0] = fabs(x[0] - 1.); y[1] = fabs(x[0]); y[2] = fabs(x[0] + 1.); // y[3] = fabs(x[0] - 1.); y[4] = fabs(x[0]); y[5] = fabs(x[0] + 1.); // create f: x -> y and stop tape recording CppAD::ADFun<double> f(x, y); // check values ok &= (y[0] == 1.); ok &= (y[1] == 0.); ok &= (y[2] == 1.); // ok &= (y[3] == 1.); ok &= (y[4] == 0.); ok &= (y[5] == 1.); // forward computation of partials w.r.t. a positive x[0] direction size_t p = 1; CPPAD_TESTVECTOR(double) dx(n), dy(m); dx[0] = 1.; dy = f.Forward(p, dx); ok &= (dy[0] == - dx[0]); ok &= (dy[1] == 0. ); // used to be (dy[1] == + dx[0]); ok &= (dy[2] == + dx[0]); // ok &= (dy[3] == - dx[0]); ok &= (dy[4] == 0. ); // used to be (dy[1] == + dx[0]); ok &= (dy[5] == + dx[0]); // forward computation of partials w.r.t. a negative x[0] direction dx[0] = -1.; dy = f.Forward(p, dx); ok &= (dy[0] == - dx[0]); ok &= (dy[1] == 0. ); // used to be (dy[1] == - dx[0]); ok &= (dy[2] == + dx[0]); // ok &= (dy[3] == - dx[0]); ok &= (dy[4] == 0. ); // used to be (dy[1] == - dx[0]); ok &= (dy[5] == + dx[0]); // reverse computation of derivative of y[0] p = 1; CPPAD_TESTVECTOR(double) w(m), dw(n); w[0] = 1.; w[1] = 0.; w[2] = 0.; w[3] = 0.; w[4] = 0.; w[5] = 0.; dw = f.Reverse(p, w); ok &= (dw[0] == -1.); // reverse computation of derivative of y[1] w[0] = 0.; w[1] = 1.; dw = f.Reverse(p, w); ok &= (dw[0] == 0.); // reverse computation of derivative of y[5] w[1] = 0.; w[5] = 1.; dw = f.Reverse(p, w); ok &= (dw[0] == 1.); // use a VecAD<Base>::reference object with abs and fabs CppAD::VecAD<double> v(1); AD<double> zero(0); v[zero] = -1; AD<double> result = fabs(v[zero]); ok &= NearEqual(result, 1., eps99, eps99); result = fabs(v[zero]); ok &= NearEqual(result, 1., eps99, eps99); return ok; } // END C++
kaskr/CppAD
example/general/fabs.cpp
C++
epl-1.0
3,090
package org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionId; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri; import java.util.Map; import org.opendaylight.yangtools.yang.binding.Augmentation; import java.util.HashMap; import org.opendaylight.yangtools.yang.binding.DataObject; import java.util.Collections; public class GroupUpdatedBuilder { private GroupRef _groupRef; private Boolean _barrier; private Buckets _buckets; private String _containerName; private GroupId _groupId; private String _groupName; private GroupTypes _groupType; private NodeRef _node; private TransactionId _transactionId; private Uri _transactionUri; private final Map<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>> augmentation = new HashMap<>(); public GroupUpdatedBuilder() { } public GroupUpdatedBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group arg) { this._barrier = arg.isBarrier(); this._buckets = arg.getBuckets(); this._containerName = arg.getContainerName(); this._groupId = arg.getGroupId(); this._groupName = arg.getGroupName(); this._groupType = arg.getGroupType(); } public GroupUpdatedBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContextRef arg) { this._node = arg.getNode(); } public GroupUpdatedBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionAware arg) { this._transactionId = arg.getTransactionId(); } public GroupUpdatedBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionMetadata arg) { this._transactionUri = arg.getTransactionUri(); } /** Set fields from given grouping argument. Valid argument is instance of one of following types: * <ul> * <li>org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group</li> * <li>org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContextRef</li> * <li>org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionMetadata</li> * <li>org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionAware</li> * </ul> * * @param arg grouping object * @throws IllegalArgumentException if given argument is none of valid types */ public void fieldsFrom(DataObject arg) { boolean isValidArg = false; if (arg instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group) { this._barrier = ((org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group)arg).isBarrier(); this._buckets = ((org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group)arg).getBuckets(); this._containerName = ((org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group)arg).getContainerName(); this._groupId = ((org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group)arg).getGroupId(); this._groupName = ((org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group)arg).getGroupName(); this._groupType = ((org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group)arg).getGroupType(); isValidArg = true; } if (arg instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContextRef) { this._node = ((org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContextRef)arg).getNode(); isValidArg = true; } if (arg instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionMetadata) { this._transactionUri = ((org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionMetadata)arg).getTransactionUri(); isValidArg = true; } if (arg instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionAware) { this._transactionId = ((org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionAware)arg).getTransactionId(); isValidArg = true; } if (!isValidArg) { throw new IllegalArgumentException( "expected one of: [org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group, org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContextRef, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionMetadata, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionAware] \n" + "but was: " + arg ); } } public GroupRef getGroupRef() { return _groupRef; } public Boolean isBarrier() { return _barrier; } public Buckets getBuckets() { return _buckets; } public String getContainerName() { return _containerName; } public GroupId getGroupId() { return _groupId; } public String getGroupName() { return _groupName; } public GroupTypes getGroupType() { return _groupType; } public NodeRef getNode() { return _node; } public TransactionId getTransactionId() { return _transactionId; } public Uri getTransactionUri() { return _transactionUri; } @SuppressWarnings("unchecked") public <E extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>> E getAugmentation(Class<E> augmentationType) { if (augmentationType == null) { throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!"); } return (E) augmentation.get(augmentationType); } public GroupUpdatedBuilder setGroupRef(GroupRef value) { this._groupRef = value; return this; } public GroupUpdatedBuilder setBarrier(Boolean value) { this._barrier = value; return this; } public GroupUpdatedBuilder setBuckets(Buckets value) { this._buckets = value; return this; } public GroupUpdatedBuilder setContainerName(String value) { this._containerName = value; return this; } public GroupUpdatedBuilder setGroupId(GroupId value) { this._groupId = value; return this; } public GroupUpdatedBuilder setGroupName(String value) { this._groupName = value; return this; } public GroupUpdatedBuilder setGroupType(GroupTypes value) { this._groupType = value; return this; } public GroupUpdatedBuilder setNode(NodeRef value) { this._node = value; return this; } public GroupUpdatedBuilder setTransactionId(TransactionId value) { this._transactionId = value; return this; } public GroupUpdatedBuilder setTransactionUri(Uri value) { this._transactionUri = value; return this; } public GroupUpdatedBuilder addAugmentation(Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>> augmentationType, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated> augmentation) { this.augmentation.put(augmentationType, augmentation); return this; } public GroupUpdated build() { return new GroupUpdatedImpl(this); } private static final class GroupUpdatedImpl implements GroupUpdated { public Class<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated> getImplementedInterface() { return org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated.class; } private final GroupRef _groupRef; private final Boolean _barrier; private final Buckets _buckets; private final String _containerName; private final GroupId _groupId; private final String _groupName; private final GroupTypes _groupType; private final NodeRef _node; private final TransactionId _transactionId; private final Uri _transactionUri; private final Map<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>> augmentation; private GroupUpdatedImpl(GroupUpdatedBuilder builder) { this._groupRef = builder.getGroupRef(); this._barrier = builder.isBarrier(); this._buckets = builder.getBuckets(); this._containerName = builder.getContainerName(); this._groupId = builder.getGroupId(); this._groupName = builder.getGroupName(); this._groupType = builder.getGroupType(); this._node = builder.getNode(); this._transactionId = builder.getTransactionId(); this._transactionUri = builder.getTransactionUri(); switch (builder.augmentation.size()) { case 0: this.augmentation = Collections.emptyMap(); break; case 1: final Map.Entry<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>> e = builder.augmentation.entrySet().iterator().next(); this.augmentation = Collections.<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>>singletonMap(e.getKey(), e.getValue()); break; default : this.augmentation = new HashMap<>(builder.augmentation); } } @Override public GroupRef getGroupRef() { return _groupRef; } @Override public Boolean isBarrier() { return _barrier; } @Override public Buckets getBuckets() { return _buckets; } @Override public String getContainerName() { return _containerName; } @Override public GroupId getGroupId() { return _groupId; } @Override public String getGroupName() { return _groupName; } @Override public GroupTypes getGroupType() { return _groupType; } @Override public NodeRef getNode() { return _node; } @Override public TransactionId getTransactionId() { return _transactionId; } @Override public Uri getTransactionUri() { return _transactionUri; } @SuppressWarnings("unchecked") @Override public <E extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated>> E getAugmentation(Class<E> augmentationType) { if (augmentationType == null) { throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!"); } return (E) augmentation.get(augmentationType); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_groupRef == null) ? 0 : _groupRef.hashCode()); result = prime * result + ((_barrier == null) ? 0 : _barrier.hashCode()); result = prime * result + ((_buckets == null) ? 0 : _buckets.hashCode()); result = prime * result + ((_containerName == null) ? 0 : _containerName.hashCode()); result = prime * result + ((_groupId == null) ? 0 : _groupId.hashCode()); result = prime * result + ((_groupName == null) ? 0 : _groupName.hashCode()); result = prime * result + ((_groupType == null) ? 0 : _groupType.hashCode()); result = prime * result + ((_node == null) ? 0 : _node.hashCode()); result = prime * result + ((_transactionId == null) ? 0 : _transactionId.hashCode()); result = prime * result + ((_transactionUri == null) ? 0 : _transactionUri.hashCode()); result = prime * result + ((augmentation == null) ? 0 : augmentation.hashCode()); return result; } @Override public boolean equals(java.lang.Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } GroupUpdatedImpl other = (GroupUpdatedImpl) obj; if (_groupRef == null) { if (other._groupRef != null) { return false; } } else if(!_groupRef.equals(other._groupRef)) { return false; } if (_barrier == null) { if (other._barrier != null) { return false; } } else if(!_barrier.equals(other._barrier)) { return false; } if (_buckets == null) { if (other._buckets != null) { return false; } } else if(!_buckets.equals(other._buckets)) { return false; } if (_containerName == null) { if (other._containerName != null) { return false; } } else if(!_containerName.equals(other._containerName)) { return false; } if (_groupId == null) { if (other._groupId != null) { return false; } } else if(!_groupId.equals(other._groupId)) { return false; } if (_groupName == null) { if (other._groupName != null) { return false; } } else if(!_groupName.equals(other._groupName)) { return false; } if (_groupType == null) { if (other._groupType != null) { return false; } } else if(!_groupType.equals(other._groupType)) { return false; } if (_node == null) { if (other._node != null) { return false; } } else if(!_node.equals(other._node)) { return false; } if (_transactionId == null) { if (other._transactionId != null) { return false; } } else if(!_transactionId.equals(other._transactionId)) { return false; } if (_transactionUri == null) { if (other._transactionUri != null) { return false; } } else if(!_transactionUri.equals(other._transactionUri)) { return false; } if (augmentation == null) { if (other.augmentation != null) { return false; } } else if(!augmentation.equals(other.augmentation)) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder("GroupUpdated ["); boolean first = true; if (_groupRef != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_groupRef="); builder.append(_groupRef); } if (_barrier != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_barrier="); builder.append(_barrier); } if (_buckets != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_buckets="); builder.append(_buckets); } if (_containerName != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_containerName="); builder.append(_containerName); } if (_groupId != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_groupId="); builder.append(_groupId); } if (_groupName != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_groupName="); builder.append(_groupName); } if (_groupType != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_groupType="); builder.append(_groupType); } if (_node != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_node="); builder.append(_node); } if (_transactionId != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_transactionId="); builder.append(_transactionId); } if (_transactionUri != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_transactionUri="); builder.append(_transactionUri); } if (first) { first = false; } else { builder.append(", "); } builder.append("augmentation="); builder.append(augmentation.values()); return builder.append(']').toString(); } } }
niuqg/controller
opendaylight/md-sal/model/model-flow-service/src/main/yang-gen-sal/org/opendaylight/yang/gen/v1/urn/opendaylight/group/service/rev130918/GroupUpdatedBuilder.java
Java
epl-1.0
20,277
/******************************************************************************* * Copyright (c) 2011, 2020 Eurotech 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 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.net.admin.modem; import org.eclipse.kura.KuraErrorCode; import org.eclipse.kura.KuraException; import org.eclipse.kura.executor.CommandExecutorService; import org.eclipse.kura.linux.net.dns.LinuxDns; import org.eclipse.kura.linux.net.ppp.PppLinux; import org.eclipse.kura.linux.net.util.LinuxIfconfig; import org.eclipse.kura.linux.net.util.LinuxNetworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Ppp implements IModemLinkService { private static final Logger logger = LoggerFactory.getLogger(Ppp.class); private static final Object LOCK = new Object(); private final String iface; private final String port; private final CommandExecutorService executorService; private final PppLinux pppLinux; private final LinuxNetworkUtil linuxNetworkUtil; public Ppp(String iface, String port, CommandExecutorService executorService) { this.iface = iface; this.port = port; this.executorService = executorService; this.pppLinux = new PppLinux(executorService); this.linuxNetworkUtil = new LinuxNetworkUtil(executorService); } @Override public void connect() throws KuraException { this.pppLinux.connect(this.iface, this.port); } @Override public void disconnect() throws KuraException { logger.info("disconnecting :: stopping PPP monitor ..."); this.pppLinux.disconnect(this.iface, this.port); try { LinuxDns linuxDns = LinuxDns.getInstance(); if (linuxDns.isPppDnsSet()) { linuxDns.unsetPppDns(this.executorService); } } catch (Exception e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } } @Override public String getIPaddress() throws KuraException { String ipAddress = null; LinuxIfconfig ifconfig = this.linuxNetworkUtil.getInterfaceConfiguration(this.iface); if (ifconfig != null) { ipAddress = ifconfig.getInetAddress(); } return ipAddress; } @Override public String getIfaceName() { return this.iface; } @Override public PppState getPppState() throws KuraException { synchronized (LOCK) { final PppState pppState; final boolean pppdRunning = this.pppLinux.isPppProcessRunning(this.iface, this.port); final String ip = getIPaddress(); if (pppdRunning && ip != null) { pppState = PppState.CONNECTED; } else if (pppdRunning) { pppState = PppState.IN_PROGRESS; } else { pppState = PppState.NOT_CONNECTED; } return pppState; } } }
nicolatimeus/kura
kura/org.eclipse.kura.net.admin/src/main/java/org/eclipse/kura/net/admin/modem/Ppp.java
Java
epl-1.0
3,282
package ch.elexis.core.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.time.LocalDate; import java.time.Month; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import ch.elexis.core.model.builder.ICoverageBuilder; import ch.elexis.core.model.builder.IEncounterBuilder; import ch.elexis.core.services.IQuery; import ch.elexis.core.services.IQuery.COMPARATOR; import ch.elexis.core.test.AbstractTest; import ch.rgw.tools.Money; import ch.rgw.tools.Result; import ch.rgw.tools.VersionedResource; public class EncounterTest extends AbstractTest { @Override @Before public void before(){ super.before(); super.createUserSetActiveInContext(); super.createMandator(); super.createPatient(); super.createCoverage(); } @Override @After public void after() { super.after(); } @Test public void createFindDeleteEncounter(){ IEncounter encounter = new IEncounterBuilder(coreModelService, coverage, mandator).buildAndSave(); LocalDate date = LocalDate.of(2018, Month.SEPTEMBER, 21); encounter.setDate(date); VersionedResource vr = VersionedResource.load(null); vr.update("Test consultation\nWith some test text.", "Administrator"); vr.update("Test consultation\n pdate done by user", "user"); encounter.setVersionedEntry(vr); coreModelService.save(encounter); IQuery<IEncounter> query = coreModelService.getQuery(IEncounter.class); query.and(ModelPackage.Literals.IENCOUNTER__COVERAGE, COMPARATOR.EQUALS, coverage); assertEquals(encounter, query.executeSingleResult().get()); assertEquals(date, encounter.getDate()); assertTrue(encounter.getVersionedEntry().getHead(), encounter.getVersionedEntry().getHead().contains("done by user")); coreModelService.delete(encounter); } @Test public void addRemoveDiagnosis(){ IEncounter encounter = new IEncounterBuilder(coreModelService, coverage, mandator).buildAndSave(); IDiagnosisReference diagnosis = coreModelService.create(IDiagnosisReference.class); diagnosis.setCode("test"); coreModelService.save(diagnosis); IDiagnosisReference diagnosis1 = coreModelService.create(IDiagnosisReference.class); diagnosis.setCode("test1"); coreModelService.save(diagnosis1); encounter.addDiagnosis(diagnosis); encounter.addDiagnosis(diagnosis1); coreModelService.save(encounter); Optional<IEncounter> loaded = coreModelService.load(encounter.getId(), IEncounter.class); assertEquals(loaded.get(), encounter); assertEquals(encounter.getDiagnoses().size(), loaded.get().getDiagnoses().size()); encounter.removeDiagnosis(diagnosis1); coreModelService.save(encounter); loaded = coreModelService.load(encounter.getId(), IEncounter.class); assertEquals(loaded.get(), encounter); assertEquals(encounter.getDiagnoses().size(), loaded.get().getDiagnoses().size()); encounter.removeDiagnosis(diagnosis); coreModelService.save(encounter); loaded = coreModelService.load(encounter.getId(), IEncounter.class); assertEquals(loaded.get(), encounter); assertTrue(loaded.get().getDiagnoses().isEmpty()); coreModelService.remove(diagnosis); coreModelService.remove(diagnosis1); coreModelService.remove(encounter); } @Test public void addRemoveBilled(){ ICustomService service = coreModelService.create(ICustomService.class); service.setCode("12.34"); service.setNetPrice(new Money(1)); service.setPrice(new Money(2)); service.setText("test"); coreModelService.save(service); IEncounter encounter = new IEncounterBuilder(coreModelService, coverage, mandator).buildAndSave(); coreModelService.save(encounter); Result<IBilled> result = service.getOptifier().add(service, encounter, 1.5); assertTrue(result.isOK()); assertFalse(encounter.getBilled().isEmpty()); Optional<IEncounter> loaded = coreModelService.load(encounter.getId(), IEncounter.class); assertEquals(loaded.get(), encounter); assertFalse(loaded.get().getBilled().isEmpty()); IBilled billed = loaded.get().getBilled().get(0); assertEquals(1.5, billed.getAmount(), 0.01); assertEquals(service.getText(), billed.getText()); assertEquals(service, billed.getBillable()); encounter.removeBilled(billed); assertFalse(encounter.getBilled().contains(billed)); assertTrue(billed.isDeleted()); coreModelService.remove(service); coreModelService.remove(encounter); } @SuppressWarnings("unchecked") @Test public void modifyBilled(){ ICustomService service = coreModelService.create(ICustomService.class); service.setCode("12.34"); service.setNetPrice(new Money(1)); service.setPrice(new Money(2)); service.setText("test"); coreModelService.save(service); IEncounter encounter = new IEncounterBuilder(coreModelService, coverage, mandator).buildAndSave(); coreModelService.save(encounter); // add billed Result<IBilled> result = service.getOptifier().add(service, encounter, 1.5); assertTrue(result.isOK()); IBilled billed = encounter.getBilled().get(0); assertEquals(1.5, billed.getAmount(), 0.01); // change property and save -> results in new entity which leads to problem (reason for caching lists in Adapters) billed.setText("changed text"); coreModelService.save(billed); // add amount result = service.getOptifier().add(service, encounter, 1.5); assertEquals(3, billed.getAmount(), 0.01); billed = encounter.getBilled().get(0); assertEquals(3, billed.getAmount(), 0.01); coreModelService.remove(service); coreModelService.remove(encounter); } @SuppressWarnings("unchecked") @Test public void multiThreadMappedProperties() throws InterruptedException{ IEncounter encounter = new IEncounterBuilder(coreModelService, coverage, mandator).buildAndSave(); coreModelService.save(encounter); ExecutorService executor = Executors.newFixedThreadPool(3); for (int i = 0; i < 100; i++) { final int number = i; executor.execute(() -> { contextService.setActiveUser(user); ICustomService service = coreModelService.create(ICustomService.class); service.setCode("code" + number); service.setNetPrice(new Money(number)); service.setPrice(new Money(number)); service.setText("test" + number); coreModelService.save(service); Result<IBilled> result = service.getOptifier().add(service, encounter, 1); assertNotNull(result); assertTrue(result.isOK()); }); executor.execute(() -> { if (!encounter.getVersionedEntry() .update("Test consultation\nmulti billing " + number, "Administrator")) { fail(); } coreModelService.save(encounter); }); } executor.shutdown(); executor.awaitTermination(5, TimeUnit.SECONDS); assertEquals(100, encounter.getBilled().size()); assertTrue(encounter.getLastupdate() > 0); for (IBilled billed : encounter.getBilled()) { assertTrue(billed.getLastupdate() > 0); } coreModelService.remove(encounter); IQuery<ICustomService> query = coreModelService.getQuery(ICustomService.class); for (ICustomService service : query.execute()) { coreModelService.remove(service); } } @Test public void changeCoverage(){ IEncounter encounter = new IEncounterBuilder(coreModelService, coverage, mandator).buildAndSave(); LocalDate date = LocalDate.of(2018, Month.SEPTEMBER, 21); encounter.setDate(date); coreModelService.save(encounter); IEncounter encounter1 = new IEncounterBuilder(coreModelService, coverage, mandator).buildAndSave(); LocalDate date1 = LocalDate.of(2018, Month.SEPTEMBER, 22); encounter.setDate(date1); coreModelService.save(encounter1); assertEquals(2, coverage.getEncounters().size()); ICoverage coverage1 = new ICoverageBuilder(coreModelService, patient, "testCoverage1", "testReason1", "testBillingSystem1").buildAndSave(); encounter1.setCoverage(coverage1); coreModelService.save(encounter1); assertEquals(1, coverage1.getEncounters().size()); assertEquals(1, coverage.getEncounters().size()); coreModelService.delete(encounter); } @Test public void addAndUpdateVersionsEntry(){ IEncounter encounter = new IEncounterBuilder(coreModelService, coverage, mandator).buildAndSave(); VersionedResource vr = VersionedResource.load(null); vr.update("TESTME", "Administrator"); encounter.setVersionedEntry(vr); coreModelService.save(encounter); assertEquals("TESTME", encounter.getVersionedEntry().getHead()); encounter.getVersionedEntry().update("changed", ""); coreModelService.save(encounter); assertEquals("changed", encounter.getVersionedEntry().getHead()); assertEquals("changed", coreModelService.load(encounter.getId(), IEncounter.class).get() .getVersionedEntry().getHead()); assertEquals("changed", coreModelService.load(encounter.getId(), IEncounter.class, true, true).get() .getVersionedEntry().getHead()); } }
elexis/elexis-3-core
tests/ch.elexis.core.model.test/src/ch/elexis/core/model/EncounterTest.java
Java
epl-1.0
9,169
/* First created by JCasGen Wed Mar 16 10:14:05 CET 2011 */ package org.u_compare.shared.label.penn.bracket.release; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.u_compare.shared.label.penn.bracket.general.NounPhrase_Type; /** Used within certain complex NPs to mark the head of the NP * Updated by JCasGen Tue Mar 06 16:28:15 CET 2012 * @generated */ public class NX_Type extends NounPhrase_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (NX_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = NX_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new NX(addr, NX_Type.this); NX_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new NX(addr, NX_Type.this); } }; /** @generated */ public final static int typeIndexID = NX.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("org.u_compare.shared.label.penn.bracket.release.NX"); /** initialize variables to correspond with Cas Type and Features * @generated */ public NX_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
rockt/ChemSpot
src/main/types/org/u_compare/shared/label/penn/bracket/release/NX_Type.java
Java
epl-1.0
1,799
package org.allmyinfo.operation; import org.allmyinfo.util.osgi.reactor.BaseReactor; import org.eclipse.jdt.annotation.NonNull; import org.osgi.framework.BundleContext; public interface TypeRegistry { @NonNull Class<?> get(@NonNull String name); void add(@NonNull Class<?> type); public static class Reactor extends BaseReactor { @SuppressWarnings("null") public Reactor(final @NonNull BundleContext bundleContext, final @NonNull TypeRegistry defaultInstance) { super(bundleContext, TypeRegistry.class.getName(), null, defaultInstance); } @Override public @NonNull TypeRegistry getInstance() { return (TypeRegistry) super.getInstance(); } } }
sschafer/atomic
org.allmyinfo.operation/src/org/allmyinfo/operation/TypeRegistry.java
Java
epl-1.0
675
/** * Eclipse Public License - v 1.0 * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION * OF THE * PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * 1. DEFINITIONS * * "Contribution" means: * * a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and * b) in the case of each subsequent Contributor: * i) changes to the Program, and * ii) additions to the Program; * where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution * 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. * Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program * under their own license agreement, and (ii) are not derivative works of the Program. * "Contributor" means any person or entity that distributes the Program. * * "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone * or when combined with the Program. * * "Program" means the Contributions distributed in accordance with this Agreement. * * "Recipient" means anyone who receives the Program under this Agreement, including all Contributors. * * 2. GRANT OF RIGHTS * * a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license * to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, * if any, and such derivative works, in source code and object code form. * b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license * under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source * code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the * Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The * patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. * c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided * by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor * disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. * As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other * intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the * Program, it is Recipient's responsibility to acquire that license before distributing the Program. * d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright * license set forth in this Agreement. * 3. REQUIREMENTS * * A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: * * a) it complies with the terms and conditions of this Agreement; and * b) its license agreement: * i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions * of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; * ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and * consequential damages, such as lost profits; * iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and * iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner * on or through a medium customarily used for software exchange. * When the Program is made available in source code form: * * a) it must be made available under this Agreement; and * b) a copy of this Agreement must be included with each copy of the Program. * Contributors may not remove or alter any copyright notices contained within the Program. * * Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients * to identify the originator of the Contribution. * * 4. COMMERCIAL DISTRIBUTION * * Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this * license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering * should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in * a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor * ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions * brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in * connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or * Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly * notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the * Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim * at its own expense. * * For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial * Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims * and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend * claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay * any damages as a result, the Commercial Contributor must pay those damages. * * 5. NO WARRANTY * * EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS * FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and * assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program * errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. * * 6. DISCLAIMER OF LIABILITY * * EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION * OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * 7. GENERAL * * If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the * remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum * extent necessary to make such provision valid and enforceable. * * If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program * itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's * rights granted under Section 2(b) shall terminate as of the date such litigation is filed. * * All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this * Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights * under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, * Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. * * Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may * only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this * Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the * initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate * entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be * distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is * published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in * Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, * whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. * * This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to * this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights * to a jury trial in any resulting litigation. */ package com.runescape.server.revised.content.skill.combat; public class LegacyMode { }
RodriguesJ/Atem
src/com/runescape/server/revised/content/skill/combat/LegacyMode.java
Java
epl-1.0
11,717
package ebikyatto.pycalculator.model.club; import org.springframework.stereotype.Component; import ebikyatto.pycalculator.common.abstracts.Club; @Component public class Club4I extends Club { }
ebikyatto/pycalculator
src/main/java/ebikyatto/pycalculator/model/club/Club4I.java
Java
epl-1.0
196
package com.temenos.t24.tools.eclipse.basic.protocols.ftp; import com.temenos.t24.tools.eclipse.basic.PluginConstants; import com.temenos.t24.tools.eclipse.basic.utils.EclipseUtil; /** * Utility class for remote file transfer. * * @author ssethupathi * */ public final class RemoteFileTransferUtil { /** * Returns the default local path of the file name passed. * * @param fileName * @return default local path */ public static String getDefaultLocalPath(String fileName) { String filePath = ""; filePath = EclipseUtil.getTemporaryProject().toOSString() + "//" + T24FTPClientHelper.getLocalFileName(fileName); return filePath; } /** * Removes the .d extension from the data file. * * @param fileName file name. * @return file name extension removed. */ public static String removeDataFileExtension(String fileName) { if (fileName == null) { return null; } String extn = ".d"; if (fileName.endsWith(extn)) { int length = fileName.length(); fileName = fileName.substring(0, length - 2); return fileName; } return fileName; } /** * Returns the remote path in respect to the local path and remote root. * * @param localRoot * @param localFullPath * @param remoteRoot * @return */ public static String getExtendedeRmotePath(String localRoot, String localFullPath, String remoteRoot) { String extendedRemotePath = remoteRoot; if (localFullPath != null && localFullPath.startsWith(localRoot)) { String tempPath = localFullPath.replace(localRoot, ""); extendedRemotePath = remoteRoot + tempPath; extendedRemotePath = extendedRemotePath.replace('\\', '/'); int endIndex = extendedRemotePath.lastIndexOf('/'); if (endIndex > 0) { extendedRemotePath = extendedRemotePath.substring(0, endIndex); } } return extendedRemotePath; } /** * Returns the list of sub directories to be created from the remote root to * the full remote path. * * @param base * @param extended * @return */ public static String[] getSubDirectories(String base, String extended) { if (base == null || extended == null) { return null; // TODO: Handle it! } if (extended.startsWith(base)) { String tempPath = extended.replace(base + "/", ""); return tempPath.split("/"); } return null; } /** * returns the hyperlink path to look as configured in preference page. If * no value is specified GLOBUS.BP will be returned * * @return directories */ public static synchronized String[] getHyperLinkDirectories() { String remoteDir = EclipseUtil.getPreferenceStore().getString(PluginConstants.T24_HYPERLINK_DIR).trim(); String[] remoteDirList = null; if (remoteDir.length() == 0) { remoteDirList = new String[] { PluginConstants.SERVER_PRIMARY_SOURCE_ALTERNATE, PluginConstants.SERVER_PRIMARY_SOURCE }; } else { remoteDirList = remoteDir.split(","); } return remoteDirList; } }
debabratahazra/DS
designstudio/components/basic/ui/com.odcgroup.basic.ui/src/main/java/com/temenos/t24/tools/eclipse/basic/protocols/ftp/RemoteFileTransferUtil.java
Java
epl-1.0
3,357
/* * */ package SimpleBPMN.diagram.providers.assistants; /** * @generated */ public class SimpleBPMNModelingAssistantProviderOfPool2EditPart extends SimpleBPMN.diagram.providers.SimpleBPMNModelingAssistantProvider { }
bluezio/simplified-bpmn-example
org.eclipse.epsilon.eugenia.bpmn.diagram/src/SimpleBPMN/diagram/providers/assistants/SimpleBPMNModelingAssistantProviderOfPool2EditPart.java
Java
epl-1.0
227
var a = 10; var num = parseInt("70");
watrool/orion_tools_visualstudio
test.js
JavaScript
epl-1.0
38
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ /*global define*/ define('Nexus/navigation/section',['extjs', 'sonatype', 'Sonatype/strings'], function(Ext, Sonatype, Strings){ Ext.namespace('Sonatype.navigation'); Sonatype.navigation.Section = function(cfg) { var config = cfg || {}, defaultConfig = { collapsible : true, titleCollapse : true, collapsed : false }; if (config.items) { config.items = this.transformItem(config.items); } if (!config.items || config.items.length === 0) { config.hidden = true; } Ext.apply(this, config, defaultConfig); Sonatype.navigation.Section.superclass.constructor.call(this, { cls : 'st-server-sub-container', layout : 'fit', frame : true, autoHeight : true, hideMode : 'offsets', animCollapse : false, listeners : { collapse : this.collapseExpandHandler, expand : this.collapseExpandHandler, scope : this } }); }; Ext.extend(Sonatype.navigation.Section, Ext.Panel, { collapseExpandHandler : function() { if (this.layout && this.layout.layout) { this.ownerCt.doLayout(); } }, transformItem : function(c) { if (!c) { return null; } var i, item, c2; if (Ext.isArray(c)) { c2 = []; for (i = 0; i < c.length; i=i+1) { item = this.transformItem(c[i]); if (item) { c2.push(item); } } return c2; } if (!c.xtype) { if (c.href) { // regular external link return { sortable_title : c.title, autoHeight : true, html : '<ul class="group-links"><li><a href="' + c.href + '" target="' + c.href + '"' + (c.style ? ' style="' + c.style + '"' : '') + '>' + c.title + '</a></li></ul>' }; } else if (c.tabCode || c.handler) { if (Sonatype.view.supportedNexusTabs) { Sonatype.view.supportedNexusTabs[c.tabId] = true; } // panel open action return (c.enabled === false) ? null : { sortable_title : c.title, autoHeight : true, id : 'navigation-' + c.tabId, initialConfigNavigation : c, listeners : { render : { fn : function(panel) { panel.body.on('click', Ext.emptyFn, null, { delegate : 'a', preventDefault : true }); panel.body.on('mousedown', function(e, target) { e.stopEvent(); if (c.handler) { c.handler(); } else { Sonatype.view.mainTabPanel.addOrShowTab(c.tabId, c.tabCode, { title : c.tabTitle || c.title }); } }, c.scope, { delegate : 'a' }); }, scope : this } }, html : '<ul class="group-links"><li><a href="#">' + c.title + '</a></li></ul>' }; } } return c; }, add : function(c) { var i, arr = null, a = arguments; if (a.length > 1) { arr = a; } else if (Ext.isArray(c)) { arr = c; } if (arr !== null) { for (i = 0; i < arr.length; i=i+1) { this.add(arr[i]); } return; } c = this.transformItem(c); if (!c) { return; } if (this.hidden) { this.show(); } return Sonatype.navigation.Section.superclass.add.call(this, c); }, sort : function(asOrder) { if(!this.items) { return; } var _fSorter = function(obj1, obj2) { var fieldName = "sortable_title"; return Strings.sortFn(obj1[fieldName], obj2[fieldName]); }; this.items.sort(asOrder || 'ASC', _fSorter); } }); });
scmod/nexus-public
plugins/basic/nexus-ui-extjs3-plugin/src/main/resources/static/js/Nexus/navigation/section.js
JavaScript
epl-1.0
5,383
/******************************************************************************* * 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 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Bosch Software Innovations GmbH - Please refer to git log *******************************************************************************/ package org.eclipse.vorto.perspective; import java.net.URL; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.ViewPart; import org.eclipse.vorto.core.model.IModelElement; import org.eclipse.vorto.core.model.IModelProject; import org.eclipse.vorto.core.service.ModelProjectServiceFactory; import org.eclipse.vorto.core.ui.changeevent.ModelProjectChangeEvent; import org.eclipse.vorto.core.ui.changeevent.ModelProjectDeleteEvent; import org.eclipse.vorto.core.ui.changeevent.ModelProjectEventListenerRegistry; import org.eclipse.vorto.core.ui.changeevent.NewModelProjectEvent; public abstract class AbstractTreeViewPart extends ViewPart implements IModelContentProvider { protected TreeViewer treeViewer; protected IContentProvider contentProvider; protected ILabelProvider labelProvider; public void createPartControl(Composite parent) { init(); // Create the tree viewer as a child of the composite parent treeViewer = new TreeViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL); treeViewer.setContentProvider(contentProvider); treeViewer.setLabelProvider(labelProvider); treeViewer.setUseHashlookup(true); hookListeners(); treeViewer.setInput(getContent()); ColumnViewerToolTipSupport.enableFor(treeViewer); getSite().setSelectionProvider(treeViewer); initContextMenu(); } protected void init() { DefaultTreeModelContentProvider contentProvider = new DefaultTreeModelContentProvider( this); ModelProjectEventListenerRegistry.getInstance().add(contentProvider); this.contentProvider = contentProvider; this.labelProvider = new DefaultTreeModelLabelProvider(); } private void initContextMenu() { // initalize the context menu MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$ Menu menu = menuMgr.createContextMenu(this.treeViewer.getTree()); this.treeViewer.getTree().setMenu(menu); getSite().registerContextMenu(menuMgr, this.treeViewer); } protected void hookListeners() { addSelectionChangedEventListener(treeViewer); addWorkspaceChangeEventListenr(); } public ImageDescriptor getImage(String imageFileName) { URL url; try { url = new URL( "platform:/plugin/org.eclipse.vorto.fbeditor.ui/icons/" + imageFileName); return ImageDescriptor.createFromURL(url); } catch (Exception e) { e.printStackTrace(); } return null; } protected void addWorkspaceChangeEventListenr() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IResourceChangeListener rcl = new IResourceChangeListener() { public void resourceChanged(IResourceChangeEvent event) { if (hasChanges(event)) { processChanges(event.getDelta()); } } private boolean hasChanges(IResourceChangeEvent event) { return event.getDelta() != null && event.getDelta().getAffectedChildren() != null; } }; workspace.addResourceChangeListener(rcl); } private void processChanges(IResourceDelta changes) { for (IResourceDelta change : changes.getAffectedChildren()) { IProject project = change.getResource().getProject(); IModelChangeProcessor processor = ModelChangeProcessorFactory .getModelChangeProcessor(change.getKind()); processor.processChange(project); } } private static class ModelChangeProcessorFactory { private static final IModelChangeProcessor MODEL_DELETE_PROCESSOR = new ModelDeleteProcessor(); private static final IModelChangeProcessor NEW_MODEL_PROCESSOR = new NewModelProcessor(); private static final IModelChangeProcessor MODEL_CHANGE_PROCESSOR = new ModelChangeProcessor(); public static IModelChangeProcessor getModelChangeProcessor( int changeKind) { if (changeKind == IResourceDelta.REMOVED || changeKind == IResourceDelta.REMOVED_PHANTOM) { return MODEL_DELETE_PROCESSOR; } else if (changeKind == IResourceDelta.ADDED || changeKind == IResourceDelta.ADDED_PHANTOM) { return NEW_MODEL_PROCESSOR; } else { return MODEL_CHANGE_PROCESSOR; } } } /** * Provide operation to handle model project change */ private static interface IModelChangeProcessor { /** * Process model change based give project * * @param project * : Project that has been changed */ void processChange(IProject project); } private final static class ModelDeleteProcessor implements IModelChangeProcessor { public ModelDeleteProcessor() { } @Override public void processChange(IProject project) { ModelProjectEventListenerRegistry.getInstance().sendDeleteEvent( new ModelProjectDeleteEvent(project.getName())); } } private final static class NewModelProcessor implements IModelChangeProcessor { public NewModelProcessor() { } @Override public void processChange(IProject project) { if (isModelProject(project)) { IModelProject modelProject = getModelProject(project); ModelProjectEventListenerRegistry.getInstance().sendAddedEvent( new NewModelProjectEvent(modelProject)); } } } private final static class ModelChangeProcessor implements IModelChangeProcessor { public ModelChangeProcessor() { } @Override public void processChange(IProject project) { if (isModelProject(project)) { IModelProject modelProject = getModelProject(project); ModelProjectEventListenerRegistry.getInstance() .sendChangeEvent( new ModelProjectChangeEvent(modelProject)); } } } private static boolean isModelProject(IProject project) { IModelProject modelProject = getModelProject(project); return modelProject != null; } private static IModelProject getModelProject(IProject project) { try { return ModelProjectServiceFactory.getDefault() .getProjectFromEclipseProject(project); } catch (IllegalArgumentException e) { // ingore model parsing exception due to model not found } return null; } @Override public void setFocus() { } protected void addSelectionChangedEventListener(TreeViewer treeviewer) { treeviewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (event.getSelection().isEmpty()) { return; } if (event.getSelection() instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) event .getSelection(); if (selection.size() > 0) { if (selection.getFirstElement() instanceof IModelElement) { IModelElement modelElement = (IModelElement) selection .getFirstElement(); if (modelElement.getModelFile() != null) { openFileInEditor(modelElement.getModelFile()); } } } } } }); } protected void openFileInEditor(IFile fileToOpen) { if (fileToOpen.exists()) { org.eclipse.ui.IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); try { IDE.openEditor(page, fileToOpen); } catch (org.eclipse.ui.PartInitException e) { e.printStackTrace(); } } else { System.out.println("File not found for: " + fileToOpen); } } }
aedelmann/vorto
bundles/org.eclipse.vorto.perspective/src/org/eclipse/vorto/perspective/AbstractTreeViewPart.java
Java
epl-1.0
8,783
/** * Copyright (c) 2014-2017 by the respective copyright holders. * 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.smarthome.binding.tradfri.internal.discovery; import static org.eclipse.smarthome.binding.tradfri.TradfriBindingConstants.*; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.eclipse.smarthome.binding.tradfri.TradfriBindingConstants; import org.eclipse.smarthome.binding.tradfri.handler.TradfriGatewayHandler; import org.eclipse.smarthome.binding.tradfri.internal.DeviceUpdateListener; import org.eclipse.smarthome.config.discovery.AbstractDiscoveryService; import org.eclipse.smarthome.config.discovery.DiscoveryResult; import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; /** * This class identifies devices that are available on the gateway and adds discovery results for them. * * @author Kai Kreuzer - Initial contribution */ public class TradfriDiscoveryService extends AbstractDiscoveryService implements DeviceUpdateListener { private Logger logger = LoggerFactory.getLogger(TradfriDiscoveryService.class); private TradfriGatewayHandler handler; private String[] COLOR_TEMP_MODELS = new String[] { "TRADFRI bulb E27 WS opal 980lm", "TRADFRI bulb GU10 WS 400lm" }; public TradfriDiscoveryService(TradfriGatewayHandler bridgeHandler) { super(TradfriBindingConstants.SUPPORTED_LIGHT_TYPES_UIDS, 10, true); this.handler = bridgeHandler; } @Override protected void startScan() { handler.startScan(); } public void activate() { handler.registerDeviceUpdateListener(this); } @Override public void deactivate() { handler.unregisterDeviceUpdateListener(this); } @Override public void onUpdate(String instanceId, JsonObject data) { ThingUID bridge = handler.getThing().getUID(); try { if (data.has(INSTANCE_ID)) { int id = data.get(INSTANCE_ID).getAsInt(); String type = data.get(TYPE).getAsString(); JsonObject deviceInfo = data.get(DEVICE).getAsJsonObject(); String model = deviceInfo.get(DEVICE_MODEL).getAsString(); ThingUID thingId = null; if (type.equals(TYPE_LIGHT) && data.has(LIGHT)) { JsonObject state = data.get(LIGHT).getAsJsonArray().get(0).getAsJsonObject(); // Color temperature light // We do not always receive a COLOR attribute, even the light supports it - but the gateway does not // seem to have this information, if the bulb is unreachable. We therefore also check against // concrete model names. if (state.has(COLOR) || (model != null && Arrays.asList(COLOR_TEMP_MODELS).contains(model))) { thingId = new ThingUID(THING_TYPE_COLOR_TEMP_LIGHT, bridge, Integer.toString(id)); } else { thingId = new ThingUID(THING_TYPE_DIMMABLE_LIGHT, bridge, Integer.toString(id)); } } if (thingId == null) { // we didn't identify any device, so let's quit return; } String label = data.get(NAME).getAsString(); Map<String, Object> properties = new HashMap<>(1); properties.put("id", id); properties.put(Thing.PROPERTY_MODEL_ID, model); if (deviceInfo.get(DEVICE_VENDOR) != null) { properties.put(Thing.PROPERTY_VENDOR, deviceInfo.get(DEVICE_VENDOR).getAsString()); } if (deviceInfo.get(DEVICE_FIRMWARE) != null) { properties.put(Thing.PROPERTY_FIRMWARE_VERSION, deviceInfo.get(DEVICE_FIRMWARE).getAsString()); } logger.debug("Adding device {} to inbox", thingId); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingId).withBridge(bridge) .withLabel(label).withProperties(properties).withRepresentationProperty("id").build(); thingDiscovered(discoveryResult); } } catch (JsonSyntaxException e) { logger.debug("JSON error during discovery: {}", e.getMessage()); } } }
vkolotov/smarthome
extensions/binding/org.eclipse.smarthome.binding.tradfri/src/main/java/org/eclipse/smarthome/binding/tradfri/internal/discovery/TradfriDiscoveryService.java
Java
epl-1.0
4,883
public class CarSpeedMeter extends SpeedMeter { public double getRadius() { return 0.28; } public static void main(String[] args) { CarSpeedMeter csm = new CarSpeedMeter(); csm.setTurnRate(15); System.out.println(csm.getSpeed()); System.out.println("Hello World!"); } }
xuchunhui/Java
codes/06/6-5/CarSpeedMeter.java
Java
epl-1.0
288
package org.matmaul.freeboxos.wifi; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; @JsonAutoDetect(fieldVisibility = Visibility.ANY) public class WifiGlobalConfig { protected Boolean enabled; protected String mac_filter_state; // enum disabled, whitelist, blacklist public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public String getMacFilterState() { return mac_filter_state; } } /*public class WifiGlobalConfig { public BSS bss; public Ap_Params ap_params; public static class BSS { public Perso perso; } public static class Perso { public Boolean enabled; public String ssid; public String encryption; public int eapol_version; public Boolean hide_ssid; public String mac_filter; public String key; } public static class Ap_Params { public Boolean enabled; public String ht_mode; public int channel; } public Boolean getEnabled() { return ap_params.enabled; } public void setEnabled(Boolean enabled) { ap_params.enabled = enabled; bss.perso.enabled = enabled; } public String getMacFilter() { return bss.perso.mac_filter; } }*/
MatMaul/freeboxos-java
src/org/matmaul/freeboxos/wifi/WifiGlobalConfig.java
Java
epl-1.0
1,244
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ package org.sonatype.nexus.web; import java.util.List; /** * Container for contributed {@link WebResource}. * * @since 2.8 */ public interface WebResourceBundle { List<WebResource> getResources(); }
scmod/nexus-public
components/nexus-core/src/main/java/org/sonatype/nexus/web/WebResourceBundle.java
Java
epl-1.0
987
/****************************************************************************** ** Copyright (c) 2008-2014 Franz 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 ******************************************************************************/ package com.franz.agraph.http.handler; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.HttpMethod; import org.openrdf.query.resultio.BooleanQueryResultFormat; import org.openrdf.query.resultio.BooleanQueryResultParser; import org.openrdf.query.resultio.QueryResultIO; import org.openrdf.query.resultio.QueryResultParseException; import com.franz.agraph.http.exception.AGHttpException; public class AGBQRHandler extends AGResponseHandler { private boolean result; public AGBQRHandler() { super(BooleanQueryResultFormat.TEXT.getDefaultMIMEType()); } @Override public void handleResponse(HttpMethod method) throws IOException, AGHttpException { String mimeType = getResponseMIMEType(method); if (!mimeType.equals(getRequestMIMEType())) { throw new AGHttpException("unexpected response MIME type: " + mimeType); } InputStream response = getInputStream(method); try { BooleanQueryResultFormat format = BooleanQueryResultFormat.TEXT; BooleanQueryResultParser parser = QueryResultIO.createParser(format); result = parser.parse(response); } catch (QueryResultParseException e) { throw new AGHttpException(e); } } public boolean getResult() { return result; } }
mohanever4u/ag-java-client
src/com/franz/agraph/http/handler/AGBQRHandler.java
Java
epl-1.0
1,695
require "rjava" # Copyright (c) 2000, 2009 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 module Org::Eclipse::Swt::Internal::Cocoa module NSTextFieldImports #:nodoc: class_module.module_eval { include ::Java::Lang include ::Org::Eclipse::Swt::Internal::Cocoa } end class NSTextField < NSTextFieldImports.const_get :NSControl include_class_members NSTextFieldImports typesig { [] } def initialize super() end typesig { [::Java::Int] } # long def initialize(id) super(id) end typesig { [Id] } def initialize(id) super(id) end typesig { [Id] } def select_text(sender) OS.objc_msg_send(self.attr_id, OS.attr_sel_select_text_, !(sender).nil? ? sender.attr_id : 0) end typesig { [NSColor] } def set_background_color(color) OS.objc_msg_send(self.attr_id, OS.attr_sel_set_background_color_, !(color).nil? ? color.attr_id : 0) end typesig { [::Java::Boolean] } def set_bordered(flag) OS.objc_msg_send(self.attr_id, OS.attr_sel_set_bordered_, flag) end typesig { [Id] } def set_delegate(an_object) OS.objc_msg_send(self.attr_id, OS.attr_sel_set_delegate_, !(an_object).nil? ? an_object.attr_id : 0) end typesig { [::Java::Boolean] } def set_draws_background(flag) OS.objc_msg_send(self.attr_id, OS.attr_sel_set_draws_background_, flag) end typesig { [::Java::Boolean] } def set_editable(flag) OS.objc_msg_send(self.attr_id, OS.attr_sel_set_editable_, flag) end typesig { [::Java::Boolean] } def set_selectable(flag) OS.objc_msg_send(self.attr_id, OS.attr_sel_set_selectable_, flag) end typesig { [NSColor] } def set_text_color(color) OS.objc_msg_send(self.attr_id, OS.attr_sel_set_text_color_, !(color).nil? ? color.attr_id : 0) end class_module.module_eval { typesig { [] } # long def cell_class return OS.objc_msg_send(OS.attr_class_nstext_field, OS.attr_sel_cell_class) end typesig { [::Java::Int] } # long def set_cell_class(factory_id) OS.objc_msg_send(OS.attr_class_nstext_field, OS.attr_sel_set_cell_class_, factory_id) end } private alias_method :initialize__nstext_field, :initialize end end
neelance/swt4ruby
swt4ruby/lib/darwin-x86_32/org/eclipse/swt/internal/cocoa/NSTextField.rb
Ruby
epl-1.0
2,678
/* * Copyright 2011 Yuri Kanivets * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.umeitime.common.views.citypickerview.widget.wheel.adapters; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import java.util.LinkedList; import java.util.List; /** * Abstract Wheel adapter. */ public abstract class AbstractWheelAdapter implements WheelViewAdapter { // Observers private List<DataSetObserver> datasetObservers; @Override public View getEmptyItem(View convertView, ViewGroup parent) { return null; } @Override public void registerDataSetObserver(DataSetObserver observer) { if (datasetObservers == null) { datasetObservers = new LinkedList<DataSetObserver>(); } datasetObservers.add(observer); } @Override public void unregisterDataSetObserver(DataSetObserver observer) { if (datasetObservers != null) { datasetObservers.remove(observer); } } /** * Notifies observers about data changing */ protected void notifyDataChangedEvent() { if (datasetObservers != null) { for (DataSetObserver observer : datasetObservers) { observer.onChanged(); } } } /** * Notifies observers about invalidating data */ protected void notifyDataInvalidatedEvent() { if (datasetObservers != null) { for (DataSetObserver observer : datasetObservers) { observer.onInvalidated(); } } } }
umeitime/common
common-library/src/main/java/com/umeitime/common/views/citypickerview/widget/wheel/adapters/AbstractWheelAdapter.java
Java
epl-1.0
2,136
package org.lskk.lumen.helpdesk.gtr_package.WebAnalytic; import com.fasterxml.jackson.databind.ObjectMapper; import org.joda.time.YearMonth; import org.lskk.lumen.helpdesk.gtr_package.ChartJSMain; import org.springframework.web.bind.annotation.*; /** * Created by user on 9/27/2016. */ @RestController @CrossOrigin public class WebAnalyticsController { // @RequestMapping("/") // public String index() { // return "Greetings from Spring Boot!"; // } @RequestMapping(value = "/mostMentionedTopics", method = RequestMethod.GET) public String mostMentionedTopicsData(@RequestParam(value = "month") int month, @RequestParam(value = "year") int year, @RequestParam(value = "topics") String topics){ YearMonth ym = new YearMonth(year, month); ChartJSMain cjs = new ChartJSMain(); cjs.mostMentionedTopicsOrAreas("logstash-2016.07.27", ym, this.splitString(topics)); String cjsResultJSON = ""; try { cjsResultJSON = new ObjectMapper().writeValueAsString(cjs); }catch(Exception e){ e.printStackTrace(); } return cjsResultJSON; // return "Hello World"; } @RequestMapping(value = "/mostMentionedAreas", method = RequestMethod.GET) public String mostMentionedAreasData(@RequestParam(value = "month") int month, @RequestParam(value = "year") int year, @RequestParam(value = "areas") String areas){ YearMonth ym = new YearMonth(year, month); ChartJSMain cjs = new ChartJSMain(); cjs.mostMentionedTopicsOrAreas("logstash-2016.07.27", ym, this.splitString(areas)); String cjsResultJSON = ""; try { cjsResultJSON = new ObjectMapper().writeValueAsString(cjs); }catch(Exception e){ e.printStackTrace(); } return cjsResultJSON; } @RequestMapping(value = "/totalCasePerMonth", method = RequestMethod.GET) public String totalCasePerMonthData(@RequestParam(value = "year") int year){ ChartJSMain totalCasesPerMonth = new ChartJSMain(); totalCasesPerMonth.totalCasesPerMonth("logstash-2016.07.27", year); String resultJSON3 = ""; try { resultJSON3 = new ObjectMapper().writeValueAsString(totalCasesPerMonth); }catch(Exception e){ e.printStackTrace(); } return resultJSON3; } @RequestMapping(value = "/totalCasePerDay", method = RequestMethod.GET) public String totalCasePerDayData(@RequestParam(value = "month") int month, @RequestParam(value = "year") int year){ YearMonth ym = new YearMonth(year, month); ChartJSMain totalCasesPerDay = new ChartJSMain(); totalCasesPerDay.totalCasesPerDay("logstash-2016.07.27", ym); String resultJSON4 = ""; try { resultJSON4 = new ObjectMapper().writeValueAsString(totalCasesPerDay); }catch(Exception e){ e.printStackTrace(); } return resultJSON4; } private String[] splitString(String dataString){ return dataString.split(","); } }
lumenrobot/lumen-helpdesk
src/main/java/org/lskk/lumen/helpdesk/gtr_package/WebAnalytic/WebAnalyticsController.java
Java
epl-1.0
3,096
/** * Copyright (c) 2014 AtoS. * * * 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.topcased.checktool.xsdrules.xsdRules.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.ResourceLocator; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.topcased.checktool.results.provider.RuleItemProvider; import org.topcased.checktool.xsdrules.xsdRules.XSDRule; /** * This is the item provider adapter for a {@link org.topcased.checktool.xsdrules.xsdRules.XSDRule} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class XSDRuleItemProvider extends RuleItemProvider implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public XSDRuleItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public List getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; } /** * This returns XSDRule.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/XSDRule")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getText(Object object) { String label = ((XSDRule)object).getName(); return label == null || label.length() == 0 ? getString("_UI_XSDRule_type") : getString("_UI_XSDRule_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void collectNewChildDescriptors(Collection newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } /** * Return the resource locator for this item provider's resources. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ResourceLocator getResourceLocator() { return ChecktoolresultsEditPlugin.INSTANCE; } }
TristanFAURE/oclCheckTool
plugins/org.topcased.checktool.xsdrules.edit/src/org/topcased/checktool/xsdrules/xsdRules/provider/XSDRuleItemProvider.java
Java
epl-1.0
3,687
/** * generated by Xtext */ package org.eclipse.xtext.validation.csvalidationtest.util; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.validation.csvalidationtest.*; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see org.eclipse.xtext.validation.csvalidationtest.CsvalidationtestPackage * @generated */ public class CsvalidationtestAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static CsvalidationtestPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CsvalidationtestAdapterFactory() { if (modelPackage == null) { modelPackage = CsvalidationtestPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CsvalidationtestSwitch<Adapter> modelSwitch = new CsvalidationtestSwitch<Adapter>() { @Override public Adapter caseModel(Model object) { return createModelAdapter(); } @Override public Adapter caseSimpleGroup(SimpleGroup object) { return createSimpleGroupAdapter(); } @Override public Adapter caseSimpleAlternative(SimpleAlternative object) { return createSimpleAlternativeAdapter(); } @Override public Adapter caseSimpleMultiplicities(SimpleMultiplicities object) { return createSimpleMultiplicitiesAdapter(); } @Override public Adapter caseGroupMultiplicities(GroupMultiplicities object) { return createGroupMultiplicitiesAdapter(); } @Override public Adapter caseAlternativeMultiplicities(AlternativeMultiplicities object) { return createAlternativeMultiplicitiesAdapter(); } @Override public Adapter caseAssignedAction(AssignedAction object) { return createAssignedActionAdapter(); } @Override public Adapter caseUnassignedAction1(UnassignedAction1 object) { return createUnassignedAction1Adapter(); } @Override public Adapter caseUnassignedAction2(UnassignedAction2 object) { return createUnassignedAction2Adapter(); } @Override public Adapter caseUnassignedAction3(UnassignedAction3 object) { return createUnassignedAction3Adapter(); } @Override public Adapter caseUnassignedRuleCall1(UnassignedRuleCall1 object) { return createUnassignedRuleCall1Adapter(); } @Override public Adapter caseUnassignedRuleCall1Sub(UnassignedRuleCall1Sub object) { return createUnassignedRuleCall1SubAdapter(); } @Override public Adapter caseUnassignedRuleCall2(UnassignedRuleCall2 object) { return createUnassignedRuleCall2Adapter(); } @Override public Adapter caseUnassignedRuleCall2Sub(UnassignedRuleCall2Sub object) { return createUnassignedRuleCall2SubAdapter(); } @Override public Adapter caseCombination1(Combination1 object) { return createCombination1Adapter(); } @Override public Adapter caseCombination2(Combination2 object) { return createCombination2Adapter(); } @Override public Adapter caseCombination3(Combination3 object) { return createCombination3Adapter(); } @Override public Adapter caseCombination4(Combination4 object) { return createCombination4Adapter(); } @Override public Adapter caseList1(List1 object) { return createList1Adapter(); } @Override public Adapter caseList2(List2 object) { return createList2Adapter(); } @Override public Adapter caseList3(List3 object) { return createList3Adapter(); } @Override public Adapter caseList4(List4 object) { return createList4Adapter(); } @Override public Adapter caseList5(List5 object) { return createList5Adapter(); } @Override public Adapter caseAltList1(AltList1 object) { return createAltList1Adapter(); } @Override public Adapter caseAltList2(AltList2 object) { return createAltList2Adapter(); } @Override public Adapter caseTransientObject(TransientObject object) { return createTransientObjectAdapter(); } @Override public Adapter caseTransientObjectSub(TransientObjectSub object) { return createTransientObjectSubAdapter(); } @Override public Adapter caseTransientSerializeables1(TransientSerializeables1 object) { return createTransientSerializeables1Adapter(); } @Override public Adapter caseStaticSimplification(StaticSimplification object) { return createStaticSimplificationAdapter(); } @Override public Adapter caseTwoVersion(TwoVersion object) { return createTwoVersionAdapter(); } @Override public Adapter caseHeuristic1(Heuristic1 object) { return createHeuristic1Adapter(); } @Override public Adapter caseUnassignedAction2Sub(UnassignedAction2Sub object) { return createUnassignedAction2SubAdapter(); } @Override public Adapter caseUnassignedAction2Sub1(UnassignedAction2Sub1 object) { return createUnassignedAction2Sub1Adapter(); } @Override public Adapter caseUnassignedAction2Sub2(UnassignedAction2Sub2 object) { return createUnassignedAction2Sub2Adapter(); } @Override public Adapter caseUnassignedRuleCall2SubAction(UnassignedRuleCall2SubAction object) { return createUnassignedRuleCall2SubActionAdapter(); } @Override public Adapter caseEmptyAlternativeSub(EmptyAlternativeSub object) { return createEmptyAlternativeSubAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.Model <em>Model</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.Model * @generated */ public Adapter createModelAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.SimpleGroup <em>Simple Group</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.SimpleGroup * @generated */ public Adapter createSimpleGroupAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.SimpleAlternative <em>Simple Alternative</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.SimpleAlternative * @generated */ public Adapter createSimpleAlternativeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.SimpleMultiplicities <em>Simple Multiplicities</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.SimpleMultiplicities * @generated */ public Adapter createSimpleMultiplicitiesAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.GroupMultiplicities <em>Group Multiplicities</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.GroupMultiplicities * @generated */ public Adapter createGroupMultiplicitiesAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.AlternativeMultiplicities <em>Alternative Multiplicities</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.AlternativeMultiplicities * @generated */ public Adapter createAlternativeMultiplicitiesAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.AssignedAction <em>Assigned Action</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.AssignedAction * @generated */ public Adapter createAssignedActionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedAction1 <em>Unassigned Action1</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedAction1 * @generated */ public Adapter createUnassignedAction1Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedAction2 <em>Unassigned Action2</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedAction2 * @generated */ public Adapter createUnassignedAction2Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedAction3 <em>Unassigned Action3</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedAction3 * @generated */ public Adapter createUnassignedAction3Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedRuleCall1 <em>Unassigned Rule Call1</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedRuleCall1 * @generated */ public Adapter createUnassignedRuleCall1Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedRuleCall1Sub <em>Unassigned Rule Call1 Sub</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedRuleCall1Sub * @generated */ public Adapter createUnassignedRuleCall1SubAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedRuleCall2 <em>Unassigned Rule Call2</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedRuleCall2 * @generated */ public Adapter createUnassignedRuleCall2Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedRuleCall2Sub <em>Unassigned Rule Call2 Sub</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedRuleCall2Sub * @generated */ public Adapter createUnassignedRuleCall2SubAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.Combination1 <em>Combination1</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.Combination1 * @generated */ public Adapter createCombination1Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.Combination2 <em>Combination2</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.Combination2 * @generated */ public Adapter createCombination2Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.Combination3 <em>Combination3</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.Combination3 * @generated */ public Adapter createCombination3Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.Combination4 <em>Combination4</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.Combination4 * @generated */ public Adapter createCombination4Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.List1 <em>List1</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.List1 * @generated */ public Adapter createList1Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.List2 <em>List2</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.List2 * @generated */ public Adapter createList2Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.List3 <em>List3</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.List3 * @generated */ public Adapter createList3Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.List4 <em>List4</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.List4 * @generated */ public Adapter createList4Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.List5 <em>List5</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.List5 * @generated */ public Adapter createList5Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.AltList1 <em>Alt List1</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.AltList1 * @generated */ public Adapter createAltList1Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.AltList2 <em>Alt List2</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.AltList2 * @generated */ public Adapter createAltList2Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.TransientObject <em>Transient Object</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.TransientObject * @generated */ public Adapter createTransientObjectAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.TransientObjectSub <em>Transient Object Sub</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.TransientObjectSub * @generated */ public Adapter createTransientObjectSubAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.TransientSerializeables1 <em>Transient Serializeables1</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.TransientSerializeables1 * @generated */ public Adapter createTransientSerializeables1Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.StaticSimplification <em>Static Simplification</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.StaticSimplification * @generated */ public Adapter createStaticSimplificationAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.TwoVersion <em>Two Version</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.TwoVersion * @generated */ public Adapter createTwoVersionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.Heuristic1 <em>Heuristic1</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.Heuristic1 * @generated */ public Adapter createHeuristic1Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedAction2Sub <em>Unassigned Action2 Sub</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedAction2Sub * @generated */ public Adapter createUnassignedAction2SubAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedAction2Sub1 <em>Unassigned Action2 Sub1</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedAction2Sub1 * @generated */ public Adapter createUnassignedAction2Sub1Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedAction2Sub2 <em>Unassigned Action2 Sub2</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedAction2Sub2 * @generated */ public Adapter createUnassignedAction2Sub2Adapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.UnassignedRuleCall2SubAction <em>Unassigned Rule Call2 Sub Action</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.UnassignedRuleCall2SubAction * @generated */ public Adapter createUnassignedRuleCall2SubActionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.xtext.validation.csvalidationtest.EmptyAlternativeSub <em>Empty Alternative Sub</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.xtext.validation.csvalidationtest.EmptyAlternativeSub * @generated */ public Adapter createEmptyAlternativeSubAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //CsvalidationtestAdapterFactory
miklossy/xtext-core
org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/csvalidationtest/util/CsvalidationtestAdapterFactory.java
Java
epl-1.0
28,723
/******************************************************************************* * Copyright (c) 2021, 2022 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 com.ibm.ws.microprofile.mpjwt20.tck; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import componenttest.annotation.Server; import componenttest.custom.junit.runner.FATRunner; import componenttest.topology.impl.LibertyServer; import componenttest.topology.impl.JavaInfo; import componenttest.topology.utils.MvnUtils; /** * This is a test class that runs a whole Maven TCK as one test FAT test. * */ //@Mode(TestMode.QUARANTINE) @RunWith(FATRunner.class) public class Mpjwt20TCKLauncher_noaud_noenv { @Server("jwt20tckNoaudNoEnv") public static LibertyServer server; @BeforeClass public static void setUp() throws Exception { server.startServer(); server.waitForStringInLog("CWWKS4105I", 30000); // wait for ltpa keys to be created and service ready, which can happen after startup. } @AfterClass public static void tearDown() throws Exception { // CWWKZ0014W - we need app listed in server.xml even when it might not there, so allow this "missing app" error. // CWWKE0921W, 12w - the harness generates a java2sec socketpermission error, there's no way to suppress it by itself in server.xml, so allow this way // CWWKG0014E - intermittently caused by server.xml being momentarily missing during server reconfig server.stopServer("CWWKG0014E", "CWWKS5524E", "CWWKS6023E", "CWWKS5523E", "CWWKS6031E", "CWWKS5524E", "CWWKZ0014W", "CWWKE0921W", "CWWKE0912W"); } @Test //@AllowedFFDC // The tested deployment exceptions cause FFDC so we have to allow for this. public void launchMpjwt20TCKLauncher_noaud_noenv() throws Exception { String bucketAndTestName = this.getClass().getCanonicalName(); MvnUtils.runTCKMvnCmd(server, bucketAndTestName, bucketAndTestName, "tck_suite_noaud_noenv.xml", Collections.emptyMap(), Collections.emptySet()); Map<String, String> resultInfo = MvnUtils.getResultInfo(server); resultInfo.put("results_type", "MicroProfile"); resultInfo.put("feature_name", "JWT Auth"); resultInfo.put("feature_version", "2.0"); MvnUtils.preparePublicationFile(resultInfo); } }
OpenLiberty/open-liberty
dev/io.openliberty.microprofile.jwt.2.0.internal_fat_tck/fat/src/com/ibm/ws/microprofile/mpjwt20/tck/Mpjwt20TCKLauncher_noaud_noenv.java
Java
epl-1.0
2,929
package tama.edu.socket; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class ClientUdp { public static void main(String[] args) { try { DatagramSocket datagramSocket = new DatagramSocket(); byte[] sendData = new byte[1024]; sendData = new String("abc").getBytes(); InetAddress ipAddress = InetAddress.getByName("localhost"); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, 6789); datagramSocket.send(sendPacket); byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); datagramSocket.receive(receivePacket); String message = new String(receivePacket.getData()); System.out.println("Received from server: " + message); datagramSocket.close(); } catch (Exception e) { e.printStackTrace(); } } }
tama124/TinyProjectsOfTama
src/tama/edu/socket/ClientUdp.java
Java
epl-1.0
942
/** * */ package eu.quanticol.carma.examples.bikesharing; import org.apache.commons.math3.random.RandomGenerator; import eu.quanticol.carma.simulator.CarmaInput; import eu.quanticol.carma.simulator.CarmaOutput; import eu.quanticol.carma.simulator.CarmaPredicate; import eu.quanticol.carma.simulator.CarmaProcessAutomaton; import eu.quanticol.carma.simulator.CarmaStore; import eu.quanticol.carma.simulator.CarmaStoreUpdate; import eu.quanticol.carma.simulator.CarmaSystem; /** * @author loreti * */ public class BikeSharingDefinitions { public static final int TAKE_BIKE = 0; public static final int RETURN_BIKE = 1; public static final int MOVE = 2; public static final int STOP = 3; public static final int RESTART = 4; public static final CarmaProcessAutomaton UserProcess = createUserProcess(); public static final CarmaProcessAutomaton ParkingProcess = createParkingProcess(); private static CarmaProcessAutomaton createUserProcess() { CarmaProcessAutomaton toReturn = new CarmaProcessAutomaton("User"); CarmaProcessAutomaton.State pedestrian = toReturn.newState("Pedestrian"); CarmaProcessAutomaton.State waitingBike = toReturn.newState("WaitingBike"); CarmaProcessAutomaton.State biker = toReturn.newState("Biker"); CarmaProcessAutomaton.State waitingSlot = toReturn.newState("WaitingSlot"); CarmaOutput moveAction = new CarmaOutput( BikeSharing.MOVE , true ) { @Override protected Object getValue(CarmaSystem sys, CarmaStore store, double now) { return null; } @Override protected CarmaStoreUpdate getUpdate(CarmaSystem sys, double now) { return new CarmaStoreUpdate() { @Override public void update(RandomGenerator r, CarmaStore store) { int next = r.nextInt(BikeSharing.ZONES); store.set("zone", next ); } }; } @Override protected CarmaPredicate getPredicate(CarmaSystem sys, CarmaStore store) { return CarmaPredicate.FALSE; } }; CarmaOutput stopAction = new CarmaOutput( BikeSharing.STOP , true ) { @Override protected Object getValue(CarmaSystem sys, CarmaStore store, double now) { return null; } @Override protected CarmaStoreUpdate getUpdate(CarmaSystem sys,double now) { return null; } @Override protected CarmaPredicate getPredicate(CarmaSystem sys, CarmaStore store) { return CarmaPredicate.FALSE; } }; CarmaOutput restartAction = new CarmaOutput( BikeSharing.RESTART , true ) { @Override protected Object getValue(CarmaSystem sys, CarmaStore store, double now) { return null; } @Override protected CarmaStoreUpdate getUpdate(CarmaSystem sys, double now) { return null; } @Override protected CarmaPredicate getPredicate(CarmaSystem sys, CarmaStore store) { return CarmaPredicate.FALSE; } }; CarmaInput takeBike = new CarmaInput( BikeSharing.TAKE_BIKE , false ) { @Override protected CarmaPredicate getPredicate(CarmaSystem sys, CarmaStore store, Object value) { return CarmaPredicate.TRUE; } @Override protected CarmaStoreUpdate getUpdate(CarmaSystem sys, Object value, double now) { return new CarmaStoreUpdate() { @Override public void update(RandomGenerator r, CarmaStore store) { store.set( "status ", BikeSharing.BIKER ); } }; } }; CarmaInput returnBike = new CarmaInput( BikeSharing.RETURN_BIKE , false ) { @Override protected CarmaPredicate getPredicate(CarmaSystem sys, CarmaStore store, Object value) { return CarmaPredicate.TRUE; } @Override protected CarmaStoreUpdate getUpdate(CarmaSystem sys, Object value, double now) { return new CarmaStoreUpdate() { @Override public void update(RandomGenerator r, CarmaStore store) { store.set( "status ", BikeSharing.PEDESTRIAN ); } }; } }; toReturn.addTransition(biker, moveAction, biker); toReturn.addTransition(biker, stopAction, waitingSlot); toReturn.addTransition(pedestrian, restartAction, waitingBike); toReturn.addTransition(waitingBike, takeBike, biker); toReturn.addTransition(waitingSlot, returnBike, pedestrian); return toReturn; } private static CarmaProcessAutomaton createParkingProcess() { CarmaProcessAutomaton toReturn = new CarmaProcessAutomaton("User"); CarmaProcessAutomaton.State state = toReturn.newState("S"); CarmaOutput takeBike = new CarmaOutput( BikeSharing.TAKE_BIKE , false ) { @Override protected Object getValue(CarmaSystem sys, CarmaStore store, double now) { return null; } @Override protected CarmaStoreUpdate getUpdate(CarmaSystem sys, double now) { return new CarmaStoreUpdate() { @Override public void update(RandomGenerator r, CarmaStore store) { int bikes = store.get("bikes" , Integer.class ); int slots = store.get("slots" , Integer.class ); store.set( "bikes" , bikes-1); store.set( "slots" , slots+1); } }; } @Override protected CarmaPredicate getPredicate(CarmaSystem sys, CarmaStore store) { return new CarmaPredicate.HasValue<Integer>("zone", Integer.class, store.get("zone",Integer.class)); } }; CarmaOutput returnBike = new CarmaOutput( BikeSharing.RETURN_BIKE , false ) { @Override protected Object getValue(CarmaSystem sys, CarmaStore store, double now) { return null; } @Override protected CarmaStoreUpdate getUpdate(CarmaSystem sys, double now) { return new CarmaStoreUpdate() { @Override public void update(RandomGenerator r, CarmaStore store) { int bikes = store.get("bikes" , Integer.class ); int slots = store.get("slots" , Integer.class ); store.set( "bikes" , bikes+1); store.set( "slots" , slots-1); } }; } @Override protected CarmaPredicate getPredicate(CarmaSystem sys, CarmaStore store) { return new CarmaPredicate.HasValue<Integer>("zone", Integer.class, store.get("zone",Integer.class)); } }; CarmaPredicate returnBikeGuard = new CarmaPredicate() { @Override public boolean satisfy(double now,CarmaStore store) { int slots = store.get("slots", Integer.class); return slots > 0; } }; CarmaPredicate takeBikeGuard = new CarmaPredicate() { @Override public boolean satisfy(double now,CarmaStore store) { int bikes = store.get("bikes", Integer.class); return bikes > 0; } }; toReturn.addTransition(state,takeBikeGuard,takeBike,state); toReturn.addTransition(state,returnBikeGuard,returnBike,state); return toReturn; } }
Quanticol/CARMA
TESTS/eu.quanticol.carma.examples.bikesharing/src/eu/quanticol/carma/examples/bikesharing/BikeSharingDefinitions.java
Java
epl-1.0
6,677
# -*- encoding : utf-8 -*- class TransferRequest < ActiveRecord::Base STATUS_PENDING = :pending STATUS_ACCEPTED = :accepted STATUS_REJECTED = :rejected ALLOWED_TYPES = [STATUS_PENDING, STATUS_ACCEPTED, STATUS_REJECTED].freeze belongs_to :offering_user, foreign_key: :offering_user_id, class_name: 'User' belongs_to :target_user, foreign_key: :target_user_id, class_name: 'User' belongs_to :offered_player, foreign_key: :offered_player_id, class_name: 'NflPlayer' belongs_to :target_player, foreign_key: :target_player_id, class_name: 'NflPlayer' validates :offering_user, presence: true validates :target_user, presence: true validates :offered_player, presence: true validates :target_player, presence: true validate :users_are_different validate :players_are_different validates :status, inclusion: { in: ALLOWED_TYPES, allow_nil: false } def users_are_different return unless offering_user.present? && target_user.present? offering_user_id = offering_user.id target_user_id = target_user.id return unless offering_user_id == target_user_id errors.add(:users, "Request and target users are the same, with id #{offering_user_id}") end def players_are_different return unless offered_player.present? && target_player.present? offered_player_id = offered_player.id target_player_id = target_player.id return unless offered_player_id == target_player_id errors.add(:players, "Offered and Target players are the same, with id #{offered_player_id}") end end
ishakir/shakitz-fantasy-football
app/models/transfer_request.rb
Ruby
epl-1.0
1,709
package org.zsx.android.api.widget; import org.zsx.android.api.R; import org.zsx.android.base._BaseActivity; import android.os.Build; import android.os.Bundle; import android.widget.Toast; public class TextClock_Activity extends _BaseActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR1){ setContentView(R.layout.widget_textclock); }else{ Toast.makeText(this, "需要 Android 4.2", Toast.LENGTH_SHORT).show(); finish(); } } }
z1986s8x11/androidLib
help/src/main/java/org/zsx/android/api/widget/TextClock_Activity.java
Java
epl-1.0
566
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ public partial class SysLog_CommonDataEditActionLog { /// <summary> /// SearchUpdatePanel 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.UpdatePanel SearchUpdatePanel; /// <summary> /// DataTableNameDropDownList 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.DropDownList DataTableNameDropDownList; /// <summary> /// ActionTypeDropDownList 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ActionTypeDropDownList; /// <summary> /// StuffIdCtl 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox StuffIdCtl; /// <summary> /// StuffNameCtl 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox StuffNameCtl; /// <summary> /// SrhAfterLogInTimeCtl 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox SrhAfterLogInTimeCtl; /// <summary> /// SrhBeforeLogInTimeCtl 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox SrhBeforeLogInTimeCtl; /// <summary> /// SearchBtn 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button SearchBtn; /// <summary> /// GridViewUpdatePanel 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.UpdatePanel GridViewUpdatePanel; /// <summary> /// CommonDataEditActionLogGridView 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::Gc.WebControls.GridView CommonDataEditActionLogGridView; /// <summary> /// CommonDataEditActionLogDS 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.ObjectDataSource CommonDataEditActionLogDS; }
hijoy/VSL_ERS
WebUI/SysLog/CommonDataEditActionLog.aspx.designer.cs
C#
gpl-2.0
3,949
/* * GanttBar.cpp * * * Created by Owen Thomas on 16/11/06. * Copyright 2006 __MyCompanyName__. All rights reserved. * */ #include "GanttBar.h" #include "GanttBarContainer.h" void GanttBar::mousePressEvent (QMouseEvent* event) { initMovingPosition = event-> x(); } void GanttBar::mouseMoveEvent (QMouseEvent* event) { if(!editable) return; barHasMoved = true; int delta = initMovingPosition - event->x (); if(x() - delta > 0) { move ( x() - delta, y() ); emit moved (this); } else { move (0, y()); emit moved (this); } container->setWidth (); } void GanttBar::mouseReleaseEvent (QMouseEvent* event) { //Only trigger the event within the container //if we have moved the position of the gantt bar. if(barHasMoved) { /** There is a bug in the Gantt Chart that causes an arcane bus error in apple / qt event handling. It has something to do with the fact that the call to container->commitModification wil lcause this GanttBar to be deleted. Deleting the event that triggers the ultimate deletion of this event appears to stop the bus error. I'd like to know why this is happening and why deleting the event stops the problem. I imagine that when the widget is deleted, this events perhaps stays around is accessed by the event handling mechanism. It somehow has a reference to some data that is deleted when this gantt bar is deleted. */ event->accept (); // [daa] According to comments above, this should not be commented out. // I found it this way, but when I uncommented it, it crashed on bar moving. //delete event; container->commitModification (); } barHasMoved = false; } void GanttBar::mouseDoubleClickEvent (QMouseEvent* ) { if(editable)container->nextOutcome (); }
PlanTool/plantool
code/Uncertainty/FPG/Brazil/source/dynamic-gantt/GanttBar.cpp
C++
gpl-2.0
1,798
#!/usr/bin/python import spidev import time import datetime import sys import math import struct """ ================================================ ABElectronics IO Pi V2 32-Channel Port Expander Version 1.0 Created 20/05/2014 Version 1.1 16/11/2014 updated code and functions to PEP8 format Requires python smbus to be installed ================================================ """ class ADC: """ Based on the Microchip MCP3208 """ # variables __adcrefvoltage = 4.096 # reference voltage for the ADC chip. # Define SPI bus and init __spiADC = spidev.SpiDev() __spiADC.open(0, 0) __spiADC.max_speed_hz = (50000) # public methods def read_adc_voltage(self, channel): """ Read the voltage from the selected channel on the ADC Channel = 1 to 8 """ if ((channel > 8) or (channel < 1)): print 'ADC channel needs to be 1 to 8' raw = self.readADCraw(channel) voltage = (self.__adcrefvoltage / 4096) * raw return voltage def readADCraw(self, channel): """ Read the raw value from the selected channel on the ADC Channel = 1 to 8 """ if ((channel > 8) or (channel < 1)): print 'ADC channel needs to be 1 to 8' return 0.0 channel = channel - 1 r = self.__spiADC.xfer2([4 + (channel >> 2), (channel & 3) << 6, 0]) ret = ((r[1] & 0x0F) << 8) + (r[2]) return ret def set_adc_refvoltage(self, voltage): """ set the reference voltage for the analogue to digital converter. By default the ADC uses an onboard 4.096V voltage reference. If you choose to use an external voltage reference you will need to use this method to set the ADC reference voltage to match the supplied reference voltage. The reference voltage must be less than or equal to the voltage on the Raspberry Pi 5V rail. """ if (voltage >= 0.0) and (voltage <= 5.5): self.__adcrefvoltage = voltage else: print 'reference voltage out of range' return class DAC: """ Based on the Microchip MCP4822 Define SPI bus and init """ __spiDAC = spidev.SpiDev() __spiDAC.open(0, 1) __spiDAC.max_speed_hz = (4000000) def set_dac_voltage(self, channel, voltage): """ set the voltage for the selected channel on the DAC voltage can be between 0 and 2.047 volts """ if ((channel > 2) or (channel < 1)): print 'DAC channel needs to be 1 or 2' if (voltage >= 0.0) and (voltage < 2.048): rawval = (voltage / 2.048) * 4096 self.set_dac_raw(channel, int(rawval)) return def set_dac_raw(self, channel, value): """ Set the raw value from the selected channel on the DAC Channel = 1 or 2 Value between 0 and 4095 """ lowByte = value & 0xff highByte = ( (value >> 8) & 0xff) | ( channel - 1) << 7 | 0x1 << 5 | 1 << 4 self.__spiDAC.xfer2([highByte, lowByte]) return class IO: """ The MCP23017 chip is split into two 8-bit ports. port 0 controls pins 1 to 8 while port 1 controls pins 9 to 16. When writing to or reading from a port the least significant bit represents the lowest numbered pin on the selected port. # """ # Define registers values from datasheet IODIRA = 0x00 # IO direction A - 1= input 0 = output IODIRB = 0x01 # IO direction B - 1= input 0 = output # Input polarity A - If a bit is set, the corresponding GPIO register bit # will reflect the inverted value on the pin. IPOLA = 0x02 # Input polarity B - If a bit is set, the corresponding GPIO register bit # will reflect the inverted value on the pin. IPOLB = 0x03 # The GPINTEN register controls the interrupt-onchange feature for each # pin on port A. GPINTENA = 0x04 # The GPINTEN register controls the interrupt-onchange feature for each # pin on port B. GPINTENB = 0x05 # Default value for port A - These bits set the compare value for pins # configured for interrupt-on-change. If the associated pin level is the # opposite from the register bit, an interrupt occurs. DEFVALA = 0x06 # Default value for port B - These bits set the compare value for pins # configured for interrupt-on-change. If the associated pin level is the # opposite from the register bit, an interrupt occurs. DEFVALB = 0x07 # Interrupt control register for port A. If 1 interrupt is fired when the # pin matches the default value, if 0 the interrupt is fired on state # change INTCONA = 0x08 # Interrupt control register for port B. If 1 interrupt is fired when the # pin matches the default value, if 0 the interrupt is fired on state # change INTCONB = 0x09 IOCON = 0x0A # see datasheet for configuration register GPPUA = 0x0C # pull-up resistors for port A GPPUB = 0x0D # pull-up resistors for port B # The INTF register reflects the interrupt condition on the port A pins of # any pin that is enabled for interrupts. A set bit indicates that the # associated pin caused the interrupt. INTFA = 0x0E # The INTF register reflects the interrupt condition on the port B pins of # any pin that is enabled for interrupts. A set bit indicates that the # associated pin caused the interrupt. INTFB = 0x0F # The INTCAP register captures the GPIO port A value at the time the # interrupt occurred. INTCAPA = 0x10 # The INTCAP register captures the GPIO port B value at the time the # interrupt occurred. INTCAPB = 0x11 GPIOA = 0x12 # data port A GPIOB = 0x13 # data port B OLATA = 0x14 # output latches A OLATB = 0x15 # output latches B # variables __ioaddress = 0x20 # I2C address __portA_dir = 0x00 # port a direction __portB_dir = 0x00 # port b direction __portA_val = 0x00 # port a value __portB_val = 0x00 # port b value __portA_pullup = 0x00 # port a pull-up resistors __portB_pullup = 0x00 # port a pull-up resistors __portA_polarity = 0x00 # input polarity for port a __portB_polarity = 0x00 # input polarity for port b __intA = 0x00 # interrupt control for port a __intB = 0x00 # interrupt control for port a # initial configuration - see IOCON page in the MCP23017 datasheet for # more information. __ioconfig = 0x22 global _bus def __init__(self, bus): """ init object with i2c address, default is 0x20, 0x21 for IOPi board, load default configuration """ self._bus = bus self._bus.write_byte_data(self.__ioaddress, self.IOCON, self.__ioconfig) self.__portA_val = self._bus.read_byte_data(self.__ioaddress, self.GPIOA) self.__portB_val = self._bus.read_byte_data(self.__ioaddress, self.GPIOB) self._bus.write_byte_data(self.__ioaddress, self.IODIRA, 0xFF) self._bus.write_byte_data(self.__ioaddress, self.IODIRB, 0xFF) return # local methods def __updatebyte(self, byte, bit, value): """ internal method for setting the value of a single bit within a byte """ if value == 0: return byte & ~(1 << bit) elif value == 1: return byte | (1 << bit) def __checkbit(self, byte, bit): """ internal method for reading the value of a single bit within a byte """ if byte & (1 << bit): return 1 else: return 0 # public methods def set_pin_direction(self, pin, direction): """ set IO direction for an individual pin pins 1 to 16 direction 1 = input, 0 = output """ pin = pin - 1 if pin < 8: self.__portA_dir = self.__updatebyte(self.__portA_dir, pin, direction) self._bus.write_byte_data(self.address, self.IODIRA, self.__portA_dir) else: self.__portB_dir = self.__updatebyte(self.__portB_dir, pin - 8, direction) self._bus.write_byte_data(self.address, self.IODIRB, self.__portB_dir) return def set_port_direction(self, port, direction): """ set direction for an IO port port 0 = pins 1 to 8, port 1 = pins 9 to 16 1 = input, 0 = output """ if port == 1: self._bus.write_byte_data(self.__ioaddress, self.IODIRB, direction) self.__portB_dir = direction else: self._bus.write_byte_data(self.__ioaddress, self.IODIRA, direction) self.__portA_dir = direction return def set_pin_pullup(self, pin, value): """ set the internal 100K pull-up resistors for an individual pin pins 1 to 16 value 1 = enabled, 0 = disabled """ pin = pin - 1 if pin < 8: self.__portA_pullup = self.__updatebyte(self.__portA_pullup, pin, value) self._bus.write_byte_data(self.address, self.GPPUA, self.__portA_pullup) else: self.__portB_pullup = self.__updatebyte(self.__portB_pullup,pin - 8,value) self._bus.write_byte_data(self.address, self.GPPUB, self.__portB_pullup) return def set_port_pullups(self, port, value): """ set the internal 100K pull-up resistors for the selected IO port """ if port == 1: self.__portA_pullup = value self._bus.write_byte_data(self.__ioaddress, self.GPPUB, value) else: self.__portB_pullup = value self._bus.write_byte_data(self.__ioaddress, self.GPPUA, value) return def write_pin(self, pin, value): """ write to an individual pin 1 - 16 """ pin = pin - 1 if pin < 8: self.__portA_val = self.__updatebyte(self.__portA_val, pin, value) self._bus.write_byte_data( self.__ioaddress, self.GPIOA, self.__portA_val) else: self.__portB_val = self.__updatebyte( self.__portB_val, pin - 8, value) self._bus.write_byte_data( self.__ioaddress, self.GPIOB, self.__portB_val) return def write_port(self, port, value): """ write to all pins on the selected port port 0 = pins 1 to 8, port 1 = pins 9 to 16 value = number between 0 and 255 or 0x00 and 0xFF """ if port == 1: self._bus.write_byte_data(self.__ioaddress, self.GPIOB, value) self.__portB_val = value else: self._bus.write_byte_data(self.__ioaddress, self.GPIOA, value) self.__portA_val = value return def read_pin(self, pin): """ read the value of an individual pin 1 - 16 returns 0 = logic level low, 1 = logic level high """ pin = pin - 1 if pin < 8: self.__portA_val =self._bus.read_byte_data( self.__ioaddress, self.GPIOA) return self.__checkbit(self.__portA_val, pin) else: pin = pin - 8 self.__portB_val =self._bus.read_byte_data( self.__ioaddress, self.GPIOB) return self.__checkbit(self.__portB_val, pin) def read_port(self, port): """ read all pins on the selected port port 0 = pins 1 to 8, port 1 = pins 9 to 16 returns number between 0 and 255 or 0x00 and 0xFF """ if port == 1: self.__portB_val =self._bus.read_byte_data( self.__ioaddress, self.GPIOB) return self.__portB_val else: self.__portA_val =self._bus.read_byte_data( self.__ioaddress, self.GPIOA) return self.__portA_val def invert_port(self, port, polarity): """ invert the polarity of the pins on a selected port port 0 = pins 1 to 8, port 1 = pins 9 to 16 polarity 0 = same logic state of the input pin, 1 = inverted logic state of the input pin """ if port == 1: self._bus.write_byte_data(self.__ioaddress, self.IPOLB, polarity) self.__portB_polarity = polarity else: self._bus.write_byte_data(self.__ioaddress, self.IPOLA, polarity) self.__portA_polarity = polarity return def invert_pin(self, pin, polarity): """ invert the polarity of the selected pin pins 1 to 16 polarity 0 = same logic state of the input pin, 1 = inverted logic state of the input pin """ pin = pin - 1 if pin < 8: self.__portA_polarity = self.__updatebyte( self.__portA_val, pin, polarity) self._bus.write_byte_data( self.__ioaddress, self.IPOLA, self.__portA_polarity) else: self.__portB_polarity = self.__updatebyte( self.__portB_val, pin - 8, polarity) self._bus.write_byte_data( self.__ioaddress, self.IPOLB, self.__portB_polarity) return def mirror_interrupts(self, value): """ 1 = The INT pins are internally connected, 0 = The INT pins are not connected. __intA is associated with PortA and __intB is associated with PortB """ if value == 0: self.config = self.__updatebyte(self.__ioconfig, 6, 0) self._bus.write_byte_data(self.__ioaddress, self.IOCON, self.__ioconfig) if value == 1: self.config = self.__updatebyte(self.__ioconfig, 6, 1) self._bus.write_byte_data(self.__ioaddress, self.IOCON, self.__ioconfig) return def set_interrupt_polarity(self, value): """ This sets the polarity of the INT output pins - 1 = Active-high. 0 = Active-low. """ if value == 0: self.config = self.__updatebyte(self.__ioconfig, 1, 0) self._bus.write_byte_data(self.__ioaddress, self.IOCON, self.__ioconfig) if value == 1: self.config = self.__updatebyte(self.__ioconfig, 1, 1) self._bus.write_byte_data(self.__ioaddress, self.IOCON, self.__ioconfig) return return def set_interrupt_type(self, port, value): """ Sets the type of interrupt for each pin on the selected port 1 = interrupt is fired when the pin matches the default value, 0 = the interrupt is fired on state change """ if port == 0: self._bus.write_byte_data(self.__ioaddress, self.INTCONA, value) else: self._bus.write_byte_data(self.__ioaddress, self.INTCONB, value) return def set_interrupt_defaults(self, port, value): """ These bits set the compare value for pins configured for interrupt-on-change on the selected port. If the associated pin level is the opposite from the register bit, an interrupt occurs. """ if port == 0: self._bus.write_byte_data(self.__ioaddress, self.DEFVALA, value) else: self._bus.write_byte_data(self.__ioaddress, self.DEFVALB, value) return def set_interrupt_on_port(self, port, value): """ Enable interrupts for the pins on the selected port port 0 = pins 1 to 8, port 1 = pins 9 to 16 value = number between 0 and 255 or 0x00 and 0xFF """ if port == 0: self._bus.write_byte_data(self.__ioaddress, self.GPINTENA, value) self.__intA = value else: self._bus.write_byte_data(self.__ioaddress, self.GPINTENB, value) self.__intB = value return def set_interrupt_on_pin(self, pin, value): """ Enable interrupts for the selected pin Pin = 1 to 16 Value 0 = interrupt disabled, 1 = interrupt enabled """ pin = pin - 1 if pin < 8: self.__intA = self.__updatebyte(self.__intA, pin, value) self._bus.write_byte_data(self.__ioaddress, self.GPINTENA, self.__intA) else: self.__intB = self.__updatebyte(self.__intB, pin - 8, value) self._bus.write_byte_data(self.__ioaddress, self.GPINTENB, self.__intB) return def read_interrupt_status(self, port): """ read the interrupt status for the pins on the selected port port 0 = pins 1 to 8, port 1 = pins 9 to 16 """ if port == 0: return self._bus.read_byte_data(self.__ioaddress, self.INTFA) else: return self._bus.read_byte_data(self.__ioaddress, self.INTFB) def read_interrupt_capture(self, port): """ read the value from the selected port at the time of the last interrupt trigger port 0 = pins 1 to 8, port 1 = pins 9 to 16 """ if port == 0: return self._bus.read_byte_data(self.__ioaddress, self.INTCAPA) else: return self._bus.read_byte_data(self.__ioaddress, self.INTCAPB) def reset_interrupts(self): """ Reset the interrupts A and B to 0 """ self.read_interrupt_capture(0) self.read_interrupt_capture(1) return class RTC: """ Based on the Maxim DS1307 Define registers values from datasheet """ SECONDS = 0x00 MINUTES = 0x01 HOURS = 0x02 DAYOFWEEK = 0x03 DAY = 0x04 MONTH = 0x05 YEAR = 0x06 CONTROL = 0x07 # variables __rtcaddress = 0x68 # I2C address # initial configuration - square wave and output disabled, frequency set # to 32.768KHz. __rtcconfig = 0x03 # the DS1307 does not store the current century so that has to be added on # manually. __century = 2000 # local methods def __init__(self, bus): self._bus = bus self.__config = self.__rtcconfig self._bus.write_byte_data(self.__rtcaddress, self.CONTROL, self.__config) return def __bcd_to_dec(self, x): return x - 6 * (x >> 4) def __dec_to_bcd(self, val): return ((val / 10 * 16) + (val % 10)) def __get_century(self, val): if len(val) > 2: y = val[0] + val[1] self.__century = int(y) * 100 return def __updatebyte(self, byte, bit, value): """ internal method for setting the value of a single bit within a byte """ if value == 0: return byte & ~(1 << bit) elif value == 1: return byte | (1 << bit) # public methods def set_date(self, date): """ set the date and time on the RTC date must be in ISO 8601 format - YYYY-MM-DDTHH:MM:SS """ d = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S") self.__get_century(date) self._bus.write_byte_data( self.__rtcaddress, self.SECONDS, self.__dec_to_bcd( d.second)) self._bus.write_byte_data( self.__rtcaddress, self.MINUTES, self.__dec_to_bcd( d.minute)) self._bus.write_byte_data( self.__rtcaddress, self.HOURS, self.__dec_to_bcd( d.hour)) self._bus.write_byte_data( self.__rtcaddress, self.DAYOFWEEK, self.__dec_to_bcd( d.weekday())) self._bus.write_byte_data( self.__rtcaddress, self.DAY, self.__dec_to_bcd( d.day)) self._bus.write_byte_data( self.__rtcaddress, self.MONTH, self.__dec_to_bcd( d.month)) self._bus.write_byte_data( self.__rtcaddress, self.YEAR, self.__dec_to_bcd( d.year - self.__century)) return def read_date(self): """ read the date and time from the RTC in ISO 8601 format - YYYY-MM-DDTHH:MM:SS """ seconds, minutes, hours, dayofweek, day, month, year \ =self._bus.read_i2c_block_data(self.__rtcaddress, 0, 7) date = ( "%02d-%02d-%02dT%02d:%02d:%02d " % (self.__bcd_to_dec(year) + self.__century, self.__bcd_to_dec(month), self.__bcd_to_dec(day), self.__bcd_to_dec(hours), self.__bcd_to_dec(minutes), self.__bcd_to_dec(seconds))) return date def enable_output(self): """ Enable the output pin """ self.__config = self.__updatebyte(self.__config, 7, 1) self.__config = self.__updatebyte(self.__config, 4, 1) self._bus.write_byte_data(self.__rtcaddress, self.CONTROL, self.__config) return def disable_output(self): """ Disable the output pin """ self.__config = self.__updatebyte(self.__config, 7, 0) self.__config = self.__updatebyte(self.__config, 4, 0) self._bus.write_byte_data(self.__rtcaddress, self.CONTROL, self.__config) return def set_frequency(self, frequency): """ set the frequency of the output pin square-wave options are: 1 = 1Hz, 2 = 4.096KHz, 3 = 8.192KHz, 4 = 32.768KHz """ if frequency == 1: self.__config = self.__updatebyte(self.__config, 0, 0) self.__config = self.__updatebyte(self.__config, 1, 0) if frequency == 2: self.__config = self.__updatebyte(self.__config, 0, 1) self.__config = self.__updatebyte(self.__config, 1, 0) if frequency == 3: self.__config = self.__updatebyte(self.__config, 0, 0) self.__config = self.__updatebyte(self.__config, 1, 1) if frequency == 4: self.__config = self.__updatebyte(self.__config, 0, 1) self.__config = self.__updatebyte(self.__config, 1, 1) self._bus.write_byte_data(self.__rtcaddress, self.CONTROL, self.__config) return
moeskerv/ABElectronics_Python_Libraries
ExpanderPi/ABE_ExpanderPi.py
Python
gpl-2.0
22,720
namespace ERP.Sale { @Serenity.Decorators.registerClass() @Serenity.Decorators.filterable() export class OrderGrid extends Serenity.EntityGrid<OrderRow, any> { protected getColumnsKey() { return "Sale.Order"; } protected getDialogType() { return <any>OrderDialog; } protected getIdProperty() { return OrderRow.idProperty; } protected getLocalTextPrefix() { return OrderRow.localTextPrefix; } protected getService() { return OrderService.baseUrl; } protected shippingStateFilter: Serenity.EnumEditor; constructor(container: JQuery) { super(container); } protected createQuickFilters() { super.createQuickFilters(); let fld = OrderRow.Fields; this.shippingStateFilter = this.findQuickFilter(Serenity.EnumEditor, fld.ShippingState); } protected getButtons() { var buttons = super.getButtons(); buttons.push(Common.ExcelExportHelper.createToolButton({ grid: this, service: OrderService.baseUrl + '/ListExcel', onViewSubmit: () => this.onViewSubmit(), separator: true })); buttons.push(Common.PdfExportHelper.createToolButton({ grid: this, onViewSubmit: () => this.onViewSubmit() })); return buttons; } public set_shippingState(value: number): void { this.shippingStateFilter.value = value == null ? '' : value.toString(); } } }
justdoitman/ERP
ERP/ERP.Web/Modules/Sale/Order/OrderGrid.ts
TypeScript
gpl-2.0
1,649
package miniprospector.enums; import javafx.scene.paint.Color; import miniprospector.util.Utility; public enum Status { NOT_ACTIVE(-1, "", Color.TRANSPARENT, Color.TRANSPARENT), ACTIVE(0, "ANALYSING", Color.TRANSPARENT, Color.YELLOW), TRACE(1, "TRACE", Utility.sgetColorWithAlpha(Color.GHOSTWHITE, 0.1), Utility.sgetColorWithAlpha(Color.ALICEBLUE, 0.1)), SLIGHT(2, "SLIGHT TRACE", Utility.sgetColorWithAlpha(Color.MEDIUMBLUE, 0.1), Utility.sgetColorWithAlpha(Color.MEDIUMBLUE, 0.1)), FAINT(3, "FAINT TRACE", Utility.sgetColorWithAlpha(Color.DODGERBLUE, 0.1), Utility.sgetColorWithAlpha(Color.DODGERBLUE, 0.1)), MINISCULE(4, "MINISCULE TRACE", Utility.sgetColorWithAlpha(Color.GREENYELLOW, 0.1), Utility.sgetColorWithAlpha(Color.GREENYELLOW, 0.1)), VAGUE(5, "VAGUE TRACE", Utility.sgetColorWithAlpha(Color.DARKORANGE, 0.1), Utility.sgetColorWithAlpha(Color.DARKORANGE, 0.1)), INDISTINCT(6, "INDISTINCT TRACE", Utility.sgetColorWithAlpha(Color.CRIMSON, 0.1), Utility.sgetColorWithAlpha(Color.CRIMSON, 0.1)); private int distance; private String text; private Color fill; private Color stroke; private Status (int _d, String _t, Color _f, Color _s) { distance = _d; text = _t; fill = _f; stroke = _s; } public int getDistance() { return distance; } public String getText() { return text; } public Color getFill() { return fill; } public Color getStroke() { return stroke; } public static Status getRangeFromDist (int _d) { return values()[_d+1]; } }
WDonegan/javafx
Mini-Prospector/src/miniprospector/enums/Status.java
Java
gpl-2.0
1,546
/** * @version 3.4 February 3, 2012 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2012 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ var Fusion = new Class({ version: "3.0", options: { centered: false, tweakInitial: {x: 0, y: 0}, tweakSubsequent: {x: 0, y: 0}, tweakSizes: {'width': 0, 'height': 0}, pill: true, direction: { x: 'right', y: 'down' }, effect: 'slide and fade', orientation: 'horizontal', opacity: 1, hideDelay: 50000, menuFx: { duration: 500, transition: Fx.Transitions.Quad.easeOut }, pillFx: { duration: 400, transition: Fx.Transitions.Back.easeOut } }, initialize: function(element, options) { this.element = $$(element)[0]; this.id = $$('.fusion')[0]; if (this.id) this.id = this.id.id; else this.id = ''; this.setOptions(options); var links = this.element.getElements('.item'), opts = this.options; this.rtl = $(document.body).getStyle('direction') == 'rtl'; this.options.tweakSubsequent.x -= this.options.tweakSizes.width / 2; this.options.tweakSubsequent.y -= this.options.tweakSizes.height / 2; if (this.rtl) { this.options.direction.x = 'left'; this.options.tweakInitial.x *= -1; this.options.tweakSubsequent.x *= -1; } if (this.options.pill) { var pill = new Element('div', {'class': 'fusion-pill-l'}).inject(this.element, 'after').setStyle('display', 'none'), self = this; new Element('div', {'class': 'fusion-pill-r'}).inject(pill); this.pillsRoots = this.element.getElements('.root'); var active = this.element.getElement('.active'); this.pillsMargins = pill.getStyle('margin-left').toInt() + pill.getStyle('margin-right').toInt(); this.pillsTopMargins = pill.getStyle('margin-top').toInt() + pill.getStyle('margin-bottom').toInt(); if (!active) { this.options.pill = false; } else { pill.setStyle('display', 'block'); this.pillsDefaults = { 'left': active.offsetLeft, 'width': active.offsetWidth - this.pillsMargins, 'top': active.offsetTop }; this.pillFx = new Fx.Styles(pill, { duration: opts.pillFx.duration, transition: opts.pillFx.transition, wait: false }).set(this.pillsDefaults); var ghosts = this.pillsRoots.filter(function(item) { return !item.hasClass('parent'); }); $$(ghosts).addEvents({ 'mouseenter': function() { self.ghostRequest = true; self.pillFx.start({ 'left': this.offsetLeft, 'width': this.offsetWidth - self.pillsMargins, 'top': this.offsetTop }); }, 'mouseleave': function() { self.ghostRequest = false; self.pillFx.start(self.pillsDefaults); } }); } }; this.parentLinks = {}; this.parentSubMenus = {}; this.childMenu = {}; this.menuType = {}; this.subMenus = []; this.hideAllMenusTimeout = null; this.subMenuZindex = 1; links.each(function(link, i) { link.getID(); this.parentLinks[link.id] = link.getParent().getParents('li', this.element).getElement('.item'); this.childMenu[link.id] = link.getNextTag('fusion-submenu-wrapper', 'class') || link.getNextTag('ul') || link.getNextTag('ol'); if (this.childMenu[link.id]) link.fusionSize = this.childMenu[link.id].getCoordinates(); if (this.childMenu[link.id] && window.ie) { var ul = this.childMenu[link.id].getElement('ul'); if (ul) { var padding = ul.getStyle('padding-bottom').toInt() || 0; link.fusionSize.height += padding; } } var type = 'subseq'; if ($(link.getParentTag('fusion-submenu-wrapper', 'class') || link.getParentTag('ul') || link.getParentTag('ol')) === this.element) type = 'init'; this.menuType[link.id] = type; }, this); this.jsContainer = new Element('div', {'class': 'fusion-js-container menutop'}).inject(document.body); this.jsContainer.addEvents({ 'mouseenter': function() { window.RTFUSION = true; }, 'mouseleave': function() { window.RTFUSION = false; } }); var cls = this.element.className.replace("menutop", ""); if (this.id.length) this.jsContainer.id = this.id; if (cls.length) { var newCls = "fusion-js-container " + cls + " menutop"; this.jsContainer.className = newCls.clean(); } var els = this.element.getElements('.fusion-submenu-wrapper'); if (!els.length) els = this.element.getElements('ul'); els.each(function(item,index){ var active = item.getElements('.item')[index]; if (active && this.parentLinks[active.id].length == 1) active = this.parentLinks[active.id].getLast().getParents('li')[0]; var subContainer = new Element('div', {'class': 'fusion-js-subs'}).inject(this.jsContainer).adopt(item); if (active && active.hasClass('active')) { item.getParent().addClass('active'); } }, this); this.jsContainer.getElements('.item').setProperty('tabindex', '-1'); links.each(function(link, i){ if (!this.childMenu[link.id]) {return;} this.childMenu[link.id] = this.childMenu[link.id].getParentTag('div'); this.subMenus.include(this.childMenu[link.id]); var tmp = []; this.parentLinks[link.id].each(function(parent, i) { tmp.push(this.childMenu[parent.id]); }, this); this.parentSubMenus[link.id] = tmp; link.aSubMenu = new FusionSubMenu(this.options,this, link); }, this); } }); Fusion.implement(new Options); var FusionSubMenu = new Class({ options: { onSubMenuInit_begin: (function(subMenuClass){}), onSubMenuInit_complete: (function(subMenuClass){}), onMatchWidth_begin: (function(subMenuClass){}), onMatchWidth_complete: (function(subMenuClass){}), onHideSubMenu_begin: (function(subMenuClass){}), onHideSubMenu_complete: (function(subMenuClass){}), onHideOtherSubMenus_begin: (function(subMenuClass){}), onHideOtherSubMenus_complete: (function(subMenuClass){}), onHideAllSubMenus_begin: (function(subMenuClass){}), onHideAllSubMenus_complete: (function(subMenuClass){}), onPositionSubMenu_begin: (function(subMenuClass){}), onPositionSubMenu_complete: (function(subMenuClass){}), onShowSubMenu_begin: (function(subMenuClass){}), onShowSubMenu_complete: (function(subMenuClass){}) }, root:null, btn:null, hidden:true, myEffect:null, initialize: function(options,root,btn){ this.setOptions(options); this.root = root; this.btn = $(btn); this.childMenu = $(root.childMenu[btn.id]); this.subMenuType = root.menuType[btn.id]; this.parentSubMenus = $$(root.parentSubMenus[btn.id]); this.parentLinks = $$(root.parentLinks[btn.id]); this.parentSubMenu = $(this.parentSubMenus[0]); this.otherSubMenus = {}; this.fxMorph = {}; this.rtl = root.rtl; this.options.tweakInitial = this.root.options.tweakInitial; this.options.tweakSubsequent = this.root.options.tweakSubsequent; this.options.centered = this.root.options.centered; this.childMenu.fusionStatus = 'closed'; this.options.onSubMenuInit_begin(this); this.childMenu.addEvent('hide', this.hideSubMenu.bind(this)); this.childMenu.addEvent('show', this.showSubMenu.bind(this)); var child = this.childMenu; if (this.options.effect) { this.myEffect = new Fx.Styles(this.childMenu.getFirst(), { duration: this.options.menuFx.duration, transition: this.options.menuFx.transition, wait: false, onStart: function() { if (window.ie) this.element.setStyle('display', 'block'); }, onComplete: function() { if (child.fusionStatus == 'closed') { if (!window.ie) { child.setStyle('display', 'none'); } else { this.element.setStyle('display', 'none'); } } } }); } if (this.options.effect == 'slide' || this.options.effect == 'slide and fade') { if (this.subMenuType == 'init' && this.options.orientation == 'horizontal') this.myEffect.set({'margin-top': '0'}); else { if (!this.rtl) this.myEffect.set({'margin-left': '0'}); else this.myEffect.set({'margin-right': '0'}); } } else if (this.options.effect == 'fade' || this.options.effect == 'slide and fade') this.myEffect.set({'opacity': 0}); if (this.options.effect != 'fade' && this.options.effect != 'slide and fade') this.myEffect.set({'opacity': this.options.opacity}); //attach event handlers to non-parent sub menu buttons var nonParentBtns = $(this.childMenu).getElements('.item').filter(function(item, index){ return !root.childMenu[item.id]; }); nonParentBtns.each(function(item, index){ $(item).getParent().addClass('f-submenu-item'); var prnt = item.getParent(); var listParents = item.getParents('li').length; if (listParents < 2 && !prnt.hasClass('fusion-grouped')) { prnt.addEvents({ 'mouseenter': function(e){ this.childMenu.fireEvent('show'); this.cancellHideAllSubMenus(); this.hideOtherSubMenus(); }.bind(this), 'focus': function(e){ this.childMenu.fireEvent('show'); this.cancellHideAllSubMenus(); this.hideOtherSubMenus(); }.bind(this), 'mouseleave': function(e){ this.cancellHideAllSubMenus(); this.hideAllSubMenus(); }.bind(this), 'blur': function(e){ this.cancellHideAllSubMenus(); this.hideAllSubMenus(); }.bind(this) }); } else { prnt.addEvents({ 'mouseenter': function(e){ this.childMenu.fireEvent('show'); this.cancellHideAllSubMenus(); if (!prnt.hasClass('fusion-grouped')) this.hideOtherSubMenus(); }.bind(this) }); } }, this); this.btn.removeClass('fusion-submenu-item'); if (this.subMenuType == 'init') this.btn.getParent().addClass('f-main-parent'); else this.btn.getParent().addClass('f-parent-item'); //attach event handlers to parent button this.btn.getParent().addEvents({ 'mouseenter' : function(e){ this.cancellHideAllSubMenus(); this.hideOtherSubMenus(); this.showSubMenu(); if (this.subMenuType == 'init' && this.options.mmbClassName && this.options.mmbFocusedClassName) { if (!this.fxMorph[this.btn.id]) this.fxMorph[this.btn.id] = {}; if (!this.fxMorph[this.btn.id]['btnMorph']) this.fxMorph[this.btn.id]['btnMorph'] = new Fx.Styles(this.btn, { 'duration': this.options.menuFx.duration, transition: this.options.menuFx.transition, wait: false }); this.fxMorph[this.btn.id]['btnMorph'].start(this.options.mmbFocusedClassName); } }.bind(this), 'focus' : function(e) { this.cancellHideAllSubMenus(); this.hideOtherSubMenus(); this.showSubMenu(); if (this.subMenuType == 'init' && this.options.mmbClassName && this.options.mmbFocusedClassName) { if (!this.fxMorph[this.btn.id]) this.fxMorph[this.btn.id] = {}; if (!this.fxMorph[this.btn.id]['btnMorph']) this.fxMorph[this.btn.id]['btnMorph'] = new Fx.Styles(this.btn, { 'duration': this.options.menuFx.duration, transition: this.options.menuFx.transition, wait: false }); this.fxMorph[this.btn.id]['btnMorph'].start(this.options.mmbFocusedClassName); } }.bind(this), 'mouseleave': function(e) { this.cancellHideAllSubMenus(); this.hideAllSubMenus(this.btn, this.btn.getParent().getParent().getTag() == 'ol'); }.bind(this), 'blur': function(e) { this.cancellHideAllSubMenus(); this.hideAllSubMenus(); }.bind(this) }); this.options.onSubMenuInit_complete(this); }, matchWidth:function(){ if (this.widthMatched || this.subMenuType === 'subseq') { return; } this.options.onMatchWidth_begin(this); var parentWidth = this.btn.getCoordinates().width; this.childMenu.getElements('.item').each(function(item,index) { var borderWidth = parseFloat(this.childMenu.getFirst().getStyle('border-left-width')) + parseFloat(this.childMenu.getFirst().getStyle('border-right-width')); var paddingWidth = parseFloat(item.getStyle('padding-left')) + parseFloat(item.getStyle('padding-right')); var offset = borderWidth + paddingWidth; //if(parentWidth > item.getCoordinates().width){ // item.setStyle('width',parentWidth - offset); // item.setStyle('margin-right',-borderWidth); //} }.bind(this)); this.width = this.btn.fusionSize.width; this.widthMatched = true; this.options.onMatchWidth_complete(this); }, hideSubMenu: function() { if(this.childMenu.fusionStatus === 'closed'){return;} this.options.onHideSubMenu_begin(this); if (this.subMenuType == 'init') { if (this.options.mmbClassName && this.options.mmbFocusedClassName) { if (!this.fxMorph[this.btn.id]) this.fxMorph[this.btn.id] = {}; if (!this.fxMorph[this.btn.id]['btnMorph']) this.fxMorph[this.btn.id]['btnMorph'] = new Fx.Styles(this.btn, { 'duration': this.options.menuFx.duration, transition: this.options.menuFx.transition, wait: false }); this.fxMorph[this.btn.id]['btnMorph'].start(this.options.mmbClassName).chain(function() { this.btn.getParent().removeClass('f-mainparent-itemfocus'); this.btn.getParent().addClass('f-mainparent-item'); }.bind(this)); } else { this.btn.getParent().removeClass('f-mainparent-itemfocus'); this.btn.getParent().addClass('f-mainparent-item'); } } else { this.btn.getParent().removeClass('f-menuparent-itemfocus'); this.btn.getParent().addClass('f-menuparent-item'); } this.childMenu.setStyle('z-index',1); if (this.options.effect && this.options.effect.toLowerCase() === 'slide') { if (this.subMenuType == 'init' && this.options.orientation == 'horizontal' && this.options.direction.y == 'down') { this.myEffect.start({'margin-top': -this.height}).chain(function() { if (this.childMenu.fusionStatus == 'closed') { if (!window.ie) { this.myEffect.set({'display': 'none'}); } else { this.myEffect.element.setStyle('display', 'none'); } } }.bind(this)); } else if (this.subMenuType == 'init' && this.options.orientation == 'horizontal' && this.options.direction.y == 'up') { this.myEffect.start({'margin-top': this.height}).chain(function() { if (this.childMenu.fusionStatus == 'closed') { if (!window.ie) { this.myEffect.set({'display': 'none'}); } else { this.myEffect.element.setStyle('display', 'none'); } } }.bind(this)); } else if (this.options.direction.x == 'right') { if (!this.rtl) tmp = {'margin-left': -this.width}; else tmp = {'margin-right': this.width}; this.myEffect.start(tmp).chain(function(){ if (this.childMenu.fusionStatus == 'closed') { if (!window.ie) { this.myEffect.set({'display': 'none'}); } else { this.myEffect.element.setStyle('display', 'none'); } } }.bind(this)); } else if (this.options.direction.x == 'left') { if (!this.rtl) tmp = {'margin-left': this.width}; else tmp = {'margin-right': -this.width}; this.myEffect.start(tmp).chain(function(){ if (this.childMenu.fusionStatus == 'closed') { if (!window.ie) { this.myEffect.set({'display': 'none'}); } else { this.myEffect.element.setStyle('display', 'none'); } } }.bind(this)); } } else if (this.options.effect == 'fade') { this.myEffect.start({'opacity': 0}).chain(function() { if (this.childMenu.fusionStatus == 'closed') { if (!window.ie) { this.myEffect.set({'display': 'none'}); } else { this.myEffect.element.setStyle('display', 'none'); } } }.bind(this)); } else if (this.options.effect == 'slide and fade') { if (this.subMenuType == 'init' && this.options.orientation == 'horizontal' && this.options.direction.y == 'down') { this.myEffect.start({'margin-top': -this.height,opacity: 0}).chain(function(){ if (this.childMenu.fusionStatus == 'closed') { if (!window.ie) { this.myEffect.set({'display': 'none'}); } else { this.myEffect.element.setStyle('display', 'none'); } } }.bind(this)); } else if (this.subMenuType == 'init' && this.options.orientation == 'horizontal' && this.options.direction.y == 'up') { this.myEffect.start({'margin-top': this.height,opacity: 0}).chain(function() { if (this.childMenu.fusionStatus == 'closed') { if (!window.ie) { this.myEffect.set({'display': 'none'}); } else { this.myEffect.element.setStyle('display', 'none'); } } }.bind(this)); } else if (this.options.direction.x == 'right') { if (!this.rtl) tmp = {'margin-left': -this.width, 'opacity': 0}; else tmp = {'margin-right': this.width, 'opacity': 0}; this.myEffect.start(tmp).chain(function() { if (this.childMenu.fusionStatus == 'closed') { if (!window.ie) { this.myEffect.set({'display': 'none'}); } else { this.myEffect.element.setStyle('display', 'none'); } } }.bind(this)); } else if (this.options.direction.x == 'left') { if (!this.rtl) tmp = {'margin-left': this.width, 'opacity': 0}; else tmp = {'margin-right': -this.width, 'opacity': 0}; this.myEffect.start(tmp).chain(function() { if (this.childMenu.fusionStatus == 'closed') { if (!window.ie) { this.myEffect.set({'display': 'none'}); } else { this.myEffect.element.setStyle('display', 'none'); } } }.bind(this)); } } else { if (!window.ie) { this.myEffect.set({'display': 'none'}); } else { this.myEffect.element.setStyle('display', 'none'); } } this.childMenu.fusionStatus = 'closed'; this.options.onHideSubMenu_complete(this); }, hideOtherSubMenus: function() { this.options.onHideOtherSubMenus_begin(this); if(!this.otherSubMenus[this.btn.id]){ this.otherSubMenus[this.btn.id] = $$(this.root.subMenus.filter(function(item){ return !this.root.parentSubMenus[this.btn.id].contains(item) && item != this.childMenu; }.bind(this)) ); } this.parentSubMenus.fireEvent('show'); this.otherSubMenus[this.btn.id].fireEvent('hide'); this.options.onHideOtherSubMenus_complete(this); }, hideAllSubMenus: function(btn, group){ this.options.onHideAllSubMenus_begin(this); $clear(this.root.hideAllMenusTimeout); this.root.hideAllMenusTimeout = (function(){ if (!window.RTFUSION) { $clear(this.hideAllMenusTimeout); this.myEffect.stop(); if (this.root.options.pill && !this.root.ghostRequest) this.root.pillFx.start(this.root.pillsDefaults); if (group) { var itms = $$(this.root.subMenus).filter(function(wrap) { return !wrap.hasChild(btn); }); $$(itms).fireEvent('hide'); } else $$(this.root.subMenus).fireEvent('hide'); } }).bind(this).delay(this.options.hideDelay); // (function() { if (!window.RTFUSION) this.root.hideAllMenusTimeout(); }.bind(this)).delay(this.options.hideDelay); this.options.onHideAllSubMenus_complete(this); }, cancellHideAllSubMenus: function(){ $clear(this.root.hideAllMenusTimeout); }, showSubMenu: function(now){ if (this.root.options.pill && this.subMenuType == 'init') { this.root.ghostRequest = false; this.root.pillFx.start({ 'left': this.btn.getParent().offsetLeft, 'width': this.btn.getParent().offsetWidth - this.root.pillsMargins, 'top': this.btn.getParent().offsetTop }); }; if(this.childMenu.fusionStatus === 'open') { return; } this.options.onShowSubMenu_begin(this); if (this.subMenuType == 'init') { this.btn.getParent().removeClass('f-mainparent-item'); this.btn.getParent().addClass('f-mainparent-itemfocus'); } else { this.btn.getParent().removeClass('f-menuparent-item'); this.btn.getParent().addClass('f-menuparent-itemfocus'); } this.root.subMenuZindex++; this.childMenu.setStyles({'display':'block','visibility':'hidden','z-index': this.root.subMenuZindex }); if(!this.width || !this.height ){ this.width = this.btn.fusionSize.width; this.height = this.btn.fusionSize.height; this.childMenu.getFirst().setStyle('height',this.height,'border'); if(this.options.effect == 'slide' || this.options.effect == 'slide and fade'){ if (this.subMenuType == 'init' && this.options.orientation == 'horizontal' ) { this.childMenu.getFirst().setStyle('margin-top','0' ); if (this.options.direction.y == 'down') { this.myEffect.set({'margin-top': - this.height}); } else if (this.options.direction.y == 'up') { this.myEffect.set({'margin-top': this.height}); } } else { if (this.options.direction.x == 'left') { if (!this.rtl) tmp = {'margin-left': this.width}; else tmp = {'margin-right': -this.width}; this.myEffect.set(tmp); } else { if (!this.rtl) tmp = {'margin-left': -this.width}; else tmp = {'margin-right': this.width}; this.myEffect.set(tmp); } } } } this.matchWidth(); this.positionSubMenu(); this.fixedHeader = $(document.body).hasClass('fixedheader-1'); if (this.fixedHeader && !this.scrollingEvent){ this.scrollingEvent = true; window.addEvent('scroll', function(){ this.positionSubMenu(); }.bind(this)); this.positionSubMenu(); } if (this.options.effect == 'slide' ) { this.childMenu.setStyles({'display': 'block', 'visibility': 'visible'}); if (this.subMenuType === 'init' && this.options.orientation === 'horizontal') { if (now) this.myEffect.set({'margin-top': 0}).chain(function() { this.showSubMenuComplete(); }.bind(this)); else this.myEffect.start({'margin-top': 0}).chain(function() { this.showSubMenuComplete(); }.bind(this)); } else { if (!this.rtl) tmp = {'margin-left': 0}; else tmp = {'margin-right': 0}; if (now) this.myEffect.set(tmp).chain(function() { this.showSubMenuComplete(); }.bind(this)); else this.myEffect.start(tmp).chain(function(){ this.showSubMenuComplete(); }.bind(this)); } } else if (this.options.effect == 'fade') { if (now) this.myEffect.set({'opacity': this.options.opacity}).chain(function() { this.showSubMenuComplete(); }.bind(this)); else this.myEffect.start({'opacity': this.options.opacity}).chain(function() { this.showSubMenuComplete(); }.bind(this)); } else if (this.options.effect == 'slide and fade') { this.childMenu.setStyles({'display': 'block', 'visibility': 'visible'}); this.childMenu.getFirst().setStyles({'left': 0}); if (this.subMenuType == 'init' && this.options.orientation == 'horizontal') { if (now) this.myEffect.set({'margin-top': 0, 'opacity': this.options.opacity}).chain(function() { this.showSubMenuComplete(); }.bind(this)); else this.myEffect.start({'margin-top': 0, 'opacity': this.options.opacity}).chain(function() { this.showSubMenuComplete(); }.bind(this)); } else { if (!this.rtl) tmp = {'margin-left': 0, 'opacity': this.options.opacity}; else tmp = {'margin-right': 0, 'opacity': this.options.opacity}; if (now) { if (this.options.direction.x == 'right') { this.myEffect.set(tmp).chain(function() { this.showSubMenuComplete(); }.bind(this)); } else if (this.options.direction.x == 'left') { this.myEffect.set(tmp).chain(function() { this.showSubMenuComplete(); }.bind(this)); } } else { if (this.options.direction.x == 'right') { this.myEffect.set({'margin-left': -this.width, 'opacity': this.options.opacity}); this.myEffect.start(tmp).chain(function() { this.showSubMenuComplete(); }.bind(this)); } else if (this.options.direction.x == 'left') { this.myEffect.set({'margin-left': this.width, 'opacity': this.options.opacity}); this.myEffect.start(tmp).chain(function(){ this.showSubMenuComplete(); }.bind(this)); } } } } else { this.childMenu.setStyles({'display': 'block', 'visibility': 'visible'}); this.showSubMenuComplete(this); } this.childMenu.fusionStatus = 'open'; }, showSubMenuComplete:function(){ this.options.onShowSubMenu_complete(this); }, positionSubMenu: function(){ if (this.root.disableScroll) return; this.options.onPositionSubMenu_begin(this); var height = this.childMenu.getStyle('padding-bottom').toInt() + this.options.tweakSizes.height; var width = this.options.tweakSizes.width; if (!window.presto || !window.gecko || !window.webkit) { width = 0; height = 0; } if (!this.rtl) { this.childMenu.setStyles({ 'width': this.width + this.options.tweakSizes.width, 'padding-bottom': this.options.tweakSizes.height, 'padding-top': this.options.tweakSizes.height / 2, 'padding-left': this.options.tweakSizes.width / 2 }); } else { this.childMenu.setStyles({ 'width': this.width + this.options.tweakSizes.width, 'padding-bottom': this.options.tweakSizes.height, 'padding-top': this.options.tweakSizes.height / 2, 'padding-right': this.options.tweakSizes.width / 2 }); } this.childMenu.getFirst().setStyles({ 'width': this.width }); if (this.subMenuType == 'subseq') { this.options.direction.x = 'right'; this.options.direction.xInverse = 'left'; this.options.direction.y = 'down'; this.options.direction.yInverse = 'up'; if (this.rtl) { this.options.direction.x = 'left'; this.options.direction.xInverse = 'right'; } } var top; var overlap; if (this.subMenuType == 'init') { if (this.options.direction.y == 'up') { if (this.options.orientation == 'vertical'){ top = (this.fixedHeader ? window.getSize().scroll.y : 0) + this.btn.getCoordinates().bottom - this.height + this.options.tweakInitial.y; } else { top = (this.fixedHeader ? window.getSize().scroll.y : 0) + this.btn.getCoordinates().top - this.height + this.options.tweakInitial.y; } this.childMenu.style.top = top + 'px'; } else if (this.options.orientation == 'horizontal') { this.childMenu.style.top = (this.fixedHeader ? window.getSize().scroll.y : 0) + this.btn.getCoordinates().bottom + this.options.tweakInitial.y + 'px'; } else if (this.options.orientation == 'vertical') { top = this.btn.getPosition().y + this.options.tweakInitial.y; if ((top + this.childMenu.getSize().y) >= $(document.body).getSize().scrollSize.y) { overlap = (top + this.childMenu.getSize().y) - $(document.body).getSize().scrollSize.y; top = top - overlap - 20; } this.childMenu.style.top = top + 'px'; } if (this.options.orientation == 'horizontal') { var position = this.btn.getPosition().x + this.options.tweakInitial.x, compensation = 0; if (this.rtl) { var x = 0; if (this.btn.getStyle('margin-left').toInt() < 0 && !this.options.centered) x = this.btn.getParent().getPosition().x + this.options.tweakInitial.x; else if (this.btn.getStyle('margin-left').toInt() < 0 && this.options.centered) x = this.btn.getPosition().x - this.options.tweakInitial.x; else x = this.btn.getPosition().x; position = x + this.btn.getSize().size.x - this.childMenu.getSize().size.x; } if (this.options.centered) { compensation = 0; var itemSize = this.btn.getSize().size.x; if (this.btn.getStyle('margin-left').toInt() < 0 && !this.rtl) compensation = Math.abs(this.btn.getStyle('margin-left').toInt()) - Math.abs(this.btn.getFirst().getStyle('padding-left').toInt()); else compensation = Math.abs(this.btn.getStyle('margin-right').toInt()) - Math.abs(this.btn.getFirst().getStyle('padding-right').toInt()); var childSize = this.childMenu.getSize().size.x; itemSize += compensation; var max = Math.max(itemSize, childSize), min = Math.min(itemSize, childSize); size = (max-min) / 2; if (!this.rtl) position -= size; else position += size; } this.childMenu.style.left = position + 'px'; } else if (this.options.direction.x == 'left') { this.childMenu.style.left = this.btn.getPosition().x - this.childMenu.getCoordinates().width + this.options.tweakInitial.x + 'px'; } else if (this.options.direction.x == 'right') { this.childMenu.style.left = this.btn.getCoordinates().right + this.options.tweakInitial.x + 'px'; } } else if (this.subMenuType == 'subseq') { if (this.options.direction.y === 'down') { if ((this.btn.getCoordinates().top + this.options.tweakSubsequent.y + this.childMenu.getSize().y) >= $(document.body).getSize().scrollSize.y) { overlap = (this.btn.getCoordinates().top + this.options.tweakSubsequent.y + this.childMenu.getSize().y) - $(document.body).getSize().scrollSize.y; this.childMenu.style.top = (this.btn.getCoordinates().top + this.options.tweakSubsequent.y) - overlap - 20 + 'px'; } else { this.childMenu.style.top = this.btn.getCoordinates().top + this.options.tweakSubsequent.y + 'px'; } } else if (this.options.direction.y === 'up') { if ((this.btn.getCoordinates().bottom - this.height + this.options.tweakSubsequent.y) < 1) { this.options.direction.y = 'down'; this.options.direction.yInverse = 'up'; this.childMenu.style.top = this.btn.getCoordinates().top + this.options.tweakSubsequent.y + 'px'; } else { this.childMenu.style.top = this.btn.getCoordinates().bottom - this.height + this.options.tweakSubsequent.y + 'px'; } } if (this.options.direction.x == 'left') { this.childMenu.style.left = this.btn.getCoordinates().left - this.childMenu.getCoordinates().width + this.options.tweakSubsequent.x + 'px'; if (this.childMenu.getPosition().x < 0) { this.options.direction.x = 'right'; this.options.direction.xInverse = 'left'; this.childMenu.style.left = this.btn.getPosition().x + this.btn.getCoordinates().width + this.options.tweakSubsequent.x + 'px'; if(this.options.effect === 'slide' || this.options.effect === 'slide and fade'){ if (!this.rtl) tmp = {'margin-left': -this.width, 'opacity': this.options.opacity}; else tmp = {'margin-right': this.width, 'opacity': this.options.opacity}; this.myEffect.set(tmp); } } } else if(this.options.direction.x == 'right') { this.childMenu.style.left = this.btn.getCoordinates().right + this.options.tweakSubsequent.x + 'px'; var smRight = this.childMenu.getCoordinates().right; var viewportRightEdge = $(document.body).getSize().size.x + $(window).getSize().scroll.x; if(smRight > viewportRightEdge) { this.options.direction.x = 'left'; this.options.direction.xInverse = 'right'; this.childMenu.style.left = this.btn.getCoordinates().left - this.childMenu.getCoordinates().width - this.options.tweakSubsequent.x + 'px'; if (this.options.effect == 'slide' || this.options.effect == 'slide and fade') { if (!this.rtl) tmp = {'margin-left': this.width, 'opacity': this.options.opacity}; else tmp = {'margin-right': -this.width, 'opacity': this.options.opacity}; this.myEffect.set(tmp); } } } } this.options.onPositionSubMenu_complete(this); } }); FusionSubMenu.implement(new Options); Element.extend({ getID: function(){ if(!this.id){ var rid = this.getTag() + "-" + $time() + $random(0, 1000); //while ($(rid)) {this.getTag() + "-" + $time() + $random(0, 1000);} this.id = rid; }; return this.id; }, getParents: function(tag, el) { var matched = []; var cur = this.getParent(); while (cur && cur !== ($(el) || document)) { if(cur.getTag().test(tag)) matched.push(cur); cur = cur.getParent(); } return $$(matched); }, getNextTag: function(tag) { var next = this; while (next = next.getNext()) { if (next.hasClass(tag) || next.getTag() == tag) return next; } return false; }, getParentTag: function(tag, type) { if (!type) type = 'tag'; var parent = this.getParent(); while (parent && parent != document.body) { if (parent.className.test(tag) && type == 'class') return parent; if (parent.getTag() == tag && type == 'tag') return parent; parent = parent.getParent(); } return false; } });
srajib/share2learn
modules/mod_roknavmenu/themes/fusion/js/fusion.source.js
JavaScript
gpl-2.0
32,452
#This stores supporting configuration classes used in the config file to register class mappings and parameter mappings etc. require 'app/request_store' require 'exception/rubyamf_exception' module RubyAMF module Configuration #ClassMappings configuration support class class ClassMappings # these NEED to be outside the class << self to work @ignore_fields = ['created_at','created_on','updated_at','updated_on'] @translate_case = false @class_mappings_by_ruby_class = {} @class_mappings_by_actionscript_class = {} @scoped_class_mappings_by_ruby_class = {} @attribute_names = {} @hash_key_access = :symbol @translate_case = false @force_active_record_ids = true @assume_types = false @use_ruby_date_time = false @use_array_collection = false @check_for_associations = true # Aryk: I cleaned up how the class variables are called here. It doesnt matter if you use class variables or instance variables on the class level. Check out this simple tutorial # - http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby class << self include RubyAMF::App include RubyAMF::Exceptions attr_accessor :ignore_fields, :use_array_collection, :default_mapping_scope, :force_active_record_ids, :attribute_names, :use_ruby_date_time, :current_mapping_scope, :check_for_associations, :translate_case, :assume_types, :hash_key_access #the rails parameter mapping type def register(mapping) #register a value object map #build out ignore field logic hashed_ignores = {} ClassMappings.ignore_fields.to_a.each{|k| hashed_ignores[k] = true} # strings and nils will be put into an array with to_a mapping[:ignore_fields].to_a.each{|k| hashed_ignores[k] = true} mapping[:ignore_fields] = hashed_ignores # overwrite the original ignore fields # if they specify custom attributes, ensure that AR ids are being passed as well if they opt for it. if force_active_record_ids && mapping[:attributes] && mapping[:type]=="active_record" && !mapping[:attributes].include?("id") mapping[:attributes] << "id" end # created caching hashes for mapping @class_mappings_by_ruby_class[mapping[:ruby]] = mapping # for quick referencing purposes @class_mappings_by_actionscript_class[mapping[:actionscript]] = mapping # for quick referencing purposes @scoped_class_mappings_by_ruby_class[mapping[:ruby]] = {} # used later for caching based on scope (will get cached after the first run) # for deserialization - looking up in a hash is faster than looking up in an array. begin if mapping[:type] == "active_record" @attribute_names[mapping[:ruby]] = (mapping[:ruby].constantize.new.attribute_names + ["id"]).inject({}){|hash, attr| hash[attr]=true ; hash} # include the id attribute end rescue ActiveRecord::StatementInvalid => e # This error occurs during migrations, since the AR constructed above will check its columns, but the table won't exist yet. # We'll ignore the error if we're migrating. raise unless ARGV.include?("migrate") or ARGV.include?("db:migrate") end end def get_vo_mapping_for_ruby_class(ruby_class) return unless scoped_class_mapping = @scoped_class_mappings_by_ruby_class[ruby_class] # just in case they didnt specify a ClassMapping for this Ruby Class scoped_class_mapping[@current_mapping_scope] ||= (if vo_mapping = @class_mappings_by_ruby_class[ruby_class] vo_mapping = vo_mapping.dup # need to duplicate it or else we will overwrite the keys from the original mappings vo_mapping[:attributes] = vo_mapping[:attributes][@current_mapping_scope]||[] if vo_mapping[:attributes].is_a?(Hash) # don't include any of these attributes if there is no scope vo_mapping[:associations] = vo_mapping[:associations][@current_mapping_scope]||[] if vo_mapping[:associations].is_a?(Hash) # don't include any of these attributes vo_mapping end ) end def get_vo_mapping_for_actionscript_class(actionscript_class) @class_mappings_by_actionscript_class[actionscript_class] end end end class ParameterMappings @parameter_mappings = {} @always_add_to_params = true @scaffolding = false class << self attr_accessor :scaffolding, :always_add_to_params def register(mapping) raise RUBYAMFException.new(RUBYAMFException.USER_ERROR, "You must atleast specify the :controller for a parameter mapping") unless mapping[:controller] set_parameter_mapping(mapping[:controller], mapping[:action], mapping) end def update_request_parameters(controller_class_name, controller_action_name, request_params, rubyamf_params, remoting_params) if map = get_parameter_mapping(controller_class_name, controller_action_name) map[:params].each do |k,v| val = eval("remoting_params#{v}") if scaffolding && val.is_a?(ActiveRecord::Base) request_params[k.to_sym] = val.attributes.dup val.instance_variables.each do |assoc| next if "@new_record" == assoc request_params[k.to_sym][assoc[1..-1]] = val.instance_variable_get(assoc) end else request_params[k.to_sym] = val end rubyamf_params[k.to_sym] = request_params[k.to_sym] # assign it to rubyamf_params for consistency end else #do some default mappings for the first element in the parameters if remoting_params.is_a?(Array) if scaffolding if (first = remoting_params[0]) if first.is_a?(ActiveRecord::Base) key = first.class.to_s.to_snake!.downcase.to_sym # a generated scaffold expects params in snake_case, rubyamf_params gets them for consistency in scaffolding rubyamf_params[key] = first.attributes.dup first.instance_variables.each do |assoc| next if "@new_record" == assoc rubyamf_params[key][assoc[1..-1]] = first.instance_variable_get(assoc) end if always_add_to_params #if wanted in params, put it in request_params[key] = rubyamf_params[key] #put it into rubyamf_params end else if first.is_a?(RubyAMF::VoHelper::VoHash) if (key = first.explicitType.split('::').last.to_snake!.downcase.to_sym) rubyamf_params[key] = first if always_add_to_params request_params[key] = first end end elsif first.is_a?(Hash) # a simple hash should become named params in params rubyamf_params.merge!(first) if always_add_to_params request_params.merge!(first) end end end request_params[:id] = rubyamf_params[:id] = first['id'] if (first['id'] && !(first['id']==0)) end end end end end private def get_parameter_mapping(controller_class_name, controller_action_name) @parameter_mappings[end_point_string(controller_class_name, controller_action_name)]|| # first check to see if there is a paramter mapping for the controller/action combo, @parameter_mappings[end_point_string(controller_class_name)] # then just check if there is one for the controller end def set_parameter_mapping(controller_class_name, controller_action_name, mapping) @parameter_mappings[end_point_string(controller_class_name, controller_action_name)] = mapping end def end_point_string(controller_class_name, controller_action_name=nil) # if the controller_action_name is nil, than we the parameter mapping is for the entire controller eps = controller_class_name.to_s.dup # could be a symbol from the class mapping ; need to dup because it will recursively append the action_name eps << ".#{controller_action_name}" if controller_action_name eps end end end end end
jfbvm/planigle
vendor/plugins/rubyamf/app/configuration.rb
Ruby
gpl-2.0
8,872
// ************************************************************************* // // PARALUTION www.paralution.com // // Copyright (C) 2012-2013 Dimitar Lukarski // // 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 3 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, see <http://www.gnu.org/licenses/>. // // ************************************************************************* #ifndef PARALUTION_KRYLOV_CR_HPP_ #define PARALUTION_KRYLOV_CR_HPP_ #include "../solver.hpp" #include <vector> namespace paralution { template <class OperatorType, class VectorType, typename ValueType> class CR : public IterativeLinearSolver<OperatorType, VectorType, ValueType> { public: CR(); virtual ~CR(); virtual void Print(void) const; virtual void Build(void); virtual void Clear(void); protected: virtual void SolveNonPrecond_(const VectorType &rhs, VectorType *x); virtual void SolvePrecond_(const VectorType &rhs, VectorType *x); virtual void PrintStart_(void) const; virtual void PrintEnd_(void) const; virtual void MoveToHostLocalData_(void); virtual void MoveToAcceleratorLocalData_(void); private: VectorType r_, z_, t_; VectorType p_, q_, v_; }; } #endif // PARALUTION_KRYLOV_CR_HPP_
hpfem/agros2d
3rdparty/paralution/src/solvers/krylov/cr.hpp
C++
gpl-2.0
1,835
/**************************************************************************** * * This file is part of the ViSP software. * Copyright (C) 2005 - 2017 by Inria. All rights reserved. * * This software 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. * See the file LICENSE.txt at the root directory of this source * distribution for additional information about the GNU GPL. * * For using ViSP with software that can not be combined with the GNU * GPL, please contact Inria about acquiring a ViSP Professional * Edition License. * * See http://visp.inria.fr for more information. * * This software was developed at: * Inria Rennes - Bretagne Atlantique * Campus Universitaire de Beaulieu * 35042 Rennes Cedex * France * * If you have questions regarding the use of this file, please contact * Inria at visp@inria.fr * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Description: * Operation on row vectors. * * Authors: * Eric Marchand * *****************************************************************************/ /*! \file vpRowVector.cpp \brief Definition of vpRowVector class member */ #include <assert.h> #include <cmath> #include <sstream> #include <stdlib.h> #include <string.h> #include <visp3/core/vpArray2D.h> #include <visp3/core/vpColVector.h> #include <visp3/core/vpDebug.h> #include <visp3/core/vpException.h> #include <visp3/core/vpMatrix.h> #include <visp3/core/vpRowVector.h> //! Copy operator. Allow operation such as A = v vpRowVector &vpRowVector::operator=(const vpRowVector &v) { unsigned int k = v.colNum; if (colNum != k) { try { resize(k); } catch (...) { throw; } } memcpy(data, v.data, colNum * sizeof(double)); return *this; } /*! Initialize a row vector from a 1-by-n size matrix. \warning Handled with care m should be a 1 column matrix. \exception vpException::dimensionError If the matrix is not a 1-by-n dimension matrix. */ vpRowVector &vpRowVector::operator=(const vpMatrix &M) { if (M.getRows() != 1) { throw(vpException(vpException::dimensionError, "Cannot initialize a (1x%d) row vector from a (%dx%d) matrix", M.getCols(), M.getRows(), M.getCols())); } if (M.getCols() != colNum) resize(M.getCols()); memcpy(data, M.data, colNum * sizeof(double)); return *this; } /*! Initialize a row vector from a standard vector of double. */ vpRowVector &vpRowVector::operator=(const std::vector<double> &v) { resize((unsigned int)v.size()); for (unsigned int i = 0; i < v.size(); i++) (*this)[i] = v[i]; return *this; } /*! Initialize a row vector from a standard vector of double. */ vpRowVector &vpRowVector::operator=(const std::vector<float> &v) { resize((unsigned int)v.size()); for (unsigned int i = 0; i < v.size(); i++) (*this)[i] = (float)v[i]; return *this; } //! Initialize each element of the vector with \e x. vpRowVector &vpRowVector::operator=(double x) { for (unsigned int i = 0; i < rowNum; i++) { for (unsigned int j = 0; j < colNum; j++) { rowPtrs[i][j] = x; } } return *this; } /*! Multiply a row vector by a column vector. \param x : Column vector. \warning The number of elements of the two vectors must be equal. \exception vpException::dimensionError : If the number of elements of the two vectors is not the same. \return A scalar. */ double vpRowVector::operator*(const vpColVector &x) const { unsigned int nelements = x.getRows(); if (getCols() != nelements) { throw(vpException(vpException::dimensionError, "Cannot multiply (1x%d) row vector by (%dx1) column vector", colNum, x.getRows())); } double scalar = 0.0; for (unsigned int i = 0; i < nelements; i++) { scalar += (*this)[i] * x[i]; } return scalar; } /*! Multiply a row vector by a matrix. \param M : Matrix. \warning The number of elements of the row vector must be equal to the number of rows of the matrix. \exception vpException::dimensionError If the number of elements of the row vector is not equal to the number of rows of the matrix. \return The resulting row vector. */ vpRowVector vpRowVector::operator*(const vpMatrix &M) const { vpRowVector c(M.getCols()); if (colNum != M.getRows()) { throw(vpException(vpException::dimensionError, "Cannot multiply (1x%d) row vector by (%dx%d) matrix", colNum, M.getRows(), M.getCols())); } c = 0.0; for (unsigned int i = 0; i < colNum; i++) { double bi = data[i]; // optimization em 5/12/2006 for (unsigned int j = 0; j < M.getCols(); j++) { c[j] += bi * M[i][j]; } } return c; } /*! Operator that allows to multiply each element of a row vector by a scalar. \param x : The scalar. \return The row vector multiplied by the scalar. The current row vector (*this) is unchanged. \code vpRowVector v(3); v[0] = 1; v[1] = 2; v[2] = 3; vpRowVector w = v * 3; // v is unchanged // w is now equal to : [3 6 9] \endcode */ vpRowVector vpRowVector::operator*(double x) const { vpRowVector v(colNum); double *vd = v.data; double *d = data; for (unsigned int i = 0; i < colNum; i++) *(vd++) = (*d++) * x; return v; } /*! Operator that allows to multiply each element of a row vector by a scalar. \param x : The scalar. \return The row vector multiplied by the scalar. \code vpRowVector v(3); v[0] = 1; v[1] = 2; v[2] = 3; v *= 3; // v is now equal to : [3 6 9] \endcode */ vpRowVector &vpRowVector::operator*=(double x) { for (unsigned int i = 0; i < colNum; i++) (*this)[i] *= x; return (*this); } /*! Operator that allows to divide each element of a row vector by a scalar. \param x : The scalar. \return The row vector divided by the scalar. The current row vector (*this) is unchanged. \code vpRowVector v(3); v[0] = 8; v[1] = 4; v[2] = 2; vpRowVector w = v / 2; // v is equal to : [8 4 2] // w is equal to : [4 2 1] \endcode */ vpRowVector vpRowVector::operator/(double x) const { vpRowVector v(colNum); double *vd = v.data; double *d = data; for (unsigned int i = 0; i < colNum; i++) *(vd++) = (*d++) / x; return v; } /*! Operator that allows to divide each element of a row vector by a scalar. \param x : The scalar. \return The row vector divided by the scalar. \code vpRowVector v(3); v[0] = 8; v[1] = 4; v[2] = 2; // v is equal to : [8 4 2] v /= 2; // v is equal to : [4 2 1] \endcode */ vpRowVector &vpRowVector::operator/=(double x) { for (unsigned int i = 0; i < colNum; i++) (*this)[i] /= x; return (*this); } /*! Operator that allows to negate all the row vector elements. \code vpRowVector r(3, 1); // r contains [1 1 1] vpRowVector v = -r; // v contains [-1 -1 -1] \endcode */ vpRowVector vpRowVector::operator-() const { vpRowVector A(colNum); double *vd = A.data; double *d = data; for (unsigned int i = 0; i < colNum; i++) *(vd++) = -(*d++); return A; } /*! Operator that allows to substract to row vectors that have the same size. \exception vpException::dimensionError If the vectors size differ. */ vpRowVector vpRowVector::operator-(const vpRowVector &m) const { if (getCols() != m.getCols()) { throw(vpException(vpException::dimensionError, "Cannot substract (1x%d) row vector to (1x%d) row vector", getCols(), m.getCols())); } vpRowVector v(colNum); for (unsigned int i = 0; i < colNum; i++) v[i] = (*this)[i] - m[i]; return v; } /*! Operator that allows to add to row vectors that have the same size. \exception vpException::dimensionError If the vectors size differ. */ vpRowVector vpRowVector::operator+(const vpRowVector &v) const { if (getCols() != v.getCols()) { throw(vpException(vpException::dimensionError, "Cannot add (1x%d) row vector to (1x%d) row vector", getCols(), v.getCols())); } vpRowVector r(colNum); for (unsigned int i = 0; i < colNum; i++) r[i] = (*this)[i] + v[i]; return r; } /*! Operator that allows to add two row vectors that have the same size. \exception vpException::dimensionError If the size of the two vectors differ. */ vpRowVector &vpRowVector::operator+=(vpRowVector v) { if (getCols() != v.getCols()) { throw(vpException(vpException::dimensionError, "Cannot add (1x%d) row vector to (1x%d) row vector", getCols(), v.getCols())); } for (unsigned int i = 0; i < colNum; i++) (*this)[i] += v[i]; return (*this); } /*! Operator that allows to substract two row vectors that have the same size. \exception vpException::dimensionError If the size of the two vectors differ. */ vpRowVector &vpRowVector::operator-=(vpRowVector v) { if (getCols() != v.getCols()) { throw(vpException(vpException::dimensionError, "Cannot substract (1x%d) row vector to (1x%d) row vector", getCols(), v.getCols())); } for (unsigned int i = 0; i < colNum; i++) (*this)[i] -= v[i]; return (*this); } /*! Copy operator. Allows operation such as A << v \code #include <visp3/core/vpRowVector.h> int main() { vpRowVector A, B(5); for (unsigned int i=0; i<B.size(); i++) B[i] = i; A << B; std::cout << "A: " << A << std::endl; } \endcode In row vector A we get: \code A: 0 1 2 3 4 \endcode */ vpRowVector &vpRowVector::operator<<(const vpRowVector &v) { *this = v; return *this; } /*! Transpose the row vector. The resulting vector becomes a column vector. */ vpColVector vpRowVector::t() const { vpColVector v(colNum); memcpy(v.data, data, colNum * sizeof(double)); return v; } /*! Transpose the row vector. The resulting vector becomes a column vector. \sa t() */ vpColVector vpRowVector::transpose() const { return t(); } /*! Transpose the row vector. The resulting vector \e v becomes a column vector. \sa t() */ void vpRowVector::transpose(vpColVector &v) const { v = t(); } /*! Constructor that creates a row vector corresponding to row \e i of matrix \e M. */ vpRowVector::vpRowVector(const vpMatrix &M, unsigned int i) : vpArray2D<double>(1, M.getCols()) { for (unsigned int j = 0; j < M.getCols(); j++) (*this)[j] = M[i][j]; } /*! Constructor that creates a row vector from a 1-by-n matrix \e M. \exception vpException::dimensionError If the matrix is not a 1-by-n matrix. */ vpRowVector::vpRowVector(const vpMatrix &M) : vpArray2D<double>(1, M.getCols()) { if (M.getRows() != 1) { throw(vpException(vpException::dimensionError, "Cannot construct a (1x%d) row vector from a (%dx%d) matrix", M.getCols(), M.getRows(), M.getCols())); } for (unsigned int j = 0; j < M.getCols(); j++) (*this)[j] = M[0][j]; } /*! Constructor that creates a row vector from a std vector of double. */ vpRowVector::vpRowVector(const std::vector<double> &v) : vpArray2D<double>(1, (unsigned int)v.size()) { for (unsigned int j = 0; j < v.size(); j++) (*this)[j] = v[j]; } /*! Constructor that creates a row vector from a std vector of float. */ vpRowVector::vpRowVector(const std::vector<float> &v) : vpArray2D<double>(1, (unsigned int)v.size()) { for (unsigned int j = 0; j < v.size(); j++) (*this)[j] = (double)(v[j]); } /*! Construct a row vector from a part of an input row vector \e v. \param v : Input row vector used for initialization. \param c : column index in \e v that corresponds to the first element of the row vector to contruct. \param ncols : Number of columns of the constructed row vector. The sub-vector starting from v[c] element and ending on v[c+ncols-1] element is used to initialize the contructed row vector. \sa init() */ vpRowVector::vpRowVector(const vpRowVector &v, unsigned int c, unsigned int ncols) : vpArray2D<double>(1, ncols) { init(v, c, ncols); } /*! Normalise the vector given as input parameter and return the normalized vector: \f[ {\bf x} = \frac{{\bf x}}{\sqrt{\sum_{i=1}^{n}x^2_i}} \f] where \f$x_i\f$ is an element of the row vector \f$\bf x\f$. */ vpRowVector &vpRowVector::normalize(vpRowVector &x) const { x = x / sqrt(x.sumSquare()); return x; } /*! Normalise the vector modifying the vector as: \f[ {\bf x} = \frac{{\bf x}}{\sqrt{\sum_{i=1}^{n}x^2_i}} \f] where \f$x_i\f$ is an element of the row vector \f$\bf x\f$. */ vpRowVector &vpRowVector::normalize() { double sum_square = sumSquare(); if (std::fabs(sum_square) > std::numeric_limits<double>::epsilon()) { *this /= sqrt(sum_square); } // If sum = 0, we have a nul vector. So we return just. return *this; } /*! Reshape the row vector in a matrix. \param nrows : number of rows of the matrix. \param ncols : number of columns of the matrix. \return The resulting matrix. \exception vpException::dimensionError If the matrix and the row vector have not the same size. \sa reshape(vpMatrix &, const unsigned int &, const unsigned int &) */ vpMatrix vpRowVector::reshape(const unsigned int &nrows, const unsigned int &ncols) { vpMatrix M(nrows, ncols); reshape(M, nrows, ncols); return M; } /*! Reshape the row vector in a matrix. \param M : the reshaped matrix. \param nrows : number of rows of the matrix. \param ncols : number of columns of the matrix. \exception vpException::dimensionError If the matrix and the row vector have not the same size. The following example shows how to use this method. \code #include <visp/vpRowVector.h> int main() { int var=0; vpMatrix mat(3, 4); for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) mat[i][j] = ++var; std::cout << "mat: \n" << mat << std::endl; vpRowVector row = mat.stackRows(); std::cout << "row vector: " << row << std::endl; vpMatrix remat = row.reshape(3, 4); std::cout << "remat: \n" << remat << std::endl; } \endcode If you run the previous example, you get: \code mat: 1 2 3 4 5 6 7 8 9 10 11 12 row vector: 1 2 3 4 5 6 7 8 9 10 11 12 remat: 1 2 3 4 5 6 7 8 9 10 11 12 \endcode */ void vpRowVector::reshape(vpMatrix &M, const unsigned int &nrows, const unsigned int &ncols) { if (dsize != nrows * ncols) { throw(vpException(vpException::dimensionError, "Cannot reshape (1x%d) row vector in (%dx%d) matrix", colNum, M.getRows(), M.getCols())); } try { if ((M.getRows() != nrows) || (M.getCols() != ncols)) M.resize(nrows, ncols); } catch (...) { throw; } for (unsigned int i = 0; i < nrows; i++) for (unsigned int j = 0; j < ncols; j++) M[i][j] = data[i * ncols + j]; } /*! Insert a row vector. \param i : Index of the first element to introduce. This index starts from 0. \param v : Row vector to insert. The following example shows how to use this function: \code #include <visp/vpRowVector.h> int main() { vpRowVector v(4); for (unsigned int i=0; i < v.size(); i++) v[i] = i; std::cout << "v: " << v << std::endl; vpRowVector w(2); for (unsigned int i=0; i < w.size(); i++) w[i] = i+10; std::cout << "w: " << w << std::endl; v.insert(1, w); std::cout << "v: " << v << std::endl; } \endcode It produces the following output: \code v: 0 1 2 3 w: 10 11 v: 0 10 11 3 \endcode */ void vpRowVector::insert(unsigned int i, const vpRowVector &v) { if (i + v.size() > this->size()) throw(vpException(vpException::dimensionError, "Unable to insert (1x%d) row vector in (1x%d) row " "vector at position (%d)", v.getCols(), colNum, i)); for (unsigned int j = 0; j < v.size(); j++) (*this)[i + j] = v[j]; } /*! Stack row vector with a new element at the end of the vector. \param d : Element to stack to the existing one. \code vpRowVector v(3, 1); // v is equal to [1 1 1] v.stack(-2); // v is equal to [1 1 1 -2] \endcode \sa stack(const vpRowVector &, const vpRowVector &) \sa stack(const vpRowVector &, const vpRowVector &, vpRowVector &) */ void vpRowVector::stack(double d) { this->resize(colNum + 1, false); (*this)[colNum - 1] = d; } /*! Stack row vectors. \param v : Vector to stack to the existing one. \code vpRowVector v1(3, 1); // v1 is equal to [1 1 1] vpRowVector v2(2, 3); // v2 is equal to [3 3] v1.stack(v2); // v1 is equal to [1 1 1 3 3] \endcode \sa stack(const vpRowVector &, const double &) \sa stack(const vpRowVector &, const vpRowVector &) \sa stack(const vpRowVector &, const vpRowVector &, vpRowVector &) */ void vpRowVector::stack(const vpRowVector &v) { *this = vpRowVector::stack(*this, v); } /*! Stack row vectors. \param A : Initial vector. \param B : Vector to stack at the end of A. \return Stacked vector \f$[A B]\f$. \code vpRowVector r1(3, 1); // r1 is equal to [1 1 1] vpRowVector r2(2, 3); // r2 is equal to [3 3] vpRowVector v; v = vpRowVector::stack(r1, r2); // v is equal to [1 1 1 3 3] \endcode \sa stack(const vpRowVector &) \sa stack(const vpRowVector &, const vpRowVector &, vpRowVector &) */ vpRowVector vpRowVector::stack(const vpRowVector &A, const vpRowVector &B) { vpRowVector C; vpRowVector::stack(A, B, C); return C; } /*! Stack row vectors. \param A : Initial vector. \param B : Vector to stack at the end of A. \param C : Resulting stacked vector \f$C = [A B]\f$. \code vpRowVector r1(3, 1); // r1 is equal to [1 1 1] vpRowVector r2(2, 3); // r2 is equal to [3 3] vpRowVector v; vpRowVector::stack(r1, r2, v); // v is equal to [1 1 1 3 3] \endcode \sa stack(const vpRowVector &) \sa stack(const vpRowVector &, const vpRowVector &) */ void vpRowVector::stack(const vpRowVector &A, const vpRowVector &B, vpRowVector &C) { unsigned int nrA = A.getCols(); unsigned int nrB = B.getCols(); if (nrA == 0 && nrB == 0) { C.resize(0); return; } if (nrB == 0) { C = A; return; } if (nrA == 0) { C = B; return; } // General case C.resize(nrA + nrB); for (unsigned int i = 0; i < nrA; i++) C[i] = A[i]; for (unsigned int i = 0; i < nrB; i++) C[nrA + i] = B[i]; } /*! Compute the mean value of all the elements of the vector. */ double vpRowVector::mean(const vpRowVector &v) { if (v.data == NULL || v.size() == 0) { throw(vpException(vpException::dimensionError, "Cannot compute mean value of an empty row vector")); } double mean = 0; double *vd = v.data; for (unsigned int i = 0; i < v.getCols(); i++) mean += *(vd++); return mean / v.getCols(); } /*! Compute the median value of all the elements of the vector. */ double vpRowVector::median(const vpRowVector &v) { if (v.data == NULL || v.size() == 0) { throw(vpException(vpException::dimensionError, "Cannot compute mean value of an empty row vector")); } std::vector<double> vectorOfDoubles(v.data, v.data + v.colNum); return vpMath::getMedian(vectorOfDoubles); } /*! Compute the standard deviation value of all the elements of the vector. */ double vpRowVector::stdev(const vpRowVector &v, const bool useBesselCorrection) { if (v.data == NULL || v.size() == 0) { throw(vpException(vpException::dimensionError, "Cannot compute mean value of an empty row vector")); } double mean_value = mean(v); double sum_squared_diff = 0.0; for (unsigned int i = 0; i < v.size(); i++) { sum_squared_diff += (v[i] - mean_value) * (v[i] - mean_value); } double divisor = (double)v.size(); if (useBesselCorrection && v.size() > 1) { divisor = divisor - 1; } return std::sqrt(sum_squared_diff / divisor); } /*! Pretty print a row vector. The data are tabulated. The common widths before and after the decimal point are set with respect to the parameter maxlen. \param s Stream used for the printing. \param length The suggested width of each row vector element. The actual width grows in order to accomodate the whole integral part, and shrinks if the whole extent is not needed for all the numbers. \param intro The introduction which is printed before the vector. Can be set to zero (or omitted), in which case the introduction is not printed. \return Returns the common total width for all vector elements. \sa std::ostream &operator<<(std::ostream &s, const vpArray2D<Type> &A) */ int vpRowVector::print(std::ostream &s, unsigned int length, char const *intro) const { typedef std::string::size_type size_type; unsigned int m = 1; unsigned int n = getCols(); std::vector<std::string> values(m * n); std::ostringstream oss; std::ostringstream ossFixed; std::ios_base::fmtflags original_flags = oss.flags(); // ossFixed <<std::fixed; ossFixed.setf(std::ios::fixed, std::ios::floatfield); size_type maxBefore = 0; // the length of the integral part size_type maxAfter = 0; // number of decimals plus // one place for the decimal point for (unsigned int j = 0; j < n; ++j) { oss.str(""); oss << (*this)[j]; if (oss.str().find("e") != std::string::npos) { ossFixed.str(""); ossFixed << (*this)[j]; oss.str(ossFixed.str()); } values[j] = oss.str(); size_type thislen = values[j].size(); size_type p = values[j].find('.'); if (p == std::string::npos) { maxBefore = vpMath::maximum(maxBefore, thislen); // maxAfter remains the same } else { maxBefore = vpMath::maximum(maxBefore, p); maxAfter = vpMath::maximum(maxAfter, thislen - p - 1); } } size_type totalLength = length; // increase totalLength according to maxBefore totalLength = vpMath::maximum(totalLength, maxBefore); // decrease maxAfter according to totalLength maxAfter = (std::min)(maxAfter, totalLength - maxBefore); if (maxAfter == 1) maxAfter = 0; // the following line is useful for debugging // std::cerr <<totalLength <<" " <<maxBefore <<" " <<maxAfter <<"\n"; if (intro) s << intro; s << "[" << m << "," << n << "]=\n"; s << " "; for (unsigned int j = 0; j < n; j++) { size_type p = values[j].find('.'); s.setf(std::ios::right, std::ios::adjustfield); s.width((std::streamsize)maxBefore); s << values[j].substr(0, p).c_str(); if (maxAfter > 0) { s.setf(std::ios::left, std::ios::adjustfield); if (p != std::string::npos) { s.width((std::streamsize)maxAfter); s << values[j].substr(p, maxAfter).c_str(); } else { assert(maxAfter > 1); s.width((std::streamsize)maxAfter); s << ".0"; } } s << ' '; } s << std::endl; s.flags(original_flags); // restore s to standard state return (int)(maxBefore + maxAfter); } /*! Allows to multiply a scalar by row vector. */ vpRowVector operator*(const double &x, const vpRowVector &v) { vpRowVector vout; vout = v * x; return vout; } /*! Return the sum of all the elements \f$v_{i}\f$ of the row vector v(n). \return The sum square value: \f$\sum_{j=0}^{n} v_j\f$. */ double vpRowVector::sum() const { double sum = 0.0; for (unsigned int j = 0; j < colNum; j++) { sum += rowPtrs[0][j]; } return sum; } /*! Return the sum square of all the elements \f$v_{i}\f$ of the row vector v(n). \return The sum square value: \f$\sum_{j=0}^{n} v_j^{2}\f$. */ double vpRowVector::sumSquare() const { double sum_square = 0.0; for (unsigned int j = 0; j < colNum; j++) { double x = rowPtrs[0][j]; sum_square += x * x; } return sum_square; } /*! Compute and return the Euclidean norm \f$ ||x|| = \sqrt{ \sum{v_{i}^2}} \f$. \return The Euclidean norm if the vector is initialized, 0 otherwise. */ double vpRowVector::euclideanNorm() const { double norm = 0.0; for (unsigned int i = 0; i < dsize; i++) { double x = *(data + i); norm += x * x; } return sqrt(norm); } /*! Initialize the row vector from a part of an input row vector \e v. \param v : Input row vector used for initialization. \param c : column index in \e v that corresponds to the first element of the row vector to contruct. \param ncols : Number of columns of the constructed row vector. The sub-vector starting from v[c] element and ending on v[c+ncols-1] element is used to initialize the contructed row vector. The following code shows how to use this function: \code #include <visp3/core/vpRowVector.h> int main() { vpRowVector v(4); int val = 0; for(size_t i=0; i<v.getCols(); i++) { v[i] = val++; } std::cout << "v: " << v << std::endl; vpRowVector w; w.init(v, 1, 2); std::cout << "w: " << w << std::endl; } \endcode It produces the following output: \code v: 0 1 2 3 w: 1 2 \endcode */ void vpRowVector::init(const vpRowVector &v, unsigned int c, unsigned int ncols) { unsigned int cncols = c + ncols; if (cncols > v.getCols()) throw(vpException(vpException::dimensionError, "Bad column dimension (%d > %d) used to initialize vpRowVector", cncols, v.getCols())); resize(ncols); if (this->rowPtrs == NULL) // Fix coverity scan: explicit null dereferenced return; // Noting to do for (unsigned int i = 0; i < ncols; i++) (*this)[i] = v[i + c]; } /*! Print to be used as part of a C++ code later. \param os : the stream to be printed in. \param matrixName : name of the row vector, "A" by default. \param octet : if false, print using double, if true, print byte per byte each bytes of the double array. The following code shows how to use this function: \code #include <visp3/core/vpRowVector.h> int main() { vpRowVector r(3); for (unsigned int i=0; i<r.size(); i++) r[i] = i; r.cppPrint(std::cout, "r"); } \endcode It produces the following output that could be copy/paste in a C++ code: \code vpRowVector r (3); r[0] = 0; r[1] = 1; r[2] = 2; \endcode */ std::ostream &vpRowVector::cppPrint(std::ostream &os, const std::string &matrixName, bool octet) const { os << "vpRowVector " << matrixName << " (" << this->getCols() << "); " << std::endl; for (unsigned int j = 0; j < this->getCols(); ++j) { if (!octet) { os << matrixName << "[" << j << "] = " << (*this)[j] << "; " << std::endl; } else { for (unsigned int k = 0; k < sizeof(double); ++k) { os << "((unsigned char*)&(" << matrixName << "[" << j << "]) )[" << k << "] = 0x" << std::hex << (unsigned int)((unsigned char *)&((*this)[j]))[k] << "; " << std::endl; } } } std::cout << std::endl; return os; } /*! Print/save a row vector in csv format. The following code \code #include <visp3/core/vpRowVector.h> int main() { std::ofstream ofs("log.csv", std::ofstream::out); vpRowVector r(3); for (unsigned int i=0; i<r.size(); i++) r[i] = i; r.csvPrint(ofs); ofs.close(); } \endcode produces log.csv file that contains: \code 0, 1, 2 \endcode */ std::ostream &vpRowVector::csvPrint(std::ostream &os) const { for (unsigned int j = 0; j < this->getCols(); ++j) { os << (*this)[j]; if (!(j == (this->getCols() - 1))) os << ", "; } os << std::endl; return os; } /*! Print using Maple syntax, to copy/paste in Maple later. The following code \code #include <visp3/core/vpRowVector.h> int main() { vpRowVector r(3); for (unsigned int i=0; i<r.size(); i++) r[i] = i; std::cout << "r = "; r.maplePrint(std::cout); } \endcode produces this output: \code r = ([ [0, 1, 2, ], ]) \endcode that could be copy/paste in Maple. */ std::ostream &vpRowVector::maplePrint(std::ostream &os) const { os << "([ " << std::endl; os << "["; for (unsigned int j = 0; j < this->getCols(); ++j) { os << (*this)[j] << ", "; } os << "]," << std::endl; os << "])" << std::endl; return os; } /*! Print using Matlab syntax, to copy/paste in Matlab later. The following code \code #include <visp3/core/vpRowVector.h> int main() { vpRowVector r(3); for (unsigned int i=0; i<r.size(); i++) r[i] = i; std::cout << "r = "; r.matlabPrint(std::cout); } \endcode produces this output: \code r = [ 0, 1, 2, ] \endcode that could be copy/paste in Matlab: \code >> r = [ 0, 1, 2, ] r = 0 1 2 >> \endcode */ std::ostream &vpRowVector::matlabPrint(std::ostream &os) const { os << "[ "; for (unsigned int j = 0; j < this->getCols(); ++j) { os << (*this)[j] << ", "; } os << "]" << std::endl; return os; }
s-trinh/visp
modules/core/src/math/matrix/vpRowVector.cpp
C++
gpl-2.0
28,813
/* * Copyright 1997-2007 Sun Microsystems, Inc. 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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package java.util; /** * This class provides a skeletal implementation of the {@link List} * interface to minimize the effort required to implement this interface * backed by a "random access" data store (such as an array). For sequential * access data (such as a linked list), {@link AbstractSequentialList} should * be used in preference to this class. * * <p>To implement an unmodifiable list, the programmer needs only to extend * this class and provide implementations for the {@link #get(int)} and * {@link List#size() size()} methods. * * <p>To implement a modifiable list, the programmer must additionally * override the {@link #set(int, Object) set(int, E)} method (which otherwise * throws an {@code UnsupportedOperationException}). If the list is * variable-size the programmer must additionally override the * {@link #add(int, Object) add(int, E)} and {@link #remove(int)} methods. * * <p>The programmer should generally provide a void (no argument) and collection * constructor, as per the recommendation in the {@link Collection} interface * specification. * * <p>Unlike the other abstract collection implementations, the programmer does * <i>not</i> have to provide an iterator implementation; the iterator and * list iterator are implemented by this class, on top of the "random access" * methods: * {@link #get(int)}, * {@link #set(int, Object) set(int, E)}, * {@link #add(int, Object) add(int, E)} and * {@link #remove(int)}. * * <p>The documentation for each non-abstract method in this class describes its * implementation in detail. Each of these methods may be overridden if the * collection being implemented admits a more efficient implementation. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @author Josh Bloch * @author Neal Gafter * @since 1.2 */ public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected AbstractList() { } /** * Appends the specified element to the end of this list (optional * operation). * * <p>Lists that support this operation may place limitations on what * elements may be added to this list. In particular, some * lists will refuse to add null elements, and others will impose * restrictions on the type of elements that may be added. List * classes should clearly specify in their documentation any restrictions * on what elements may be added. * * <p>This implementation calls {@code add(size(), e)}. * * <p>Note that this implementation throws an * {@code UnsupportedOperationException} unless * {@link #add(int, Object) add(int, E)} is overridden. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) * @throws UnsupportedOperationException if the {@code add} operation * is not supported by this list * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws NullPointerException if the specified element is null and this * list does not permit null elements * @throws IllegalArgumentException if some property of this element * prevents it from being added to this list */ public boolean add(E e) { add(size(), e); return true; } /** * {@inheritDoc} * * @throws IndexOutOfBoundsException {@inheritDoc} */ abstract public E get(int index); /** * {@inheritDoc} * * <p>This implementation always throws an * {@code UnsupportedOperationException}. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} * * <p>This implementation always throws an * {@code UnsupportedOperationException}. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} * * <p>This implementation always throws an * {@code UnsupportedOperationException}. * * @throws UnsupportedOperationException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { throw new UnsupportedOperationException(); } // Search Operations /** * {@inheritDoc} * * <p>This implementation first gets a list iterator (with * {@code listIterator()}). Then, it iterates over the list until the * specified element is found or the end of the list is reached. * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public int indexOf(Object o) { ListIterator<E> e = listIterator(); if (o==null) { while (e.hasNext()) if (e.next()==null) return e.previousIndex(); } else { while (e.hasNext()) if (o.equals(e.next())) return e.previousIndex(); } return -1; } /** * {@inheritDoc} * * <p>This implementation first gets a list iterator that points to the end * of the list (with {@code listIterator(size())}). Then, it iterates * backwards over the list until the specified element is found, or the * beginning of the list is reached. * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public int lastIndexOf(Object o) { ListIterator<E> e = listIterator(size()); if (o==null) { while (e.hasPrevious()) if (e.previous()==null) return e.nextIndex(); } else { while (e.hasPrevious()) if (o.equals(e.previous())) return e.nextIndex(); } return -1; } // Bulk Operations /** * Removes all of the elements from this list (optional operation). * The list will be empty after this call returns. * * <p>This implementation calls {@code removeRange(0, size())}. * * <p>Note that this implementation throws an * {@code UnsupportedOperationException} unless {@code remove(int * index)} or {@code removeRange(int fromIndex, int toIndex)} is * overridden. * * @throws UnsupportedOperationException if the {@code clear} operation * is not supported by this list */ public void clear() { removeRange(0, size()); } /** * {@inheritDoc} * * <p>This implementation gets an iterator over the specified collection * and iterates over it, inserting the elements obtained from the * iterator into this list at the appropriate position, one at a time, * using {@code add(int, E)}. * Many implementations will override this method for efficiency. * * <p>Note that this implementation throws an * {@code UnsupportedOperationException} unless * {@link #add(int, Object) add(int, E)} is overridden. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); boolean modified = false; Iterator<? extends E> e = c.iterator(); while (e.hasNext()) { add(index++, e.next()); modified = true; } return modified; } // Iterators /** * Returns an iterator over the elements in this list in proper sequence. * * <p>This implementation returns a straightforward implementation of the * iterator interface, relying on the backing list's {@code size()}, * {@code get(int)}, and {@code remove(int)} methods. * * <p>Note that the iterator returned by this method will throw an * {@link UnsupportedOperationException} in response to its * {@code remove} method unless the list's {@code remove(int)} method is * overridden. * * <p>This implementation can be made to throw runtime exceptions in the * face of concurrent modification, as described in the specification * for the (protected) {@link #modCount} field. * * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { return new Itr(); } /** * {@inheritDoc} * * <p>This implementation returns {@code listIterator(0)}. * * @see #listIterator(int) */ public ListIterator<E> listIterator() { return listIterator(0); } /** * {@inheritDoc} * * <p>This implementation returns a straightforward implementation of the * {@code ListIterator} interface that extends the implementation of the * {@code Iterator} interface returned by the {@code iterator()} method. * The {@code ListIterator} implementation relies on the backing list's * {@code get(int)}, {@code set(int, E)}, {@code add(int, E)} * and {@code remove(int)} methods. * * <p>Note that the list iterator returned by this implementation will * throw an {@link UnsupportedOperationException} in response to its * {@code remove}, {@code set} and {@code add} methods unless the * list's {@code remove(int)}, {@code set(int, E)}, and * {@code add(int, E)} methods are overridden. * * <p>This implementation can be made to throw runtime exceptions in the * face of concurrent modification, as described in the specification for * the (protected) {@link #modCount} field. * * @throws IndexOutOfBoundsException {@inheritDoc} */ public ListIterator<E> listIterator(final int index) { rangeCheckForAdd(index); return new ListItr(index); } private class Itr implements Iterator<E> { /** * Index of element to be returned by subsequent call to next. */ int cursor = 0; /** * Index of element returned by most recent call to next or * previous. Reset to -1 if this element is deleted by a call * to remove. */ int lastRet = -1; /** * The modCount value that the iterator believes that the backing * List should have. If this expectation is violated, the iterator * has detected concurrent modification. */ int expectedModCount = modCount; public boolean hasNext() { return cursor != size(); } public E next() { checkForComodification(); try { int i = cursor; E next = get(i); lastRet = i; cursor = i + 1; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { cursor = index; } public boolean hasPrevious() { return cursor != 0; } public E previous() { checkForComodification(); try { int i = cursor - 1; E previous = get(i); lastRet = cursor = i; return previous; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public int nextIndex() { return cursor; } public int previousIndex() { return cursor-1; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.set(lastRet, e); expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; AbstractList.this.add(i, e); lastRet = -1; cursor = i + 1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } /** * {@inheritDoc} * * <p>This implementation returns a list that subclasses * {@code AbstractList}. The subclass stores, in private fields, the * offset of the subList within the backing list, the size of the subList * (which can change over its lifetime), and the expected * {@code modCount} value of the backing list. There are two variants * of the subclass, one of which implements {@code RandomAccess}. * If this list implements {@code RandomAccess} the returned list will * be an instance of the subclass that implements {@code RandomAccess}. * * <p>The subclass's {@code set(int, E)}, {@code get(int)}, * {@code add(int, E)}, {@code remove(int)}, {@code addAll(int, * Collection)} and {@code removeRange(int, int)} methods all * delegate to the corresponding methods on the backing abstract list, * after bounds-checking the index and adjusting for the offset. The * {@code addAll(Collection c)} method merely returns {@code addAll(size, * c)}. * * <p>The {@code listIterator(int)} method returns a "wrapper object" * over a list iterator on the backing list, which is created with the * corresponding method on the backing list. The {@code iterator} method * merely returns {@code listIterator()}, and the {@code size} method * merely returns the subclass's {@code size} field. * * <p>All methods first check to see if the actual {@code modCount} of * the backing list is equal to its expected value, and throw a * {@code ConcurrentModificationException} if it is not. * * @throws IndexOutOfBoundsException if an endpoint index value is out of range * {@code (fromIndex < 0 || toIndex > size)} * @throws IllegalArgumentException if the endpoint indices are out of order * {@code (fromIndex > toIndex)} */ public List<E> subList(int fromIndex, int toIndex) { return (this instanceof RandomAccess ? new RandomAccessSubList<E>(this, fromIndex, toIndex) : new SubList<E>(this, fromIndex, toIndex)); } // Comparison and hashing /** * Compares the specified object with this list for equality. Returns * {@code true} if and only if the specified object is also a list, both * lists have the same size, and all corresponding pairs of elements in * the two lists are <i>equal</i>. (Two elements {@code e1} and * {@code e2} are <i>equal</i> if {@code (e1==null ? e2==null : * e1.equals(e2))}.) In other words, two lists are defined to be * equal if they contain the same elements in the same order.<p> * * This implementation first checks if the specified object is this * list. If so, it returns {@code true}; if not, it checks if the * specified object is a list. If not, it returns {@code false}; if so, * it iterates over both lists, comparing corresponding pairs of elements. * If any comparison returns {@code false}, this method returns * {@code false}. If either iterator runs out of elements before the * other it returns {@code false} (as the lists are of unequal length); * otherwise it returns {@code true} when the iterations complete. * * @param o the object to be compared for equality with this list * @return {@code true} if the specified object is equal to this list */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof List)) return false; ListIterator<E> e1 = listIterator(); ListIterator e2 = ((List) o).listIterator(); while(e1.hasNext() && e2.hasNext()) { E o1 = e1.next(); Object o2 = e2.next(); if (!(o1==null ? o2==null : o1.equals(o2))) return false; } return !(e1.hasNext() || e2.hasNext()); } /** * Returns the hash code value for this list. * * <p>This implementation uses exactly the code that is used to define the * list hash function in the documentation for the {@link List#hashCode} * method. * * @return the hash code value for this list */ public int hashCode() { int hashCode = 1; for (E e : this) hashCode = 31*hashCode + (e==null ? 0 : e.hashCode()); return hashCode; } /** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by {@code (toIndex - fromIndex)} elements. * (If {@code toIndex==fromIndex}, this operation has no effect.) * * <p>This method is called by the {@code clear} operation on this list * and its subLists. Overriding this method to take advantage of * the internals of the list implementation can <i>substantially</i> * improve the performance of the {@code clear} operation on this list * and its subLists. * * <p>This implementation gets a list iterator positioned before * {@code fromIndex}, and repeatedly calls {@code ListIterator.next} * followed by {@code ListIterator.remove} until the entire range has * been removed. <b>Note: if {@code ListIterator.remove} requires linear * time, this implementation requires quadratic time.</b> * * @param fromIndex index of first element to be removed * @param toIndex index after last element to be removed */ protected void removeRange(int fromIndex, int toIndex) { ListIterator<E> it = listIterator(fromIndex); for (int i=0, n=toIndex-fromIndex; i<n; i++) { it.next(); it.remove(); } } /** * The number of times this list has been <i>structurally modified</i>. * Structural modifications are those that change the size of the * list, or otherwise perturb it in such a fashion that iterations in * progress may yield incorrect results. * * <p>This field is used by the iterator and list iterator implementation * returned by the {@code iterator} and {@code listIterator} methods. * If the value of this field changes unexpectedly, the iterator (or list * iterator) will throw a {@code ConcurrentModificationException} in * response to the {@code next}, {@code remove}, {@code previous}, * {@code set} or {@code add} operations. This provides * <i>fail-fast</i> behavior, rather than non-deterministic behavior in * the face of concurrent modification during iteration. * * <p><b>Use of this field by subclasses is optional.</b> If a subclass * wishes to provide fail-fast iterators (and list iterators), then it * merely has to increment this field in its {@code add(int, E)} and * {@code remove(int)} methods (and any other methods that it overrides * that result in structural modifications to the list). A single call to * {@code add(int, E)} or {@code remove(int)} must add no more than * one to this field, or the iterators (and list iterators) will throw * bogus {@code ConcurrentModificationExceptions}. If an implementation * does not wish to provide fail-fast iterators, this field may be * ignored. */ protected transient int modCount = 0; private void rangeCheckForAdd(int index) { if (index < 0 || index > size()) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size(); } } class SubList<E> extends AbstractList<E> { private final AbstractList<E> l; private final int offset; private int size; SubList(AbstractList<E> list, int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > list.size()) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); l = list; offset = fromIndex; size = toIndex - fromIndex; this.modCount = l.modCount; } public E set(int index, E element) { rangeCheck(index); checkForComodification(); return l.set(index+offset, element); } public E get(int index) { rangeCheck(index); checkForComodification(); return l.get(index+offset); } public int size() { checkForComodification(); return size; } public void add(int index, E element) { rangeCheckForAdd(index); checkForComodification(); l.add(index+offset, element); this.modCount = l.modCount; size++; } public E remove(int index) { rangeCheck(index); checkForComodification(); E result = l.remove(index+offset); this.modCount = l.modCount; size--; return result; } protected void removeRange(int fromIndex, int toIndex) { checkForComodification(); l.removeRange(fromIndex+offset, toIndex+offset); this.modCount = l.modCount; size -= (toIndex-fromIndex); } public boolean addAll(Collection<? extends E> c) { return addAll(size, c); } public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); int cSize = c.size(); if (cSize==0) return false; checkForComodification(); l.addAll(offset+index, c); this.modCount = l.modCount; size += cSize; return true; } public Iterator<E> iterator() { return listIterator(); } public ListIterator<E> listIterator(final int index) { checkForComodification(); rangeCheckForAdd(index); return new ListIterator<E>() { private final ListIterator<E> i = l.listIterator(index+offset); public boolean hasNext() { return nextIndex() < size; } public E next() { if (hasNext()) return i.next(); else throw new NoSuchElementException(); } public boolean hasPrevious() { return previousIndex() >= 0; } public E previous() { if (hasPrevious()) return i.previous(); else throw new NoSuchElementException(); } public int nextIndex() { return i.nextIndex() - offset; } public int previousIndex() { return i.previousIndex() - offset; } public void remove() { i.remove(); SubList.this.modCount = l.modCount; size--; } public void set(E e) { i.set(e); } public void add(E e) { i.add(e); SubList.this.modCount = l.modCount; size++; } }; } public List<E> subList(int fromIndex, int toIndex) { return new SubList<E>(this, fromIndex, toIndex); } private void rangeCheck(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void rangeCheckForAdd(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } private void checkForComodification() { if (this.modCount != l.modCount) throw new ConcurrentModificationException(); } } class RandomAccessSubList<E> extends SubList<E> implements RandomAccess { RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) { super(list, fromIndex, toIndex); } public List<E> subList(int fromIndex, int toIndex) { return new RandomAccessSubList<E>(this, fromIndex, toIndex); } }
neelance/jre4ruby
jre4ruby/src/share/java/util/AbstractList.java
Java
gpl-2.0
28,015
////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // // copyright : (C) 2008 by Eran Ifrah // file name : editorsettingsmiscpanel.cpp // // ------------------------------------------------------------------------- // A // _____ _ _ _ _ // / __ \ | | | | (_) | // | / \/ ___ __| | ___| | _| |_ ___ // | | / _ \ / _ |/ _ \ | | | __/ _ ) // | \__/\ (_) | (_| | __/ |___| | || __/ // \____/\___/ \__,_|\___\_____/_|\__\___| // // F i l e // // 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. // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #include "editorsettingsmiscpanel.h" #include "generalinfo.h" #include "frame.h" #include "manager.h" #include "pluginmanager.h" #include "file_logger.h" #include "wx/wxprec.h" #include <wx/intl.h> #include <wx/fontmap.h> #include "ctags_manager.h" #include "globals.h" #include "cl_config.h" #ifdef __WXMSW__ #include <wx/msw/uxtheme.h> #endif EditorSettingsMiscPanel::EditorSettingsMiscPanel(wxWindow* parent) : EditorSettingsMiscBasePanel(parent) , TreeBookNode<EditorSettingsMiscPanel>() , m_restartRequired(false) { GeneralInfo info = clMainFrame::Get()->GetFrameGeneralInfo(); OptionsConfigPtr options = EditorConfigST::Get()->GetOptions(); if(options->GetIconsSize() == 16) { m_toolbarIconSize->SetSelection(0); } else { m_toolbarIconSize->SetSelection(1); } if(options->GetOptions() & OptionsConfig::Opt_IconSet_FreshFarm) m_choiceIconSet->SetSelection(1); else if(options->GetOptions() & OptionsConfig::Opt_IconSet_Classic_Dark) m_choiceIconSet->SetSelection(2); else m_choiceIconSet->SetSelection(0); // Default m_checkBoxEnableMSWTheme->SetValue(options->GetMswTheme()); m_useSingleToolbar->SetValue(!PluginManager::Get()->AllowToolbar()); m_oldSetLocale = options->GetUseLocale(); m_SetLocale->SetValue(m_oldSetLocale); m_oldpreferredLocale = options->GetPreferredLocale(); // Load the available locales and feed them to the wxchoice int select = FindAvailableLocales(); if(select != wxNOT_FOUND) { m_AvailableLocales->SetSelection(select); } wxArrayString astrEncodings; wxFontEncoding fontEnc; int iCurrSelId = 0; size_t iEncCnt = wxFontMapper::GetSupportedEncodingsCount(); for(size_t i = 0; i < iEncCnt; i++) { fontEnc = wxFontMapper::GetEncoding(i); if(wxFONTENCODING_SYSTEM == fontEnc) { // skip system, it is changed to UTF-8 in optionsconfig continue; } astrEncodings.Add(wxFontMapper::GetEncodingName(fontEnc)); if(fontEnc == options->GetFileFontEncoding()) { iCurrSelId = i; } } m_fileEncoding->Append(astrEncodings); m_fileEncoding->SetSelection(iCurrSelId); m_singleAppInstance->SetValue(clConfig::Get().Read(kConfigSingleInstance, false)); m_versionCheckOnStartup->SetValue(clConfig::Get().Read(kConfigCheckForNewVersion, true)); m_maxItemsFindReplace->ChangeValue(::wxIntToString(clConfig::Get().Read(kConfigMaxItemsInFindReplaceDialog, 15))); m_spinCtrlMaxOpenTabs->ChangeValue(::wxIntToString(clConfig::Get().Read(kConfigMaxOpenedTabs, 15))); m_choice4->SetStringSelection( FileLogger::GetVerbosityAsString(clConfig::Get().Read(kConfigLogVerbosity, FileLogger::Error))); m_checkBoxRestoreSession->SetValue(clConfig::Get().Read(kConfigRestoreLastSession, true)); m_textCtrlPattern->ChangeValue(clConfig::Get().Read(kConfigFrameTitlePattern, wxString("$workspace $fullpath"))); m_statusbarShowLine->SetValue(clConfig::Get().Read(kConfigStatusbarShowLine, true)); m_statusbarShowCol->SetValue(clConfig::Get().Read(kConfigStatusbarShowColumn, true)); m_statusbarShowPos->SetValue(clConfig::Get().Read(kConfigStatusbarShowPosition, false)); m_statusbarShowFileLength->SetValue(clConfig::Get().Read(kConfigStatusbarShowLength, false)); bool showSplash = info.GetFlags() & CL_SHOW_SPLASH ? true : false; m_showSplashScreen->SetValue(showSplash); m_oldMswUseTheme = m_checkBoxEnableMSWTheme->IsChecked(); m_redirectLogOutput->SetValue(clConfig::Get().Read(kConfigRedirectLogOutput, true)); m_checkBoxPromptReleaseOnly->SetValue(clConfig::Get().Read("PromptForNewReleaseOnly", false)); } void EditorSettingsMiscPanel::OnClearButtonClick(wxCommandEvent&) { ManagerST::Get()->ClearWorkspaceHistory(); clMainFrame::Get()->GetMainBook()->ClearFileHistory(); } void EditorSettingsMiscPanel::Save(OptionsConfigPtr options) { if(m_showSplashScreen->IsChecked()) { clMainFrame::Get()->SetFrameFlag(true, CL_SHOW_SPLASH); } else { clMainFrame::Get()->SetFrameFlag(false, CL_SHOW_SPLASH); } // Set the theme support. // This option requires a restart of codelite options->SetMswTheme(m_checkBoxEnableMSWTheme->IsChecked()); if(m_oldMswUseTheme != m_checkBoxEnableMSWTheme->IsChecked()) { m_restartRequired = true; } clConfig::Get().Write(kConfigSingleInstance, m_singleAppInstance->IsChecked()); clConfig::Get().Write(kConfigCheckForNewVersion, m_versionCheckOnStartup->IsChecked()); clConfig::Get().Write(kConfigMaxItemsInFindReplaceDialog, ::wxStringToInt(m_maxItemsFindReplace->GetValue(), 15)); clConfig::Get().Write(kConfigMaxOpenedTabs, ::wxStringToInt(m_spinCtrlMaxOpenTabs->GetValue(), 15)); clConfig::Get().Write(kConfigRestoreLastSession, m_checkBoxRestoreSession->IsChecked()); clConfig::Get().Write(kConfigFrameTitlePattern, m_textCtrlPattern->GetValue()); clConfig::Get().Write(kConfigStatusbarShowLine, m_statusbarShowLine->IsChecked()); clConfig::Get().Write(kConfigStatusbarShowColumn, m_statusbarShowCol->IsChecked()); clConfig::Get().Write(kConfigStatusbarShowPosition, m_statusbarShowPos->IsChecked()); clConfig::Get().Write(kConfigStatusbarShowLength, m_statusbarShowFileLength->IsChecked()); bool oldUseSingleToolbar = !PluginManager::Get()->AllowToolbar(); EditorConfigST::Get()->SetInteger(wxT("UseSingleToolbar"), m_useSingleToolbar->IsChecked() ? 1 : 0); // check to see of the icon size was modified int oldIconSize(24); OptionsConfigPtr oldOptions = EditorConfigST::Get()->GetOptions(); if(oldOptions) { oldIconSize = oldOptions->GetIconsSize(); } int iconSize(24); if(m_toolbarIconSize->GetSelection() == 0) { iconSize = 16; } options->SetIconsSize(iconSize); bool setlocale = m_SetLocale->IsChecked(); options->SetUseLocale(setlocale); wxString newLocaleString = m_AvailableLocales->GetStringSelection(); // I don't think we should check if newLocaleString is empty; that's still useful information newLocaleString = newLocaleString.BeforeFirst(wxT(':')); // Store it as "fr_FR", not "fr_FR: French" options->SetPreferredLocale(newLocaleString); if((setlocale != m_oldSetLocale) || (newLocaleString != m_oldpreferredLocale)) { m_restartRequired = true; } // save file font encoding options->SetFileFontEncoding(m_fileEncoding->GetStringSelection()); TagsManagerST::Get()->SetEncoding(options->GetFileFontEncoding()); if(oldIconSize != iconSize || oldUseSingleToolbar != m_useSingleToolbar->IsChecked()) { EditorConfigST::Get()->SetInteger(wxT("LoadSavedPrespective"), 0); // notify the user m_restartRequired = true; } else { EditorConfigST::Get()->SetInteger(wxT("LoadSavedPrespective"), 1); } size_t flags = options->GetOptions(); size_t oldFlags = oldOptions->GetOptions(); // Keep the old icon-set flags, this is done for deciding whether we should // prompt the user for possible restart size_t oldIconFlags(0); size_t newIconFlags(0); if(oldFlags & OptionsConfig::Opt_IconSet_Classic) oldIconFlags |= OptionsConfig::Opt_IconSet_Classic; if(oldFlags & OptionsConfig::Opt_IconSet_FreshFarm) oldIconFlags |= OptionsConfig::Opt_IconSet_FreshFarm; if(oldFlags & OptionsConfig::Opt_IconSet_Classic_Dark) oldIconFlags |= OptionsConfig::Opt_IconSet_Classic_Dark; if(oldIconFlags == 0) oldIconFlags = OptionsConfig::Opt_IconSet_Classic; // Clear old settings flags &= ~(OptionsConfig::Opt_IconSet_Classic); flags &= ~(OptionsConfig::Opt_IconSet_FreshFarm); flags &= ~(OptionsConfig::Opt_IconSet_Classic_Dark); if(m_choiceIconSet->GetSelection() == 0) { newIconFlags |= OptionsConfig::Opt_IconSet_Classic; flags |= OptionsConfig::Opt_IconSet_Classic; } else if(m_choiceIconSet->GetSelection() == 2) { newIconFlags |= OptionsConfig::Opt_IconSet_Classic_Dark; flags |= OptionsConfig::Opt_IconSet_Classic_Dark; } else { // 1 newIconFlags |= OptionsConfig::Opt_IconSet_FreshFarm; flags |= OptionsConfig::Opt_IconSet_FreshFarm; } clConfig::Get().Write("RedirectLogOutput", m_redirectLogOutput->IsChecked()); clConfig::Get().Write("PromptForNewReleaseOnly", m_checkBoxPromptReleaseOnly->IsChecked()); options->SetOptions(flags); m_restartRequired = ((oldIconFlags != newIconFlags) || m_restartRequired); } void EditorSettingsMiscPanel::OnClearUI(wxUpdateUIEvent& e) { wxArrayString a1, a2; clMainFrame::Get()->GetMainBook()->GetRecentlyOpenedFiles(a1); ManagerST::Get()->GetRecentlyOpenedWorkspaces(a2); e.Enable(!a1.IsEmpty() && !a2.IsEmpty()); } void EditorSettingsMiscPanel::OnEnableThemeUI(wxUpdateUIEvent& event) { #ifdef __WXMSW__ int major, minor; wxGetOsVersion(&major, &minor); if(wxUxThemeEngine::GetIfActive() && major >= 6 /* Win 7 and up */) { event.Enable(true); } else { event.Enable(false); } #else event.Enable(false); #endif } void EditorSettingsMiscPanel::LocaleChkUpdateUI(wxUpdateUIEvent& event) { event.Enable(m_AvailableLocales->GetCount() > 0); } void EditorSettingsMiscPanel::LocaleChoiceUpdateUI(wxUpdateUIEvent& event) { event.Enable(m_SetLocale->IsChecked()); } void EditorSettingsMiscPanel::LocaleStaticUpdateUI(wxUpdateUIEvent& event) { event.Enable(m_SetLocale->IsChecked()); } int EditorSettingsMiscPanel::FindAvailableLocales() { wxArrayString canonicalNames; int select(wxNOT_FOUND), sysdefault_sel(wxNOT_FOUND); m_AvailableLocales->Clear(); int system_lang = wxLocale::GetSystemLanguage(); if(system_lang == wxLANGUAGE_UNKNOWN) { // Least-stupid fallback value system_lang = wxLANGUAGE_ENGLISH_US; } for(int n = 0, lang = wxLANGUAGE_UNKNOWN + 1; lang < wxLANGUAGE_USER_DEFINED; ++lang) { const wxLanguageInfo* info = wxLocale::GetLanguageInfo(lang); // Check there *is* a Canonical name, as empty strings return a valid locale :/ if((info && !info->CanonicalName.IsEmpty()) && wxLocale::IsAvailable(lang)) { // Check we haven't already seen this item: we may find the system default twice if(canonicalNames.Index(info->CanonicalName) == wxNOT_FOUND) { // Display the name as e.g. "en_GB: English (U.K.)" m_AvailableLocales->Append(info->CanonicalName + wxT(": ") + info->Description); canonicalNames.Add(info->CanonicalName); if(info->CanonicalName == m_oldpreferredLocale) { // Use this as the selection in the wxChoice select = n; } if(lang == system_lang) { // Use this as the selection if m_oldpreferredLocale isn't found sysdefault_sel = n; } ++n; } } } return (select != wxNOT_FOUND) ? select : sysdefault_sel; } void EditorSettingsMiscPanel::OnLogVerbosityChanged(wxCommandEvent& event) { FileLogger::SetVerbosity(event.GetString()); clConfig::Get().Write("LogVerbosity", FileLogger::GetVerbosityAsNumber(m_choice4->GetStringSelection())); } void EditorSettingsMiscPanel::OnShowLogFile(wxCommandEvent& event) { wxUnusedVar(event); wxString logfile; logfile << clStandardPaths::Get().GetUserDataDir() << wxFileName::GetPathSeparator() << wxT("codelite.log"); clMainFrame::Get()->GetMainBook()->OpenFile(logfile); } void EditorSettingsMiscPanel::OnLogoutputCheckUpdateUI(wxUpdateUIEvent& event) { #ifdef __WXGTK__ event.Enable(true); #else m_redirectLogOutput->SetValue(false); event.Enable(false); #endif } void EditorSettingsMiscPanel::OnResetAnnoyingDialogsAnswers(wxCommandEvent& event) { wxUnusedVar(event); clConfig::Get().ClearAnnoyingDlgAnswers(); } void EditorSettingsMiscPanel::OnPromptStableReleaseUI(wxUpdateUIEvent& event) { event.Enable(m_versionCheckOnStartup->IsChecked()); }
StefanoBelloni/codelite
LiteEditor/editorsettingsmiscpanel.cpp
C++
gpl-2.0
13,648
<?php /*----------------------------------------------------------------------------------- Below we have all of the custom functions for the theme Please be extremely cautious editing this file! -----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/ /* Global theme variables /*-----------------------------------------------------------------------------------*/ $theme = wp_get_theme(); $themename = $theme->Name; $shortname = "t2t"; // Customizer require_once(get_template_directory() . '/includes/customizer.php'); // Plugin activation require_once(get_template_directory() . '/includes/plugins.php'); // Shortcode filters and extensions require_once(get_template_directory() . '/includes/shortcodes.php'); // Widget filters and extensions require_once(get_template_directory() . '/includes/widgets.php'); // Metabox filters and extensions require_once(get_template_directory() . '/includes/meta_boxes.php'); // Theme colors require_once(get_template_directory() . '/stylesheets/theme_colors.php'); /** * meta boxes * */ foreach(scandir(get_template_directory() . "/includes/page_template_options") as $filename) { $path = get_template_directory() . '/includes/page_template_options/' . $filename; if(is_file($path) && preg_match("/template-[a-z_-]+.php/", $filename)) { require_once($path); } } /*-----------------------------------------------------------------------------------*/ /* Add Localization Support /*-----------------------------------------------------------------------------------*/ load_theme_textdomain('framework', get_template_directory() . '/languages'); /*-----------------------------------------------------------------------------------*/ /* Set Max Content Width /*-----------------------------------------------------------------------------------*/ if(!isset($content_width)) { $content_width = 940; } add_theme_support('automatic-feed-links'); function t2t_layout_style($classes) { $current_layout = array(); // If homepage template if(is_page_template("template-home.php")) { $classes[] = "homepage"; } // Set animation style if(get_theme_mod("t2t_customizer_animation_style")) { $classes[] = "animate-".get_theme_mod("t2t_customizer_animation_style", "flip"); } else { $classes[] = "animate-flip"; } // Set theme color if(get_theme_mod("t2t_customizer_theme_color")) { $classes[] = "theme-".get_theme_mod("t2t_customizer_theme_color", "flip"); } else { $classes[] = "theme-light"; } // Set header style if(get_theme_mod("t2t_customizer_header_style") == "centered") { $classes[] = "header-centered"; } return $classes; } add_filter('body_class','t2t_layout_style'); function t2t_header_layout() { $classes = array(); if(get_theme_mod("t2t_customizer_header_style") == "centered") { $classes[] = "centered"; } return join(" ", $classes); } /*-----------------------------------------------------------------------------------*/ /* WooCommerce support /*-----------------------------------------------------------------------------------*/ add_theme_support('woocommerce'); /*-----------------------------------------------------------------------------------*/ /* Register Sidebars /*-----------------------------------------------------------------------------------*/ if(function_exists('register_sidebar')) { register_sidebar(array( "id" => "blog-sidebar", "name" => __("Blog", "framework"), "description" => __("Appears on the blog template.", "framework"), "before_widget" => '<div id="%1$s" class="widget %2$s">', "after_widget" => "</div>", "before_title" => "<h5>", "after_title" => "</h5>" )); register_sidebar(array( "id" => "page-sidebar", "name" => __("Page", "framework"), "description" => __("Appears on page templates.", "framework"), "before_widget" => '<div id="%1$s" class="widget %2$s">', "after_widget" => "</div>", "before_title" => "<h5>", "after_title" => "</h5>" )); register_sidebar(array( "id" => "footer-widget-1", "name" => __("Footer Widget 1", "framework"), "description" => __("Appears in the footer area.", "framework"), "before_widget" => '<div id="%1$s" class="widget %2$s">', "after_widget" => "</div>", "before_title" => "<h5 class=\"widget-title\">", "after_title" => "</h5>" )); register_sidebar(array( "id" => "footer-widget-2", "name" => __("Footer Widget 2", "framework"), "description" => __("Appears in the footer area.", "framework"), "before_widget" => '<div id="%1$s" class="widget %2$s">', "after_widget" => "</div>", "before_title" => "<h5 class=\"widget-title\">", "after_title" => "</h5>" )); register_sidebar(array( "id" => "footer-widget-3", "name" => __("Footer Widget 3", "framework"), "description" => __("Appears in the footer area.", "framework"), "before_widget" => '<div id="%1$s" class="widget %2$s">', "after_widget" => "</div>", "before_title" => "<h5 class=\"widget-title\">", "after_title" => "</h5>" )); register_sidebar(array( "id" => "footer-widget-4", "name" => __("Footer Widget 4", "framework"), "description" => __("Appears in the footer area.", "framework"), "before_widget" => '<div id="%1$s" class="widget %2$s">', "after_widget" => "</div>", "before_title" => "<h5 class=\"widget-title\">", "after_title" => "</h5>" )); } /*-----------------------------------------------------------------------------------*/ /* Google typography settings /*-----------------------------------------------------------------------------------*/ if(function_exists('register_typography')) { register_typography(array( 'logo' => array( 'preview_text' => 'Website Name', 'preview_color' => 'light', 'font_family' => 'Exo', 'font_variant' => 'normal', 'font_size' => '40px', 'font_color' => '#444444', 'css_selectors' => 'header .logo' ), 'slider_titles' => array( 'preview_text' => 'Slider Titles', 'preview_color' => 'light', 'font_family' => 'Open Sans', 'font_variant' => '300', 'font_size' => '45px', 'font_color' => '#555555', 'css_selectors' => '.slide-content .title' ), 'slider_captions' => array( 'preview_text' => 'Slider Captions', 'preview_color' => 'light', 'font_family' => 'Open Sans', 'font_variant' => '300', 'font_size' => '18px', 'font_color' => '#555555', 'css_selectors' => '.slide-content .caption' ), 'paragraphs' => array( 'preview_text' => 'Paragraph Text', 'preview_color' => 'light', 'font_family' => 'Open Sans', 'font_variant' => 'normal', 'font_size' => '14px', 'font_color' => '#8a8a8a', 'css_selectors' => 'p' ) )); } /*-----------------------------------------------------------------------------------*/ /* If WP 3.0 or > include support for wp_nav_menu() /*-----------------------------------------------------------------------------------*/ if ( function_exists( 'register_nav_menus' ) ) { register_nav_menus( array( 'primary-menu' => __('Main Menu', 'framework' ) ) ); } /*-----------------------------------------------------------------------------------*/ /* Custom Gravatar Support /*-----------------------------------------------------------------------------------*/ function t2t_custom_gravatar( $avatar_defaults ) { $tz_avatar = get_template_directory_uri() . '/images/gravatar.png'; $avatar_defaults[$tz_avatar] = 'Custom Gravatar (/images/gravatar.png)'; return $avatar_defaults; } add_filter( 'avatar_defaults', 't2t_custom_gravatar' ); /*-----------------------------------------------------------------------------------*/ /* Add/configure thumbnails /*-----------------------------------------------------------------------------------*/ if ( function_exists( 'add_theme_support' ) ) { add_theme_support( 'post-thumbnails' ); // change the default thumbnail size update_option("thumbnail_size_w", 290); update_option("thumbnail_size_h", 290); update_option("thumbnail_crop", 1); update_option('shop_catalog_image_size', array( "width" => "290", "height" => "290", "crop" => 1 ) ); // change the default medium size update_option("medium_size_w", 560); update_option("medium_size_h", 420); update_option("medium_crop", 1); update_option('shop_single_image_size', array( "width" => "560", "height" => "420", "crop" => 1 ) ); // change the default medium size update_option("large_size_w", 940); update_option("large_size_h", 999999); update_option("large_crop", 0); } /*-----------------------------------------------------------------------------------*/ /* Register and load javascripts /*-----------------------------------------------------------------------------------*/ function t2t_register_js() { global $theme; if (!is_admin()) { // wp_register_script('moment', get_template_directory_uri() . '/javascripts/moment.min.js', 'jquery', $theme->version, true); // wp_register_script('html5shiv', get_template_directory_uri() . '/javascripts/html5shiv.js', 'jquery', $theme->version, true); // wp_register_script('easing', get_template_directory_uri() . '/javascripts/jquery.easing.js', 'jquery', $theme->version, true); // wp_register_script('bacond', get_template_directory_uri() . '/javascripts/jquery.ba-cond.min.js', 'jquery', $theme->version, true); // wp_register_script('tipsy', get_template_directory_uri() . '/javascripts/jquery.tipsy.js', 'jquery', $theme->version, true); // wp_register_script('isotope', get_template_directory_uri() . '/javascripts/jquery.isotope.js', 'jquery', $theme->version, true); // wp_register_script('imagesloaded', get_template_directory_uri() . '/javascripts/jquery.imagesloaded.js', 'jquery', $theme->version, true); // wp_register_script('mobilemenu', get_template_directory_uri() . '/javascripts/jquery.mobilemenu.js', 'jquery', $theme->version, true); // wp_register_script('retinise', get_template_directory_uri() . '/javascripts/jquery.retinise.js', 'jquery', $theme->version, true); // wp_register_script('fullcalendar', get_template_directory_uri() . '/javascripts/fullcalendar.js', 'jquery', $theme->version, true); // wp_register_script('uitotop', get_template_directory_uri() . '/javascripts/jquery.ui.totop.js', 'jquery', $theme->version, true); // wp_register_script('waypoints', get_template_directory_uri() . '/javascripts/jquery.waypoints.js', 'jquery', $theme->version, true); // wp_register_script('hoverintent', get_template_directory_uri() . '/javascripts/jquery.hoverIntent.js', 'jquery', $theme->version, true); // wp_register_script('headroom', get_template_directory_uri() . '/javascripts/headroom.js', 'jquery', $theme->version, true); // wp_register_script('jcarousel', get_template_directory_uri() . '/javascripts/jquery.jcarousel.js', 'jquery', $theme->version, true); // wp_register_script('fancyselect', get_template_directory_uri() . '/javascripts/fancySelect.js', 'jquery', $theme->version, true); wp_register_script('combined', get_template_directory_uri() . '/javascripts/_combined.min.js', 'jquery', $theme->version, true); wp_register_script('custom', get_template_directory_uri() . '/javascripts/custom.js', 'jquery', $theme->version, true); wp_enqueue_script('jquery'); // wp_enqueue_script('moment'); // wp_enqueue_script('html5shiv'); // wp_enqueue_script('easing'); // wp_enqueue_script('bacond'); // wp_enqueue_script('tipsy'); // wp_enqueue_script('isotope'); // wp_enqueue_script('imagesloaded'); // wp_enqueue_script('retinise'); // wp_enqueue_script('fullcalendar'); // wp_enqueue_script('uitotop'); // wp_enqueue_script('waypoints'); // wp_enqueue_script('hoverintent'); // wp_enqueue_script('headroom'); // wp_enqueue_script('jcarousel'); // wp_enqueue_script('fancyselect'); // wp_enqueue_script('mobilemenu'); if ( is_singular() AND comments_open() AND (get_option('thread_comments') == 1)) { wp_enqueue_script('comment-reply'); } wp_enqueue_script('combined'); wp_enqueue_script('custom'); } } add_action('wp_enqueue_scripts', 't2t_register_js'); /*-----------------------------------------------------------------------------------*/ /* Register and load css /*-----------------------------------------------------------------------------------*/ function t2t_register_css() { global $theme; if (!is_admin()) { wp_enqueue_style("google-fonts", 'http://fonts.googleapis.com/css?family=Exo:100,200,300,400,500,600,700,800,900,100italic,200italic,300italic,400italic,500italic,600italic,700italic,800italic,900italic|Source+Sans+Pro:300,400,600,700', false, false, "all"); wp_register_style('fullcalendar', get_template_directory_uri() . '/stylesheets/fullcalendar.css', array()); wp_register_style('tipsy', get_template_directory_uri() . '/stylesheets/tipsy.css', array()); wp_register_style('fancyselect', get_template_directory_uri() . '/stylesheets/fancySelect.css', array()); wp_register_style('style', get_stylesheet_uri(), array()); wp_enqueue_style('fullcalendar'); wp_enqueue_style('tipsy'); wp_enqueue_style('fancyselect'); if(!class_exists("T2T_Toolkit")) { wp_enqueue_style("icons", get_template_directory_uri() . "/stylesheets/icons.css", array(), $theme->version, "screen"); } wp_enqueue_style('style'); } } add_action('wp_enqueue_scripts', 't2t_register_css'); function t2t_register_admin_head() { $admin_head = ""; // Google typography tweaks $css = '<style type="text/css">'; $css .= '#google_typography input { box-shadow: none; }'; $css .= '#google_typography .wp-picker-container { display: none; }'; $css .= '#google_typography .preview_color { display: none; }'; $css .= 'div#google_typography .collection[data-default="true"] .font_options a.delete_collection { display: none; }'; $css .= '</style>'; $admin_head .= $css; // Meta box tweaks $js = "<script type=\"text/javascript\">"; $js .= " jQuery(document).ready(function($) {"; $js .= " $('#album_layout_style, #t2t_album-album_layout_style').parent().hide();"; $js .= " });"; $js .= "</script>"; $admin_head .= $js; echo $admin_head; } add_action('admin_head', 't2t_register_admin_head'); function themeit_add_editor_style() { add_editor_style( 'style-editor.css' ); } add_action( 'after_setup_theme', 'themeit_add_editor_style' ); /*-----------------------------------------------------------------------------------*/ /* Theme customizer hooks /*-----------------------------------------------------------------------------------*/ function t2t_customizer_css() { $css = '<style type="text/css">'; $css .= get_theme_mod('t2t_customizer_css'); $css .= '</style>'; echo $css; } add_action('wp_head', 't2t_customizer_css'); function t2t_customizer_analytics() { echo get_theme_mod('t2t_customizer_analytics'); } add_action('wp_footer', 't2t_customizer_analytics'); /*-----------------------------------------------------------------------------------*/ /* Function to output social links /*-----------------------------------------------------------------------------------*/ function get_t2t_social_links() { $social_links = array( "twitter" => array( "rounded" => "entypo-twitter-circled", "circular" => "typicons-social-twitter-circular", "simple" => "typicons-social-twitter", "href" => get_theme_mod("t2t_customizer_social_twitter") ), "facebook" => array( "rounded" => "entypo-facebook-circled", "circular" => "typicons-social-facebook-circular", "simple" => "typicons-social-facebook", "href" => get_theme_mod("t2t_customizer_social_facebook") ), "flickr" => array( "rounded" => "entypo-flickr-circled", "circular" => "typicons-social-flickr-circular", "simple" => "typicons-social-flickr", "href" => get_theme_mod("t2t_customizer_social_flickr") ), "github" => array( "rounded" => "entypo-github-circled", "circular" => "typicons-social-github-circular", "simple" => "typicons-social-github", "href" => get_theme_mod("t2t_customizer_social_github") ), "vimeo" => array( "rounded" => "entypo-vimeo-circled", "circular" => "typicons-social-vimeo-circular", "simple" => "typicons-social-vimeo", "href" => get_theme_mod("t2t_customizer_social_vimeo") ), "pinterest" => array( "rounded" => "entypo-pinterest-circled", "circular" => "typicons-social-pinterest-circular", "simple" => "typicons-social-pinterest", "href" => get_theme_mod("t2t_customizer_social_pinterest") ), "linkedin" => array( "rounded" => "entypo-linkedin-circled", "circular" => "typicons-social-linkedin-circular", "simple" => "typicons-social-linkedin", "href" => get_theme_mod("t2t_customizer_social_linked") ), "dribbble" => array( "rounded" => "entypo-dribbble-circled", "circular" => "typicons-social-dribbble-circular", "simple" => "typicons-social-dribbble", "href" => get_theme_mod("t2t_customizer_social_dribbble") ), "lastfm" => array( "rounded" => "entypo-lastfm-circled", "circular" => "typicons-social-last-fm-circular", "simple" => "typicons-social-last-fm", "href" => get_theme_mod("t2t_customizer_social_lastfm") ), "skype" => array( "rounded" => "entypo-skype-circled", "circular" => "typicons-social-skype-outline", "simple" => "typicons-social-skype", "href" => get_theme_mod("t2t_customizer_social_skype") ), "email" => array( "rounded" => "typicons-at", "circular" => "typicons-at", "simple" => "typicons-mail", "href" => get_theme_mod("t2t_customizer_social_email") ) ); $social_style = get_theme_mod("t2t_customizer_social_style", "rounded"); $html = "<ul class=\"social " . $social_style . "\">"; foreach($social_links as $site => $settings) { // only include the link if a url was provided if(!empty($settings["href"]) && $settings["href"] != "") { $html .= "<li><a href=\"" . $settings["href"] . "\" title=\"" . $site . "\" rel=\"tipsy\" target=\"_blank\"><span class=\"" . $settings[$social_style] . "\"></span></a></li>"; } } $html .= '</ul>'; return $html; } // same as get_t2t_social_links method but rather than // returning the markup, it prints it by default function t2t_social_links() { echo get_t2t_social_links(); } /*-----------------------------------------------------------------------------------*/ /* Custom Excerpt Functions /*-----------------------------------------------------------------------------------*/ function custom_excerpt_length( $length ) { return 13; } add_filter( 'excerpt_length', 'custom_excerpt_length', 999 ); function new_excerpt_more( $more ) { return '...'; } add_filter('excerpt_more', 'new_excerpt_more'); /*-----------------------------------------------------------------------------------*/ /* Password protected posts /*-----------------------------------------------------------------------------------*/ function custom_password_text($content) { $before = 'Password:'; $after = ''; $content = str_replace($before, $after, $content); return $content; } add_filter('the_password_form', 'custom_password_text'); function custom_password_prompt($content) { $before = 'This post is password protected. To view it please enter your password below:'; $after = 'This content is password protected. To view it please enter your password below:'; $content = str_replace($before, $after, $content); return $content; } add_filter('the_password_form', 'custom_password_prompt'); /*-----------------------------------------------------------------------------------*/ /* Register plugins /*-----------------------------------------------------------------------------------*/ function t2t_required_plugins() { $plugins = array( array( 'name' => 'T2T Toolkit', 'slug' => 't2t-toolkit', 'source' => 'http://assets.t2themes.com/plugins/t2t-toolkit/t2t-toolkit-latest.zip', 'external_url' => 'http://t2themes.com', 'required' => true ), array( 'name' => 'Google Typography', 'slug' => 'google-typography', 'required' => false ), array( 'name' => 'Contact Form 7', 'slug' => 'contact-form-7', 'required' => false ), array( 'name' => 'Easy Theme and Plugin Upgrades', 'slug' => 'easy-theme-and-plugin-upgrades', 'required' => false ) ); $theme_text_domain = 'framework'; $config = array('domain' => $theme_text_domain, 'menu' => 'install-required-plugins'); tgmpa( $plugins, $config ); } add_action( 'tgmpa_register', 't2t_required_plugins' ); add_theme_support( 'post-formats' ); function rw_title($title, $sep, $seplocation) { global $page, $paged; // don't affect in feeds. if(is_feed()) { return $title; } // add the blog name if($seplocation == "right") { $title .= get_bloginfo('name'); } else { $title = get_bloginfo("name") . $title; } // add the blog description for the home/front page. $site_description = get_bloginfo("description", "display"); if($site_description && (is_home() || is_front_page())) { $title .= " {$sep} {$site_description}"; } // add a page number if necessary: if($paged >= 2 || $page >= 2) { $title .= " {$sep} " . sprintf(__('Page %s', 'dbt'), max($paged, $page)); } return $title; } add_filter("wp_title", "rw_title", 10, 3); /*-----------------------------------------------------------------------------------*/ /* T2T_Toolkit-ness /*-----------------------------------------------------------------------------------*/ function enable_t2t_post_types($post_types) { if(class_exists("T2T_Page")) { array_push($post_types, new T2T_Page()); } if(class_exists("T2T_Post")) { array_push($post_types, new T2T_Post()); } if(class_exists("T2T_SlitSlider")) { array_push($post_types, new T2T_SlitSlider(array( "show_shortcodes" => false ))); } if(class_exists("T2T_ElasticSlider")) { array_push($post_types, new T2T_ElasticSlider(array( "show_shortcodes" => false ))); } if(class_exists("T2T_FlexSlider")) { array_push($post_types, new T2T_FlexSlider(array( "show_shortcodes" => false, "args" => array( "supports" => array("title", "editor", "thumbnail", "post-formats") ) ))); } if(class_exists("T2T_Person")) { array_push($post_types, new T2T_Person()); } if(class_exists("T2T_Service")) { array_push($post_types, new T2T_Service()); } if(class_exists("T2T_Album")) { array_push($post_types, new T2T_Album()); } if(class_exists("T2T_Testimonial")) { array_push($post_types, new T2T_Testimonial()); } if(class_exists("T2T_Special")) { array_push($post_types, new T2T_Special()); } if(class_exists("T2T_Carousel")) { array_push($post_types, new T2T_Carousel(array( "show_taxonomy" => false, "args" => array( "supports" => array("title") ) ))); } return $post_types; } add_filter("t2t_toolkit_enabled_post_types", "enable_t2t_post_types"); function enable_icon_sets($available_sets) { // override the enabled icon sets return array( "fiticon", "maki" ); } add_filter("t2t_toolkit_icon_sets", "enable_icon_sets"); function rename_person_name($current) { return "t2t_coach"; } add_filter("t2t_post_type_person_name", "rename_person_name"); function rename_person_title($current) { return __("Coach", "framework"); } add_filter("t2t_post_type_person_title", "rename_person_title"); function rename_service_name($current) { return "t2t_program"; } add_filter("t2t_post_type_service_name", "rename_service_name"); function rename_service_title($current) { return __("Program", "framework"); } add_filter("t2t_post_type_service_title", "rename_service_title"); function rename_album_name($current) { return "t2t_gallery"; } add_filter("t2t_post_type_album_name", "rename_album_name"); function rename_album_title($current) { return __("Gallery", "framework"); } add_filter("t2t_post_type_album_title", "rename_album_title"); function post_post_formats($formats) { return array("standard", "aside" => "WOD", "video", "image", "quote", "audio", "gallery"); } add_filter("post_post_formats", "post_post_formats"); function t2t_flexslider_post_formats($formats) { return array("image", "video"); } add_filter("t2t_flexslider_post_formats", "t2t_flexslider_post_formats"); ?>
gregmccabe/headstrong-wp
wp-content/themes/workout/functions.php
PHP
gpl-2.0
24,923
package com.comphenix.xp.lookup; import static org.junit.Assert.*; import org.bukkit.entity.EntityType; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.junit.Test; import com.comphenix.xp.parser.ParsingException; import com.comphenix.xp.parser.text.MobMatcher; import com.comphenix.xp.parser.text.MobParser; public class MobParserTest { @Test public void testParser() throws ParsingException { MobQuery universal = MobQuery.fromAny(); MobQuery allZombies = MobQuery.fromAny(EntityType.ZOMBIE); MobQuery fallingZombies = MobQuery.fromAny(EntityType.ZOMBIE, DamageCause.FALL); MobQuery spawnedMobs = MobQuery.fromAny((EntityType) null, null, SpawnReason.SPAWNER, null, null, null, null); MobQuery smallSlimes = MobQuery.fromAny(EntityType.SLIME, null, 1, null, null, null, null, null); MobParser parser = new MobParser(new MobMatcher()); assertEquals(universal, parser.parse("?")); assertEquals(allZombies, parser.parse("zombie")); assertEquals(fallingZombies, parser.parse("zombie|fall")); assertEquals(fallingZombies, parser.parse("zombie|fall|spawner,!spawner")); assertEquals(smallSlimes, parser.parse("slime|?|tiny")); assertEquals(spawnedMobs, parser.parse("?|?|spawner")); assertNotSame(universal, parser.parse("?|?|spawner")); } }
aadnk/ExperienceMod
ExperienceMod/src/test/java/com/comphenix/xp/lookup/MobParserTest.java
Java
gpl-2.0
1,403
/* * Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org> * Copyright (c) 2011-2012 University of Paderborn - UPB * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * * This file is part of PeerfactSim.KOM. * * PeerfactSim.KOM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * PeerfactSim.KOM 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 PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * */ package org.peerfact.impl.scenario; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.dom4j.Element; import org.peerfact.api.common.Component; import org.peerfact.api.common.ComponentFactory; import org.peerfact.api.common.Host; import org.peerfact.api.scenario.Composable; import org.peerfact.api.scenario.Configurator; import org.peerfact.api.scenario.HostBuilder; import org.peerfact.impl.common.DefaultHost; import org.peerfact.impl.common.DefaultHostProperties; import org.peerfact.impl.util.logging.SimLogger; /** * This builder will parse an XML subtree and create hosts as specified there. * It expects a tree which looks as follows: <code> * &lt;HostBuilder&gt; * &lt;Host id="..." groupID="..."&gt;... * &lt;Group size="..." id="..." groupID="..."&gt;... * &lt;HostBuilder/&gt; * </code> * * The exact values for XML tags are specified as constants in this class (see * below). * * @author Konstantin Pussep <peerfact@kom.tu-darmstadt.de> * @author Sebastian Kaune * @author Matthias Feldotto <info@peerfact.org> * @version 3.0, 29.11.2007 * */ public class DefaultHostBuilder implements HostBuilder, Composable { /** * XML attribute with this name specifies the size of the group. */ public static final String GROUP_SIZE_TAG = "size"; /** * XML element with this name specifies a group of hosts. */ public static final String GROUP_TAG = "Group"; /** * XML element with this name specifies a single host and behaves equivalent * to an element with the name = GROUP_TAG value and group size of 1. */ public static final String HOST_TAG = "Host"; /** * XML attribute with this name specifies the id of the group, which is used * to refer to this group lateron, e.g. when you specify scenario actions. */ public static final String ID_TAG = "id"; /** * XML attribute with this name specifies the id group id which is used for * gnp mapping. */ public static final String GROUP_ID_TAG = "groupID"; private static final Logger log = SimLogger .getLogger(DefaultHostBuilder.class); /** * Groups of hosts indexed by group ids. */ protected Map<String, List<Host>> groups; protected int experimentSize; /** * Flat list of all hosts. */ protected final List<Host> hosts = new LinkedList<Host>(); /** * Will be called by the configurator. * * @param size * total number of hosts in the simulator TODO we could remove * this or force its correctness... */ public void setExperimentSize(int size) { groups = new LinkedHashMap<String, List<Host>>(size); this.experimentSize = size; } @Override public void compose(Configurator config) { // unused } /* * (non-Javadoc) * * @see org.peerfact.api.scenario.HostBuilder#getAllHostsWithIDs() */ @Override public Map<String, List<Host>> getAllHostsWithIDs() { Map<String, List<Host>> hostsMap = new LinkedHashMap<String, List<Host>>( groups); return hostsMap; } /* * (non-Javadoc) * * @see org.peerfact.api.scenario.HostBuilder#getAllHosts() */ @Override public List<Host> getAllHosts() { return hosts; } /* * (non-Javadoc) * * @see * org.peerfact.api.scenario.HostBuilder#getHosts(java.lang.String) */ @Override public List<Host> getHosts(String id) { return groups.get(id); } /* * (non-Javadoc) * * @see org.peerfact.api.scenario.HostBuilder#parse(org.dom4j.Element, * org.peerfact.api.scenario.Configurator) */ @Override public void parse(Element elem, Configurator config) { DefaultConfigurator defaultConfigurator = (DefaultConfigurator) config; // create groups for (Iterator<?> iter = elem.elementIterator(); iter.hasNext();) { Element groupElem = (Element) iter.next(); String groupID = groupElem.attributeValue(GROUP_ID_TAG); String id = groupElem.attributeValue(ID_TAG); if (id == null) { // FIXME: remove, only for compatibility id = groupID; } if (id == null) { throw new IllegalArgumentException("Id of host/group " + groupElem.asXML() + " must not be null"); } // either a group of hosts or a single host (=group with size 1) int groupSize; if (groupElem.getName().equals(HOST_TAG)) { groupSize = 1; } else if (groupElem.getName().equals(GROUP_TAG)) { String attributeValue = config.parseValue(groupElem .attributeValue(GROUP_SIZE_TAG)); groupSize = Integer.parseInt(attributeValue); } else { throw new IllegalArgumentException("Unexpected tag " + groupElem.getName()); } List<Host> group = new ArrayList<Host>(groupSize); // create hosts and instances of specified components for each host for (int i = 0; i < groupSize; i++) { DefaultHost host = new DefaultHost(); // initialize properties DefaultHostProperties hostProperties = new DefaultHostProperties(); host.setProperties(hostProperties); // minimal information for host properties is the id and the // group id hostProperties.setId(id); hostProperties.setGroupID(groupID); // initialize layers and properties for (Iterator<?> layers = groupElem.elementIterator(); layers .hasNext();) { Element layerElem = (Element) layers.next(); if (layerElem.getName().equals( Configurator.HOST_PROPERTIES_TAG)) { defaultConfigurator.configureAttributes(hostProperties, layerElem); } else { // layer component factory ComponentFactory layer = (ComponentFactory) defaultConfigurator .configureComponent(layerElem); Component comp = layer.createComponent(host); host.setComponent(comp); } } group.add(host); } log.debug("Created a group with " + group.size() + " hosts"); hosts.addAll(group); groups.put(id, group); } log.info("CREATED " + hosts.size() + " hosts"); if (hosts.size() != experimentSize) { log .warn("Only " + hosts.size() + " hosts were specified, though the experiment size was set to " + experimentSize); } } }
flyroom/PeerfactSimKOM_Clone
src/org/peerfact/impl/scenario/DefaultHostBuilder.java
Java
gpl-2.0
7,070
import os import csv import sys import re import importlib import networkx as nx # settings #curDir = 'E:/Copy/Coursera/Bioinformatics Algorithms (part-I)/MyPrograms/week6-python' curDir = 'D:/Copy/Coursera/Bioinformatics Algorithms (part-I)/MyPrograms/week6-python' inputFile = './data/6.local_alignment-2.txt' #inputFile = 'C:/Users/Ashis/Downloads/dataset_247_9.txt' outputFile = './results/6.local_alignment.txt' scoreFile = './data/PAM250_1.txt' # set current directory os.chdir(curDir) ## read input with open(inputFile) as f: inputs = f.readlines() protein1 = inputs[0].strip() protein2 = inputs[1].strip() ## read pam score matrix ## colIndex is map from amino acid to its index ## pam is a 2D matrix with open(scoreFile) as f: lines = f.readlines() cols = re.split("\\s*", lines[0].strip()) colIndex = {cols[i]:i for i in range(0,len(cols))} pam = [[int(i) for i in re.split("\\s*", row.strip())[1:]] for row in lines[1:]] #print(pam) ## indel penalty sigma = 5 ## create scores and backtrack arrays len1 = len(protein1) len2 = len(protein2) scores = [[0]*(len2+1) for x in range(len1+1)] backtrack = [[3]*(len2+1) for x in range(len1+1)] # 0: top, 1:left, 2:diag, 3:start ## put first row and first column of scores and backtrack arrays #for i in range(1,len1+1): # scores[i][0] = scores[i-1][0] - sigma # backtrack[i][0] = 0 #for j in range(1,len2+1): # scores[0][j] = scores[0][j-1] - sigma # backtrack[0][j] = 1 ## update scores in greedy approach for i in range(1,len1+1): for j in range(1,len2+1): topScore = scores[i-1][j] - sigma leftScore = scores[i][j-1] - sigma diagScore = scores[i-1][j-1] + pam[colIndex[protein1[i-1]]][colIndex[protein2[j-1]]] startScore = 0 candidateScores = [topScore, leftScore, diagScore, startScore] scores[i][j] = max(candidateScores) backtrack[i][j] = candidateScores.index(scores[i][j]) ## max score node is the maxScore = float("-inf") maxi = -1 maxj = -1 for i in range(1,len1+1): for j in range(1,len2+1): if scores[i][j] > maxScore: maxScore = scores[i][j] maxi = i maxj = j ## max score #maxScore = scores[len1][len2] ## backtrack and find alignment alignment1 = [] alignment2 = [] i = maxi j = maxj while i!=0 or j!=0: if backtrack[i][j] == 0: # top alignment1.append(protein1[i-1]) alignment2.append('-') i = i-1 elif backtrack[i][j] == 1: # left alignment1.append('-') alignment2.append(protein2[j-1]) j = j-1 elif backtrack[i][j] == 2: # diag alignment1.append(protein1[i-1]) alignment2.append(protein2[j-1]) i = i-1 j = j-1 else: # start i = 0 j = 0 alignment1.reverse() alignment2.reverse() print(maxScore) #print(alignment1) #print(alignment2) # output with open(outputFile, "w") as f: f.writelines(str(maxScore) + "\n") f.writelines("".join(alignment1) + "\n") f.writelines("".join(alignment2) + "\n")
alorchhota/bioinformatics-algorithms-1
week6-Python/code/6.LocalAlignment.py
Python
gpl-2.0
3,114
var mongoclient = require('mongodb').MongoClient; var format = require('util').format; var server_settings = require('../../server_settings'); var enumurations = require('../../../../common/biz/enum'); var mongoAddress = server_settings.databaseAddress; var PROCEDURE = enumurations.P_DATABASE_OPERATIONS; exports.DoProcedure_CallBackWithResults = function(operation, params, callback) { console.log("mongo_client: running procedure: " + operation); switch(operation) { case PROCEDURE.INIT: var collectionName = params.collection; mongoclient.connect(mongoAddress, function(error, db) { console.log("mongo_client: MongoClient just called back") if(error) { return callback(error) }; var collection = db.collection(collectionName); console.log(format("mongo_client: init " + collectionName)); db.close(); callback(null, collectionName); }); break; case PROCEDURE.INSERT: var insertDocs = params.docs; var collectionName = params.collection; mongoclient.connect(mongoAddress, function(error, db) { console.log("mongo_client: MongoClient just called back") if(error) { return callback(error) }; var collection = db.collection(collectionName); collection.insert(insertDocs, function(error, docs) { console.log("mongo_client: test_collection just called back"); if (error) { return callback(error) }; collection.count(function(error, count) { if (error) { return callback(error) }; console.log(format("mongo_client: insert successful in " + collectionName)); db.close(); callback(null, count); }); }); }); break; case PROCEDURE.FIND: console.log("mongo_client: params: " + params.query + ", params as string:" + JSON.stringify(params.query)); mongoclient.connect(mongoAddress, function(error, db) { console.log("mongo_client: MongoClient just called back") if(error) { return callback(error) }; var collection = db.collection(params.collection); collection.find(params.query, function(error, cursor) { console.log("mongo_client: test_collection just called back"); if (error) { return callback(error) }; cursor.toArray(function(error, docs)) { console.log(format("mongo_client: find successful")); db.close(); //console.log(docs); callback(null, docs); }); }); }); break; case PROCEDURE.UPDATE: default: console.log("p_database: unrecognized operation request: " + JSON.stringify(operation)); return callback("p_database: unrecognized operation request: " + JSON.stringify(operation)); break; } }
dpxxdp/Pipes
server/server/procedure_types/db_clients/mongo_client.js
JavaScript
gpl-2.0
3,511
<!-- Pricing --> <div class="wps-form-group wps-form-group-tight"> <table class="form-table"> <tbody> <tr valign="top"> <th scope="row" class="titledesc"> <?php esc_attr_e( 'Cart counter', WPS_PLUGIN_TEXT_DOMAIN ); ?> <span class="wps-help-tip" title="<?php esc_attr_e( 'Changes the background color of the cart icon counter. Note, changing this value may potentially override any custom CSS from your theme.', WPS_PLUGIN_TEXT_DOMAIN ); ?>"></span> </th> <td class="wps-input"> <div id="wps-color-picker-cart-counter"> <span class="wps-placeholder wps-placeholder-checkbox"></span> </div> </td> </tr> </tbody> </table> </div>
arobbins/wp-shopify
admin/partials/settings/cart/settings-cart-counter-color.php
PHP
gpl-2.0
742
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005,2006 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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 * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include <algorithm> #include "ns3/log.h" #include "ns3/simulator.h" #include "ns3/packet.h" #include "wifi-phy-state-helper.h" #include "wifi-tx-vector.h" #include "wifi-phy-listener.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("WifiPhyStateHelper"); NS_OBJECT_ENSURE_REGISTERED (WifiPhyStateHelper); TypeId WifiPhyStateHelper::GetTypeId (void) { static TypeId tid = TypeId ("ns3::WifiPhyStateHelper") .SetParent<Object> () .SetGroupName ("Wifi") .AddConstructor<WifiPhyStateHelper> () .AddTraceSource ("State", "The state of the PHY layer", MakeTraceSourceAccessor (&WifiPhyStateHelper::m_stateLogger), "ns3::WifiPhyStateHelper::StateTracedCallback") .AddTraceSource ("RxOk", "A packet has been received successfully.", MakeTraceSourceAccessor (&WifiPhyStateHelper::m_rxOkTrace), "ns3::WifiPhyStateHelper::RxOkTracedCallback") .AddTraceSource ("RxError", "A packet has been received unsuccessfully.", MakeTraceSourceAccessor (&WifiPhyStateHelper::m_rxErrorTrace), "ns3::WifiPhyStateHelper::RxEndErrorTracedCallback") .AddTraceSource ("Tx", "Packet transmission is starting.", MakeTraceSourceAccessor (&WifiPhyStateHelper::m_txTrace), "ns3::WifiPhyStateHelper::TxTracedCallback") ; return tid; } WifiPhyStateHelper::WifiPhyStateHelper () : m_rxing (false), m_sleeping (false), m_isOff (false), m_endTx (Seconds (0)), m_endRx (Seconds (0)), m_endCcaBusy (Seconds (0)), m_endSwitching (Seconds (0)), m_startTx (Seconds (0)), m_startRx (Seconds (0)), m_startCcaBusy (Seconds (0)), m_startSwitching (Seconds (0)), m_startSleep (Seconds (0)), m_previousStateChangeTime (Seconds (0)) { NS_LOG_FUNCTION (this); } void WifiPhyStateHelper::SetReceiveOkCallback (RxOkCallback callback) { m_rxOkCallback = callback; } void WifiPhyStateHelper::SetReceiveErrorCallback (RxErrorCallback callback) { m_rxErrorCallback = callback; } void WifiPhyStateHelper::RegisterListener (WifiPhyListener *listener) { m_listeners.push_back (listener); } void WifiPhyStateHelper::UnregisterListener (WifiPhyListener *listener) { ListenersI i = find (m_listeners.begin (), m_listeners.end (), listener); if (i != m_listeners.end ()) { m_listeners.erase (i); } } bool WifiPhyStateHelper::IsStateIdle (void) const { return (GetState () == WifiPhyState::IDLE); } bool WifiPhyStateHelper::IsStateCcaBusy (void) const { return (GetState () == WifiPhyState::CCA_BUSY); } bool WifiPhyStateHelper::IsStateRx (void) const { return (GetState () == WifiPhyState::RX); } bool WifiPhyStateHelper::IsStateTx (void) const { return (GetState () == WifiPhyState::TX); } bool WifiPhyStateHelper::IsStateSwitching (void) const { return (GetState () == WifiPhyState::SWITCHING); } bool WifiPhyStateHelper::IsStateSleep (void) const { return (GetState () == WifiPhyState::SLEEP); } bool WifiPhyStateHelper::IsStateOff (void) const { return (GetState () == WifiPhyState::OFF); } Time WifiPhyStateHelper::GetDelayUntilIdle (void) const { Time retval; switch (GetState ()) { case WifiPhyState::RX: retval = m_endRx - Simulator::Now (); break; case WifiPhyState::TX: retval = m_endTx - Simulator::Now (); break; case WifiPhyState::CCA_BUSY: retval = m_endCcaBusy - Simulator::Now (); break; case WifiPhyState::SWITCHING: retval = m_endSwitching - Simulator::Now (); break; case WifiPhyState::IDLE: retval = Seconds (0); break; case WifiPhyState::SLEEP: NS_FATAL_ERROR ("Cannot determine when the device will wake up."); retval = Seconds (0); break; case WifiPhyState::OFF: NS_FATAL_ERROR ("Cannot determine when the device will be switched on."); retval = Seconds (0); break; default: NS_FATAL_ERROR ("Invalid WifiPhy state."); retval = Seconds (0); break; } retval = Max (retval, Seconds (0)); return retval; } Time WifiPhyStateHelper::GetLastRxStartTime (void) const { return m_startRx; } WifiPhyState WifiPhyStateHelper::GetState (void) const { if (m_isOff) { return WifiPhyState::OFF; } if (m_sleeping) { return WifiPhyState::SLEEP; } else if (m_endTx > Simulator::Now ()) { return WifiPhyState::TX; } else if (m_rxing) { return WifiPhyState::RX; } else if (m_endSwitching > Simulator::Now ()) { return WifiPhyState::SWITCHING; } else if (m_endCcaBusy > Simulator::Now ()) { return WifiPhyState::CCA_BUSY; } else { return WifiPhyState::IDLE; } } void WifiPhyStateHelper::NotifyTxStart (Time duration, double txPowerDbm) { NS_LOG_FUNCTION (this); for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++) { (*i)->NotifyTxStart (duration, txPowerDbm); } } void WifiPhyStateHelper::NotifyRxStart (Time duration) { NS_LOG_FUNCTION (this); for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++) { (*i)->NotifyRxStart (duration); } } void WifiPhyStateHelper::NotifyRxEndOk (void) { NS_LOG_FUNCTION (this); for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++) { (*i)->NotifyRxEndOk (); } } void WifiPhyStateHelper::NotifyRxEndError (void) { NS_LOG_FUNCTION (this); for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++) { (*i)->NotifyRxEndError (); } } void WifiPhyStateHelper::NotifyMaybeCcaBusyStart (Time duration) { NS_LOG_FUNCTION (this); for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++) { (*i)->NotifyMaybeCcaBusyStart (duration); } } void WifiPhyStateHelper::NotifySwitchingStart (Time duration) { NS_LOG_FUNCTION (this); for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++) { (*i)->NotifySwitchingStart (duration); } } void WifiPhyStateHelper::NotifySleep (void) { NS_LOG_FUNCTION (this); for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++) { (*i)->NotifySleep (); } } void WifiPhyStateHelper::NotifyOff (void) { NS_LOG_FUNCTION (this); for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++) { (*i)->NotifyOff (); } } void WifiPhyStateHelper::NotifyWakeup (void) { NS_LOG_FUNCTION (this); for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++) { (*i)->NotifyWakeup (); } } void WifiPhyStateHelper::NotifyOn (void) { NS_LOG_FUNCTION (this); for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++) { (*i)->NotifyOn (); } } void WifiPhyStateHelper::LogPreviousIdleAndCcaBusyStates (void) { NS_LOG_FUNCTION (this); Time now = Simulator::Now (); Time idleStart = Max (m_endCcaBusy, m_endRx); idleStart = Max (idleStart, m_endTx); idleStart = Max (idleStart, m_endSwitching); NS_ASSERT (idleStart <= now); if (m_endCcaBusy > m_endRx && m_endCcaBusy > m_endSwitching && m_endCcaBusy > m_endTx) { Time ccaBusyStart = Max (m_endTx, m_endRx); ccaBusyStart = Max (ccaBusyStart, m_startCcaBusy); ccaBusyStart = Max (ccaBusyStart, m_endSwitching); m_stateLogger (ccaBusyStart, idleStart - ccaBusyStart, WifiPhyState::CCA_BUSY); } m_stateLogger (idleStart, now - idleStart, WifiPhyState::IDLE); } void WifiPhyStateHelper::SwitchToTx (Time txDuration, Ptr<const Packet> packet, double txPowerDbm, WifiTxVector txVector) { NS_LOG_FUNCTION (this << txDuration << packet << txPowerDbm << txVector); m_txTrace (packet, txVector.GetMode (), txVector.GetPreambleType (), txVector.GetTxPowerLevel ()); Time now = Simulator::Now (); switch (GetState ()) { case WifiPhyState::RX: /* The packet which is being received as well * as its endRx event are cancelled by the caller. */ m_rxing = false; m_stateLogger (m_startRx, now - m_startRx, WifiPhyState::RX); m_endRx = now; break; case WifiPhyState::CCA_BUSY: { Time ccaStart = Max (m_endRx, m_endTx); ccaStart = Max (ccaStart, m_startCcaBusy); ccaStart = Max (ccaStart, m_endSwitching); m_stateLogger (ccaStart, now - ccaStart, WifiPhyState::CCA_BUSY); } break; case WifiPhyState::IDLE: LogPreviousIdleAndCcaBusyStates (); break; default: NS_FATAL_ERROR ("Invalid WifiPhy state."); break; } m_stateLogger (now, txDuration, WifiPhyState::TX); m_previousStateChangeTime = now; m_endTx = now + txDuration; m_startTx = now; NotifyTxStart (txDuration, txPowerDbm); } void WifiPhyStateHelper::SwitchToRx (Time rxDuration) { NS_LOG_FUNCTION (this << rxDuration); NS_ASSERT (IsStateIdle () || IsStateCcaBusy ()); NS_ASSERT (!m_rxing); Time now = Simulator::Now (); switch (GetState ()) { case WifiPhyState::IDLE: LogPreviousIdleAndCcaBusyStates (); break; case WifiPhyState::CCA_BUSY: { Time ccaStart = Max (m_endRx, m_endTx); ccaStart = Max (ccaStart, m_startCcaBusy); ccaStart = Max (ccaStart, m_endSwitching); m_stateLogger (ccaStart, now - ccaStart, WifiPhyState::CCA_BUSY); } break; default: NS_FATAL_ERROR ("Invalid WifiPhy state."); break; } m_previousStateChangeTime = now; m_rxing = true; m_startRx = now; m_endRx = now + rxDuration; NotifyRxStart (rxDuration); NS_ASSERT (IsStateRx ()); } void WifiPhyStateHelper::SwitchToChannelSwitching (Time switchingDuration) { NS_LOG_FUNCTION (this << switchingDuration); Time now = Simulator::Now (); switch (GetState ()) { case WifiPhyState::RX: /* The packet which is being received as well * as its endRx event are cancelled by the caller. */ m_rxing = false; m_stateLogger (m_startRx, now - m_startRx, WifiPhyState::RX); m_endRx = now; break; case WifiPhyState::CCA_BUSY: { Time ccaStart = Max (m_endRx, m_endTx); ccaStart = Max (ccaStart, m_startCcaBusy); ccaStart = Max (ccaStart, m_endSwitching); m_stateLogger (ccaStart, now - ccaStart, WifiPhyState::CCA_BUSY); } break; case WifiPhyState::IDLE: LogPreviousIdleAndCcaBusyStates (); break; default: NS_FATAL_ERROR ("Invalid WifiPhy state."); break; } if (now < m_endCcaBusy) { m_endCcaBusy = now; } m_stateLogger (now, switchingDuration, WifiPhyState::SWITCHING); m_previousStateChangeTime = now; m_startSwitching = now; m_endSwitching = now + switchingDuration; NotifySwitchingStart (switchingDuration); NS_ASSERT (IsStateSwitching ()); } void WifiPhyStateHelper::SwitchFromRxEndOk (Ptr<Packet> packet, double snr, WifiTxVector txVector) { NS_LOG_FUNCTION (this << packet << snr << txVector); m_rxOkTrace (packet, snr, txVector.GetMode (), txVector.GetPreambleType ()); NotifyRxEndOk (); DoSwitchFromRx (); if (!m_rxOkCallback.IsNull ()) { m_rxOkCallback (packet, snr, txVector); } } void WifiPhyStateHelper::SwitchFromRxEndError (Ptr<Packet> packet, double snr) { NS_LOG_FUNCTION (this << packet << snr); m_rxErrorTrace (packet, snr); NotifyRxEndError (); DoSwitchFromRx (); if (!m_rxErrorCallback.IsNull ()) { m_rxErrorCallback (); } } void WifiPhyStateHelper::DoSwitchFromRx (void) { NS_LOG_FUNCTION (this); NS_ASSERT (IsStateRx ()); NS_ASSERT (m_rxing); Time now = Simulator::Now (); m_stateLogger (m_startRx, now - m_startRx, WifiPhyState::RX); m_previousStateChangeTime = now; m_rxing = false; NS_ASSERT (IsStateIdle () || IsStateCcaBusy ()); } void WifiPhyStateHelper::SwitchMaybeToCcaBusy (Time duration) { NS_LOG_FUNCTION (this << duration); NotifyMaybeCcaBusyStart (duration); Time now = Simulator::Now (); switch (GetState ()) { case WifiPhyState::IDLE: LogPreviousIdleAndCcaBusyStates (); break; default: break; } if (GetState () != WifiPhyState::CCA_BUSY) { m_startCcaBusy = now; } m_endCcaBusy = std::max (m_endCcaBusy, now + duration); } void WifiPhyStateHelper::SwitchToSleep (void) { NS_LOG_FUNCTION (this); Time now = Simulator::Now (); switch (GetState ()) { case WifiPhyState::IDLE: LogPreviousIdleAndCcaBusyStates (); break; case WifiPhyState::CCA_BUSY: { Time ccaStart = Max (m_endRx, m_endTx); ccaStart = Max (ccaStart, m_startCcaBusy); ccaStart = Max (ccaStart, m_endSwitching); m_stateLogger (ccaStart, now - ccaStart, WifiPhyState::CCA_BUSY); } break; default: NS_FATAL_ERROR ("Invalid WifiPhy state."); break; } m_previousStateChangeTime = now; m_sleeping = true; m_startSleep = now; NotifySleep (); NS_ASSERT (IsStateSleep ()); } void WifiPhyStateHelper::SwitchFromSleep (Time duration) { NS_LOG_FUNCTION (this << duration); NS_ASSERT (IsStateSleep ()); Time now = Simulator::Now (); m_stateLogger (m_startSleep, now - m_startSleep, WifiPhyState::SLEEP); m_previousStateChangeTime = now; m_sleeping = false; NotifyWakeup (); //update m_endCcaBusy after the sleep period m_endCcaBusy = std::max (m_endCcaBusy, now + duration); if (m_endCcaBusy > now) { NotifyMaybeCcaBusyStart (m_endCcaBusy - now); } } void WifiPhyStateHelper::SwitchFromRxAbort (void) { NS_LOG_FUNCTION (this); NS_ASSERT (IsStateRx ()); NS_ASSERT (m_rxing); m_endRx = Simulator::Now (); DoSwitchFromRx (); NS_ASSERT (!IsStateRx ()); } void WifiPhyStateHelper::SwitchToOff (void) { NS_LOG_FUNCTION (this); Time now = Simulator::Now (); switch (GetState ()) { case WifiPhyState::RX: /* The packet which is being received as well * as its endRx event are cancelled by the caller. */ m_rxing = false; m_stateLogger (m_startRx, now - m_startRx, WifiPhyState::RX); m_endRx = now; break; case WifiPhyState::TX: /* The packet which is being transmitted as well * as its endTx event are cancelled by the caller. */ m_stateLogger (m_startTx, now - m_startTx, WifiPhyState::TX); m_endTx = now; break; case WifiPhyState::IDLE: LogPreviousIdleAndCcaBusyStates (); break; case WifiPhyState::CCA_BUSY: { Time ccaStart = Max (m_endRx, m_endTx); ccaStart = Max (ccaStart, m_startCcaBusy); ccaStart = Max (ccaStart, m_endSwitching); m_stateLogger (ccaStart, now - ccaStart, WifiPhyState::CCA_BUSY); } break; default: NS_FATAL_ERROR ("Invalid WifiPhy state."); break; } m_previousStateChangeTime = now; m_isOff = true; NotifyOff (); NS_ASSERT (IsStateOff ()); } void WifiPhyStateHelper::SwitchFromOff (Time duration) { NS_LOG_FUNCTION (this << duration); NS_ASSERT (IsStateOff ()); Time now = Simulator::Now (); m_previousStateChangeTime = now; m_isOff = false; NotifyOn (); //update m_endCcaBusy after the off period m_endCcaBusy = std::max (m_endCcaBusy, now + duration); if (m_endCcaBusy > now) { NotifyMaybeCcaBusyStart (m_endCcaBusy - now); } } } //namespace ns3
tomhenderson/ns-3-dev-git
src/wifi/model/wifi-phy-state-helper.cc
C++
gpl-2.0
16,452
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package AnalisisLexico; import Repositorio.Variables; import static com.sun.java.accessibility.util.AWTEventMonitor.addKeyListener; import com.sun.org.apache.xalan.internal.lib.ExsltStrings; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.FileNotFoundException; import java.io.IOException; import java.util.LinkedList; import java.util.Map; import java.util.Scanner; /** * * @author ceron */ public class DesCicloMain { public boolean bandera = true, banMate = false; private Variables varia; Operaciones ope = new Operaciones(); LinkedList llist = new LinkedList(); public LinkedList temporal = new LinkedList(); Scanner var = new Scanner(System.in); String supm []={"Pastelito","MedioPastelito","Paleta.Payaso", "Dulce de chocolate", "paletita", "Postre"}; public boolean EvaluaBloques(String obtenLinea, int linea, LinkedList lli)throws FileNotFoundException, IOException{ this.llist = lli; if(Desicion(obtenLinea, linea)){ bandera = true; } else if(DesisionSino(obtenLinea, linea)){ bandera = true; } else if(Impresion(obtenLinea, linea)){ bandera = true; } else if(Ciclo(obtenLinea, linea)){ bandera = true; } else if(Main(obtenLinea, linea)){ bandera = true; } else if(Lectura(obtenLinea, linea)){ bandera = true; } else{ bandera = true; } //varia = null; return bandera; } public boolean Desicion(String obtenLinea, int linea)throws FileNotFoundException, IOException{ String aux[] = obtenLinea.split("\\("); if(aux[0].equals(supm[0])){ if(ope.operacLogic(obtenLinea, linea, supm[0], llist, "N")){ bandera = false; } else { bandera = true; } } else{ bandera = false; } return bandera; } public boolean Main(String obtenLinea, int linea)throws FileNotFoundException, IOException{ String aux[] = obtenLinea.split("\\("); if(aux[0].equals(supm[3])){ if(ope.operacLogic(obtenLinea, linea, supm[3], llist, "N")){ bandera = false; } else { bandera = true; } } else{ bandera = false; } return bandera; } public boolean DesisionSino(String obtenLinea, int linea)throws FileNotFoundException, IOException{ String aux[] = obtenLinea.split("\\("); if(aux[0].equals(supm[1])){ if(ope.operacLogic(obtenLinea, linea, supm[1], llist, "N")){ bandera = false; } else { bandera = true; } } else{ bandera = false; } return bandera; } public boolean Impresion(String obtenLinea, int linea)throws FileNotFoundException, IOException{ String aux[] = obtenLinea.split("\\("); if(aux[0].equals(supm[2])){ if(ope.operacLogic(obtenLinea, linea, supm[2], llist, "N")){ bandera = false; } else { bandera = true; } } else{ bandera = false; } return bandera; } public boolean Ciclo(String obtenLinea, int linea)throws FileNotFoundException, IOException{ String aux[] = obtenLinea.split("\\("); if(aux[0].equals(supm[4])){ if(ope.operacLogic(obtenLinea, linea, supm[4], llist, "N")){ bandera = false; } else { bandera = true; } } else{ bandera = false; } return bandera; } public boolean Lectura(String obtenLinea, int linea){ varia = new Variables(); varia.setIdentificadores(llist); String aux[] = obtenLinea.split("\\("); String variable; boolean ban = true; if(aux[0].equals(supm[5])){ if(aux[1].matches("[a-zA-Z]+[\\)][;]")){ String valor = aux[1].replaceAll("\\);", ""); if(!varia.buscIgualdad(valor)){ varia.ModificaValIdentificador(valor.toLowerCase(), "0", "L"); bandera = true; } else{ System.err.println("Imposible leer "+valor.toUpperCase()+" Error en la linea:"+linea); } } else { bandera = false; } } else{ bandera = false; } return bandera; } public boolean Buscsupm(String verLinea){ boolean ban = true; String borra = verLinea.replaceAll("[\\s]", ""); for (int i = 0; i < 10; i++) { } return ban; } public LinkedList getLLisDesc(){ LinkedList ll = new LinkedList(); ll = this.llist; return ll; } }
DarkCeron/sweetmeat_candy
src/AnalisisLexico/DesCicloMain.java
Java
gpl-2.0
5,455
package ru.svalov.ma.planner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.svalov.ma.data.tempo.PlannedVacation; import ru.svalov.ma.model.CalendarEvent; import ru.svalov.ma.model.CalendarEvents; import ru.svalov.ma.model.Employee; import ru.svalov.ma.model.EventType; import ru.svalov.ma.planner.tempo.VacationService; import ru.svalov.util.JavaTimeUtils; import java.time.LocalDate; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.time.temporal.ChronoUnit.DAYS; public class VacationReplicationService { private static final Logger LOGGER = LoggerFactory.getLogger(VacationReplicationService.class); private CalendarEventsService holidayEventService; private VacationService vacationService; public VacationReplicationService(final CalendarEventsService holidayEventService, final VacationService vacationService) { this.holidayEventService = holidayEventService; this.vacationService = vacationService; } public void replicateVacations(List<Employee> users, LocalDate start, LocalDate end) { List<PlannedVacation> tempoLabors = users.stream().map(Employee::getLogin).map(user -> vacationService.getUserLabors(user, start, end)) .flatMap(List::stream).collect(Collectors.toList()); final CalendarEvents calendarEvents = holidayEventService.get(start, end); Stream.iterate(start, d -> d.plusDays(1)) .limit(start.until(end, DAYS)) .forEach(currentDate -> { final List<CalendarEvent> eventsToRemove = calendarEvents.get(currentDate, EventType.VACATION); eventsToRemove.forEach(ev -> { final long usersCount = users.stream().filter(u -> u.getLogin().equals(ev.getSubject())).count(); if (usersCount > 0) holidayEventService.delete(ev.getId()); }); createNewVacationEvent(users, tempoLabors, currentDate); }); } private void createNewVacationEvent(final List<Employee> users, final List<PlannedVacation> tempoVacs, final LocalDate currentDate) { tempoVacs.stream().filter(vac -> JavaTimeUtils.isInPeriod(currentDate, vac.getStart(), vac.getEnd())).forEach (plannedVacation -> { Optional<Employee> employee = users.stream().filter(user -> user.getLogin().equalsIgnoreCase(plannedVacation.getAssignee().getKey ())).findFirst(); if (!employee.isPresent()) { LOGGER.error("Can't find employee with login: {}", plannedVacation.getAssignee().getKey()); return; } final CalendarEvent event = new CalendarEvent(); event.setDate(currentDate); event.setType(EventType.VACATION); event.setSubject(plannedVacation.getAssignee().getKey()); event.setAttendees(Collections.singletonList(employee.get())); holidayEventService.create(event); }); } }
subzero0x1/SDMA
planner/src/main/java/ru/svalov/ma/planner/VacationReplicationService.java
Java
gpl-2.0
3,248
goog.provide('ol.control.FullScreen'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.classlist'); goog.require('goog.dom.fullscreen'); goog.require('goog.dom.fullscreen.EventType'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('ol'); goog.require('ol.control.Control'); goog.require('ol.css'); /** * @classdesc * Provides a button that when clicked fills up the full screen with the map. * When in full screen mode, a close button is shown to exit full screen mode. * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to * toggle the map in full screen mode. * * * @constructor * @extends {ol.control.Control} * @param {olx.control.FullScreenOptions=} opt_options Options. * @api stable */ ol.control.FullScreen = function(opt_options) { var options = opt_options ? opt_options : {}; /** * @private * @type {string} */ this.cssClassName_ = options.className ? options.className : 'ol-full-screen'; var label = options.label ? options.label : '\u2922'; /** * @private * @type {Node} */ this.labelNode_ = goog.isString(label) ? document.createTextNode(label) : label; var labelActive = options.labelActive ? options.labelActive : '\u00d7'; /** * @private * @type {Node} */ this.labelActiveNode_ = goog.isString(labelActive) ? document.createTextNode(labelActive) : labelActive; var tipLabel = options.tipLabel ? options.tipLabel : 'Toggle full-screen'; var button = goog.dom.createDom('BUTTON', { 'class': this.cssClassName_ + '-' + goog.dom.fullscreen.isFullScreen(), 'type': 'button', 'title': tipLabel }, this.labelNode_); goog.events.listen(button, goog.events.EventType.CLICK, this.handleClick_, false, this); goog.events.listen(goog.global.document, goog.dom.fullscreen.EventType.CHANGE, this.handleFullScreenChange_, false, this); var cssClasses = this.cssClassName_ + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' + ol.css.CLASS_CONTROL + ' ' + (!goog.dom.fullscreen.isSupported() ? ol.css.CLASS_UNSUPPORTED : ''); var element = goog.dom.createDom('DIV', cssClasses, button); goog.base(this, { element: element, target: options.target }); /** * @private * @type {boolean} */ this.keys_ = options.keys !== undefined ? options.keys : false; }; goog.inherits(ol.control.FullScreen, ol.control.Control); /** * @param {goog.events.BrowserEvent} event The event to handle * @private */ ol.control.FullScreen.prototype.handleClick_ = function(event) { event.preventDefault(); this.handleFullScreen_(); }; /** * @private */ ol.control.FullScreen.prototype.handleFullScreen_ = function() { if (!goog.dom.fullscreen.isSupported()) { return; } var map = this.getMap(); if (!map) { return; } if (goog.dom.fullscreen.isFullScreen()) { goog.dom.fullscreen.exitFullScreen(); } else { var target = map.getTarget(); goog.asserts.assert(target, 'target should be defined'); var element = goog.dom.getElement(target); goog.asserts.assert(element, 'element should be defined'); if (this.keys_) { goog.dom.fullscreen.requestFullScreenWithKeys(element); } else { goog.dom.fullscreen.requestFullScreen(element); } } }; /** * @private */ ol.control.FullScreen.prototype.handleFullScreenChange_ = function() { var opened = this.cssClassName_ + '-true'; var closed = this.cssClassName_ + '-false'; var button = goog.dom.getFirstElementChild(this.element); var map = this.getMap(); if (goog.dom.fullscreen.isFullScreen()) { goog.dom.classlist.swap(button, closed, opened); goog.dom.replaceNode(this.labelActiveNode_, this.labelNode_); } else { goog.dom.classlist.swap(button, opened, closed); goog.dom.replaceNode(this.labelNode_, this.labelActiveNode_); } if (map) { map.updateSize(); } };
tutorielgeo/google-openlayers
ol/ol/control/fullscreencontrol.js
JavaScript
gpl-2.0
3,934
<?php namespace app\controllers; use Yii; use app\models\Expenses; use app\models\ExpensesSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\filters\AccessControl; use yii\filters\AccessRule; use kartik\widgets\Growl; use app\models\User; /** * ExpensesController implements the CRUD actions for Expenses model. */ class ExpensesController extends Controller { public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), // We will override the default rule config with the new AccessRule class 'ruleConfig' => [ 'class' => AccessRule::className(), ], 'only' => ['create', 'update', 'delete'], 'rules' => [ [ 'actions' => ['create'], 'allow' => true, // Allow users, moderators and admins to create 'roles' => [ User::ROLE_MODERATOR, User::ROLE_ADMIN ], ], [ 'actions' => ['update'], 'allow' => true, // Allow moderators and admins to update 'roles' => [ User::ROLE_MODERATOR, User::ROLE_ADMIN ], ], [ 'actions' => ['delete'], 'allow' => true, // Allow admins to delete 'roles' => [ User::ROLE_ADMIN ], ], ], ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Lists all Expenses models. * @return mixed */ public function actionIndex() { $searchModel = new ExpensesSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Expenses model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Expenses model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Expenses(); $e_id = ""; //Get the expense id if(isset($_POST['Expenses'])){ $model->attributes = $_POST['Expenses']; $hs = $model->expense_id; //sql to insert bank charges and water charges to other expenses $sql = "INSERT INTO expenses "; } if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->getSession()->setFlash('success', [ 'type' => Growl::TYPE_SUCCESS, 'duration' => 12000, 'icon' => 'fa fa-users', 'message' => 'Save was successful', 'title' => '', 'positonY' => 'bottom', 'positonX' => 'left' ]); return $this->redirect(['expenses/create']); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Expenses model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->getSession()->setFlash('success', [ 'type' => Growl::TYPE_GROWL, 'duration' => 12000, 'icon' => 'fa fa-users', 'message' => 'Update was successful', 'positonY' => 'bottom', 'positonX' => 'left' ]); return $this->redirect(['view', 'id' => $model->expense_id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Expenses model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Expenses model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Expenses the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Expenses::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
mirr254/paki
controllers/ExpensesController.php
PHP
gpl-2.0
5,396