repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
mlopezFC/flow
flow-server/src/test/java/com/vaadin/flow/component/ComponentTest.java
/* * Copyright 2000-2021 <NAME>. * * 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.vaadin.flow.component; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import com.vaadin.flow.component.dependency.JavaScript; import com.vaadin.flow.component.dependency.StyleSheet; import com.vaadin.flow.component.dependency.Uses; import com.vaadin.flow.component.internal.DependencyList; import com.vaadin.flow.component.internal.UIInternals; import com.vaadin.flow.dom.DisabledUpdateMode; import com.vaadin.flow.dom.DomEvent; import com.vaadin.flow.dom.Element; import com.vaadin.flow.dom.ElementFactory; import com.vaadin.flow.internal.nodefeature.ElementListenerMap; import com.vaadin.flow.server.MockServletServiceSessionSetup; import com.vaadin.flow.server.MockVaadinServletService; import com.vaadin.flow.server.VaadinSession; import com.vaadin.flow.shared.Registration; import com.vaadin.flow.shared.ui.Dependency; import com.vaadin.tests.util.MockDeploymentConfiguration; import com.vaadin.tests.util.MockUI; import com.vaadin.tests.util.TestUtil; import elemental.json.Json; public class ComponentTest { private UI ui; @After public void checkThreadLocal() { Assert.assertNull(Component.elementToMapTo.get()); } @com.vaadin.flow.component.DomEvent("foo") public static class TestDomEvent extends ComponentEvent<Component> { public TestDomEvent(Component source, boolean fromClient) { super(source, fromClient); } } @com.vaadin.flow.component.DomEvent(value = "foo", allowUpdates = DisabledUpdateMode.ALWAYS) public static class EnabledDomEvent extends ComponentEvent<Component> { public EnabledDomEvent(Component source, boolean fromClient) { super(source, fromClient); } } @Tag("div") public static class TestDiv extends Component { @Synchronize(value = "bar", property = "baz", allowUpdates = DisabledUpdateMode.ALWAYS) public String getFoo() { return null; } @Synchronize(value = "foo", property = "bar") public String getBaz() { return null; } } @Tag("div") public static class EnabledDiv extends Component implements HasComponents { } @Tag("div") public static class TestComponentWhichHasComponentField extends Component { private TestButton button = new TestButton(); public TestComponentWhichHasComponentField() { getElement().appendChild(button.getElement()); } } public static class TestComponentWhichUsesElementConstructor extends Component { public TestComponentWhichUsesElementConstructor() { super(new Element("my-element")); } } public static class TestComponentWhichUsesNullElementConstructor extends Component { public TestComponentWhichUsesNullElementConstructor() { super(null); } } @Tag("div") public static class TestComponentWhichCreatesComponentInConstructor extends Component { public TestComponentWhichCreatesComponentInConstructor() { getElement().appendChild(new TestButton().getElement()); } } @Tag("button") public static class TestButton extends Component { } @Tag("button") public static class TestOtherButton extends Component { } private Component divWithTextComponent; private Component parentDivComponent; private Component child1SpanComponent; private Component child2InputComponent; private Component shadowRootParent; private Component shadowChild; private UI testUI; private MockServletServiceSessionSetup mocks; public interface TracksAttachDetach { default void track() { if (this instanceof Component) { ((Component) this).addAttachListener( event -> getAttachEvents().incrementAndGet()); ((Component) this).addDetachListener( event -> getDetachEvents().incrementAndGet()); } else { throw new IllegalStateException("Cannot track a non-component"); } } AtomicInteger getAttachEvents(); AtomicInteger getDetachEvents(); default void assertAttachEvents(int attachEvents) { Assert.assertEquals(attachEvents, getAttachEvents().get()); } default void assertDetachEvents(int detachEvents) { Assert.assertEquals(detachEvents, getDetachEvents().get()); } } public static abstract class TracksAttachDetachComponent extends Component implements TracksAttachDetach { private AtomicInteger attachEvents = new AtomicInteger(); private AtomicInteger detachEvents = new AtomicInteger(); public TracksAttachDetachComponent() { } public TracksAttachDetachComponent(Element element) { super(element); } @Override public AtomicInteger getAttachEvents() { return attachEvents; } @Override public AtomicInteger getDetachEvents() { return detachEvents; } } public static class TestComponent extends TracksAttachDetachComponent { public TestComponent() { this(ElementFactory.createDiv()); } public TestComponent(Element element) { super(element); } @Override public String toString() { return getElement().getText(); } @Override public void fireEvent(ComponentEvent<?> componentEvent) { super.fireEvent(componentEvent); } @Override public <T extends ComponentEvent<?>> Registration addListener( Class<T> eventType, ComponentEventListener<T> listener) { return super.addListener(eventType, listener); } @Override public ComponentEventBus getEventBus() { return super.getEventBus(); } } @Tag(Tag.DIV) private static class TestComponentWithTag extends Component { } private static class TestComponentWithInheritedTag extends TestComponentWithTag { } @Tag("") private static class TestComponentWithEmptyTag extends Component { } private static class TestComponentWithoutTag extends Component { } private static class BrokenComponent extends Component { public BrokenComponent() { super(null); } } private static class TestComponentContainer extends TestComponent { public TestComponentContainer() { } public void add(Component c) { getElement().appendChild(c.getElement()); } public void remove(Component c) { getElement().removeChild(c.getElement()); } } @Before public void setup() throws Exception { divWithTextComponent = new TestComponent( ElementFactory.createDiv("Test component")); parentDivComponent = new TestComponent(ElementFactory.createDiv()); child1SpanComponent = new TestComponent( ElementFactory.createSpan("Span")); child2InputComponent = new TestComponent(ElementFactory.createInput()); parentDivComponent.getElement().appendChild( child1SpanComponent.getElement(), child2InputComponent.getElement()); mocks = new MockServletServiceSessionSetup(); VaadinSession session = mocks.getSession(); ui = new UI() { @Override public VaadinSession getSession() { return session; } }; ui.getInternals().setSession(session); UI.setCurrent(ui); } @After public void tearDown() { UI.setCurrent(null); mocks.cleanup(); } @Test public void getElement() { Assert.assertEquals(Tag.DIV, divWithTextComponent.getElement().getTag()); Assert.assertEquals("Test component", divWithTextComponent.getElement().getTextRecursively()); } @Test public void getParentForAttachedComponent() { Assert.assertEquals(parentDivComponent, child1SpanComponent.getParent().get()); Assert.assertEquals(parentDivComponent, child2InputComponent.getParent().get()); } @Test public void getUIForAttachedComponentInShadowRoot() { shadowRootParent = new TestComponent(ElementFactory.createDiv()); shadowRootParent.getElement().attachShadow(); shadowChild = new TestComponent(ElementFactory.createSpan()); shadowRootParent.getElement().getShadowRoot().get() .appendChild(shadowChild.getElement()); testUI = new UI(); testUI.add(shadowRootParent); Assert.assertEquals(testUI, shadowChild.getUI().get()); } @Test public void getParentForDetachedComponent() { Assert.assertFalse(parentDivComponent.getParent().isPresent()); } @Test public void defaultGetChildrenDirectlyAttached() { assertChildren(parentDivComponent, child1SpanComponent, child2InputComponent); } public static void assertChildren(Component parent, Component... expectedChildren) { List<Component> children = parent.getChildren() .collect(Collectors.toList()); Assert.assertArrayEquals(expectedChildren, children.toArray()); for (Component c : children) { Assert.assertEquals(c.getParent().get(), parent); } } @Test public void defaultGetChildrenMultiple() { // parent // * level1 // ** child1 // ** child2 Element level1 = ElementFactory.createDiv("Level1"); parentDivComponent.getElement().appendChild(level1); level1.appendChild(child1SpanComponent.getElement()); level1.appendChild(child2InputComponent.getElement()); assertChildren(parentDivComponent, child1SpanComponent, child2InputComponent); } @Test public void defaultGetChildrenDirectlyDeepElementHierarchy() { // parent // * level1 // ** level2 // *** child1 // * child2 // * level1b // ** child3 TestComponent parent = new TestComponent(ElementFactory.createDiv()); TestComponent child1 = new TestComponent( ElementFactory.createDiv("Child1")); TestComponent child2 = new TestComponent( ElementFactory.createDiv("Child2")); TestComponent child3 = new TestComponent( ElementFactory.createDiv("Child2")); Element parentElement = parent.getElement(); parentElement.appendChild( new Element("level1").appendChild( new Element("level2").appendChild(child1.getElement())), child2.getElement(), new Element("level1b").appendChild(child3.getElement())); List<Component> children = parent.getChildren() .collect(Collectors.toList()); Assert.assertArrayEquals(new Component[] { child1, child2, child3 }, children.toArray()); } @Test public void defaultGetChildrenNoChildren() { List<Component> children = parentDivComponent.getChildren() .collect(Collectors.toList()); Assert.assertArrayEquals( new Component[] { child1SpanComponent, child2InputComponent }, children.toArray()); } @Test(expected = AssertionError.class) public void attachBrokenComponent() { BrokenComponent c = new BrokenComponent(); TestComponentContainer tc = new TestComponentContainer(); tc.add(c); } @Test public void setElement() { Component c = new Component(null) { }; Element element = ElementFactory.createDiv(); Component.setElement(c, element); Assert.assertEquals(c, element.getComponent().get()); Assert.assertEquals(element, c.getElement()); } @Test(expected = IllegalArgumentException.class) public void setElementNull() { Component c = new Component(null) { }; Component.setElement(c, null); } @Test(expected = IllegalStateException.class) public void setElementTwice() { Component c = new Component(null) { }; Element element = ElementFactory.createDiv(); Component.setElement(c, element); Component.setElement(c, element); } @Test public void createComponentWithTag() { Component component = new TestComponentWithTag(); Assert.assertEquals(Tag.DIV, component.getElement().getTag()); } @Test public void createComponentWithInheritedTag() { Component component = new TestComponentWithInheritedTag(); Assert.assertEquals(Tag.DIV, component.getElement().getTag()); } @Test(expected = IllegalStateException.class) public void createComponentWithEmptyTag() { new TestComponentWithEmptyTag(); } @Test(expected = IllegalStateException.class) public void createComponentWithoutTag() { new TestComponentWithoutTag(); } @Test public void getUI_noParent() { TestComponent c = new TestComponent(); assertEmpty(c.getUI()); } @Test public void getUI_detachedParent() { TestComponentContainer parent = new TestComponentContainer(); TestComponent child = new TestComponent(); parent.add(child); assertEmpty(child.getUI()); } @Test public void getUI_attachedToUI() { TestComponent child = new TestComponent(); UI ui = new UI(); ui.add(child); Assert.assertEquals(ui, child.getUI().get()); } @Test public void getUI_attachedThroughParent() { TestComponentContainer parent = new TestComponentContainer(); TestComponent child = new TestComponent(); parent.add(child); UI ui = new UI(); ui.add(parent); Assert.assertEquals(ui, child.getUI().get()); } private void assertEmpty(Optional<?> optional) { Assert.assertEquals("Optional should be empty but is " + optional, Optional.empty(), optional); } @Test public void testAttachDetachListeners_parentAttachDetach_childListenersTriggered() { UI ui = new UI(); TestComponentContainer parent = new TestComponentContainer(); TestComponentContainer child = new TestComponentContainer(); TestComponent grandChild = new TestComponent(); child.track(); Registration attachRegistrationHandle = grandChild.addAttachListener( event -> grandChild.getAttachEvents().incrementAndGet()); Registration detachRegistrationHandle = grandChild.addDetachListener( event -> grandChild.getDetachEvents().incrementAndGet()); parent.add(child); child.add(grandChild); child.assertAttachEvents(0); grandChild.assertAttachEvents(0); ui.add(parent); child.assertAttachEvents(1); grandChild.assertAttachEvents(1); child.assertDetachEvents(0); grandChild.assertDetachEvents(0); ui.remove(parent); parent.remove(child); child.assertAttachEvents(1); grandChild.assertAttachEvents(1); child.assertDetachEvents(1); grandChild.assertDetachEvents(1); ui.add(parent); parent.add(child); child.assertAttachEvents(2); grandChild.assertAttachEvents(2); child.assertDetachEvents(1); grandChild.assertDetachEvents(1); ui.remove(parent); child.assertAttachEvents(2); grandChild.assertAttachEvents(2); child.assertDetachEvents(2); grandChild.assertDetachEvents(2); attachRegistrationHandle.remove(); detachRegistrationHandle.remove(); ui.add(child); child.assertAttachEvents(3); grandChild.assertAttachEvents(2); ui.remove(child); child.assertDetachEvents(3); grandChild.assertDetachEvents(2); } @Test public void testAttachListener_eventOrder_childFirst() { UI ui = new UI(); TestComponentContainer parent = new TestComponentContainer(); TestComponent child = new TestComponent(); child.track(); parent.track(); child.addAttachListener(event -> { Assert.assertEquals(0, parent.getAttachEvents().get()); }); parent.addAttachListener(event -> { Assert.assertEquals(1, child.getAttachEvents().get()); }); parent.add(child); child.assertAttachEvents(0); parent.assertAttachEvents(0); ui.add(parent); child.assertAttachEvents(1); parent.assertAttachEvents(1); } @Test public void testDetachListener_eventOrder_childFirst() { UI ui = new UI(); TestComponentContainer parent = new TestComponentContainer(); TestComponent child = new TestComponent(); child.track(); parent.track(); child.addDetachListener(event -> { Assert.assertEquals(0, parent.getDetachEvents().get()); }); parent.addDetachListener(event -> { Assert.assertEquals(1, child.getDetachEvents().get()); }); parent.add(child); ui.add(parent); child.assertDetachEvents(0); parent.assertDetachEvents(0); ui.remove(parent); child.assertDetachEvents(1); parent.assertDetachEvents(1); } @Test public void testAttachDetach_elementMoved_bothEventsTriggered() { UI ui = new UI(); TestComponentContainer parent = new TestComponentContainer(); TestComponent child = new TestComponent(); parent.add(child); ui.add(parent); child.track(); child.addAttachListener(event -> { Assert.assertEquals(1, child.getDetachEvents().get()); }); child.addDetachListener(event -> { Assert.assertEquals(0, child.getAttachEvents().get()); }); ui.add(child); child.assertAttachEvents(1); child.assertDetachEvents(1); } @Test public void testAttachDetachEvent_uiCanBeFound() { UI ui = new UI(); TestComponent testComponent = new TestComponent(); testComponent.track(); testComponent.addAttachListener(event -> Assert.assertEquals(ui, event.getSource().getUI().get())); testComponent.addDetachListener(event -> Assert.assertEquals(ui, event.getSource().getUI().get())); testComponent.assertAttachEvents(0); ui.add(testComponent); testComponent.assertAttachEvents(1); testComponent.assertDetachEvents(0); ui.remove(testComponent); testComponent.assertDetachEvents(1); } @Test public void testOnAttachOnDetachAndEventsOrder() { List<String> triggered = new ArrayList<>(); Component customComponent = new Component(new Element("div")) { @Override protected void onAttach(AttachEvent attachEvent) { triggered.add("onAttach"); } @Override protected void onDetach(DetachEvent detachEvent) { triggered.add("onDetach"); } }; customComponent .addAttachListener(event -> triggered.add("attachEvent")); customComponent .addDetachListener(event -> triggered.add("detachEvent")); UI ui = new UI(); ui.add(customComponent); TestUtil.assertArrays(triggered.toArray(), new String[] { "onAttach", "attachEvent" }); triggered.clear(); ui.remove(customComponent); TestUtil.assertArrays(triggered.toArray(), new String[] { "onDetach", "detachEvent" }); TestComponentContainer container = new TestComponentContainer(); ui.add(customComponent, container); triggered.clear(); container.add(customComponent); TestUtil.assertArrays(triggered.toArray(), new String[] { "onDetach", "detachEvent", "onAttach", "attachEvent" }); } @Test public void testUIInitialAttach() { AtomicBoolean initialAttach = new AtomicBoolean(false); UI ui = new UI(); ui.addAttachListener(e -> { initialAttach.set(e.isInitialAttach()); }); MockDeploymentConfiguration config = new MockDeploymentConfiguration(); ui.getInternals().setSession( new VaadinSession(new MockVaadinServletService(config))); Assert.assertTrue(initialAttach.get()); // UI is never detached and reattached } @Test public void testInitialAttach() { AtomicBoolean initialAttach = new AtomicBoolean(false); TestComponent c = new TestComponent(); c.addAttachListener(e -> { initialAttach.set(e.isInitialAttach()); }); UI ui = new UI(); ui.add(c); Assert.assertTrue(initialAttach.get()); } @Test public void testSecondAttach() { AtomicBoolean initialAttach = new AtomicBoolean(false); TestComponent c = new TestComponent(); c.addAttachListener(e -> { initialAttach.set(e.isInitialAttach()); }); UI ui = new UI(); ui.add(c); ui.remove(c); ui.add(c); Assert.assertFalse(initialAttach.get()); } /** * Tests {@link Component#isAttached}. */ @Test public void testIsAttached() { UI ui = new UI(); // ui is initially attached Assert.assertTrue(ui.isAttached()); TestComponentContainer parent = new TestComponentContainer(); TestComponentContainer child = new TestComponentContainer(); TestComponent grandChild = new TestComponent(); child.track(); grandChild.addAttachListener( event -> Assert.assertTrue(grandChild.isAttached())); grandChild.addDetachListener( event -> grandChild.getDetachEvents().incrementAndGet()); parent.add(child); child.add(grandChild); Assert.assertFalse(parent.isAttached()); Assert.assertFalse(child.isAttached()); Assert.assertFalse(grandChild.isAttached()); ui.add(parent); Assert.assertTrue(parent.isAttached()); Assert.assertTrue(child.isAttached()); Assert.assertTrue(grandChild.isAttached()); ui.remove(parent); Assert.assertFalse(parent.isAttached()); Assert.assertFalse(child.isAttached()); Assert.assertFalse(grandChild.isAttached()); ui.add(parent); Assert.assertTrue(parent.isAttached()); Assert.assertTrue(child.isAttached()); Assert.assertTrue(grandChild.isAttached()); // Mock closing of UI after request handled ui.getInternals().setSession(Mockito.mock(VaadinSession.class)); ui.close(); ui.getInternals().setSession(null); Assert.assertFalse(parent.isAttached()); Assert.assertFalse(child.isAttached()); Assert.assertFalse(grandChild.isAttached()); Assert.assertFalse(ui.isAttached()); } @Test(expected = IllegalArgumentException.class) public void wrapNullComponentType() { new Element("div").as(null); } @Test(expected = IllegalArgumentException.class) public void wrapWrongTag() { Element foo = new Element("foo"); foo.as(TestDiv.class); } @Test(expected = IllegalStateException.class) public void wrappedComponentGetParent() { Element div = new Element("div"); Element button = new Element("button"); div.appendChild(button); div.as(TestDiv.class); button.as(TestButton.class).getParent(); } @Test(expected = IllegalStateException.class) public void wrappedComponentGetChildren() { Element div = new Element("div"); Element button = new Element("button"); div.appendChild(button); button.as(TestButton.class); div.as(TestDiv.class).getChildren(); } @Test public void componentFromHierarchy() { Element div = new Element("div"); Element button = new Element("button"); div.appendChild(button); TestDiv testDiv = Component.from(div, TestDiv.class); TestButton testButton = Component.from(button, TestButton.class); Assert.assertEquals(testButton.getParent().get(), testDiv); Assert.assertTrue(testDiv.getChildren().anyMatch(c -> c == testButton)); } @Test public void wrappedComponentUsesElement() { Element div = new Element("div"); div.setAttribute("id", "foo"); Assert.assertEquals(Optional.of("foo"), div.as(TestDiv.class).getId()); } @Test public void wrappedComponentModifyElement() { Element div = new Element("div"); div.as(TestDiv.class).setId("foo"); Assert.assertEquals("foo", div.getAttribute("id")); } @Test public void wrapToExistingComponent() { TestButton button = new TestButton(); TestButton button2 = button.getElement().as(TestButton.class); button.setId("id1"); Assert.assertEquals(Optional.of("id1"), button2.getId()); Assert.assertEquals(Optional.of("id1"), button.getId()); } @Test public void wrapDifferentTypeToExistingComponent() { TestButton button = new TestButton(); TestOtherButton button2 = button.getElement().as(TestOtherButton.class); button.setId("id1"); Assert.assertEquals(Optional.of("id1"), button2.getId()); Assert.assertEquals(Optional.of("id1"), button.getId()); } @Test(expected = IllegalArgumentException.class) public void mapToExistingComponent() { TestButton button = new TestButton(); Component.from(button.getElement(), TestButton.class); } @Test(expected = IllegalArgumentException.class) public void mapToNullComponentType() { Component.from(new Element("div"), null); } @Test(expected = IllegalArgumentException.class) public void mapFromNullElement() { Component.from(null, TestButton.class); } @Test public void mapToComponentWhichCreatesComponentInConstructor() { Element e = new Element("div"); TestComponentWhichCreatesComponentInConstructor c = Component.from(e, TestComponentWhichCreatesComponentInConstructor.class); Element buttonElement = c.getElement().getChild(0); Assert.assertEquals(e, c.getElement()); Assert.assertNotEquals(e, buttonElement); Assert.assertEquals("button", buttonElement.getTag()); } @Test public void mapToComponentWhichHasComponentField() { Element e = new Element("div"); TestComponentWhichHasComponentField c = Component.from(e, TestComponentWhichHasComponentField.class); Element buttonElement = c.getElement().getChild(0); Assert.assertEquals(e, c.getElement()); Assert.assertNotEquals(e, buttonElement); Assert.assertEquals("button", buttonElement.getTag()); } @Test public void mapToComponentWithElementConstructor() { Element e = new Element("my-element"); TestComponentWhichUsesElementConstructor c = Component.from(e, TestComponentWhichUsesElementConstructor.class); Assert.assertSame(e, c.getElement()); Assert.assertSame(c, e.getComponent().get()); } @Test public void mapToComponentWithNullElementConstructor() { Element e = new Element("div"); TestComponentWhichUsesNullElementConstructor c = Component.from(e, TestComponentWhichUsesNullElementConstructor.class); Assert.assertSame(e, c.getElement()); Assert.assertSame(c, e.getComponent().get()); } @Tag("div") public static class SynchronizePropertyOnChangeComponent extends Component { @Synchronize("change") public String getFoo() { return ""; } } public static class SynchronizePropertyUsingElementConstructor extends Component { public SynchronizePropertyUsingElementConstructor() { super(null); } @Synchronize("change") public String getFoo() { return ""; } public void customInit() { setElement(this, new Element("Span")); } } @Tag("div") public static class SynchronizePropertyOnChangeGivenPropertyComponent extends Component { @Synchronize(value = "change", property = "bar") public String getFoo() { return ""; } } @Tag("div") public static class SynchronizePropertyOnMultipleEventsComponent extends Component { @Synchronize(value = { "input", "blur" }) public String getFoo() { return ""; } } @Tag("div") public static class SynchronizeOnNonGetterComponent extends Component { @Synchronize("change") public String doWork() { return ""; } } private void assertSynchronizedProperties(String domEventName, Element element, String... properties) { Set<String> expected = Stream.of(properties) .collect(Collectors.toSet()); Set<String> expressions = element.getNode() .getFeature(ElementListenerMap.class) .getExpressions(domEventName); Assert.assertEquals(expected, expressions); } @Test public void synchronizePropertyBasedOnGetterName() { SynchronizePropertyOnChangeComponent component = new SynchronizePropertyOnChangeComponent(); Element element = component.getElement(); assertSynchronizedProperties("change", element, "}foo"); } @Test public void synchronizePropertyElementConstructor() { SynchronizePropertyUsingElementConstructor component = new SynchronizePropertyUsingElementConstructor(); component.customInit(); Element element = component.getElement(); assertSynchronizedProperties("change", element, "}foo"); } @Test public void componentMetaDataCached() { ComponentUtil.componentMetaDataCache.clear(); Assert.assertFalse( ComponentUtil.componentMetaDataCache.contains(Text.class)); new Text("foobar"); Assert.assertTrue( ComponentUtil.componentMetaDataCache.contains(Text.class)); } @Test public void synchronizePropertyWithPropertyName() { SynchronizePropertyOnChangeGivenPropertyComponent component = new SynchronizePropertyOnChangeGivenPropertyComponent(); Element element = component.getElement(); assertSynchronizedProperties("change", element, "}bar"); } @Test public void synchronizePropertyWithMultipleEvents() { SynchronizePropertyOnMultipleEventsComponent component = new SynchronizePropertyOnMultipleEventsComponent(); Element element = component.getElement(); assertSynchronizedProperties("input", element, "}foo"); assertSynchronizedProperties("blur", element, "}foo"); } @Test(expected = IllegalStateException.class) public void synchronizeOnNonGetter() { new SynchronizeOnNonGetterComponent(); } @Tag("div") @JavaScript("js.js") @StyleSheet("css.css") public static class ComponentWithDependencies extends Component { } @Tag("span") @Uses(ComponentWithDependencies.class) @JavaScript("uses.js") public static class UsesComponentWithDependencies extends Component { } @Tag("span") @Uses(UsesComponentWithDependencies.class) public static class UsesUsesComponentWithDependencies extends Component { } @Tag("div") @StyleSheet("css1.css") @Uses(CircularDependencies2.class) public static class CircularDependencies1 extends Component { } @Tag("div") @StyleSheet("css2.css") @Uses(CircularDependencies1.class) public static class CircularDependencies2 extends Component { } @Test public void usesComponent() { UI ui = UI.getCurrent(); ui.getInternals() .addComponentDependencies(UsesComponentWithDependencies.class); Map<String, Dependency> pendingDependencies = getDependenciesMap( ui.getInternals().getDependencyList().getPendingSendToClient()); Assert.assertEquals(1, pendingDependencies.size()); assertDependency(Dependency.Type.STYLESHEET, "css.css", pendingDependencies); } @Test public void usesChain() { UIInternals internals = UI.getCurrent().getInternals(); internals.addComponentDependencies( UsesUsesComponentWithDependencies.class); Map<String, Dependency> pendingDependencies = getDependenciesMap( internals.getDependencyList().getPendingSendToClient()); Assert.assertEquals(1, pendingDependencies.size()); assertDependency(Dependency.Type.STYLESHEET, "css.css", pendingDependencies); } @Test public void circularDependencies() { UIInternals internals = new MockUI().getInternals(); DependencyList dependencyList = internals.getDependencyList(); internals.addComponentDependencies(CircularDependencies1.class); Map<String, Dependency> pendingDependencies = getDependenciesMap( dependencyList.getPendingSendToClient()); Assert.assertEquals(2, pendingDependencies.size()); assertDependency(Dependency.Type.STYLESHEET, "css1.css", pendingDependencies); assertDependency(Dependency.Type.STYLESHEET, "css2.css", pendingDependencies); internals = new MockUI().getInternals(); dependencyList = internals.getDependencyList(); internals.addComponentDependencies(CircularDependencies2.class); pendingDependencies = getDependenciesMap( dependencyList.getPendingSendToClient()); Assert.assertEquals(2, pendingDependencies.size()); assertDependency(Dependency.Type.STYLESHEET, "css1.css", pendingDependencies); assertDependency(Dependency.Type.STYLESHEET, "css2.css", pendingDependencies); } @Test public void noJsDependenciesAreAdded() { UIInternals internals = new MockUI().getInternals(); DependencyList dependencyList = internals.getDependencyList(); internals.addComponentDependencies(ComponentWithDependencies.class); Map<String, Dependency> pendingDependencies = getDependenciesMap( dependencyList.getPendingSendToClient()); Assert.assertEquals(1, pendingDependencies.size()); assertDependency(Dependency.Type.STYLESHEET, "css.css", pendingDependencies); } @Test public void declarativeSyncProperties_propertiesAreRegisteredWithProperDisabledUpdateMode() { TestDiv div = new TestDiv(); ElementListenerMap feature = div.getElement().getNode() .getFeature(ElementListenerMap.class); Set<String> props = feature.getExpressions("bar"); Assert.assertEquals(1, props.size()); Assert.assertTrue(props.contains("}baz")); Assert.assertEquals(DisabledUpdateMode.ALWAYS, feature.getPropertySynchronizationMode("baz")); props = feature.getExpressions("foo"); Assert.assertEquals(1, props.size()); Assert.assertTrue(props.contains("}bar")); Assert.assertEquals(DisabledUpdateMode.ONLY_WHEN_ENABLED, feature.getPropertySynchronizationMode("bar")); } @Test public void enabledComponent_fireDomEvent_listenerReceivesEvent() { TestDiv div = new TestDiv(); AtomicInteger count = new AtomicInteger(); div.addListener(TestDomEvent.class, vent -> count.incrementAndGet()); div.getElement().getNode().getFeature(ElementListenerMap.class) .fireEvent(createEvent("foo", div)); Assert.assertEquals(1, count.get()); } @Test public void disabledComponent_fireDomEvent_listenerDoesntReceivesEvent() { TestDiv div = new TestDiv(); div.getElement().setEnabled(false); AtomicInteger count = new AtomicInteger(); div.addListener(TestDomEvent.class, vent -> count.incrementAndGet()); div.getElement().getNode().getFeature(ElementListenerMap.class) .fireEvent(createEvent("foo", div)); Assert.assertEquals(0, count.get()); } @Test public void implicityDisabledComponent_fireDomEvent_listenerDoesntReceivesEvent() { TestDiv div = new TestDiv(); UI ui = new UI(); ui.add(div); ui.setEnabled(false); AtomicInteger count = new AtomicInteger(); div.addListener(TestDomEvent.class, event -> count.incrementAndGet()); div.getElement().getNode().getFeature(ElementListenerMap.class) .fireEvent(createEvent("foo", div)); Assert.assertEquals(0, count.get()); } @Test public void disabledComponent_fireAlwaysEnabledDomEvent_listenerReceivesEvent() { TestDiv div = new TestDiv(); div.getElement().setEnabled(false); AtomicInteger count = new AtomicInteger(); div.addListener(EnabledDomEvent.class, event -> count.incrementAndGet()); div.getElement().getNode().getFeature(ElementListenerMap.class) .fireEvent(createEvent("foo", div)); Assert.assertEquals(1, count.get()); } @Test public void removeOnRegistration_registrationIsIdempotent() { TestDiv div = new TestDiv(); Registration registration = div.addListener(ComponentEvent.class, (ComponentEventListener) event -> { }); registration.remove(); // It's still possible to call the same method one more time registration.remove(); } private DomEvent createEvent(String type, Component component) { return new DomEvent(component.getElement(), type, Json.createObject()); } private void assertDependency(Dependency.Type type, String url, Map<String, Dependency> pendingDependencies) { Dependency dependency = pendingDependencies.get(url); Assert.assertNotNull( "Could not locate a dependency object for url=" + url, dependency); Assert.assertEquals(type, dependency.getType()); Assert.assertEquals(url, dependency.getUrl()); } private Map<String, Dependency> getDependenciesMap( Collection<Dependency> dependencies) { return dependencies.stream().collect( Collectors.toMap(Dependency::getUrl, Function.identity())); } @Test // 3818 public void enabledStateChangeOnAttachCalledForParentState() { enabledStateChangeOnAttachCalledForParentState(false, (parent, child) -> parent.add(child)); } @Test // 7085 public void enabledStateChangeOnDisableParent() { enabledStateChangeOnAttachCalledForParentState(true, (parent, child) -> { parent.add(child); parent.setEnabled(false); }); } @Test public void enabledStateChangeOnAttachCalledForParentOfVirtualChildState() { enabledStateChangeOnAttachCalledForParentState(false, (parent, child) -> { Element wrapper = ElementFactory.createAnchor(); parent.getElement().appendVirtualChild(wrapper); wrapper.appendChild(child.getElement()); }); } @Test public void enabledStateChangeOnDisableParentOfVirtualChild() { enabledStateChangeOnAttachCalledForParentState(true, (parent, child) -> { Element wrapper = ElementFactory.createAnchor(); parent.getElement().appendVirtualChild(wrapper); wrapper.appendChild(child.getElement()); parent.setEnabled(false); }); } @Test // 3818 public void enabledStateChangeOnDetachReturnsOldState() { UI ui = new UI(); EnabledDiv parent = new EnabledDiv(); parent.setEnabled(false); ui.add(parent); AtomicReference<Boolean> stateChange = new AtomicReference<>(); EnabledDiv child = new EnabledDiv() { @Override public void onEnabledStateChanged(boolean enabled) { super.onEnabledStateChanged(enabled); stateChange.set(enabled); } }; Assert.assertFalse("Parent should be disabled", parent.isEnabled()); Assert.assertTrue("Child should be enabled.", child.isEnabled()); Assert.assertNull(child.getElement().getAttribute("disabled")); parent.add(child); Assert.assertFalse("After attach child should be disabled", child.isEnabled()); Assert.assertFalse("Disabled event should have triggered", stateChange.get()); Assert.assertNotNull(child.getElement().getAttribute("disabled")); parent.remove(child); Assert.assertTrue("After detach child should be enabled", child.isEnabled()); Assert.assertTrue("Enable event should have triggered", stateChange.get()); Assert.assertNull(child.getElement().getAttribute("disabled")); } @Test public void enabledStateChangeOnParentDetachReturnsOldState() { enabledStateChangeOnParentDetachReturnsOldState( (parent, child) -> parent.add(child)); } @Test public void enabledStateChangeOnParentOfVirtualChildDetachReturnsOldState() { enabledStateChangeOnParentDetachReturnsOldState((parent, child) -> { Element wrapper = ElementFactory.createAnchor(); parent.getElement().appendVirtualChild(wrapper); wrapper.appendChild(child.getElement()); }); } @Test // 3818 public void enabledStateChangeOnDetachChildKeepsDisabledState() { UI ui = new UI(); EnabledDiv parent = new EnabledDiv(); parent.setEnabled(false); ui.add(parent); AtomicReference<Boolean> stateChange = new AtomicReference<>(); EnabledDiv child = new EnabledDiv() { @Override public void onEnabledStateChanged(boolean enabled) { super.onEnabledStateChanged(enabled); stateChange.set(enabled); } }; child.setEnabled(false); // Clear state change from setEnabled stateChange.set(null); Assert.assertFalse("Parent should be disabled", parent.isEnabled()); Assert.assertFalse("Child should be enabled.", child.isEnabled()); Assert.assertNotNull(child.getElement().getAttribute("disabled")); parent.add(child); Assert.assertFalse("After attach child should be disabled", child.isEnabled()); Assert.assertNull("No change event should have fired", stateChange.get()); Assert.assertNotNull(child.getElement().getAttribute("disabled")); parent.remove(child); Assert.assertFalse("After detach child should still be disabled", child.isEnabled()); Assert.assertNull("No change event should have fired", stateChange.get()); Assert.assertNotNull(child.getElement().getAttribute("disabled")); } @Test // 3818 public void enabledStateChangeOnAttachAndDetachChildAndGrandChildrenAreNotified() { UI ui = new UI(); EnabledDiv parent = new EnabledDiv(); parent.setEnabled(false); ui.add(parent); AtomicReference<Boolean> stateChange = new AtomicReference<>(); EnabledDiv child = new EnabledDiv() { @Override public void onEnabledStateChanged(boolean enabled) { super.onEnabledStateChanged(enabled); stateChange.set(enabled); } }; AtomicReference<Boolean> grandStateChange = new AtomicReference<>(); EnabledDiv grandChild = new EnabledDiv() { @Override public void onEnabledStateChanged(boolean enabled) { super.onEnabledStateChanged(enabled); grandStateChange.set(enabled); } }; child.add(grandChild); Assert.assertFalse("Parent should be disabled", parent.isEnabled()); Assert.assertTrue("Child should be enabled.", child.isEnabled()); Assert.assertNull(child.getElement().getAttribute("disabled")); Assert.assertTrue("GrandChild should be enabled.", grandChild.isEnabled()); Assert.assertNull(grandChild.getElement().getAttribute("disabled")); parent.add(child); Assert.assertFalse("After attach child should be disabled", child.isEnabled()); Assert.assertFalse("Disabled event should have triggered", stateChange.get()); Assert.assertNotNull(child.getElement().getAttribute("disabled")); Assert.assertFalse("After attach GrandChild should be disabled", grandChild.isEnabled()); Assert.assertFalse("Disabled event should have triggered", grandStateChange.get()); Assert.assertNotNull(grandChild.getElement().getAttribute("disabled")); parent.remove(child); Assert.assertTrue("After detach child should be enabled", child.isEnabled()); Assert.assertTrue("Enable event should have triggered", stateChange.get()); Assert.assertNull(child.getElement().getAttribute("disabled")); Assert.assertTrue("After detach GrandChild should be enabled", grandChild.isEnabled()); Assert.assertTrue("GrandChild should have gotten true event", grandStateChange.get()); Assert.assertNull(grandChild.getElement().getAttribute("disabled")); } @Test // 3818 public void enabledStateChangeOnAttachAndDetachDisabledChildAndGrandChildAreDisabled() { UI ui = new UI(); EnabledDiv parent = new EnabledDiv(); parent.setEnabled(false); ui.add(parent); AtomicReference<Boolean> stateChange = new AtomicReference<>(); EnabledDiv child = new EnabledDiv() { @Override public void onEnabledStateChanged(boolean enabled) { super.onEnabledStateChanged(enabled); stateChange.set(enabled); } }; child.setEnabled(false); // Clear state change from setEnabled stateChange.set(null); AtomicReference<Boolean> grandStateChange = new AtomicReference<>(); EnabledDiv grandChild = new EnabledDiv() { @Override public void onEnabledStateChanged(boolean enabled) { super.onEnabledStateChanged(enabled); grandStateChange.set(enabled); } }; child.add(grandChild); Assert.assertFalse("Parent should be disabled", parent.isEnabled()); Assert.assertFalse("Child should be disabled.", child.isEnabled()); Assert.assertNotNull(child.getElement().getAttribute("disabled")); Assert.assertFalse("GrandChild should be disabled.", grandChild.isEnabled()); // note that add doesn't create an attach event as we are not connected // to the UI. Assert.assertNull(grandChild.getElement().getAttribute("disabled")); parent.add(child); Assert.assertFalse("After attach child should be disabled", child.isEnabled()); Assert.assertNull("Disabled event should have triggered", stateChange.get()); Assert.assertNotNull(child.getElement().getAttribute("disabled")); Assert.assertFalse("After attach GrandChild should be disabled", grandChild.isEnabled()); Assert.assertFalse("Disabled event should have triggered", grandStateChange.get()); Assert.assertNotNull(grandChild.getElement().getAttribute("disabled")); parent.remove(child); Assert.assertFalse("After detach child should be disabled", child.isEnabled()); Assert.assertNull("No change event should have been sent", stateChange.get()); Assert.assertFalse("After detach GrandChild should be disabled", grandChild.isEnabled()); Assert.assertFalse("Latest state change should have been disabled", grandStateChange.get()); } @Test // 3818 public void enabledStateChangeOnAttachAndDetachDisabledGrandChildAreDisabled() { UI ui = new UI(); EnabledDiv parent = new EnabledDiv(); parent.setEnabled(false); ui.add(parent); AtomicReference<Boolean> stateChange = new AtomicReference<>(); EnabledDiv child = new EnabledDiv() { @Override public void onEnabledStateChanged(boolean enabled) { super.onEnabledStateChanged(enabled); stateChange.set(enabled); } }; AtomicReference<Boolean> grandStateChange = new AtomicReference<>(); EnabledDiv grandChild = new EnabledDiv() { @Override public void onEnabledStateChanged(boolean enabled) { super.onEnabledStateChanged(enabled); grandStateChange.set(enabled); } }; grandChild.setEnabled(false); child.add(grandChild); Assert.assertFalse("Parent should be disabled", parent.isEnabled()); Assert.assertTrue("Child should be enabled.", child.isEnabled()); Assert.assertNull(child.getElement().getAttribute("disabled")); Assert.assertFalse("GrandChild should be disabled.", grandChild.isEnabled()); Assert.assertNotNull(grandChild.getElement().getAttribute("disabled")); parent.add(child); Assert.assertFalse("After attach child should be disabled", child.isEnabled()); Assert.assertFalse("Disabled event should have triggered", stateChange.get()); Assert.assertNotNull(child.getElement().getAttribute("disabled")); Assert.assertFalse("After attach GrandChild should be disabled", grandChild.isEnabled()); Assert.assertFalse("Disabled event should have triggered", grandStateChange.get()); Assert.assertNotNull(grandChild.getElement().getAttribute("disabled")); parent.remove(child); Assert.assertTrue("After detach child should be enabled", child.isEnabled()); Assert.assertTrue("Enable event should have triggered", stateChange.get()); Assert.assertNull(child.getElement().getAttribute("disabled")); Assert.assertFalse("After detach GrandChild should be disabled", grandChild.isEnabled()); Assert.assertFalse("Latest state change should have been disabled", grandStateChange.get()); Assert.assertNotNull(grandChild.getElement().getAttribute("disabled")); } @Test // 3818 public void enabledPassesThroughAllChildensChildrenAndAttributeShouldBeSet() { UI ui = new UI(); EnabledDiv parent = new EnabledDiv(); EnabledDiv child = new EnabledDiv(); EnabledDiv subChild = new EnabledDiv(); EnabledDiv subSubChild = new EnabledDiv(); parent.add(child); child.add(subChild); subChild.add(subSubChild); ui.add(parent); Assert.assertTrue("Parent should be enabled.", parent.isEnabled()); Assert.assertTrue("Child should be enabled.", child.isEnabled()); Assert.assertTrue("SubChild should be enabled.", subChild.isEnabled()); Assert.assertTrue("SubsubChild should be enabled.", subSubChild.isEnabled()); Assert.assertNull("No disabled attribute should not exist for parent", parent.getElement().getAttribute("disabled")); Assert.assertNull("No disabled attribute should not exist for child", child.getElement().getAttribute("disabled")); Assert.assertNull("No disabled attribute should not exist for subChild", subChild.getElement().getAttribute("disabled")); Assert.assertNull( "No disabled attribute should not exist for subSubChild", subSubChild.getElement().getAttribute("disabled")); parent.setEnabled(false); Assert.assertFalse("Parent should be disabled.", parent.isEnabled()); Assert.assertFalse("Child should be disabled.", child.isEnabled()); Assert.assertFalse("SubChild should be disabled.", subChild.isEnabled()); Assert.assertFalse("SubsubChild should be disabled.", subSubChild.isEnabled()); Assert.assertNotNull("Disabled attribute should exist for parent", parent.getElement().getAttribute("disabled")); Assert.assertNotNull("Disabled attribute should exist for child", child.getElement().getAttribute("disabled")); Assert.assertNotNull("Disabled attribute should exist for subChild", subChild.getElement().getAttribute("disabled")); Assert.assertNotNull("Disabled attribute should exist for subSubChild", subSubChild.getElement().getAttribute("disabled")); } @Test(expected = IllegalStateException.class) public void add_componentIsAttachedToAnotherUI_throwsIllegalStateException() { // given TestComponent child = new TestComponent(); UI ui1 = new UI(); ui1.add(child); UI ui2 = new UI(); // then ui2.add(child); } private void enabledStateChangeOnAttachCalledForParentState( boolean initiallyEnabled, BiConsumer<EnabledDiv, Component> modificationStartegy) { UI ui = new UI(); EnabledDiv parent = new EnabledDiv(); parent.setEnabled(initiallyEnabled); ui.add(parent); AtomicReference<Boolean> stateChange = new AtomicReference<>(); EnabledDiv child = new EnabledDiv() { @Override public void onEnabledStateChanged(boolean enabled) { super.onEnabledStateChanged(enabled); Assert.assertTrue("Expected empty state for enabled change", stateChange.compareAndSet(null, enabled)); } }; Assert.assertEquals("Parent should be disabled", initiallyEnabled, parent.isEnabled()); Assert.assertTrue("Child should be enabled.", child.isEnabled()); Assert.assertNull(child.getElement().getAttribute("disabled")); modificationStartegy.accept(parent, child); Assert.assertFalse("After attach child should be disabled", child.isEnabled()); Assert.assertFalse("Disabled event should have triggered", stateChange.get()); Assert.assertNotNull(child.getElement().getAttribute("disabled")); } private void enabledStateChangeOnParentDetachReturnsOldState( BiConsumer<EnabledDiv, Component> modificationStartegy) { UI ui = new UI(); EnabledDiv grandParent = new EnabledDiv(); grandParent.setEnabled(false); ui.add(grandParent); EnabledDiv parent = new EnabledDiv(); AtomicReference<Boolean> stateChange = new AtomicReference<>(); EnabledDiv child = new EnabledDiv() { @Override public void onEnabledStateChanged(boolean enabled) { super.onEnabledStateChanged(enabled); stateChange.set(enabled); } }; Assert.assertTrue("Parent should be enabled", parent.isEnabled()); Assert.assertTrue("Child should be enabled.", child.isEnabled()); Assert.assertNull(child.getElement().getAttribute("disabled")); modificationStartegy.accept(parent, child); grandParent.add(parent); Assert.assertFalse("After attach child should be disabled", child.isEnabled()); Assert.assertFalse("Disabled event should have triggered", stateChange.get()); Assert.assertNotNull(child.getElement().getAttribute("disabled")); grandParent.remove(parent); Assert.assertTrue("After detach child should be enabled", child.isEnabled()); Assert.assertTrue("Enable event should have triggered", stateChange.get()); Assert.assertNull(child.getElement().getAttribute("disabled")); } }
Ashwanigupta9125/code-DS-ALGO
CodeForces/Complete/100-199/166E-Tetrahedron.cpp
<filename>CodeForces/Complete/100-199/166E-Tetrahedron.cpp #include <cstdio> int main(){ long n(0); scanf("%ld", &n); const int a = 4; const long modNumber = 1000000007; long long f(0), g(0), fPrev(0), gPrev(1); for(long k = 2; k <= n; k++){ f = (a - 1) * gPrev; g = fPrev + (a - 2) * gPrev; f %= modNumber; g %= modNumber; fPrev = f; gPrev = g; } printf("%lld\n", f); }
llorz-o/rich-m
cli/site/doc/index.js
<filename>cli/site/doc/index.js<gh_stars>0 import Vue from 'vue' import VueRouter from 'vue-router' import App from "./App.vue" import Doc from './views/Doc.vue' import * as docs from '../../dist/component-descript' Vue.use(VueRouter) let routes = [] let componentsKeys = Object.keys(docs) componentsKeys.forEach(key => routes.push({ path: `/${key}`, component: Doc, })) window.__vue = new Vue({ el: "#app", data() { return { componentsKeys, currentComponent: null, } }, computed: { doc() { return this.currentComponent && docs[this.currentComponent] } }, watch: { $route(news) { let { component } = news.query this.currentComponent = component } }, mounted() { let { component } = this.$route.query this.currentComponent = component }, render: h => h(App), router: new VueRouter({ mode: "hash", routes, }), })
rssh/scala-gopher
js/src/test/scala/gopher/impl/RingBufferTest.scala
<reponame>rssh/scala-gopher package gopher.impl import cps._ import cps.monads.FutureAsyncMonad import gopher._ import scala.concurrent._ import scalajs.concurrent.JSExecutionContext import scalajs.concurrent.JSExecutionContext.Implicits.queue import munit._ class RingBufferTests extends munit.FunSuite{ test("ring buffer ") { val gopher = JSGopher[Future](JSGopherConfig()) val ch = gopher.makeChannel[Int](3) var x = 0 async[Future] { ch.write(1) ch.write(2) ch.write(3) // we should be blocked before sending next JSExecutionContext.queue.execute{ () => x = 1 ch.aread() } ch.write(4) assert(x != 0) } } }
almarklein/stentseg
lspeas/_dicomStatic2ssdf.py
<reponame>almarklein/stentseg """ Load static CT data and save to ssdf format """ import os import sys import imageio from stentseg.utils.datahandling import select_dir, loadvol from stentseg.utils.datahandling import savecropvols, saveaveraged # Select base directory for LOADING DICOM data # The stentseg datahandling module is agnostic about where the DICOM data is dicom_basedir = select_dir(r'G:\LSPEAS_data', r'D:\LSPEAS\LSPEAS_data_BACKUP') # Select base directory to SAVE SSDF ssdf_basedir = select_dir(r'D:\LSPEAS\LSPEAS_ssdf', r'F:\LSPEAS_ssdf_toPC', r'G:\LSPEAS_ssdf_toPC') ptcode = 'LSPEAS_022_CTA_20160126' # ctcode = 'S40' # 'CTA_pre', 'static..' stenttype = 'anaconda' # Set which crops to save cropnames = ['ring'] # ['prox'] or ['ring','stent'] or .. # Step A: read single volume if ctcode == 'CTA_pre': vol = imageio.volread(os.path.join(dicom_basedir, ctcode, ptcode), 'dicom') else: vol = imageio.volread(os.path.join(dicom_basedir, ptcode, ctcode), 'dicom') print () print(vol.meta.SeriesDescription) print(vol.meta.sampling) print() # Step B: Crop and Save SSDF vols = [vol] for cropname in cropnames: savecropvols(vols, ssdf_basedir, ptcode, ctcode, cropname, stenttype) ## Visualize result s1 = loadvol(ssdf_basedir, ptcode, ctcode, cropnames[0], what ='phase') vol = s1.vol # Visualize and compare colormap = {'r': [(0.0, 0.0), (0.17727272, 1.0)], 'g': [(0.0, 0.0), (0.27272728, 1.0)], 'b': [(0.0, 0.0), (0.34545454, 1.0)], 'a': [(0.0, 1.0), (1.0, 1.0)]} import visvis as vv fig = vv.figure(1); vv.clf() fig.position = 0, 22, 1366, 706 a = vv.gca() a.daspect = 1,1,-1 t1 = vv.volshow(vol, clim=(0, 2500), renderStyle='iso') # iso or mip t1.isoThreshold = 400 t1.colormap = colormap t2 = vv.volshow2(vol, clim=(-550, 500)) vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z') # vv.title('One volume at %i procent of cardiac cycle' % phase ) vv.title('Static CT Volume' )
sLeeNguyen/sales-support
sales/models.py
from django.db import models from django.utils import timezone from core.utils import server_timezone from customers.models import Customer from coupons.models import Coupon from stores.models import Store from users.models import User from products.models import Product class InvoiceManager(models.Manager): prefix = 'HD' def gen_default_code(self, store): query_set = self.get_queryset().filter(store=store) postfix = str(query_set.count()) return self.prefix + '0'*(6 - len(postfix)) + postfix class OrderManager(models.Manager): prefix = 'DH' def gen_default_code(self, store): query_set = self.get_queryset().filter(store=store) postfix = str(query_set.count()) return self.prefix + '0'*(6 - len(postfix)) + postfix class Order(models.Model): STATUS_CHOICES = [ (0, 'Xoá'), (1, 'Hoàn thành'), (2, 'Chưa xử lý'), ] order_code = models.CharField(max_length=10, blank=False, null=False) time_create = models.DateTimeField(auto_now_add=timezone.now()) note = models.TextField(default='') status = models.PositiveIntegerField(default=2, choices=STATUS_CHOICES) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=True, null=True) coupon = models.ForeignKey(Coupon, on_delete=models.CASCADE, blank=True, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE) objects = OrderManager() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.list_product_items = [] def add_item(self, product, quantity, price) -> 'ProductItem': product_item = ProductItem(product=product, price=price, quantity=quantity) self.list_product_items.append(product_item) return product_item def save_list_items(self): # list product items must be saved after its order be saved for item in self.get_list_product_items(): item.order = self res = ProductItem.objects.bulk_create(self.list_product_items) return res def save(self, force_insert=False, force_update=False, using=None, update_fields=None): # update customer points if it exists if self.customer is not None: self.customer.points += self.calc_total_money() // 1000 self.customer.save() self.order_code = Order.objects.gen_default_code(self.store) super().save(force_insert, force_update, using, update_fields) self.save_list_items() def get_list_product_items(self): if len(self.list_product_items) == 0 and self.id: self.list_product_items = list(ProductItem.objects.filter(order=self)) return self.list_product_items def calc_total_money(self) -> 'int': total = 0 for product_item in self.list_product_items: total += product_item.get_sub_total() return int(total) def calc_discount(self): return 0 def get_total_products(self): num_of_products = 0 for product_item in self.list_product_items: num_of_products += product_item.quantity return num_of_products def get_customer(self): if self.customer is not None: return self.customer.customer_name return "Khách lẻ" class Invoice(models.Model): STATUS_CHOICES = [ (0, 'Huỷ'), (1, 'Hoàn thành'), ] invoice_code = models.CharField(max_length=10, blank=True, null=True) time_create = models.DateTimeField(auto_now_add=timezone.now()) status = models.PositiveIntegerField(default=1, choices=STATUS_CHOICES) total_products = models.FloatField(blank=False, null=False) total = models.PositiveIntegerField(blank=False, null=False) customer_given = models.PositiveIntegerField(blank=True, null=True) discount = models.PositiveIntegerField(default=0, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE) staff = models.ForeignKey(User, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE) objects = InvoiceManager() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.invoice_code = Invoice.objects.gen_default_code(self.store) super().save(force_insert, force_update, using, update_fields) return self def get_time_create_format(self): return server_timezone(self.time_create).strftime("%d/%m/%Y %H:%M") def get_staff_name(self): return self.staff.get_display_name() @property def must_pay(self): return self.total - self.discount @property def refund(self): return self.customer_given - self.must_pay class ProductItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.PositiveIntegerField(default=0) quantity = models.PositiveIntegerField(default=0) order = models.ForeignKey(Order, on_delete=models.CASCADE) def get_sub_total(self): return int(self.price * self.quantity)
tompis/casual
middleware/transaction/source/resource/proxy_server.cpp
<gh_stars>0 //! //! resource_proxy_server.cpp //! //! Created on: Aug 2, 2013 //! Author: Lazan //! #include "transaction/resource/proxy_server.h" #include "transaction/resource/proxy.h" #include "common/error.h" #include "common/arguments.h" #include "common/environment.h" #include "common/trace.h" #include "common/internal/trace.h" #include "common/exception.h" #include "sf/log.h" int casual_start_reource_proxy( struct casual_resource_proxy_service_argument* serverArguments) { try { casual::common::trace::internal::Scope trace{ "casual_start_reource_proxy"}; casual::transaction::resource::State state; state.xaSwitches = serverArguments->xaSwitches; { casual::common::Arguments arguments{ { casual::common::argument::directive( {"-q", "--tm-queue"}, "tm queue", state.tm_queue), casual::common::argument::directive( {"-k", "--rm-key"}, "resource key", state.rm_key), casual::common::argument::directive( {"-o", "--rm-openinfo"}, "open info", state.rm_openinfo), casual::common::argument::directive( {"-c", "--rm-closeinfo"}, "close info", state.rm_closeinfo), casual::common::argument::directive( {"-i", "--rm-id"}, "resource id", state.rm_id), casual::common::argument::directive( {"-d", "--domain"}, "domain name", state.domain) }}; arguments.parse( serverArguments->argc, serverArguments->argv); casual::common::environment::domain::name( state.domain); } casual::common::log::internal::transaction << CASUAL_MAKE_NVP( state); casual::transaction::resource::Proxy proxy( std::move( state)); proxy.start(); } catch( const casual::common::exception::signal::Terminate& exception) { return 0; } catch( ...) { return casual::common::error::handler(); } return 0; }
feiooo/games-puzzles-algorithms
old/lib/setup.py
from setuptools import setup, find_packages import warnings setup( name='games_puzzles_algorithms', version='0.0.1', license='MIT', packages=find_packages(), install_requires=[ 'future == 0.15.2', 'setuptools == 20.2.2', 'heapdict == 1.0.0', ], tests_require=['pytest', 'pytest-cov'], setup_requires=['pytest-runner'], classifiers=[ 'License :: OSI Approved :: MIT License' ], )
santosh653/checker-framework
framework/tests/flowexpression/ArrayCreationParsing.java
package flowexpression; import org.checkerframework.framework.testchecker.flowexpression.qual.FlowExp; public class ArrayCreationParsing { @FlowExp("new int[2]") Object value1; @FlowExp("new int[2][2]") Object value2; @FlowExp("new String[2]") Object value3; @FlowExp("new String[] {\"a\", \"b\"}") Object value4; int i; @FlowExp("new int[i]") Object value5; @FlowExp("new int[this.i]") Object value6; @FlowExp("new int[getI()]") Object value7; @FlowExp("new int[] {i, this.i, getI()}") Object value8; int getI() { return i; } void method(@FlowExp("new java.lang.String[2]") Object param) { value3 = param; // :: error: (assignment.type.incompatible) value1 = param; } }
RFXTechnologies/fleet
server/datastore/mysql/migrations/tables/20220307104655_AddHostDeviceAuth.go
package tables import ( "database/sql" "github.com/pkg/errors" ) func init() { MigrationClient.AddMigration(Up_20220307104655, Down_20220307104655) } func Up_20220307104655(tx *sql.Tx) error { hostDeviceAuthTable := ` CREATE TABLE IF NOT EXISTS host_device_auth ( host_id int(10) UNSIGNED NOT NULL, token VARCHAR(255) NOT NULL, PRIMARY KEY (host_id), UNIQUE INDEX idx_host_device_auth_token (token) ); ` if _, err := tx.Exec(hostDeviceAuthTable); err != nil { return errors.Wrap(err, "create host_device_auth table") } return nil } func Down_20220307104655(tx *sql.Tx) error { return nil }
Fusion-Rom/android_external_chromium_org_third_party_WebKit
Source/bindings/core/v8/V8DOMConfiguration.cpp
<reponame>Fusion-Rom/android_external_chromium_org_third_party_WebKit<gh_stars>1-10 /* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "bindings/core/v8/V8DOMConfiguration.h" #include "bindings/core/v8/V8ObjectConstructor.h" #include "platform/TraceEvent.h" namespace blink { void V8DOMConfiguration::installAttributes(v8::Handle<v8::ObjectTemplate> instanceTemplate, v8::Handle<v8::ObjectTemplate> prototype, const AttributeConfiguration* attributes, size_t attributeCount, v8::Isolate* isolate) { for (size_t i = 0; i < attributeCount; ++i) installAttribute(instanceTemplate, prototype, attributes[i], isolate); } void V8DOMConfiguration::installAccessors(v8::Handle<v8::ObjectTemplate> prototype, v8::Handle<v8::Signature> signature, const AccessorConfiguration* accessors, size_t accessorCount, v8::Isolate* isolate) { DOMWrapperWorld& world = DOMWrapperWorld::current(isolate); for (size_t i = 0; i < accessorCount; ++i) { if (accessors[i].exposeConfiguration == OnlyExposedToPrivateScript && !world.isPrivateScriptIsolatedWorld()) continue; v8::FunctionCallback getterCallback = accessors[i].getter; v8::FunctionCallback setterCallback = accessors[i].setter; if (world.isMainWorld()) { if (accessors[i].getterForMainWorld) getterCallback = accessors[i].getterForMainWorld; if (accessors[i].setterForMainWorld) setterCallback = accessors[i].setterForMainWorld; } v8::Local<v8::FunctionTemplate> getter; if (getterCallback) { getter = v8::FunctionTemplate::New(isolate, getterCallback, v8::External::New(isolate, const_cast<WrapperTypeInfo*>(accessors[i].data)), signature, 0); getter->RemovePrototype(); } v8::Local<v8::FunctionTemplate> setter; if (setterCallback) { setter = v8::FunctionTemplate::New(isolate, setterCallback, v8::External::New(isolate, const_cast<WrapperTypeInfo*>(accessors[i].data)), signature, 1); setter->RemovePrototype(); } prototype->SetAccessorProperty(v8AtomicString(isolate, accessors[i].name), getter, setter, accessors[i].attribute, accessors[i].settings); } } // Constant installation // // installConstants() is be used for simple constants. It installs constants // using v8::Template::Set(), which results in a property that is much faster to // access from scripts. // installConstant() is used when some C++ code needs to be executed when the // constant is accessed, e.g. to handle deprecation or measuring usage. The // property appears the same to scripts, but is slower to access. void V8DOMConfiguration::installConstants(v8::Handle<v8::FunctionTemplate> functionDescriptor, v8::Handle<v8::ObjectTemplate> prototype, const ConstantConfiguration* constants, size_t constantCount, v8::Isolate* isolate) { for (size_t i = 0; i < constantCount; ++i) { const ConstantConfiguration* constant = &constants[i]; v8::Handle<v8::String> constantName = v8AtomicString(isolate, constant->name); switch (constant->type) { case ConstantTypeShort: case ConstantTypeLong: case ConstantTypeUnsignedShort: functionDescriptor->Set(constantName, v8::Integer::New(isolate, constant->ivalue), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete)); prototype->Set(constantName, v8::Integer::New(isolate, constant->ivalue), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete)); break; case ConstantTypeUnsignedLong: functionDescriptor->Set(constantName, v8::Integer::NewFromUnsigned(isolate, constant->ivalue), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete)); prototype->Set(constantName, v8::Integer::NewFromUnsigned(isolate, constant->ivalue), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete)); break; case ConstantTypeFloat: case ConstantTypeDouble: functionDescriptor->Set(constantName, v8::Number::New(isolate, constant->dvalue), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete)); prototype->Set(constantName, v8::Number::New(isolate, constant->dvalue), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete)); break; case ConstantTypeString: functionDescriptor->Set(constantName, v8::String::NewFromUtf8(isolate, constant->svalue), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete)); prototype->Set(constantName, v8::String::NewFromUtf8(isolate, constant->svalue), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete)); break; default: ASSERT_NOT_REACHED(); } } } void V8DOMConfiguration::installConstant(v8::Handle<v8::FunctionTemplate> functionDescriptor, v8::Handle<v8::ObjectTemplate> prototype, const char* name, v8::AccessorGetterCallback getter, v8::Isolate* isolate) { v8::Handle<v8::String> constantName = v8AtomicString(isolate, name); functionDescriptor->SetNativeDataProperty(constantName, getter, 0, v8::Handle<v8::Value>(), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete)); prototype->SetNativeDataProperty(constantName, getter, 0, v8::Handle<v8::Value>(), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete)); } void V8DOMConfiguration::installMethods(v8::Handle<v8::ObjectTemplate> prototype, v8::Handle<v8::Signature> signature, v8::PropertyAttribute attributes, const MethodConfiguration* callbacks, size_t callbackCount, v8::Isolate* isolate) { for (size_t i = 0; i < callbackCount; ++i) installMethod(prototype, signature, attributes, callbacks[i], isolate); } v8::Handle<v8::FunctionTemplate> V8DOMConfiguration::functionTemplateForCallback(v8::Handle<v8::Signature> signature, v8::FunctionCallback callback, int length, v8::Isolate* isolate) { v8::Local<v8::FunctionTemplate> functionTemplate = v8::FunctionTemplate::New(isolate, callback, v8Undefined(), signature, length); functionTemplate->RemovePrototype(); return functionTemplate; } v8::Local<v8::Signature> V8DOMConfiguration::installDOMClassTemplate(v8::Handle<v8::FunctionTemplate> functionDescriptor, const char* interfaceName, v8::Handle<v8::FunctionTemplate> parentClass, size_t fieldCount, const AttributeConfiguration* attributes, size_t attributeCount, const AccessorConfiguration* accessors, size_t accessorCount, const MethodConfiguration* callbacks, size_t callbackCount, v8::Isolate* isolate) { functionDescriptor->SetClassName(v8AtomicString(isolate, interfaceName)); v8::Local<v8::ObjectTemplate> instanceTemplate = functionDescriptor->InstanceTemplate(); instanceTemplate->SetInternalFieldCount(fieldCount); if (!parentClass.IsEmpty()) { functionDescriptor->Inherit(parentClass); // Marks the prototype object as one of native-backed objects. // This is needed since bug 110436 asks WebKit to tell native-initiated prototypes from pure-JS ones. // This doesn't mark kinds "root" classes like Node, where setting this changes prototype chain structure. v8::Local<v8::ObjectTemplate> prototype = functionDescriptor->PrototypeTemplate(); prototype->SetInternalFieldCount(v8PrototypeInternalFieldcount); } v8::Local<v8::Signature> defaultSignature = v8::Signature::New(isolate, functionDescriptor); if (attributeCount) installAttributes(instanceTemplate, functionDescriptor->PrototypeTemplate(), attributes, attributeCount, isolate); if (accessorCount) installAccessors(functionDescriptor->PrototypeTemplate(), defaultSignature, accessors, accessorCount, isolate); if (callbackCount) installMethods(functionDescriptor->PrototypeTemplate(), defaultSignature, static_cast<v8::PropertyAttribute>(v8::DontDelete), callbacks, callbackCount, isolate); return defaultSignature; } v8::Handle<v8::FunctionTemplate> V8DOMConfiguration::domClassTemplate(v8::Isolate* isolate, WrapperTypeInfo* wrapperTypeInfo, void (*configureDOMClassTemplate)(v8::Handle<v8::FunctionTemplate>, v8::Isolate*)) { V8PerIsolateData* data = V8PerIsolateData::from(isolate); v8::Local<v8::FunctionTemplate> result = data->existingDOMTemplate(wrapperTypeInfo); if (!result.IsEmpty()) return result; TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "BuildDOMTemplate"); result = v8::FunctionTemplate::New(isolate, V8ObjectConstructor::isValidConstructorMode); configureDOMClassTemplate(result, isolate); data->setDOMTemplate(wrapperTypeInfo, result); return result; } } // namespace blink
Geomatys/sis
core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/transform/AbstractLinearTransform.java
<gh_stars>10-100 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sis.referencing.operation.transform; import java.util.Arrays; import java.io.Serializable; import org.opengis.parameter.ParameterValueGroup; import org.opengis.parameter.ParameterDescriptorGroup; import org.opengis.referencing.operation.Matrix; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.MathTransformFactory; import org.opengis.referencing.operation.NoninvertibleTransformException; import org.apache.sis.referencing.operation.matrix.Matrices; import org.apache.sis.internal.referencing.provider.Affine; import org.apache.sis.internal.referencing.Resources; import org.apache.sis.internal.util.Numerics; import org.apache.sis.util.ComparisonMode; import org.apache.sis.util.resources.Errors; import org.opengis.util.FactoryException; /** * Base class of linear transforms. For efficiency reasons, this transform implements itself the matrix * to be returned by {@link #getMatrix()}. * * <p>Subclasses need to implement the following methods:</p> * <ul> * <li>{@link #getElement(int, int)}</li> * <li>{@link #equalsSameClass(Object)}</li> * </ul> * * @author <NAME> (Geomatys) * @version 1.1 * @since 0.6 * @module */ abstract class AbstractLinearTransform extends AbstractMathTransform implements LinearTransform, Matrix, Serializable { /** * For cross-version compatibility. */ private static final long serialVersionUID = -4649708313541868599L; /** * The inverse transform, or {@code null} if not yet created. * This field is part of the serialization form in order to avoid rounding errors if a user * asks for the inverse of the inverse (i.e. the original transform) after deserialization. * * @see #inverse() */ volatile LinearTransform inverse; /** * Constructs a transform. */ AbstractLinearTransform() { } /** * Returns {@code true} if this transform is affine. * * @return {@code true} if this transform is affine, or {@code false} otherwise. */ @Override public boolean isAffine() { return Matrices.isAffine(this); } /** * Returns a copy of the matrix that user can modify. * The object returned by this method is not of the same class than this object. */ @Override @SuppressWarnings({"CloneInNonCloneableClass", "CloneDoesntCallSuperClone"}) public final Matrix clone() { return Matrices.copy(this); } /** * Returns an immutable view of the matrix for this transform. */ @Override public final Matrix getMatrix() { return this; } /** * Gets the number of rows in the matrix. */ @Override public int getNumRow() { return getTargetDimensions() + 1; } /** * Gets the number of columns in the matrix. */ @Override public int getNumCol() { return getSourceDimensions() + 1; } /** * Returns an identity transform if this transform is the inverse of the given transform. * If this method is unsure, it conservatively returns {@code null}. */ @Override protected final MathTransform tryConcatenate(boolean applyOtherFirst, MathTransform other, MathTransformFactory factory) throws FactoryException { if (other instanceof LinearTransform) { return super.tryConcatenate(applyOtherFirst, other, factory); } return null; // No need to compute the inverse if the other transform is not linear. } /** * Returns the inverse transform of this object. * This method invokes {@link #createInverse()} when first needed, then caches the result. */ @Override @SuppressWarnings("DoubleCheckedLocking") // Okay since 'inverse' is volatile. public LinearTransform inverse() throws NoninvertibleTransformException { LinearTransform inv = inverse; if (inv == null) { synchronized (this) { inv = inverse; if (inv == null) { inv = createInverse(); inverse = inv; } } } return inv; } /** * Invoked by {@link #inverse()} the first time that the inverse transform needs to be computed. */ LinearTransform createInverse() throws NoninvertibleTransformException { /* * Should never be the identity transform at this point (except during tests) because * MathTransforms.linear(…) should never instantiate this class in the identity case. * But we check anyway as a paranoiac safety. */ if (isIdentity()) { return this; } final LinearTransform inv = MathTransforms.linear(Matrices.inverse(this)); if (inv instanceof AbstractLinearTransform) { ((AbstractLinearTransform) inv).inverse = this; } return inv; } /** * Returns the parameter descriptors for this math transform. * * @return {@inheritDoc} */ @Override public ParameterDescriptorGroup getParameterDescriptors() { return Affine.getProvider(getSourceDimensions(), getTargetDimensions(), isAffine()).getParameters(); } /** * Returns the matrix elements as a group of parameters values. The number of parameters depends on the * matrix size. Only matrix elements different from their default value will be included in this group. * * @return the parameter values for this math transform. */ @Override public ParameterValueGroup getParameterValues() { return Affine.parameters(this); } /** * Unsupported operation, since this matrix is unmodifiable. */ @Override public final void setElement(final int row, final int column, final double value) { throw new UnsupportedOperationException(isAffine() ? Resources.format(Resources.Keys.UnmodifiableAffineTransform) : Errors.format(Errors.Keys.UnmodifiableObject_1, AbstractLinearTransform.class)); } /** * Transforms an array of relative distance vectors. Distance vectors are transformed without applying * the translation components. The default implementation is not very efficient, but it should not be * an issue since this method is not invoked often. * * @since 0.7 */ @Override public void deltaTransform(double[] srcPts, int srcOff, double[] dstPts, int dstOff, int numPts) { int offFinal = 0; double[] dstFinal = null; final int srcDim, dstDim; int srcInc = srcDim = getSourceDimensions(); int dstInc = dstDim = getTargetDimensions(); if (srcPts == dstPts) { switch (IterationStrategy.suggest(srcOff, srcDim, dstOff, dstDim, numPts)) { case ASCENDING: { break; } case DESCENDING: { srcOff += (numPts - 1) * srcDim; srcInc = -srcInc; dstOff += (numPts - 1) * dstDim; dstInc = -dstInc; break; } default: { srcPts = Arrays.copyOfRange(srcPts, srcOff, srcOff + numPts*srcDim); srcOff = 0; break; } case BUFFER_TARGET: { dstFinal = dstPts; dstPts = new double[numPts * dstInc]; offFinal = dstOff; dstOff = 0; break; } } } final double[] buffer = new double[dstDim]; while (--numPts >= 0) { for (int j=0; j<dstDim; j++) { double sum = 0; for (int i=0; i<srcDim; i++) { final double e = getElement(j, i); if (e != 0) { // See the comment in ProjectiveTransform for the purpose of this test. sum += srcPts[srcOff + i] * e; } } buffer[j] = sum; } System.arraycopy(buffer, 0, dstPts, dstOff, dstDim); srcOff += srcInc; dstOff += dstInc; } if (dstFinal != null) { System.arraycopy(dstPts, 0, dstFinal, offFinal, dstPts.length); } } /** * Compares this math transform with an object which is known to be of the same class. * Implementers can safely cast the {@code object} argument to their subclass. * * @param object the object to compare with this transform. * @return {@code true} if the given object is considered equals to this math transform. */ protected abstract boolean equalsSameClass(final Object object); /** * Compares the specified object with this linear transform for equality. * This implementation returns {@code true} if the following conditions are met: * <ul> * <li>In {@code STRICT} mode, the objects are of the same class and {@link #equalsSameClass(Object)} * returns {@code true}.</li> * <li>In other modes, the matrix are equals or approximately equals (depending on the mode).</li> * </ul> * * @param object the object to compare with this transform. * @param mode the strictness level of the comparison. Default to {@link ComparisonMode#STRICT STRICT}. * @return {@code true} if the given object is considered equals to this math transform. */ @Override public final boolean equals(final Object object, final ComparisonMode mode) { if (object == this) { return true; // Slight optimization } if (object == null) { return false; } final boolean isApproximate = mode.isApproximate(); if (!isApproximate && getClass() == object.getClass()) { if (!equalsSameClass(object)) { return false; } } else if (mode == ComparisonMode.STRICT) { return false; } else { final Matrix m; if (object instanceof LinearTransform) { m = ((LinearTransform) object).getMatrix(); } else if (object instanceof Matrix) { m = (Matrix) object; } else { return false; } if (!Matrices.equals(this, m, mode)) { return false; } } /* * At this point the transforms are considered equal. In theory we would not need to check * the inverse transforms since if A and B are equal, then A⁻¹ and B⁻¹ should be equal too. * However in Apache SIS this is not exactly true because computation of inverse transforms * avoid NaN values in some circumstances. For example the inverse of a 2×3 matrix normally * sets the "new" dimensions to NaN, but in the particular case where the transform is used * for a "Geographic 2D to 3D" conversion it will rather set the new dimensions to zero. So * A⁻¹ and B⁻¹ may differ in their "NaN versus 0" values even if A and B are equal. * * Opportunistically, the comparison of inverse transforms in approximated mode also ensures * that we are below the tolerance threshold not only for this matrix, but for the inverse one * as well. */ if (object instanceof AbstractLinearTransform) { /* * If the 'inverse' matrix was not computed in any of the transforms being compared * (i.e. if 'this.inverse' and 'object.inverse' are both null), then assume that the * two transforms will compute their inverse in the same way. The intent is to avoid * to trig the inverse transform computation. * * Note that this code requires the 'inverse' fields to be volatile * (otherwise we would need to synchronize). */ if (inverse == ((AbstractLinearTransform) object).inverse) { return true; } } /* * Get the matrices of inverse transforms. In the following code 'null' is really the intended * value for non-invertible matrices because the Matrices.equals(…) methods accept null values, * so we are okay to ignore NoninvertibleTransformException in this particular case. */ Matrix mt = null, mo = null; try { mt = inverse().getMatrix(); } catch (NoninvertibleTransformException e) { // Leave 'mt' to null. } try { if (object instanceof LinearTransform) { mo = ((LinearTransform) object).inverse().getMatrix(); } else if (object instanceof Matrix) { mo = Matrices.inverse((Matrix) object); } } catch (NoninvertibleTransformException e) { // Leave 'mo' to null. } return Matrices.equals(mt, mo, isApproximate ? Numerics.COMPARISON_THRESHOLD : 0, isApproximate); } /** * Returns a string representation of the matrix. */ @Override public String toString() { return Matrices.toString(this); } }
ArtemiusL/ark
src/containers/footerContent/footerContent.js
<reponame>ArtemiusL/ark import './footerContent.scss'; import 'components/contact';
Bigfluf/BloodMagic
src/main/java/WayofTime/alchemicalWizardry/common/demonVillage/demonHoard/demon/EntityMinorDemonGrunt.java
package WayofTime.alchemicalWizardry.common.demonVillage.demonHoard.demon; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIAttackOnCollide; import net.minecraft.entity.ai.EntityAIFollowOwner; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIOwnerHurtByTarget; import net.minecraft.entity.ai.EntityAIOwnerHurtTarget; import net.minecraft.entity.ai.EntityAISwimming; import net.minecraft.entity.ai.EntityAIWander; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.monster.EntityCreeper; import net.minecraft.entity.monster.EntityGhast; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.DamageSource; import net.minecraft.world.World; import WayofTime.alchemicalWizardry.AlchemicalWizardry; import WayofTime.alchemicalWizardry.ModItems; import WayofTime.alchemicalWizardry.api.Int3; import WayofTime.alchemicalWizardry.api.rituals.IMasterRitualStone; import WayofTime.alchemicalWizardry.api.rituals.LocalRitualStorage; import WayofTime.alchemicalWizardry.common.EntityAITargetAggroCloaking; import WayofTime.alchemicalWizardry.common.demonVillage.ai.EntityAIOccasionalRangedAttack; import WayofTime.alchemicalWizardry.common.demonVillage.ai.EntityDemonAIHurtByTarget; import WayofTime.alchemicalWizardry.common.demonVillage.ai.IOccasionalRangedAttackMob; import WayofTime.alchemicalWizardry.common.demonVillage.tileEntity.TEDemonPortal; import WayofTime.alchemicalWizardry.common.entity.mob.EntityDemon; import WayofTime.alchemicalWizardry.common.entity.projectile.HolyProjectile; import WayofTime.alchemicalWizardry.common.rituals.LocalStorageAlphaPact; import WayofTime.alchemicalWizardry.common.spell.complex.effect.SpellHelper; public class EntityMinorDemonGrunt extends EntityDemon implements IOccasionalRangedAttackMob, IHoardDemon { private EntityAIOccasionalRangedAttack aiArrowAttack = new EntityAIOccasionalRangedAttack(this, 1.0D, 40, 40, 15.0F, 5); private EntityAIAttackOnCollide aiAttackOnCollide = new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.2D, false); private boolean isAngry = true; private Int3 demonPortal; private static float maxTamedHealth = 200.0F; private static float maxUntamedHealth = 200.0F; private boolean enthralled = false; public EntityMinorDemonGrunt(World par1World) { super(par1World, AlchemicalWizardry.entityMinorDemonGruntID); this.setSize(0.7F, 1.8F); this.getNavigator().setAvoidsWater(true); this.tasks.addTask(1, new EntityAISwimming(this)); this.tasks.addTask(2, this.aiSit); this.tasks.addTask(3, new EntityAIFollowOwner(this, 1.0D, 10.0F, 2.0F)); this.tasks.addTask(4, new EntityAIWander(this, 1.0D)); this.tasks.addTask(5, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); this.tasks.addTask(6, new EntityAILookIdle(this)); this.targetTasks.addTask(1, new EntityAIOwnerHurtByTarget(this)); this.targetTasks.addTask(2, new EntityAIOwnerHurtTarget(this)); this.targetTasks.addTask(3, new EntityDemonAIHurtByTarget(this, true)); this.targetTasks.addTask(4, new EntityAITargetAggroCloaking(this, EntityPlayer.class, 0, false, 0)); this.setAggro(false); this.setTamed(false); demonPortal = new Int3(0,0,0); if (par1World != null && !par1World.isRemote) { this.setCombatTask(); } //this.isImmuneToFire = true; } public boolean isTameable() { return false; } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); //This line affects the speed of the monster this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.30000001192092896D); if (this.isTamed()) { this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxTamedHealth); } else { this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxUntamedHealth); } } @Override protected void dropFewItems(boolean par1, int par2) { if(!this.getDoesDropCrystal()) { ItemStack lifeShardStack = new ItemStack(ModItems.baseItems, 1, 28); ItemStack soulShardStack = new ItemStack(ModItems.baseItems, 1, 29); int dropAmount = 0; for(int i=0; i<=par2; i++) { dropAmount += this.worldObj.rand.nextFloat() < 0.6f ? 1 : 0; } ItemStack drop = this.worldObj.rand.nextBoolean() ? lifeShardStack : soulShardStack; drop.stackSize = dropAmount; if(dropAmount > 0) { this.entityDropItem(drop, 0.0f); } }else { super.dropFewItems(par1, par2); } } @Override public void setPortalLocation(Int3 position) { this.demonPortal = position; } @Override public Int3 getPortalLocation() { return this.demonPortal; } /** * Returns true if the newer Entity AI code should be run */ public boolean isAIEnabled() { return true; } /** * Sets the active target the Task system uses for tracking */ public void setAttackTarget(EntityLivingBase par1EntityLivingBase) { super.setAttackTarget(par1EntityLivingBase); if (par1EntityLivingBase == null) { this.setAngry(false); } else if (!this.isTamed()) { this.setAngry(true); } } /** * main AI tick function, replaces updateEntityActionState */ // @Override // protected void updateAITick() // { // this.dataWatcher.updateObject(18, Float.valueOf(this.getHealth())); // } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ @Override public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound) { super.writeEntityToNBT(par1NBTTagCompound); par1NBTTagCompound.setBoolean("Angry", this.isAngry()); this.demonPortal.writeToNBT(par1NBTTagCompound); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ @Override public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound) { super.readEntityFromNBT(par1NBTTagCompound); this.setAngry(par1NBTTagCompound.getBoolean("Angry")); this.demonPortal = Int3.readFromNBT(par1NBTTagCompound); this.setCombatTask(); } /** * Returns the sound this mob makes while it's alive. */ @Override protected String getLivingSound() { //TODO change sounds return "none"; } /** * Returns the sound this mob makes when it is hurt. */ @Override protected String getHurtSound() { return "none"; } /** * Returns the sound this mob makes on death. */ @Override protected String getDeathSound() { return "mob.wolf.death"; } /** * Returns the volume for the sounds this mob makes. */ @Override protected float getSoundVolume() { return 0.4F; } /** * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons * use this to react to sunlight and start to burn. */ @Override public void onLivingUpdate() { super.onLivingUpdate(); } /** * Called to update the entity's position/logic. */ @Override public void onUpdate() { if(!this.enthralled) { TileEntity tile = this.worldObj.getTileEntity(this.demonPortal.xCoord, this.demonPortal.yCoord, this.demonPortal.zCoord); if(tile instanceof TEDemonPortal) { ((TEDemonPortal) tile).enthrallDemon(this); this.enthralled = true; }else if(tile instanceof IMasterRitualStone) { IMasterRitualStone stone = (IMasterRitualStone)tile; LocalRitualStorage stor = stone.getLocalStorage(); if(stor instanceof LocalStorageAlphaPact) { LocalStorageAlphaPact storage = (LocalStorageAlphaPact)stor; storage.thrallDemon(this); } } } super.onUpdate(); } @Override public float getEyeHeight() { return this.height * 0.8F; } /** * The speed it takes to move the entityliving's rotationPitch through the faceEntity method. This is only currently * use in wolves. */ @Override public int getVerticalFaceSpeed() { return this.isSitting() ? 20 : super.getVerticalFaceSpeed(); } @Override public void setTamed(boolean par1) { super.setTamed(par1); if (par1) { this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxTamedHealth); } else { this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxUntamedHealth); } } /** * Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a pig. */ @Override public boolean interact(EntityPlayer par1EntityPlayer) { ItemStack itemstack = par1EntityPlayer.inventory.getCurrentItem(); if (this.isTamed()) { if (itemstack != null) { if (itemstack.getItem() instanceof ItemFood) { ItemFood itemfood = (ItemFood) itemstack.getItem(); if (itemfood.isWolfsFavoriteMeat() && this.dataWatcher.getWatchableObjectFloat(18) < maxTamedHealth) { if (!par1EntityPlayer.capabilities.isCreativeMode) { --itemstack.stackSize; } this.heal((float) itemfood.func_150905_g(itemstack)); if (itemstack.stackSize <= 0) { par1EntityPlayer.inventory.setInventorySlotContents(par1EntityPlayer.inventory.currentItem, null); } return true; } } } if (this.getOwner() instanceof EntityPlayer && SpellHelper.getUsername(par1EntityPlayer).equalsIgnoreCase(SpellHelper.getUsername((EntityPlayer) this.getOwner())) && !this.isBreedingItem(itemstack)) { if (!this.worldObj.isRemote) { this.aiSit.setSitting(!this.isSitting()); this.isJumping = false; this.setPathToEntity(null); this.setTarget(null); this.setAttackTarget(null); } this.sendSittingMessageToPlayer(par1EntityPlayer, !this.isSitting()); } } else if (this.isTameable() && itemstack != null && itemstack.getItem().equals(ModItems.weakBloodOrb) && !this.isAngry()) { if (!par1EntityPlayer.capabilities.isCreativeMode) { --itemstack.stackSize; } if (itemstack.stackSize <= 0) { par1EntityPlayer.inventory.setInventorySlotContents(par1EntityPlayer.inventory.currentItem, null); } if (!this.worldObj.isRemote) { if (this.rand.nextInt(1) == 0) { this.setTamed(true); this.setPathToEntity(null); this.setAttackTarget(null); this.aiSit.setSitting(true); this.setHealth(maxTamedHealth); this.func_152115_b(par1EntityPlayer.getUniqueID().toString()); this.playTameEffect(true); this.worldObj.setEntityState(this, (byte) 7); } else { this.playTameEffect(false); this.worldObj.setEntityState(this, (byte) 6); } } return true; } return super.interact(par1EntityPlayer); } public boolean isBreedingItem(ItemStack par1ItemStack) { return false; } /** * Determines whether this wolf is angry or not. */ public boolean isAngry() { return this.isAngry; } /** * Sets whether this wolf is angry or not. */ public void setAngry(boolean angry) { this.isAngry = angry; } /** * Returns true if the mob is currently able to mate with the specified mob. */ @Override public boolean canMateWith(EntityAnimal par1EntityAnimal) { return false; } /** * Determines if an entity can be despawned, used on idle far away entities */ @Override protected boolean canDespawn() { //return !this.isTamed() && this.ticksExisted > 2400; return false; } /** * A call to determine if this entity should attack the other entity */ @Override public boolean func_142018_a(EntityLivingBase par1EntityLivingBase, EntityLivingBase par2EntityLivingBase) { if (!(par1EntityLivingBase instanceof EntityCreeper) && !(par1EntityLivingBase instanceof EntityGhast)) { if (par1EntityLivingBase instanceof EntityDemon) { EntityDemon entitywolf = (EntityDemon) par1EntityLivingBase; if (entitywolf.isTamed() && entitywolf.getOwner() == par2EntityLivingBase) { return false; } } return par1EntityLivingBase instanceof EntityPlayer && par2EntityLivingBase instanceof EntityPlayer && !((EntityPlayer) par2EntityLivingBase).canAttackPlayer((EntityPlayer) par1EntityLivingBase) ? false : !(par1EntityLivingBase instanceof EntityHorse) || !((EntityHorse) par1EntityLivingBase).isTame(); } else { return false; } } @Override public boolean attackEntityAsMob(Entity par1Entity) { int i = this.isTamed() ? 20 : 20; if(par1Entity instanceof IHoardDemon && ((IHoardDemon) par1Entity).isSamePortal(this)) { return false; } return par1Entity.attackEntityFrom(DamageSource.causeMobDamage(this), (float) i); } /** * Attack the specified entity using a ranged attack. */ @Override public void attackEntityWithRangedAttack(EntityLivingBase par1EntityLivingBase, float par2) { if(par1EntityLivingBase instanceof IHoardDemon && ((IHoardDemon) par1EntityLivingBase).isSamePortal(this)) { return; } HolyProjectile hol = new HolyProjectile(worldObj, this, par1EntityLivingBase, 1.8f, 0f, 15, 600); this.worldObj.spawnEntityInWorld(hol); } /** * sets this entity's combat AI. */ public void setCombatTask() { this.tasks.removeTask(this.aiAttackOnCollide); this.tasks.removeTask(this.aiArrowAttack); this.tasks.addTask(4, this.aiArrowAttack); this.tasks.addTask(5, this.aiAttackOnCollide); } @Override public boolean shouldUseRangedAttack() { return true; } @Override public boolean thrallDemon(Int3 location) { this.setPortalLocation(location); return true; } @Override public boolean isSamePortal(IHoardDemon demon) { Int3 position = demon.getPortalLocation(); TileEntity portal = worldObj.getTileEntity(this.demonPortal.xCoord, this.demonPortal.yCoord, this.demonPortal.zCoord); return portal instanceof TEDemonPortal ? portal == worldObj.getTileEntity(position.xCoord, position.yCoord, position.zCoord) : false; } }
isbjorntrading/aiocells
src/aiocells/demo_5.py
<reponame>isbjorntrading/aiocells #!/usr/bin/env python3 import asyncio from functools import partial import aiocells # This example demonstrates graph nodes that are coroutines. We use # a different computer; one that know how to deal with coroutines. def main(): graph = aiocells.DependencyGraph() # First, we add a lambda function before_sleep = graph.add_node(lambda: print("Sleeping...")) # Second, we create a coroutine function using functools.partial. This # is the closest we can get to a lambda for an async function sleep_2 = partial(asyncio.sleep, 2) # Finally, another lambda function wake_up = graph.add_node(lambda: print("Woke up!")) # Here, 'sleep' will implicitly be added to the graph because it is # part of the precedence relationship graph.add_precedence(before_sleep, sleep_2) graph.add_precedence(sleep_2, wake_up) # Here, we use the `async_compute_sequential`, which, like # `compute_sequential`, call the nodes in a topologically correct sequence. # However, whereas `compute_sequential` only supports vanilla callables, # `async_compute_sequential` additionally supports coroutine functions, # as defined by `inspect.iscoroutinefunction`. However, the execution is # still sequential. Each coroutine function is executed using 'await' and # must complete before the next node is executed. The function # `async_compute_sequential` is a coroutine and must be awaited. Here, # we simply pass it to `asyncio.run`. asyncio.run(aiocells.async_compute_sequential(graph))
zhiming-shen/Xen-Blanket-NG
xen/xen-4.2.2/tools/qemu-xen-traditional/linux-user/arm/nwfpe/fpa11.c
/* NetWinder Floating Point Emulator (c) Rebel.COM, 1998,1999 Direct questions, comments to <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "fpa11.h" #include "fpopcode.h" //#include "fpmodule.h" //#include "fpmodule.inl" //#include <asm/system.h> #include <stdio.h> /* forward declarations */ unsigned int EmulateCPDO(const unsigned int); unsigned int EmulateCPDT(const unsigned int); unsigned int EmulateCPRT(const unsigned int); FPA11* qemufpa=0; CPUARMState* user_registers; /* Reset the FPA11 chip. Called to initialize and reset the emulator. */ void resetFPA11(void) { int i; FPA11 *fpa11 = GET_FPA11(); /* initialize the register type array */ for (i=0;i<=7;i++) { fpa11->fType[i] = typeNone; } /* FPSR: set system id to FP_EMULATOR, set AC, clear all other bits */ fpa11->fpsr = FP_EMULATOR | BIT_AC; /* FPCR: set SB, AB and DA bits, clear all others */ #ifdef MAINTAIN_FPCR fpa11->fpcr = MASK_RESET; #endif } void SetRoundingMode(const unsigned int opcode) { int rounding_mode; FPA11 *fpa11 = GET_FPA11(); #ifdef MAINTAIN_FPCR fpa11->fpcr &= ~MASK_ROUNDING_MODE; #endif switch (opcode & MASK_ROUNDING_MODE) { default: case ROUND_TO_NEAREST: rounding_mode = float_round_nearest_even; #ifdef MAINTAIN_FPCR fpa11->fpcr |= ROUND_TO_NEAREST; #endif break; case ROUND_TO_PLUS_INFINITY: rounding_mode = float_round_up; #ifdef MAINTAIN_FPCR fpa11->fpcr |= ROUND_TO_PLUS_INFINITY; #endif break; case ROUND_TO_MINUS_INFINITY: rounding_mode = float_round_down; #ifdef MAINTAIN_FPCR fpa11->fpcr |= ROUND_TO_MINUS_INFINITY; #endif break; case ROUND_TO_ZERO: rounding_mode = float_round_to_zero; #ifdef MAINTAIN_FPCR fpa11->fpcr |= ROUND_TO_ZERO; #endif break; } set_float_rounding_mode(rounding_mode, &fpa11->fp_status); } void SetRoundingPrecision(const unsigned int opcode) { int rounding_precision; FPA11 *fpa11 = GET_FPA11(); #ifdef MAINTAIN_FPCR fpa11->fpcr &= ~MASK_ROUNDING_PRECISION; #endif switch (opcode & MASK_ROUNDING_PRECISION) { case ROUND_SINGLE: rounding_precision = 32; #ifdef MAINTAIN_FPCR fpa11->fpcr |= ROUND_SINGLE; #endif break; case ROUND_DOUBLE: rounding_precision = 64; #ifdef MAINTAIN_FPCR fpa11->fpcr |= ROUND_DOUBLE; #endif break; case ROUND_EXTENDED: rounding_precision = 80; #ifdef MAINTAIN_FPCR fpa11->fpcr |= ROUND_EXTENDED; #endif break; default: rounding_precision = 80; } set_floatx80_rounding_precision(rounding_precision, &fpa11->fp_status); } /* Emulate the instruction in the opcode. */ /* ??? This is not thread safe. */ unsigned int EmulateAll(unsigned int opcode, FPA11* qfpa, CPUARMState* qregs) { unsigned int nRc = 0; // unsigned long flags; FPA11 *fpa11; // save_flags(flags); sti(); qemufpa=qfpa; user_registers=qregs; #if 0 fprintf(stderr,"emulating FP insn 0x%08x, PC=0x%08x\n", opcode, qregs[REG_PC]); #endif fpa11 = GET_FPA11(); if (fpa11->initflag == 0) /* good place for __builtin_expect */ { resetFPA11(); SetRoundingMode(ROUND_TO_NEAREST); SetRoundingPrecision(ROUND_EXTENDED); fpa11->initflag = 1; } set_float_exception_flags(0, &fpa11->fp_status); if (TEST_OPCODE(opcode,MASK_CPRT)) { //fprintf(stderr,"emulating CPRT\n"); /* Emulate conversion opcodes. */ /* Emulate register transfer opcodes. */ /* Emulate comparison opcodes. */ nRc = EmulateCPRT(opcode); } else if (TEST_OPCODE(opcode,MASK_CPDO)) { //fprintf(stderr,"emulating CPDO\n"); /* Emulate monadic arithmetic opcodes. */ /* Emulate dyadic arithmetic opcodes. */ nRc = EmulateCPDO(opcode); } else if (TEST_OPCODE(opcode,MASK_CPDT)) { //fprintf(stderr,"emulating CPDT\n"); /* Emulate load/store opcodes. */ /* Emulate load/store multiple opcodes. */ nRc = EmulateCPDT(opcode); } else { /* Invalid instruction detected. Return FALSE. */ nRc = 0; } // restore_flags(flags); if(nRc == 1 && get_float_exception_flags(&fpa11->fp_status)) { //printf("fef 0x%x\n",float_exception_flags); nRc=-get_float_exception_flags(&fpa11->fp_status); } //printf("returning %d\n",nRc); return(nRc); } #if 0 unsigned int EmulateAll1(unsigned int opcode) { switch ((opcode >> 24) & 0xf) { case 0xc: case 0xd: if ((opcode >> 20) & 0x1) { switch ((opcode >> 8) & 0xf) { case 0x1: return PerformLDF(opcode); break; case 0x2: return PerformLFM(opcode); break; default: return 0; } } else { switch ((opcode >> 8) & 0xf) { case 0x1: return PerformSTF(opcode); break; case 0x2: return PerformSFM(opcode); break; default: return 0; } } break; case 0xe: if (opcode & 0x10) return EmulateCPDO(opcode); else return EmulateCPRT(opcode); break; default: return 0; } } #endif
davidpicard/jkernelmachines
src/main/java/net/jkernelmachines/evaluation/NFoldCrossValidation.java
/******************************************************************************* * Copyright (c) 2016, <NAME>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package net.jkernelmachines.evaluation; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.jkernelmachines.classifier.Classifier; import net.jkernelmachines.type.TrainingSample; import net.jkernelmachines.util.ArraysUtils; import net.jkernelmachines.util.DebugPrinter; /** * <p>Class for performing N-Fold Cross-validation.</p> * <p>The list of samples used is taken in order. Let us consider 10 folds. * For the first fold, the first 10% are used for testing, and the remaining * 90% are used for training. For the second fold, the second 10% are used for * testing, and the remaining for training, and so on. * <b>Warning, no randomization is performed on the list, so be careful it is not * in the order of the classes which would bias the learning.</b> * This CV is balanced by default * </p> * @author picard * */ public class NFoldCrossValidation<T> implements CrossValidation, BalancedCrossValidation, MultipleEvaluatorCrossValidation<T> { boolean balanced = true; int N = 5; Classifier<T> classifier; List<TrainingSample<T>> list; Map<String, Evaluator<T>> evaluators = new HashMap<String, Evaluator<T>>(); Map<String, double[]> results = new HashMap<String, double[]>(); DebugPrinter debug = new DebugPrinter(); /** * Default constructor with number of folds, classifier, full samples list and evaluation metric. * @param n the number of folds * @param cls the classifier to evaluate * @param l the full list of sample * @param eval the evaluation metric to compute on each fold */ public NFoldCrossValidation(int n, Classifier<T> cls, List<TrainingSample<T>> l, Evaluator<T> eval) { N = Math.max(n, 2); // avoid 1 fold or less cv ;) classifier = cls; evaluators.put("default", eval); list = new ArrayList<TrainingSample<T>>(); list.addAll(l); } /* (non-Javadoc) * @see fr.lip6.evaluation.CrossValidation#run() */ @Override public void run() { for(String name : evaluators.keySet()) { results.put(name, new double[N]); } List<TrainingSample<T>> pos = new ArrayList<TrainingSample<T>>(); List<TrainingSample<T>> neg = new ArrayList<TrainingSample<T>>(); for(TrainingSample<T> t : list) { if(t.label == 1) { pos.add(t); } else { neg.add(t); } } for (int n = 0 ; n < N ; n++) { //setting nth fold List<TrainingSample<T>> test = new ArrayList<TrainingSample<T>>(); List<TrainingSample<T>> train = new ArrayList<TrainingSample<T>>(); if(balanced) { int step = pos.size() / N; test.addAll(pos.subList(n*step, (n+1)*step)); train.addAll(pos); step = neg.size() / N; test.addAll(neg.subList(n*step, (n+1)*step)); train.addAll(neg); train.removeAll(test); } else { int step = list.size() / N; test.addAll(list.subList(n*step, (n+1)*step)); train.addAll(list); train.removeAll(test); } debug.println(4, "train size: "+train.size()); debug.println(4, "test size: "+test.size()); // train classifier.train(train); //setting evaluator for(String name : evaluators.keySet()) { Evaluator<T> e = evaluators.get(name); e.setClassifier(classifier); e.setTrainingSet(null); e.setTestingSet(test); //compute results e.evaluate(); results.get(name)[n] = e.getScore(); } } } /* (non-Javadoc) * @see fr.lip6.evaluation.CrossValidation#getAverageScore() */ @Override public double getAverageScore() { double[] res = results.get("default"); if(res == null) return Double.NaN; return ArraysUtils.mean(res); } /* (non-Javadoc) * @see fr.lip6.evaluation.CrossValidation#getStdDevScore() */ @Override public double getStdDevScore() { double[] res = results.get("default"); if(res == null) return Double.NaN; return ArraysUtils.stddev(res); } /* (non-Javadoc) * @see fr.lip6.evaluation.CrossValidation#getScores() */ @Override public double[] getScores() { return results.get("default"); } /** * Returns true if the splits are balanced between positive and negative * @return true if balanced */ public boolean isBalanced() { return balanced; } /** * Set class balancing strategy when computing the splits * @param balanced true if enables balancing */ public void setBalanced(boolean balanced) { this.balanced = balanced; } /* (non-Javadoc) * @see fr.lip6.jkernelmachines.evaluation.MultipleEvaluatorCorssValidation#addEvaluator(java.lang.String, fr.lip6.jkernelmachines.evaluation.Evaluator) */ @Override public void addEvaluator(String name, Evaluator<T> e) { evaluators.put(name, e); } /* (non-Javadoc) * @see fr.lip6.jkernelmachines.evaluation.MultipleEvaluatorCorssValidation#removeEvaluator(java.lang.String) */ @Override public void removeEvaluator(String name) { if(evaluators.containsKey(name)) { evaluators.remove(name); } } /* (non-Javadoc) * @see fr.lip6.jkernelmachines.evaluation.MultipleEvaluatorCorssValidation#getAverageScore(java.lang.String) */ @Override public double getAverageScore(String name) { double[] res = results.get(name); if(res == null) { return Double.NaN; } return ArraysUtils.mean(res); } /* (non-Javadoc) * @see fr.lip6.jkernelmachines.evaluation.MultipleEvaluatorCorssValidation#getStdDevScore(java.lang.String) */ @Override public double getStdDevScore(String name) { double[] res = results.get(name); if(res == null) { return Double.NaN; } return ArraysUtils.stddev(res); } /* (non-Javadoc) * @see fr.lip6.jkernelmachines.evaluation.MultipleEvaluatorCorssValidation#getScores(java.lang.String) */ @Override public double[] getScores(String name) { return results.get(name); } }
soleil-taruto/Henrietta
e20190001_Hetapuz/Hetapuz/Hetapuz/Input.h
<gh_stars>0 enum { INP_DIR_2, INP_DIR_4, INP_DIR_6, INP_DIR_8, INP_START, INP_DECIDE, INP_CANCEL, INP_ROT_L, INP_ROT_R, INP_BOMB, INP_END, }; #define INP_ROT_DECIDE INP_ROT_L #define INP_ROT_CANCEL INP_ROT_R typedef struct Input_st { int Map_Key; int Map_Pad; int Press; int PressCount; int Hit; int RendaHit; } Input_t; extern Input_t InputList[2][INP_END]; void InitInput(void); int GetMap(Input_t *i, int forPad); void SetMap(Input_t *i, int forPad, int map); void RefreshInput(void); int GetInput(int pSide, int index, int mode); int GetPressPS(int pSide, int index); int GetHitPS(int pSide, int index); int GetRendaHitPS(int pSide, int index); int GetPress(int index); int GetHit(int index); int GetRendaHit(int index);
bcgov/OCWA
frontend/src/modules/requests/containers/form-wrapper.js
<gh_stars>1-10 import { connect } from 'react-redux'; import findKey from 'lodash/findKey'; import get from 'lodash/get'; import withRequest from '@src/modules/data/components/data-request'; import Form from '../components/request-form/form'; import { fetchForm } from '../actions'; import { formSchema } from '../schemas'; const mapStateToProps = (state, props) => { const formEntities = get(state, 'data.entities.forms', {}); const formId = findKey(formEntities, f => f.path === props.id); const form = get(formEntities, formId, {}); return { newRequestId: state.requests.newRequestId, form, formId, }; }; export default connect( mapStateToProps, { initialRequest: ({ id }) => fetchForm({ url: `/api/v2/requests/forms/${id}`, schema: formSchema, }), } )(withRequest(Form));
manjunathnilugal/PyBaMM
pybamm/models/submodels/active_material/__init__.py
<gh_stars>1-10 from .base_active_material import BaseModel from .constant_active_material import Constant from .stress_driven_active_material import StressDriven from .reaction_driven_active_material import ReactionDriven
winstin/Purestart
src/redux/components/Refund/index.js
<gh_stars>1-10 import React from 'react'; import {connect} from 'react-redux'; import { bindActionCreators } from 'redux' import Button from 'qnui/lib/button'; import Icon from 'qnui/lib/icon'; import Select, {Option} from 'qnui/lib/select'; import * as actionTypes from './RefundAction' import RefundTable from './TableConfig' import Search from './Search' import Refund from './Refund' import Scan from './Scan' import Detail from './Detail' import {DialogRefund} from './Dialog' import './main.css' class App extends React.Component { componentDidMount() { this.props.getRefund({ page_no:1, sort:"{}", }); } onSearch =(params)=>{ this.props.searchRefundOrder(params) } render() { const page = this.props.route.page; // url参数 console.log(this.props); return ( <div style={{height:'100%'}}> {/* 新建售后单 */} <DialogRefund title="新建售后单" visible={this.props.dialogShow.DialogRefund} onClose={()=>{this.props.toggleDialog('DialogRefund')}} onOk= {(params)=>{ this.props.addRefundOrder(params); this.props.toggleDialog('DialogRefund'); // 关闭 弹窗 }} /> <div className="excep-buttons" style={{display:page==='todo'?'block':'none'}}> <Button type="primary" onClick={()=>{this.props.toggleDialog('DialogRefund')}}> <Icon type="add" /> 新建售后单 </Button> </div> {/* 售后查询 */} <div className="excep-buttons" style={{display:page==='search'?'block':'none'}}> <Search onSearch={this.onSearch} /> </div> {/* 入库 */} <div className="excep-buttons" style={{display:page==='storage'?'block':'none'}}> <Refund /> </div> {/* 扫描 */} {page==='scan'?<Scan />:null} {/* 入库详情 */} {page==='detail'?<Detail />:null} { ['todo','search','storage'].indexOf(page)>-1 ?<RefundTable {...this.props} /> :null } </div> ); } } export default connect( (state)=>state.Refund, (dispatch)=>bindActionCreators(actionTypes,dispatch) )(App);
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/aarch64/clz.c
<reponame>best08618/asylo /* { dg-do compile } */ /* { dg-options "-O2" } */ unsigned int functest (unsigned int x) { return __builtin_clz (x); } /* { dg-final { scan-assembler "clz\tw" } } */
jeremiahtenbrink/SynapsFrontend
src/reducers/usersReducer.js
<reponame>jeremiahtenbrink/SynapsFrontend<gh_stars>1-10 import { SIGNED_IN, SIGNIN_FAILED, SIGNOUT, ATTEMPT_SIGNIN, USER_REGISTER_FAILED, USER_ATTEMPT_REGISTER, USER_REGISTER_COMPLETE, CHECK_USER_REGISTERED, } from '../actions'; /** * @typedef {object} UsersReducerState * @property {boolean} fetching - Fetching the user from the database. * @property {Error | null} error - Fetching the user from the database. * @property {User | {}} user - Fetching the user from the database. * @property {boolean} checkingRegistered - Fetching the user from the database. * @property {boolean} userRegistered - Fetching the user from the database. * @property {Error | null} registerError - Fetching the user from the database. */ /** * @type {UsersReducerState} */ const initialState = { user: {}, fetching: false, checkingRegistered: false, registering: false, userRegistered: false, registerError: null, error: null, }; /** * Users Reducer * @category Reducers * @function * @name usersReducer * @param {UsersReducerState} state * @param {Action} action * @returns {UsersReducerState} state */ export const usersReducer = (state = initialState, action) => { switch (action.type) { case 'SET_INIT_STATE': if ( action.payload && action.payload.name && action.payload.name.includes('users') && action.payload.value ) { return action.payload.value; } return state; case ATTEMPT_SIGNIN: return {...state, fetching: true}; case SIGNED_IN: return {...state, user: action.payload, fetching: false}; case SIGNIN_FAILED: return {...state, user: {}, fetching: false, error: action.payload}; case SIGNOUT: return {...state, user: {}, error: null}; case CHECK_USER_REGISTERED: return {...state, checkingRegistered: true}; case USER_ATTEMPT_REGISTER: return {...state, checkingRegistered: false, registering: true}; case USER_REGISTER_COMPLETE: return {...state, registering: false, userRegistered: true}; case USER_REGISTER_FAILED: return { ...state, user: {}, registering: false, userRegistered: false, registerError: action.payload, }; default: return state; } };
cisco-ie/cisco-proto
codegen/go/xr/65x/cisco_ios_xr_ipv4_igmp_oper/igmp/standby/vrfs/vrf/explicit_groups/explicit_group/igmp_edm_groups_et_bag.pb.go
<filename>codegen/go/xr/65x/cisco_ios_xr_ipv4_igmp_oper/igmp/standby/vrfs/vrf/explicit_groups/explicit_group/igmp_edm_groups_et_bag.pb.go /* Copyright 2019 Cisco Systems 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. */ // Code generated by protoc-gen-go. DO NOT EDIT. // source: igmp_edm_groups_et_bag.proto package cisco_ios_xr_ipv4_igmp_oper_igmp_standby_vrfs_vrf_explicit_groups_explicit_group import ( fmt "fmt" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type IgmpEdmGroupsEtBag_KEYS struct { VrfName string `protobuf:"bytes,1,opt,name=vrf_name,json=vrfName,proto3" json:"vrf_name,omitempty"` GroupAddress string `protobuf:"bytes,2,opt,name=group_address,json=groupAddress,proto3" json:"group_address,omitempty"` InterfaceName string `protobuf:"bytes,3,opt,name=interface_name,json=interfaceName,proto3" json:"interface_name,omitempty"` SourceAddress string `protobuf:"bytes,4,opt,name=source_address,json=sourceAddress,proto3" json:"source_address,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *IgmpEdmGroupsEtBag_KEYS) Reset() { *m = IgmpEdmGroupsEtBag_KEYS{} } func (m *IgmpEdmGroupsEtBag_KEYS) String() string { return proto.CompactTextString(m) } func (*IgmpEdmGroupsEtBag_KEYS) ProtoMessage() {} func (*IgmpEdmGroupsEtBag_KEYS) Descriptor() ([]byte, []int) { return fileDescriptor_63cc168d6bd20e9e, []int{0} } func (m *IgmpEdmGroupsEtBag_KEYS) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_IgmpEdmGroupsEtBag_KEYS.Unmarshal(m, b) } func (m *IgmpEdmGroupsEtBag_KEYS) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_IgmpEdmGroupsEtBag_KEYS.Marshal(b, m, deterministic) } func (m *IgmpEdmGroupsEtBag_KEYS) XXX_Merge(src proto.Message) { xxx_messageInfo_IgmpEdmGroupsEtBag_KEYS.Merge(m, src) } func (m *IgmpEdmGroupsEtBag_KEYS) XXX_Size() int { return xxx_messageInfo_IgmpEdmGroupsEtBag_KEYS.Size(m) } func (m *IgmpEdmGroupsEtBag_KEYS) XXX_DiscardUnknown() { xxx_messageInfo_IgmpEdmGroupsEtBag_KEYS.DiscardUnknown(m) } var xxx_messageInfo_IgmpEdmGroupsEtBag_KEYS proto.InternalMessageInfo func (m *IgmpEdmGroupsEtBag_KEYS) GetVrfName() string { if m != nil { return m.VrfName } return "" } func (m *IgmpEdmGroupsEtBag_KEYS) GetGroupAddress() string { if m != nil { return m.GroupAddress } return "" } func (m *IgmpEdmGroupsEtBag_KEYS) GetInterfaceName() string { if m != nil { return m.InterfaceName } return "" } func (m *IgmpEdmGroupsEtBag_KEYS) GetSourceAddress() string { if m != nil { return m.SourceAddress } return "" } type IgmpAddrtype struct { AfName string `protobuf:"bytes,1,opt,name=af_name,json=afName,proto3" json:"af_name,omitempty"` Ipv4Address string `protobuf:"bytes,2,opt,name=ipv4_address,json=ipv4Address,proto3" json:"ipv4_address,omitempty"` Ipv6Address string `protobuf:"bytes,3,opt,name=ipv6_address,json=ipv6Address,proto3" json:"ipv6_address,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *IgmpAddrtype) Reset() { *m = IgmpAddrtype{} } func (m *IgmpAddrtype) String() string { return proto.CompactTextString(m) } func (*IgmpAddrtype) ProtoMessage() {} func (*IgmpAddrtype) Descriptor() ([]byte, []int) { return fileDescriptor_63cc168d6bd20e9e, []int{1} } func (m *IgmpAddrtype) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_IgmpAddrtype.Unmarshal(m, b) } func (m *IgmpAddrtype) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_IgmpAddrtype.Marshal(b, m, deterministic) } func (m *IgmpAddrtype) XXX_Merge(src proto.Message) { xxx_messageInfo_IgmpAddrtype.Merge(m, src) } func (m *IgmpAddrtype) XXX_Size() int { return xxx_messageInfo_IgmpAddrtype.Size(m) } func (m *IgmpAddrtype) XXX_DiscardUnknown() { xxx_messageInfo_IgmpAddrtype.DiscardUnknown(m) } var xxx_messageInfo_IgmpAddrtype proto.InternalMessageInfo func (m *IgmpAddrtype) GetAfName() string { if m != nil { return m.AfName } return "" } func (m *IgmpAddrtype) GetIpv4Address() string { if m != nil { return m.Ipv4Address } return "" } func (m *IgmpAddrtype) GetIpv6Address() string { if m != nil { return m.Ipv6Address } return "" } type IgmpEdmGroupsBag struct { GroupAddressXr *IgmpAddrtype `protobuf:"bytes,1,opt,name=group_address_xr,json=groupAddressXr,proto3" json:"group_address_xr,omitempty"` InterfaceNameXr string `protobuf:"bytes,2,opt,name=interface_name_xr,json=interfaceNameXr,proto3" json:"interface_name_xr,omitempty"` Uptime uint64 `protobuf:"varint,3,opt,name=uptime,proto3" json:"uptime,omitempty"` ExpirationTime int32 `protobuf:"zigzag32,4,opt,name=expiration_time,json=expirationTime,proto3" json:"expiration_time,omitempty"` LastReporter *IgmpAddrtype `protobuf:"bytes,5,opt,name=last_reporter,json=lastReporter,proto3" json:"last_reporter,omitempty"` ExplicitTrackingEnabled bool `protobuf:"varint,6,opt,name=explicit_tracking_enabled,json=explicitTrackingEnabled,proto3" json:"explicit_tracking_enabled,omitempty"` IsSelfJoin bool `protobuf:"varint,7,opt,name=is_self_join,json=isSelfJoin,proto3" json:"is_self_join,omitempty"` RowStatus string `protobuf:"bytes,8,opt,name=row_status,json=rowStatus,proto3" json:"row_status,omitempty"` IsLowMemory bool `protobuf:"varint,9,opt,name=is_low_memory,json=isLowMemory,proto3" json:"is_low_memory,omitempty"` RouterFilterMode uint32 `protobuf:"varint,10,opt,name=router_filter_mode,json=routerFilterMode,proto3" json:"router_filter_mode,omitempty"` SourceAddress *IgmpAddrtype `protobuf:"bytes,11,opt,name=source_address,json=sourceAddress,proto3" json:"source_address,omitempty"` OlderHostVersion1Timer uint32 `protobuf:"varint,12,opt,name=older_host_version1_timer,json=olderHostVersion1Timer,proto3" json:"older_host_version1_timer,omitempty"` OlderHostVersion2Timer uint32 `protobuf:"varint,13,opt,name=older_host_version2_timer,json=olderHostVersion2Timer,proto3" json:"older_host_version2_timer,omitempty"` IsAdded bool `protobuf:"varint,14,opt,name=is_added,json=isAdded,proto3" json:"is_added,omitempty"` IsSuppressed bool `protobuf:"varint,15,opt,name=is_suppressed,json=isSuppressed,proto3" json:"is_suppressed,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *IgmpEdmGroupsBag) Reset() { *m = IgmpEdmGroupsBag{} } func (m *IgmpEdmGroupsBag) String() string { return proto.CompactTextString(m) } func (*IgmpEdmGroupsBag) ProtoMessage() {} func (*IgmpEdmGroupsBag) Descriptor() ([]byte, []int) { return fileDescriptor_63cc168d6bd20e9e, []int{2} } func (m *IgmpEdmGroupsBag) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_IgmpEdmGroupsBag.Unmarshal(m, b) } func (m *IgmpEdmGroupsBag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_IgmpEdmGroupsBag.Marshal(b, m, deterministic) } func (m *IgmpEdmGroupsBag) XXX_Merge(src proto.Message) { xxx_messageInfo_IgmpEdmGroupsBag.Merge(m, src) } func (m *IgmpEdmGroupsBag) XXX_Size() int { return xxx_messageInfo_IgmpEdmGroupsBag.Size(m) } func (m *IgmpEdmGroupsBag) XXX_DiscardUnknown() { xxx_messageInfo_IgmpEdmGroupsBag.DiscardUnknown(m) } var xxx_messageInfo_IgmpEdmGroupsBag proto.InternalMessageInfo func (m *IgmpEdmGroupsBag) GetGroupAddressXr() *IgmpAddrtype { if m != nil { return m.GroupAddressXr } return nil } func (m *IgmpEdmGroupsBag) GetInterfaceNameXr() string { if m != nil { return m.InterfaceNameXr } return "" } func (m *IgmpEdmGroupsBag) GetUptime() uint64 { if m != nil { return m.Uptime } return 0 } func (m *IgmpEdmGroupsBag) GetExpirationTime() int32 { if m != nil { return m.ExpirationTime } return 0 } func (m *IgmpEdmGroupsBag) GetLastReporter() *IgmpAddrtype { if m != nil { return m.LastReporter } return nil } func (m *IgmpEdmGroupsBag) GetExplicitTrackingEnabled() bool { if m != nil { return m.ExplicitTrackingEnabled } return false } func (m *IgmpEdmGroupsBag) GetIsSelfJoin() bool { if m != nil { return m.IsSelfJoin } return false } func (m *IgmpEdmGroupsBag) GetRowStatus() string { if m != nil { return m.RowStatus } return "" } func (m *IgmpEdmGroupsBag) GetIsLowMemory() bool { if m != nil { return m.IsLowMemory } return false } func (m *IgmpEdmGroupsBag) GetRouterFilterMode() uint32 { if m != nil { return m.RouterFilterMode } return 0 } func (m *IgmpEdmGroupsBag) GetSourceAddress() *IgmpAddrtype { if m != nil { return m.SourceAddress } return nil } func (m *IgmpEdmGroupsBag) GetOlderHostVersion1Timer() uint32 { if m != nil { return m.OlderHostVersion1Timer } return 0 } func (m *IgmpEdmGroupsBag) GetOlderHostVersion2Timer() uint32 { if m != nil { return m.OlderHostVersion2Timer } return 0 } func (m *IgmpEdmGroupsBag) GetIsAdded() bool { if m != nil { return m.IsAdded } return false } func (m *IgmpEdmGroupsBag) GetIsSuppressed() bool { if m != nil { return m.IsSuppressed } return false } type IgmpEdmGroupsHostBag struct { Address *IgmpAddrtype `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Uptime uint32 `protobuf:"varint,2,opt,name=uptime,proto3" json:"uptime,omitempty"` IsExclude bool `protobuf:"varint,3,opt,name=is_exclude,json=isExclude,proto3" json:"is_exclude,omitempty"` ExpirationTime uint32 `protobuf:"varint,4,opt,name=expiration_time,json=expirationTime,proto3" json:"expiration_time,omitempty"` SourceCount uint32 `protobuf:"varint,5,opt,name=source_count,json=sourceCount,proto3" json:"source_count,omitempty"` SourceAddress []*IgmpAddrtype `protobuf:"bytes,6,rep,name=source_address,json=sourceAddress,proto3" json:"source_address,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *IgmpEdmGroupsHostBag) Reset() { *m = IgmpEdmGroupsHostBag{} } func (m *IgmpEdmGroupsHostBag) String() string { return proto.CompactTextString(m) } func (*IgmpEdmGroupsHostBag) ProtoMessage() {} func (*IgmpEdmGroupsHostBag) Descriptor() ([]byte, []int) { return fileDescriptor_63cc168d6bd20e9e, []int{3} } func (m *IgmpEdmGroupsHostBag) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_IgmpEdmGroupsHostBag.Unmarshal(m, b) } func (m *IgmpEdmGroupsHostBag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_IgmpEdmGroupsHostBag.Marshal(b, m, deterministic) } func (m *IgmpEdmGroupsHostBag) XXX_Merge(src proto.Message) { xxx_messageInfo_IgmpEdmGroupsHostBag.Merge(m, src) } func (m *IgmpEdmGroupsHostBag) XXX_Size() int { return xxx_messageInfo_IgmpEdmGroupsHostBag.Size(m) } func (m *IgmpEdmGroupsHostBag) XXX_DiscardUnknown() { xxx_messageInfo_IgmpEdmGroupsHostBag.DiscardUnknown(m) } var xxx_messageInfo_IgmpEdmGroupsHostBag proto.InternalMessageInfo func (m *IgmpEdmGroupsHostBag) GetAddress() *IgmpAddrtype { if m != nil { return m.Address } return nil } func (m *IgmpEdmGroupsHostBag) GetUptime() uint32 { if m != nil { return m.Uptime } return 0 } func (m *IgmpEdmGroupsHostBag) GetIsExclude() bool { if m != nil { return m.IsExclude } return false } func (m *IgmpEdmGroupsHostBag) GetExpirationTime() uint32 { if m != nil { return m.ExpirationTime } return 0 } func (m *IgmpEdmGroupsHostBag) GetSourceCount() uint32 { if m != nil { return m.SourceCount } return 0 } func (m *IgmpEdmGroupsHostBag) GetSourceAddress() []*IgmpAddrtype { if m != nil { return m.SourceAddress } return nil } type IgmpEdmGroupsEtBag struct { IncludeHosts uint32 `protobuf:"varint,50,opt,name=include_hosts,json=includeHosts,proto3" json:"include_hosts,omitempty"` ExcludeHosts uint32 `protobuf:"varint,51,opt,name=exclude_hosts,json=excludeHosts,proto3" json:"exclude_hosts,omitempty"` GroupInfo *IgmpEdmGroupsBag `protobuf:"bytes,52,opt,name=group_info,json=groupInfo,proto3" json:"group_info,omitempty"` Host []*IgmpEdmGroupsHostBag `protobuf:"bytes,53,rep,name=host,proto3" json:"host,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *IgmpEdmGroupsEtBag) Reset() { *m = IgmpEdmGroupsEtBag{} } func (m *IgmpEdmGroupsEtBag) String() string { return proto.CompactTextString(m) } func (*IgmpEdmGroupsEtBag) ProtoMessage() {} func (*IgmpEdmGroupsEtBag) Descriptor() ([]byte, []int) { return fileDescriptor_63cc168d6bd20e9e, []int{4} } func (m *IgmpEdmGroupsEtBag) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_IgmpEdmGroupsEtBag.Unmarshal(m, b) } func (m *IgmpEdmGroupsEtBag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_IgmpEdmGroupsEtBag.Marshal(b, m, deterministic) } func (m *IgmpEdmGroupsEtBag) XXX_Merge(src proto.Message) { xxx_messageInfo_IgmpEdmGroupsEtBag.Merge(m, src) } func (m *IgmpEdmGroupsEtBag) XXX_Size() int { return xxx_messageInfo_IgmpEdmGroupsEtBag.Size(m) } func (m *IgmpEdmGroupsEtBag) XXX_DiscardUnknown() { xxx_messageInfo_IgmpEdmGroupsEtBag.DiscardUnknown(m) } var xxx_messageInfo_IgmpEdmGroupsEtBag proto.InternalMessageInfo func (m *IgmpEdmGroupsEtBag) GetIncludeHosts() uint32 { if m != nil { return m.IncludeHosts } return 0 } func (m *IgmpEdmGroupsEtBag) GetExcludeHosts() uint32 { if m != nil { return m.ExcludeHosts } return 0 } func (m *IgmpEdmGroupsEtBag) GetGroupInfo() *IgmpEdmGroupsBag { if m != nil { return m.GroupInfo } return nil } func (m *IgmpEdmGroupsEtBag) GetHost() []*IgmpEdmGroupsHostBag { if m != nil { return m.Host } return nil } func init() { proto.RegisterType((*IgmpEdmGroupsEtBag_KEYS)(nil), "cisco_ios_xr_ipv4_igmp_oper.igmp.standby.vrfs.vrf.explicit_groups.explicit_group.igmp_edm_groups_et_bag_KEYS") proto.RegisterType((*IgmpAddrtype)(nil), "cisco_ios_xr_ipv4_igmp_oper.igmp.standby.vrfs.vrf.explicit_groups.explicit_group.igmp_addrtype") proto.RegisterType((*IgmpEdmGroupsBag)(nil), "cisco_ios_xr_ipv4_igmp_oper.igmp.standby.vrfs.vrf.explicit_groups.explicit_group.igmp_edm_groups_bag") proto.RegisterType((*IgmpEdmGroupsHostBag)(nil), "cisco_ios_xr_ipv4_igmp_oper.igmp.standby.vrfs.vrf.explicit_groups.explicit_group.igmp_edm_groups_host_bag") proto.RegisterType((*IgmpEdmGroupsEtBag)(nil), "cisco_ios_xr_ipv4_igmp_oper.igmp.standby.vrfs.vrf.explicit_groups.explicit_group.igmp_edm_groups_et_bag") } func init() { proto.RegisterFile("igmp_edm_groups_et_bag.proto", fileDescriptor_63cc168d6bd20e9e) } var fileDescriptor_63cc168d6bd20e9e = []byte{ // 755 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x56, 0x5d, 0x6b, 0xe3, 0x46, 0x14, 0x45, 0x71, 0xea, 0x8f, 0x6b, 0xc9, 0x49, 0xa6, 0x90, 0xc8, 0xb4, 0x01, 0xc7, 0x25, 0x34, 0x94, 0x62, 0xa8, 0x93, 0x06, 0xda, 0xb7, 0x50, 0x52, 0xfa, 0x95, 0x52, 0xe4, 0x50, 0xd2, 0xa7, 0x41, 0x96, 0x46, 0xee, 0xa4, 0xb2, 0x46, 0xcc, 0x8c, 0xfc, 0xf1, 0xd2, 0xa7, 0x50, 0xe8, 0xcf, 0x58, 0xf6, 0x71, 0x7f, 0xd9, 0xfe, 0x8b, 0x65, 0xee, 0xc8, 0xde, 0x28, 0xf1, 0xbe, 0x6d, 0xfc, 0x92, 0x68, 0xce, 0x3d, 0x33, 0xf7, 0xdc, 0x33, 0xf7, 0x4a, 0x86, 0xcf, 0xf9, 0x64, 0x9a, 0x53, 0x16, 0x4f, 0xe9, 0x44, 0x8a, 0x22, 0x57, 0x94, 0x69, 0x3a, 0x0e, 0x27, 0x83, 0x5c, 0x0a, 0x2d, 0xc8, 0x1f, 0x11, 0x57, 0x91, 0xa0, 0x5c, 0x28, 0xba, 0x90, 0x94, 0xe7, 0xb3, 0x0b, 0x8a, 0x7c, 0x91, 0x33, 0x39, 0x30, 0x4f, 0x03, 0xa5, 0xc3, 0x2c, 0x1e, 0x2f, 0x07, 0x33, 0x99, 0x28, 0xf3, 0x67, 0xc0, 0x16, 0x79, 0xca, 0x23, 0xae, 0xcb, 0xf3, 0x9e, 0xac, 0xfb, 0x6f, 0x1c, 0xf8, 0x6c, 0x73, 0x4a, 0xfa, 0xeb, 0xf5, 0x5f, 0x23, 0xd2, 0x85, 0xe6, 0x4c, 0x26, 0x34, 0x0b, 0xa7, 0xcc, 0x77, 0x7a, 0xce, 0x59, 0x2b, 0x68, 0xcc, 0x64, 0xf2, 0x7b, 0x38, 0x65, 0xe4, 0x0b, 0xf0, 0x70, 0x03, 0x0d, 0xe3, 0x58, 0x32, 0xa5, 0xfc, 0x1d, 0x8c, 0xbb, 0x08, 0x5e, 0x59, 0x8c, 0x9c, 0x42, 0x87, 0x67, 0x9a, 0xc9, 0x24, 0x8c, 0x98, 0x3d, 0xa5, 0x86, 0x2c, 0x6f, 0x8d, 0xe2, 0x59, 0xa7, 0xd0, 0x51, 0xa2, 0x90, 0x11, 0x5b, 0x1f, 0xb6, 0x6b, 0x69, 0x16, 0x2d, 0x4f, 0xeb, 0x67, 0xe0, 0xa1, 0x58, 0x43, 0xd2, 0xcb, 0x9c, 0x91, 0x23, 0x68, 0x84, 0x15, 0x75, 0xf5, 0xd0, 0x8a, 0x3b, 0x01, 0x17, 0xed, 0xa9, 0x6a, 0x6b, 0x1b, 0x6c, 0x25, 0xcd, 0x52, 0x2e, 0xd7, 0x94, 0xda, 0x9a, 0x72, 0xb9, 0xca, 0xf7, 0xba, 0x01, 0x9f, 0x3e, 0x75, 0x67, 0x1c, 0x4e, 0xc8, 0xff, 0x0e, 0xec, 0x57, 0x6a, 0xa7, 0x0b, 0x89, 0x02, 0xda, 0x43, 0x3a, 0xf8, 0xd8, 0x77, 0x34, 0xa8, 0x94, 0x1c, 0x74, 0x1e, 0xfb, 0x7b, 0x27, 0xc9, 0x57, 0x70, 0x50, 0x75, 0xd8, 0x68, 0xb1, 0xe5, 0xee, 0x55, 0x4c, 0xbe, 0x93, 0xe4, 0x10, 0xea, 0x45, 0xae, 0x79, 0x79, 0x0b, 0xbb, 0x41, 0xb9, 0x22, 0x5f, 0xc2, 0x1e, 0x5b, 0xe4, 0x5c, 0x86, 0x9a, 0x8b, 0x8c, 0x22, 0xc1, 0xf8, 0x7f, 0x10, 0x74, 0xde, 0xc3, 0xb7, 0x86, 0xf8, 0xe0, 0x80, 0x97, 0x86, 0x4a, 0x53, 0xc9, 0x72, 0x21, 0x35, 0x93, 0xfe, 0x27, 0xdb, 0xa9, 0xda, 0x35, 0x59, 0x83, 0x32, 0x29, 0xf9, 0x1e, 0xba, 0x6b, 0xb6, 0x96, 0x61, 0xf4, 0x0f, 0xcf, 0x26, 0x94, 0x65, 0xe1, 0x38, 0x65, 0xb1, 0x5f, 0xef, 0x39, 0x67, 0xcd, 0xe0, 0x68, 0x45, 0xb8, 0x2d, 0xe3, 0xd7, 0x36, 0x4c, 0x7a, 0xe0, 0x72, 0x45, 0x15, 0x4b, 0x13, 0x7a, 0x2f, 0x78, 0xe6, 0x37, 0x90, 0x0e, 0x5c, 0x8d, 0x58, 0x9a, 0xfc, 0x22, 0x78, 0x46, 0x8e, 0x01, 0xa4, 0x98, 0x53, 0xa5, 0x43, 0x5d, 0x28, 0xbf, 0x89, 0x56, 0xb6, 0xa4, 0x98, 0x8f, 0x10, 0x20, 0x7d, 0xf0, 0xb8, 0xa2, 0xa9, 0x98, 0xd3, 0x29, 0x9b, 0x0a, 0xb9, 0xf4, 0x5b, 0x78, 0x42, 0x9b, 0xab, 0xdf, 0xc4, 0xfc, 0x06, 0x21, 0xf2, 0x35, 0x10, 0x29, 0x0a, 0xcd, 0x24, 0x4d, 0x78, 0x6a, 0xfe, 0x4d, 0x45, 0xcc, 0x7c, 0xe8, 0x39, 0x67, 0x5e, 0xb0, 0x6f, 0x23, 0x3f, 0x62, 0xe0, 0x46, 0xc4, 0x8c, 0xfc, 0xe7, 0x3c, 0x6b, 0xff, 0xf6, 0x76, 0x6c, 0xad, 0xce, 0x17, 0xf9, 0x0e, 0xba, 0x22, 0x8d, 0x99, 0xa4, 0x7f, 0x0b, 0xa5, 0xe9, 0x8c, 0x49, 0xc5, 0x45, 0xf6, 0x0d, 0x36, 0x84, 0xf4, 0x5d, 0x54, 0x7f, 0x88, 0x84, 0x9f, 0x84, 0xd2, 0x7f, 0x96, 0x61, 0xd3, 0x18, 0x72, 0xf3, 0xd6, 0x61, 0xb9, 0xd5, 0xdb, 0xbc, 0x75, 0x68, 0xb7, 0x76, 0xa1, 0xc9, 0x95, 0xd1, 0xc4, 0x62, 0xbf, 0x83, 0x5e, 0x36, 0xb8, 0xba, 0x32, 0x4b, 0xf3, 0x8e, 0x31, 0x97, 0x55, 0xe4, 0xb9, 0xd1, 0xc7, 0x62, 0x7f, 0x0f, 0xe3, 0x2e, 0x57, 0xa3, 0x35, 0xd6, 0x7f, 0x55, 0x03, 0xff, 0xe9, 0x94, 0xa2, 0x0a, 0x33, 0xaa, 0x4b, 0x68, 0xac, 0x3c, 0xdd, 0xd2, 0x80, 0xae, 0xf2, 0x3d, 0x9a, 0xb6, 0x1d, 0xac, 0x7f, 0x35, 0x6d, 0xc7, 0x00, 0x5c, 0x51, 0xb6, 0x88, 0xd2, 0x22, 0xb6, 0x93, 0xd8, 0x0c, 0x5a, 0x5c, 0x5d, 0x5b, 0xe0, 0x43, 0xc3, 0xe8, 0x3d, 0x1b, 0xc6, 0x13, 0x70, 0xcb, 0xae, 0x89, 0x44, 0x91, 0x69, 0x1c, 0x45, 0x2f, 0x68, 0x5b, 0xec, 0x07, 0x03, 0x6d, 0xea, 0xac, 0x7a, 0xaf, 0xb6, 0xfd, 0xce, 0xea, 0xbf, 0xdd, 0x81, 0xc3, 0xcd, 0xdf, 0x19, 0xbc, 0xe3, 0x0c, 0x4b, 0xc7, 0x5b, 0x53, 0xfe, 0x10, 0xeb, 0x70, 0x4b, 0xd0, 0xf4, 0x8b, 0x32, 0xa4, 0xd2, 0xb0, 0x92, 0x74, 0x6e, 0x49, 0x25, 0x68, 0x49, 0x0f, 0x0e, 0x80, 0x7d, 0x2d, 0xf3, 0x2c, 0x11, 0xfe, 0x05, 0xde, 0x37, 0x7b, 0xa1, 0x4a, 0xab, 0x9f, 0x84, 0xa0, 0x85, 0xcf, 0x3f, 0x67, 0x89, 0x20, 0xff, 0xc2, 0xae, 0xd1, 0xe8, 0x7f, 0x8b, 0x4e, 0xdf, 0xbf, 0x7c, 0xfe, 0x55, 0xb3, 0x07, 0x98, 0x77, 0x5c, 0xc7, 0x1f, 0x0b, 0xe7, 0xef, 0x02, 0x00, 0x00, 0xff, 0xff, 0x02, 0xb8, 0x0b, 0xb0, 0x4c, 0x08, 0x00, 0x00, }
wondery/hdfs-nfs-proxy
src/main/java/com/cloudera/hadoop/hdfs/nfs/nfs4/requests/CompoundRequest.java
<gh_stars>1-10 /** * Copyright 2012 Cloudera Inc. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.cloudera.hadoop.hdfs.nfs.nfs4.requests; import java.util.List; import org.apache.log4j.Logger; import com.cloudera.hadoop.hdfs.nfs.nfs4.MessageBase; import com.cloudera.hadoop.hdfs.nfs.nfs4.OperationFactory; import com.cloudera.hadoop.hdfs.nfs.rpc.RPCBuffer; import com.cloudera.hadoop.hdfs.nfs.security.AuthenticatedCredentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; public class CompoundRequest implements MessageBase, RequiresCredentials { protected static final Logger LOGGER = Logger.getLogger(CompoundRequest.class); public static CompoundRequest from(RPCBuffer buffer) { CompoundRequest request = new CompoundRequest(); request.read(buffer); return request; } protected int mMinorVersion; protected byte[] mTags = new byte[0]; protected AuthenticatedCredentials mCredentials; protected ImmutableList<OperationRequest> mOperations = ImmutableList.<OperationRequest>builder().build(); public CompoundRequest() { } @Override public AuthenticatedCredentials getCredentials() { return mCredentials; } public int getMinorVersion() { return mMinorVersion; } public ImmutableList<OperationRequest> getOperations() { return mOperations; } @Override public void read(RPCBuffer buffer) { mTags = buffer.readBytes(); mMinorVersion = buffer.readUint32(); int count = buffer.readUint32(); List<OperationRequest> ops = Lists.newArrayList(); for (int i = 0; i < count; i++) { int id = buffer.readUint32(); if (OperationFactory.isSupported(id)) { ops.add(OperationFactory.parseRequest(id, buffer)); } else { LOGGER.warn("Dropping request with id " + id + ": " + ops); throw new UnsupportedOperationException("NFS ID " + id); } } mOperations = ImmutableList.<OperationRequest>builder().addAll(ops).build(); } @Override public void setCredentials(AuthenticatedCredentials mCredentials) { this.mCredentials = mCredentials; } public void setMinorVersion(int mMinorVersion) { this.mMinorVersion = mMinorVersion; } public void setOperations(List<OperationRequest> operations) { mOperations = ImmutableList.<OperationRequest>copyOf(operations); } @Override public String toString() { return this.getClass().getName() + " = " + mOperations.toString(); } @Override public void write(RPCBuffer buffer) { buffer.writeUint32(mTags.length); buffer.writeBytes(mTags); buffer.writeUint32(mMinorVersion); buffer.writeUint32(mOperations.size()); for (OperationRequest operation : mOperations) { buffer.writeUint32(operation.getID()); operation.write(buffer); } } }
eleswastaken/odin-project
todo-list/src/components/AllProjects.js
<filename>todo-list/src/components/AllProjects.js<gh_stars>0 import ProjectComponent from "./Project.js"; import NewProject from "./NewProject.js"; import { sortByComplete } from "../sort.js"; export default function AllProjects(projects) { const wrapper = document.createElement("div"); const ul = document.createElement("ul"); const h1 = document.createElement('h1'); wrapper.id = "all-projects"; h1.innerHTML = "All Projects"; function renderUl() { wrapper.innerHTML = ''; ul.innerHTML = ''; wrapper.appendChild(h1) wrapper.appendChild(NewProject(renderUl)) projects.forEach( pr => { const li = document.createElement("li"); const project = document.createElement("div"); const title = document.createElement("h2"); const taskUl = document.createElement("ul"); const tasks = sortByComplete(pr.tasks)[0].slice(0, 8); project.onclick = ()=> { wrapper.innerHTML = ''; wrapper.appendChild(ProjectComponent(pr, renderUl)) } project.className = "project"; title.innerHTML = pr.title; project.appendChild(title); if (tasks.length === 0) { const msg = document.createElement('h3') msg.className = "msg" msg.textContent = "No Tasks Here!"; project.appendChild(msg) } else { tasks.forEach(task => { const title = document.createElement("p"); const taskLi = document.createElement("li"); title.innerHTML = task.title; taskLi.appendChild(title) taskUl.appendChild(taskLi); }) project.appendChild(taskUl); } li.appendChild(project) ul.appendChild(li) wrapper.appendChild(ul); }) } renderUl() wrapper.render = renderUl; return wrapper; }
afzalhub/wasp
contracts/rust/fairroulette/test/consts.go
// Copyright 2020 <NAME> // SPDX-License-Identifier: Apache-2.0 package test import ( "github.com/iotaledger/wasp/packages/coretypes" ) const ScName = "fairroulette" const ScHname = coretypes.Hname(0xdf79d138) const ParamNumber = "number" const ParamPlayPeriod = "playPeriod" const VarBets = "bets" const VarLastWinningNumber = "lastWinningNumber" const VarLockedBets = "lockedBets" const VarPlayPeriod = "playPeriod" const FuncLockBets = "lockBets" const FuncPayWinners = "payWinners" const FuncPlaceBet = "placeBet" const FuncPlayPeriod = "playPeriod" const HFuncLockBets = coretypes.Hname(0xe163b43c) const HFuncPayWinners = coretypes.Hname(0xfb2b0144) const HFuncPlaceBet = coretypes.Hname(0xdfba7d1b) const HFuncPlayPeriod = coretypes.Hname(0xcb94b293)
FazeelUsmani/Leetcode
2020 Leetcode Challenges/07 July Leetcode Challenge 2020/03 prisonAfterKdays.cpp
class Solution { public: vector<int> prisonAfterNDays(vector<int>& cells, int N) { vector<int> temp(8, 0); N = (N % 14==0) ? 14 : N%14; while (N--){ for (int i = 1; i < 7; ++i){ if ((cells[i-1] == 0 && cells[i+1] == 0) || (cells[i-1] == 1 && cells[i+1] == 1)) temp[i] = 1; else temp[i] = 0; } cells = temp; } return cells; } };
jglrxavpok/Minestom
src/main/java/fr/themode/demo/blocks/StoneBlock.java
<reponame>jglrxavpok/Minestom package fr.themode.demo.blocks; import net.minestom.server.data.Data; import net.minestom.server.entity.Player; import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.CustomBlock; import net.minestom.server.utils.BlockPosition; import net.minestom.server.utils.time.UpdateOption; public class StoneBlock extends CustomBlock { public StoneBlock() { super((short) 1, "custom_block"); } @Override public void onPlace(Instance instance, BlockPosition blockPosition, Data data) { } @Override public void onDestroy(Instance instance, BlockPosition blockPosition, Data data) { } @Override public void onInteract(Player player, Player.Hand hand, BlockPosition blockPosition, Data data) { } @Override public UpdateOption getUpdateOption() { return null; } @Override public int getBreakDelay(Player player) { return 750; } @Override public short getCustomBlockId() { return 2; } }
scnipper/Solitaire
core/src/me/creese/solitaire/screens/GameScreen.java
<gh_stars>0 package me.creese.solitaire.screens; import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.ScreenViewport; import me.creese.solitaire.entity.FillBlack; import me.creese.solitaire.entity.impl.BaseGame; import me.creese.solitaire.menu.Logo; import me.creese.solitaire.menu.Menu; import me.creese.solitaire.util.P; import me.creese.util.display.Display; import me.creese.util.display.GameView; public class GameScreen extends GameView { private final Menu menu; private final Stage stageBaseGame; private BaseGame baseGame; public GameScreen(Display root) { super(new FitViewport(P.WIDTH, P.HEIGHT), root, new PolygonSpriteBatch()); Stage stage = new Stage(new ScreenViewport()); addStage(stage, 0); //stageScreen = new Stage(new ScreenViewport()); //fillBlack = new FillBlack(); //stageScreen.addActor(fillBlack); stageBaseGame = new Stage(new FitViewport(P.WIDTH, P.HEIGHT)); addActor(new Logo()); addStage(stageBaseGame); menu = new Menu(root); root.addTransitObject(menu); } public Menu getMenu() { return menu; } @Override public void addRoot(Display display) { super.addRoot(display); if (display != null) { baseGame.setRoot(display); addActor(menu); stageBaseGame.addActor(baseGame); baseGame.start(); } } public BaseGame getBaseGame() { return baseGame; } public void setBaseGame(BaseGame baseGame) { this.baseGame = baseGame; } }
osamamagdy/addons-server
src/olympia/files/decorators.py
<reponame>osamamagdy/addons-server from django import http from django.core.exceptions import ObjectDoesNotExist, PermissionDenied import olympia.core.logger from olympia import amo from olympia.access import acl from olympia.addons.decorators import owner_or_unlisted_reviewer log = olympia.core.logger.getLogger('z.addons') def allowed(request, file): try: version = file.version addon = version.addon except ObjectDoesNotExist: raise http.Http404 # General case: addon is listed. if version.channel == amo.RELEASE_CHANNEL_LISTED: # We don't show the file-browser publicly because of potential DOS # issues, we're working on a fix but for now, let's not do this. # (cgrebs, 06042017) is_owner = acl.check_addon_ownership(request, addon, dev=True) if acl.is_reviewer(request, addon) or is_owner: return True # Public and sources are visible, or reviewer. raise PermissionDenied # Listed but not allowed. # Not listed? Needs an owner or an "unlisted" admin. else: if owner_or_unlisted_reviewer(request, addon): return True raise http.Http404 # Not listed, not owner or admin.
ua-eas/devops-automation-ksd-kc5.2.1-rice
impl/src/main/java/org/kuali/rice/kew/role/service/impl/RoleServiceImpl.java
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kew.role.service.impl; import org.apache.commons.collections.CollectionUtils; import org.kuali.rice.core.api.exception.RiceIllegalArgumentException; import org.kuali.rice.kew.actionrequest.ActionRequestValue; import org.kuali.rice.kew.api.KewApiServiceLocator; import org.kuali.rice.kew.api.action.RolePokerQueue; import org.kuali.rice.kew.api.document.DocumentProcessingQueue; import org.kuali.rice.kew.api.rule.RoleName; import org.kuali.rice.kew.doctype.bo.DocumentType; import org.kuali.rice.kew.engine.RouteContext; import org.kuali.rice.kew.engine.node.RouteNodeInstance; import org.kuali.rice.kew.role.service.RoleService; import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue; import org.kuali.rice.kew.rule.FlexRM; import org.kuali.rice.kew.rule.bo.RuleTemplateAttributeBo; import org.kuali.rice.kew.rule.bo.RuleTemplateBo; import org.kuali.rice.kew.service.KEWServiceLocator; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * * @author <NAME> (<EMAIL>) */ public class RoleServiceImpl implements RoleService { private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(RoleServiceImpl.class); public void reResolveRole(DocumentType documentType, String roleName) { String infoString = "documentType="+(documentType == null ? null : documentType.getName())+", role="+roleName; if (documentType == null || org.apache.commons.lang.StringUtils.isEmpty(roleName)) { throw new IllegalArgumentException("Cannot pass null or empty arguments to reResolveQualifiedRole: "+infoString); } LOG.debug("Re-resolving role asynchronously for "+infoString); Set documentIds = new HashSet(); findAffectedDocuments(documentType, roleName, null, documentIds); LOG.debug(documentIds.size()+" documents were affected by this re-resolution, requeueing with the RolePokerQueue"); for (Iterator iterator = documentIds.iterator(); iterator.hasNext();) { String documentId = (String) iterator.next(); String applicationId = KEWServiceLocator.getRouteHeaderService().getApplicationIdByDocumentId(documentId); RolePokerQueue rolePokerQueue = KewApiServiceLocator.getRolePokerQueue(documentId, applicationId); rolePokerQueue.reResolveRole(documentId, roleName); } } public void reResolveQualifiedRole(DocumentType documentType, String roleName, String qualifiedRoleNameLabel) { String infoString = "documentType="+(documentType == null ? null : documentType.getName())+", role="+roleName+", qualifiedRole="+qualifiedRoleNameLabel; if (documentType == null || org.apache.commons.lang.StringUtils.isEmpty(roleName) || org.apache.commons.lang.StringUtils.isEmpty(qualifiedRoleNameLabel)) { throw new IllegalArgumentException("Cannot pass null or empty arguments to reResolveQualifiedRole: "+infoString); } LOG.debug("Re-resolving qualified role asynchronously for "+infoString); Set documentIds = new HashSet(); findAffectedDocuments(documentType, roleName, qualifiedRoleNameLabel, documentIds); LOG.debug(documentIds.size()+" documents were affected by this re-resolution, requeueing with the RolePokerQueue"); for (Iterator iterator = documentIds.iterator(); iterator.hasNext();) { String documentId = (String) iterator.next(); String applicationId = KEWServiceLocator.getRouteHeaderService().getApplicationIdByDocumentId(documentId); RolePokerQueue rolePokerQueue = KewApiServiceLocator.getRolePokerQueue(documentId, applicationId); rolePokerQueue.reResolveQualifiedRole(documentId, roleName, qualifiedRoleNameLabel); } } /** * * route level and then filters in the approriate ones. */ public void reResolveQualifiedRole(DocumentRouteHeaderValue routeHeader, String roleName, String qualifiedRoleNameLabel) { String infoString = "routeHeader="+(routeHeader == null ? null : routeHeader.getDocumentId())+", role="+roleName+", qualifiedRole="+qualifiedRoleNameLabel; if (routeHeader == null || org.apache.commons.lang.StringUtils.isEmpty(roleName) || org.apache.commons.lang.StringUtils.isEmpty(qualifiedRoleNameLabel)) { throw new IllegalArgumentException("Cannot pass null arguments to reResolveQualifiedRole: "+infoString); } LOG.debug("Re-resolving qualified role synchronously for "+infoString); List nodeInstances = findNodeInstances(routeHeader, roleName); int requestsGenerated = 0; if (!nodeInstances.isEmpty()) { deletePendingRoleRequests(routeHeader.getDocumentId(), roleName, qualifiedRoleNameLabel); for (Iterator nodeIt = nodeInstances.iterator(); nodeIt.hasNext();) { RouteNodeInstance nodeInstance = (RouteNodeInstance)nodeIt.next(); RuleTemplateBo ruleTemplate = nodeInstance.getRouteNode().getRuleTemplate(); FlexRM flexRM = new FlexRM(); RouteContext context = RouteContext.getCurrentRouteContext(); context.setDocument(routeHeader); context.setNodeInstance(nodeInstance); try { List actionRequests = flexRM.getActionRequests(routeHeader, nodeInstance, ruleTemplate.getName()); for (Iterator iterator = actionRequests.iterator(); iterator.hasNext();) { ActionRequestValue actionRequest = (ActionRequestValue) iterator.next(); if (roleName.equals(actionRequest.getRoleName()) && qualifiedRoleNameLabel.equals(actionRequest.getQualifiedRoleNameLabel())) { actionRequest = KEWServiceLocator.getActionRequestService().initializeActionRequestGraph(actionRequest, routeHeader, nodeInstance); KEWServiceLocator.getActionRequestService().saveActionRequest(actionRequest); requestsGenerated++; } } } catch (Exception e) { RouteContext.clearCurrentRouteContext(); } } } LOG.debug("Generated "+requestsGenerated+" action requests after re-resolve: "+infoString); requeueDocument(routeHeader); } public void reResolveRole(DocumentRouteHeaderValue routeHeader, String roleName) { String infoString = "routeHeader="+(routeHeader == null ? null : routeHeader.getDocumentId())+", role="+roleName; if (routeHeader == null || org.apache.commons.lang.StringUtils.isEmpty(roleName)) { throw new RiceIllegalArgumentException("Cannot pass null arguments to reResolveQualifiedRole: "+infoString); } LOG.debug("Re-resolving role synchronously for "+infoString); List nodeInstances = findNodeInstances(routeHeader, roleName); int requestsGenerated = 0; if (!nodeInstances.isEmpty()) { deletePendingRoleRequests(routeHeader.getDocumentId(), roleName, null); for (Iterator nodeIt = nodeInstances.iterator(); nodeIt.hasNext();) { RouteNodeInstance nodeInstance = (RouteNodeInstance)nodeIt.next(); RuleTemplateBo ruleTemplate = nodeInstance.getRouteNode().getRuleTemplate(); FlexRM flexRM = new FlexRM(); RouteContext context = RouteContext.getCurrentRouteContext(); context.setDocument(routeHeader); context.setNodeInstance(nodeInstance); try { List actionRequests = flexRM.getActionRequests(routeHeader, nodeInstance, ruleTemplate.getName()); for (Iterator iterator = actionRequests.iterator(); iterator.hasNext();) { ActionRequestValue actionRequest = (ActionRequestValue) iterator.next(); if (roleName.equals(actionRequest.getRoleName())) { actionRequest = KEWServiceLocator.getActionRequestService().initializeActionRequestGraph(actionRequest, routeHeader, nodeInstance); KEWServiceLocator.getActionRequestService().saveActionRequest(actionRequest); requestsGenerated++; } } } finally { RouteContext.clearCurrentRouteContext(); } } } LOG.debug("Generated "+requestsGenerated+" action requests after re-resolve: "+infoString); requeueDocument(routeHeader); } // search the document type and all its children private void findAffectedDocuments(DocumentType documentType, String roleName, String qualifiedRoleNameLabel, Set documentIds) { List pendingRequests = KEWServiceLocator.getActionRequestService().findPendingRootRequestsByDocumentType(documentType.getDocumentTypeId()); for (Iterator iterator = pendingRequests.iterator(); iterator.hasNext();) { ActionRequestValue actionRequest = (ActionRequestValue) iterator.next(); if (roleName.equals(actionRequest.getRoleName()) && (qualifiedRoleNameLabel == null || qualifiedRoleNameLabel.equals(actionRequest.getQualifiedRoleNameLabel()))) { documentIds.add(actionRequest.getDocumentId()); } } for (Iterator iterator = documentType.getChildrenDocTypes().iterator(); iterator.hasNext();) { DocumentType childDocumentType = (DocumentType) iterator.next(); findAffectedDocuments(childDocumentType, roleName, qualifiedRoleNameLabel, documentIds); } } private void deletePendingRoleRequests(String documentId, String roleName, String qualifiedRoleNameLabel) { List pendingRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(documentId); pendingRequests = KEWServiceLocator.getActionRequestService().getRootRequests(pendingRequests); List requestsToDelete = new ArrayList(); for (Iterator iterator = pendingRequests.iterator(); iterator.hasNext();) { ActionRequestValue actionRequest = (ActionRequestValue) iterator.next(); if (roleName.equals(actionRequest.getRoleName()) && (qualifiedRoleNameLabel == null || qualifiedRoleNameLabel.equals(actionRequest.getQualifiedRoleNameLabel()))) { requestsToDelete.add(actionRequest); } } LOG.debug("Deleting "+requestsToDelete.size()+" action requests for roleName="+roleName+", qualifiedRoleNameLabel="+qualifiedRoleNameLabel); for (Iterator iterator = requestsToDelete.iterator(); iterator.hasNext();) { KEWServiceLocator.getActionRequestService().deleteActionRequestGraph((ActionRequestValue)iterator.next()); } } private List findNodeInstances(DocumentRouteHeaderValue routeHeader, String roleName) { List nodeInstances = new ArrayList(); Collection activeNodeInstances = KEWServiceLocator.getRouteNodeService().getActiveNodeInstances(routeHeader.getDocumentId()); if (CollectionUtils.isEmpty(activeNodeInstances)) { throw new IllegalStateException("Document does not currently have any active nodes so re-resolving is not legal."); } for (Iterator iterator = activeNodeInstances.iterator(); iterator.hasNext();) { RouteNodeInstance activeNodeInstance = (RouteNodeInstance) iterator.next(); RuleTemplateBo template = activeNodeInstance.getRouteNode().getRuleTemplate(); if (templateHasRole(template, roleName)) { nodeInstances.add(activeNodeInstance); } } if (nodeInstances.isEmpty()) { throw new IllegalStateException("Could not locate given role to re-resolve: " + roleName); } return nodeInstances; } private boolean templateHasRole(RuleTemplateBo template, String roleName) { List<RuleTemplateAttributeBo> templateAttributes = template.getRuleTemplateAttributes(); for (RuleTemplateAttributeBo templateAttribute : templateAttributes) { List<RoleName> roleNames = KEWServiceLocator.getWorkflowRuleAttributeMediator().getRoleNames(templateAttribute); for (RoleName role : roleNames) { if (role.getLabel().equals(roleName)) { return true; } } } return false; } protected void requeueDocument(DocumentRouteHeaderValue document) { String applicationId = document.getDocumentType().getApplicationId(); DocumentProcessingQueue documentProcessingQueue = KewApiServiceLocator.getDocumentProcessingQueue(document.getDocumentId(), applicationId); documentProcessingQueue.process(document.getDocumentId()); } }
FedericoQuin/2dv50e
machine_learner/machine_learner/preprocessing/feature_selection_multigoal.py
<filename>machine_learner/machine_learner/preprocessing/feature_selection_multigoal.py import matplotlib.pyplot as plt import json import sys import numpy as np from sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor import os def doFeatureSelectionClass(data): target_packetloss, target_latency = data['target_classification_packetloss'], data['target_classification_latency'] totalTargets = [] for target_pl, target_l in zip(target_packetloss, target_latency): totalTargets.append(target_pl + (target_l << 1)) model = ExtraTreesClassifier(random_state=10) model.fit(data['features'], totalTargets) importances = model.feature_importances_ return importances def doFeatureSelectionRegression(data): target_packetloss, target_latency = data['target_regression_packetloss'], data['target_regression_latency'] model1 = ExtraTreesRegressor(random_state=10) model1.fit(data['features'], target_packetloss) model2 = ExtraTreesRegressor(random_state=10) model2.fit(data['features'], target_latency) importances1 = model1.feature_importances_ importances2 = model2.feature_importances_ importances = [(importances1[i] + importances2[i]) / 2 for i in range(len(importances1))] return importances def doFeatureSelection(network): path = os.path.join('machine_learner', 'collected_data', 'dataset_with_all_features.json') data = json.load(open(path)) importancesClass = doFeatureSelectionClass(data) importancesRegr = doFeatureSelectionRegression(data) importances = [(importancesClass[i] + importancesRegr[i]) / 2 for i in range(len(importancesClass))] plt.subplot(1, 1, 1) if network == 'DeltaIoTv1': plt.bar(range(1, 18), importances[:17], color='r', label='1-17 SNR') plt.bar(range(18, 35), importances[17:34], color='b', label='18-34 Power Settings') plt.bar(range(35, 52), importances[34:51], color='orange', label='35-51 Packets Distribution') plt.bar(range(52, 66), importances[51:65], color='green', label='52-65 Traffic Load') plt.xticks([1, 17, 34, 51, 65]) elif network == 'DeltaIoTv2': plt.bar(range(1, 43), importances[:42], color='r', label='1-42 SNR') plt.bar(range(43, 85), importances[42:84], color='b', label='43-84 Power Settings') plt.bar(range(85, 127), importances[84:126], color='orange', label='85-126 Packets Distribution') plt.bar(range(127, 163), importances[126:162], color='green', label='127-162 Traffic Load') plt.xticks([1, 42, 84, 126, 162]) else: print(f'Network \'{network}\' is currently not supported.') sys.exit(1) plt.xlabel('Features') plt.ylabel('Importance Score') plt.title('Feature importances') plt.legend() indices = np.array([i for i in range(len(importances)) if importances[i] != 0]) # save the selected features in a separate file newFileData = json.load(open(path)) newFeatures = [] for feature_vec in newFileData['features']: newFeatures.append(np.array(feature_vec)[indices].tolist()) newFileData['features'] = newFeatures outputPath = os.path.join('machine_learner','collected_data',f'dataset_selected_features.json') with open(outputPath, 'w') as f: json.dump(newFileData, f, indent=1) plt.tight_layout() plt.show() if __name__ == '__main__': doFeatureSelection('DeltaIoTv2')
ung-org/lib-c
src/setjmp/sigjmp_buf.c
<gh_stars>0 #include <setjmp.h> /** program environment with signal mask **/ typedef jmp_buf sigjmp_buf; /*** is used to hold all the information needed to restore a a calling environment, including the signal mask. ***/ /* TYPEDEF(an array type) POSIX(1) */
sriharshakappala/ggrc-core
src/ggrc/models/system_control.py
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: <EMAIL> # Maintained By: <EMAIL> from ggrc import db from .mixins import Base class SystemControl(Base, db.Model): __tablename__ = 'system_controls' system_id = db.Column(db.Integer, db.ForeignKey('systems.id'), nullable=False) control_id = db.Column(db.Integer, db.ForeignKey('controls.id'), nullable=False) state = db.Column(db.Integer, default=1, nullable=False) cycle_id = db.Column(db.Integer, db.ForeignKey('cycles.id')) cycle = db.relationship('Cycle', uselist=False) __table_args__ = ( db.UniqueConstraint('system_id', 'control_id'), ) _publish_attrs = [ 'system', 'control', 'state', 'cycle', ] @classmethod def eager_query(cls): from sqlalchemy import orm query = super(SystemControl, cls).eager_query() return query.options( orm.joinedload('cycle'), orm.subqueryload('system'), orm.subqueryload('control')) def _display_name(self): return self.control.display_name + '<->' + self.system.display_name
kojole/WikiEduDashboard
app/workers/greet_students_worker.rb
<reponame>kojole/WikiEduDashboard # frozen_string_literal: true class GreetStudentsWorker include Sidekiq::Worker sidekiq_options unique: :until_executed def self.schedule_greetings(course, greeter) perform_async(course.id, greeter.id) end def perform(course_id, greeter_id) course = Course.find(course_id) greeter = User.find(greeter_id) GreetUngreetedStudents.new(course, greeter) end end
PrachieNaik/DSA
LinkedList/MergeTwoList/MergeTwoList.cpp
<reponame>PrachieNaik/DSA /* Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space). Constraints: 0 <= N <= 50 1 <= Mi <= 20 1 <= Element of linked list <= 10^3 Approaches: Method 1: The recursive solution can be formed, given the linked lists are sorted. Compare the head of both linked lists. Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes. The rest elements of both lists will appear after that. Now run a recursive function with parameters, the next node of the smaller element and the other head. The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction() Handle some corner cases. If both the heads are NULL return null. If one head is null return the other. Time complexity:O(n). Only one traversal of the linked lists are needed. Auxiliary Space:O(n). If the recursive stack space is taken into consideration. Method 2: This approach is very similar to the above recursive approach. Traverse the list from start to end. If the head node of second list lies in between two node of the first list, insert it there and make the next node of second list as the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed. If the first list has reached end while traversing, point the next node to the head of second list. Note: Compare both the lists where the list with smaller head value is the first list. Time complexity:O(n). As only one traversal of the linked lists is needed. Auxiliary Space:O(1). As there is no space required. */ // Merges two lists with headers as h1 and h2. // It assumes that h1's data is smaller than // or equal to h2's data. struct Node* mergeUtil(struct Node* h1, struct Node* h2) { // if only one node in first list // simply point its head to second list if (!h1->next) { h1->next = h2; return h1; } // Initialize current and next pointers of // both lists struct Node *curr1 = h1, *next1 = h1->next; struct Node *curr2 = h2, *next2 = h2->next; while (next1 && curr2) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2->data) >= (curr1->data) && (curr2->data) <= (next1->data)) { next2 = curr2->next; curr1->next = curr2; curr2->next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1->next) { next1 = next1->next; curr1 = curr1->next; } // else point the last node of first list // to the remaining nodes of second list else { next1->next = curr2; return h1; } } } return h1; } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() struct Node* merge(struct Node* h1, struct Node* h2) { if (!h1) return h2; if (!h2) return h1; // start with the linked list // whose head data is the least if (h1->data < h2->data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1); }
KrisiKostadinov/myblog
app.js
const express = require('express'); const exphbs = require('express-handlebars'); const session = require('express-session'); const methodOverride = require('method-override'); const cookieParser = require('cookie-parser'); const flash = require('connect-flash'); const passport = require('passport'); const fileUpload = require('express-fileupload'); const cloudinary = require('cloudinary'); require('dotenv').config(); require('./config/db'); const indexRouter = require('./routes/index'); const usersRouter = require('./routes/users'); const administrationRouter = require('./routes/administration'); const postRouter = require('./routes/post'); const projectAppsRouter = require('./routes/projectApps'); const commentAppRouter = require('./routes/comment'); require('./config/passport')(passport); const app = express(); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(methodOverride('_method')); app.use(require("body-parser").json()); app.use(fileUpload({ useTempFiles: true, })); cloudinary.config({ cloud_name: process.env.CLOUDINARY_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET }); app.engine('.hbs', exphbs({ defaultLayout: 'main', extname: '.hbs', helpers: { is: function (first, second, options) { return first === second ? options.fn(this) : options.inverse(this); }, inc: function (number) { return parseInt(number) + 1; }, dec: function (number) { return parseInt(number) - 1; }, times: function (n, block) { var accum = ''; for (var i = 0; i < n; ++i) accum += block.fn(i); return accum; }, isAsNum: function (first, second, options) { console.log(' - ' + first, second); return Number(first) === Number(second) ? options.fn(Number(this)) : options.inverse(Number(this)); }, } })); app.use(session({ secret: 'secret', resave: true, saveUninitialized: true })) app.use(passport.initialize()) app.use(passport.session()) app.use(flash()); app.set('view engine', '.hbs'); app.use("/public", express.static(__dirname + '/public')); app.use((req, res, next) => { res.locals.error_msg = req.flash('error_msg'); res.locals.success_msg = req.flash('success_msg'); res.locals.error = req.flash('error'); console.log(res.locals); next(); }); app.use('/', indexRouter); app.use('/users', usersRouter); app.use('/administration', administrationRouter); app.use('/post', postRouter); app.use('/projects/apps', projectAppsRouter); app.use('/comment', commentAppRouter); app.use('*', (req, res) => res.render('404')); app.listen(process.env.PORT, () => console.log('Server listening on port: ' + process.env.PORT));
5GZORRO/governance-manager
src/main/java/eu/_5gzorro/governancemanager/controller/v1/response/PagedMembersResponse.java
package eu._5gzorro.governancemanager.controller.v1.response; import eu._5gzorro.governancemanager.dto.MemberDto; import org.springframework.data.domain.Page; import java.util.Objects; public class PagedMembersResponse { private final Page<MemberDto> pagedMembers; public PagedMembersResponse(Page<MemberDto> pagedMembers) { this.pagedMembers = pagedMembers; } public Page<MemberDto> getPagedMembers() { return pagedMembers; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PagedMembersResponse that = (PagedMembersResponse) o; return Objects.equals(pagedMembers, that.pagedMembers); } @Override public int hashCode() { return Objects.hash(pagedMembers); } @Override public String toString() { return "PagedMemberResponse{" + "pagedMembers=" + pagedMembers + '}'; } }
mariusj/org.openntf.domino
domino/core/src/test/java/org/openntf/domino/tests/jpg/KeyValueStore.java
/** * */ package org.openntf.domino.tests.jpg; import static java.lang.Math.pow; import static org.openntf.domino.utils.DominoUtils.checksum; import java.util.HashMap; import java.util.Map; import org.openntf.domino.Database; import org.openntf.domino.DbDirectory; import org.openntf.domino.Document; import org.openntf.domino.Session; /** * @author jgallagher * */ public class KeyValueStore { public interface ServerStrategy { public String getServerForHashChunk(final String hashChunk); } private final Session session_; private final String server_; private final ServerStrategy serverStrategy_; private final String baseName_; private final Map<String, Database> dbCache_ = new HashMap<String, Database>(); private final Map<String, DbDirectory> dbdirCache_ = new HashMap<String, DbDirectory>(); private final int places_; public KeyValueStore(final Session session, final String server, final String baseName, final int places) { if (session == null) throw new NullPointerException("session cannot be null"); if (baseName == null || baseName.length() == 0) throw new IllegalArgumentException("baseName cannot be null or zero-length"); if (places < 0) throw new IllegalArgumentException("places must be nonnegative"); session_ = session; baseName_ = baseName.toLowerCase().endsWith(".nsf") ? baseName.substring(0, baseName.length() - 4) : baseName; places_ = places; server_ = server == null ? "" : server; dbdirCache_.put("only", session_.getDbDirectory(server_)); serverStrategy_ = null; } public KeyValueStore(final Session session, final ServerStrategy serverStrategy, final String baseName, final int places) { if (session == null) throw new NullPointerException("session cannot be null"); if (baseName == null || baseName.length() == 0) throw new IllegalArgumentException("baseName cannot be null or zero-length"); if (places < 1) throw new IllegalArgumentException("places must be greater than zero"); if (serverStrategy == null) throw new NullPointerException("serverStrategy cannot be null"); session_ = session; baseName_ = baseName.toLowerCase().endsWith(".nsf") ? baseName.substring(0, baseName.length() - 4) : baseName; places_ = places; server_ = null; serverStrategy_ = serverStrategy; } public void initializeDatabases() { if (places_ > 0) { for (int i = 0; i < pow(16, places_); i++) { String hashChunk = Integer.toString(i, 16).toLowerCase(); while (hashChunk.length() < places_) hashChunk = "0" + hashChunk; String server = serverStrategy_ == null ? server_ : serverStrategy_.getServerForHashChunk(hashChunk); DbDirectory dbdir = getDbDirectoryForHashChunk(hashChunk); String dbName = baseName_ + "-" + hashChunk + ".nsf"; Database database = session_.getDatabase(server, dbName, true); if (!database.isOpen()) { database = createDatabase(dbdir, dbName); } dbCache_.put(dbName, database); } } else { Database database = session_.getDatabase(server_, baseName_ + ".nsf"); if (!database.isOpen()) { database = createDatabase(getDbDirectoryForHashChunk(null), baseName_ + ".nsf"); } dbCache_.put(baseName_ + ".nsf", database); } } public Object get(final String key) { String hashKey = checksum(key, "MD5"); Database keyDB = getDatabaseForKey(hashKey); Document keyDoc = keyDB.getDocumentWithKey(key); return keyDoc == null ? null : keyDoc.get("Value"); } public void put(final String key, final Object value) { String hashKey = checksum(key, "MD5"); Database keyDB = getDatabaseForKey(hashKey); Document keyDoc = keyDB.getDocumentWithKey(key, true); keyDoc.replaceItemValue("Value", value); keyDoc.save(); } private Database getDatabaseForKey(final String hashKey) { String hashChunk = hashKey.substring(0, places_); String dbName = baseName_ + "-" + hashChunk + ".nsf"; if (!dbCache_.containsKey(dbName)) { String server = serverStrategy_ == null ? server_ : serverStrategy_.getServerForHashChunk(hashChunk); Database database = session_.getDatabase(server, dbName, true); if (!database.isOpen()) { DbDirectory dbdir = getDbDirectoryForHashChunk(hashChunk); database = createDatabase(dbdir, dbName); } dbCache_.put(dbName, database); } return dbCache_.get(dbName); } private DbDirectory getDbDirectoryForHashChunk(final String hashChunk) { if (server_ != null) { return dbdirCache_.get("only"); } else { if (!dbdirCache_.containsKey(hashChunk)) { String server = serverStrategy_ == null ? server_ : serverStrategy_.getServerForHashChunk(hashChunk); dbdirCache_.put(hashChunk, session_.getDbDirectory(server)); } return dbdirCache_.get(hashChunk); } } private Database createDatabase(final DbDirectory dbdir, final String dbName) { Database database = dbdir.createDatabase(dbName, true); database.createView(); database.setOption(Database.DBOption.LZ1, true); database.setOption(Database.DBOption.COMPRESSDESIGN, true); database.setOption(Database.DBOption.COMPRESSDOCUMENTS, true); database.setOption(Database.DBOption.NOUNREAD, true); return database; } }
nadavtal/3dbia
app/containers/Wijmo/WijmoCheckBoxTable.js
import React from 'react' import { FlexGrid, FlexGridColumn } from "@grapecity/wijmo.react.grid"; import { Selector } from "@grapecity/wijmo.grid.selector"; import { HeadersVisibility } from "@grapecity/wijmo.grid"; import { CollectionView, PropertyGroupDescription } from "@grapecity/wijmo"; import {MDBInput} from 'mdbreact' import { FlexGridFilter } from '@grapecity/wijmo.react.grid.filter'; import { FlexGridSearch } from '@grapecity/wijmo.react.grid.search'; class WijmoCheckBoxTable extends React.Component { constructor(props) { super(props); this.selector = null; this.state = { view: new CollectionView(props.data), grouped: true, headers: true, flex: null, selectedItems: [] }; this.theGrid = React.createRef(); this.theSearch = React.createRef(); } capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } createTableColumnsArray(object) { let coloumns = [] coloumns = Object.keys(object).map(key => { const header = this.capitalizeFirstLetter(key.replace("_", " ")); return { header: header, accessor: key, } }) // console.log(coloumns) return coloumns } initGrid(grid) { this.setGroups(true); this.selector = new Selector(grid, { itemChecked: (s, e) => { console.log(s) console.log(e) console.log(grid.selectedItems); this.props.handleCheckboxClick(grid.selectedItems) this.setState({ selectedItems: grid.selectedItems }); } }); } setGroups(groupsOn) { let groups = this.state.view.groupDescriptions; groups.clear(); if (groupsOn) { groups.push( new PropertyGroupDescription('surveyName'), new PropertyGroupDescription('name'), ); } this.setState({ grouped: groupsOn }); } setHeaders(headersOn) { let theGrid = this.selector.column.grid; theGrid.headersVisibility = headersOn ? HeadersVisibility.All : HeadersVisibility.Column; this.selector.column = headersOn ? theGrid.rowHeaders.columns[0] : theGrid.columns[0]; this.setState({ headers: headersOn }); } componentDidMount() { // connect search box and grid let theGrid = this.theGrid.current.control; let theSearch = this.theSearch.current.control; theSearch.grid = theGrid; } render() { return ( <div className="container-fluid"> <div className="toolbar-item col-sm-3 col-md-5"> <FlexGridSearch ref={this.theSearch} placeholder="Search" cssMatch=""/> </div> <MDBInput label="Grouped Data" filled type="checkbox" id={`checkbox1`} containerClass="" checked={this.state.grouped} onChange={e => this.setGroups(e.target.checked)} /> <MDBInput label="Header Column" filled type="checkbox" id={`checkbox2`} containerClass="" checked={this.state.headers} onChange={e => this.setHeaders(e.target.checked)} /> <p> There are now <b>{this.state.selectedItems.length}</b>{' '} items selected. </p> <FlexGridGroupPanel grid={this.state.flex} placeholder={"Drag columns here to create groups"}/> <FlexGrid ref={this.theGrid} allowAddNew allowDelete newRowAtTop allowPinning="SingleColumn" deferResizing={true} showMarquee={true} alternatingRowStep={0} itemsSource={this.state.view} initialized={s => this.initGrid(s)} > <FlexGridFilter /> {this.createTableColumnsArray(this.props.data[0]).map( coloumn => { // console.log(coloumn) return ( <FlexGridColumn key={coloumn.accessor} header={coloumn.header} binding={coloumn.accessor} // width={70} isReadOnly={true} /> ); }, )} {/* <FlexGridColumn binding="id" header="ID" isReadOnly={true} /> <FlexGridColumn binding="country" header="Country" /> <FlexGridColumn binding="product" header="Product" /> <FlexGridColumn binding="discount" header="Discount" format="p0" /> <FlexGridColumn binding="downloads" header="Downloads" /> <FlexGridColumn binding="sales" header="Sales" /> <FlexGridColumn binding="expenses" header="Expenses" /> */} </FlexGrid> </div> ); } } export default WijmoCheckBoxTable
jmdbo/TRSA
src/t7_package/src/tf_subscriber_node.cpp
#include <ros/ros.h> #include "t7_package/TfSubscriber.h" int main(int argc, char **argv) { ros::init( argc, argv, "tf_subscriber" ); TfSubscriber subscriber; subscriber.run(); return EXIT_SUCCESS; }
Archadia/terrabyte
src/main/java/com/projectkroma/terrabyte/imgui/ImGuiBridge.java
<reponame>Archadia/terrabyte package com.projectkroma.terrabyte.imgui; import imgui.ImDrawData; import imgui.ImGuiImplTerrabyte; public interface ImGuiBridge { void newFrameGLFW(); void renderGL(ImDrawData drawData); void dispose(); public static ImGuiBridge newBridge(long window, String glslVersion) { return new ImGuiImplTerrabyte(window, glslVersion); } }
echokepler/megad2561
cmd/backup/main.go
package main import ( "flag" "github.com/echokepler/megad2561/internal/backup" "log" "os" ) func main() { var ( addr = flag.String("host", "http://192.168.88.14", "Сетевой адрес веб сервера megad") pwd = flag.String("password", "<PASSWORD>", "<PASSWORD> доступка к megad") backupFilePath = flag.String("backup_file", "", "Путь до бэкап файла") outputDirPath = flag.String("output", "", "Путь до папки куда сохранится бэкап") ) flag.Parse() var ( infoLog = log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime) needGeneration = len(*outputDirPath) > 0 needUploading = len(*backupFilePath) > 0 mode backup.WorkMode ) if needGeneration { mode = backup.GENERATE } else if needUploading { mode = backup.UPLOAD } infoLog.Println("Creating backup megad") infoLog.Printf("Address: %v Password: %v Mode: %v", *addr, *pwd, mode) if mode == backup.GENERATE { backup.GenerateBackup(*outputDirPath, *addr, *pwd) } else if mode == backup.UPLOAD { backup.UploadBackup(*backupFilePath, *addr, *pwd) } } // Загрузка бэкапа -> $ backupmegad --addr=192.168.88.14 --password=<PASSWORD> --backup_file=~/WorkSpace/apphub/megad_backup_15032021.yaml // Создание бэкапа -> $ backupmegad --addr=192.168.88.14 --password=<PASSWORD> --output=~/WorkSpace/apphub
NlaakStudios/Just-Old-Code
archives/1_H5C3_Framework/h5c3/lib/r2wl/brand.js
/** * * @namespace Core * @class h5c3.Brand * @augments h5c3.Base * @description * [Extends <a href='h5c3.Base'>h5c3.Base</a>] * <p> * * <pre><code> * * </code></pre> * * </p> */ h5c3.Brand = h5c3.Base.extend('h5c3.Brand', { _CLASSNAME :'Brand', _CLASSVERSION :'0.0.2' },{ /** * @public * @method * @memberof h5c3.Brand * @desc * </p> * Simply creates the I2TM labs / H5C3 Branding object * </p> */ init:function() { this._super(); }, update:function() { $("#h5c3built").text(h5c3.BUILT); $("#h5c3version").text(h5c3.DISTRO+'-'+h5c3.VERSION); if (h5c3.devMode===true) $("#h5c3version").css("color","#FF0000"); else $("#h5c3version").css("color","#ddffdd"); }, populate:function() { var $css; $css='<style id="h5c3-logo">#h5c3_logo {font-size:1em;display: block;}'; $css+='#hlmc {position: relative;display:block;top:0px;left:0px;width:100%;height:100%;font-family: Neuropol, sans-serif;text-transform: uppercase;text-align: center;}'; $css+='#h5c3_logo .c_H { display:inline; font-size: 100%; color: #e98900; }#h5c3_logo .c_5 { display:inline; font-size: 50%; color: #e98900; }#h5c3_logo .c_C { display:inline; font-size: 100%; color: #000beb; }#h5c3_logo .c_3 { display:inline; font-size: 50%; color: #000beb; }#h5c3_logo .w_FW { display:block; font-size: 42%; color: #444444;}</style>\n'; $css+='#i2tm_logo{font-size:3em;display:block;}#i2tm_logo .w_il{display:inline;font-size:100%;color:#00cc00;}'; $css+='#ilmc {position:relative;display:block;top:0px;left:0px;width:100%;height:100%;font-family:Neuropol,sans-serif;text-transform:uppercase;text-align:center;padding-top:6.25%;}</style>\n'; h5c3.r2wl.app.stylesheet.add('brand-logos',$css,'R2WL'); }, logoI2TM:function($scale) { $scale = CHK($scale,4); return '<div id="i2tm_logo" data-role="applet" style="font-size:'+$scale+'em"><div id="ilmc"><div class="w_il backlight">i2tm Labs</div></div></div>\n'; }, logoH5C3:function($scale) { $scale = CHK($scale,4); return '<div id="h5c3_logo" class="animateIn" data-role="applet" style="font-size:'+$scale+'em"><div id="hlmc"><div class="c_H emboss backlight">H</div><div class="c_5 emboss backlight">5</div><div class="c_C emboss backlight">C</div><div class="c_3 emboss backlight">3</div><div class="w_FW emboss backlight">framework</div></div></div>\n'; }, youAreRunning:function() { var $html=''; $html+='<h3 style="margin:0">You are running</h3>'; $html+=this.logoI2TM(4); $html+=this.logoH5C3(5); $html+='<p id="h5c3version" class="center">version</p>'; $html+='<p id="h5c3built" class="center">built on</p>'; return $html; }, poweredBy:function($scale) { $scale = CHK($scale,0.5); var $clr = (h5c3.devMode) ? 'red' : 'green'; return '<div style="font-size:'+$scale+'em;color:'+$clr+';width:23%;letter-spacing:0.20em;position: relative;margin:0 auto">Powered By '+h5c3.tag()+'</div>'; }, start:function() { this.populate(); this.update(); } });
marcussacana/DirectPackageInstaller
Payload/freebsd-headers/rpc/rpcb_prot.h
/* * Please do not edit this file. * It was generated using rpcgen. */ #ifndef _RPCB_PROT_H_RPCGEN #define _RPCB_PROT_H_RPCGEN #include <rpc/rpc.h> #ifdef __cplusplus extern "C" { #endif /* * $FreeBSD: release/9.0.0/include/rpc/rpcb_prot.x 92223 2002-03-13 10:29:06Z obrien $ * * Sun RPC is a product of Sun Microsystems, Inc. and is provided for * unrestricted use provided that this legend is included on all tape * media and as a part of the software program in whole or part. Users * may copy or modify Sun RPC without charge, but are not authorized * to license or distribute it to anyone else except as part of a product or * program developed by the user. * * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun RPC is provided with no support and without any obligation on the * part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ /* * Copyright (c) 1988 by Sun Microsystems, Inc. */ /* from rpcb_prot.x */ /* #pragma ident "@(#)rpcb_prot.x 1.5 94/04/29 SMI" */ #ifndef _KERNEL /* * The following procedures are supported by the protocol in version 3: * * RPCBPROC_NULL() returns () * takes nothing, returns nothing * * RPCBPROC_SET(rpcb) returns (bool_t) * TRUE is success, FALSE is failure. Registers the tuple * [prog, vers, address, owner, netid]. * Finds out owner and netid information on its own. * * RPCBPROC_UNSET(rpcb) returns (bool_t) * TRUE is success, FALSE is failure. Un-registers tuple * [prog, vers, netid]. addresses is ignored. * If netid is NULL, unregister all. * * RPCBPROC_GETADDR(rpcb) returns (string). * 0 is failure. Otherwise returns the universal address where the * triple [prog, vers, netid] is registered. Ignore address and owner. * * RPCBPROC_DUMP() RETURNS (rpcblist_ptr) * used to dump the entire rpcbind maps * * RPCBPROC_CALLIT(rpcb_rmtcallargs) * RETURNS (rpcb_rmtcallres); * Calls the procedure on the remote machine. If it is not registered, * this procedure is quiet; i.e. it does not return error information!!! * This routine only passes null authentication parameters. * It has no interface to xdr routines for RPCBPROC_CALLIT. * * RPCBPROC_GETTIME() returns (int). * Gets the remote machines time * * RPCBPROC_UADDR2TADDR(strint) RETURNS (struct netbuf) * Returns the netbuf address from universal address. * * RPCBPROC_TADDR2UADDR(struct netbuf) RETURNS (string) * Returns the universal address from netbuf address. * * END OF RPCBIND VERSION 3 PROCEDURES */ /* * Except for RPCBPROC_CALLIT, the procedures above are carried over to * rpcbind version 4. Those below are added or modified for version 4. * NOTE: RPCBPROC_BCAST HAS THE SAME FUNCTIONALITY AND PROCEDURE NUMBER * AS RPCBPROC_CALLIT. * * RPCBPROC_BCAST(rpcb_rmtcallargs) * RETURNS (rpcb_rmtcallres); * Calls the procedure on the remote machine. If it is not registered, * this procedure IS quiet; i.e. it DOES NOT return error information!!! * This routine should be used for broadcasting and nothing else. * * RPCBPROC_GETVERSADDR(rpcb) returns (string). * 0 is failure. Otherwise returns the universal address where the * triple [prog, vers, netid] is registered. Ignore address and owner. * Same as RPCBPROC_GETADDR except that if the given version number * is not available, the address is not returned. * * RPCBPROC_INDIRECT(rpcb_rmtcallargs) * RETURNS (rpcb_rmtcallres); * Calls the procedure on the remote machine. If it is not registered, * this procedure is NOT quiet; i.e. it DOES return error information!!! * as any normal application would expect. * * RPCBPROC_GETADDRLIST(rpcb) returns (rpcb_entry_list_ptr). * Same as RPCBPROC_GETADDR except that it returns a list of all the * addresses registered for the combination (prog, vers) (for all * transports). * * RPCBPROC_GETSTAT(void) returns (rpcb_stat_byvers) * Returns the statistics about the kind of requests received by rpcbind. */ /* * A mapping of (program, version, network ID) to address */ struct rpcb { rpcprog_t r_prog; rpcvers_t r_vers; char *r_netid; char *r_addr; char *r_owner; }; typedef struct rpcb rpcb; typedef rpcb RPCB; /* * A list of mappings * * Below are two definitions for the rpcblist structure. This is done because * xdr_rpcblist() is specified to take a struct rpcblist **, rather than a * struct rpcblist * that rpcgen would produce. One version of the rpcblist * structure (actually called rp__list) is used with rpcgen, and the other is * defined only in the header file for compatibility with the specified * interface. */ struct rp__list { rpcb rpcb_map; struct rp__list *rpcb_next; }; typedef struct rp__list rp__list; typedef rp__list *rpcblist_ptr; typedef struct rp__list rpcblist; typedef struct rp__list RPCBLIST; #ifndef __cplusplus struct rpcblist { RPCB rpcb_map; struct rpcblist *rpcb_next; }; #endif #ifdef __cplusplus extern "C" { #endif extern bool_t xdr_rpcblist(XDR *, rpcblist**); #ifdef __cplusplus } #endif /* * Arguments of remote calls */ struct rpcb_rmtcallargs { rpcprog_t prog; rpcvers_t vers; rpcproc_t proc; struct { u_int args_len; char *args_val; } args; }; typedef struct rpcb_rmtcallargs rpcb_rmtcallargs; /* * Client-side only representation of rpcb_rmtcallargs structure. * * The routine that XDRs the rpcb_rmtcallargs structure must deal with the * opaque arguments in the "args" structure. xdr_rpcb_rmtcallargs() needs to * be passed the XDR routine that knows the args' structure. This routine * doesn't need to go over-the-wire (and it wouldn't make sense anyway) since * the application being called already knows the args structure. So we use a * different "XDR" structure on the client side, r_rpcb_rmtcallargs, which * includes the args' XDR routine. */ struct r_rpcb_rmtcallargs { rpcprog_t prog; rpcvers_t vers; rpcproc_t proc; struct { u_int args_len; char *args_val; } args; xdrproc_t xdr_args; /* encodes args */ }; /* * Results of the remote call */ struct rpcb_rmtcallres { char *addr; struct { u_int results_len; char *results_val; } results; }; typedef struct rpcb_rmtcallres rpcb_rmtcallres; /* * Client-side only representation of rpcb_rmtcallres structure. */ struct r_rpcb_rmtcallres { char *addr; struct { u_int32_t results_len; char *results_val; } results; xdrproc_t xdr_res; /* decodes results */ }; /* * rpcb_entry contains a merged address of a service on a particular * transport, plus associated netconfig information. A list of rpcb_entrys * is returned by RPCBPROC_GETADDRLIST. See netconfig.h for values used * in r_nc_* fields. */ struct rpcb_entry { char *r_maddr; char *r_nc_netid; u_int r_nc_semantics; char *r_nc_protofmly; char *r_nc_proto; }; typedef struct rpcb_entry rpcb_entry; /* * A list of addresses supported by a service. */ struct rpcb_entry_list { rpcb_entry rpcb_entry_map; struct rpcb_entry_list *rpcb_entry_next; }; typedef struct rpcb_entry_list rpcb_entry_list; typedef rpcb_entry_list *rpcb_entry_list_ptr; /* * rpcbind statistics */ #define rpcb_highproc_2 RPCBPROC_CALLIT #define rpcb_highproc_3 RPCBPROC_TADDR2UADDR #define rpcb_highproc_4 RPCBPROC_GETSTAT #define RPCBSTAT_HIGHPROC 13 #define RPCBVERS_STAT 3 #define RPCBVERS_4_STAT 2 #define RPCBVERS_3_STAT 1 #define RPCBVERS_2_STAT 0 /* Link list of all the stats about getport and getaddr */ struct rpcbs_addrlist { rpcprog_t prog; rpcvers_t vers; int success; int failure; char *netid; struct rpcbs_addrlist *next; }; typedef struct rpcbs_addrlist rpcbs_addrlist; /* Link list of all the stats about rmtcall */ struct rpcbs_rmtcalllist { rpcprog_t prog; rpcvers_t vers; rpcproc_t proc; int success; int failure; int indirect; char *netid; struct rpcbs_rmtcalllist *next; }; typedef struct rpcbs_rmtcalllist rpcbs_rmtcalllist; typedef int rpcbs_proc[RPCBSTAT_HIGHPROC]; typedef rpcbs_addrlist *rpcbs_addrlist_ptr; typedef rpcbs_rmtcalllist *rpcbs_rmtcalllist_ptr; struct rpcb_stat { rpcbs_proc info; int setinfo; int unsetinfo; rpcbs_addrlist_ptr addrinfo; rpcbs_rmtcalllist_ptr rmtinfo; }; typedef struct rpcb_stat rpcb_stat; /* * One rpcb_stat structure is returned for each version of rpcbind * being monitored. */ typedef rpcb_stat rpcb_stat_byvers[RPCBVERS_STAT]; /* * We don't define netbuf in RPCL, since it would contain structure member * names that would conflict with the definition of struct netbuf in * <tiuser.h>. Instead we merely declare the XDR routine xdr_netbuf() here, * and implement it ourselves in rpc/rpcb_prot.c. */ #ifdef __cplusplus extern "C" bool_t xdr_netbuf(XDR *, struct netbuf *); #else /* __STDC__ */ extern bool_t xdr_netbuf(XDR *, struct netbuf *); #endif #define RPCBVERS_3 RPCBVERS #define RPCBVERS_4 RPCBVERS4 #define _PATH_RPCBINDSOCK "/var/run/rpcbind.sock" #else /* ndef _KERNEL */ #ifdef __cplusplus extern "C" { #endif /* * A mapping of (program, version, network ID) to address */ struct rpcb { rpcprog_t r_prog; /* program number */ rpcvers_t r_vers; /* version number */ char *r_netid; /* network id */ char *r_addr; /* universal address */ char *r_owner; /* owner of the mapping */ }; typedef struct rpcb RPCB; /* * A list of mappings */ struct rpcblist { RPCB rpcb_map; struct rpcblist *rpcb_next; }; typedef struct rpcblist RPCBLIST; typedef struct rpcblist *rpcblist_ptr; /* * Remote calls arguments */ struct rpcb_rmtcallargs { rpcprog_t prog; /* program number */ rpcvers_t vers; /* version number */ rpcproc_t proc; /* procedure number */ u_int32_t arglen; /* arg len */ caddr_t args_ptr; /* argument */ xdrproc_t xdr_args; /* XDR routine for argument */ }; typedef struct rpcb_rmtcallargs rpcb_rmtcallargs; /* * Remote calls results */ struct rpcb_rmtcallres { char *addr_ptr; /* remote universal address */ u_int32_t resultslen; /* results length */ caddr_t results_ptr; /* results */ xdrproc_t xdr_results; /* XDR routine for result */ }; typedef struct rpcb_rmtcallres rpcb_rmtcallres; struct rpcb_entry { char *r_maddr; char *r_nc_netid; unsigned int r_nc_semantics; char *r_nc_protofmly; char *r_nc_proto; }; typedef struct rpcb_entry rpcb_entry; /* * A list of addresses supported by a service. */ struct rpcb_entry_list { rpcb_entry rpcb_entry_map; struct rpcb_entry_list *rpcb_entry_next; }; typedef struct rpcb_entry_list rpcb_entry_list; typedef rpcb_entry_list *rpcb_entry_list_ptr; /* * rpcbind statistics */ #define rpcb_highproc_2 RPCBPROC_CALLIT #define rpcb_highproc_3 RPCBPROC_TADDR2UADDR #define rpcb_highproc_4 RPCBPROC_GETSTAT #define RPCBSTAT_HIGHPROC 13 #define RPCBVERS_STAT 3 #define RPCBVERS_4_STAT 2 #define RPCBVERS_3_STAT 1 #define RPCBVERS_2_STAT 0 /* Link list of all the stats about getport and getaddr */ struct rpcbs_addrlist { rpcprog_t prog; rpcvers_t vers; int success; int failure; char *netid; struct rpcbs_addrlist *next; }; typedef struct rpcbs_addrlist rpcbs_addrlist; /* Link list of all the stats about rmtcall */ struct rpcbs_rmtcalllist { rpcprog_t prog; rpcvers_t vers; rpcproc_t proc; int success; int failure; int indirect; char *netid; struct rpcbs_rmtcalllist *next; }; typedef struct rpcbs_rmtcalllist rpcbs_rmtcalllist; typedef int rpcbs_proc[RPCBSTAT_HIGHPROC]; typedef rpcbs_addrlist *rpcbs_addrlist_ptr; typedef rpcbs_rmtcalllist *rpcbs_rmtcalllist_ptr; struct rpcb_stat { rpcbs_proc info; int setinfo; int unsetinfo; rpcbs_addrlist_ptr addrinfo; rpcbs_rmtcalllist_ptr rmtinfo; }; typedef struct rpcb_stat rpcb_stat; /* * One rpcb_stat structure is returned for each version of rpcbind * being monitored. */ typedef rpcb_stat rpcb_stat_byvers[RPCBVERS_STAT]; #ifdef __cplusplus } #endif #endif /* ndef _KERNEL */ #define RPCBPROG ((unsigned long)(100000)) #define RPCBVERS ((unsigned long)(3)) extern void rpcbprog_3(struct svc_req *rqstp, SVCXPRT *transp); #define RPCBPROC_SET ((unsigned long)(1)) extern bool_t * rpcbproc_set_3(rpcb *, CLIENT *); extern bool_t * rpcbproc_set_3_svc(rpcb *, struct svc_req *); #define RPCBPROC_UNSET ((unsigned long)(2)) extern bool_t * rpcbproc_unset_3(rpcb *, CLIENT *); extern bool_t * rpcbproc_unset_3_svc(rpcb *, struct svc_req *); #define RPCBPROC_GETADDR ((unsigned long)(3)) extern char ** rpcbproc_getaddr_3(rpcb *, CLIENT *); extern char ** rpcbproc_getaddr_3_svc(rpcb *, struct svc_req *); #define RPCBPROC_DUMP ((unsigned long)(4)) extern rpcblist_ptr * rpcbproc_dump_3(void *, CLIENT *); extern rpcblist_ptr * rpcbproc_dump_3_svc(void *, struct svc_req *); #define RPCBPROC_CALLIT ((unsigned long)(5)) extern rpcb_rmtcallres * rpcbproc_callit_3(rpcb_rmtcallargs *, CLIENT *); extern rpcb_rmtcallres * rpcbproc_callit_3_svc(rpcb_rmtcallargs *, struct svc_req *); #define RPCBPROC_GETTIME ((unsigned long)(6)) extern u_int * rpcbproc_gettime_3(void *, CLIENT *); extern u_int * rpcbproc_gettime_3_svc(void *, struct svc_req *); #define RPCBPROC_UADDR2TADDR ((unsigned long)(7)) extern struct netbuf * rpcbproc_uaddr2taddr_3(char **, CLIENT *); extern struct netbuf * rpcbproc_uaddr2taddr_3_svc(char **, struct svc_req *); #define RPCBPROC_TADDR2UADDR ((unsigned long)(8)) extern char ** rpcbproc_taddr2uaddr_3(struct netbuf *, CLIENT *); extern char ** rpcbproc_taddr2uaddr_3_svc(struct netbuf *, struct svc_req *); extern int rpcbprog_3_freeresult(SVCXPRT *, xdrproc_t, caddr_t); #define RPCBVERS4 ((unsigned long)(4)) extern void rpcbprog_4(struct svc_req *rqstp, SVCXPRT *transp); extern bool_t * rpcbproc_set_4(rpcb *, CLIENT *); extern bool_t * rpcbproc_set_4_svc(rpcb *, struct svc_req *); extern bool_t * rpcbproc_unset_4(rpcb *, CLIENT *); extern bool_t * rpcbproc_unset_4_svc(rpcb *, struct svc_req *); extern char ** rpcbproc_getaddr_4(rpcb *, CLIENT *); extern char ** rpcbproc_getaddr_4_svc(rpcb *, struct svc_req *); extern rpcblist_ptr * rpcbproc_dump_4(void *, CLIENT *); extern rpcblist_ptr * rpcbproc_dump_4_svc(void *, struct svc_req *); #define RPCBPROC_BCAST ((unsigned long)(RPCBPROC_CALLIT)) extern rpcb_rmtcallres * rpcbproc_bcast_4(rpcb_rmtcallargs *, CLIENT *); extern rpcb_rmtcallres * rpcbproc_bcast_4_svc(rpcb_rmtcallargs *, struct svc_req *); extern u_int * rpcbproc_gettime_4(void *, CLIENT *); extern u_int * rpcbproc_gettime_4_svc(void *, struct svc_req *); extern struct netbuf * rpcbproc_uaddr2taddr_4(char **, CLIENT *); extern struct netbuf * rpcbproc_uaddr2taddr_4_svc(char **, struct svc_req *); extern char ** rpcbproc_taddr2uaddr_4(struct netbuf *, CLIENT *); extern char ** rpcbproc_taddr2uaddr_4_svc(struct netbuf *, struct svc_req *); #define RPCBPROC_GETVERSADDR ((unsigned long)(9)) extern char ** rpcbproc_getversaddr_4(rpcb *, CLIENT *); extern char ** rpcbproc_getversaddr_4_svc(rpcb *, struct svc_req *); #define RPCBPROC_INDIRECT ((unsigned long)(10)) extern rpcb_rmtcallres * rpcbproc_indirect_4(rpcb_rmtcallargs *, CLIENT *); extern rpcb_rmtcallres * rpcbproc_indirect_4_svc(rpcb_rmtcallargs *, struct svc_req *); #define RPCBPROC_GETADDRLIST ((unsigned long)(11)) extern rpcb_entry_list_ptr * rpcbproc_getaddrlist_4(rpcb *, CLIENT *); extern rpcb_entry_list_ptr * rpcbproc_getaddrlist_4_svc(rpcb *, struct svc_req *); #define RPCBPROC_GETSTAT ((unsigned long)(12)) extern rpcb_stat * rpcbproc_getstat_4(void *, CLIENT *); extern rpcb_stat * rpcbproc_getstat_4_svc(void *, struct svc_req *); extern int rpcbprog_4_freeresult(SVCXPRT *, xdrproc_t, caddr_t); /* the xdr functions */ extern bool_t xdr_rpcb(XDR *, rpcb*); extern bool_t xdr_rp__list(XDR *, rp__list*); extern bool_t xdr_rpcblist_ptr(XDR *, rpcblist_ptr*); extern bool_t xdr_rpcb_rmtcallargs(XDR *, rpcb_rmtcallargs*); extern bool_t xdr_rpcb_rmtcallres(XDR *, rpcb_rmtcallres*); extern bool_t xdr_rpcb_entry(XDR *, rpcb_entry*); extern bool_t xdr_rpcb_entry_list(XDR *, rpcb_entry_list*); extern bool_t xdr_rpcb_entry_list_ptr(XDR *, rpcb_entry_list_ptr*); extern bool_t xdr_rpcbs_addrlist(XDR *, rpcbs_addrlist*); extern bool_t xdr_rpcbs_rmtcalllist(XDR *, rpcbs_rmtcalllist*); extern bool_t xdr_rpcbs_proc(XDR *, rpcbs_proc); extern bool_t xdr_rpcbs_addrlist_ptr(XDR *, rpcbs_addrlist_ptr*); extern bool_t xdr_rpcbs_rmtcalllist_ptr(XDR *, rpcbs_rmtcalllist_ptr*); extern bool_t xdr_rpcb_stat(XDR *, rpcb_stat*); extern bool_t xdr_rpcb_stat_byvers(XDR *, rpcb_stat_byvers); #ifdef __cplusplus } #endif #endif /* !_RPCB_PROT_H_RPCGEN */
iot-bc/eer-application
server/models/organizationSchema.js
const mongoose = require("mongoose"); const Schema = mongoose.Schema; let organizationSchema = new Schema({ orgID: { type: String, required: true, unique: true }, orgName: { type: String, required: true } }); organizationSchema.methods.setOrgID = function(orgID) { this.orgID = orgID; }; organizationSchema.methods.getOrgID = function() { return this.orgID; }; organizationSchema.methods.setOrgName = function(orgName) { this.orgName = orgName; }; organizationSchema.methods.getOrgName = function() { return this.orgName; }; let Organization = mongoose.model("Organization", organizationSchema); module.exports = Organization;
RedBeard0531/mongo_utils
util/fail_point_service.h
<reponame>RedBeard0531/mongo_utils /* * Copyright (C) 2012 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "mongo/base/init.h" #include "mongo/util/fail_point.h" #include "mongo/util/fail_point_registry.h" namespace mongo { /** * @return the global fail point registry. */ FailPointRegistry* getGlobalFailPointRegistry(); /** * Convenience macro for defining a fail point. Must be used at namespace scope. * Note: that means never at local scope (inside functions) or class scope. * * NOTE: Never use in header files, only sources. */ #define MONGO_FAIL_POINT_DEFINE(fp) \ ::mongo::FailPoint fp; \ MONGO_INITIALIZER_GENERAL(fp, ("FailPointRegistry"), ("AllFailPointsRegistered")) \ (::mongo::InitializerContext * context) { \ return ::mongo::getGlobalFailPointRegistry()->addFailPoint(#fp, &fp); \ } /** * Convenience macro for declaring a fail point in a header. */ #define MONGO_FAIL_POINT_DECLARE(fp) extern ::mongo::FailPoint fp; /** * Convenience class for enabling a failpoint and disabling it as this goes out of scope. */ class FailPointEnableBlock { public: FailPointEnableBlock(const std::string& failPointName); ~FailPointEnableBlock(); private: FailPoint* _failPoint; }; } // namespace mongo
consumer-tasks/letcode
1785-minimum-elements-to-add-to-form-a-given-sum.js
<reponame>consumer-tasks/letcode /** * @param {number[]} nums * @param {number} limit * @param {number} goal * @return {number} */ const minElements = function(nums, limit, goal) { const sum = nums.reduce((ac, e) => ac + e, 0) let delta = goal - sum if(delta === 0) return 0 const op = delta > 0 ? '+' : '-' let res = 0 delta = Math.abs(delta) return Math.floor(delta / limit) + (delta % limit > 0 ? 1 : 0) };
skkuse-adv/2019Fall_team2
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/kr/co/popone/fitts/viewmodel/store/newest/NewestProductViewModel$registerLikeProductBus$2.java
<gh_stars>1-10 package kr.co.popone.fitts.viewmodel.store.newest; import com.orhanobut.logger.Logger; import io.reactivex.functions.Consumer; final class NewestProductViewModel$registerLikeProductBus$2<T> implements Consumer<Throwable> { public static final NewestProductViewModel$registerLikeProductBus$2 INSTANCE = new NewestProductViewModel$registerLikeProductBus$2(); NewestProductViewModel$registerLikeProductBus$2() { } public final void accept(Throwable th) { Logger.d("Observing Failed about WishStateUpdateEvent", new Object[0]); } }
NewBediver/FarLight
FarLight/src/FarLight/ConfigurationSystem/LocalConfigurations/Application/ApplicationConfiguration.h
<reponame>NewBediver/FarLight #pragma once #include <string> #include "FarLight/ConfigurationSystem/Configuration.h" namespace FarLight { class ApplicationConfiguration final : public Configuration { public: explicit ApplicationConfiguration() noexcept : Configuration("Application") { } unsigned GetWidth() noexcept; void SetWidth(unsigned width) noexcept; unsigned GetHeight() noexcept; void SetHeight(unsigned height) noexcept; std::string GetTitle() noexcept; void SetTitle(const std::string& title) noexcept; }; }
AleksK1NG/React-Redux-practice-workshop
src/components/NewArticlesList/NewArticlesList.js
<gh_stars>0 import React, { Component } from 'react' import { connect } from 'react-redux' import {addNewArticle, deleteNewArticle} from '../../actions/newArticlesActions' import { newArticleSelector, newArticleTitlesSelector, newArtComboSelector } from '../../selectors'; class NewArticlesList extends Component { state = { id: '', title: '', rating: 0 } handleSubmit = (e) => { e.preventDefault() const newArticle = { id: this.state.id, title: this.state.title, rating: this.state.rating } this.props.addNewArticle(newArticle) console.log('Submit form', newArticle) this.setState({ id: '', title: '', rating: '' }) } handleChange = (e) => { this.setState({ [e.target.name]: e.target.value }) } render() { const { articlesList, deleteNewArticle, titles, newArtCombo } = this.props const { id, rating, title } = this.state return ( <div> <h1>NewArticlesList</h1> <form onSubmit={this.handleSubmit}> <label>ID</label> <input value={id} onChange={this.handleChange} name="id" type="number" /> <label>Title</label> <input value={title} onChange={this.handleChange} name="title" type="text" /> <label>Rating</label> <input value={rating} onChange={this.handleChange} name="rating" type="number" /> <button>Add Article</button> </form> {articlesList && articlesList.map((article) => ( <div key={article.id}> <h2>{article.title}</h2> <p>Rating is: {article.rating} </p> <button onClick={() => deleteNewArticle(article.id)}> Delete </button> </div> ))} <hr/> </div> ) } } const mapStateToProps = (state) => ({ // articlesList: state.newArticles.articlesList, articlesList: newArticleSelector(state), // titles: newArticleTitlesSelector(state), // newArtCombo: newArtComboSelector(state) }) export default connect( mapStateToProps, { deleteNewArticle, addNewArticle } )(NewArticlesList)
Danylo79/Dankom-Core
src/main/java/dev/dankom/interfaces/runner/MethodRunner.java
<gh_stars>1-10 package dev.dankom.interfaces.runner; public interface MethodRunner { void run(); }
jonahbull/apm-agent-java
apm-agent-attach/src/main/java/co/elastic/apm/attach/RemoteAttacher.java
<filename>apm-agent-attach/src/main/java/co/elastic/apm/attach/RemoteAttacher.java /*- * #%L * Elastic APM Java agent * %% * Copyright (C) 2018 - 2019 Elastic and contributors * %% * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * #L% */ package co.elastic.apm.attach; import javax.annotation.Nonnull; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Scanner; import java.util.Set; /** * Attaches the Elastic APM Java agent to a JVM with a specific PID or runs continuously and attaches to all running and starting JVMs which match. */ public class RemoteAttacher { private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private final Arguments arguments; private Set<JvmInfo> runningJvms = new HashSet<>(); private RemoteAttacher(Arguments arguments) { this.arguments = arguments; } public static void main(String[] args) throws IOException, InterruptedException { Arguments arguments; try { arguments = Arguments.parse(args); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); arguments = Arguments.parse("--help"); } final RemoteAttacher attacher = new RemoteAttacher(arguments); if (arguments.isHelp()) { arguments.printHelp(System.out); } else if (arguments.isList()) { System.out.println(getJpsOutput()); } else if (arguments.getPid() != null) { log("INFO", "Attaching the Elastic APM agent to %s", arguments.getPid()); ElasticApmAttacher.attach(arguments.getPid(), arguments.getConfig()); log("INFO", "Done"); } else { do { attacher.attachToNewJvms(getJpsOutput()); Thread.sleep(1000); } while (arguments.isContinuous()); } } private static void log(String level, String message, Object... args) { System.out.println(String.format("%s %5s ", df.format(new Date()), level) + String.format(message, args)); } @Nonnull private static String getJpsOutput() throws IOException, InterruptedException { final Process jps = new ProcessBuilder("jps", "-l").start(); if (jps.waitFor() == 0) { return toString(jps.getInputStream()); } else { throw new IllegalStateException(toString(jps.getErrorStream())); } } private static String toString(InputStream inputStream) throws IOException { try { Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; } finally { inputStream.close(); } } private void attachToNewJvms(String jpsOutput) { final Set<JvmInfo> currentlyRunningJvms = getJVMs(jpsOutput); for (JvmInfo jvmInfo : getStartedJvms(currentlyRunningJvms)) { if (!jvmInfo.packageOrPath.endsWith(".Jps") && !jvmInfo.packageOrPath.isEmpty()) { onJvmStart(jvmInfo); } } runningJvms = currentlyRunningJvms; } @Nonnull private Set<JvmInfo> getJVMs(String jpsOutput) { Set<JvmInfo> set = new HashSet<>(); for (String s : jpsOutput.split("\n")) { JvmInfo parse = JvmInfo.parse(s); set.add(parse); } return set; } private Set<JvmInfo> getStartedJvms(Set<JvmInfo> currentlyRunningJvms) { final HashSet<JvmInfo> newJvms = new HashSet<>(currentlyRunningJvms); newJvms.removeAll(runningJvms); return newJvms; } private void onJvmStart(JvmInfo jvmInfo) { if (isIncluded(jvmInfo) && !isExcluded(jvmInfo)) { try { final String agentArgs = getAgentArgs(jvmInfo); log("INFO", "Attaching the Elastic APM agent to %s with arguments %s", jvmInfo, agentArgs); ElasticApmAttacher.attach(jvmInfo.pid, agentArgs); log("INFO", "Done"); } catch (Exception e) { e.printStackTrace(); } } else { log("DEBUG", "Not attaching the Elastic APM agent to %s, because it is not included or excluded.", jvmInfo); } } private String getAgentArgs(JvmInfo jvmInfo) throws IOException, InterruptedException { return arguments.getArgsProvider() != null ? getArgsProviderOutput(jvmInfo) : ElasticApmAttacher.toAgentArgs(arguments.getConfig()); } private String getArgsProviderOutput(JvmInfo jvmInfo) throws IOException, InterruptedException { final Process jps = new ProcessBuilder(arguments.getArgsProvider(), jvmInfo.pid, jvmInfo.packageOrPath).start(); if (jps.waitFor() == 0) { return toString(jps.getInputStream()); } else { log("INFO", "Not attaching the Elastic APM agent to %s, " + "because the '--args-provider %s' script ended with a non-zero status code.", jvmInfo, arguments.argsProvider); throw new IllegalStateException(toString(jps.getErrorStream())); } } private boolean isIncluded(JvmInfo jvmInfo) { if (arguments.getIncludes().isEmpty()) { return true; } for (String include : arguments.getIncludes()) { if (jvmInfo.packageOrPath.matches(include)) { return true; } } return false; } private boolean isExcluded(JvmInfo jvmInfo) { for (String exclude : arguments.getExcludes()) { if (jvmInfo.packageOrPath.matches(exclude)) { return true; } } return false; } static class JvmInfo { final String pid; final String packageOrPath; JvmInfo(String pid, String packageOrPath) { this.pid = pid; this.packageOrPath = packageOrPath; } static JvmInfo parse(String jpsLine) { final int firstSpace = jpsLine.indexOf(' '); return new JvmInfo(jpsLine.substring(0, firstSpace), jpsLine.substring(firstSpace + 1)); } @Override public String toString() { return "JvmInfo{" + "pid='" + pid + '\'' + ", packageOrPath='" + packageOrPath + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; JvmInfo jvmInfo = (JvmInfo) o; return pid.equals(jvmInfo.pid); } @Override public int hashCode() { return Objects.hash(pid); } } static class Arguments { private final String pid; private final List<String> includes; private final List<String> excludes; private final Map<String, String> config; private final String argsProvider; private final boolean help; private final boolean list; private final boolean continuous; private Arguments(String pid, List<String> includes, List<String> excludes, Map<String, String> config, String argsProvider, boolean help, boolean list, boolean continuous) { this.help = help; this.list = list; this.continuous = continuous; if (!config.isEmpty() && argsProvider != null) { throw new IllegalArgumentException("Providing both --config and --args-provider is illegal"); } if (pid != null && (!includes.isEmpty() || !excludes.isEmpty() || continuous)) { throw new IllegalArgumentException("Providing --pid and either of --include, --exclude or --continuous is illegal"); } this.pid = pid; this.includes = includes; this.excludes = excludes; this.config = config; this.argsProvider = argsProvider; } static Arguments parse(String... args) { String pid = null; List<String> includes = new ArrayList<>(); List<String> excludes = new ArrayList<>(); Map<String, String> config = new HashMap<>(); String argsProvider = null; boolean help = args.length == 0; boolean list = false; boolean continuous = false; String currentArg = ""; for (String arg : normalize(args)) { if (arg.startsWith("-")) { currentArg = arg; switch (arg) { case "-h": case "--help": help = true; break; case "-l": case "--list": list = true; break; case "-c": case "--continuous": continuous = true; break; case "-p": case "--pid": case "-a": case "--args": case "-C": case "--config": case "-A": case "--args-provider": case "-e": case "--exclude": case "-i": case "--include": break; default: throw new IllegalArgumentException("Illegal argument: " + arg); } } else { switch (currentArg) { case "-e": case "--exclude": excludes.add(arg); break; case "-i": case "--include": includes.add(arg); break; case "-p": case "--pid": pid = arg; break; case "-a": case "--args": System.err.println("--args is deprecated in favor of --config"); for (String conf : arg.split(";")) { config.put(conf.substring(0, conf.indexOf('=')), conf.substring(conf.indexOf('=') + 1)); } break; case "-C": case "--config": config.put(arg.substring(0, arg.indexOf('=')), arg.substring(arg.indexOf('=') + 1)); break; case "-A": case "--args-provider": argsProvider = arg; break; default: throw new IllegalArgumentException("Illegal argument: " + arg); } } } return new Arguments(pid, includes, excludes, config, argsProvider, help, list, continuous); } // -ab -> -a -b private static List<String> normalize(String[] args) { final List<String> normalizedArgs = new ArrayList<>(args.length); for (String arg : args) { if (arg.startsWith("-") && !arg.startsWith("--")) { for (int i = 1; i < arg.length(); i++) { normalizedArgs.add("-" + arg.charAt(i)); } } else { normalizedArgs.add(arg); } } return normalizedArgs; } void printHelp(PrintStream out) { out.println("SYNOPSIS"); out.println(" java -jar apm-agent-attach.jar -p <pid> [--args <agent_arguments>]"); out.println(" java -jar apm-agent-attach.jar [-i <include_pattern>...] [-e <exclude_pattern>...] [--continuous]"); out.println(" [--config <key=value>... | --args-provider <args_provider_script>]"); out.println(" java -jar apm-agent-attach.jar (--list | --help)"); out.println(); out.println("DESCRIPTION"); out.println(" Attaches the Elastic APM Java agent to a JVM with a specific PID or runs continuously and attaches to all running and starting JVMs which match the filters."); out.println(); out.println("OPTIONS"); out.println(" -l, --list"); out.println(" Lists all running JVMs. Same output as 'jps -l'."); out.println(); out.println(" -p, --pid <pid>"); out.println(" PID of the JVM to attach. If not provided, attaches to all currently running JVMs which match the --exclude and --include filters."); out.println(); out.println(" -c, --continuous"); out.println(" If provided, this program continuously runs and attaches to all running and starting JVMs which match the --exclude and --include filters."); out.println(); out.println(" -e, --exclude <exclude_pattern>..."); out.println(" A list of regular expressions of fully qualified main class names or paths to JARs of applications the java agent should not be attached to."); out.println(" (Matches the output of 'jps -l')"); out.println(); out.println(" -i, --include <include_pattern>..."); out.println(" A list of regular expressions of fully qualified main class names or paths to JARs of applications the java agent should be attached to."); out.println(" (Matches the output of 'jps -l')"); out.println(); out.println(" -a, --args <agent_arguments>"); out.println(" Deprecated in favor of --config."); out.println(" If set, the arguments are used to configure the agent on the attached JVM (agentArguments of agentmain)."); out.println(" The syntax of the arguments is 'key1=value1;key2=value1,value2'."); out.println(); out.println(" -C --config <key=value>..."); out.println(" This repeatable option sets one agent configuration option."); out.println(" Example: --config server_urls=http://localhost:8200,http://localhost:8201."); out.println(); out.println(" -A, --args-provider <args_provider_script>"); out.println(" The name of a program which is called when a new JVM starts up."); out.println(" The program gets the pid and the main class name or path to the JAR file as an argument"); out.println(" and returns an arg string which is used to configure the agent on the attached JVM (agentArguments of agentmain)."); out.println(" When returning a non-zero status code from this program, the agent will not be attached to the starting JVM."); out.println(" The syntax of the arguments is 'key1=value1;key2=value1,value2'."); out.println(" Note: this option can not be used in conjunction with --pid and --args."); } String getPid() { return pid; } List<String> getIncludes() { return includes; } List<String> getExcludes() { return excludes; } Map<String, String> getConfig() { return config; } String getArgsProvider() { return argsProvider; } boolean isHelp() { return help; } boolean isList() { return list; } boolean isContinuous() { return continuous; } } }
cloud-SN1/uxcool
packages/uxcool/src/index.js
<reponame>cloud-SN1/uxcool<gh_stars>10-100 import { install } from './components/index'; export { default } from './components/index'; require.context('./components', true, /^\.\/[^_][\w-]+\/style\/index\.js$/); if (typeof window !== 'undefined' && window.Vue) { window.Vue.use(install); }
dhiaayachi/go-newton-co
query/tick_sizes_test.go
<filename>query/tick_sizes_test.go package query_test import ( "net/http" "reflect" "testing" "github.com/dhiaayachi/go-newton-co/query" "github.com/onsi/gomega" ) func TestTickSizesGetBody(t *testing.T) { g := gomega.NewGomegaWithT(t) sut := &query.TickSizes{} actualBody, err := sut.GetBody() g.Expect(err).Should(gomega.BeNil()) g.Expect(actualBody).Should(gomega.BeEquivalentTo(query.EMPTY_BODY)) } func TestTickSizesGetMethod(t *testing.T) { g := gomega.NewGomegaWithT(t) sut := &query.TickSizes{} g.Expect(sut.GetMethod()).Should(gomega.Equal(http.MethodGet)) } func TestTickSizesGetPath(t *testing.T) { g := gomega.NewGomegaWithT(t) sut := &query.TickSizes{} g.Expect(sut.GetPath()).Should(gomega.Equal(query.TickSizesPath)) } func TestTickSizesGetParameters(t *testing.T) { g := gomega.NewGomegaWithT(t) sut := &query.TickSizes{} parameters := sut.GetParameters() g.Expect(len(parameters)).Should(gomega.Equal(0)) } func TestTickSizesGetResponse(t *testing.T) { g := gomega.NewGomegaWithT(t) sut := &query.TickSizes{} response := sut.GetResponse() g.Expect(reflect.TypeOf(response)).Should(gomega.Equal(reflect.TypeOf(&query.TickSizesResponse{}))) } func TestTickSizesIsPublic(t *testing.T) { g := gomega.NewGomegaWithT(t) sut := &query.TickSizes{} g.Expect(sut.IsPublic()).Should(gomega.BeTrue()) }
vikingdr/SoberGrid
SoberGrid/XMPPFiles/Core/XMPPParser.h
#import <Foundation/Foundation.h> #if TARGET_OS_IPHONE #import "DDXML.h" #endif @interface XMPPParser : NSObject - (id)initWithDelegate:(id)delegate delegateQueue:(dispatch_queue_t)dq; - (id)initWithDelegate:(id)delegate delegateQueue:(dispatch_queue_t)dq parserQueue:(dispatch_queue_t)pq; - (void)setDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue; /** * Asynchronously parses the given data. * The delegate methods will be dispatch_async'd as events occur. **/ - (void)parseData:(NSData *)data; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPParserDelegate @optional - (void)xmppParser:(XMPPParser *)sender didReadRoot:(NSXMLElement *)root; - (void)xmppParser:(XMPPParser *)sender didReadElement:(NSXMLElement *)element; - (void)xmppParserDidEnd:(XMPPParser *)sender; - (void)xmppParser:(XMPPParser *)sender didFail:(NSError *)error; - (void)xmppParserDidParseData:(XMPPParser *)sender; @end
jamescaoBJ/springcloud
springboot-dao/src/main/java/com/ncme/springboot/model/NcmeStudyCardHistory.java
package com.ncme.springboot.model; import java.util.Date; public class NcmeStudyCardHistory { private String cardNo; private String cardPasswd; private String cardType; private Date operatorDate; private String userName; private Date linkDate; private Integer balance; private Integer times; private String orderNo; private Integer saleType; private String parentCard; private String remark; public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public String getCardPasswd() { return cardPasswd; } public void setCardPasswd(String cardPasswd) { this.cardPasswd = cardPasswd; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } public Date getOperatorDate() { return operatorDate; } public void setOperatorDate(Date operatorDate) { this.operatorDate = operatorDate; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getLinkDate() { return linkDate; } public void setLinkDate(Date linkDate) { this.linkDate = linkDate; } public Integer getBalance() { return balance; } public void setBalance(Integer balance) { this.balance = balance; } public Integer getTimes() { return times; } public void setTimes(Integer times) { this.times = times; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public Integer getSaleType() { return saleType; } public void setSaleType(Integer saleType) { this.saleType = saleType; } public String getParentCard() { return parentCard; } public void setParentCard(String parentCard) { this.parentCard = parentCard; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
caibirdme/leetforfun
leetcode/leet_76/source.go
<gh_stars>10-100 package leet_76 func minWindow(s string, t string) string { target := make(map[byte]int) for i := 0; i < len(t); i++ { if _, ok := target[t[i]]; !ok { target[t[i]] = 1 } else { target[t[i]]++ } } count := make(map[byte]int) ans := len(s) + 1 pos := make([]int, 0, len(target)) left := 0 res := "" for i := 0; i < len(s); i++ { if _, ok := target[s[i]]; !ok { continue } addCount(count, s[i]) pos = append(pos, i) if mapEq(target, count) { l := i - pos[left] + 1 if ans > l { ans = l res = s[pos[left] : i+1] } for { ch := s[pos[left]] left++ if left >= len(pos) { break } reduceCount(count, ch) if mapEq(target, count) { l := i - pos[left] + 1 if ans > l { ans = l res = s[pos[left] : i+1] } } else { left-- addCount(count, ch) break } } } } return res } func reduceCount(count map[byte]int, ch byte) { v := count[ch] if v > 1 { count[ch]-- } else { delete(count, ch) } } func addCount(count map[byte]int, ch byte) { if _, ok := count[ch]; !ok { count[ch] = 1 } else { count[ch]++ } } func min(a, b int) int { if a < b { return a } return b } func mapEq(mp1, mp2 map[byte]int) bool { if len(mp1) != len(mp2) { return false } for k, v1 := range mp1 { v2, ok := mp2[k] if !ok { return false } if v1 > v2 { return false } } return true }
CloudifySource/Cloudify-iTests
src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/persistence/ScaleoutAfterRecoveryUsingHostNamesTest.java
package org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.byon.persistence; import iTests.framework.utils.LogUtils; import iTests.framework.utils.NetworkUtils; import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services.byon.MultipleTemplatesByonCloudService; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Created with IntelliJ IDEA. * User: elip * Date: 5/6/13 * Time: 11:24 AM * To change this template use File | Settings | File Templates. */ public class ScaleoutAfterRecoveryUsingHostNamesTest extends AbstractByonManagementPersistencyTest { private MultipleTemplatesByonCloudService service = new MultipleTemplatesByonCloudService(); @BeforeClass(alwaysRun = true) protected void bootstrap() throws Exception { String[] machines = service.getMachines(); LogUtils.log("Converting IP Addresses to host names"); String[] machinesHostNames = NetworkUtils.resolveIpsToHostNames(machines); service.setMachines(machinesHostNames); service.setManagementMachineTemplate("TEMPLATE_1"); service.setNumberOfHostsForTemplate("TEMPLATE_1", 2); // assign two hosts for management. // all other hosts will be assigned to the default "SMALL_LINUX" template. super.bootstrap(service); super.installTomcatService(1, null); } @Test(timeOut = DEFAULT_TEST_TIMEOUT * 4, enabled = true) public void testScaleoutAfterRecovery() throws Exception { super.testScaleoutAfterRecovery(); } @AfterClass(alwaysRun = true) public void teardown() throws Exception{ super.teardown(); } }
Kangmo/bitcoinj
core/src/main/scala/com/nhnsoft/bitcoin/core/PeerFilterProvider.scala
/* * Copyright 2013 Google Inc. * Copyright 2014 <NAME> * * 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.nhnsoft.bitcoin.core; import java.util.concurrent.locks.Lock; /** * An interface which provides the information required to properly filter data downloaded from Peers. * Note that an implementer is responsible for calling {@link PeerGroup#recalculateFastCatchupAndFilter(boolean)} whenever a * change occurs which effects the data provided via this interface. */ trait PeerFilterProvider { /** * Returns the earliest timestamp (seconds since epoch) for which full/bloom-filtered blocks must be downloaded. * Blocks with timestamps before this time will only have headers downloaded. 0 requires that all blocks be * downloaded, and thus this should default to {@link System#currentTimeMillis()}/1000. */ def getEarliestKeyCreationTime() : Long /** * Gets the number of elements that will be added to a bloom filter returned by * {@link PeerFilterProvider#getBloomFilter(int, double, long)} */ def getBloomFilterElementCount() : Int /** * Gets a bloom filter that contains all the necessary elements for the listener to receive relevant transactions. * Default value should be an empty bloom filter with the given size, falsePositiveRate, and nTweak. */ def getBloomFilter(size : Int, falsePositiveRate : Double, nTweak : Long) : BloomFilter /** Whether this filter provider depends on the server updating the filter on all matches */ def isRequiringUpdateAllBloomFilter() : Boolean /** * Returns an object that will be locked before any other methods are called and unlocked afterwards. You must * provide one of these because the results from calling the above methods must be consistent. Otherwise it's * possible for the {@link com.nhnsoft.bitcoin.net.FilterMerger} to request the counts of a bunch of providers * with {@link #getBloomFilterElementCount()}, create a filter of the right size, call {@link #getBloomFilter(int, double, long)} * and then the filter provider discovers it's been mutated in the mean time and now has a different number of * elements. For instance, a Wallet that has keys added to it whilst a filter recalc is in progress could cause * experience this race. */ def getLock() : Lock }
JSybrandt/SuperSpirograph
src/main/java/geometry/wheelshape/Shield.java
package geometry.wheelshape; /** * A shield shaped wheel. */ public class Shield extends WheelGeometry { /** * * @param scale a positive value representing the general size of the shape. */ public Shield(float scale){ super(null); } }
UM-ARM-Lab/mab_ms
deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgwidgettable/osgwidgettable.cpp
<filename>deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgwidgettable/osgwidgettable.cpp // -*-c++-*- osgWidget - Code by: <NAME> (cubicool) 2007-2008 // $Id: osgwidgettable.cpp 43 2008-04-17 03:40:05Z cubicool $ #include <osgWidget/Util> #include <osgWidget/WindowManager> #include <osgWidget/Table> const unsigned int MASK_2D = 0xF0000000; // This examples demonstrates the use of an osgWidget::Table, which differs from a Box in // many ways. First and foremost, a Table's size is intially known, whereas a Box can be // dynamically added to. Secondly, a table is matrix Layout, with both vertical and // horizontal placement cells. A Box, on the other hand, can only be vertical or horizontal. int main(int argc, char** argv) { osgViewer::Viewer viewer; osgWidget::WindowManager* wm = new osgWidget::WindowManager( &viewer, 1280.0f, 1024.0f, MASK_2D, osgWidget::WindowManager::WM_PICK_DEBUG ); osgWidget::Table* table = new osgWidget::Table("table", 3, 3); // Here we create our "cells" manually, though it will often be convenient to // do so algorithmically. Also, notice how we set the text name of each widget to // correspond with it's "index" in the table. This is merely a convenience, which // we use later... table->addWidget(new osgWidget::Widget("0, 0", 100.0f, 25.0f), 0, 0); table->addWidget(new osgWidget::Widget("0, 1", 100.0f, 25.0f), 0, 1); table->addWidget(new osgWidget::Widget("0, 2", 100.0f, 75.0f), 0, 2); table->addWidget(new osgWidget::Widget("1, 0", 200.0f, 45.0f), 1, 0); table->addWidget(new osgWidget::Widget("1, 1", 200.0f, 45.0f), 1, 1); table->addWidget(new osgWidget::Widget("1, 2", 200.0f, 45.0f), 1, 2); table->addWidget(new osgWidget::Widget("2, 0", 300.0f, 65.0f), 2, 0); table->addWidget(new osgWidget::Widget("2, 1", 300.0f, 65.0f), 2, 1); table->addWidget(new osgWidget::Widget("2, 2", 300.0f, 65.0f), 2, 2); table->getBackground()->setColor(0.0f, 0.0f, 0.5f, 1.0f); table->attachMoveCallback(); // Use a hackish method of setting the spacing for all Widgets. for(osgWidget::Table::Iterator i = table->begin(); i != table->end(); i++) i->get()->setPadding(1.0f) ; // Now we fetch the very first 0, 0 Widget in the table using an awkward method. // This is merely one way to fetch a Widget from a Window, there are many others. // The osgWidget::Window::getByName interface will be very handy in scripting languages // where users will want to retrieve handles to existing Windows using a useful // textual name, such as "MainGUIParent" or something. table->getByName("0, 0")->setAlignHorizontal(osgWidget::Widget::HA_LEFT); table->getByName("0, 0")->setAlignVertical(osgWidget::Widget::VA_BOTTOM); table->getByName("0, 0")->setPadLeft(50.0f); table->getByName("0, 0")->setPadTop(3.0f); // Change the colors a bit to differentiate this row from the others. table->getByName("2, 0")->setColor(1.0f, 0.0f, 0.0f, 1.0f, osgWidget::Widget::LOWER_LEFT); table->getByName("2, 1")->setColor(1.0f, 0.0f, 0.0f, 0.5f); table->getByName("2, 2")->setColor(1.0f, 0.0f, 0.0f, 0.5f); wm->addChild(table); return createExample(viewer, wm); }
ruoranluomu/AliOS-Things
platform/mcu/msp432p4xx/ti/drivers/.meta/AESCCM.syscfg.js
<reponame>ruoranluomu/AliOS-Things /*! * ======== AESCCM configuration ======== * Advanced Encryption Standard (AES) module, counter (CTR) mode with cypher * block chaining message authentication (CBC-MAC). */ "use strict"; /* global exports, system */ /* get Common /ti/drivers utility functions */ let Common = system.getScript("/ti/drivers/Common.js"); /* get /ti/drivers family name from device object */ let family = Common.device2Family(system.deviceData, "AESCCM"); /* Intro splash on GUI */ let longDescription = "AESCCM combines CBC-MAC with an AES block cipher in CTR mode " + "of operation. This combination of block cipher modes enables CCM to encrypt " + "messages of any length and not only multiples of the block cipher block size."; let intPriority = Common.newIntPri()[0]; intPriority.displayName = "Crypto peripheral interrupt priority"; let swiPriority = Common.newSwiPri(); swiPriority.displayName = "Crypto interrupt Swi handler priority"; /*! * ======== base ======== * Define the base ECDH properties and methods */ let base = { displayName : "AESCCM", description : "AES CCM mode ", longDescription : longDescription, validate : validate, defaultInstanceName : "Board_AESCCM", maxInstances : 1, moduleStatic : { config : [ intPriority, swiPriority ] } }; /*! * ======== validate ======== * Validate this module's configuration * * @param inst - AESCCM instance to be validated * @param validation - object to hold detected validation issues */ function validate(inst, validation) { } /* get family-specific AEECCM module */ let devAESCCM = system.getScript("/ti/drivers/aesccm/AESCCM" + family); exports = devAESCCM.extend(base);
cuihaoleo/exercises
UVaOJ/694 - The Collatz Sequence.c
#include <stdio.h> #include <stdlib.h> int main() { int ct = 0; while (1) { long long a; int l, step = 1; scanf("%lld%d", &a, &l); if (a < 0) break; printf("Case %d: A = %lld, limit = %d, ", ++ct, a, l); while (a!=1) { a = a%2 ? a*3+1 : a/2; if (a <= l) step++; else break; } printf("number of terms = %d\n", step); } return 0; }
saxix/django-db-logging
tests/demoapp/demo/settings.py
<gh_stars>0 from django_db_logging.router import LoggingRouter DEBUG = True STATIC_URL = '/static/' SITE_ID = 1 ROOT_URLCONF = 'demo.urls' SECRET_KEY = 'abc' STATIC_ROOT = 'static' MEDIA_ROOT = 'media' INSTALLED_APPS = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'admin_extra_urls', 'django_db_logging', 'demo' ] MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': ['django.contrib.messages.context_processors.messages', 'django.contrib.auth.context_processors.auth', "django.template.context_processors.request", ] }, }, ] LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'debug': { 'format': '%(levelno)s:%(levelname)-8s %(name)s %(funcName)s:%(lineno)s:: %(message)s' } }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'debug' }, 'db': { 'level': 'DEBUG', 'class': 'django_db_logging.handlers.DBHandler', }, 'db-demo': { 'level': 'DEBUG', 'class': 'django_db_logging.handlers.DBHandler', 'model': 'demo.CustomLogger', }, }, 'loggers': { 'django_db_logging': { 'handlers': ['null', 'db'], 'propagate': True, 'level': 'DEBUG' }, 'demo': { 'handlers': ['db-demo'], 'propagate': True, 'level': 'DEBUG' } } } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' }, 'logging': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } } DATABASE_ROUTERS = [ LoggingRouter("logging") ]
rsumner33/PTVS
Release/Tests/AnalysisTest/Python.VS.TestData/Grammar/Keywords25.py
with = 1 as = 2
appfs/appfs
Brand/ex1/html/search/variables_3.js
var searchData= [ ['totlines',['totLines',['../ex1_8cpp.html#a93c5413e758efa3b9cefdb398c6edcd5',1,'ex1.cpp']]] ];
Grace-Amondi/Health
widgets/Chart/nls/sl/strings.js
define({ "_widgetLabel": "Grafikon", "executeChartTip": "Kliknite enega od naslednjih elementov nalog za izvedbo grafikona.", "invalidConfig": "Neveljavna konfiguracija.", "noneChartTip": "Opravilo grafikona ni konfigurirano za ta pripomoček", "chartParams": "Možnosti", "charts": "GRAFIKONI", "apply": "UPORABI", "useSpatialFilter": "Uporabi prostorski filter za omejitev geoobjektov", "useCurrentMapExtent": "Samo geoobjekti, ki sekajo trenutno območje karte", "drawGraphicOnMap": "Samo geoobjekti, ki sekajo območje, ki ga je določil uporabnik", "chartResults": "Rezultati grafikona", "clearResults": "Počisti rezultate", "noPermissionsMsg": "Za dostop do te storitve nimate dovoljenj.", "specifySpatialFilterMsg": "Določite prostorski filter za to nalogo.", "queryError": "Poizvedba ni uspela.", "noResults": "Geoobjekta ni mogoče najti.", "category": "Kategorija", "count": "Števec", "label": "Napis", "horizontalAxis": "Horizontalna os", "verticalAxis": "Vertikalna os", "dataLabels": "Napisi podatkov", "color": "Barva", "colorful": "Pisano", "monochromatic": "Enobarvno", "tasks": "Opravila", "results": "Rezultati", "applySpatialFilterToLimitResults": "Za omejitev rezultatov uporabi prostorski filter", "useCurrentExtentTip": "Delno ali v celoti znotraj trenutnega obsega karte", "useDrawGraphicTip": "Delno ali v celoti znotraj oblike, narisane na karti", "useFeaturesTip": "Glede na njihove lokacije, relativno na geoobjekte v drugem sloju", "noSpatialLimitTip": "Rezultatov ne omejuj prostorsko", "applySearchDistance": "Uporabite iskalno razdaljo.", "spatialRelationship": "Prostorska relacija", "relatedLayer": "Relacijski sloj", "clear": "Počisti", "bufferDistance": "Razdalja obrisa", "miles": "Milje", "kilometers": "Kilometri", "feet": "Čevlji", "meters": "Metri", "yards": "Jardi", "nauticalMiles": "Morske milje", "back": "Nazaj", "execute": "Uporabi", "backCharts": "Nazaj na grafikone", "backOptions": "Nazaj na možnosti", "clearCharts": "Počisti vse grafikone" });
Jeanmilost/Demos
Embarcadero/OpenGL/MD3 reader/Classes/QR_Base/QR_MemoryTools/QR_MemoryTools.cpp
<filename>Embarcadero/OpenGL/MD3 reader/Classes/QR_Base/QR_MemoryTools/QR_MemoryTools.cpp<gh_stars>1-10 /***************************************************************************** * ==> QR_MemoryTools -------------------------------------------------------* * *************************************************************************** * Description : Some memory tools * * Developer : <NAME> * *****************************************************************************/ #include "QR_MemoryTools.h" // std #include <mem.h> // qr engine #include "QR_Exception.h" //--------------------------------------------------------------------------- // QR_MemoryTools::IBuffer - c++ cross-platform //--------------------------------------------------------------------------- QR_MemoryTools::IBuffer::IBuffer() : m_pBuffer(NULL), m_Length(0) {} //--------------------------------------------------------------------------- QR_MemoryTools::IBuffer::~IBuffer() {} //--------------------------------------------------------------------------- // QR_MemoryTools - c++ cross-platform //--------------------------------------------------------------------------- QR_MemoryTools::QR_MemoryTools() {} //--------------------------------------------------------------------------- QR_MemoryTools::~QR_MemoryTools() {} //--------------------------------------------------------------------------- bool QR_MemoryTools::CompareBuffers(const IBuffer& buffer1, const IBuffer& buffer2, IEBufferCompType type, QR_SizeT blockLength) { // are buffers defined? if (!buffer1.m_pBuffer || !buffer2.m_pBuffer) // return true only if both buffers are NULL return (!buffer1.m_pBuffer && !buffer2.m_pBuffer); // are lengths equals? if (buffer1.m_Length != buffer2.m_Length) return false; // calculate memory block count to compare const QR_SizeT count = (buffer1.m_Length / blockLength) + (buffer1.m_Length % blockLength ? 1 : 0); // iterate through memory blocks to compare for (QR_SizeT i = 0; i < count; ++i) switch (type) { case IE_BC_FromStartToEnd: { // calculate next offset const QR_BufferSizeType offset = i * blockLength; // get next block length to compare const QR_SizeT length = std::min(blockLength, buffer1.m_Length - offset); // is memory block identical? #if defined(__CODEGEARC__) || defined(__APPLE__) if (std::memcmp(buffer1.m_pBuffer + offset, buffer2.m_pBuffer + offset, length) != 0) #else if (memcmp(buffer1.m_pBuffer + offset, buffer2.m_pBuffer + offset, length) != 0) #endif // __CODEGEARC__ / __APPLE__ return false; continue; } case IE_BC_FromEndToStart: { // calculate next offset const QR_BufferSizeType offset = ((count - i) - 1) * blockLength; // get next block length to compare const QR_SizeT length = std::min(blockLength, buffer1.m_Length - offset); // is memory block identical? #if defined(__CODEGEARC__) || defined(__APPLE__) if (std::memcmp(buffer1.m_pBuffer + offset, buffer2.m_pBuffer + offset, length) != 0) #else if (memcmp(buffer1.m_pBuffer + offset, buffer2.m_pBuffer + offset, length) != 0) #endif // __CODEGEARC__ / __APPLE__ return false; continue; } case IE_BC_Symmetric: { // calculate next start and end offsets const QR_BufferSizeType startOffset = i * blockLength; const QR_BufferSizeType endOffset = ((count - i) - 1) * blockLength; // middle of the buffer is reached? if (startOffset >= endOffset && buffer1.m_Length > blockLength) return true; // get next start and end block lengths to compare const QR_SizeT startLength = std::min(blockLength, buffer1.m_Length - startOffset); const QR_SizeT endLength = std::min(blockLength, buffer1.m_Length - endOffset); // is start memory block identical? #if defined(__CODEGEARC__) || defined(__APPLE__) if (std::memcmp(buffer1.m_pBuffer + startOffset, buffer2.m_pBuffer + startOffset, startLength) != 0) #else if (memcmp(buffer1.m_pBuffer + startOffset, buffer2.m_pBuffer + startOffset, startLength) != 0) #endif // __CODEGEARC__ / __APPLE__ return false; // is end memory block identical? #if defined(__CODEGEARC__) || defined(__APPLE__) if (std::memcmp(buffer1.m_pBuffer + endOffset, buffer2.m_pBuffer + endOffset, endLength) != 0) #else if (memcmp(buffer1.m_pBuffer + endOffset, buffer2.m_pBuffer + endOffset, endLength) != 0) #endif // __CODEGEARC__ / __APPLE__ return false; continue; } default: M_THROW_EXCEPTION("Unknown comparison type"); } return true; } //---------------------------------------------------------------------------
ipl-adm/xray-oxygen
code/engine.vc2008/xrEngine/Environment_misc.cpp
<reponame>ipl-adm/xray-oxygen<filename>code/engine.vc2008/xrEngine/Environment_misc.cpp #include "stdafx.h" #pragma hdrstop #include "Environment.h" #include "xr_efflensflare.h" #include "thunderbolt.h" #include "rain.h" #include "IGame_Level.h" #include "../xrServerEntities/object_broker.h" #include "../xrServerEntities/LevelGameDef.h" ENGINE_API float ccSunshaftsIntensity = 0.f; void CEnvModifier::load (IReader* fs, u32 version) { use_flags.one (); fs->r_fvector3 (position); radius = fs->r_float (); power = fs->r_float (); far_plane = fs->r_float (); fs->r_fvector3 (fog_color); fog_density = fs->r_float (); fs->r_fvector3 (ambient); fs->r_fvector3 (sky_color); fs->r_fvector3 (hemi_color); if(version>=0x0016) { use_flags.assign(fs->r_u16()); } } float CEnvModifier::sum (CEnvModifier& M, Fvector3& view) { float _dist_sq = view.distance_to_sqr(M.position); if (_dist_sq>=(M.radius*M.radius)) return 0; float _att = 1-_sqrt(_dist_sq)/M.radius; //[0..1]; float _power = M.power*_att; if(M.use_flags.test(eViewDist)) { far_plane += M.far_plane*_power; use_flags.set (eViewDist, TRUE); } if(M.use_flags.test(eFogColor)) { fog_color.mad (M.fog_color,_power); use_flags.set (eFogColor, TRUE); } if(M.use_flags.test(eFogDensity)) { fog_density += M.fog_density*_power; use_flags.set (eFogDensity, TRUE); } if(M.use_flags.test(eAmbientColor)) { ambient.mad (M.ambient,_power); use_flags.set (eAmbientColor, TRUE); } if(M.use_flags.test(eSkyColor)) { sky_color.mad (M.sky_color,_power); use_flags.set (eSkyColor, TRUE); } if(M.use_flags.test(eHemiColor)) { hemi_color.mad (M.hemi_color,_power); use_flags.set (eHemiColor, TRUE); } return _power; } //----------------------------------------------------------------------------- // Environment ambient //----------------------------------------------------------------------------- void CEnvAmbient::SSndChannel::load(CInifile& config, LPCSTR sect) { m_load_section = sect; m_sound_dist.x = config.r_float (m_load_section, "min_distance"); m_sound_dist.y = config.r_float (m_load_section, "max_distance"); m_sound_period.x = config.r_s32 (m_load_section, "period0"); m_sound_period.y = config.r_s32 (m_load_section, "period1"); m_sound_period.z = config.r_s32 (m_load_section, "period2"); m_sound_period.w = config.r_s32 (m_load_section, "period3"); // m_sound_period = config.r_ivector4(sect,"sound_period"); R_ASSERT (m_sound_period.x <= m_sound_period.y && m_sound_period.z <= m_sound_period.w); // m_sound_period.mul (1000);// now in ms // m_sound_dist = config.r_fvector2(sect,"sound_dist"); R_ASSERT2 (m_sound_dist.y > m_sound_dist.x, sect); LPCSTR snds = config.r_string (sect,"sounds"); u32 cnt = _GetItemCount (snds); string_path tmp; R_ASSERT3 (cnt,"sounds empty", sect); m_sounds.resize (cnt); for (u32 k=0; k<cnt; ++k) { _GetItem (snds,k,tmp); m_sounds[k].create (tmp,st_Effect,sg_SourceType); } } CEnvAmbient::SEffect* CEnvAmbient::create_effect (CInifile& config, LPCSTR id) { SEffect* result = xr_new<SEffect>(); result->life_time = iFloor(config.r_float(id,"life_time")*1000.f); result->particles = config.r_string (id,"particles"); VERIFY (result->particles.size()); result->offset = config.r_fvector3 (id,"offset"); result->wind_gust_factor = config.r_float(id,"wind_gust_factor"); if (config.line_exist(id,"sound")) result->sound.create (config.r_string(id,"sound"),st_Effect,sg_SourceType); if (config.line_exist(id,"wind_blast_strength")) { result->wind_blast_strength = config.r_float(id,"wind_blast_strength"); result->wind_blast_direction.setHP (deg2rad(config.r_float(id,"wind_blast_longitude")), 0.f); result->wind_blast_in_time = config.r_float(id,"wind_blast_in_time"); result->wind_blast_out_time = config.r_float(id,"wind_blast_out_time"); return (result); } result->wind_blast_strength = 0.f; result->wind_blast_direction.set (0.f, 0.f, 1.f); result->wind_blast_in_time = 0.f; result->wind_blast_out_time = 0.f; return (result); } CEnvAmbient::SSndChannel* CEnvAmbient::create_sound_channel (CInifile& config, LPCSTR id) { SSndChannel* result = xr_new<SSndChannel>(); result->load (config, id); return (result); } CEnvAmbient::~CEnvAmbient () { destroy (); } void CEnvAmbient::destroy () { delete_data (m_effects); delete_data (m_sound_channels); } void CEnvAmbient::load(CInifile& ambients_config, CInifile& sound_channels_config, CInifile& effects_config, const shared_str& sect) { m_ambients_config_filename = ambients_config.fname(); m_load_section = sect; string_path tmp; // sounds LPCSTR channels = ambients_config.r_string(sect, "sound_channels"); u32 cnt = _GetItemCount(channels); m_sound_channels.resize(cnt); for (u32 i = 0; i < cnt; ++i) { m_sound_channels[i] = create_sound_channel(sound_channels_config, _GetItem(channels, i, tmp)); } // effects m_effect_period.set(iFloor(ambients_config.r_float(sect, "min_effect_period")*1000.f), iFloor(ambients_config.r_float(sect, "max_effect_period")*1000.f)); LPCSTR effs = ambients_config.r_string(sect, "effects"); cnt = _GetItemCount(effs); m_effects.resize(cnt); for (u32 k = 0; k < cnt; ++k) m_effects[k] = create_effect(effects_config, _GetItem(effs, k, tmp)); R_ASSERT(!m_sound_channels.empty() || !m_effects.empty()); } //----------------------------------------------------------------------------- // Environment descriptor //----------------------------------------------------------------------------- CEnvDescriptor::CEnvDescriptor (shared_str const& identifier) : m_identifier (identifier) { exec_time = 0.0f; exec_time_loaded = 0.0f; clouds_color.set (1,1,1,1); sky_color.set (1,1,1); sky_rotation = 0.0f; far_plane = 400.0f;; fog_color.set (1,1,1); fog_density = 0.0f; fog_distance = 400.0f; rain_density = 0.0f; rain_color.set (0,0,0); bolt_period = 0.0f; bolt_duration = 0.0f; wind_velocity = 0.0f; wind_direction = 0.0f; ambient.set (0,0,0); hemi_color.set (1,1,1,1); sun_color.set (1,1,1); sun_dir.set (0,-1,0); m_fSunShaftsIntensity = 1; m_fWaterIntensity = 1; m_fTreeAmplitudeIntensity = 0.01; m_fDropletsIntensity = 0; // Max - 1.5 lens_flare_id = ""; tb_id = ""; env_ambient = NULL; } #define C_CHECK(C) if (C.x<0 || C.x>2 || C.y<0 || C.y>2 || C.z<0 || C.z>2) { Msg("! Invalid '%s' in env-section '%s'",#C,m_identifier.c_str());} void CEnvDescriptor::load (CEnvironment& environment, CInifile& config) { Ivector3 tm ={0,0,0}; sscanf (m_identifier.c_str(),"%d:%d:%d",&tm.x,&tm.y,&tm.z); R_ASSERT3 ((tm.x>=0)&&(tm.x<24)&&(tm.y>=0)&&(tm.y<60)&&(tm.z>=0)&&(tm.z<60),"Incorrect weather time",m_identifier.c_str()); exec_time = tm.x*3600.f+tm.y*60.f+tm.z; exec_time_loaded = exec_time; string_path st,st_env; xr_strcpy (st,config.r_string (m_identifier.c_str(),"sky_texture")); strconcat (sizeof(st_env),st_env,st,"#small" ); sky_texture_name = st; sky_texture_env_name = st_env; clouds_texture_name = config.r_string (m_identifier.c_str(),"clouds_texture"); LPCSTR cldclr = config.r_string (m_identifier.c_str(),"clouds_color"); float multiplier = 0, save=0; sscanf (cldclr,"%f,%f,%f,%f,%f",&clouds_color.x,&clouds_color.y,&clouds_color.z,&clouds_color.w,&multiplier); save=clouds_color.w; clouds_color.mul (.5f*multiplier); clouds_color.w = save; sky_color = config.r_fvector3 (m_identifier.c_str(),"sky_color"); if (config.line_exist(m_identifier.c_str(),"sky_rotation")) sky_rotation = deg2rad(config.r_float(m_identifier.c_str(),"sky_rotation")); else sky_rotation = 0; far_plane = config.r_float (m_identifier.c_str(),"far_plane"); fog_color = config.r_fvector3 (m_identifier.c_str(),"fog_color"); fog_density = config.r_float (m_identifier.c_str(),"fog_density"); fog_distance = config.r_float (m_identifier.c_str(),"fog_distance"); rain_density = config.r_float (m_identifier.c_str(),"rain_density"); clamp(rain_density,0.f,1.f); rain_color = config.r_fvector3 (m_identifier.c_str(),"rain_color"); wind_velocity = config.r_float (m_identifier.c_str(),"wind_velocity"); wind_direction = deg2rad(config.r_float(m_identifier.c_str(),"wind_direction")); ambient = config.r_fvector3 (m_identifier.c_str(),"ambient_color"); hemi_color = config.r_fvector4 (m_identifier.c_str(),"hemisphere_color"); sun_color = config.r_fvector3 (m_identifier.c_str(),"sun_color"); // if (config.line_exist(m_identifier.c_str(),"sun_altitude")) sun_dir.setHP ( deg2rad(config.r_float(m_identifier.c_str(),"sun_altitude")), deg2rad(config.r_float(m_identifier.c_str(),"sun_longitude")) ); R_ASSERT ( _valid(sun_dir) ); // else // sun_dir.setHP ( // deg2rad(config.r_fvector2(m_identifier.c_str(),"sun_dir").y), // deg2rad(config.r_fvector2(m_identifier.c_str(),"sun_dir").x) // ); VERIFY2 (sun_dir.y < 0, "Invalid sun direction settings while loading"); lens_flare_id = environment.eff_LensFlare->AppendDef(environment, environment.m_suns_config, config.r_string(m_identifier,"sun")); tb_id = environment.eff_Thunderbolt->AppendDef(environment, environment.m_thunderbolt_collections_config, environment.m_thunderbolts_config, config.r_string(m_identifier,"thunderbolt_collection")); bolt_period = (tb_id.size())?config.r_float (m_identifier,"thunderbolt_period"):0.f; bolt_duration = (tb_id.size())?config.r_float (m_identifier,"thunderbolt_duration"):0.f; env_ambient = config.line_exist(m_identifier,"ambient")?environment.AppendEnvAmb (config.r_string(m_identifier,"ambient")):0; if (config.line_exist(m_identifier.c_str(), "sun_shafts_intensity")) m_fSunShaftsIntensity = config.r_float(m_identifier.c_str(), "sun_shafts_intensity"); if (config.line_exist(m_identifier,"water_intensity")) m_fWaterIntensity = config.r_float(m_identifier,"water_intensity"); if (config.line_exist(m_identifier, "tree_amplitude_intensity")) m_fTreeAmplitudeIntensity = config.r_float(m_identifier, "tree_amplitude_intensity"); if (config.line_exist(m_identifier, "droplets_intensity")) m_fDropletsIntensity = config.r_float(m_identifier, "droplets_intensity"); C_CHECK (clouds_color); C_CHECK (sky_color ); C_CHECK (fog_color ); C_CHECK (rain_color ); C_CHECK (ambient ); C_CHECK (hemi_color ); C_CHECK (sun_color ); on_device_create (); } void CEnvDescriptor::on_device_create () { m_pDescriptor->OnDeviceCreate(*this); } void CEnvDescriptor::on_device_destroy () { m_pDescriptor->OnDeviceDestroy(); } //----------------------------------------------------------------------------- // Environment Mixer //----------------------------------------------------------------------------- CEnvDescriptorMixer::CEnvDescriptorMixer(shared_str const& identifier) : CEnvDescriptor (identifier) { } void CEnvDescriptorMixer::destroy() { m_pDescriptorMixer->Destroy(); // Reuse existing code on_device_destroy(); } void CEnvDescriptorMixer::clear () { m_pDescriptorMixer->Clear(); } int get_ref_count(IUnknown* ii); void CEnvDescriptorMixer::lerp (CEnvironment* , CEnvDescriptor& A, CEnvDescriptor& B, float f, CEnvModifier& Mdf, float modifier_power) { float modif_power = 1.f/(modifier_power+1); // the environment itself float fi = 1-f; m_pDescriptorMixer->lerp(&*A.m_pDescriptor, &*B.m_pDescriptor); weight = f; clouds_color.lerp (A.clouds_color,B.clouds_color,f); sky_rotation = (fi*A.sky_rotation + f*B.sky_rotation); if(Mdf.use_flags.test(eViewDist)) far_plane = (fi*A.far_plane + f*B.far_plane + Mdf.far_plane)*psVisDistance*modif_power; else far_plane = (fi*A.far_plane + f*B.far_plane)*psVisDistance; fog_color.lerp (A.fog_color,B.fog_color,f); if(Mdf.use_flags.test(eFogColor)) fog_color.add(Mdf.fog_color).mul(modif_power); fog_density = (fi*A.fog_density + f*B.fog_density); if(Mdf.use_flags.test(eFogDensity)) { fog_density += Mdf.fog_density; fog_density *= modif_power; } fog_distance = (fi*A.fog_distance + f*B.fog_distance); fog_near = (1.0f - fog_density)*0.85f * fog_distance; fog_far = 0.99f * fog_distance; rain_density = fi*A.rain_density + f*B.rain_density; rain_color.lerp (A.rain_color,B.rain_color,f); bolt_period = fi*A.bolt_period + f*B.bolt_period; bolt_duration = fi*A.bolt_duration + f*B.bolt_duration; // wind wind_velocity = fi*A.wind_velocity + f*B.wind_velocity; wind_direction = fi*A.wind_direction + f*B.wind_direction; if (ccSunshaftsIntensity > 0.f) m_fSunShaftsIntensity = ccSunshaftsIntensity; else m_fSunShaftsIntensity = fi*A.m_fSunShaftsIntensity + f*B.m_fSunShaftsIntensity; m_fWaterIntensity = fi*A.m_fWaterIntensity + f*B.m_fWaterIntensity; m_fTreeAmplitudeIntensity = fi*A.m_fTreeAmplitudeIntensity + f*B.m_fTreeAmplitudeIntensity; m_fDropletsIntensity = fi*A.m_fDropletsIntensity + f*B.m_fDropletsIntensity; // colors //. sky_color.lerp (A.sky_color,B.sky_color,f).add(Mdf.sky_color).mul(modif_power); sky_color.lerp (A.sky_color,B.sky_color,f); if(Mdf.use_flags.test(eSkyColor)) sky_color.add(Mdf.sky_color).mul(modif_power); //. ambient.lerp (A.ambient,B.ambient,f).add(Mdf.ambient).mul(modif_power); ambient.lerp (A.ambient,B.ambient,f); if(Mdf.use_flags.test(eAmbientColor)) ambient.add(Mdf.ambient).mul(modif_power); hemi_color.lerp (A.hemi_color,B.hemi_color,f); if(Mdf.use_flags.test(eHemiColor)) { hemi_color.x += Mdf.hemi_color.x; hemi_color.y += Mdf.hemi_color.y; hemi_color.z += Mdf.hemi_color.z; hemi_color.x *= modif_power; hemi_color.y *= modif_power; hemi_color.z *= modif_power; } sun_color.lerp (A.sun_color,B.sun_color,f); R_ASSERT ( _valid(A.sun_dir) ); R_ASSERT ( _valid(B.sun_dir) ); sun_dir.lerp (A.sun_dir,B.sun_dir,f).normalize(); R_ASSERT ( _valid(sun_dir) ); VERIFY2 (sun_dir.y<0,"Invalid sun direction settings while lerp");} //----------------------------------------------------------------------------- // Environment IO //----------------------------------------------------------------------------- CEnvAmbient* CEnvironment::AppendEnvAmb (const shared_str& sect) { for (auto it=Ambients.begin(); it!=Ambients.end(); it++) if ((*it)->name().equal(sect)) return (*it); Ambients.push_back (xr_new<CEnvAmbient>()); Ambients.back()->load ( *m_ambients_config, *m_sound_channels_config, *m_effects_config, sect ); return (Ambients.back()); } void CEnvironment::mods_load() { Modifiers.clear(); string_path path; if (FS.exist(path, "$level$", "level.env_mod")) { IReader* fs = FS.r_open(path); u32 id = 0; u32 ver = 0x0015; u32 sz; while (0 != (sz = fs->find_chunk(id))) { if (id == 0 && sz == sizeof(u32)) { ver = fs->r_u32(); } else { CEnvModifier E; E.load(fs, ver); Modifiers.push_back(E); } id++; } FS.r_close(fs); } load_level_specific_ambients(); } void CEnvironment::mods_unload () { Modifiers.clear (); } void CEnvironment::load_level_specific_ambients () { const shared_str level_name = g_pGameLevel->name(); string_path path; strconcat(sizeof(path), path, "environment\\ambients\\", level_name.c_str(), ".ltx"); string_path full_path; CInifile* level_ambients = xr_new<CInifile>( FS.update_path(full_path, "$game_config$", path), TRUE, TRUE, FALSE); for ( auto I=Ambients.begin(), E=Ambients.end(); I!=E; ++I ) { CEnvAmbient* ambient = *I; shared_str section_name = ambient->name(); // choose a source ini file CInifile* source = (level_ambients && level_ambients->section_exist(section_name)) ? level_ambients : m_ambients_config; // check and reload if needed if ( xr_strcmp( ambient->get_ambients_config_filename().c_str(), source->fname() ) ) { ambient->destroy(); ambient->load(*source, *m_sound_channels_config, *m_effects_config, section_name); } } xr_delete(level_ambients); } CEnvDescriptor* CEnvironment::create_descriptor (shared_str const& identifier, CInifile* config) { CEnvDescriptor* result = xr_new<CEnvDescriptor>(identifier); if (config) result->load(*this, *config); return (result); } void CEnvironment::load_weathers () { if (!WeatherCycles.empty()) return; typedef xr_vector<LPSTR> file_list_type; file_list_type* file_list = FS.file_list_open("$game_weathers$",""); VERIFY (file_list); file_list_type::const_iterator i = file_list->begin(); file_list_type::const_iterator e = file_list->end(); for ( ; i != e; ++i) { u32 length = xr_strlen(*i); VERIFY (length >= 4); VERIFY ((*i)[length - 4] == '.'); VERIFY ((*i)[length - 3] == 'l'); VERIFY ((*i)[length - 2] == 't'); VERIFY ((*i)[length - 1] == 'x'); u32 new_length = length - 4; LPSTR identifier = (LPSTR)_alloca((new_length + 1)*sizeof(char)); std::memcpy(identifier, *i, new_length*sizeof(char)); identifier[new_length] = 0; EnvVec& env = WeatherCycles[identifier]; string_path file_name; FS.update_path (file_name, "$game_weathers$", identifier); xr_strcat (file_name, ".ltx"); CInifile* config = CInifile::Create(file_name); typedef CInifile::Root sections_type; sections_type& sections = config->sections(); env.reserve (sections.size()); for (CInifile::Sect* it: sections) { CEnvDescriptor* object = create_descriptor(it->Name, config); env.push_back (object); } CInifile::Destroy (config); } FS.file_list_close (file_list); // sorting weather envs for (auto _I: WeatherCycles) { R_ASSERT3(_I.second.size()>1,"Environment in weather must >=2",_I.first.data()); std::sort(_I.second.begin(),_I.second.end(),sort_env_etl_pred); } R_ASSERT2 (!WeatherCycles.empty(),"Empty weathers."); SetWeather ((*WeatherCycles.begin()).first); } void CEnvironment::load_weather_effects () { if (!WeatherFXs.empty()) return; typedef xr_vector<LPSTR> file_list_type; file_list_type* pfile_list = FS.file_list_open("$game_weather_effects$", ""); VERIFY (pfile_list); file_list_type& file_list = *pfile_list; for (char* weatherEffectFileName : file_list) { u32 length = xr_strlen(weatherEffectFileName); VERIFY (length >= 4); VERIFY ((weatherEffectFileName)[length - 4] == '.'); VERIFY ((weatherEffectFileName)[length - 3] == 'l'); VERIFY ((weatherEffectFileName)[length - 2] == 't'); VERIFY ((weatherEffectFileName)[length - 1] == 'x'); u32 new_length = length - 4; LPSTR identifier = (LPSTR)_alloca((new_length + 1)*sizeof(char)); std::memcpy(identifier, weatherEffectFileName, new_length*sizeof(char)); identifier[new_length] = 0; EnvVec& env = WeatherFXs[identifier]; string_path file_name; FS.update_path (file_name, "$game_weather_effects$", identifier); xr_strcat (file_name, ".ltx"); CInifile* config = CInifile::Create(file_name); typedef CInifile::Root sections_type; sections_type& sections = config->sections(); env.reserve (sections.size() + 2); env.push_back (create_descriptor("00:00:00", false)); for (CInifile::Sect* section : sections) { CEnvDescriptor* object = create_descriptor(section->Name, config); env.push_back (object); } CInifile::Destroy (config); env.push_back (create_descriptor("24:00:00", false)); env.back()->exec_time_loaded = DAY_LENGTH; } FS.file_list_close (pfile_list); // sorting weather envs auto _I=WeatherFXs.begin(); auto _E=WeatherFXs.end(); for (; _I!=_E; _I++){ R_ASSERT3 (_I->second.size()>1,"Environment in weather must >=2",*_I->first); std::sort (_I->second.begin(),_I->second.end(),sort_env_etl_pred); } } void CEnvironment::load () { if (!CurrentEnv) create_mixer (); m_pRender->OnLoad(); //tonemap = Device.Resources->_CreateTexture("$user$tonemap"); //. hack if (!eff_Rain) eff_Rain = xr_new<CEffect_Rain>(); if (!eff_LensFlare) eff_LensFlare = xr_new<CLensFlare>(); if (!eff_Thunderbolt) eff_Thunderbolt = xr_new<CEffect_Thunderbolt>(); load_weathers (); load_weather_effects (); } void CEnvironment::unload () { // clear weathers auto _I = WeatherCycles.begin(); auto _E = WeatherCycles.end(); for (; _I!=_E; _I++){ for (auto it=_I->second.begin(); it!=_I->second.end(); it++) xr_delete (*it); } WeatherCycles.clear (); // clear weather effect _I = WeatherFXs.begin(); _E = WeatherFXs.end(); for (; _I!=_E; _I++){ for (auto it=_I->second.begin(); it!=_I->second.end(); it++) xr_delete (*it); } WeatherFXs.clear (); // clear ambient for (auto it=Ambients.begin(); it!=Ambients.end(); it++) xr_delete (*it); Ambients.clear (); // misc xr_delete (eff_Rain); xr_delete (eff_LensFlare); xr_delete (eff_Thunderbolt); CurrentWeather = 0; CurrentWeatherName = 0; CurrentEnv->clear (); Invalidate (); m_pRender->OnUnload (); // tonemap = 0; }
migijs/m
tests/objkeep/test.js
<filename>tests/objkeep/test.js var path = require('path'); var fs = require('fs'); module.exports = { 'init': function(browser) { browser .url('file://' + path.join(__dirname, 'index.html')) .waitForElementVisible('body', 1000) .assert.containsText('#test [ref="1"]', '51') .assert.containsText('#test [ref="2"]', '15') }, 'click': function(browser) { browser .click('#test p[ref="c1"]') .assert.containsText('#test [ref="1"]', '512') .assert.containsText('#test [ref="2"]', '125') .click('#test p[ref="c2"]') .assert.containsText('#test [ref="1"]', '12') .assert.containsText('#test [ref="2"]', '12') .end(); } };
akhr0m/go
chapter-85-understanding-net-http-serverMux/01.routing.go
<filename>chapter-85-understanding-net-http-serverMux/01.routing.go package main import ( "io" "net/http" ) type hotdog int func (m hotdog) ServeHTTP(w http.ResponseWriter, req *http.Request) { switch req.URL.Path { case "/dog": io.WriteString(w, "doggy doggy doggy") case "/cat": io.WriteString(w, "kitty kitty kitty") default: io.WriteString(w, "hello world") } } func main() { var d hotdog http.ListenAndServe(":8080", d) }
gdeignacio/fbit-digitalgov-libs
utils/src/main/java/org/fundaciobit/administraciodigital/utils/data/DataAdapter.java
<reponame>gdeignacio/fbit-digitalgov-libs /* * Copyright 2016 gdeignacio. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fundaciobit.administraciodigital.utils.data; import java.util.*; /** * Implementa una clase Data. * Se utiliza cuando queremos crear una Data pero no queremos implementar todos * los métodos de Data. En ese caso extenderemos de la clase DataAdapter. * * @author ELU * @author gdeignacio * @version 1.0.1 * @created 16-02-2017 */ public class DataAdapter implements Data { /** * Constructor por defecto. */ public DataAdapter() { } /** * Función que devuelve el valor de cada uno de los atributos de la clase Data. * @return Devuelve el resultado por defecto */ public String toString() { return this.toString(); } /** * Función que devuelve el código de la clase data en formato string para las * listas de valores. * @return En este caso devuelve un String vacío. */ public String getCodigoLOV() { return ""; } /** * Función que devuelve la descripción que deseamos que aparezca en las * listas de valores. * @return En este caso devuelve un String vacío. */ public String getValorLOV() { return ""; } /** * Se añade para que DWR no provoque fallos * @param codigo */ public void setCodigoLOV(String codigo) { } /** * Idem que setCodigoLOV. * @param valor */ public void setValorLOV(String valor) { } }
michaelthomasj/trusted-firmware-m
platform/ext/target/cypress/psoc64/Native_Driver/include/cy_syslib.h
<reponame>michaelthomasj/trusted-firmware-m /***************************************************************************//** * \file cy_syslib.h * \version 2.40.1 * * Provides an API declaration of the SysLib driver. * ******************************************************************************** * \copyright * Copyright 2016-2019 Cypress Semiconductor Corporation * SPDX-License-Identifier: Apache-2.0 * * 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. *******************************************************************************/ /** * \addtogroup group_syslib * \{ * The system libraries provide APIs that can be called in the user application * to handle the timing, logical checking or register. * * The functions and other declarations used in this driver are in cy_syslib.h. * You can include cy_pdl.h (ModusToolbox only) to get access to all functions * and declarations in the PDL. * * The SysLib driver contains a set of different system functions. These functions * can be called in the application routine. Major features of the system library: * * Delay functions * * The register Read/Write macro * * Assert and Halt * * Assert Classes and Levels * * A software reset * * Reading the reset cause * * An API to invalidate the flash cache and buffer * * Data manipulation macro * * A variable type definition from MISRA-C which specifies signedness * * Cross compiler compatible attributes * * Getting a silicon-unique ID API * * Setting wait states API * * Resetting the backup domain API * * APIs to serve Fault handler * * \section group_syslib_configuration Configuration Considerations * <b> Assertion Usage </b> <br /> * Use the CY_ASSERT() macro to check expressions that must be true as long as the * program is running correctly. It is a convenient way to insert sanity checks. * The CY_ASSERT() macro is defined in the cy_syslib.h file which is part of * the PDL library. The behavior of the macro is as follows: if the expression * passed to the macro is false, output an error message that includes the file * name and line number, and then halts the CPU. \n * In case of fault, the CY_ASSERT() macro calls the Cy_SysLib_AssertFailed() function. * This is a weakly linked function. The default implementation stores the file * name and line number of the ASSERT into global variables, cy_assertFileName * and cy_assertLine . It then calls the Cy_SysLib_Halt() function. * \note Firmware can redefine the Cy_SysLib_AssertFailed() function for custom processing. * * The PDL source code uses this assert mechanism extensively. It is recommended * that you enable asserts when debugging firmware. \n * <b> Assertion Classes and Levels </b> <br /> * The PDL defines three assert classes, which correspond to different kinds * of parameters. There is a corresponding assert "level" for each class. * <table class="doxtable"> * <tr><th>Class Macro</th><th>Level Macro</th><th>Type of check</th></tr> * <tr> * <td>CY_ASSERT_CLASS_1</td> * <td>CY_ASSERT_L1</td> * <td>A parameter that could change between different PSoC devices * (e.g. the number of clock paths)</td> * </tr> * <tr> * <td>CY_ASSERT_CLASS_2</td> * <td>CY_ASSERT_L2</td> * <td>A parameter that has fixed limits such as a counter period</td> * </tr> * <tr> * <td>CY_ASSERT_CLASS_3</td> * <td>CY_ASSERT_L3</td> * <td>A parameter that is an enum constant</td> * </tr> * </table> * Firmware defines which ASSERT class is enabled by defining CY_ASSERT_LEVEL. * This is a compiler command line argument, similar to how the DEBUG / NDEBUG * macro is passed. \n * Enabling any class also enables any lower-numbered class. * CY_ASSERT_CLASS_3 is the default level, and it enables asserts for all three * classes. The following example shows the command-line option to enable all * the assert levels: * \code -D CY_ASSERT_LEVEL=CY_ASSERT_CLASS_3 \endcode * \note The use of special characters, such as spaces, parenthesis, etc. must * be protected with quotes. * * After CY_ASSERT_LEVEL is defined, firmware can use * one of the three level macros to make an assertion. For example, if the * parameter can vary between devices, firmware uses the L1 macro. * \code CY_ASSERT_L1(clkPath < SRSS_NUM_CLKPATH); \endcode * If the parameter has bounds, firmware uses L2. * \code CY_ASSERT_L2(trim <= CY_CTB_TRIM_VALUE_MAX); \endcode * If the parameter is an enum, firmware uses L3. * \code CY_ASSERT_L3(config->LossAction <= CY_SYSCLK_CSV_ERROR_FAULT_RESET); \endcode * Each check uses the appropriate level macro for the kind of parameter being checked. * If a particular assert class/level is not enabled, then the assert does nothing. * * \section group_syslib_more_information More Information * Refer to the technical reference manual (TRM). * * \section group_syslib_MISRA MISRA-C Compliance * <table class="doxtable"> * <tr> * <th>MISRA Rule</th> * <th>Rule Class (Required/Advisory)</th> * <th>Rule Description</th> * <th>Description of Deviation(s)</th> * </tr> * <tr> * <td>1.2</td> * <td>R</td> * <td>No reliance shall be placed on undefined or unspecified behaviour.</td> * <td>This specific behavior is explicitly covered in rule 20.1.</td> * </tr> * <tr> * <td>2.1</td> * <td>R</td> * <td>This function contains a mixture of in-line assembler statements and C statements.</td> * <td>This si required by design of the Cy_SysLib_Halt function.</td> * </tr> * <tr> * <td>18.4</td> * <td>R</td> * <td>Unions shall not be used.</td> * <td>The unions are used for CFSR, HFSR and SHCSR Fault Status Registers * content access as a word in code and as a structure during debug.</td> * </tr> * <tr> * <td>19.13</td> * <td>A</td> * <td>The # and ## operators should not be used.</td> * <td>The ## preprocessor operator is used in macros to form the field mask.</td> * </tr> * <tr> * <td>20.1</td> * <td>R</td> * <td>Reserved identifiers, macros and functions in the standard library, shall not be * defined, redefined or undefined.</td> * <td>The driver defines the macros with leading underscores * (_CLR_SET_FLD/_BOOL2FLD/_FLD2BOOL) and therefore generates this MISRA violation.</td> * </tr> * </table> * * \section group_syslib_changelog Changelog * <table class="doxtable"> * <tr><th>Version</th><th>Changes</th><th>Reason for Change</th></tr> * <tr> * <td>2.40.1</td> * <td>Correct the CY_RAMFUNC_BEGIN macro for the IAR compiler.</td> * <td>Removed the IAR compiler warning.</td> * </tr> * <tr> * <td>2.40</td> * <td>Added new macros CY_SYSLIB_DIV_ROUND and CY_SYSLIB_DIV_ROUNDUP to easy perform integer division with rounding.</td> * <td>Improve PDL code base.</td> * </tr> * <tr> * <td rowspan="3">2.30</td> * <td>Updated implementation of the Cy_SysLib_AsmInfiniteLoop() function to be compatible with ARMC6.</td> * <td>Provided support for the ARM Compiler 6.</td> * </tr> * <tr> * <td>Minor documentation edits.</td> * <td>Documentation update and clarification.</td> * </tr> * <tr> * <td>Added new macros CY_RAMFUNC_BEGIN and CY_RAMFUNC_END for convenient placement function in RAM for all supported compilers.</td> * <td>Improve user experience.</td> * </tr> * <tr> * <td rowspan="2">2.20</td> * <td>Updated implementation of the \ref Cy_SysLib_AssertFailed() function to be available in Release and Debug modes.</td> * <td>Provided support for the PDL static library in Release mode.</td> * </tr> * <tr> * <td>Minor documentation edits.</td> * <td>Documentation update and clarification.</td> * </tr> * <tr> * <td rowspan="4">2.10</td> * <td>Flattened the organization of the driver source code into the single source directory and the single include directory.</td> * <td>Driver library directory-structure simplification.</td> * </tr> * <tr> * <td>Added the following macros: \ref CY_REG32_CLR_SET, \ref _CLR_SET_FLD16U, \ref CY_REG16_CLR_SET, \ref _CLR_SET_FLD8U, \ref CY_REG8_CLR_SET</td> * <td>Register access simplification.</td> * </tr> * <tr> * <td>Removed the Cy_SysLib_GetNumHfclkResetCause API function.</td> * <td>This feature is not supported by SRSS_ver1.</td> * </tr> * <tr> * <td>Added register access layer. Use register access macros instead * of direct register access using dereferenced pointers.</td> * <td>Makes register access device-independent, so that the PDL does * not need to be recompiled for each supported part number.</td> * </tr> * <tr> * <td>2.0.1</td> * <td>Minor documentation edits</td> * <td>Documentation update and clarification</td> * </tr> * <tr> * <td rowspan="4"> 2.0</td> * <td> * Added Cy_SysLib_ResetBackupDomain() API implementation. \n * Added CY_NOINLINE attribute implementation. \n * Added DIE_YEAR field to 64-bit unique ID return value of Cy_SysLib_GetUniqueId() API. \n * Added storing of SCB->HFSR, SCB->SHCSR registers and SCB->MMFAR, SCB->BFAR addresses to Fault Handler debug structure. \n * Optimized Cy_SysLib_SetWaitStates() API implementation. * </td> * <td>Improvements made based on usability feedback.</td> * </tr> * <tr> * <td>Added Assertion Classes and Levels.</td> * <td>For error checking, parameter validation and status returns in the PDL API.</td> * </tr> * <tr> * <td>Applied CY_NOINIT attribute to cy_assertFileName, cy_assertLine, and cy_faultFrame global variables.</td> * <td>To store debug information into a non-zero init area for future analysis.</td> * </tr> * <tr> * <td>Removed CY_WEAK attribute implementation.</td> * <td>CMSIS __WEAK attribute should be used instead.</td> * </tr> * <tr> * <td>1.0</td> * <td>Initial version</td> * <td></td> * </tr> * </table> * * \defgroup group_syslib_macros Macros * \defgroup group_syslib_functions Functions * \defgroup group_syslib_data_structures Data Structures * \defgroup group_syslib_enumerated_types Enumerated Types * */ #if !defined(CY_SYSLIB_H) #define CY_SYSLIB_H #include <stdint.h> #include <stdbool.h> #include "cy_device.h" #include "cy_device_headers.h" #if defined(__cplusplus) extern "C" { #endif /* defined(__cplusplus) */ #if defined( __ICCARM__ ) /* Suppress the warning for multiple volatile variables in an expression. */ /* This is common for driver's code and the usage is not order-dependent. */ #pragma diag_suppress=Pa082 #endif /* defined( __ICCARM__ ) */ /** * \addtogroup group_syslib_macros * \{ */ /****************************************************************************** * Macros *****************************************************************************/ #define CY_CPU_CORTEX_M0P (__CORTEX_M == 0) /**< CM0+ core CPU Code */ #define CY_CPU_CORTEX_M4 (__CORTEX_M == 4) /**< CM4 core CPU Code */ /** The macro to disable the Fault Handler */ #define CY_ARM_FAULT_DEBUG_DISABLED (0U) /** The macro to enable the Fault Handler */ #define CY_ARM_FAULT_DEBUG_ENABLED (1U) #if !defined(CY_ARM_FAULT_DEBUG) /** The macro defines if the Fault Handler is enabled. Enabled by default. */ #define CY_ARM_FAULT_DEBUG (CY_ARM_FAULT_DEBUG_ENABLED) #endif /* CY_ARM_FAULT_DEBUG */ /** * \defgroup group_syslib_macros_status_codes Status codes * \{ * Function status type codes */ #define CY_PDL_STATUS_CODE_Pos (0U) /**< The module status code position in the status code */ #define CY_PDL_STATUS_TYPE_Pos (16U) /**< The status type position in the status code */ #define CY_PDL_MODULE_ID_Pos (18U) /**< The software module ID position in the status code */ #define CY_PDL_STATUS_INFO (0UL << CY_PDL_STATUS_TYPE_Pos) /**< The information status type */ #define CY_PDL_STATUS_WARNING (1UL << CY_PDL_STATUS_TYPE_Pos) /**< The warning status type */ #define CY_PDL_STATUS_ERROR (2UL << CY_PDL_STATUS_TYPE_Pos) /**< The error status type */ #define CY_PDL_MODULE_ID_Msk (0x3FFFU) /**< The software module ID mask */ /** Get the software PDL module ID */ #define CY_PDL_DRV_ID(id) ((uint32_t)((uint32_t)((id) & CY_PDL_MODULE_ID_Msk) << CY_PDL_MODULE_ID_Pos)) #define CY_SYSLIB_ID CY_PDL_DRV_ID(0x11U) /**< SYSLIB PDL ID */ /** \} group_syslib_macros_status_codes */ /** \} group_syslib_macros */ /** * \addtogroup group_syslib_enumerated_types * \{ */ /** The SysLib status code structure. */ typedef enum { CY_SYSLIB_SUCCESS = 0x00UL, /**< The success status code */ CY_SYSLIB_BAD_PARAM = CY_SYSLIB_ID | CY_PDL_STATUS_ERROR | 0x01UL, /**< The bad parameter status code */ CY_SYSLIB_TIMEOUT = CY_SYSLIB_ID | CY_PDL_STATUS_ERROR | 0x02UL, /**< The time out status code */ CY_SYSLIB_INVALID_STATE = CY_SYSLIB_ID | CY_PDL_STATUS_ERROR | 0x03UL, /**< The invalid state status code */ CY_SYSLIB_UNKNOWN = CY_SYSLIB_ID | CY_PDL_STATUS_ERROR | 0xFFUL /**< Unknown status code */ } cy_en_syslib_status_t; /** \} group_syslib_enumerated_types */ /** * \addtogroup group_syslib_data_structures * \{ */ #if (CY_ARM_FAULT_DEBUG == CY_ARM_FAULT_DEBUG_ENABLED) #if (CY_CPU_CORTEX_M4) /** Configurable Fault Status Register - CFSR */ typedef struct { /** MemManage Fault Status Sub-register - MMFSR */ uint32_t iaccViol : 1; /**< MemManage Fault - The instruction access violation flag */ uint32_t daccViol : 1; /**< MemManage Fault - The data access violation flag */ uint32_t reserved1 : 1; /**< Reserved */ uint32_t mUnstkErr : 1; /**< MemManage Fault - Unstacking for a return from exception */ uint32_t mStkErr : 1; /**< MemManage Fault - MemManage fault on stacking for exception entry */ uint32_t mlspErr : 1; /**< MemManage Fault - MemManage fault occurred during floating-point lazy state preservation */ uint32_t reserved2 : 1; /**< Reserved */ uint32_t mmarValid : 1; /**< MemManage Fault - The MemManage Address register valid flag */ /** Bus Fault Status Sub-register - UFSR */ uint32_t iBusErr : 1; /**< Bus Fault - The instruction bus error */ uint32_t precisErr : 1; /**< Bus Fault - The precise Data bus error */ uint32_t imprecisErr : 1; /**< Bus Fault - The imprecise data bus error */ uint32_t unstkErr : 1; /**< Bus Fault - Unstacking for an exception return has caused one or more bus faults */ uint32_t stkErr : 1; /**< Bus Fault - Stacking for an exception entry has caused one or more bus faults */ uint32_t lspErr : 1; /**< Bus Fault - A bus fault occurred during the floating-point lazy state */ uint32_t reserved3 : 1; /**< Reserved */ uint32_t bfarValid : 1; /**< Bus Fault - The bus fault address register valid flag */ /** Usage Fault Status Sub-register - UFSR */ uint32_t undefInstr : 1; /**< Usage Fault - An undefined instruction */ uint32_t invState : 1; /**< Usage Fault - The invalid state */ uint32_t invPC : 1; /**< Usage Fault - An invalid PC */ uint32_t noCP : 1; /**< Usage Fault - No coprocessor */ uint32_t reserved4 : 4; /**< Reserved */ uint32_t unaligned : 1; /**< Usage Fault - Unaligned access */ uint32_t divByZero : 1; /**< Usage Fault - Divide by zero */ uint32_t reserved5 : 6; /**< Reserved */ } cy_stc_fault_cfsr_t; /** Hard Fault Status Register - HFSR */ typedef struct { uint32_t reserved1 : 1; /**< Reserved. */ uint32_t vectTbl : 1; /**< HFSR - Indicates a bus fault on a vector table read during exception processing */ uint32_t reserved2 : 28; /**< Reserved. */ uint32_t forced : 1; /**< HFSR - Indicates a forced hard fault */ uint32_t debugEvt : 1; /**< HFSR - Reserved for the debug use. */ } cy_stc_fault_hfsr_t; /** System Handler Control and State Register - SHCSR */ typedef struct { uint32_t memFaultAct : 1; /**< SHCSR - The MemManage exception active bit, reads as 1 if the exception is active */ uint32_t busFaultAct : 1; /**< SHCSR - The BusFault exception active bit, reads as 1 if the exception is active */ uint32_t reserved1 : 1; /**< Reserved. */ uint32_t usgFaultAct : 1; /**< SHCSR - The UsageFault exception active bit, reads as 1 if the exception is active */ uint32_t reserved2 : 3; /**< Reserved. */ uint32_t svCallAct : 1; /**< SHCSR - The SVCall active bit, reads as 1 if the SVC call is active */ uint32_t monitorAct : 1; /**< SHCSR - The debug monitor active bit, reads as 1 if the debug monitor is active */ uint32_t reserved3 : 1; /**< Reserved. */ uint32_t pendSVAct : 1; /**< SHCSR - The PendSV exception active bit, reads as 1 if the exception is active */ uint32_t sysTickAct : 1; /**< SHCSR - The SysTick exception active bit, reads as 1 if the exception is active */ uint32_t usgFaultPended : 1; /**< SHCSR - The UsageFault exception pending bit, reads as 1 if the exception is pending */ uint32_t memFaultPended : 1; /**< SHCSR - The MemManage exception pending bit, reads as 1 if the exception is pending */ uint32_t busFaultPended : 1; /**< SHCSR - The BusFault exception pending bit, reads as 1 if the exception is pending */ uint32_t svCallPended : 1; /**< SHCSR - The SVCall pending bit, reads as 1 if the exception is pending */ uint32_t memFaultEna : 1; /**< SHCSR - The MemManage enable bit, set to 1 to enable */ uint32_t busFaultEna : 1; /**< SHCSR - The BusFault enable bit, set to 1 to enable */ uint32_t usgFaultEna : 1; /**< SHCSR - The UsageFault enable bit, set to 1 to enable */ uint32_t reserved4 : 13; /**< Reserved */ } cy_stc_fault_shcsr_t; #endif /* CY_CPU_CORTEX_M4 */ /** The fault configuration structure. */ typedef struct { uint32_t r0; /**< R0 register content */ uint32_t r1; /**< R1 register content */ uint32_t r2; /**< R2 register content */ uint32_t r3; /**< R3 register content */ uint32_t r12; /**< R12 register content */ uint32_t lr; /**< LR register content */ uint32_t pc; /**< PC register content */ uint32_t psr; /**< PSR register content */ #if (CY_CPU_CORTEX_M4) union { uint32_t cfsrReg; /**< CFSR register content as a word */ cy_stc_fault_cfsr_t cfsrBits; /**< CFSR register content as a structure */ } cfsr; union { uint32_t hfsrReg; /**< HFSR register content as a word */ cy_stc_fault_hfsr_t hfsrBits; /**< HFSR register content as a structure */ } hfsr; union { uint32_t shcsrReg; /**< SHCSR register content as a word */ cy_stc_fault_shcsr_t shcsrBits; /**< SHCSR register content as a structure */ } shcsr; uint32_t mmfar; /**< MMFAR register content */ uint32_t bfar; /**< BFAR register content */ #if ((defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)) && \ (defined (__FPU_USED ) && (__FPU_USED == 1U))) uint32_t s0; /**< FPU S0 register content */ uint32_t s1; /**< FPU S1 register content */ uint32_t s2; /**< FPU S2 register content */ uint32_t s3; /**< FPU S3 register content */ uint32_t s4; /**< FPU S4 register content */ uint32_t s5; /**< FPU S5 register content */ uint32_t s6; /**< FPU S6 register content */ uint32_t s7; /**< FPU S7 register content */ uint32_t s8; /**< FPU S8 register content */ uint32_t s9; /**< FPU S9 register content */ uint32_t s10; /**< FPU S10 register content */ uint32_t s11; /**< FPU S11 register content */ uint32_t s12; /**< FPU S12 register content */ uint32_t s13; /**< FPU S13 register content */ uint32_t s14; /**< FPU S14 register content */ uint32_t s15; /**< FPU S15 register content */ uint32_t fpscr; /**< FPU FPSCR register content */ #endif /* __FPU_PRESENT */ #endif /* CY_CPU_CORTEX_M4 */ } cy_stc_fault_frame_t; #endif /* (CY_ARM_FAULT_DEBUG == CY_ARM_FAULT_DEBUG_ENABLED) */ /** \} group_syslib_data_structures */ /** * \addtogroup group_syslib_macros * \{ */ /** The driver major version */ #define CY_SYSLIB_DRV_VERSION_MAJOR 2 /** The driver minor version */ #define CY_SYSLIB_DRV_VERSION_MINOR 40 /******************************************************************************* * Data manipulation defines *******************************************************************************/ /** Get the lower 8 bits of a 16-bit value. */ #define CY_LO8(x) ((uint8_t) ((x) & 0xFFU)) /** Get the upper 8 bits of a 16-bit value. */ #define CY_HI8(x) ((uint8_t) ((uint16_t)(x) >> 8U)) /** Get the lower 16 bits of a 32-bit value. */ #define CY_LO16(x) ((uint16_t) ((x) & 0xFFFFU)) /** Get the upper 16 bits of a 32-bit value. */ #define CY_HI16(x) ((uint16_t) ((uint32_t)(x) >> 16U)) /** Swap the byte ordering of a 16-bit value */ #define CY_SWAP_ENDIAN16(x) ((uint16_t)(((x) << 8U) | (((x) >> 8U) & 0x00FFU))) /** Swap the byte ordering of a 32-bit value */ #define CY_SWAP_ENDIAN32(x) ((uint32_t)((((x) >> 24U) & 0x000000FFU) | (((x) & 0x00FF0000U) >> 8U) | \ (((x) & 0x0000FF00U) << 8U) | ((x) << 24U))) /** Swap the byte ordering of a 64-bit value */ #define CY_SWAP_ENDIAN64(x) ((uint64_t) (((uint64_t) CY_SWAP_ENDIAN32((uint32_t)(x)) << 32U) | \ CY_SWAP_ENDIAN32((uint32_t)((x) >> 32U)))) /******************************************************************************* * Memory model definitions *******************************************************************************/ #if defined(__ARMCC_VERSION) /** To create cross compiler compatible code, use the CY_NOINIT, CY_SECTION, CY_UNUSED, CY_ALIGN * attributes at the first place of declaration/definition. * For example: CY_NOINIT uint32_t noinitVar; */ #if (__ARMCC_VERSION >= 6010050) #define CY_NOINIT __attribute__ ((section(".noinit"))) #else #define CY_NOINIT __attribute__ ((section(".noinit"), zero_init)) #endif /* (__ARMCC_VERSION >= 6010050) */ #define CY_SECTION(name) __attribute__ ((section(name))) #define CY_UNUSED __attribute__ ((unused)) #define CY_NOINLINE __attribute__ ((noinline)) /* Specifies the minimum alignment (in bytes) for variables of the specified type. */ #define CY_ALIGN(align) __ALIGNED(align) #define CY_RAMFUNC_BEGIN __attribute__ ((section(".ramfunc"))) #define CY_RAMFUNC_END #elif defined (__GNUC__) #if defined (__clang__) #define CY_NOINIT __attribute__ ((section("__DATA, __noinit"))) #define CY_SECTION(name) __attribute__ ((section("__DATA, "name))) #define CY_RAMFUNC_BEGIN __attribute__ ((section("__DATA, .ramfunc"))) #define CY_RAMFUNC_END #else #define CY_NOINIT __attribute__ ((section(".noinit"))) #define CY_SECTION(name) __attribute__ ((section(name))) #define CY_RAMFUNC_BEGIN __attribute__ ((section(".ramfunc"))) #define CY_RAMFUNC_END #endif #define CY_UNUSED __attribute__ ((unused)) #define CY_NOINLINE __attribute__ ((noinline)) #define CY_ALIGN(align) __ALIGNED(align) #elif defined (__ICCARM__) #define CY_PRAGMA(x) _Pragma(#x) #define CY_NOINIT __no_init #define CY_SECTION(name) CY_PRAGMA(location = name) #define CY_UNUSED #define CY_NOINLINE CY_PRAGMA(optimize = no_inline) #define CY_RAMFUNC_BEGIN CY_PRAGMA(diag_suppress = Ta023) __ramfunc #define CY_RAMFUNC_END CY_PRAGMA(diag_default = Ta023) #if (__VER__ < 8010001) #define CY_ALIGN(align) CY_PRAGMA(data_alignment = align) #else #define CY_ALIGN(align) __ALIGNED(align) #endif /* (__VER__ < 8010001) */ #else #error "An unsupported toolchain" #endif /* (__ARMCC_VERSION) */ typedef void (* cy_israddress)(void); /**< Type of ISR callbacks */ #if defined (__ICCARM__) typedef union { cy_israddress __fun; void * __ptr; } cy_intvec_elem; #endif /* defined (__ICCARM__) */ /* MISRA rule 6.3 recommends using specific-length typedef for the basic * numerical types of signed and unsigned variants of char, float, and double. */ typedef char char_t; /**< Specific-length typedef for the basic numerical types of char */ typedef float float32_t; /**< Specific-length typedef for the basic numerical types of float */ typedef double float64_t; /**< Specific-length typedef for the basic numerical types of double */ #if !defined(NDEBUG) /** The max size of the file name which stores the ASSERT location */ #define CY_MAX_FILE_NAME_SIZE (24U) extern CY_NOINIT char_t cy_assertFileName[CY_MAX_FILE_NAME_SIZE]; /**< The assert buffer */ extern CY_NOINIT uint32_t cy_assertLine; /**< The assert line value */ #endif /* NDEBUG */ #if (CY_ARM_FAULT_DEBUG == CY_ARM_FAULT_DEBUG_ENABLED) #define CY_R0_Pos (0U) /**< The position of the R0 content in a fault structure */ #define CY_R1_Pos (1U) /**< The position of the R1 content in a fault structure */ #define CY_R2_Pos (2U) /**< The position of the R2 content in a fault structure */ #define CY_R3_Pos (3U) /**< The position of the R3 content in a fault structure */ #define CY_R12_Pos (4U) /**< The position of the R12 content in a fault structure */ #define CY_LR_Pos (5U) /**< The position of the LR content in a fault structure */ #define CY_PC_Pos (6U) /**< The position of the PC content in a fault structure */ #define CY_PSR_Pos (7U) /**< The position of the PSR content in a fault structure */ #if (CY_CPU_CORTEX_M4) && ((defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)) && \ (defined (__FPU_USED ) && (__FPU_USED == 1U))) #define CY_FPSCR_IXC_Msk (0x00000010U) /**< The cumulative exception bit for floating-point exceptions */ #define CY_FPSCR_IDC_Msk (0x00000080U) /**< The cumulative exception bit for floating-point exceptions */ #define CY_S0_Pos (8U) /**< The position of the FPU S0 content in a fault structure */ #define CY_S1_Pos (9U) /**< The position of the FPU S1 content in a fault structure */ #define CY_S2_Pos (10U) /**< The position of the FPU S2 content in a fault structure */ #define CY_S3_Pos (11U) /**< The position of the FPU S3 content in a fault structure */ #define CY_S4_Pos (12U) /**< The position of the FPU S4 content in a fault structure */ #define CY_S5_Pos (13U) /**< The position of the FPU S5 content in a fault structure */ #define CY_S6_Pos (14U) /**< The position of the FPU S6 content in a fault structure */ #define CY_S7_Pos (15U) /**< The position of the FPU S7 content in a fault structure */ #define CY_S8_Pos (16U) /**< The position of the FPU S8 content in a fault structure */ #define CY_S9_Pos (17U) /**< The position of the FPU S9 content in a fault structure */ #define CY_S10_Pos (18U) /**< The position of the FPU S10 content in a fault structure */ #define CY_S11_Pos (19U) /**< The position of the FPU S11 content in a fault structure */ #define CY_S12_Pos (20U) /**< The position of the FPU S12 content in a fault structure */ #define CY_S13_Pos (21U) /**< The position of the FPU S13 content in a fault structure */ #define CY_S14_Pos (22U) /**< The position of the FPU S14 content in a fault structure */ #define CY_S15_Pos (23U) /**< The position of the FPU S15 content in a fault structure */ #define CY_FPSCR_Pos (24U) /**< The position of the FPU FPSCR content in a fault structure */ #endif /* CY_CPU_CORTEX_M4 && __FPU_PRESENT */ extern CY_NOINIT cy_stc_fault_frame_t cy_faultFrame; /**< Fault frame structure */ #endif /* (CY_ARM_FAULT_DEBUG == CY_ARM_FAULT_DEBUG_ENABLED) */ /******************************************************************************* * Macro Name: CY_GET_REG8(addr) ****************************************************************************//** * * Reads the 8-bit value from the specified address. This function can't be * used to access the Core register, otherwise a fault occurs. * * \param addr The register address. * * \return The read value. * *******************************************************************************/ #define CY_GET_REG8(addr) (*((const volatile uint8_t *)(addr))) /******************************************************************************* * Macro Name: CY_SET_REG8(addr, value) ****************************************************************************//** * * Writes an 8-bit value to the specified address. This function can't be * used to access the Core register, otherwise a fault occurs. * * \param addr The register address. * * \param value The value to write. * *******************************************************************************/ #define CY_SET_REG8(addr, value) (*((volatile uint8_t *)(addr)) = (uint8_t)(value)) /******************************************************************************* * Macro Name: CY_GET_REG16(addr) ****************************************************************************//** * * Reads the 16-bit value from the specified address. * * \param addr The register address. * * \return The read value. * *******************************************************************************/ #define CY_GET_REG16(addr) (*((const volatile uint16_t *)(addr))) /******************************************************************************* * Macro Name: CY_SET_REG16(addr, value) ****************************************************************************//** * * Writes the 16-bit value to the specified address. * * \param addr The register address. * * \param value The value to write. * *******************************************************************************/ #define CY_SET_REG16(addr, value) (*((volatile uint16_t *)(addr)) = (uint16_t)(value)) /******************************************************************************* * Macro Name: CY_GET_REG24(addr) ****************************************************************************//** * * Reads the 24-bit value from the specified address. * * \param addr The register address. * * \return The read value. * *******************************************************************************/ #define CY_GET_REG24(addr) (((uint32_t) (*((const volatile uint8_t *)(addr)))) | \ (((uint32_t) (*((const volatile uint8_t *)(addr) + 1))) << 8U) | \ (((uint32_t) (*((const volatile uint8_t *)(addr) + 2))) << 16U)) /******************************************************************************* * Macro Name: CY_SET_REG24(addr, value) ****************************************************************************//** * * Writes the 24-bit value to the specified address. * * \param addr The register address. * * \param value The value to write. * *******************************************************************************/ #define CY_SET_REG24(addr, value) do \ { \ (*((volatile uint8_t *) (addr))) = (uint8_t)(value); \ (*((volatile uint8_t *) (addr) + 1)) = (uint8_t)((value) >> 8U); \ (*((volatile uint8_t *) (addr) + 2)) = (uint8_t)((value) >> 16U); \ } \ while(0) /******************************************************************************* * Macro Name: CY_GET_REG32(addr) ****************************************************************************//** * * Reads the 32-bit value from the specified register. The address is the little * endian order (LSB in lowest address). * * \param addr The register address. * * \return The read value. * *******************************************************************************/ #define CY_GET_REG32(addr) (*((const volatile uint32_t *)(addr))) /******************************************************************************* * Macro Name: CY_SET_REG32(addr, value) ****************************************************************************//** * * Writes the 32-bit value to the specified register. The address is the little * endian order (LSB in lowest address). * * \param addr The register address. * * \param value The value to write. * *******************************************************************************/ #define CY_SET_REG32(addr, value) (*((volatile uint32_t *)(addr)) = (uint32_t)(value)) /** * \defgroup group_syslib_macros_assert Assert Classes and Levels * \{ * Defines for the Assert Classes and Levels */ /** * Class 1 - The highest class, safety-critical functions which rely on parameters that could be * changed between different PSoC devices */ #define CY_ASSERT_CLASS_1 (1U) /** Class 2 - Functions that have fixed limits such as counter periods (16-bits/32-bits etc.) */ #define CY_ASSERT_CLASS_2 (2U) /** Class 3 - Functions that accept enums as constant parameters */ #define CY_ASSERT_CLASS_3 (3U) #ifndef CY_ASSERT_LEVEL /** The user-definable assert level from compiler command-line argument (similarly to DEBUG / NDEBUG) */ #define CY_ASSERT_LEVEL CY_ASSERT_CLASS_3 #endif /* CY_ASSERT_LEVEL */ #if (CY_ASSERT_LEVEL == CY_ASSERT_CLASS_1) #define CY_ASSERT_L1(x) CY_ASSERT(x) /**< Assert Level 1 */ #define CY_ASSERT_L2(x) do{} while(0) /**< Assert Level 2 */ #define CY_ASSERT_L3(x) do{} while(0) /**< Assert Level 3 */ #elif (CY_ASSERT_LEVEL == CY_ASSERT_CLASS_2) #define CY_ASSERT_L1(x) CY_ASSERT(x) /**< Assert Level 1 */ #define CY_ASSERT_L2(x) CY_ASSERT(x) /**< Assert Level 2 */ #define CY_ASSERT_L3(x) do{} while(0) /**< Assert Level 3 */ #else /* Default is Level 3 */ #define CY_ASSERT_L1(x) CY_ASSERT(x) /**< Assert Level 1 */ #define CY_ASSERT_L2(x) CY_ASSERT(x) /**< Assert Level 2 */ #define CY_ASSERT_L3(x) CY_ASSERT(x) /**< Assert Level 3 */ #endif /* CY_ASSERT_LEVEL == CY_ASSERT_CLASS_1 */ /** \} group_syslib_macros_assert */ /******************************************************************************* * Macro Name: CY_ASSERT ****************************************************************************//** * * The macro that evaluates the expression and, if it is false (evaluates to 0), * the processor is halted. Cy_SysLib_AssertFailed() is called when the logical * expression is false to store the ASSERT location and halt the processor. * * \param x The logical expression. Asserts if false. * \note This macro is evaluated unless NDEBUG is not defined. * If NDEBUG is defined, just empty do while cycle is generated for this * macro for the sake of consistency and to avoid MISRA violation. * NDEBUG is defined by default for a Release build setting and not defined * for a Debug build setting. * *******************************************************************************/ #if !defined(NDEBUG) #define CY_ASSERT(x) do \ { \ if(!(x)) \ { \ Cy_SysLib_AssertFailed((char_t *) __FILE__, (uint32_t) __LINE__); \ } \ } while(0) #else #define CY_ASSERT(x) do \ { \ } while(0) #endif /* !defined(NDEBUG) */ /******************************************************************************* * Macro Name: _CLR_SET_FLD32U ****************************************************************************//** * * The macro for setting a register with a name field and value for providing * get-clear-modify-write operations. * Returns a resulting value to be assigned to the register. * *******************************************************************************/ #define _CLR_SET_FLD32U(reg, field, value) (((reg) & ((uint32_t)(~(field ## _Msk)))) | (_VAL2FLD(field, value))) /******************************************************************************* * Macro Name: CY_REG32_CLR_SET ****************************************************************************//** * * Uses _CLR_SET_FLD32U macro for providing get-clear-modify-write * operations with a name field and value and writes a resulting value * to the 32-bit register. * *******************************************************************************/ #define CY_REG32_CLR_SET(reg, field, value) ((reg) = _CLR_SET_FLD32U((reg), field, (value))) /******************************************************************************* * Macro Name: _CLR_SET_FLD16U ****************************************************************************//** * * The macro for setting a 16-bit register with a name field and value for providing * get-clear-modify-write operations. * Returns a resulting value to be assigned to the 16-bit register. * *******************************************************************************/ #define _CLR_SET_FLD16U(reg, field, value) ((uint16_t)(((reg) & ((uint16_t)(~(field ## _Msk)))) | \ ((uint16_t)_VAL2FLD(field, value)))) /******************************************************************************* * Macro Name: CY_REG16_CLR_SET ****************************************************************************//** * * Uses _CLR_SET_FLD16U macro for providing get-clear-modify-write * operations with a name field and value and writes a resulting value * to the 16-bit register. * *******************************************************************************/ #define CY_REG16_CLR_SET(reg, field, value) ((reg) = _CLR_SET_FLD16U((reg), field, (value))) /******************************************************************************* * Macro Name: _CLR_SET_FLD8U ****************************************************************************//** * * The macro for setting a 8-bit register with a name field and value for providing * get-clear-modify-write operations. * Returns a resulting value to be assigned to the 8-bit register. * *******************************************************************************/ #define _CLR_SET_FLD8U(reg, field, value) ((uint8_t)(((reg) & ((uint8_t)(~(field ## _Msk)))) | \ ((uint8_t)_VAL2FLD(field, value)))) /******************************************************************************* * Macro Name: CY_REG8_CLR_SET ****************************************************************************//** * * Uses _CLR_SET_FLD8U macro for providing get-clear-modify-write * operations with a name field and value and writes a resulting value * to the 8-bit register. * *******************************************************************************/ #define CY_REG8_CLR_SET(reg, field, value) ((reg) = _CLR_SET_FLD8U((reg), field, (value))) /******************************************************************************* * Macro Name: _BOOL2FLD ****************************************************************************//** * * Returns a field mask if the value is not false. * Returns 0, if the value is false. * *******************************************************************************/ #define _BOOL2FLD(field, value) (((value) != false) ? (field ## _Msk) : 0UL) /******************************************************************************* * Macro Name: _FLD2BOOL ****************************************************************************//** * * Returns true, if the value includes the field mask. * Returns false, if the value doesn't include the field mask. * *******************************************************************************/ #define _FLD2BOOL(field, value) (((value) & (field ## _Msk)) != 0UL) /******************************************************************************* * Macro Name: CY_SYSLIB_DIV_ROUND ****************************************************************************//** * * Calculates a / b with rounding to the nearest integer, * a and b must have the same sign. * *******************************************************************************/ #define CY_SYSLIB_DIV_ROUND(a, b) (((a) + ((b) / 2U)) / (b)) /******************************************************************************* * Macro Name: CY_SYSLIB_DIV_ROUNDUP ****************************************************************************//** * * Calculates a / b with rounding up if remainder != 0, * both a and b must be positive. * *******************************************************************************/ #define CY_SYSLIB_DIV_ROUNDUP(a, b) ((((a) - 1U) / (b)) + 1U) /****************************************************************************** * Constants *****************************************************************************/ /** Defines a 32-kHz clock delay */ #define CY_DELAY_MS_OVERFLOW (0x8000U) /** * \defgroup group_syslib_macros_reset_cause Reset cause * \{ * Define RESET_CAUSE mask values */ /** A basic WatchDog Timer (WDT) reset has occurred since the last power cycle. */ #define CY_SYSLIB_RESET_HWWDT (0x0001U) /** The fault logging system requested a reset from its Active logic. */ #define CY_SYSLIB_RESET_ACT_FAULT (0x0002U) /** The fault logging system requested a reset from its Deep-Sleep logic. */ #define CY_SYSLIB_RESET_DPSLP_FAULT (0x0004U) /** The CPU requested a system reset through it's SYSRESETREQ. This can be done via a debugger probe or in firmware. */ #define CY_SYSLIB_RESET_SOFT (0x0010U) /** The Multi-Counter Watchdog timer #0 reset has occurred since the last power cycle. */ #define CY_SYSLIB_RESET_SWWDT0 (0x0020U) /** The Multi-Counter Watchdog timer #1 reset has occurred since the last power cycle. */ #define CY_SYSLIB_RESET_SWWDT1 (0x0040U) /** The Multi-Counter Watchdog timer #2 reset has occurred since the last power cycle. */ #define CY_SYSLIB_RESET_SWWDT2 (0x0080U) /** The Multi-Counter Watchdog timer #3 reset has occurred since the last power cycle. */ #define CY_SYSLIB_RESET_SWWDT3 (0x0100U) /** The reset has occurred on a wakeup from Hibernate power mode. */ #define CY_SYSLIB_RESET_HIB_WAKEUP (0x40000UL) /** \} group_syslib_macros_reset_cause */ /** Bit[31:24] Opcode = 0x1B (SoftReset) * Bit[7:1] Type = 1 (Only CM4 reset) */ #define CY_IPC_DATA_FOR_CM4_SOFT_RESET (0x1B000002UL) /** * \defgroup group_syslib_macros_unique_id Unique ID * \{ * Unique ID fields positions */ #define CY_UNIQUE_ID_DIE_YEAR_Pos (57U) /**< The position of the DIE_YEAR field in the silicon Unique ID */ #define CY_UNIQUE_ID_DIE_MINOR_Pos (56U) /**< The position of the DIE_MINOR field in the silicon Unique ID */ #define CY_UNIQUE_ID_DIE_SORT_Pos (48U) /**< The position of the DIE_SORT field in the silicon Unique ID */ #define CY_UNIQUE_ID_DIE_Y_Pos (40U) /**< The position of the DIE_Y field in the silicon Unique ID */ #define CY_UNIQUE_ID_DIE_X_Pos (32U) /**< The position of the DIE_X field in the silicon Unique ID */ #define CY_UNIQUE_ID_DIE_WAFER_Pos (24U) /**< The position of the DIE_WAFER field in the silicon Unique ID */ #define CY_UNIQUE_ID_DIE_LOT_2_Pos (16U) /**< The position of the DIE_LOT_2 field in the silicon Unique ID */ #define CY_UNIQUE_ID_DIE_LOT_1_Pos (8U) /**< The position of the DIE_LOT_1 field in the silicon Unique ID */ #define CY_UNIQUE_ID_DIE_LOT_0_Pos (0U) /**< The position of the DIE_LOT_0 field in the silicon Unique ID */ /** \} group_syslib_macros_unique_id */ /** \} group_syslib_macros */ /****************************************************************************** * Function prototypes ******************************************************************************/ /** * \addtogroup group_syslib_functions * \{ */ void Cy_SysLib_Delay(uint32_t milliseconds); void Cy_SysLib_DelayUs(uint16_t microseconds); /** Delays for the specified number of cycles. * The function is implemented in the assembler for each supported compiler. * \param cycles The number of cycles to delay. */ void Cy_SysLib_DelayCycles(uint32_t cycles); __NO_RETURN void Cy_SysLib_Halt(uint32_t reason); void Cy_SysLib_AssertFailed(const char_t * file, uint32_t line); void Cy_SysLib_ClearFlashCacheAndBuffer(void); cy_en_syslib_status_t Cy_SysLib_ResetBackupDomain(void); uint32_t Cy_SysLib_GetResetReason(void); void Cy_SysLib_ClearResetReason(void); uint64_t Cy_SysLib_GetUniqueId(void); #if (CY_CPU_CORTEX_M0P) void Cy_SysLib_SoftResetCM4(void); #endif /* CY_CPU_CORTEX_M0P */ #if (CY_ARM_FAULT_DEBUG == CY_ARM_FAULT_DEBUG_ENABLED) || defined(CY_DOXYGEN) void Cy_SysLib_FaultHandler(uint32_t const *faultStackAddr); void Cy_SysLib_ProcessingFault(void); #endif /* (CY_ARM_FAULT_DEBUG == CY_ARM_FAULT_DEBUG_ENABLED) */ void Cy_SysLib_SetWaitStates(bool ulpMode, uint32_t clkHfMHz); /******************************************************************************* * Function Name: Cy_SysLib_EnterCriticalSection ****************************************************************************//** * * Cy_SysLib_EnterCriticalSection disables interrupts and returns a value * indicating whether the interrupts were previously enabled. * * \return Returns the current interrupt status. Returns 0 if the interrupts * were previously enabled or 1 if the interrupts were previously * disabled. * * \note Implementation of Cy_SysLib_EnterCriticalSection manipulates the IRQ * enable bit with interrupts still enabled. * *******************************************************************************/ uint32_t Cy_SysLib_EnterCriticalSection(void); /******************************************************************************* * Function Name: Cy_SysLib_ExitCriticalSection ****************************************************************************//** * * Re-enables the interrupts if they were enabled before * Cy_SysLib_EnterCriticalSection() was called. The argument should be the value * returned from \ref Cy_SysLib_EnterCriticalSection(). * * \param savedIntrStatus Puts the saved interrupts status returned by * the \ref Cy_SysLib_EnterCriticalSection(). * *******************************************************************************/ void Cy_SysLib_ExitCriticalSection(uint32_t savedIntrStatus); /** \cond INTERNAL */ #define CY_SYSLIB_DEVICE_REV_0A (0x21U) /**< The device TO *A Revision ID */ #define CY_SYSLIB_DEVICE_PSOC6ABLE2 (0x100U) /**< The PSoC6 BLE2 device Family ID */ /******************************************************************************* * Function Name: Cy_SysLib_GetDeviceRevision ****************************************************************************//** * * This function returns a device Revision ID. * * \return A device Revision ID. * *******************************************************************************/ __STATIC_INLINE uint8_t Cy_SysLib_GetDeviceRevision(void) { return ((SFLASH_SI_REVISION_ID == 0UL) ? CY_SYSLIB_DEVICE_REV_0A : SFLASH_SI_REVISION_ID); } /******************************************************************************* * Function Name: Cy_SysLib_GetDevice ****************************************************************************//** * * This function returns a device Family ID. * * \return A device Family ID. * *******************************************************************************/ __STATIC_INLINE uint16_t Cy_SysLib_GetDevice(void) { return ((SFLASH_FAMILY_ID == 0UL) ? CY_SYSLIB_DEVICE_PSOC6ABLE2 : SFLASH_FAMILY_ID); } typedef uint32_t cy_status; /** The ARM 32-bit status value for backward compatibility with the UDB components. Do not use it in your code. */ typedef uint32_t cystatus; typedef uint8_t uint8; /**< Alias to uint8_t for backward compatibility */ typedef uint16_t uint16; /**< Alias to uint16_t for backward compatibility */ typedef uint32_t uint32; /**< Alias to uint32_t for backward compatibility */ typedef int8_t int8; /**< Alias to int8_t for backward compatibility */ typedef int16_t int16; /**< Alias to int16_t for backward compatibility */ typedef int32_t int32; /**< Alias to int32_t for backward compatibility */ typedef float float32; /**< Alias to float for backward compatibility */ typedef double float64; /**< Alias to double for backward compatibility */ typedef int64_t int64; /**< Alias to int64_t for backward compatibility */ typedef uint64_t uint64; /**< Alias to uint64_t for backward compatibility */ /* Signed or unsigned depending on the compiler selection */ typedef char char8; /**< Alias to char for backward compatibility */ typedef volatile uint8_t reg8; /**< Alias to uint8_t for backward compatibility */ typedef volatile uint16_t reg16; /**< Alias to uint16_t for backward compatibility */ typedef volatile uint32_t reg32; /**< Alias to uint32_t for backward compatibility */ /** The ARM 32-bit Return error / status code for backward compatibility. * Do not use them in your code. */ #define CY_RET_SUCCESS (0x00U) /* Successful */ #define CY_RET_BAD_PARAM (0x01U) /* One or more invalid parameters */ #define CY_RET_INVALID_OBJECT (0x02U) /* An invalid object specified */ #define CY_RET_MEMORY (0x03U) /* A memory-related failure */ #define CY_RET_LOCKED (0x04U) /* A resource lock failure */ #define CY_RET_EMPTY (0x05U) /* No more objects available */ #define CY_RET_BAD_DATA (0x06U) /* Bad data received (CRC or other error check) */ #define CY_RET_STARTED (0x07U) /* Operation started, but not necessarily completed yet */ #define CY_RET_FINISHED (0x08U) /* Operation is completed */ #define CY_RET_CANCELED (0x09U) /* Operation is canceled */ #define CY_RET_TIMEOUT (0x10U) /* Operation timed out */ #define CY_RET_INVALID_STATE (0x11U) /* Operation is not setup or is in an improper state */ #define CY_RET_UNKNOWN ((cy_status) 0xFFFFFFFFU) /* Unknown failure */ /** ARM 32-bit Return error / status codes for backward compatibility with the UDB components. * Do not use them in your code. */ #define CYRET_SUCCESS (0x00U) /* Successful */ #define CYRET_BAD_PARAM (0x01U) /* One or more invalid parameters */ #define CYRET_INVALID_OBJECT (0x02U) /* An invalid object specified */ #define CYRET_MEMORY (0x03U) /* A memory-related failure */ #define CYRET_LOCKED (0x04U) /* A resource lock failure */ #define CYRET_EMPTY (0x05U) /* No more objects available */ #define CYRET_BAD_DATA (0x06U) /* Bad data received (CRC or other error check) */ #define CYRET_STARTED (0x07U) /* Operation started, but not necessarily completed yet */ #define CYRET_FINISHED (0x08U) /* Operation is completed */ #define CYRET_CANCELED (0x09U) /* Operation is canceled */ #define CYRET_TIMEOUT (0x10U) /* Operation timed out */ #define CYRET_INVALID_STATE (0x11U) /* Operation is not setup or is in an improper state */ #define CYRET_UNKNOWN ((cystatus) 0xFFFFFFFFU) /* Unknown failure */ /** A type of ISR callbacks for backward compatibility with the UDB components. Do not use it in your code. */ typedef void (* cyisraddress)(void); #if defined (__ICCARM__) /** A type of ISR callbacks for backward compatibility with the UDB components. Do not use it in your code. */ typedef union { cyisraddress __fun; void * __ptr; } intvec_elem; #endif /* defined (__ICCARM__) */ /** The backward compatibility define for the CyDelay() API for the UDB components. * Do not use it in your code. */ #define CyDelay Cy_SysLib_Delay /** The backward compatibility define for the CyDelayUs() API for the UDB components. * Do not use it in your code. */ #define CyDelayUs Cy_SysLib_DelayUs /** The backward compatibility define for the CyDelayCycles() API for the UDB components. * Do not use it in your code. */ #define CyDelayCycles Cy_SysLib_DelayCycles /** The backward compatibility define for the CyEnterCriticalSection() API for the UDB components. * Do not use it in your code. */ #define CyEnterCriticalSection() ((uint8_t) Cy_SysLib_EnterCriticalSection()) /** The backward compatibility define for the CyExitCriticalSection() API for the UDB components. * Do not use it in your code. */ #define CyExitCriticalSection(x) (Cy_SysLib_ExitCriticalSection((uint32_t) (x))) /** \endcond */ /** \} group_syslib_functions */ #if defined(__cplusplus) } #endif /* defined(__cplusplus) */ #endif /* CY_SYSLIB_H */ /** \} group_syslib */ /* [] END OF FILE */
mwlang/jasonette-rails
lib/jasonette/core/items.rb
module Jasonette class Items < Jasonette::Base def label caption=nil, skip_type=false item = Jasonette::Item.new(context) do text caption unless caption.nil? type "label" unless skip_type encode(&::Proc.new) if block_given? end append item end def text caption=nil, skip_type=false item = Jasonette::Item.new(context) do text caption unless caption.nil? type "text" unless skip_type encode(&::Proc.new) if block_given? end append item end def video uri=nil, skip_type=false item = Jasonette::Item.new(context) do type "video" unless skip_type file_url uri unless uri.nil? encode(&::Proc.new) if block_given? end append item end def image uri=nil, skip_type=false, url_key="url" item = Jasonette::Item.new(context) do type "image" unless skip_type set! url_key, uri unless uri.nil? encode(&::Proc.new) if block_given? end append item end def button caption=nil, is_url=false, skip_type=false item = Jasonette::Item.new(context) do type "button" unless skip_type unless caption.nil? is_url ? (url caption) : (text caption) end encode(&::Proc.new) if block_given? end append item end def slider name, value=nil, skip_type=false item = Jasonette::Item.new(context) do type "slider" unless skip_type name name value value unless value.nil? encode(&::Proc.new) if block_given? end append item end def layout orientation="vertical" item = Jasonette::Layout.new(context) do type orientation encode(&::Proc.new) if block_given? end append item end def textfield name=nil, value=nil, skip_type=false item = Jasonette::Item.new(context) do type "textfield" unless skip_type name name unless name.nil? value value unless value.nil? encode(&::Proc.new) if block_given? end append item end def textarea name=nil, value=nil, skip_type=false item = Jasonette::Item.new(context) do type "textarea" unless skip_type name name unless name.nil? value value unless value.nil? encode(&::Proc.new) if block_given? end append item end def space height=nil, skip_type=false item = Jasonette::Item.new(context) do type "space" unless skip_type height height unless height.nil? encode(&::Proc.new) if block_given? end append item end def map skip_type=false item = Jasonette::Map.new(context) do type "map" unless skip_type encode(&::Proc.new) if block_given? end append item end def html text, skip_type=false item = Jasonette::Item.new(context) do type "html" unless skip_type text text unless text.nil? encode(&::Proc.new) if block_given? end append item end def merge! items item = Jasonette::Item.new(context) do merge! items encode(&::Proc.new) if block_given? end append item end private def append builder @attributes = [] if @attributes.empty? raise "HashError : You may have used `set!` before" if ::Hash === @attributes @attributes << builder.attributes! builder end end end
cheeepsan/ure-test
src/main/java/ure/ui/modals/UModalTarget.java
<gh_stars>100-1000 package ure.ui.modals; import ure.commands.UCommand; import ure.math.UColor; import ure.sys.Entity; import ure.sys.GLKey; import java.util.ArrayList; public class UModalTarget extends UModal { String prompt; ArrayList<Entity> targets; boolean shiftFree, visibleOnly; String glyphs = "v<^>"; UColor glyphColor; int cellx, celly; public UModalTarget(String _prompt, HearModalTarget _callback, String _callbackContext, ArrayList<Entity> _targets, boolean _shiftFree, boolean _visibleOnly) { super(_callback, _callbackContext); prompt = _prompt; targets = _targets; shiftFree = _shiftFree; visibleOnly = _visibleOnly; setDimensions(3,3); cellx = commander.player().areaX(); celly = commander.player().areaY(); glyphColor = new UColor(commander.config.getHiliteColor()); } @Override public void setDimensions(int x, int y) { cellw = x; cellh = y; } @Override public void drawFrame() { } @Override public void drawContent() { commander.printScroll(prompt); int camx = cellx - commander.camera().leftEdge; int camy = celly - commander.camera().topEdge; renderer.drawGlyph(glyphs.charAt(0), (camx) * gw(), (camy-1)*gh(), glyphColor); renderer.drawGlyph(glyphs.charAt(2), (camx) * gw(), (camy+1)*gh(), glyphColor); renderer.drawGlyph(glyphs.charAt(3), (camx - 1) * gw(), camy * gh(), glyphColor); renderer.drawGlyph(glyphs.charAt(1), (camx + 1) * gw(), camy * gh(), glyphColor); } @Override public void hearCommand(UCommand command, GLKey k) { if (command.id.equals("MOVE_N")) celly -= 1; if (command.id.equals("MOVE_S")) celly += 1; if (command.id.equals("MOVE_W")) cellx -= 1; if (command.id.equals("MOVE_E")) cellx += 1; if (command.id.equals("ESC")) escape(); if (command.id.equals("PASS")) returnSelection(); } public void returnSelection() { dismiss(); ((HearModalTarget)callback).hearModalTarget(callbackContext, null, cellx, celly); } @Override public void animationTick() { glyphColor.setAlpha((float)Math.sin(commander.frameCounter * 0.14f) * 0.3f + 0.4f); super.animationTick(); } }
clousale/amazon-sp-api-javascript
src/client/models/Promotion.js
<reponame>clousale/amazon-sp-api-javascript<filename>src/client/models/Promotion.js /** * Selling Partner API for Finances * The Selling Partner API for Finances helps you obtain financial information relevant to a seller's business. You can obtain financial events for a given order, financial event group, or date range without having to wait until a statement period closes. You can also obtain financial event groups for a given date range. * * OpenAPI spec version: v0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * */ import ApiClient from '../ApiClient'; import Currency from './Currency'; /** * The Promotion model module. * @module client/models/Promotion * @version v0 */ export default class Promotion { /** * Constructs a new <code>Promotion</code>. * A promotion applied to an item. * @alias module:client/models/Promotion * @class */ constructor() { } /** * Constructs a <code>Promotion</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:client/models/Promotion} obj Optional instance to populate. * @return {module:client/models/Promotion} The populated <code>Promotion</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new Promotion(); if (data.hasOwnProperty('PromotionType')) { obj['PromotionType'] = ApiClient.convertToType(data['PromotionType'], 'String'); } if (data.hasOwnProperty('PromotionId')) { obj['PromotionId'] = ApiClient.convertToType(data['PromotionId'], 'String'); } if (data.hasOwnProperty('PromotionAmount')) { obj['PromotionAmount'] = Currency.constructFromObject(data['PromotionAmount']); } } return obj; } /** * The type of promotion. * @member {String} PromotionType */ 'PromotionType' = undefined; /** * The seller-specified identifier for the promotion. * @member {String} PromotionId */ 'PromotionId' = undefined; /** * @member {module:client/models/Currency} PromotionAmount */ 'PromotionAmount' = undefined; }
kzhioki/U8g2_Arduino
src/clib/u8g2_font_t0_17b_mf.c
#include "u8g2.h" /* Fontname: -UW-Ttyp0-Bold-R-Normal--17-160-75-75-C-90-ISO10646-1 Copyright: Copyright (C) 2012-2015 <NAME> Glyphs: 191/3075 BBX Build Mode: 2 */ const uint8_t u8g2_font_t0_17b_mf[3988] U8G2_FONT_SECTION("u8g2_font_t0_17b_mf") = "\277\2\4\2\4\5\1\3\5\11\21\0\375\13\375\14\377\2O\4\373\17w \10\31'\77\377\15\0!" "\14\31'\77\205\316\337#tz\2\42\17\31'\77J!R\210\24\242H\236\217\1#\33\31'\77a" "&\244\320\14\6\221\305F!Rh\26\223\301 \243\20e\362p\0$\36\31'\77.\30\33L\24\11" "\211\42\22Q\304\6\261A,!\251\220(\22\222\301,\230\6%\35\31'\77\134\224PD\24\212\204D" "Q\244\220Y\210\22\212\210B\221\220(\212\364h\0&\32\31'\77\201L\221R\244\24\61\331J\241\210" "(\24\21\33\311f\220\320\203\1'\13\31'\77\316\231.\317W\0(\17\31'\77Pf'\323y\250" "\23\332\243\0)\17\31'\77Jh'\324y\246\223\331\3\1*\23\31'\77\333LH\241\32\15\6\241" "\225B\224\311\23\2+\21\31'\77#\235\321`\240\30\14D:{J\0,\13\31'\77_\353\314t" "q\0-\15\31'\77\327\203Ad\60\310s\4.\11\31'\77_\353\354\11/\23\31'\77R'\323" "\311t\62\235L'\323\351\362P\0\60\27\31'\77\301J\241\61\321H\64\22\215D#\321H\64\26\252" "=\1\61\16\31'\77\211l\65\10)t\376\36\16\62\25\31'\77|\240\221L\64:\231w\271\301 " "\62\30\344\321\0\63\23\31'\77|\240\261\63S\15\202:\23\215f\240\207\3\64\25\31'\77\211\354*" "!R\210\42\32\211f\60\210\351\354\341\0\65\26\31'\77| \32\210\202\301A*\42\324IB\22\243" "A\236\0\66\27\31'\77\301 $\323Yl&\66\22\215D#\321h\6z\70\0\67\24\31'\77z" "\60\210\14\6\221T.\247\313\231\351\354)\0\70\27\31'\77|\240\61\321H\64\26\252\225Bc\242\221" "h\64\3=\34\71\26\31'\77|\240\61\321H\64\22\215D\262Y\350\314D\203<\1:\13\31'\77" "w\356\21:{\2;\14\31'\77w\356\21:\63]\34<\14\31'\77\261\314;\241\367h\0=\22" "\31'\77G\203Ad\60\310\16\6\221\301 \317\2>\13\31'\77\241\357d\336\223\0\77\21\31'\77" "|\60\21)D:\231;=B\247'@\32\31'\77\305h\241\11E\24\203H\302$a\222\60Q\14" "\62\301\205j\17\7A\27\31'\77EN\67[%T\21QD\63\330\204$!\205H\217\6B\31\31" "'\77z\260\61\321H\64\22Mf\260\61\321H\64\22\215d\260\207\3C\22\31'\77\301@#\61\212" "\350|(\21\15\362p\0D\30\31'\77z \222hL\64\22\215D#\321H\64\22\215\304f\240'" "E\33\31'\77z\60\210h$\242\210N\22\32\210$!\235(\242\221\14\6y\64\0F\26\31'\77" "|\60\210h$\242\210N\22\32\210$!\235{\22\0G\27\31'\77\301@#\61\212\350L&\32\211" "F\242\61\21\15\364h\0H\33\31'\77Z#\321H\64\22\215D#\31\14\42\32\211F\242\221h$" "\32=\32I\15\31'\77|\260\322\371W\203=\32J\20\31'\77\305 \246\363\33\211F\42\32\344\11" "K\32\31'\77Z#\321d$\32IH\221\32\210\6\42\211F\242\61\321\350\321\0L\17\31'\77Z" "\347\37E\64\222\301 \217\6M\34\31'\77Z#\321H\26\223\305d\60\210$L\22&!IH\22" "\222\204\364h\0N\35\31'\77Z\24\331D\66\221\204\244BR\242\210D\24\221\314$\63\11IRy" "\64\0O\32\31'\77|\240\61\321H\64\22\215D#\321H\64\22\215D\243\31\350\341\0P\23\31'" "\77z\260\61\321H\64\22\215d\260\321yO\3Q\34\31'\77|\240\61\321H\64\22\215D#\321H" "\64\222AB\242Hh\6:\341\22R\31\31'\77z\260\61\321H\64\22\215d\260Q\210$\32\211\306" "D\243G\3S\27\31'\77|\60\321HD\21\341n\220\23JB\22\215d\260\207\3T\17\31'\77" "z\60P\270\210HB:\177OU\33\31'\77Z#\321H\64\22\215D#\321H\64\22\215D#\321" "h\6z\70\0V\27\31'\77Z\244\20ED\31\211F\22\222\244\24\251\331N\227\247\0W\35\31'" "\77Z\225P%T\11I\205\244B\261H\14\6\22\305F\242\221h$z\64\0X\26\31'\77Z#" "\321\230\204\24\261]n\226\20E\64&\32=\32Y\22\31'\77Z\244\20e\64\31IJ\221\332\371\236" "\0Z\27\31'\77z\60\210h$\31\235\314N\246\323D\64\222\301 \217\6[\21\31'\77j \32" "\210t\376\335@\64\320\243\0\134\23\31'\77(\250\23\352\204:\241N\250\23\352\364 \0]\20\31'" "\77j \32\350\374G\3\321@\217\2^\16\31'\77.\267RhLRy\276\0_\15\31'\77\277" "\36\14\42\203A\36\4`\13\31'\77\316\241\60\317'\0a\25\31'\77\333\201H\242\323\14&\32\211" "F\42\331,\364h\0b\25\31'\77Z\347b\63\261\221h$\32\211F\62\261\330\303\1c\20\31'" "\77\343AHb\347P\42\32\344\341\0d\27\31'\77\215\316f!\221L\64\22\215D#\321H$\233" "\205\36\15e\24\31'\77\343AHb#\31\14\42:\241D\64\310\303\1f\22\31'\77\305 \244\20" "\351T\203AH\347{\12\0g\31\31'\77\333A\42\42\231\330HD\203\220p \32LD\21\215f" " \1h\26\31'\77Z\347b\63\261\221h$\32\211F\242\221h\364h\0i\15\31'\77\316\36\271" "\363\253\301\36\15j\22\31'\77P\247\7\16r\376F\242\221\210\6\31\0k\26\31'\77Z\347F\242" "\311HB\12\321@$\321\230h\364h\0l\14\31'\77\301\316\177\65\330\243\1m\35\31'\77\323D" "B\63\30D\24\11\211\42!Q$$\212\204D\221\220(\22z\64\0n\25\31'\77S\305fb#" "\321H\64\22\215D#\321\350\321\0o\25\31'\77\333\201\306D#\321H\64\22\215D\243\31\350\341\0" "p\25\31'\77S\305fb#\321H\64\22\215db\261\321\231\1q\26\31'\77\333\205D\62\321H" "\64\22\215D#\221l\26:\27\0r\17\31'\77\323\305f\241\321dt\336\223\0s\22\31'\77\333" "\201\306d\67\310\15%\32\315@\17\7t\17\31'\77\245N\65X\351|\241\332\303\1u\26\31'\77" "S\215D#\321H\64\22\215D#\221l\26z\64\0v\23\31'\77S\221B\224\221\204$)Ej" "\247\313S\0w\27\31'\77SUB\225\220TH*\24\213\310`#\321H\364h\0x\24\31'\77" "S\215d\242Q\304\204\262\204F\62\321\350\321\0y\24\31'\77S\215Dc\22\222\244\24\251\235]J" "\221Z\1z\24\31'\77\323\301 \42\231ddn\42\23\311`\220G\3{\16\31'\77p\245sf" "h\347p\17\2|\12\31'\77\316\377\367\60\0}\16\31'\77j\250shf\347j\217\3~\20\31" "'\77J\23\31DJ\6\221\214\236o\1\240\21\31'\77\237\246\42\251\310`\20\31\14\362 \0\241\14" "\31'\77k\235\36\241\363\67\0\242\27\31'\77\273\320 \244\230HB\12\221\42\65\210I\64\3Q\36" "\11\243\31\31'\77\301 $\321H\64:\331@\245\323\205\42\203Ad\60\310\243\1\244\22\31'\77S" "\215f R\210\24\242\201\306\236\5\0\245\27\31'\77Z\244\20e\64\31IJ\221\31\14D\242\301@" "\244\263'\246\14\31'\77\316\367D:\357a\0\247\32\31'\77\301 \244\20\11u+\205H!R\210" "\24\252\235P\244\20\15\62\0\250\14\31'\77J!R\350\371\71\0\251\31\31'\77\301h\61I%\24" "\27\36)D\12\213\13E*\262\30\355a\0\252\23\31'\77\301 (\32h$\242\201x\260\31\354\231" "\2\253\21\31'\77g\12\215B\243P)T\12=\13\0\254\16\31'\77\327\203Ad\60\310\271\247\3" "\255\14\31'\77\347\3\321@\317\25\0\256\32\31'\77\301h\61I%\6\213\205_\14\42\12/\6\211" "Td\61\332\303\0\257\14\31'\77j\260\31\354\371\65\0\260\17\31'\77\301J!\312\204\24\252=/" "\1\261\26\31'\77\251\316h\60P\14\6\42\235\321`\240\30\14\364`\0\262\22\31'\77l\20\222h" "\62\62\225l\260\31\354\271\6\263\21\31'\77l\20\222\350TC\215D\64\310s\16\264\13\31'\77P" "f\227\347s\0\265\27\31'\77S\215D#\321H\64\22\215D#YL\24\212\210\316\14\266\36\31'" "\77|\60Q$$\212\204D\221\220(\22\232\205*\241J\250\22\252\204*\241G\3\267\12\31'\77/" "t\366\214\1\270\14\31'\77\177\241\23\212\6\31\0\271\14\31'\77N\266J\350\274\347\1\272\24\31'" "\77\301 $\321H\64\22\321 =\330\14\366L\1\273\21\31'\77G\12\225B\245\320(\64\12=\33" "\0\274\34\31'\77J\266\221h$\66\12\221Bf!\32h\24\23EB\242\30\310\364 \0\275\33\31" "'\77J\266\221h$\66\12\221B&\33\210\26\22'!\305@\64\320c\0\276\35\31'\77j\245\260" "\221\210\6\21\305 \63\220Y\210\6\32\305D\221\220(\6\62=\10\277\21\31'\77k\235\36\241\223\271" "\23)D\222\301\2\300\31\31'\307P\17\311\351f\253\204*\42\212h\6\233\220$\244\20\351\321\0\301" "\31\31'\323J\17\311\351f\253\204*\42\212h\6\233\220$\244\20\351\321\0\302\33\31'\217l\220\212" "\344\1\272\331*\241\212\210\42\232\301&$\11)Dz\64\0\303\33\31'\217B\223\330\3r\272\331*" "\241\212\210\42\232\301&$\11)Dz\64\0\304\33\31'\213B\244\320\3r\272\331*\241\212\210\42\232" "\301&$\11)Dz\64\0\305\33\31'\317J!R\250v\271\331*\241\212\210\42\232\301&$\11)" "Dz\64\0\306\35\31'\77\305@$\311L\62\253\204\42\223\30d\22\212\310@\24\221$\42\222\3=" "\30\307\23\31'\77\301@#\61\212\350|(\21\15bA\231\10\310\33\31'\313P=\30D\64\22Q" "D'\11\15D\222\220N\24\321H\6\203<\32\311\33\31'\323J>\30D\64\22QD'\11\15D" "\222\220N\24\321H\6\203<\32\312\33\31'Sn\245\20\17\6\21\215D'\11\15D\222\220N\24\321" "H\6\203<\32\313\35\31'\213B\244\20\17\6\21\215D\24\321IB\3\221$\244\23E\64\222\301 " "\217\6\314\16\31'\313P>X\351\374\253\301\36\15\315\16\31'\327J>X\351\374\253\301\36\15\316\21" "\31'\223l\220\212\244\7+\235\277\32\354\321\0\317\20\31'\213B\244P\17V:\377j\260G\3\320" "\32\31'\77z \222hL\64\212\201B\61PH\64\22\215D#\261\31\350\11\321\37\31'\217B\223" "\30\213\42\233\310&\222\220THJ\24\221\210\42\222\231d&!I*\217\6\322\33\31'\313P>\320" "\230h$\32\211F\242\221h$\32\211F\242\321\14\364p\0\323\33\31'\327J>\320\230h$\32\211" "F\242\221h$\32\211F\242\321\14\364p\0\324\33\31'Sn\245P\17\64&\32\211F\242\221h$" "\32\211F\242\321\14\364p\0\325\34\31'\217B\223X\17\64&\32\211F\242\221h$\32\211F\242\221" "h\64\3=\34\326\34\31'\213B\244P\17\64&\32\211F\242\221h$\32\211F\242\221h\64\3=" "\34\327\23\31'\77\333PF\42\32\304d\203\220D\23\312\323\1\330\35\31'\77\64\63\320\230H&\222" "\211\42!Q$$\212\204d\42\231\330h\6\232<\24\331\33\31'\313P\255\221h$\32\211F\242\221" "h$\32\211F\242\221h\64\3=\34\332\33\31'\327J\255\221h$\32\211F\242\221h$\32\211F" "\242\221h\64\3=\34\333\33\31'Sn\245\20k$\32\211F\242\221h$\32\211F\242\221h\64\3" "=\34\334\35\31'\213B\244\20k$\32\211F\242\221h$\32\211F\242\221h$\32\315@\17\7\335" "\22\31'\327J-R\210\62\232\214$\245H\355|O\336\23\31'\77Zg\67\330\230h$\32\311`" "\243\263\247\1\337\33\31'\77|\20\222h$\32\211F!RlL\64\22\215D\221\220(\366p\0\340" "\27\31'\77L(\214\17D\22\235f\60\321H\64\22\311f\241G\3\341\30\31'\77P\246\313\3\6" "\42\211N\63\230h$\32\211d\263\320\243\1\342\31\31'\77N\66HE\322\3\221D\247\31L\64\22" "\215D\262Y\350\321\0\343\32\31'\77,\22\32\210\42\361\201H\242\323\14&\32\211F\42\331,\364h" "\0\344\30\31'\77\134!R\250\7\42\211N\63\230h$\32\211d\263\320\243\1\345\31\31'\363J!" "R\250\346\3\221D\247\31L\64\22\215D\262Y\350\321\0\346\26\31'\77[\305Da\244\220\14\6\11" "#\205Ha\242\330\243\1\347\22\31'\77\343AHb\347P\42\32\304\202\62\21\0\350\27\31'\77L" "(\314\3\6!\211\215d\60\210\350\204\22\321 \17\7\351\27\31'\77P\246\313#\6!\211\215d\60" "\210\350\204\22\321 \17\7\352\30\31'\77N\66HE\342\203\220\304F\62\30DtB\211h\220\207\3" "\353\27\31'\77\134!R\310\7!\211\215d\60\210\350\204\22\321 \17\7\354\17\31'\77L(\314\3" "v~\65\330\243\1\355\17\31'\77P\246\313#v~\65\330\243\1\356\20\31'\77N\66HE\342;" "\277\32\354\321\0\357\17\31'\77\134!R\310w~\65\330\243\1\360\27\31'\77Z\241Z)d\203\220" "Bc\242\221h$\32\13\325\236\0\361\32\31'\77,\22\32\210\42i\305fb#\321H\64\22\215D" "#\321\350\321\0\362\30\31'\77J(\314\3\6\32\23\215D#\321H\64\22\215f\240\207\3\363\30\31" "'\77P\246\313\3\6\32\23\215D#\321H\64\22\215f\240\207\3\364\30\31'\77.\267R\250\7\32" "\23\215D#\321H\64\22\215f\240\207\3\365\32\31'\77,\22\32\210\42\361\201\306D#\321H\64\22" "\215D\243\31\350\341\0\366\30\31'\77\134!R\250\7\32\23\215D#\321H\64\22\215f\240\207\3\367" "\20\31'\77\251\316z\60P\14\6j\235=\1\370\30\31'\77\273\314@c\42\231(\22\22EB\62" "\261\321\14\64y(\0\371\30\31'\77J(\214k$\32\211F\242\221h$\32\211d\263\320\243\1\372" "\30\31'\77P\246\213k$\32\211F\242\221h$\32\211d\263\320\243\1\373\31\31'\77.\267R\210" "\65\22\215D#\321H\64\22\215D\262Y\350\321\0\374\31\31'\77\134!R\210\65\22\215D#\321H" "\64\22\215D\262Y\350\321\0\375\26\31'\77P\246\213k$\32\223\220$\245H\355\354R\212\324\12\376" "\26\31'\77Z\347b\63\261\221h$\32\211F\62\261\330\350\314\0\377\27\31'\77\134!R\210\65\22" "\215IH\222R\244vv)Ej\5\0\0\0\4\377\377\0";
bappogroup/bappo-open
packages/bappo-components/storybook/storybook-native/storybook/stories/2-components/Button/examples/PropDisabled.js
<reponame>bappogroup/bappo-open<filename>packages/bappo-components/storybook/storybook-native/storybook/stories/2-components/Button/examples/PropDisabled.js import React from 'react'; import { Button, View } from 'bappo-components'; const ButtonSizeExample = () => ( <View style={styles.horizontal}> <Button text="Disabled" disabled /> </View> ); const styles = { horizontal: { alignItems: 'center', flexDirection: 'row', }, rightPadding: { marginRight: 10, }, }; export default ButtonSizeExample;
graemeaj/VRMiniGun
Plugins/VRExpansionPlugin/VRExpansionPlugin/Intermediate/Build/Win64/UE4Editor/Inc/VRExpansionPlugin/OptionalRepSkeletalMeshActor.generated.h
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef VREXPANSIONPLUGIN_OptionalRepSkeletalMeshActor_generated_h #error "OptionalRepSkeletalMeshActor.generated.h already included, missing '#pragma once' in OptionalRepSkeletalMeshActor.h" #endif #define VREXPANSIONPLUGIN_OptionalRepSkeletalMeshActor_generated_h #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_37_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FSkeletalMeshComponentEndPhysicsTickFunctionVR_Statics; \ VREXPANSIONPLUGIN_API static class UScriptStruct* StaticStruct(); \ typedef FTickFunction Super; template<> VREXPANSIONPLUGIN_API UScriptStruct* StaticStruct<struct FSkeletalMeshComponentEndPhysicsTickFunctionVR>(); #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_SPARSE_DATA #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_RPC_WRAPPERS #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_RPC_WRAPPERS_NO_PURE_DECLS #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUNoRepSphereComponent(); \ friend struct Z_Construct_UClass_UNoRepSphereComponent_Statics; \ public: \ DECLARE_CLASS(UNoRepSphereComponent, USphereComponent, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/VRExpansionPlugin"), NO_API) \ DECLARE_SERIALIZER(UNoRepSphereComponent) \ void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; \ enum class ENetFields_Private : uint16 \ { \ NETFIELD_REP_START=(uint16)((int32)Super::ENetFields_Private::NETFIELD_REP_END + (int32)1), \ bReplicateMovement=NETFIELD_REP_START, \ NETFIELD_REP_END=bReplicateMovement }; \ NO_API virtual void ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const override; #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_INCLASS \ private: \ static void StaticRegisterNativesUNoRepSphereComponent(); \ friend struct Z_Construct_UClass_UNoRepSphereComponent_Statics; \ public: \ DECLARE_CLASS(UNoRepSphereComponent, USphereComponent, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/VRExpansionPlugin"), NO_API) \ DECLARE_SERIALIZER(UNoRepSphereComponent) \ void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; \ enum class ENetFields_Private : uint16 \ { \ NETFIELD_REP_START=(uint16)((int32)Super::ENetFields_Private::NETFIELD_REP_END + (int32)1), \ bReplicateMovement=NETFIELD_REP_START, \ NETFIELD_REP_END=bReplicateMovement }; \ NO_API virtual void ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const override; #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UNoRepSphereComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UNoRepSphereComponent) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UNoRepSphereComponent); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UNoRepSphereComponent); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UNoRepSphereComponent(UNoRepSphereComponent&&); \ NO_API UNoRepSphereComponent(const UNoRepSphereComponent&); \ public: #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UNoRepSphereComponent(UNoRepSphereComponent&&); \ NO_API UNoRepSphereComponent(const UNoRepSphereComponent&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UNoRepSphereComponent); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UNoRepSphereComponent); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UNoRepSphereComponent) #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_PRIVATE_PROPERTY_OFFSET #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_15_PROLOG #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_PRIVATE_PROPERTY_OFFSET \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_SPARSE_DATA \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_RPC_WRAPPERS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_INCLASS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_PRIVATE_PROPERTY_OFFSET \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_SPARSE_DATA \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_RPC_WRAPPERS_NO_PURE_DECLS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_INCLASS_NO_PURE_DECLS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_18_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> VREXPANSIONPLUGIN_API UClass* StaticClass<class UNoRepSphereComponent>(); #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_SPARSE_DATA #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_RPC_WRAPPERS #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_RPC_WRAPPERS_NO_PURE_DECLS #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUInversePhysicsSkeletalMeshComponent(); \ friend struct Z_Construct_UClass_UInversePhysicsSkeletalMeshComponent_Statics; \ public: \ DECLARE_CLASS(UInversePhysicsSkeletalMeshComponent, USkeletalMeshComponent, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/VRExpansionPlugin"), NO_API) \ DECLARE_SERIALIZER(UInversePhysicsSkeletalMeshComponent) \ void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; \ enum class ENetFields_Private : uint16 \ { \ NETFIELD_REP_START=(uint16)((int32)Super::ENetFields_Private::NETFIELD_REP_END + (int32)1), \ bReplicateMovement=NETFIELD_REP_START, \ NETFIELD_REP_END=bReplicateMovement }; \ NO_API virtual void ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const override; #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_INCLASS \ private: \ static void StaticRegisterNativesUInversePhysicsSkeletalMeshComponent(); \ friend struct Z_Construct_UClass_UInversePhysicsSkeletalMeshComponent_Statics; \ public: \ DECLARE_CLASS(UInversePhysicsSkeletalMeshComponent, USkeletalMeshComponent, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/VRExpansionPlugin"), NO_API) \ DECLARE_SERIALIZER(UInversePhysicsSkeletalMeshComponent) \ void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; \ enum class ENetFields_Private : uint16 \ { \ NETFIELD_REP_START=(uint16)((int32)Super::ENetFields_Private::NETFIELD_REP_END + (int32)1), \ bReplicateMovement=NETFIELD_REP_START, \ NETFIELD_REP_END=bReplicateMovement }; \ NO_API virtual void ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const override; #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UInversePhysicsSkeletalMeshComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UInversePhysicsSkeletalMeshComponent) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UInversePhysicsSkeletalMeshComponent); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UInversePhysicsSkeletalMeshComponent); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UInversePhysicsSkeletalMeshComponent(UInversePhysicsSkeletalMeshComponent&&); \ NO_API UInversePhysicsSkeletalMeshComponent(const UInversePhysicsSkeletalMeshComponent&); \ public: #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UInversePhysicsSkeletalMeshComponent(UInversePhysicsSkeletalMeshComponent&&); \ NO_API UInversePhysicsSkeletalMeshComponent(const UInversePhysicsSkeletalMeshComponent&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UInversePhysicsSkeletalMeshComponent); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UInversePhysicsSkeletalMeshComponent); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UInversePhysicsSkeletalMeshComponent) #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_PRIVATE_PROPERTY_OFFSET #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_57_PROLOG #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_PRIVATE_PROPERTY_OFFSET \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_SPARSE_DATA \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_RPC_WRAPPERS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_INCLASS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_PRIVATE_PROPERTY_OFFSET \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_SPARSE_DATA \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_RPC_WRAPPERS_NO_PURE_DECLS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_INCLASS_NO_PURE_DECLS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_60_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> VREXPANSIONPLUGIN_API UClass* StaticClass<class UInversePhysicsSkeletalMeshComponent>(); #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_SPARSE_DATA #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_RPC_WRAPPERS #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_RPC_WRAPPERS_NO_PURE_DECLS #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesAOptionalRepGrippableSkeletalMeshActor(); \ friend struct Z_Construct_UClass_AOptionalRepGrippableSkeletalMeshActor_Statics; \ public: \ DECLARE_CLASS(AOptionalRepGrippableSkeletalMeshActor, ASkeletalMeshActor, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/VRExpansionPlugin"), NO_API) \ DECLARE_SERIALIZER(AOptionalRepGrippableSkeletalMeshActor) \ void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; \ enum class ENetFields_Private : uint16 \ { \ NETFIELD_REP_START=(uint16)((int32)Super::ENetFields_Private::NETFIELD_REP_END + (int32)1), \ bIgnoreAttachmentReplication=NETFIELD_REP_START, \ bIgnorePhysicsReplication, \ NETFIELD_REP_END=bIgnorePhysicsReplication }; \ NO_API virtual void ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const override; #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_INCLASS \ private: \ static void StaticRegisterNativesAOptionalRepGrippableSkeletalMeshActor(); \ friend struct Z_Construct_UClass_AOptionalRepGrippableSkeletalMeshActor_Statics; \ public: \ DECLARE_CLASS(AOptionalRepGrippableSkeletalMeshActor, ASkeletalMeshActor, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/VRExpansionPlugin"), NO_API) \ DECLARE_SERIALIZER(AOptionalRepGrippableSkeletalMeshActor) \ void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; \ enum class ENetFields_Private : uint16 \ { \ NETFIELD_REP_START=(uint16)((int32)Super::ENetFields_Private::NETFIELD_REP_END + (int32)1), \ bIgnoreAttachmentReplication=NETFIELD_REP_START, \ bIgnorePhysicsReplication, \ NETFIELD_REP_END=bIgnorePhysicsReplication }; \ NO_API virtual void ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const override; #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API AOptionalRepGrippableSkeletalMeshActor(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AOptionalRepGrippableSkeletalMeshActor) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AOptionalRepGrippableSkeletalMeshActor); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AOptionalRepGrippableSkeletalMeshActor); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API AOptionalRepGrippableSkeletalMeshActor(AOptionalRepGrippableSkeletalMeshActor&&); \ NO_API AOptionalRepGrippableSkeletalMeshActor(const AOptionalRepGrippableSkeletalMeshActor&); \ public: #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API AOptionalRepGrippableSkeletalMeshActor(AOptionalRepGrippableSkeletalMeshActor&&); \ NO_API AOptionalRepGrippableSkeletalMeshActor(const AOptionalRepGrippableSkeletalMeshActor&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AOptionalRepGrippableSkeletalMeshActor); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AOptionalRepGrippableSkeletalMeshActor); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AOptionalRepGrippableSkeletalMeshActor) #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_PRIVATE_PROPERTY_OFFSET #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_93_PROLOG #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_PRIVATE_PROPERTY_OFFSET \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_SPARSE_DATA \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_RPC_WRAPPERS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_INCLASS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_PRIVATE_PROPERTY_OFFSET \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_SPARSE_DATA \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_RPC_WRAPPERS_NO_PURE_DECLS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_INCLASS_NO_PURE_DECLS \ VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h_96_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> VREXPANSIONPLUGIN_API UClass* StaticClass<class AOptionalRepGrippableSkeletalMeshActor>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID VRExpPluginExample_master_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Misc_OptionalRepSkeletalMeshActor_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
SitdikovRustam/CatBoost
contrib/libs/cxxsupp/libcxx/include/wrappers/math.h
#include "__wrappers_config" #include _LIBCXX_PROPER_HEADER(math.h)
jiucaihuanshe/jt_cms
jt-dubbo-web/src/main/java/com/jt/web/service/ItemServiceImpl.java
package com.jt.web.service; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.fasterxml.jackson.databind.ObjectMapper; import com.jt.common.service.HttpClientService; import com.jt.web.pojo.Item; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisClusterInfoCache; @Service public class ItemServiceImpl implements ItemService { @Autowired private HttpClientService httpClientService; private static ObjectMapper objectMapper = new ObjectMapper(); @Value("${ITEMKEY}") private String itemKey; //获取数据ITEM_ @Autowired private JedisCluster jedisCluster; /** * 前台项目没有连接数据库,所以查询操作依赖后台. * */ @Override public Item findItemById(Long itemId) { String uri = "http://manage.jt.com/web/item/"+itemId; Map<String, String> map = new HashMap<String,String>(); try { //通过后台查询Item对象的JSON数据 String restJSON = httpClientService.doPost(uri,map); Item item = objectMapper.readValue(restJSON,Item.class); return item; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 1.先查询缓存.如果缓存中有数据则先将JSON数据转化为对象之后返回 * 2.如果缓存中没有改数据,则先远程调用,之后将数据存入缓存中 * @param itemId * @return */ @Override public Item findItemByIdCache(Long itemId) { //形成唯一的标识 ITEM_1474391960 String key = itemKey+itemId; String jsonResult = jedisCluster.get(key); try { if(StringUtils.isEmpty(jsonResult)){ //进行远程调用 Item item = findItemById(itemId); String jsonData = objectMapper.writeValueAsString(item); jedisCluster.set(key, jsonData); return item; }else{ Item item = objectMapper.readValue(jsonResult, Item.class); return item; } } catch (Exception e) { e.printStackTrace(); } return null; } }
goutomroy/uva.onlinejudge
solved/mpi maelstone(423).cpp
<gh_stars>0 #include<stdio.h> #include<math.h> #include<stdlib.h> #include<string.h> #define big 200000 #define sz 150 void main() { long n,i,j,matrix[sz][sz],k,max; char ch[800],*ptr; while(scanf("%ld",&n)==1) { for(i=j=1;j<=n;j++,i++) matrix[i][j]=big; for(i=2;i<=n;i++) for(j=1;j<i;) { gets(ch); ptr=strtok(ch," "); while(ptr) { matrix[i][j]=matrix[j][i]= !strcmp(ptr,"x") ? big : atol(ptr); ptr=strtok(NULL," "); j++; } } for(k = 1; k <= n; k++) for(i = 1; i<=n; i++) for(j = 1; j <= n; j++) matrix[i][j] = (matrix[i][j]>(matrix[i][k]+matrix[k][j]) ) ? matrix[i][k]+matrix[k][j] : matrix[i][j]; max=0; for(i=2;i<=n;i++) if(matrix[i][1]>max) max=matrix[i][1]; printf("%ld\n",max); } }
wlhcode/lscct
src/L/L1480.cpp
<reponame>wlhcode/lscct<filename>src/L/L1480.cpp #include<cstdio> int main(){ int a; scanf("%d",&a); int n=a*a; int tmp; for(int clm=1;clm<=a;clm++){ for(int cout=clm;cout<=clm+(a-1)*a;cout+=a){ printf("%d",cout*a); if(cout!=clm+(a-1)*a) printf(" "); } printf("\n"); } }
hampld/newrelic-ruby-agent
test/new_relic/agent/transaction/external_request_segment_test.rb
<gh_stars>10-100 # encoding: utf-8 # This file is distributed under New Relic's license terms. # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. require File.expand_path(File.join(File.dirname(__FILE__),'..','..','..','test_helper')) require 'new_relic/agent/transaction' require 'new_relic/agent/transaction/external_request_segment' module NewRelic::Agent class Transaction class ExternalRequestSegmentTest < Minitest::Test class RequestWrapper attr_reader :headers def initialize headers = {} @headers = headers end def [] key @headers[key] end def []= key, value @headers[key] = value end def host_from_header self['host'] end def to_s headers.to_s # so logging request headers works as expected end end TRANSACTION_GUID = 'BEC1BC64675138B9' def setup @obfuscator = NewRelic::Agent::Obfuscator.new "jotorotoes" NewRelic::Agent.agent.stubs(:connected?).returns(true) NewRelic::Agent::CrossAppTracing.stubs(:obfuscator).returns(@obfuscator) NewRelic::Agent::CrossAppTracing.stubs(:valid_encoding_key?).returns(true) NewRelic::Agent.instance.span_event_aggregator.stubs(:enabled?).returns(true) nr_freeze_process_time end def teardown reset_buffers_and_caches end def test_generates_expected_name segment = ExternalRequestSegment.new "Typhoeus", "http://remotehost.com/blogs/index", "GET" assert_equal "External/remotehost.com/Typhoeus/GET", segment.name end def test_downcases_hostname segment = ExternalRequestSegment.new "Typhoeus", "http://ReMoTeHoSt.Com/blogs/index", "GET" assert_equal "External/remotehost.com/Typhoeus/GET", segment.name end def test_segment_does_not_record_metrics_outside_of_txn segment = ExternalRequestSegment.new "Net::HTTP", "http://remotehost.com/blogs/index", "GET" segment.finish refute_metrics_recorded [ "External/remotehost.com/Net::HTTP/GET", "External/all", "External/remotehost.com/all", "External/allWeb", ["External/remotehost.com/Net::HTTP/GET", "test"] ] end def test_segment_records_expected_metrics_for_non_cat_txn in_transaction "test", :category => :controller do segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.finish end expected_metrics = [ "External/remotehost.com/Net::HTTP/GET", "External/all", "External/remotehost.com/all", "External/allWeb", ["External/remotehost.com/Net::HTTP/GET", "test"] ] if Agent.config[:'distributed_tracing.enabled'] expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" end assert_metrics_recorded expected_metrics end def test_segment_records_noncat_metrics_when_cat_disabled request = RequestWrapper.new response = { 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) } with_config(cat_config.merge({:"cross_application_tracer.enabled" => false})) do in_transaction "test", :category => :controller do segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.add_request_headers request segment.process_response_headers response segment.finish end expected_metrics = [ "External/remotehost.com/Net::HTTP/GET", "External/all", "External/remotehost.com/all", "External/allWeb", ["External/remotehost.com/Net::HTTP/GET", "test"] ] if Agent.config[:'distributed_tracing.enabled'] expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" end assert_metrics_recorded expected_metrics end end def test_segment_records_noncat_metrics_without_valid_cross_process_id request = RequestWrapper.new response = { 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) } with_config(cat_config.merge({:cross_process_id => ''})) do in_transaction "test", :category => :controller do segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.add_request_headers request segment.process_response_headers response segment.finish end expected_metrics = [ "External/remotehost.com/Net::HTTP/GET", "External/all", "External/remotehost.com/all", "External/allWeb", ["External/remotehost.com/Net::HTTP/GET", "test"] ] if Agent.config[:'distributed_tracing.enabled'] expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" end assert_metrics_recorded expected_metrics end end def test_segment_records_noncat_metrics_without_valid_encoding_key CrossAppTracing.unstub(:valid_encoding_key?) request = RequestWrapper.new response = { 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) } with_config(cat_config.merge({:encoding_key => ''})) do in_transaction "test", :category => :controller do segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.add_request_headers request segment.process_response_headers response segment.finish end expected_metrics = [ "External/remotehost.com/Net::HTTP/GET", "External/all", "External/remotehost.com/all", "External/allWeb", ["External/remotehost.com/Net::HTTP/GET", "test"] ] if Agent.config[:'distributed_tracing.enabled'] expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" end assert_metrics_recorded expected_metrics end end def test_segment_records_expected_metrics_for_cat_transaction response = { 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) } with_config cat_config do in_transaction "test", :category => :controller do |txn| segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://newrelic.com/blogs/index", procedure: "GET" ) segment.process_response_headers response segment.finish end expected_metrics = [ "ExternalTransaction/newrelic.com/1#1884/txn-name", "ExternalApp/newrelic.com/1#1884/all", "External/all", "External/newrelic.com/all", "External/allWeb", ["ExternalTransaction/newrelic.com/1#1884/txn-name", "test"] ] if Agent.config[:'distributed_tracing.enabled'] expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" end assert_metrics_recorded expected_metrics end end def test_proper_metrics_recorded_for_distributed_trace_on_receiver with_config(:'distributed_tracing.enabled' => true, :trusted_account_key => 'trust_this!') do request = RequestWrapper.new payload = nil with_config account_id: "190", primary_application_id: "46954" do in_transaction do |txn| payload = txn.distributed_tracer.create_distributed_trace_payload end end NewRelic::Agent.drop_buffered_data transport_type = nil in_transaction "test_txn2", :category => :controller do |txn| txn.distributed_tracer.accept_distributed_trace_payload payload.text segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://newrelic.com/blogs/index", procedure: "GET" ) transport_type = txn.distributed_tracer.caller_transport_type segment.add_request_headers request segment.finish end expected_metrics = [ "External/all", "External/newrelic.com/all", "External/allWeb", "DurationByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/all", "DurationByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/allWeb", "TransportDuration/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/all", "TransportDuration/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/allWeb", ["External/newrelic.com/Net::HTTP/GET", "test_txn2"] ] assert_metrics_recorded expected_metrics end end def test_proper_metrics_recorded_for_distributed_trace_on_receiver_when_error_occurs with_config( :'distributed_tracing.enabled' => true, :trusted_account_key => 'trust_this') do request = RequestWrapper.new payload = nil with_config account_id: "190", primary_application_id: "46954" do in_transaction do |txn| payload = txn.distributed_tracer.create_distributed_trace_payload end end NewRelic::Agent.drop_buffered_data transport_type = nil in_transaction "test_txn2", :category => :controller do |txn| txn.distributed_tracer.accept_distributed_trace_payload payload.text segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://newrelic.com/blogs/index", procedure: "GET" ) transport_type = txn.distributed_tracer.caller_transport_type segment.add_request_headers request segment.finish NewRelic::Agent.notice_error StandardError.new("Sorry!") end expected_metrics = [ "External/all", "External/newrelic.com/all", "External/allWeb", "DurationByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/all", "DurationByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/allWeb", "TransportDuration/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/all", "TransportDuration/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/allWeb", "ErrorsByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/all", "ErrorsByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/allWeb", ["External/newrelic.com/Net::HTTP/GET", "test_txn2"] ] assert_metrics_recorded expected_metrics end end def test_segment_writes_outbound_request_headers request = RequestWrapper.new with_config cat_config do in_transaction :category => :controller do segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.add_request_headers request segment.finish end end assert request.headers.key?("X-NewRelic-ID"), "Expected to find X-NewRelic-ID header" assert request.headers.key?("X-NewRelic-Transaction"), "Expected to find X-NewRelic-Transaction header" end def test_segment_writes_outbound_request_headers_for_trace_context request = RequestWrapper.new with_config trace_context_config do in_transaction :category => :controller do segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.add_request_headers request segment.finish end end assert request.headers.key?("traceparent"), "Expected to find traceparent header" assert request.headers.key?("tracestate"), "Expected to find tracestate header" end def test_segment_writes_synthetics_header_for_synthetics_txn request = RequestWrapper.new with_config cat_config do in_transaction :category => :controller do |txn| txn.raw_synthetics_header = json_dump_and_encode [1, 42, 100, 200, 300] segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.add_request_headers request segment.finish end end assert request.headers.key?("X-NewRelic-Synthetics"), "Expected to find X-NewRelic-Synthetics header" end def test_add_request_headers_renames_segment_based_on_host_header request = RequestWrapper.new({"host" => "anotherhost.local"}) with_config cat_config do in_transaction :category => :controller do segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) assert_equal "External/remotehost.com/Net::HTTP/GET", segment.name segment.add_request_headers request assert_equal "External/anotherhost.local/Net::HTTP/GET", segment.name segment.finish end end end def test_read_response_headers_decodes_valid_appdata response = { 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) } with_config cat_config do in_transaction :category => :controller do |txn| segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.process_response_headers response segment.finish assert segment.cross_app_request? assert_equal "1#1884", segment.cross_process_id assert_equal "txn-name", segment.cross_process_transaction_name assert_equal "BEC1BC64675138B9", segment.transaction_guid end end end # Can pass :status_code and any HTTP code in headers to alter # default 200 (OK) HTTP status code def with_external_segment headers, config, segment_params segment = nil http_response = nil with_config config do in_transaction :category => :controller do |txn| segment = Tracer.start_external_request_segment(**segment_params) segment.add_request_headers headers http_response = mock_http_response headers segment.process_response_headers http_response yield if block_given? segment.finish end end return [segment, http_response] end def test_read_response_headers_ignores_invalid_appdata headers = { 'X-NewRelic-App-Data' => "this#is#not#valid#appdata" } segment_params = { library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" } segment, _http_response = with_external_segment(headers, cat_config, segment_params) refute segment.cross_app_request? assert_equal 200, segment.http_status_code assert_nil segment.cross_process_id assert_nil segment.cross_process_transaction_name assert_nil segment.transaction_guid end def test_sets_http_status_code_ok headers = { 'X-NewRelic-App-Data' => "this#is#not#valid#appdata", 'status_code' => 200, } segment_params = { library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" } segment, _http_response = with_external_segment(headers, cat_config, segment_params) assert_equal 200, segment.http_status_code refute_metrics_recorded "External/remotehost.com/Net::HTTP/GET/Error" end def test_unknown_response_records_supportability_metric response = { 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) } with_config trace_context_config do in_transaction :category => :controller do |txn| segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.process_response_headers response segment.finish refute segment.cross_app_request? refute segment.http_status_code, "No http_status_code expected!" end end expected_metrics = [ "External/remotehost.com/Net::HTTP/GET/MissingHTTPStatusCode", "External/remotehost.com/Net::HTTP/GET", "External/allWeb", ] assert_metrics_recorded expected_metrics end def test_sets_http_status_code_not_found headers = { 'X-NewRelic-App-Data' => "this#is#not#valid#appdata", 'status_code' => 404, } segment_params = { library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" } segment, _http_response = with_external_segment(headers, cat_config, segment_params) assert_equal 404, segment.http_status_code refute_metrics_recorded "External/remotehost.com/Net::HTTP/GET/MissingHTTPStatusCode" end def test_read_response_headers_ignores_invalid_cross_app_id response = { 'X-NewRelic-App-Data' => make_app_data_payload("not_an_ID", "txn-name", 2, 8, 0, TRANSACTION_GUID) } with_config cat_config do in_transaction :category => :controller do |txn| segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.process_response_headers response segment.finish refute segment.cross_app_request? assert_nil segment.cross_process_id assert_nil segment.cross_process_transaction_name assert_nil segment.transaction_guid end end end def test_uri_recorded_as_tt_attribute segment = nil uri = "http://newrelic.com/blogs/index" in_transaction :category => :controller do segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: uri, procedure: "GET" ) segment.finish end sample = last_transaction_trace node = find_node_with_name(sample, segment.name) assert_equal uri, node.params[:uri] end def test_guid_recorded_as_tt_attribute_for_cat_txn segment = nil response = { 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) } with_config cat_config do in_transaction :category => :controller do segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.process_response_headers response segment.finish end end sample = last_transaction_trace node = find_node_with_name(sample, segment.name) assert_equal TRANSACTION_GUID, node.params[:transaction_guid] end # --- get_request_metadata def test_get_request_metadata with_config cat_config.merge(:'cross_application_tracer.enabled' => true) do in_transaction do |txn| rmd = external_request_segment {|s| s.get_request_metadata} assert_instance_of String, rmd rmd = @obfuscator.deobfuscate rmd rmd = JSON.parse rmd assert_instance_of Hash, rmd assert_equal '269975#22824', rmd['NewRelicID'] assert_instance_of Array, rmd['NewRelicTransaction'] assert_equal txn.guid, rmd['NewRelicTransaction'][0] refute rmd['NewRelicTransaction'][1] assert_equal txn.distributed_tracer.cat_trip_id, rmd['NewRelicTransaction'][2] assert_equal txn.distributed_tracer.cat_path_hash, rmd['NewRelicTransaction'][3] refute rmd.key? 'NewRelicSynthetics' assert txn.distributed_tracer.is_cross_app_caller? end end end def test_get_request_metadata_with_cross_app_tracing_disabled with_config cat_config.merge(:'cross_application_tracer.enabled' => false) do in_transaction do |txn| rmd = external_request_segment {|s| s.get_request_metadata} refute rmd, "`get_request_metadata` should return nil with cross app tracing disabled" end end end def test_get_request_metadata_with_synthetics_header with_config cat_config do in_transaction do |txn| txn.raw_synthetics_header = 'raw_synth' rmd = external_request_segment {|s| s.get_request_metadata} rmd = @obfuscator.deobfuscate rmd rmd = JSON.parse rmd assert_equal 'raw_synth', rmd['NewRelicSynthetics'] end end end def test_get_request_metadata_not_in_transaction with_config cat_config do refute external_request_segment {|s| s.get_request_metadata} end end # --- process_response_metadata def test_process_response_metadata with_config cat_config do in_transaction do |txn| rmd = @obfuscator.obfuscate ::JSON.dump({ NewRelicAppData: [ NewRelic::Agent.config[:cross_process_id], 'Controller/root/index', 0.001, 0.5, 60, txn.guid ] }) segment = external_request_segment {|s| s.process_response_metadata rmd; s} assert_equal 'ExternalTransaction/example.com/269975#22824/Controller/root/index', segment.name end end end def test_process_response_metadata_not_in_transaction with_config cat_config do rmd = @obfuscator.obfuscate ::JSON.dump({ NewRelicAppData: [ NewRelic::Agent.config[:cross_process_id], 'Controller/root/index', 0.001, 0.5, 60, 'abcdef' ] }) segment = external_request_segment {|s| s.process_response_metadata rmd; s} assert_equal 'External/example.com/foo/get', segment.name end end def test_process_response_metadata_with_invalid_cross_app_id with_config cat_config do in_transaction do |txn| rmd = @obfuscator.obfuscate ::JSON.dump({ NewRelicAppData: [ 'bugz', 'Controller/root/index', 0.001, 0.5, 60, txn.guid ] }) segment = nil l = with_array_logger do segment = external_request_segment {|s| s.process_response_metadata rmd; s} end refute l.array.empty?, "process_response_metadata should log error on invalid ID" assert l.array.first =~ %r{invalid/non-trusted ID} assert_equal 'External/example.com/foo/get', segment.name end end end def test_process_response_metadata_with_untrusted_cross_app_id with_config cat_config do in_transaction do |txn| rmd = @obfuscator.obfuscate ::JSON.dump({ NewRelicAppData: [ '190#666', 'Controller/root/index', 0.001, 0.5, 60, txn.guid ] }) segment = nil l = with_array_logger do segment = external_request_segment {|s| s.process_response_metadata rmd; s} end refute l.array.empty?, "process_response_metadata should log error on invalid ID" assert l.array.first =~ %r{invalid/non-trusted ID} assert_equal 'External/example.com/foo/get', segment.name end end end # --- def test_segment_adds_distributed_trace_header distributed_tracing_config = { :'distributed_tracing.enabled' => true, :'cross_application_tracer.enabled' => false, :account_id => "190", :primary_application_id => "46954" } with_config(distributed_tracing_config) do request = RequestWrapper.new with_config cat_config.merge(distributed_tracing_config) do in_transaction :category => :controller do |txn| segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET" ) segment.add_request_headers request segment.finish end end assert request.headers.key?("newrelic"), "Expected to find newrelic header" end end def test_sets_start_time_from_api t = Process.clock_gettime(Process::CLOCK_REALTIME) in_transaction do |txn| segment = Tracer.start_external_request_segment( library: "Net::HTTP", uri: "http://remotehost.com/blogs/index", procedure: "GET", start_time: t ) segment.finish assert_equal t, segment.start_time end end def test_sampled_external_records_span_event with_config(distributed_tracing_config) do trace_id = nil txn_guid = nil sampled = nil priority = nil timestamp = nil segment = nil in_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) segment = ExternalRequestSegment.new "Typhoeus", "http://remotehost.com/blogs/index", "GET" txn.add_segment segment segment.start advance_process_time 1.0 segment.finish timestamp = Integer(segment.start_time * 1000.0) trace_id = txn.trace_id txn_guid = txn.guid sampled = txn.sampled? priority = txn.priority end last_span_events = NewRelic::Agent.agent.span_event_aggregator.harvest![1] assert_equal 2, last_span_events.size external_intrinsics, _, external_agent_attributes = last_span_events[0] root_span_event = last_span_events[1][0] root_guid = root_span_event['guid'] expected_name = 'External/remotehost.com/Typhoeus/GET' assert_equal 'Span', external_intrinsics.fetch('type') assert_equal trace_id, external_intrinsics.fetch('traceId') refute_nil external_intrinsics.fetch('guid') assert_equal root_guid, external_intrinsics.fetch('parentId') assert_equal txn_guid, external_intrinsics.fetch('transactionId') assert_equal sampled, external_intrinsics.fetch('sampled') assert_equal priority, external_intrinsics.fetch('priority') assert_equal timestamp, external_intrinsics.fetch('timestamp') assert_equal 1.0, external_intrinsics.fetch('duration') assert_equal expected_name, external_intrinsics.fetch('name') assert_equal segment.library, external_intrinsics.fetch('component') assert_equal segment.procedure, external_intrinsics.fetch('http.method') assert_equal 'http', external_intrinsics.fetch('category') assert_equal segment.uri.to_s, external_agent_attributes.fetch('http.url') end end def test_urls_are_filtered with_config(distributed_tracing_config) do segment = nil filtered_url = "https://remotehost.com/bar/baz" in_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) segment = ExternalRequestSegment.new "Typhoeus", "#{filtered_url}?a=1&b=2#fragment", "GET" txn.add_segment segment segment.start advance_process_time 1.0 segment.finish end last_span_events = NewRelic::Agent.agent.span_event_aggregator.harvest![1] assert_equal 2, last_span_events.size _, _, external_agent_attributes = last_span_events[0] assert_equal filtered_url, segment.uri.to_s assert_equal filtered_url, external_agent_attributes.fetch('http.url') end end def test_non_sampled_segment_does_not_record_span_event in_transaction('wat') do |txn| txn.stubs(:sampled?).returns(false) segment = ExternalRequestSegment.new "Typhoeus", "http://remotehost.com/blogs/index", "GET" txn.add_segment segment segment.start advance_process_time 1.0 segment.finish end last_span_events = NewRelic::Agent.agent.span_event_aggregator.harvest![1] assert_empty last_span_events end def test_non_sampled_segment_does_not_record_span_event in_transaction('wat') do |txn| txn.stubs(:ignore?).returns(true) segment = ExternalRequestSegment.new "Typhoeus", "http://remotehost.com/blogs/index", "GET" txn.add_segment segment segment.start advance_process_time 1.0 segment.finish end last_span_events = NewRelic::Agent.agent.span_event_aggregator.harvest![1] assert_empty last_span_events end def test_span_event_truncates_long_value with_config(distributed_tracing_config) do in_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) segment = NewRelic::Agent::Tracer.start_external_request_segment \ library: "Typhoeus", uri: "http://#{'a' * 300}.com", procedure: "GET" segment.finish end last_span_events = NewRelic::Agent.instance.span_event_aggregator.harvest![1] _, _, agent_attributes = last_span_events[0] assert_equal 255, agent_attributes['http.url'].bytesize assert_equal "http://#{'a' * 245}...", agent_attributes['http.url'] end end def cat_config { :cross_process_id => "269975#22824", :trusted_account_ids => [1,269975], :'cross_application_tracer.enabled' => true, :'distributed_tracing.enabled' => false, } end def distributed_tracing_config { :'distributed_tracing.enabled' => true, :'cross_application_tracer.enabled' => false, :'span_events.enabled' => true, } end def trace_context_config { :'distributed_tracing.enabled' => true, :'cross_application_tracer.enabled' => false, :account_id => "190", :primary_application_id => "46954", :trusted_account_key => "trust_this!" } end def make_app_data_payload( *args ) @obfuscator.obfuscate( args.to_json ) + "\n" end def external_request_segment segment = NewRelic::Agent::Tracer.start_external_request_segment( library: :foo, uri: 'http://example.com/root/index', procedure: :get ) v = yield segment segment.finish v end end end end
JrGoodle/djinni
test-suite/generated-src/java/com/dropbox/djinni/test/SetRecord.java
<filename>test-suite/generated-src/java/com/dropbox/djinni/test/SetRecord.java // AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from set.djinni package com.dropbox.djinni.test; import java.util.ArrayList; import java.util.HashSet; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; public class SetRecord implements android.os.Parcelable { /*package*/ final HashSet<String> mSet; /*package*/ final HashSet<Integer> mIset; public SetRecord( @Nonnull HashSet<String> set, @Nonnull HashSet<Integer> iset) { this.mSet = set; this.mIset = iset; } @Nonnull public HashSet<String> getSet() { return mSet; } @Nonnull public HashSet<Integer> getIset() { return mIset; } @Override public String toString() { return "SetRecord{" + "mSet=" + mSet + "," + "mIset=" + mIset + "}"; } public static final android.os.Parcelable.Creator<SetRecord> CREATOR = new android.os.Parcelable.Creator<SetRecord>() { @Override public SetRecord createFromParcel(android.os.Parcel in) { return new SetRecord(in); } @Override public SetRecord[] newArray(int size) { return new SetRecord[size]; } }; public SetRecord(android.os.Parcel in) { ArrayList<String> mSetTemp = new ArrayList<String>(); in.readList(mSetTemp, getClass().getClassLoader()); this.mSet = new HashSet<String>(mSetTemp); ArrayList<Integer> mIsetTemp = new ArrayList<Integer>(); in.readList(mIsetTemp, getClass().getClassLoader()); this.mIset = new HashSet<Integer>(mIsetTemp); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(android.os.Parcel out, int flags) { out.writeList(new ArrayList<String>(this.mSet)); out.writeList(new ArrayList<Integer>(this.mIset)); } }
eccenca/DataspaceConnector
src/main/java/io/dataspaceconnector/view/endpoint/GenericEndpointViewAssembler.java
<filename>src/main/java/io/dataspaceconnector/view/endpoint/GenericEndpointViewAssembler.java<gh_stars>0 /* * Copyright 2020 Fraunhofer Institute for Software and Systems Engineering * * 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 io.dataspaceconnector.view.endpoint; import java.util.UUID; import io.dataspaceconnector.controller.configuration.EndpointController; import io.dataspaceconnector.controller.resource.view.SelfLinking; import io.dataspaceconnector.controller.resource.view.ViewAssemblerHelper; import io.dataspaceconnector.model.endpoint.GenericEndpoint; import io.dataspaceconnector.view.datasource.DataSourceViewAssembler; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.stereotype.Component; /** * Assembles the REST resource for a generic endpoint. */ @Component public class GenericEndpointViewAssembler implements RepresentationModelAssembler<GenericEndpoint, GenericEndpointView>, SelfLinking { /** * Assembler for getting the url of the endpoint's datasource. */ @Autowired private DataSourceViewAssembler dataSourceViewAssembler; @Override public final Link getSelfLink(final UUID entityId) { return ViewAssemblerHelper.getSelfLink(entityId, EndpointController.class); } @Override public final GenericEndpointView toModel(final GenericEndpoint genericEndpoint) { final var modelMapper = new ModelMapper(); final var view = modelMapper.map(genericEndpoint, GenericEndpointView.class); view.add(getSelfLink(genericEndpoint.getId())); if (genericEndpoint.getDataSource() != null) { view.add(dataSourceViewAssembler.getSelfLink(genericEndpoint.getDataSource().getId()) .withRel("dataSource")); } return view; } }
wxwoods/mctorch
torch/nn/manifolds/manifold_factory.py
from .stiefel import Stiefel from .positive_definite import PositiveDefinite from .euclidean import Euclidean from ..parameter import Parameter class ManifoldShapeFactory(object): """ Base class for manifold shape factory. This is used by torch modules to determine shape of Manifolds give shape of weight matrix For each Manifold type it takes shape and whether to transpose the tensor when shape is vague (in instances when both transpose and normal are valid). To register a new factory implement a new subclass and create its object with manifold as parameter """ factories = {} @staticmethod def _addFactory(manifold, factory): ManifoldShapeFactory.factories[manifold] = factory @staticmethod def create_manifold_parameter(manifold, shape, transpose=False): if manifold not in ManifoldShapeFactory.factories: raise NotImplementedError return ManifoldShapeFactory.factories[manifold].create( shape, transpose) def __init__(self, manifold): self.manifold = manifold ManifoldShapeFactory._addFactory(manifold, self) # TODO: change return of create to manifold param and modified tensor if any def create(self, shape, transpose=False): raise NotImplementedError class StiefelLikeFactory(ManifoldShapeFactory): """ Stiefel like factory implements shape factory where tensor constrains are similar to that of Stiefel. Constraints: if 3D tensor (k,h,w): k > 1 and h > w > 1 if 2D tensor (h,w): h > w > 1 in case of h == w both normal and tranpose are valid and user has flexibility to choose if he wants (h x w) or (w x h) as manifold """ def create(self, shape, transpose=False): if len(shape) == 3: k, h, w = shape elif len(shape) == 2: k = 1 h, w = shape else: raise ValueError(("Invalid shape {}, length of shape " "tuple should be 2 or 3").format(shape)) to_transpose = transpose to_return = None if h > w: to_transpose = False to_return = Parameter(manifold=self.manifold(h, w, k=k)) elif h < w: to_transpose = True to_return = Parameter(manifold=self.manifold(w, h, k=k)) elif h == w: # use this argument only in case when shape is vague to_transpose = transpose to_return = Parameter(manifold=self.manifold(w, h, k=k)) return to_transpose, to_return class SquareManifoldFactory(ManifoldShapeFactory): """ Manifold shape factory for manifold constrained parameter which allows only for square shapes. For example PositiveDefinite manifold Constraints: if 3D tensor (k,n,n): k > 1 and n > 1 if 2D tensor (n,n): n > 1 """ def create(self, shape, transpose=False): if len(shape) == 3: k, n, m = shape elif len(shape) == 2: k = 1 n, m = shape else: raise ValueError(("Invalid shape {}, length of shape" "tuple should be 2 or 3").format(shape)) if n != m: raise ValueError(("Invalid shape {} dimensions should " "be equal").format(shape)) return transpose, Parameter(manifold=self.manifold(n=n, k=k)) class EuclideanManifoldFactory(ManifoldShapeFactory): """ Manifold factory fro euclidean just initializes parameter manifold with shape parameter of create without transpose """ def create(self, shape, transpose=False): if len(shape) == 0: raise ValueError("Shape length cannot be 0") else: return transpose, Parameter(manifold=self.manifold(*shape)) create_manifold_parameter = ManifoldShapeFactory.create_manifold_parameter StiefelLikeFactory(Stiefel) SquareManifoldFactory(PositiveDefinite) EuclideanManifoldFactory(Euclidean)
marcelocmedeiros/EstruturaSequencial
SomaSubtraMultiDivisPoten2QuocResto.py
# <NAME> # ADS UNIFIP 2020.1 # Patos-PB 17/03/2020 ''' Faça um Programa que peça dois números e imprima a soma, subtração, multiplicação, divisão, pontência, quociente e o resto. ''' # variáveis numericas num_1 = float(input('Digite o 1º número: ')) num_2 = float(input('Digite o 2º número: ')) # operadores matemáticos print(f'Soma de {num_1} + {num_2} =', num_1 + num_2) print(f'Subtração de {num_1} - {num_2} =', num_1 - num_2) print(f'Multiplicação de {num_1} * {num_2} =', num_1 * num_2) print(f'Divisão de {num_1} / {num_2} =', num_1 / num_2) print(f'Potência de {num_1} ** {num_2} =', num_1 ** num_2) print(f'Quociente de {num_1} // {num_2} =', num_1 // num_2) print(f'Resto de {num_1} % {num_2} =', num_1 % num_2)
hTangle/AlgorithmPractice
src/com/nevergetme/designmode/abstractfactory/listfactory/ListFactory.java
package com.nevergetme.designmode.abstractfactory.listfactory; import com.nevergetme.designmode.abstractfactory.factory.Factory; import com.nevergetme.designmode.abstractfactory.factory.Link; import com.nevergetme.designmode.abstractfactory.factory.Page; import com.nevergetme.designmode.abstractfactory.factory.Tray; public class ListFactory extends Factory{ @Override public Link createLink(String caption, String url) { return new ListLink(caption,url); } @Override public Tray createTray(String caption) { return new ListTray(caption); } @Override public Page createPage(String title, String author) { return new ListPage(title,author); } }
Zutubi/pulse
bundles/com.zutubi.pulse.core.commands.core/src/test/com/zutubi/pulse/core/commands/core/JUnitReportPostProcessorTest.java
<filename>bundles/com.zutubi.pulse.core.commands.core/src/test/com/zutubi/pulse/core/commands/core/JUnitReportPostProcessorTest.java /* Copyright 2017 Zutubi Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zutubi.pulse.core.commands.core; import com.zutubi.pulse.core.postprocessors.api.TestCaseResult; import com.zutubi.pulse.core.postprocessors.api.TestResult; import static com.zutubi.pulse.core.postprocessors.api.TestStatus.*; import com.zutubi.pulse.core.postprocessors.api.TestSuiteResult; import com.zutubi.pulse.core.postprocessors.api.XMLTestPostProcessorTestCase; import java.io.IOException; public class JUnitReportPostProcessorTest extends XMLTestPostProcessorTestCase { private JUnitReportPostProcessor pp = new JUnitReportPostProcessor(new JUnitReportPostProcessorConfiguration()); public void testSimple() throws Exception { TestSuiteResult tests = runProcessor("simple"); assertEquals(2, tests.getSuites().size()); checkWarning(tests.getSuites().get(0), "com.zutubi.pulse.junit.EmptyTest", 91, "No tests found"); TestSuiteResult suite = tests.getSuites().get(1); assertEquals("com.zutubi.pulse.junit.SimpleTest", suite.getName()); assertEquals(90, suite.getDuration()); TestCaseResult[] children = suite.getCases().toArray(new TestCaseResult[suite.getCases().size()]); assertEquals(3, children.length); assertEquals(new TestCaseResult("testSimple", 0, PASS), children[0]); assertEquals(new TestCaseResult("testAssertionFailure", 10, FAILURE, "junit.framework.AssertionFailedError: expected:<1> but was:<2>\n" + "\tat com.zutubi.pulse.junit.SimpleTest.testAssertionFailure(Unknown Source)"), children[1]); assertEquals(new TestCaseResult("testThrowException", 10, ERROR, "java.lang.RuntimeException: random message\n" + "\tat com.zutubi.pulse.junit.SimpleTest.testThrowException(Unknown Source)"), children[2]); } public void testRandomJunkIgnored() throws Exception { TestSuiteResult tests = runProcessor("testRandomJunkIgnored"); assertEquals(2, tests.getSuites().size()); checkWarning(tests.getSuites().get(0), "com.zutubi.pulse.junit.EmptyTest", 91, "No tests found"); TestSuiteResult suite = tests.getSuites().get(1); assertEquals("com.zutubi.pulse.junit.SimpleTest", suite.getName()); assertEquals(90, suite.getDuration()); TestCaseResult[] children = suite.getCases().toArray(new TestCaseResult[suite.getCases().size()]); assertEquals(3, children.length); assertEquals(new TestCaseResult("testSimple", (long) 0, PASS, null), children[0]); assertEquals(new TestCaseResult("testAssertionFailure", (long) 10, FAILURE, "junit.framework.AssertionFailedError: expected:<1> but was:<2>\n" + "\tat com.zutubi.pulse.junit.SimpleTest.testAssertionFailure(Unknown Source)"), children[1]); assertEquals(new TestCaseResult("testThrowException", (long) 10, ERROR, "java.lang.RuntimeException: random message\n" + "\tat com.zutubi.pulse.junit.SimpleTest.testThrowException(Unknown Source)"), children[2]); } public void testSingle() throws Exception { TestSuiteResult tests = runProcessor("single"); assertSingleSuite(tests); } public void testSuite() throws Exception { TestSuiteResult tests = runProcessor("suite"); assertEquals(274, tests.getTotal()); assertNotNull(tests.findSuite("com.zutubi.pulse.acceptance.AcceptanceTestSuite").findCase("com.zutubi.pulse.acceptance.LicenseAuthorisationAcceptanceTest.testAddProjectLinkOnlyAvailableWhenLicensed")); } public void testCustom() throws Exception { JUnitReportPostProcessorConfiguration ppConfig = pp.getConfig(); ppConfig.setSuiteElement("customtestsuite"); ppConfig.setCaseElement("customtestcase"); ppConfig.setFailureElement("customfailure"); ppConfig.setErrorElement("customerror"); ppConfig.setSkippedElement("customskipped"); ppConfig.setNameAttribute("customname"); ppConfig.setPackageAttribute("custompackage"); ppConfig.setTimeAttribute("customtime"); TestSuiteResult tests = runProcessor("custom"); assertSingleSuite(tests); } private void assertSingleSuite(TestSuiteResult tests) { assertEquals(1, tests.getSuites().size()); TestSuiteResult suite = tests.getSuites().get(0); assertEquals("com.zutubi.pulse.core.commands.core.JUnitReportPostProcessorTest", suite.getName()); assertEquals(391, suite.getDuration()); TestCaseResult[] children = suite.getCases().toArray(new TestCaseResult[suite.getCases().size()]); assertEquals(4, children.length); assertEquals(new TestCaseResult("testSimple", (long) 291, PASS, null), children[0]); assertEquals(new TestCaseResult("testSkipped", (long) 0, SKIPPED, null), children[1]); assertEquals(new TestCaseResult("testFailure", (long) 10, FAILURE, "junit.framework.AssertionFailedError\n" + "\tat\n" + " com.zutubi.pulse.core.commands.core.JUnitReportPostProcessorTest.testFailure(JUnitReportPostProcessorTest.java:63)"), children[2]); assertEquals(new TestCaseResult("testError", (long) 0, ERROR, "java.lang.RuntimeException: whoops!\n" + "\tat\n" + " com.zutubi.pulse.core.commands.core.JUnitReportPostProcessorTest.testError(JUnitReportPostProcessorTest.java:68)"), children[3]); } public void testNoMessage() throws Exception { TestSuiteResult tests = runProcessor("nomessage"); TestSuiteResult suite = tests.findSuite("com.zutubi.pulse.junit.NoMessages"); checkStatusCounts(suite, "com.zutubi.pulse.junit.NoMessages", 2, 2, 0, 0, 0); long duration1 = -1; assertEquals(new TestCaseResult("testFailureNoMessageAtAll", duration1, FAILURE, null), suite.findCase("testFailureNoMessageAtAll")); long duration = -1; assertEquals(new TestCaseResult("testFailureMessageInAttribute", duration, FAILURE, "this message only"), suite.findCase("testFailureMessageInAttribute")); } public void testNested() throws Exception { TestSuiteResult tests = runProcessor("nested"); TestSuiteResult suite = tests.findSuite("Outer"); assertNotNull(suite); checkStatusCounts(suite, "Outer", 2, 0, 0, 0, 0); TestSuiteResult nested = suite.findSuite("Nested"); checkStatusCounts(nested, "Nested", 2, 0, 0, 0, 0); long duration1 = -1; assertEquals(new TestCaseResult("test1", duration1, PASS, null), nested.findCase("test1")); long duration = -1; assertEquals(new TestCaseResult("test2", duration, PASS, null), nested.findCase("test2")); } public void testNoSuiteName() throws Exception { TestSuiteResult tests = runProcessor("nonamesuite"); assertEquals(0, tests.getSuites().size()); } private TestSuiteResult runProcessor(String name) throws IOException { return runProcessorAndGetTests(pp, name, EXTENSION_XML); } private void checkWarning(TestResult testResult, String name, long duration, String contents) { assertTrue(testResult instanceof TestSuiteResult); TestSuiteResult suite = (TestSuiteResult) testResult; assertEquals(name, suite.getName()); assertEquals(duration, suite.getDuration()); TestCaseResult[] children = suite.getCases().toArray(new TestCaseResult[suite.getCases().size()]); assertEquals(1, children.length); TestCaseResult caseResult = children[0]; assertEquals("warning", caseResult.getName()); assertEquals(10, caseResult.getDuration()); assertTrue(caseResult.getMessage().contains(contents)); } }
l33tdaima/l33tdaima
p633m/square_sum.js
<reponame>l33tdaima/l33tdaima<filename>p633m/square_sum.js /** * @param {number} c * @return {boolean} */ var judgeSquareSum = function (c) { let [a, b] = [0, ~~Math.sqrt(c)]; while (a <= b) { let p = a * a + b * b; if (p === c) { return true; } else if (p < c) { a++; } else { b--; } } return false; }; // TEST [ [5, true], [3, false], [4, true], [2, true], [1, true], ].forEach(([c, expected]) => { let actual = judgeSquareSum(c); console.log('Is', c, 'a square sum? ->', actual); console.assert(actual === expected); });
haikyuu/linkedom
test/html/script-element.js
const assert = require('../assert.js').for('HTMLScriptElement'); const {parseHTML} = global[Symbol.for('linkedom')]; const {document} = parseHTML('<!DOCTYPE html><html />'); let script = document.createElement('script'); script.setAttribute('what', 'ever'); script.appendChild(document.createTextNode('"')); assert(script.toString(), '<script what="ever">"</script>', 'text elements toString'); // Unrelated const {head} = document; head.innerHTML = `<nope csp-hash="any">"</nope>`; assert(document.toString(), '<!DOCTYPE html><html><head><nope csp-hash="any">&quot;</nope></head></html>', 'Issue #1 - <nope> node'); head.innerHTML = `<div csp-hash="any">"</div>`; assert(document.toString(), '<!DOCTYPE html><html><head><div csp-hash="any">&quot;</div></head></html>', 'Issue #1 - <div> node'); head.innerHTML = `<title csp-hash="any">"</title>`; assert(document.toString(), '<!DOCTYPE html><html><head><title csp-hash="any">"</title></head></html>', 'Issue #1 - <title> node'); head.innerHTML = `<style csp-hash="any">"</style>`; assert(document.toString(), '<!DOCTYPE html><html><head><style csp-hash="any">"</style></head></html>', 'Issue #1 - <style> node'); head.innerHTML = `<script csp-hash="any">"</script>`; assert(document.toString(), '<!DOCTYPE html><html><head><script csp-hash="any">"</script></head></html>', 'Issue #1 - <script> node'); head.innerHTML = `<textarea csp-hash="any">"</textarea>`; assert(document.toString(), '<!DOCTYPE html><html><head><textarea csp-hash="any">"</textarea></head></html>', 'Issue #1 - <textarea> node'); head.innerHTML = `<script type="application/ld+json">{}</script>`; head.querySelector("script").textContent = `{"change": true}`; assert(document.toString(), '<!DOCTYPE html><html><head><script type="application/ld+json">{"change": true}</script></head></html>', 'Issue #9 - <script> node'); head.innerHTML = `<script> <!--comment--> function test() { return html\`<div>\${'hello'}</div>\`; } </script>`; assert(head.toString(), `<head><script> <!--comment--> function test() { return html\`\${'hello'}\`; } </script></head>`, '<script>'); assert(head.firstChild.innerHTML, ` <!--comment--> function test() { return html\`\${'hello'}\`; } `, '<script>.innerHTML'); head.firstChild.innerHTML = 'html`<p>ok</p>`;'; assert(head.firstChild.innerHTML, 'html`<p>ok</p>`;', '<script>.innerHTML');
rsjtaylor/libadm
tests/xml_parser_audio_content_tests.cpp
<gh_stars>1-10 #include <catch2/catch.hpp> #include <sstream> #include "adm/document.hpp" #include "adm/elements/audio_content.hpp" #include "adm/parse.hpp" #include "adm/errors.hpp" TEST_CASE("xml_parser/audio_content") { using namespace adm; auto document = parseXml("xml_parser/audio_content.xml"); auto audioContent = document->lookup(parseAudioContentId("ACO_1001")); REQUIRE(audioContent->has<AudioContentName>() == true); REQUIRE(audioContent->has<AudioContentId>() == true); REQUIRE(audioContent->has<AudioContentLanguage>() == true); REQUIRE(audioContent->has<LoudnessMetadata>() == true); REQUIRE(audioContent->has<DialogueId>() == true); REQUIRE(audioContent->get<AudioContentName>() == "MyContent"); REQUIRE(audioContent->get<AudioContentId>().get<AudioContentIdValue>() == 0x1001u); REQUIRE(audioContent->get<AudioContentLanguage>() == "en"); REQUIRE(audioContent->get<DialogueId>() == Dialogue::DIALOGUE); REQUIRE(audioContent->get<DialogueContentKind>() == DialogueContent::VOICEOVER); } TEST_CASE("xml_parser/audio_content_duplicate_id") { REQUIRE_THROWS_AS(adm::parseXml("xml_parser/audio_content_duplicate_id.xml"), adm::error::XmlParsingDuplicateId); }
zealoussnow/chromium
remoting/host/mojom/remoting_mojom_traits.cc
<filename>remoting/host/mojom/remoting_mojom_traits.cc // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/mojom/remoting_mojom_traits.h" namespace mojo { // static bool mojo::StructTraits<remoting::mojom::ClipboardEventDataView, ::remoting::protocol::ClipboardEvent>:: Read(remoting::mojom::ClipboardEventDataView data_view, ::remoting::protocol::ClipboardEvent* out_event) { std::string mime_type; if (!data_view.ReadMimeType(&mime_type)) { return false; } out_event->set_mime_type(std::move(mime_type)); std::string data; if (!data_view.ReadData(&data)) { return false; } out_event->set_data(std::move(data)); return true; } } // namespace mojo
Starkteetje/dokoserver
src/main/java/doko/database/player/PlayerService.java
<reponame>Starkteetje/dokoserver<gh_stars>1-10 package doko.database.player; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import doko.lineup.LineUp; import doko.lineup.NamedLineUp; import doko.lineup.UnnamedLineUp; @Service public class PlayerService { private PlayerRepository playerRepository; public List<Player> getAllPlayers() { return playerRepository.findAll(); } public Optional<Player> getPlayer(Long id) { return Optional.ofNullable(playerRepository.findOne(id)); } public List<Player> getPlayersSortedById(List<Long> ids) { List<Player> players = playerRepository.findByIdIn(ids); players.sort(null); return players; } public Optional<Player> getPlayerByName(String playerName) { return Optional.ofNullable(playerRepository.findOneByName(playerName)); } public NamedLineUp getNamedLineUp(LineUp lineUp) { return new NamedLineUp(lineUp, this); } public NamedLineUp getNamedLineUp(String lineUpString) { return getNamedLineUp(new UnnamedLineUp(lineUpString)); } public NamedLineUp[] getNamedLineUps(LineUp[] lineUps) { return Arrays.stream(lineUps) .map(this::getNamedLineUp) .toArray(NamedLineUp[]::new); } public boolean addPlayer(String playerName) { Optional<Player> existingPlayer = getPlayerByName(playerName); if (existingPlayer.isPresent()) { return false; } else { Player player = new Player(playerName); playerRepository.save(player); return true; } } public boolean existsPlayer(String playerName) { return playerRepository.existsByName(playerName); } @Autowired public void setPlayerRepository(PlayerRepository playerRepository) { this.playerRepository = playerRepository; } }
chengciming/dns-server
dns_server_node/logic/broad.js
<reponame>chengciming/dns-server 'use strict'; const logger = require('../library/logger'); class Broad{ constructor(){ } /** * 获取主域名 * @param domain * @returns {string} */ getMainDomain(domain){ try{ let domainArray = domain.split('.'); return domainArray[domainArray.length-2]+'.'+domainArray[domainArray.length-1]; }catch (err){ console.log('Broad.getMainDomain'); logger.error(err); err = null; } } /** * 组建KEY路径 * @param redisSuffix * @param mainDomain * @param fullDomain * @returns {string} */ getFullKey(redisSuffix, mainDomain, fullDomain){ return redisSuffix+mainDomain+':'+fullDomain; } /** * 获取某个域名对应生效的所有KEY * @param redisObj * @param redisSuffix * @param domain * @returns {Promise<*>} */ async getKeys(redisObj, redisSuffix, domain){ try{ let mainDomain = this.getMainDomain(domain); let keys = await redisObj.keys(this.getFullKey(redisSuffix, mainDomain, '*')); if(!keys){ return false; } return keys; }catch (err){ console.log('Broad.getKeys'); logger.error(err); err = null; } return false; } /** * 获取KEY最后生效的域名规则 * @param key * @returns {*|string} */ getLastKeyRule(key){ try{ let keyArray = key.split(':'); return keyArray[keyArray.length-1]; }catch (err){ console.log('Broad.getLastKeyRule'); logger.error(err); err = null; } } /** * 组装泛解析域名: *.*.*.qq.com * @param domain * @param maxNum * @returns {*} */ parseBroadDomain(domain, maxNum){ try{ let domainArray = domain.split('.'); if(maxNum > domainArray.length - 2){ return false; } for(let i=0;i<maxNum+1;i++){ if(i >= domainArray.length-2){ break; } domainArray[i] = '*'; } let newDomain = domainArray.join('.'); if(domain === newDomain){ return false; //无变化则返回false } return newDomain; }catch (err){ console.log('Broad.parseBroadDomain'); logger.error(err); err = null; } return false; } /** * 获取域名对应命中的HOST key * @param redisObj * @param redisSuffix * @param domain * @returns {Promise<*>} */ async checkKey(redisObj, redisSuffix, domain){ try{ let keys = await this.getKeys(redisObj, redisSuffix, domain); if(!keys || keys.length <= 0){ return false; } let mainDomain = this.getMainDomain(domain); let domainArray = domain.split('.'); let fullKey = this.getFullKey(redisSuffix, mainDomain, domain); //检查完整域名域名匹配是否存在 if(keys.indexOf(fullKey) >= 0){ return fullKey; } //检查泛解析:带*号的域名,此检查固定多少段域名 for(let i = 0;i<domainArray.length-2;i++){ let broadDomain = this.parseBroadDomain(domain, i); if(broadDomain === false){ break; } fullKey = this.getFullKey(redisSuffix, mainDomain, broadDomain); if(keys.indexOf(fullKey) >= 0){ return fullKey; } } //检查双泛解析:带**号的域名,此检查不固定多少段域名 let i = 0, length = domainArray.length; while(i < length-2){ domainArray[0] = '**'; fullKey = this.getFullKey(redisSuffix, mainDomain, domainArray.join('.')); if(keys.indexOf(fullKey) >= 0){ return fullKey; } domainArray.shift(); i++; } }catch (err){ console.log('Broad.checkKey'); logger.error(err); err = null; } return false; } } module.exports = Broad;
doyaGu/C0501Q_HWJL01
sdk/doc/html/struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.js
<filename>sdk/doc/html/struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.js var struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g = [ [ "jClose_stream", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#acbdc50c6a5decd20d9cdeef1c8fcac8c", null ], [ "jControl", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#a98c93b531172c799fe250a764f57e956", null ], [ "jFree_mem", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#a678756b6552ddb3e68e9b20c527fe7cd", null ], [ "jFull_buf", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#ad8e516bdab3f14602cd0a1769f2c4b4b", null ], [ "jHeap_mem", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#a2cfa4c68c3e2aedfcf28814d2e5a095a", null ], [ "jOpen_stream", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#a276cb95f0d10d1ad3d40fdb66003b4e1", null ], [ "jOut_buf", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#abdb6094ff30df9dd72fc27902afbb4af", null ], [ "jSeek_stream", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#a022013ddc3b3aa78604feaaa754abc0b", null ], [ "jTell_stream", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#a9de41a9b540890de68cfc4921ca0e06c", null ], [ "streamType", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#a98a198dac5eb111f9349dd8e9c810fdc", null ], [ "typeName", "struct_j_p_g___s_t_r_e_a_m___d_e_s_c___t_a_g.html#ac1e158e496192cb715824f55540ea6de", null ] ];
jstormes/wp-search-with-algolia
js/instantsearch.js/dist-es5-module/src/widgets/hierarchical-menu/hierarchical-menu.js
<filename>js/instantsearch.js/dist-es5-module/src/widgets/hierarchical-menu/hierarchical-menu.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactDom = require('react-dom'); var _reactDom2 = _interopRequireDefault(_reactDom); var _utils = require('../../lib/utils.js'); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _autoHideContainer = require('../../decorators/autoHideContainer.js'); var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer); var _headerFooter = require('../../decorators/headerFooter.js'); var _headerFooter2 = _interopRequireDefault(_headerFooter); var _defaultTemplates = require('./defaultTemplates.js'); var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates); var _RefinementList = require('../../components/RefinementList/RefinementList.js'); var _RefinementList2 = _interopRequireDefault(_RefinementList); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var bem = (0, _utils.bemHelper)('ais-hierarchical-menu'); /** * Create a hierarchical menu using multiple attributes * @function hierarchicalMenu * @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget * @param {string[]} options.attributes Array of attributes to use to generate the hierarchy of the menu. * See the example for the convention to follow. * @param {number} [options.limit=10] How much facet values to get [*] * @param {string} [options.separator=">"] Separator used in the attributes to separate level values. [*] * @param {string} [options.rootPath] Prefix path to use if the first level is not the root level. * @param {string} [options.showParentLevel=false] Show the parent level of the current refined value * @param {string[]|Function} [options.sortBy=['name:asc']] How to sort refinements. Possible values: `count|isRefined|name:asc|name:desc`. * You can also use a sort function that behaves like the standard Javascript [compareFunction](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Syntax). * @param {Object} [options.templates] Templates to use for the widget * @param {string|Function} [options.templates.header=''] Header template (root level only) * @param {string|Function} [options.templates.item] Item template, provided with `name`, `count`, `isRefined`, `url` data properties * @param {string|Function} [options.templates.footer=''] Footer template (root level only) * @param {Function} [options.transformData.item] Method to change the object passed to the `item` template * @param {boolean} [options.autoHideContainer=true] Hide the container when there are no items in the menu * @param {Object} [options.cssClasses] CSS classes to add to the wrapping elements * @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element * @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element * @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element * @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element * @param {string|string[]} [options.cssClasses.list] CSS class to add to the list element * @param {string|string[]} [options.cssClasses.item] CSS class to add to each item element * @param {string|string[]} [options.cssClasses.depth] CSS class to add to each item element to denote its depth. The actual level will be appended to the given class name (ie. if `depth` is given, the widget will add `depth0`, `depth1`, ... according to the level of each item). * @param {string|string[]} [options.cssClasses.active] CSS class to add to each active element * @param {string|string[]} [options.cssClasses.link] CSS class to add to each link (when using the default template) * @param {string|string[]} [options.cssClasses.count] CSS class to add to each count element (when using the default template) * @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header * @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget * @return {Object} */ var usage = 'Usage:\nhierarchicalMenu({\n container,\n attributes,\n [ separator=\' > \' ],\n [ rootPath ],\n [ showParentLevel=true ],\n [ limit=10 ],\n [ sortBy=[\'name:asc\'] ],\n [ cssClasses.{root , header, body, footer, list, depth, item, active, link}={} ],\n [ templates.{header, item, footer} ],\n [ transformData.{item} ],\n [ autoHideContainer=true ],\n [ collapsible=false ]\n})'; function hierarchicalMenu() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, container = _ref.container, attributes = _ref.attributes, _ref$separator = _ref.separator, separator = _ref$separator === undefined ? ' > ' : _ref$separator, _ref$rootPath = _ref.rootPath, rootPath = _ref$rootPath === undefined ? null : _ref$rootPath, _ref$showParentLevel = _ref.showParentLevel, showParentLevel = _ref$showParentLevel === undefined ? true : _ref$showParentLevel, _ref$limit = _ref.limit, limit = _ref$limit === undefined ? 10 : _ref$limit, _ref$sortBy = _ref.sortBy, sortBy = _ref$sortBy === undefined ? ['name:asc'] : _ref$sortBy, _ref$cssClasses = _ref.cssClasses, userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses, _ref$autoHideContaine = _ref.autoHideContainer, autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine, _ref$templates = _ref.templates, templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates, _ref$collapsible = _ref.collapsible, collapsible = _ref$collapsible === undefined ? false : _ref$collapsible, transformData = _ref.transformData; if (!container || !attributes || !attributes.length) { throw new Error(usage); } var containerNode = (0, _utils.getContainerNode)(container); var RefinementList = (0, _headerFooter2.default)(_RefinementList2.default); if (autoHideContainer === true) { RefinementList = (0, _autoHideContainer2.default)(RefinementList); } // we need to provide a hierarchicalFacet name for the search state // so that we can always map $hierarchicalFacetName => real attributes // we use the first attribute name var hierarchicalFacetName = attributes[0]; var cssClasses = { root: (0, _classnames2.default)(bem(null), userCssClasses.root), header: (0, _classnames2.default)(bem('header'), userCssClasses.header), body: (0, _classnames2.default)(bem('body'), userCssClasses.body), footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer), list: (0, _classnames2.default)(bem('list'), userCssClasses.list), depth: bem('list', 'lvl'), item: (0, _classnames2.default)(bem('item'), userCssClasses.item), active: (0, _classnames2.default)(bem('item', 'active'), userCssClasses.active), link: (0, _classnames2.default)(bem('link'), userCssClasses.link), count: (0, _classnames2.default)(bem('count'), userCssClasses.count) }; return { getConfiguration: function getConfiguration(currentConfiguration) { return { hierarchicalFacets: [{ name: hierarchicalFacetName, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }], maxValuesPerFacet: currentConfiguration.maxValuesPerFacet !== undefined ? Math.max(currentConfiguration.maxValuesPerFacet, limit) : limit }; }, init: function init(_ref2) { var helper = _ref2.helper, templatesConfig = _ref2.templatesConfig; this._toggleRefinement = function (facetValue) { return helper.toggleRefinement(hierarchicalFacetName, facetValue).search(); }; this._templateProps = (0, _utils.prepareTemplateProps)({ transformData: transformData, defaultTemplates: _defaultTemplates2.default, templatesConfig: templatesConfig, templates: templates }); }, _prepareFacetValues: function _prepareFacetValues(facetValues, state) { var _this = this; return facetValues.slice(0, limit).map(function (subValue) { if (Array.isArray(subValue.data)) { subValue.data = _this._prepareFacetValues(subValue.data, state); } return subValue; }); }, render: function render(_ref3) { var results = _ref3.results, state = _ref3.state, createURL = _ref3.createURL; var facetValues = results.getFacetValues(hierarchicalFacetName, { sortBy: sortBy }).data || []; facetValues = this._prepareFacetValues(facetValues, state); // Bind createURL to this specific attribute function _createURL(facetValue) { return createURL(state.toggleRefinement(hierarchicalFacetName, facetValue)); } _reactDom2.default.render(_react2.default.createElement(RefinementList, { attributeNameKey: 'path', collapsible: collapsible, createURL: _createURL, cssClasses: cssClasses, facetValues: facetValues, shouldAutoHideContainer: facetValues.length === 0, templateProps: this._templateProps, toggleRefinement: this._toggleRefinement }), containerNode); } }; } exports.default = hierarchicalMenu;