hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
10d345d7819e06e500145ec92208ca1b9eb0c204
3,233
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.impl.root.component; import com.google.common.collect.Lists; import org.auraframework.Aura; import org.auraframework.def.ComponentDefRef; import org.auraframework.def.ComponentDefRefArray; import org.auraframework.instance.BaseComponent; import org.auraframework.instance.Component; import org.auraframework.service.InstanceService; import org.auraframework.system.AuraContext; import org.auraframework.throwable.quickfix.QuickFixException; import org.auraframework.util.json.Json; import org.auraframework.util.json.JsonSerializable; import java.io.IOException; import java.util.List; import java.util.Map; /** * An instance of an array of ComponentDefRefs along with the value provider they should be evaluated against. * * @since 0.22 */ public class ComponentDefRefArrayImpl implements JsonSerializable, ComponentDefRefArray { private final List<ComponentDefRef> cdrs; private final BaseComponent<?, ?> vp; public ComponentDefRefArrayImpl(List<ComponentDefRef> cdrs, BaseComponent<?, ?> vp) { this.cdrs = cdrs; this.vp = vp; } @Override public List<ComponentDefRef> getList() { return this.cdrs; } @Override public List<Component> newInstance(BaseComponent<?, ?> fallbackValueProvider) throws QuickFixException { return newInstance(fallbackValueProvider, null); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public List<Component> newInstance(BaseComponent<?, ?> fallbackValueProvider, Map<String, Object> extraProviders) throws QuickFixException { List<Component> components = Lists.newArrayListWithExpectedSize(cdrs.size()); BaseComponent<?, ?> valueProvider = this.vp != null ? this.vp : fallbackValueProvider; InstanceService instanceService = Aura.getInstanceService(); if (extraProviders != null) { // TODO: rename this thing valueProvider = new IterationValueProvider(valueProvider, extraProviders); } AuraContext context = Aura.getContextService().getCurrentContext(); int idx = 0; for (ComponentDefRef cdr : this.cdrs) { context.getInstanceStack().setAttributeIndex(idx); //components.add(cdr.newInstance(valueProvider)); components.add((Component) instanceService.getInstance(cdr, valueProvider)); context.getInstanceStack().clearAttributeIndex(idx); idx += 1; } return components; } @Override public void serialize(Json json) throws IOException { json.writeArray(cdrs); } }
37.593023
144
0.718528
34bb67ad9b248fe06396fc377a8c320349d940b8
2,859
/* * This file is part of GroupManager, licensed under the MIT License. * * Copyright (c) lucko (Luck) <[email protected]> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lucko.luckperms.sponge.service.events; import me.lucko.luckperms.sponge.LPSpongePlugin; import me.lucko.luckperms.sponge.service.model.LPSubjectData; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.EventContext; import org.spongepowered.api.event.cause.EventContextKeys; import org.spongepowered.api.event.impl.AbstractEvent; import org.spongepowered.api.event.permission.SubjectDataUpdateEvent; import org.spongepowered.api.service.permission.SubjectData; public class LPSubjectDataUpdateEvent extends AbstractEvent implements SubjectDataUpdateEvent { private final LPSpongePlugin plugin; private final LPSubjectData subjectData; public LPSubjectDataUpdateEvent(LPSpongePlugin plugin, LPSubjectData subjectData) { this.plugin = plugin; this.subjectData = subjectData; } @Override public SubjectData getUpdatedData() { return this.subjectData.sponge(); } public LPSubjectData getLuckPermsUpdatedData() { return this.subjectData; } @Override public @NonNull Cause getCause() { EventContext eventContext = EventContext.builder() .add(EventContextKeys.PLUGIN, this.plugin.getBootstrap().getPluginContainer()) .build(); return Cause.builder() .append(this.plugin.getService()) .append(this.plugin.getService().sponge()) .append(this.plugin.getBootstrap().getPluginContainer()) .build(eventContext); } }
40.842857
95
0.736621
7717a043fe4ad2ed6b3d730c1e10487f47af7e83
2,651
package org.vaadin.maps.client.ui.featurecontainer; import com.google.gwt.event.dom.client.*; import com.vaadin.client.ComponentConnector; import com.vaadin.client.ConnectorHierarchyChangeEvent; import com.vaadin.client.MouseEventDetailsBuilder; import com.vaadin.shared.MouseEventDetails; import com.vaadin.shared.ui.Connect; import org.vaadin.maps.client.DateUtility; import org.vaadin.maps.client.ui.VVectorFeatureContainer; import org.vaadin.maps.shared.ui.featurecontainer.VectorFeatureContainerServerRpc; import java.util.List; /** * @author Kamil Morong */ @Connect(org.vaadin.maps.ui.featurecontainer.VectorFeatureContainer.class) public class VectorFeatureContainerConnector extends AbstractFeatureContainerConnector implements ClickHandler, MouseDownHandler, MouseMoveHandler { private boolean mouseDown = false; private boolean mouseMoved = false; @Override protected void init() { super.init(); getWidget().addClickHandler(this); getWidget().addMouseDownHandler(this); getWidget().addMouseMoveHandler(this); } @Override public VVectorFeatureContainer getWidget() { return (VVectorFeatureContainer) super.getWidget(); } @Override public void onConnectorHierarchyChange(ConnectorHierarchyChangeEvent connectorHierarchyChangeEvent) { List<ComponentConnector> previousChildren = connectorHierarchyChangeEvent.getOldChildren(); List<ComponentConnector> children = getChildComponents(); VVectorFeatureContainer container = getWidget(); for (ComponentConnector previousChild : previousChildren) { if (!children.contains(previousChild)) { container.remove(previousChild.getWidget()); } } for (ComponentConnector child : children) { if (!previousChildren.contains(child)) { container.add(child.getWidget()); } } } @Override public void onClick(ClickEvent event) { if (!mouseMoved) { MouseEventDetails mouseDetails = MouseEventDetailsBuilder.buildMouseEventDetails(event.getNativeEvent(), getWidget().getElement()); getRpcProxy(VectorFeatureContainerServerRpc.class).click(DateUtility.getTimestamp(), mouseDetails); } else { mouseMoved = false; } mouseDown = false; } @Override public void onMouseDown(MouseDownEvent event) { mouseDown = true; } @Override public void onMouseMove(MouseMoveEvent event) { if (mouseDown) { mouseMoved = true; } } }
32.329268
116
0.696341
60eb5bad7d979bd8b42442a8285aa1c6ffb47dea
2,815
package com.tomaszpolanski.androidsandbox.commonandroid; import com.google.auto.value.AutoValue; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import polanski.option.Option; import static polanski.option.Option.ofObj; /** * Represents testable version of {@link android.content.Intent} */ @AutoValue public abstract class IntentImmutable { /** * Returns an {@link Option} of value that is located under given key * * @param key Key that expected value should be located under * @return If key exists, then returns {@link Option} of value * otherwise NONE */ @NonNull public Option<Object> extra(@NonNull final String key) { return bundle().getObject(key); } /** * Returns flags set to intent */ public abstract int flags(); /** * {@link BundleImmutable} of the intent. */ @NonNull public abstract IBundle bundle(); /** * Uri intent data */ @NonNull public abstract Option<String> data(); @NonNull public static IntentImmutable create(final int flags, @NonNull final IBundle bundle, @NonNull final Option<String> data) { return new AutoValue_IntentImmutable(flags, bundle, data); } /** * Builder for {@link IntentImmutable} */ @SuppressWarnings("ReturnOfThis") public static final class Builder { private int mFlags; @NonNull private final BundleImmutable.Builder mBundleBuilder = BundleImmutable.Builder.builder(); @Nullable private String mData; @NonNull public IntentImmutable build() { return create(mFlags, mBundleBuilder.build(), ofObj(mData)); } /** * Prepares flags for the intent * * @param flags Flags to be put to intent */ @NonNull public Builder withFlags(final int flags) { mFlags = flags; return this; } /** * Prepares key, value pair to be inserted into {@link IntentImmutable} * * @param key Key for the translateLanguageCodeOnce * @param value Value for the value */ @NonNull public Builder withExtra(@NonNull final String key, @NonNull final Object value) { mBundleBuilder.put(key, value); return this; } /** * Uri data of the intent, see {@link android.content.Intent} * * @param data Uri data */ @NonNull public Builder withData(@Nullable final String data) { mData = data; return this; } } }
25.590909
97
0.580817
1dc4ff122c2ba8c92dc1ca8a289e50783e98b482
1,155
package net.somethingdreadful.MAL.api.response; import net.somethingdreadful.MAL.api.MALApi; import java.io.Serializable; import lombok.Getter; import lombok.Setter; /* * Base stub class for relations returned by API like side stories, sequels etc. * It contains both manga_id and anime_id to make it usable as response class for deserialization * through retrofit. Only one of those variables is set to a valid value. */ public class RecordStub implements Serializable { private int anime_id = 0; private int manga_id = 0; @Getter @Setter private String title; @Getter @Setter private String url; public void setId(int id, MALApi.ListType type) { this.anime_id = type.equals(MALApi.ListType.ANIME) ? id : 0; this.manga_id = type.equals(MALApi.ListType.MANGA) ? id : 0; } public int getId() { if (anime_id > 0) return anime_id; else return manga_id; } public MALApi.ListType getType() { if (anime_id > 0) return MALApi.ListType.ANIME; if (manga_id > 0) return MALApi.ListType.MANGA; return null; } }
28.170732
97
0.665801
709c6d07a5efc5eee1e1d1556ebb6a14b8ac3d8c
580
package org.wlf.filedownloader.file_download.db_recorder; import org.wlf.filedownloader.base.Status; /** * record status * <br/> * 记录状态接口 * * @author wlf(Andy) * @email [email protected] */ public interface Record { /** * record status * * @param url download url * @param status record status,ref{@link Status} * @param increaseSize increased size since last record * @throws Exception any fail exception during recording status */ void recordStatus(String url, int status, int increaseSize) throws Exception; }
23.2
81
0.668966
ef3d759793662a7246fa084cd4af8a4163295068
7,353
/* * Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client; import com.hazelcast.client.impl.EntryListenerManager; import com.hazelcast.core.EntryListener; import com.hazelcast.core.MultiMap; import com.hazelcast.core.Prefix; import com.hazelcast.impl.ClusterOperation; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import static com.hazelcast.client.ProxyHelper.check; public class MultiMapClientProxy<K, V> implements MultiMap<K, V>, EntryHolder { private final String name; private final ProxyHelper proxyHelper; private final HazelcastClient client; public MultiMapClientProxy(HazelcastClient client, String name) { this.name = name; this.proxyHelper = new ProxyHelper(name, client); this.client = client; } public String getName() { return name.substring(Prefix.MULTIMAP.length()); } public void addLocalEntryListener(EntryListener<K, V> listener) { throw new UnsupportedOperationException("client doesn't support local entry listener"); } public void addEntryListener(EntryListener<K, V> listener, boolean includeValue) { addEntryListener(listener, null, includeValue); } public void addEntryListener(EntryListener<K, V> listener, K key, boolean includeValue) { check(listener); Boolean noEntryListenerRegistered = entryListenerManager().noListenerRegistered(key, name, includeValue); if (noEntryListenerRegistered == null) { proxyHelper.doOp(ClusterOperation.REMOVE_LISTENER, key, null); noEntryListenerRegistered = Boolean.TRUE; } if (noEntryListenerRegistered.booleanValue()) { Call c = entryListenerManager().createNewAddListenerCall(proxyHelper, key, includeValue); proxyHelper.doCall(c); } entryListenerManager().registerListener(name, key, includeValue, listener); } public void removeEntryListener(EntryListener<K, V> listener) { check(listener); proxyHelper.doOp(ClusterOperation.REMOVE_LISTENER, null, null); entryListenerManager().removeListener(name, null, listener); } public void removeEntryListener(EntryListener<K, V> listener, K key) { check(listener); check(key); proxyHelper.doOp(ClusterOperation.REMOVE_LISTENER, key, null); entryListenerManager().removeListener(name, key, listener); } private EntryListenerManager entryListenerManager() { return client.getListenerManager().getEntryListenerManager(); } public void lock(K key) { ProxyHelper.check(key); doLock(ClusterOperation.CONCURRENT_MAP_LOCK, key, -1, null); } public boolean tryLock(K key) { check(key); return (Boolean) doLock(ClusterOperation.CONCURRENT_MAP_LOCK, key, 0, null); } public boolean tryLock(K key, long time, TimeUnit timeunit) { check(key); ProxyHelper.checkTime(time, timeunit); return (Boolean) doLock(ClusterOperation.CONCURRENT_MAP_LOCK, key, time, timeunit); } private Object doLock(ClusterOperation operation, Object key, long timeout, TimeUnit timeUnit) { Packet request = proxyHelper.prepareRequest(operation, key, timeUnit); request.setTimeout(timeout); Packet response = proxyHelper.callAndGetResult(request); return proxyHelper.getValue(response); } public void unlock(K key) { check(key); proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_UNLOCK, key, null); } public boolean lockMap(long time, TimeUnit timeunit) { ProxyHelper.checkTime(time, timeunit); return (Boolean) doLock(ClusterOperation.CONCURRENT_MAP_LOCK_MAP, null, time, timeunit); } public void unlockMap() { doLock(ClusterOperation.CONCURRENT_MAP_UNLOCK_MAP, null, -1, null); } public boolean put(K key, V value) { check(key); check(value); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_PUT_MULTI, key, value); } public Collection get(Object key) { check(key); return (Collection) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_GET, key, null); } public boolean remove(Object key, Object value) { check(key); check(value); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_REMOVE_MULTI, key, value); } public Collection remove(Object key) { check(key); return (Collection) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_REMOVE_MULTI, key, null); } public Set<K> localKeySet() { throw new UnsupportedOperationException(); } public Set keySet() { final Collection<Object> collection = proxyHelper.keys(null); LightKeySet<Object> set = new LightKeySet<Object>(this, new HashSet<Object>(collection)); return set; } public Collection values() { Set<Map.Entry> set = entrySet(); return new ValueCollection(this, set); } public Set entrySet() { Set<Object> keySet = keySet(); return new LightMultiMapEntrySet<Object, Collection>(keySet, this, getInstanceType()); } public boolean containsKey(Object key) { check(key); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_CONTAINS_KEY, key, null); } public boolean containsValue(Object value) { check(value); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_CONTAINS_VALUE, null, value); } public boolean containsEntry(Object key, Object value) { check(key); check(value); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_CONTAINS_VALUE, key, value); } public int size() { return (Integer) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_SIZE, null, null); } public void clear() { Set keys = keySet(); for (Object key : keys) { remove(key); } } public int valueCount(Object key) { check(key); return (Integer) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_VALUE_COUNT, key, null); } public InstanceType getInstanceType() { return InstanceType.MULTIMAP; } public void destroy() { proxyHelper.destroy(); } public Object getId() { return name; } @Override public boolean equals(Object o) { if (o instanceof MultiMap) { return getName().equals(((MultiMap) o).getName()); } return false; } @Override public int hashCode() { return getName().hashCode(); } }
32.973094
113
0.681083
2d8da94ec6da164383316d50866b76001ecfa8bd
9,688
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.gemfire.repository.config; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Optional; import org.junit.Test; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.parsing.PassThroughSourceExtractor; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlReaderContext; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.data.gemfire.mapping.annotation.Region; import org.springframework.data.gemfire.repository.GemfireRepository; import org.springframework.data.gemfire.repository.support.GemfireRepositoryFactoryBean; import org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource; import org.springframework.data.repository.config.XmlRepositoryConfigurationSource; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Unit Tests for {@link GemfireRepositoryConfigurationExtension}. * * @author John Blum * @see org.junit.Test * @see org.mockito.Mockito * @see org.springframework.data.gemfire.repository.config.GemfireRepositoryConfigurationExtension * @since 1.6.3 */ public class GemfireRepositoryConfigurationExtensionUnitTests { private GemfireRepositoryConfigurationExtension repositoryConfigurationExtension = new GemfireRepositoryConfigurationExtension(); private Object getPropertyValue(BeanDefinitionBuilder builder, String propertyName) { return getPropertyValue(builder.getRawBeanDefinition(), propertyName); } private Object getPropertyValue(BeanDefinition beanDefinition, String propertyName) { PropertyValue propertyValue = beanDefinition.getPropertyValues().getPropertyValue(propertyName); return (propertyValue != null ? propertyValue.getValue() : null); } private Element mockElement() { Element mockElement = mock(Element.class); NodeList mockNodeList = mock(NodeList.class); when(mockNodeList.getLength()).thenReturn(0); when(mockElement.getChildNodes()).thenReturn(mockNodeList); return mockElement; } private Environment mockEnvironment() { return mock(Environment.class); } private ParserContext mockParserContext() { XmlReaderContext readerContext = mockXmlReaderContext(); BeanDefinitionParserDelegate parserDelegate = newBeanDefinitionParserDelegate(readerContext); return new ParserContext(readerContext, parserDelegate); } private XmlReaderContext mockXmlReaderContext() { BeanDefinitionRegistry mockRegistry = mock(BeanDefinitionRegistry.class); ResourceLoader mockResourceLoader = mock(ResourceLoader.class); XmlBeanDefinitionReader beanDefinitionReader = spy(new XmlBeanDefinitionReader(mockRegistry)); when(mockResourceLoader.getClassLoader()).thenReturn(Thread.currentThread().getContextClassLoader()); when(beanDefinitionReader.getResourceLoader()).thenReturn(mockResourceLoader); return new XmlReaderContext(null, null, null, new PassThroughSourceExtractor(), beanDefinitionReader, null); } private BeanDefinitionParserDelegate newBeanDefinitionParserDelegate(XmlReaderContext readerContext) { return new BeanDefinitionParserDelegate(readerContext); } @Test public void identifyingAnnotationsIncludesRegionAnnotation() { Collection<Class<? extends Annotation>> identifyingAnnotations = this.repositoryConfigurationExtension.getIdentifyingAnnotations(); assertThat(identifyingAnnotations).isNotNull(); assertThat(identifyingAnnotations).contains(Region.class); } @Test public void identifyingTypesIncludesGemfireRepositoryType() { Collection<Class<?>> identifyingTypes = this.repositoryConfigurationExtension.getIdentifyingTypes(); assertThat(identifyingTypes).isNotNull(); assertThat(identifyingTypes).contains(GemfireRepository.class); } @Test public void modulePrefixIsGemFire() { assertThat(this.repositoryConfigurationExtension.getModulePrefix()).isEqualTo("gemfire"); } @Test public void repositoryFactoryBeanClassNameIsGemfireRepositoryFactoryBean() { assertThat(this.repositoryConfigurationExtension.getRepositoryFactoryBeanClassName()) .isEqualTo(GemfireRepositoryFactoryBean.class.getName()); } @Test public void postProcessWithAnnotationRepositoryConfigurationSource() { AnnotationRepositoryConfigurationSource mockRepositoryConfigurationSource = mock(AnnotationRepositoryConfigurationSource.class); doReturn(Optional.of("testMappingContext")) .when(mockRepositoryConfigurationSource).getAttribute(eq("mappingContextRef")); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(); this.repositoryConfigurationExtension.postProcess(beanDefinitionBuilder, mockRepositoryConfigurationSource); Object mappingContextRef = getPropertyValue(beanDefinitionBuilder, "gemfireMappingContext"); assertThat(mappingContextRef).isInstanceOf(RuntimeBeanReference.class); assertThat(((RuntimeBeanReference) mappingContextRef).getBeanName()).isEqualTo("testMappingContext"); verify(mockRepositoryConfigurationSource, times(1)) .getAttribute(eq("mappingContextRef")); verifyNoMoreInteractions(mockRepositoryConfigurationSource); } @Test public void postProcessWithAnnotationRepositoryConfigurationSourceHavingNoMappingContextRefAttribute() { AnnotationRepositoryConfigurationSource mockRepositoryConfigurationSource = mock(AnnotationRepositoryConfigurationSource.class); doReturn(Optional.empty()).when(mockRepositoryConfigurationSource).getAttribute(eq("mappingContextRef")); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(); this.repositoryConfigurationExtension.postProcess(beanDefinitionBuilder, mockRepositoryConfigurationSource); Object mappingContextRef = getPropertyValue(beanDefinitionBuilder, "gemfireMappingContext"); assertThat(mappingContextRef).isInstanceOf(RuntimeBeanReference.class); assertThat(((RuntimeBeanReference) mappingContextRef).getBeanName()) .isEqualTo(GemfireRepositoryConfigurationExtension.DEFAULT_MAPPING_CONTEXT_BEAN_NAME); verify(mockRepositoryConfigurationSource, times(1)) .getAttribute(eq("mappingContextRef")); verifyNoMoreInteractions(mockRepositoryConfigurationSource); } @Test public void postProcessWithXmlRepositoryConfigurationSource() { Element mockElement = mockElement(); doReturn("testMappingContext") .when(mockElement).getAttribute(eq("mapping-context-ref")); XmlRepositoryConfigurationSource repositoryConfigurationSource = new XmlRepositoryConfigurationSource(mockElement, mockParserContext(), mockEnvironment()); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(); this.repositoryConfigurationExtension.postProcess(beanDefinitionBuilder, repositoryConfigurationSource); Object mappingContextRef = getPropertyValue(beanDefinitionBuilder, "gemfireMappingContext"); assertThat(mappingContextRef).isInstanceOf(RuntimeBeanReference.class); assertThat(((RuntimeBeanReference) mappingContextRef).getBeanName()).isEqualTo("testMappingContext"); verify(mockElement, times(1)).getAttribute(eq("mapping-context-ref")); } @Test public void postProcessWithXmlRepositoryConfigurationSourceHavingNoMappingContextRefAttribute() { Element mockElement = mockElement(); doReturn(null).when(mockElement).getAttribute(eq("mapping-context-ref")); XmlRepositoryConfigurationSource repositoryConfigurationSource = new XmlRepositoryConfigurationSource(mockElement, mockParserContext(), mockEnvironment()); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(); this.repositoryConfigurationExtension.postProcess(beanDefinitionBuilder, repositoryConfigurationSource); Object mappingContextRef = getPropertyValue(beanDefinitionBuilder, "gemfireMappingContext"); assertThat(mappingContextRef).isInstanceOf(RuntimeBeanReference.class); assertThat(((RuntimeBeanReference) mappingContextRef).getBeanName()) .isEqualTo(GemfireRepositoryConfigurationExtension.DEFAULT_MAPPING_CONTEXT_BEAN_NAME); verify(mockElement, times(1)).getAttribute(eq("mapping-context-ref")); } }
39.222672
110
0.831338
cbc2d01913b02b898fc86d6ee1b3ab507bc6fae3
4,028
/* * Copyright 2021 Tamás Balog * * 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.picimako.gherkin; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; import java.util.List; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.testFramework.fixtures.BasePlatformTestCase; import com.picimako.gherkin.toolwindow.BDDTestSupport; /** * Unit test for {@link DefaultJBehaveStoryService}. */ public class DefaultJBehaveStoryServiceTest extends BasePlatformTestCase { private JBehaveStoryService storyService; @Override public void setUp() throws Exception { super.setUp(); storyService = new DefaultJBehaveStoryService(getProject()); } @Override protected String getTestDataPath() { return "testdata/features"; } //collectMetasFromFile public void testCollectMetasFromFile() { PsiFile storyFile = myFixture.configureByText("story.story", "Meta:\n" + "@Suite smoke\n" + "@Browser firefox chrome\n" + "@Jira\n" + "\n" + "Scenario:\n" + "\n" + "Meta:\n" + "@Suite smoke\n" + "\n" + "Scenario:"); var metas = storyService.collectMetasFromFile(storyFile); assertThat(metas.entrySet()).hasSize(4); } public void testCollectNoMetasFromFileWithNoMetas() { PsiFile storyFile = myFixture.configureByText("story.story", "Scenario:"); var metas = storyService.collectMetasFromFile(storyFile); assertThat(metas.isEmpty()).isTrue(); } //collectMetasFromFileAsList public void testCollectMetasFromFileAsList() { PsiFile storyFile = myFixture.configureByText("story.story", "Meta:\n" + "@Suite smoke\n" + "@Browser firefox chrome\n" + "@Jira\n" + "\n" + "Scenario:\n" + "\n" + "Meta:\n" + "@Suite smoke\n" + "\n" + "Scenario:"); List<String> metas = storyService.collectMetasFromFileAsList(storyFile); assertThat(metas).contains("Suite:smoke", "Browser:firefox chrome", "Jira", "Suite:smoke"); } public void testCollectNoMetasFromFileWithNoMetasAsList() { PsiFile storyFile = myFixture.configureByText("story.story", "Scenario:"); List<String> metas = storyService.collectMetasFromFileAsList(storyFile); assertThat(metas).isEmpty(); } //collectMetaTextsForMetaKeyAsList public void testCollectsMetaTextsForMetaKeyAsList() { PsiFile storyFile = myFixture.configureByFile("Another story.story"); Collection<PsiElement> metaTexts = storyService.collectMetaTextsForMetaKeyAsList( BDDTestSupport.getFirstMetaKeyForName(storyFile, "@Media")); assertThat(metaTexts).isNotEmpty(); assertThat(metaTexts).extracting(PsiElement::getText).containsExactly("youtube", "vimeo"); } public void testReturnsEmptyListIfThereIsNoMetaTextForMetaKey() { PsiFile storyFile = myFixture.configureByFile("Story.story"); Collection<PsiElement> metaTexts = storyService.collectMetaTextsForMetaKeyAsList( BDDTestSupport.getFirstMetaKeyForName(storyFile, "@Disabled")); assertThat(metaTexts).isEmpty(); } }
32.224
99
0.647468
e29d12256b8d13dbc6a2a85e72a6c5f2aa7dfcc2
8,566
/** * 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.activemq.apollo.broker; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import javax.transaction.xa.Xid; import org.fusesource.hawtbuf.Buffer; import org.fusesource.hawtbuf.DataByteArrayOutputStream; /** * An implementation of JTA transaction identifier (javax.transaction.xa.Xid). */ public class XidImpl implements Xid, Cloneable, java.io.Serializable { private static final long serialVersionUID = -5363901495878210611L; private static final Buffer EMPTY_BUFFER = new Buffer(new byte[]{}); // The format identifier for the XID. A value of -1 indicates the NULLXID private int formatId = -1; // default format Buffer globalTransactionId = EMPTY_BUFFER; Buffer branchQualifier = EMPTY_BUFFER; /////////////////////////////// Constructors ///////////////////////////// /** * Constructs a new null XID. * <p> * After construction the data within the XID should be initialized. */ public XidImpl() { } public XidImpl(int formatID, byte[] globalTxnID, byte[] branchID) { this.formatId = formatID; setGlobalTransactionId(globalTxnID); setBranchQualifier(branchID); } public XidImpl(int formatID, Buffer globalTransactionId, Buffer branchQualifier) { this.formatId = formatID; this.globalTransactionId = globalTransactionId; this.branchQualifier=branchQualifier; } /** * Initialize an XID using another XID as the source of data. * * @param from * the XID to initialize this XID from */ public XidImpl(Xid from) { if ((from == null) || (from.getFormatId() == -1)) { formatId = -1; setGlobalTransactionId(null); setBranchQualifier(null); } else { formatId = from.getFormatId(); setGlobalTransactionId(from.getGlobalTransactionId()); setBranchQualifier(from.getBranchQualifier()); } } // used for test purpose public XidImpl(String globalTxnId, String branchId) { this(99, globalTxnId.getBytes(), branchId.getBytes()); } //////////// Public Methods ////////////// /** * Determine whether or not two objects of this type are equal. * * @param o * the other XID object to be compared with this XID. * * @return Returns true of the supplied object represents the same global * transaction as this, otherwise returns false. */ public boolean equals(Object o) { if (o.getClass() != XidImpl.class) return false; XidImpl other = (XidImpl) o; if (formatId == -1 && other.formatId == -1) return true; return formatId == other.formatId && globalTransactionId.equals(other.globalTransactionId) && branchQualifier.equals(other.branchQualifier); } /** * Compute the hash code. * * @return the computed hashcode */ public int hashCode() { if (formatId == -1) return (-1); return formatId ^ globalTransactionId.hashCode() ^ branchQualifier.hashCode(); } /** * Return a string representing this XID. * <p> * This is normally used to display the XID when debugging. * * @return the string representation of this XID */ public String toString() { String gtString = new String(getGlobalTransactionId()); String brString = new String(getBranchQualifier()); return new String("{Xid: " + "formatID=" + formatId + ", " + "gtrid[" + globalTransactionId.length + "]=" + gtString + ", " + "brid[" + branchQualifier.length + "]=" + brString + "}"); } /** * Obtain the format identifier part of the XID. * * @return Format identifier. -1 indicates a null XID */ public int getFormatId() { return formatId; } /** * Returns the global transaction identifier for this XID. * * @return the global transaction identifier */ public byte[] getGlobalTransactionId() { // TODO.. may want to compact() first and keep cache that.. return globalTransactionId.toByteArray(); } /** * Returns the branch qualifier for this XID. * * @return the branch qualifier */ public byte[] getBranchQualifier() { // TODO.. may want to compact() first and keep cache that.. return branchQualifier.toByteArray(); } ///////////////////////// private methods //////////////////////////////// /** * Set the branch qualifier for this XID. Note that the branch qualifier has * a maximum size. * * @param branchID * a Byte array containing the branch qualifier to be set. If the * size of the array exceeds MAXBQUALSIZE, only the first * MAXBQUALSIZE elements of qual will be used. */ private void setBranchQualifier(byte[] branchID) { if (branchID == null) { branchQualifier = EMPTY_BUFFER; } else { int length = branchID.length > MAXBQUALSIZE ? MAXBQUALSIZE : branchID.length; // TODO: Do we really need to copy the bytes?? branchQualifier = new Buffer(new byte[length]); System.arraycopy(branchID, 0, branchQualifier.data, 0, length); } } private void setGlobalTransactionId(byte[] globalTxnID) { if (globalTxnID == null) { globalTransactionId = EMPTY_BUFFER; } else { int length = globalTxnID.length > MAXGTRIDSIZE ? MAXGTRIDSIZE : globalTxnID.length; // TODO: Do we really need to copy the bytes?? globalTransactionId = new Buffer(new byte[length]); System.arraycopy(globalTxnID, 0, globalTransactionId.data, 0, length); } } public int getMemorySize() { return 4 // formatId + 4 // length of globalTxnId + globalTransactionId.length // globalTxnId + 4 // length of branchId + branchQualifier.length; // branchId } /** * Writes this XidImpl's data to the DataOutput destination * * @param out The DataOutput destination */ public void writebody(DataOutput out) throws IOException { out.writeInt(formatId); // format ID out.writeInt(globalTransactionId.length); // length of global Txn ID out.write(globalTransactionId.data, globalTransactionId.offset, globalTransactionId.length); // global transaction ID out.writeInt(branchQualifier.length); // length of branch ID out.write(branchQualifier.data, branchQualifier.offset, branchQualifier.length); // branch ID } /** * read xid from an Array and set each fields. * * @param in * the data input array * @throws IOException */ public void readbody(DataInput in) throws IOException { formatId = in.readInt(); int length = in.readInt(); byte[] data = new byte[length]; in.readFully(data); setGlobalTransactionId(data); length = in.readInt(); data = new byte[length]; in.readFully(data); setBranchQualifier(data); } /** * @param xid * @return */ public static Buffer toBuffer(Xid xid) { XidImpl x = new XidImpl(xid); DataByteArrayOutputStream baos = new DataByteArrayOutputStream(x.getMemorySize()); try { x.writebody(baos); } catch (IOException e) { //Shouldn't happen: throw new RuntimeException(e); } return baos.toBuffer(); } } // class XidImpl
33.20155
192
0.616157
7c403ca49d3ac34c82160a0006823cc6272c1838
7,784
/* * Copyright 2021 Ben Manes. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.benmanes.caffeine.cache.simulator.policy.greedy_dual; import static com.github.benmanes.caffeine.cache.simulator.policy.Policy.Characteristic.WEIGHTED; import static com.google.common.base.Preconditions.checkState; import java.util.LinkedHashSet; import java.util.NavigableSet; import java.util.Set; import java.util.TreeSet; import com.github.benmanes.caffeine.cache.simulator.BasicSettings; import com.github.benmanes.caffeine.cache.simulator.policy.AccessEvent; import com.github.benmanes.caffeine.cache.simulator.policy.Policy; import com.github.benmanes.caffeine.cache.simulator.policy.Policy.PolicySpec; import com.github.benmanes.caffeine.cache.simulator.policy.PolicyStats; import com.google.common.base.MoreObjects; import com.typesafe.config.Config; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; /** * Greedy Dual Size Frequency (GDSF) algorithm. * <p> * The algorithm is explained by the authors in * <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.304.6514&rep=rep1&type=pdf"> * Improving Web Servers and Proxies Performance with GDSF Caching Policies</a> and * <a href="http://web.cs.iastate.edu/~ciardo/pubs/2001HPCN-GreedyDualFreqSize.pdf">Role of Aging, * Frequency, and Size in Web Cache Replacement Policies</a>. * * @author [email protected] (Ben Manes) */ @PolicySpec(name = "greedy-dual.Gdsf", characteristics = WEIGHTED) public final class GdsfPolicy implements Policy { private final NavigableSet<Node> priorityQueue; private final Long2ObjectMap<Node> data; private final PolicyStats policyStats; private final long maximumSize; double clock; long size; public GdsfPolicy(Config config) { var settings = new BasicSettings(config); policyStats = new PolicyStats(name()); data = new Long2ObjectOpenHashMap<>(); maximumSize = settings.maximumSize(); priorityQueue = new TreeSet<>(); } @Override public PolicyStats stats() { return policyStats; } @Override public void record(AccessEvent event) { Node node = data.get(event.key()); if (node == null) { policyStats.recordWeightedMiss(event.weight()); onMiss(event); } else { policyStats.recordWeightedHit(event.weight()); onHit(event, node); size += (event.weight() - node.weight); node.weight = event.weight(); if (size > maximumSize) { evict(node); } } } private void onHit(AccessEvent event, Node node) { // If the request for f is a hit, f is served out of cache and: // – Used and Clock do not change // – Fr(f) is increased by one // – Pr(f) is updated using Eq. 1 and f is moved accordingly in the queue checkState(priorityQueue.remove(node), "%s not found in priority queue", node.key); node.frequency++; node.priority = priorityOf(event, node.frequency); priorityQueue.add(node); } private double priorityOf(AccessEvent event, int frequency) { // As defined in "Improving Web Servers and Proxies Performance with GDSF Caching Policies" double cost = event.isPenaltyAware() ? event.missPenalty() : 1.0; return clock + frequency * (cost / event.weight()); } private void onMiss(AccessEvent event) { // If the request for f is a miss, we need to decide whether to cache f or not: // – Fr(f) is set to one. // – Pr(f) is computed using Eq. 1 and f is enqueued accordingly. // – Used is increased by Size(f). Node candidate = new Node(event.key(), event.weight(), priorityOf(event, 1)); data.put(candidate.key, candidate); priorityQueue.add(candidate); size += candidate.weight; if (size <= maximumSize) { policyStats.recordAdmission(); } else { evict(candidate); } } private void evict(Node candidate) { // If Used > Total, not all files fit in the cache. First, we identify the smallest set // {f1, f2, ... fk} of files to evict, which have the lowest priority and satisfy // (Used − sum(f1 ... fk)) <= Total var victims = getVictims(size - maximumSize); if (victims.contains(candidate)) { // If f is among {f1, f2, ... fk}, it is simply not cached and removed from the priority // queue, while none of the files already in the cache is evicted. This happens when the value // of Pr(f) is so low that it would put f (if cached) among the first candidates for // replacement, e.g. when the file size is very large. Thus the proposed procedure will // automatically limit the cases when such files are cached policyStats.recordRejection(); remove(candidate); } else { // If f is not among {f1, f2, ... fk}: // - Clock is set to max priority(f1 ... fk) // - Used is decreased by sum(f1 ... fk) // - f1 ... fk are evicted // - f is cached policyStats.recordAdmission(); for (var victim : victims) { if (victim.priority > clock) { clock = victim.priority; } remove(victim); } } checkState(size <= maximumSize); } private Set<Node> getVictims(long weightDifference) { long weightedSize = 0L; var victims = new LinkedHashSet<Node>(); for (Node node : priorityQueue) { victims.add(node); weightedSize += node.weight; if (weightedSize >= weightDifference) { break; } } return victims; } private void remove(Node node) { policyStats.recordEviction(); priorityQueue.remove(node); data.remove(node.key); size -= node.weight; } @Override public void finished() { checkState(size <= maximumSize, "%s > %s", size, maximumSize); long weightedSize = data.values().stream().mapToLong(node -> node.weight).sum(); checkState(weightedSize == size, "%s != %s", weightedSize, size); checkState(priorityQueue.size() == data.size(), "%s != %s", priorityQueue.size(), data.size()); checkState(priorityQueue.containsAll(data.values()), "Data != PriorityQueue"); } private static final class Node implements Comparable<Node> { final long key; double priority; int frequency; int weight; public Node(long key, int weight, double priority) { this.priority = priority; this.weight = weight; this.frequency = 1; this.key = key; } @Override public int compareTo(Node node) { int result = Double.compare(priority, node.priority); return (result == 0) ? Long.compare(key, node.key) : result; } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (!(o instanceof Node)) { return false; } var node = (Node) o; return (key == node.key) && (priority == node.priority); } @Override public int hashCode() { return Long.hashCode(key); } @Override public String toString() { return MoreObjects.toStringHelper(Node.class) .add("key", key) .add("weight", weight) .add("priority", priority) .add("frequency", frequency) .toString(); } } }
33.551724
100
0.667652
2b795f01d74ebf522d4e2747593816f65123b899
1,013
package embedded.kookmin.ac.kr.projectopensource; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity";//db @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Intent intent = new Intent(this, SlideActivity.class); TextView textView = (TextView) findViewById(R.id.textView); textView.setText("Choose which one you gonna want."); Button bRecent = (Button) findViewById(R.id.bt_recent); bRecent.setOnClickListener(new View.OnClickListener() { //버튼을 클릭하여 다음 엑티비티로 이동. @Override public void onClick(View v) { startActivity(intent); } }); } }
31.65625
87
0.692991
d71a1d6d49ef9ecd150807e60f4a53b5efd7442f
1,066
package start.spring.jdbc.service; import org.springframework.stereotype.Service; import start.spring.jdbc.dao.UserDao; import start.spring.jdbc.entity.User; import javax.annotation.Resource; import java.util.List; /** * @auther: Meruem117 */ @Service public class UserService { @Resource private UserDao userDao; public void addUser(User user) { userDao.add(user); } public void updateUser(User user) { userDao.update(user); } public void deleteUser(int id) { userDao.delete(id); } public int selectCount() { return userDao.selectCount(); } public User getUserById(int id) { return userDao.getUserById(id); } public List<User> getUserList() { return userDao.getUserList(); } public void batchAdd(List<Object[]> list) { userDao.batchAdd(list); } public void batchUpdate(List<Object[]> list) { userDao.batchUpdate(list); } public void batchDelete(List<Object[]> list) { userDao.batchDelete(list); } }
19.740741
50
0.643527
a0c43f2224161b7175f00927ce52e8da9c898dd9
1,139
package problems.java.strings; public class CountAndSay { static String countAndSay(int n) { StringBuilder sb = new StringBuilder(); String s = String.valueOf(n); int count = 1; char lastChar = s.charAt(0); for(int i = 1; i < s.length(); ++i) { if(s.charAt(i) == lastChar) { count++; } else { sb.append(count); sb.append(lastChar); lastChar = s.charAt(i); count = 1; } } sb.append(count); sb.append(lastChar); return sb.toString(); } static boolean testsPass() { String h = countAndSay(121); boolean check = countAndSay(121).equals("111211"); if(!check) { return false; } return true; } public static void main(String... args) { if(testsPass()) { System.out.println("Tests passed"); } else { System.out.println("Tests failed"); } } }
20.709091
58
0.442493
2d98a9e360a37c402fbd5930fdd5ff894b6d3c61
16,284
/* * Copyright [2013-2021], Alibaba Group Holding Limited * * 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.alibaba.polardbx.atom; import com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl; import com.alibaba.druid.proxy.jdbc.DataSourceProxy; import com.alibaba.polardbx.atom.utils.EncodingUtils; import com.alibaba.polardbx.common.constants.ServerVariables; import com.alibaba.polardbx.common.exception.TddlRuntimeException; import com.alibaba.polardbx.common.exception.code.ErrorCode; import com.alibaba.polardbx.common.utils.GeneralUtil; import com.alibaba.polardbx.common.utils.TStringUtil; import com.alibaba.polardbx.common.utils.logger.Logger; import com.alibaba.polardbx.common.utils.logger.LoggerFactory; import com.google.common.collect.Sets; import org.apache.commons.lang.StringUtils; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Struct; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.concurrent.Executor; public class TAtomConnectionProxy extends ConnectionProxyImpl { private static final Logger logger = LoggerFactory.getLogger(TAtomConnectionProxy.class); private Map<String, Object> currentGlobalServerVariables; final private Map<String, Object> sessionVariables; final private Map<String, Object> sessionVariablesChanged = new HashMap<String, Object>(); private String encoding; final private Connection connection; final private long mysqlConnectionId; public TAtomConnectionProxy(DataSourceProxy dataSource, Connection connection, Properties properties, long id, Map<String, Object> serverVariables, Map<String, Object> globalServerVariables, long mysqlConnectionId) throws SQLException { super(dataSource, connection, properties, id); this.sessionVariables = serverVariables; this.currentGlobalServerVariables = globalServerVariables; this.encoding = EncodingUtils.getEncoding(connection); this.connection = connection; this.mysqlConnectionId = mysqlConnectionId; } private void setVariables(Map<String, Object> newVariables, boolean isGlobal) throws SQLException { Map<String, Object> serverVariables = null; Set<String> serverVariablesNeedToRemove = Sets.newHashSet(); if (!isGlobal) { for (String key : sessionVariablesChanged.keySet()) { // 这个连接没设置过的变量,需要用global值复原 if (newVariables.containsKey(key)) { continue; } if (serverVariables == null) { serverVariables = new HashMap<String, Object>(newVariables); // 已经全部小写 } if (currentGlobalServerVariables.containsKey(key)) { serverVariables.put(key, currentGlobalServerVariables.get(key)); } else { serverVariablesNeedToRemove.add(key); } } } else { this.currentGlobalServerVariables = new HashMap<>(currentGlobalServerVariables); } if (serverVariables == null) { serverVariables = newVariables; // 已经全部小写 } boolean first = true; List<Object> parmas = new ArrayList<Object>(); StringBuilder query = new StringBuilder("SET "); // 对比要设的值和已有的值,相同则跳过,不同则设成新值 Map<String, Object> tmpVariablesChanged = new HashMap<String, Object>(); for (Entry<String, Object> entry : serverVariables.entrySet()) { String key = entry.getKey(); // 已经全部小写 Object newValue = entry.getValue(); // 不处理 DRDS 自定义的系统变量 if (ServerVariables.extraVariables.contains(key)) { continue; } // 处理采用变量赋值的情况如 : // set sql_mode=@@sql_mode; // set sql_mode=@@global.sql_mode; // set sql_mode=@@session.sql_mode; if (newValue instanceof String) { String newValueStr = (String) newValue; if (newValueStr.startsWith("@@")) { String newValueLC = newValueStr.toLowerCase(); String keyRef; if (newValueLC.startsWith("@@session.")) { keyRef = newValueLC.substring("@@session.".length()); newValue = this.sessionVariables.get(keyRef); } else if (newValueLC.startsWith("@@global.")) { keyRef = newValueLC.substring("@@global.".length()); newValue = this.currentGlobalServerVariables.get(keyRef); } else { keyRef = newValueLC.substring("@@".length()); newValue = this.currentGlobalServerVariables.get(keyRef); } } else if ("default".equalsIgnoreCase(newValueStr)) { newValue = this.currentGlobalServerVariables.get(key); } } String newValueStr = String.valueOf(newValue); Object oldValue = isGlobal ? this.currentGlobalServerVariables.get(key) : this.sessionVariables.get(key); if (oldValue != null) { String oldValuesStr = String.valueOf(oldValue); if (TStringUtil.equalsIgnoreCase(newValueStr, oldValuesStr)) { // skip same value continue; } else if (StringUtils.isEmpty(newValueStr) && "NULL".equalsIgnoreCase(oldValuesStr)) { // skip same value continue; } else if (StringUtils.isEmpty(oldValuesStr) && "NULL".equalsIgnoreCase(newValueStr)) { // skip same value continue; } } if (!first) { query.append(" , "); } else { first = false; } boolean isBoth = ServerVariables.isMysqlBoth(key); if (isGlobal) { query.append(" GLOBAL "); } StringBuilder tmpQuery = new StringBuilder(" , "); query.append("`").append(key).append("`="); tmpQuery.append("`").append(key).append("`="); if (TStringUtil.isParsableNumber(newValueStr)) { // 纯数字类型 query.append(newValueStr); tmpQuery.append(newValueStr); } else if ("NULL".equalsIgnoreCase(newValueStr) || newValue == null || StringUtils.isEmpty(newValueStr)) { // NULL或空字符串类型 if (ServerVariables.canExecByBoth.contains(key) || ServerVariables.canOnlyExecByNullVariables .contains(key)) { query.append("NULL"); tmpQuery.append("NULL"); } else if (ServerVariables.canOnlyExecByEmptyStrVariables.contains(key)) { query.append("''"); tmpQuery.append("''"); } else { throw new TddlRuntimeException(ErrorCode.ERR_VARIABLE_CAN_NOT_SET_TO_NULL_FOR_NOW, key); } } else { // 字符串兼容类型 query.append("?"); parmas.add(newValue); if (isBoth) { tmpQuery.append("?"); parmas.add(newValue); } } if (isBoth) { query.append(tmpQuery); } tmpVariablesChanged.put(key, newValue); } for (String key : serverVariablesNeedToRemove) { if (!first) { query.append(", "); } query.append("@").append(key).append("=").append("NULL"); } if (!first) { // 需要确保SET指令是完整的, 而不是只有一个SET前缀. PreparedStatement ps = null; try { ps = this.getConnectionRaw().prepareStatement(query.toString()); if (!GeneralUtil.isEmpty(parmas)) { for (int i = 0; i < parmas.size(); i++) { ps.setObject(i + 1, parmas.get(i)); } } ps.executeUpdate(); ps.close(); ps = null; if (!isGlobal) { for (Entry<String, Object> e : tmpVariablesChanged.entrySet()) { sessionVariables.put(e.getKey(), e.getValue()); sessionVariablesChanged.put(e.getKey(), e.getValue()); } } else { for (Entry<String, Object> e : tmpVariablesChanged.entrySet()) { currentGlobalServerVariables.put(e.getKey(), e.getValue()); } } } finally { if (ps != null) { try { ps.close(); } catch (Throwable e) { logger.error("", e); } } } } } public void setSessionVariables(Map<String, Object> newServerVariables) throws SQLException { setVariables(newServerVariables, false); } public void setGlobalVariables(Map<String, Object> globalVariables) throws SQLException { setVariables(globalVariables, true); } public String getEncoding() { return encoding; } /** * IMPORTANT! must keep encoding filed in TAtomConnectionProxy identical with * encoding used in mysql */ public void setEncoding(String encoding) { this.encoding = encoding; } @Override public void clearWarnings() throws SQLException { connection.clearWarnings(); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return connection.createArrayOf(typeName, elements); } @Override public Blob createBlob() throws SQLException { return connection.createBlob(); } @Override public Clob createClob() throws SQLException { return connection.createClob(); } @Override public NClob createNClob() throws SQLException { return connection.createNClob(); } @Override public SQLXML createSQLXML() throws SQLException { return connection.createSQLXML(); } @Override public Statement createStatement() throws SQLException { return connection.createStatement(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return connection.createStatement(resultSetType, resultSetConcurrency); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return connection.createStruct(typeName, attributes); } @Override public int getHoldability() throws SQLException { return connection.getHoldability(); } @Override public DatabaseMetaData getMetaData() throws SQLException { return connection.getMetaData(); } @Override public int getNetworkTimeout() throws SQLException { return connection.getNetworkTimeout(); } @Override public String getSchema() throws SQLException { return connection.getSchema(); } @Override public int getTransactionIsolation() throws SQLException { return connection.getTransactionIsolation(); } @Override public SQLWarning getWarnings() throws SQLException { return connection.getWarnings(); } @Override public boolean isClosed() throws SQLException { return connection.isClosed(); } @Override public boolean isReadOnly() throws SQLException { return connection.isReadOnly(); } @Override public boolean isValid(int timeout) throws SQLException { return connection.isValid(timeout); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return connection.prepareCall(sql, resultSetType, resultSetConcurrency); } @Override public CallableStatement prepareCall(String sql) throws SQLException { return connection.prepareCall(sql); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return connection.prepareStatement(sql, resultSetType, resultSetConcurrency); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return connection.prepareStatement(sql, autoGeneratedKeys); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return connection.prepareStatement(sql, columnIndexes); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return connection.prepareStatement(sql, columnNames); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return connection.prepareStatement(sql); } @Override public void setHoldability(int holdability) throws SQLException { connection.setHoldability(holdability); } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { connection.setNetworkTimeout(executor, milliseconds); } @Override public void setReadOnly(boolean readOnly) throws SQLException { connection.setReadOnly(readOnly); } @Override public void setSchema(String schema) throws SQLException { connection.setSchema(schema); } @Override public void setTransactionIsolation(int level) throws SQLException { connection.setTransactionIsolation(level); } public Map<String, Object> getCurrentGlobalServerVariables() { return currentGlobalServerVariables; } public Map<String, Object> getSessionVariables() { return sessionVariables; } public long getMysqlConnectionId() { return mysqlConnectionId; } }
35.94702
119
0.617784
d61fa99f267df13917221708f55dec40d9ccf16c
2,036
/* * $Id: IntegrationTest.java,v 1.5 2016/12/10 20:55:18 oboehm Exp $ * * Copyright (c) 2010 by Oliver Boehm * * 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 orimplied. * See the License for the specific language governing permissions and * limitations under the License. * * (c)reated 05.03.2010 by oliver ([email protected]) */ package patterntesting.runtime.annotation; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import java.lang.annotation.*; /** * This annotation allows you to mark classes which are not really a unit test * but a integration test. By default this classes are not executed by a normal * test run with JUnit. Only if you set the system property * {@link patterntesting.runtime.util.Environment#INTEGRATION_TEST} these tests * will executed. * * You can use this annotation if * <ul> * <li>your JUnit test takes too long because it is a integration test,</li> * <li>you must be online for a JUnit test,</li> * <li>your JUnit test needs a database access,</li> * <li>your JUnit tests is to slow,</li> * <li>other good reason why the test should not be executed each time.</li> * </ul> * * @author oliver * @since 1.0 (05.03.2010) */ @Documented @Target({ ElementType.METHOD, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Test @Tag("integration") public @interface IntegrationTest { /** * You can give a reason why this test is an integration test or should be * skipped, e.g. "needs online access". This reason is printed to the log. * * @return the string */ String value() default "this is marked as @IntegrationTest"; }
32.31746
79
0.723477
7f995d1b6793993ae09271ab233f88aad8cf3dfe
1,693
package org.test; import loon.LTrans; import loon.LTransition; import loon.Screen; import loon.action.sprite.MovieClip; import loon.action.sprite.Sprite; import loon.event.GameTouch; import loon.opengl.GLEx; import loon.utils.res.ResourceLocal; import loon.utils.timer.LTimerContext; public class MovieClipTest extends Screen { @Override public LTransition onTransition() { return LTransition.newEmpty(); } @Override public void draw(GLEx g) { } @Override public void onLoad() { ResourceLocal res = getResourceConfig("resource.json"); MovieClip c = new MovieClip(res.getSheet("Monster01json"), 128); c.setLoop(true); c.setScale(2f, 2f); c.setLocation(155, 55); c.setTrans(LTrans.TRANS_MIRROR_ROT270); add(c); MovieClip c2 = new MovieClip(res.getSheet("Monster01json"), 128); c2.setLoop(true); c2.setLocation(255, 55); c2.setScale(2f, 2f); c2.setTrans(LTrans.TRANS_MIRROR); add(c2); MovieClip c3 = new MovieClip(res.getSheet("Monster02json"), 128); c3.setLoop(true); c3.setLocation(155, 155); c3.setScale(2f, 2f); add(c3); Sprite c4 = new Sprite(res.getSheet("Monster02json"), 255, 155, 128); c4.setScale(2f, 2f); add(c4); add(MultiScreenTest.getBackButton(this,0)); } @Override public void alter(LTimerContext timer) { } @Override public void resize(int width, int height) { } @Override public void touchDown(GameTouch e) { } @Override public void touchUp(GameTouch e) { } @Override public void touchMove(GameTouch e) { } @Override public void touchDrag(GameTouch e) { } @Override public void resume() { } @Override public void pause() { } @Override public void close() { } }
16.436893
71
0.702894
cd27748afc285dcb159dec3fd7f9fbaf8674f245
487
package io.wttech.markuply.engine.component.method.invoker; import lombok.RequiredArgsConstructor; import java.lang.reflect.Method; import java.util.List; @RequiredArgsConstructor(staticName = "of") public class ReflectiveInvoker<T> implements MethodInvoker<T> { private final Object targetInstance; private final Method method; @Override public T invoke(List<Object> parameters) throws Exception { return (T) method.invoke(targetInstance, parameters.toArray()); } }
24.35
67
0.782341
006393caf069fd8facc74d345964db625827d183
2,919
package net.runelite.client.plugins.zulrah.overlays; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Prayer; import net.runelite.client.plugins.zulrah.ZulrahPlugin; import net.runelite.client.plugins.zulrah.phase.ZulrahType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; @Slf4j public class ZulrahImageManager { private static final BufferedImage[] zulrahBufferedImages = new BufferedImage[3]; private static final BufferedImage[] smallZulrahBufferedImages = new BufferedImage[3]; private static final BufferedImage[] prayerBufferedImages = new BufferedImage[2]; public static BufferedImage getZulrahBufferedImage(ZulrahType type) { switch (type) { case RANGE: if (zulrahBufferedImages[0] == null) { zulrahBufferedImages[0] = getBufferedImage("zulrah_range.png"); } return zulrahBufferedImages[0]; case MAGIC: if (zulrahBufferedImages[1] == null) { zulrahBufferedImages[1] = getBufferedImage("zulrah_magic.png"); } return zulrahBufferedImages[1]; case MELEE: if (zulrahBufferedImages[2] == null) { zulrahBufferedImages[2] = getBufferedImage("zulrah_melee.png"); } return zulrahBufferedImages[2]; } return null; } public static BufferedImage getSmallZulrahBufferedImage(ZulrahType type) { switch (type) { case RANGE: if (smallZulrahBufferedImages[0] == null) { smallZulrahBufferedImages[0] = getBufferedImage("zulrah_range_sm.png"); } return smallZulrahBufferedImages[0]; case MAGIC: if (smallZulrahBufferedImages[1] == null) { smallZulrahBufferedImages[1] = getBufferedImage("zulrah_magic_sm.png"); } return smallZulrahBufferedImages[1]; case MELEE: if (smallZulrahBufferedImages[2] == null) { smallZulrahBufferedImages[2] = getBufferedImage("zulrah_melee_sm.png"); } return smallZulrahBufferedImages[2]; } return null; } public static BufferedImage getProtectionPrayerBufferedImage(Prayer prayer) { switch (prayer) { case PROTECT_FROM_MAGIC: if (prayerBufferedImages[0] == null) { prayerBufferedImages[0] = getBufferedImage("/prayers/protect_from_magic.png"); } return prayerBufferedImages[0]; case PROTECT_FROM_MISSILES: if (prayerBufferedImages[1] == null) { prayerBufferedImages[1] = getBufferedImage("/prayers/protect_from_missiles.png"); } return prayerBufferedImages[1]; } return null; } private static BufferedImage getBufferedImage(String path) { BufferedImage image = null; try { InputStream in = ZulrahPlugin.class.getResourceAsStream(path); image = ImageIO.read(in); } catch (IOException e) { log.debug("Error loading image {}", e); } return image; } }
27.537736
88
0.697157
6845d6a687cf68b63b59aa5fccb6fd26676a3105
3,417
package edu.jd.xyt.home; import edu.jd.xyt.common.CurrentUser; import edu.jd.xyt.common.Result; import edu.jd.xyt.common.Utils; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.*; import java.util.UUID; @MultipartConfig @WebServlet({ "/current-user",//获取当前用户信息 "/avatar"//获取头像 }) public class HomeAPI extends HttpServlet { //该方法在Sevelet初始化时执行,仅执行一次 @Override public void init() throws ServletException { File dir = new File(CurrentUser.AVATAR_DIR);//表示文件或目录的路径 if(!dir.exists()){ dir.mkdirs(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HomeService service = new HomeService(); request.setCharacterEncoding("UTF-8"); String path = request.getServletPath(); if("/avatar".equals(path)){ Part part = request.getPart("avatar"); InputStream in = part.getInputStream(); String name = UUID.randomUUID().toString(); String submitedFilename = part.getSubmittedFileName(); String suffix = submitedFilename.substring(submitedFilename.lastIndexOf(".")); String filename = name+suffix; OutputStream out = new FileOutputStream(CurrentUser.AVATAR_DIR+"/"+filename); byte[] b = new byte[10240]; int len =-1; while ((len=in.read(b))!=-1){ out.write(b,0,len); } out.flush(); out.close(); in.close(); CurrentUser currentUser = (CurrentUser)request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME); service.setAvatar(currentUser,filename); Utils.outResult(response,Result.success()); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getServletPath(); HomeService service = new HomeService(); if("/current-user".equals(path)){ System.out.println("session?"); System.out.println(request.getSession().getId()); CurrentUser currentUser = (CurrentUser)request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME); System.out.println(currentUser); service.loadCurrentUser(currentUser); System.out.println("????"); Utils.outResult(response, Result.success(currentUser)); } if ("/avatar".equals(path)) { String filename = request.getParameter("filename"); System.out.println(filename); InputStream in = new FileInputStream(CurrentUser.AVATAR_DIR+"/"+filename); OutputStream out = response.getOutputStream(); byte[] b = new byte[10240]; int len =-1; while ((len=in.read(b))!=-1){ out.write(b,0,len); } out.flush(); out.close(); in.close(); } } }
32.855769
123
0.604624
b4393dbb80a3de8a59de61f44145bf3868a2576e
3,686
/* * Copyright 2018 wladimirowichbiaran. * * 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 ru.newcontrol.ncfv; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; /** * * @author wladimirowichbiaran */ public class AppLoggerRunnableHtmlRead implements Runnable { private AppLoggerRule managerForThis; public AppLoggerRunnableHtmlRead(AppLoggerRule outerManagerForThis){ super(); this.managerForThis = outerManagerForThis; //this.managerForThis..setTrueFromHTMLNewRunner(); String threadInfoToString = NcAppHelper.getThreadInfoToString(Thread.currentThread()); System.out.println("*** ||| *** ||| *** create log reader *** ||| *** ||| ***" + threadInfoToString); } @Override public void run() { AppLoggerStateReader currentJob = this.managerForThis.currentReaderJob(); if( !currentJob.isBlankObject() ){ if( !currentJob.isFromHTMLJobDone() ){ Path fileForReadInThisJob = currentJob.getFromHTMLLogFileName(); //currentJob.setFalseFromHTMLJobDone(); System.out.println("_|_|_|_|_|_ AppLoggerRunnableHtmlRead.run() fromHTMLLogFileName " + fileForReadInThisJob.toString() + " _|_|_|_|_|_" + " start for read file"); ArrayBlockingQueue<String> readedLines = new ArrayBlockingQueue<String>(AppConstants.LOG_HTML_MESSAGES_QUEUE_SIZE); String ancorString = currentJob.getAncorString(); if( ancorString.length() > 17 ){ readedLines.add(ancorString); } try { readedLines.addAll(Files.readAllLines(fileForReadInThisJob, Charset.forName("UTF-8"))); if( readedLines != null){ System.out.println("_|_|_|_|_|_ AppLoggerRunnableHtmlRead.run() fromHTMLLogFileName " + fileForReadInThisJob.toString() + " _|_|_|_|_|_" + " readedLines.size() " + readedLines.size()); this.managerForThis.setStringBusForLogRead(readedLines); } else { System.out.println("_|_|NULL|_|_ AppLoggerRunnableHtmlRead.run() fromHTMLLogFileName " + fileForReadInThisJob.toString() + " _|_|NULL|_|_" + " readedLines.size() is null"); this.managerForThis.setStringBusForLogRead(new ArrayBlockingQueue<String>(1)); } currentJob.setFalseFromHTMLLogFileNameChanged(); } catch (IOException ex) { ex.getMessage(); ex.printStackTrace(); } } } currentJob.setTrueFromHTMLJobDone(); currentJob.setFalseFromHTMLNewRunner(); } }
43.880952
131
0.592241
f21d0d4e8a8fd47c43a65e5cb664b87fbe259bcf
2,093
package br.com.zup.bootcamp.client.response; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.Collection; // Carga intrínseca = 5/7 public class CardResponse { private final String id; private final LocalDateTime emitidoEm; private final String titular; private final Collection<BlockResponse> bloqueios; private final Collection<WarningResponse> avisos; private final Collection<WalletResponse> carteiras; private final Collection<PortionResponse> parcelas; private final BigDecimal limite; private final Collection<RenegotiationResponse> renegociacao; private final DueDateResponse vencimento; private final String idProposta; public CardResponse(String id, LocalDateTime emitidoEm, String titular, Collection<BlockResponse> bloqueios, Collection<WarningResponse> avisos, Collection<WalletResponse> carteiras, Collection<PortionResponse> parcelas, BigDecimal limite, Collection<RenegotiationResponse> renegociacao, DueDateResponse vencimento, String idProposta) { this.id = id; this.emitidoEm = emitidoEm; this.titular = titular; this.bloqueios = bloqueios; this.avisos = avisos; this.carteiras = carteiras; this.parcelas = parcelas; this.limite = limite; this.renegociacao = renegociacao; this.vencimento = vencimento; this.idProposta = idProposta; } @Override public String toString() { return "CardResponse{" + "id='" + id + '\'' + ", emitidoEm=" + emitidoEm + ", titular='" + titular + '\'' + ", bloqueios=" + bloqueios + ", avisos=" + avisos + ", carteiras=" + carteiras + ", parcelas=" + parcelas + ", limite=" + limite + ", renegociacao=" + renegociacao + ", vencimento=" + vencimento + ", idProposta='" + idProposta + '\'' + '}'; } public String getId() { return id; } }
31.712121
340
0.627329
bf179fff280896645bef57dc38053e3aa5ba0c86
397
package fr.xephi.authme.security.crypts.description; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Denotes a hashing algorithm that is restricted to the ASCII charset. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface AsciiRestricted { }
24.8125
71
0.808564
ef167a38afb63443fc1204bf616483fcfec0ec31
5,859
/** * Copyright (c) 2011 Perforce Software. All rights reserved. */ package com.perforce.p4java.tests.dev.unit.features112; import com.perforce.p4java.client.IClient; import com.perforce.p4java.impl.mapbased.rpc.RpcPropertyDefs; import com.perforce.p4java.option.server.ExportRecordsOptions; import com.perforce.p4java.tests.SSLServerRule; import com.perforce.p4java.tests.dev.annotations.Jobs; import com.perforce.p4java.tests.dev.annotations.TestId; import com.perforce.p4java.tests.dev.unit.P4JavaLocalServerTestCase; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Test 'p4 export' command. In particular, test the ability to retrieve field * values in bytes; skipping chartset translation. */ @Jobs({ "job037798" }) @TestId("Dev112_GetExportRecordsTest") public class GetExportRecordsTest extends P4JavaLocalServerTestCase { @ClassRule public static SSLServerRule p4d = new SSLServerRule("r16.1", GetExportRecordsTest.class.getSimpleName(),"ssl:localhost:10674"); private Integer journal = 0; /** * @Before annotation to a method to be run before each test in a class. */ @BeforeClass public static void beforeAll() throws Exception{ props.put(RpcPropertyDefs.RPC_RELAX_CMD_NAME_CHECKS_NICK, "true"); setupSSLServer(p4d.getP4JavaUri(), superUserName, superUserPassword, false, props); server.execMapCmd("admin", new String[]{"journal"}, null); IClient client = createClient(server, "getExportRecordsTestClient"); String[] filenames = new String[100]; for (int i=0 ; i <100; i++) { filenames[i] = "test" + i; } createTextFilesOnServer(client, filenames, "test"); client = server.getClient("p4TestUserWS"); assertNotNull(client); server.setCurrentClient(client); } /** * @Before annotation to a method to be run before each test in a class. */ @Before public void setUp() throws Exception{ journal = new Integer(server.getCounter("journal")); } /** * @After annotation to a method to be run after each test in a class. */ @AfterClass public static void afterAll() throws Exception { afterEach(server); } /** * Test 'p4 export' command - default, no skipping; normal data conversion. */ @Test public void testExportNoSkip() throws Exception { // Set skipDataConversion to false, so we should get data as strings List<Map<String, Object>> exportList = server.getExportRecords(new ExportRecordsOptions() .setUseJournal(true).setSourceNum(journal).setMaxRecs(10000) .setFilter("table=db.have")); assertNotNull(exportList); assertTrue(exportList.size() > 0); // Get the first data map and inspect the data is in string format Map<String, Object> dataMap = exportList.get(0); assertNotNull(dataMap); Object dataObject = dataMap.get("HAdfile"); assertNotNull(dataObject); assertTrue(dataObject instanceof String); } /** * Test 'p4 export' command. Skip charset translation of a range of fields * (inclusive start field and non-inclusive stop field); retrieve those * field values in bytes. <p> * * Note, by default the export command's start field is set to "op" and stop * field is set to "func". */ @Test public void testExportSkipFieldRange() throws Exception { // Set skipDataConversion to true // This query takes a little more time to run (filter by attr name) List<Map<String, Object>> exportList = server .getExportRecords(new ExportRecordsOptions() .setUseJournal(true).setSourceNum(journal) .setFilter("HAdfile=//depot/test0") .setSkipDataConversion(true)); assertNotNull(exportList); assertTrue(exportList.size() > 0); // The first data map contains the data in bytes Map<String, Object> dataMap = exportList.get(0); assertNotNull(dataMap); Object dataObject = dataMap.get("HAdfile"); assertNotNull(dataObject); // Verify the return data is of byte[] and it's size assertTrue(dataObject instanceof byte[]); assertEquals(13, ((byte[]) dataObject).length); } /** * Test 'p4 export' command. Skip chartset translation of a range of fields * (inclusive start field and non-inclusive stop field); retrieve those * field values in bytes. <p> * * Note, by default the export command's start field is set to "op" and stop * field is set to "func". */ @Test public void testExportSkipFieldRange2() throws Exception{ // Set skipDataConversion to true List<Map<String, Object>> exportList = server.getExportRecords(new ExportRecordsOptions() .setMaxRecs(50).setUseJournal(true).setSourceNum(journal) .setSkipDataConversion(true)); assertNotNull(exportList); assertEquals(exportList.size(),51); // Get the first data map and inspect the data is in bytes Map<String, Object> dataMap = exportList.get(0); assertNotNull(dataMap); } /** * Test 'p4 export' command. Skip chartset translation of fields matching a * pattern; retrieve those field values in bytes. */ @Test public void testExportSkipFieldPattern() throws Exception { // Set skipDataConversion to true List<Map<String, Object>> exportList = server.getExportRecords(new ExportRecordsOptions() .setMaxRecs(1000000).setUseJournal(true).setSourceNum(journal) .setSkipDataConversion(true) .setFilter("table=db.have") .setSkipFieldPattern("^[A-Z]{2}\\w+")); assertNotNull(exportList); assertTrue(exportList.size() > 0); // Get the first data map and inspect the data is in bytes Map<String, Object> dataMap = exportList.get(0); assertNotNull(dataMap); Object dataObject = dataMap.get("HAdfile"); assertNotNull(dataObject); assertTrue(dataObject instanceof byte[]); } }
34.464706
128
0.738351
6b5cca38f26dc204027bed1558507638e2a5a5d6
2,012
package UI; import static UI.MainUI.setUIFont; import java.awt.Color; import java.awt.Font; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYDataset; public class LineChart extends javax.swing.JFrame { public LineChart() { super(""); setUIFont (new javax.swing.plaf.FontUIResource("Segoe UI",Font.PLAIN,13)); } void createChart( String applicationTitle , String chartTitle , XYDataset dataset, int l, int h ) { JFreeChart lineChart = ChartFactory.createXYLineChart( chartTitle, "Instances","Exchange Rate", dataset, PlotOrientation.VERTICAL, true,true,false); ChartPanel chartPanel = new ChartPanel( lineChart ); final XYPlot plot = lineChart.getXYPlot(); ValueAxis axis = plot.getRangeAxis(); axis.setUpperBound(h); axis.setLowerBound(l); chartPanel.setPreferredSize( new java.awt.Dimension( 1120 , 580 ) ); setContentPane( chartPanel ); } public static void main( String[ ] args , XYDataset dataset, int l, int h) { // String a = args[0].concat("/INR"); LineChart chart = new LineChart(); chart.setIconImage(MainUI.iconImage); chart.setTitle("Graph"); chart.setBackground(new java.awt.Color(102, 102, 102)); chart.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); chart.createChart("","", dataset,l,h); chart.pack( ); RefineryUtilities.centerFrameOnScreen( chart ); chart.setVisible( true ); } }
32.451613
101
0.699304
6ead195a94ee477e7923cc5a4ade96a7cbe61a5b
2,383
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("8") class Record_58 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 58: FirstName is Ivan") void FirstNameOfRecord58() { assertEquals("Ivan", customers.get(57).getFirstName()); } @Test @DisplayName("Record 58: LastName is Cimaglia") void LastNameOfRecord58() { assertEquals("Cimaglia", customers.get(57).getLastName()); } @Test @DisplayName("Record 58: Company is Surveying And Mapping Inc") void CompanyOfRecord58() { assertEquals("Surveying And Mapping Inc", customers.get(57).getCompany()); } @Test @DisplayName("Record 58: Address is 29524 Kohoutek Way") void AddressOfRecord58() { assertEquals("29524 Kohoutek Way", customers.get(57).getAddress()); } @Test @DisplayName("Record 58: City is Union City") void CityOfRecord58() { assertEquals("Union City", customers.get(57).getCity()); } @Test @DisplayName("Record 58: County is Alameda") void CountyOfRecord58() { assertEquals("Alameda", customers.get(57).getCounty()); } @Test @DisplayName("Record 58: State is CA") void StateOfRecord58() { assertEquals("CA", customers.get(57).getState()); } @Test @DisplayName("Record 58: ZIP is 94587") void ZIPOfRecord58() { assertEquals("94587", customers.get(57).getZIP()); } @Test @DisplayName("Record 58: Phone is 510-429-4828") void PhoneOfRecord58() { assertEquals("510-429-4828", customers.get(57).getPhone()); } @Test @DisplayName("Record 58: Fax is 510-429-1348") void FaxOfRecord58() { assertEquals("510-429-1348", customers.get(57).getFax()); } @Test @DisplayName("Record 58: Email is [email protected]") void EmailOfRecord58() { assertEquals("[email protected]", customers.get(57).getEmail()); } @Test @DisplayName("Record 58: Web is http://www.ivancimaglia.com") void WebOfRecord58() { assertEquals("http://www.ivancimaglia.com", customers.get(57).getWeb()); } }
24.822917
76
0.725556
a2fb9214b602efedb77feaae5c1530b461ee4ddd
2,762
package mchorse.blockbuster.recording; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.recording.actions.AttackAction; import mchorse.blockbuster.recording.actions.EquipAction; import mchorse.blockbuster.recording.actions.SwipeAction; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; /** * Player tracker class * * This class tracks player's properties such as arm swing and player equipped * inventory. That's it. */ public class PlayerTracker { /** * Record recorder to which tracked stuff are going to be added */ public RecordRecorder recorder; /* Items to track */ private ItemStack[] items = new ItemStack[6]; public PlayerTracker(RecordRecorder recorder) { this.recorder = recorder; } /** * Track player's properties like armor, hand held items and hand swing */ public void track(EntityPlayer player) { this.trackSwing(player); this.trackHeldItem(player); this.trackArmor(player); } /** * Track armor inventory */ private void trackArmor(EntityPlayer player) { for (int i = 1; i < 5; i++) { this.trackItemToSlot(player.inventory.armorInventory[i - 1], i); } } /** * Track held items */ private void trackHeldItem(EntityPlayer player) { ItemStack mainhand = player.getHeldItemMainhand(); ItemStack offhand = player.getHeldItemOffhand(); this.trackItemToSlot(mainhand, 0); this.trackItemToSlot(offhand, 5); } /** * Track item to slot. * * This is a simple utility method that reduces number of lines for both * hands. */ private boolean trackItemToSlot(ItemStack item, int slot) { if (item != null) { if (item != this.items[slot]) { this.items[slot] = item; this.recorder.actions.add(new EquipAction((byte) slot, item)); return true; } } else if (this.items[slot] != null) { this.items[slot] = null; this.recorder.actions.add(new EquipAction((byte) slot, null)); return true; } return false; } /** * Track the hand swing (like when you do the tap-tap with left-click) */ private void trackSwing(EntityPlayer player) { if (player.isSwingInProgress && player.swingProgress == 0) { this.recorder.actions.add(new SwipeAction()); if (Blockbuster.proxy.config.record_attack_on_swipe) { this.recorder.actions.add(new AttackAction()); } } } }
25.574074
78
0.601376
29da1b552199c83ac1e4c60e485a19a05e6e2cb5
154
package com.vacker.example.utils; public class Constants { private Constants() { //hiding this class } public static String KEY; }
14
33
0.649351
8553cb5b97d90dbc8517f52b65144501d4013eba
1,502
package velosurf.util; import org.apache.velocity.VelocityContext; import org.apache.velocity.tools.generic.RenderTool; import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DynamicQueryBuilder { // Not needed // private static Pattern balancedQuotes = Pattern.compile("'[^']*?'|\"[^\"]*?\""); static protected RenderTool renderTool = new RenderTool(); public static boolean isDynamic(String query) { // Not needed /* StringBuilder unquoted = new StringBuilder(); Matcher matcher = balancedQuotes.matcher(query); int pos = 0; while (matcher.find()) { if (matcher.start() < pos) continue; unquoted.append(query.substring(pos, matcher.start())); pos = matcher.end(); } unquoted.append(query.substring(pos)); String str = unquoted.toString(); return str.indexOf('#') != -1 || str.indexOf('$') != -1; */ return query.indexOf('#') != -1 || query.indexOf('$') != -1; } public static String buildQuery(String vtl, SlotMap source) { String query = null; try { // wraps the source as an unmodifiable map inside a modifiable context VelocityContext context = new VelocityContext(new VelocityContext(Collections.<String, Object>unmodifiableMap(source))); query = renderTool.eval(context, vtl); } catch (Exception e) { Logger.error("could not evaluate expression " + vtl + e.getMessage()); } return query; } }
28.339623
126
0.660453
545fabc9308d900cae57e80da561b1712ae4c65e
7,231
package munwin.tsv_kafka_producer; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.Properties; import kafka.javaapi.producer.Producer; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; public class KafkaProducer { /** * The default number of milliseconds to sleep between submitting * messages into the queue. */ private static final int DEFAULT_MESSAGE_SLEEP = 10; /** * Path to the default configuration file for the program */ public static final String DEFAULT_CONFIG_PATH = "conf/tsv_kafka_producer.conf"; /** * Name of the queue to send messages to. */ private final String destinationQueueName; /** * Kafka Producer variable */ private Producer<String, String> kafkaProducer; /** * Instantiate KafkaProducer */ public KafkaProducer(){ this.destinationQueueName = null; } /** * Initialize the KafkaProducer with the path to a configuration file * containing configuration information. * @param configPath path to a config file containing kafka configuration. * @throws ConfigurationException if configPath isn't a path to an actual * configuration file. * @throws FileNotFoundException */ public KafkaProducer(final String configPath) throws ConfigurationException, FileNotFoundException { PropertiesConfiguration config = new PropertiesConfiguration(); config.setDelimiterParsingDisabled(true); config.load(new FileReader(configPath)); Properties props = new Properties(); props.put("zk.connect", config.getString("kafka.zkConnect")); props.put("metadata.broker.list", config.getString("kafka.metadata.broker.list")); props.put("serializer.class", "kafka.serializer.StringEncoder"); props.put("request.required.acks", "1"); ProducerConfig kafkaConfig = new ProducerConfig(props); this.kafkaProducer = new Producer<String, String>(kafkaConfig); this.destinationQueueName = config.getString("kafka.incomingQueue"); } /** * Generate KafkaProducer with an existing Kafka Producer. * @param kafkaProducer an existing Kafka Producer. * @param destinationQueueName the name of the queue to publish messages to. */ public KafkaProducer( final Producer<String, String> kafkaProducer, final String destinationQueueName) { this.kafkaProducer = kafkaProducer; this.destinationQueueName = destinationQueueName; } /** * Publish the contents of the messages at datafilePath to the kafka queue * @param datefilePath string path to a tsv file with the content to send * to the queue. * @throws Exception */ public void publishMessageFromTSVFile(final String datafilePath, final int msgSleep) throws Exception { InputTsvFile inputFile = new InputTsvFile(datafilePath); String message = inputFile.getNextMessage(); int msgCount = 0; while (message != null) { msgCount++; publishKafkaMessage(message); Thread.sleep(msgSleep); message = inputFile.getNextMessage(); } System.out.println("Published " + msgCount + " messages."); } /** * Publish the passed string as a message onto the configured kafka queue. * @param messageContent the contents of the message to create and publish. */ public void publishKafkaMessage(final String messageContent) { KeyedMessage<String, String> data = new KeyedMessage<String, String>(destinationQueueName, messageContent); kafkaProducer.send(data); } /** * Run the KafkaProducer parsing configuration information from the * command-line arguments. * * @param args Command-line arguments for configuring the * MessageFileGenerator. * @throws ConfigurationException if there's an issue reading the * configuration file indicated by the -c command-line option, or * DEFAULT_CONFIG_PATH * @throws IOException if there's an issue generating the MessageFiles */ public static void main(final String[] args) throws ConfigurationException, IOException, Exception { Options options = new Options(); OptionBuilder.withLongOpt("config"); OptionBuilder.withDescription("path to the config file with the broker" + " and queue settings"); OptionBuilder.hasArg(); OptionBuilder.withArgName("PATH"); options.addOption(OptionBuilder.create('c')); OptionBuilder.withLongOpt("datafile"); OptionBuilder.withDescription("path to a file containing the messages to publish" + " in tsv format"); OptionBuilder.hasArg(); OptionBuilder.withArgName("DATAFILE"); OptionBuilder.isRequired(); options.addOption(OptionBuilder.create('d')); OptionBuilder.withLongOpt("msgSleep"); OptionBuilder.withDescription("number of milliseconds to delay between" + " submitting messages to the queue. The default is: " + DEFAULT_MESSAGE_SLEEP + ".\n"); OptionBuilder.hasArg(); OptionBuilder.withArgName("MSGSLEEP"); options.addOption(OptionBuilder.create('s')); CommandLineParser parser = new PosixParser(); CommandLine cli = null; try { cli = parser.parse(options, args); } catch (ParseException e) { System.err.println("Parsing the command-line options failed. Reason: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(" ", options); System.exit(1); } KafkaProducer kafkaProducer = null; if ((cli != null) && cli.hasOption('c')) { String configPath = cli.getOptionValue('c'); System.out.println("Instantiating message file generator with " + configPath); kafkaProducer = new KafkaProducer(configPath); } if (kafkaProducer == null) { kafkaProducer = new KafkaProducer(DEFAULT_CONFIG_PATH); } if ((cli != null) && cli.hasOption('d')) { String datafilePath = cli.getOptionValue('d'); String msgSleepOveride = cli.getOptionValue('s'); int msgSleep = DEFAULT_MESSAGE_SLEEP; if (msgSleepOveride != null) { try { msgSleep = Integer.parseInt(msgSleepOveride); } catch (NumberFormatException nfe) { System.out.print( "Sleep duration given with '-s' parameter is not a valid " + "number. Using default delay: " + DEFAULT_MESSAGE_SLEEP + " milliseconds" ); msgSleep = DEFAULT_MESSAGE_SLEEP; } } System.out.print("Publishing message contents from:" + datafilePath); kafkaProducer.publishMessageFromTSVFile( datafilePath, msgSleep ); System.out.println("done."); } System.exit(0); } }
33.78972
111
0.701424
4da0b1316f4420af76dd21a2edff802b0492938d
1,016
package seedu.address.storage; import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.jupiter.api.Test; import seedu.address.commons.util.JsonUtil; import seedu.address.model.Shortcut; import seedu.address.testutil.TypicalPersons; public class JsonSerializableShortcutTest { private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data", "JsonSerializableShortcutTest"); private static final Path TYPICAL_SHORTCUT_FILE = TEST_DATA_FOLDER.resolve("typicalShortcut.json"); @Test public void toModelType_typicalShortcutFile_success() throws Exception { JsonSerializableShortcut dataFromFile = JsonUtil.readJsonFile(TYPICAL_SHORTCUT_FILE, JsonSerializableShortcut.class).get(); Shortcut shortcutFromFile = dataFromFile.toModelType(); Shortcut typicalShortcut = TypicalPersons.getTypicalShortcut(); assertEquals(shortcutFromFile, typicalShortcut); } }
35.034483
114
0.775591
72a7dabd06dec47adc6698a132d8942eb586ee44
482
package de.honoka.qqrobot.farm.database.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import de.honoka.qqrobot.farm.entity.system.ExceptionRecord; import org.apache.ibatis.annotations.Param; import java.util.List; /** * (ExceptionRecord)表数据库访问层 * * @author makejava * @since 2021-12-09 15:28:18 */ public interface ExceptionRecordDao extends BaseMapper<ExceptionRecord> { List<ExceptionRecord> readException(@Param("limit") int exceptionRecordMaxSize); }
26.777778
84
0.786307
22de30e67cfd80d87891eebc1b2ada5b8ca72d4f
2,831
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.propertyeditor; import java.beans.PropertyEditorSupport; import org.openmrs.Concept; import org.openmrs.Program; import org.openmrs.api.context.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; /** * Allows for serializing/deserializing an object to a string so that Spring knows how to pass * an object back and forth through an html form or other medium. <br> * If string value starts with "concept.", then the text after the dot is treated as a concept_id or uuid * The name of the concept associated with that id is treated as the name of the program to fetch. * <br> * In version 1.9, added ability for this to also retrieve objects by uuid * * @see Program */ public class ProgramEditor extends PropertyEditorSupport { private static final Logger log = LoggerFactory.getLogger(ProgramEditor.class); public ProgramEditor() { } /** * @should set using concept id * @should set using concept uuid * @should set using program id * @should set using program uuid */ @Override public void setAsText(String text) throws IllegalArgumentException { if (StringUtils.hasText(text)) { try { if (text.startsWith("concept.")) { Integer conceptId = Integer.valueOf(text.substring(text.indexOf('.') + 1)); Concept c = Context.getConceptService().getConcept(conceptId); setValue(Context.getProgramWorkflowService().getProgramByName(c.getName().getName())); } else { Integer programId = Integer.valueOf(text); setValue(Context.getProgramWorkflowService().getProgram(programId)); } } catch (Exception ex) { Program p; if (text.startsWith("concept.")) { Concept c = Context.getConceptService().getConceptByUuid(text.substring(text.indexOf('.') + 1)); p = Context.getProgramWorkflowService().getProgramByName(c.getName().getName()); } else { p = Context.getProgramWorkflowService().getProgramByUuid(text); } setValue(p); if (p == null) { log.error("Error setting text: " + text, ex); throw new IllegalArgumentException("Program not found: " + text, ex); } } } else { setValue(null); } } @Override public String getAsText() { Program p = (Program) getValue(); if (p == null) { return ""; } else { return p.getProgramId().toString(); } } }
32.170455
105
0.705051
b9f0b765cbf0ab9607bd29cc0ca9edfec361c945
2,451
package com.gschat; import com.gsrpc.Device; import com.gsrpc.KV; import java.nio.ByteBuffer; import com.gsrpc.Writer; import com.gsrpc.Reader; public class AttachmentAudio { private String key = ""; private String name = ""; private short duration = 0; public AttachmentAudio(){ } public AttachmentAudio(String key, String name, short duration ) { this.key = key; this.name = name; this.duration = duration; } public String getKey() { return this.key; } public void setKey(String arg) { this.key = arg; } public String getName() { return this.name; } public void setName(String arg) { this.name = arg; } public short getDuration() { return this.duration; } public void setDuration(short arg) { this.duration = arg; } public void marshal(Writer writer) throws Exception { writer.writeByte((byte)3); writer.writeByte((byte)com.gsrpc.Tag.String.getValue()); writer.writeString(key); writer.writeByte((byte)com.gsrpc.Tag.String.getValue()); writer.writeString(name); writer.writeByte((byte)com.gsrpc.Tag.I16.getValue()); writer.writeInt16(duration); } public void unmarshal(Reader reader) throws Exception { byte __fields = reader.readByte(); { byte tag = reader.readByte(); if(tag != com.gsrpc.Tag.Skip.getValue()) { key = reader.readString(); } if(-- __fields == 0) { return; } } { byte tag = reader.readByte(); if(tag != com.gsrpc.Tag.Skip.getValue()) { name = reader.readString(); } if(-- __fields == 0) { return; } } { byte tag = reader.readByte(); if(tag != com.gsrpc.Tag.Skip.getValue()) { duration = reader.readInt16(); } if(-- __fields == 0) { return; } } for(int i = 0; i < (int)__fields; i ++) { byte tag = reader.readByte(); if (tag == com.gsrpc.Tag.Skip.getValue()) { continue; } reader.readSkip(tag); } } }
17.507143
70
0.496124
e93135d3000c2e030dc9a814da468473c3bde662
3,479
package com.osh.rvs.form.equipment; import java.io.Serializable; import org.apache.struts.action.ActionForm; import framework.huiqing.bean.annotation.BeanField; import framework.huiqing.bean.annotation.FieldType; import framework.huiqing.common.util.CodeListUtils; /** * 设备工具备品调整记录 * * @author liuxb * */ public class DeviceSpareAdjustForm extends ActionForm implements Serializable { /** * */ private static final long serialVersionUID = 6035106423547809464L; @BeanField(title = "设备品名 ID", name = "device_type_id", type = FieldType.String, length = 11, notNull = true) private String device_type_id; @BeanField(title = "型号", name = "model_name", type = FieldType.String, length = 32, notNull = true) private String model_name; @BeanField(title = "备品种类", name = "device_spare_type", type = FieldType.Integer, length = 1, notNull = true) private String device_spare_type; @BeanField(title = "调整日时", name = "adjust_time", type = FieldType.DateTime, notNull = true) private String adjust_time; @BeanField(title = "理由", name = "reason_type", type = FieldType.Integer, length = 2, notNull = true) private String reason_type; @BeanField(title = "调整量", name = "adjust_inventory", type = FieldType.Integer, length = 5, notNull = true) private String adjust_inventory; @BeanField(title = "调整负责人", name = "operator_id", type = FieldType.String, length = 11, notNull = true) private String operator_id; @BeanField(title = "调整备注", name = "comment", type = FieldType.String, length = 250) private String comment; @BeanField(title = "调整负责人名称", name = "operator_name", type = FieldType.String) private String operator_name; private String reason_type_name; public String getDevice_type_id() { return device_type_id; } public void setDevice_type_id(String device_type_id) { this.device_type_id = device_type_id; } public String getModel_name() { return model_name; } public void setModel_name(String model_name) { this.model_name = model_name; } public String getDevice_spare_type() { return device_spare_type; } public void setDevice_spare_type(String device_spare_type) { this.device_spare_type = device_spare_type; } public String getAdjust_time() { return adjust_time; } public void setAdjust_time(String adjust_time) { this.adjust_time = adjust_time; } public String getReason_type() { return reason_type; } public void setReason_type(String reason_type) { if (reason_type.length() < 2) { this.reason_type = "0" + reason_type; } else { this.reason_type = reason_type; } } public String getAdjust_inventory() { return adjust_inventory; } public void setAdjust_inventory(String adjust_inventory) { this.adjust_inventory = adjust_inventory; } public String getOperator_id() { return operator_id; } public void setOperator_id(String operator_id) { this.operator_id = operator_id; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getOperator_name() { return operator_name; } public void setOperator_name(String operator_name) { this.operator_name = operator_name; } public String getReason_type_name() { if (reason_type != null) { return CodeListUtils.getValue("device_spare_adjust_all_reason_type", reason_type); } return reason_type_name; } public void setReason_type_name(String reason_type_name) { this.reason_type_name = reason_type_name; } }
24.5
109
0.742742
8f9756107b7abef47e7f3eafbaa426e5cb0edac0
6,706
package newbilius.com.online_comics_reader.Lists; import android.app.Activity; import android.os.AsyncTask; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import newbilius.com.online_comics_reader.SimpleComicsReaderApplication; import newbilius.com.online_comics_reader.Net.BaseUrls; import newbilius.com.online_comics_reader.Net.NetHelpers; import newbilius.com.online_comics_reader.R; import newbilius.com.online_comics_reader.Tools.FirebaseEventsHelper; import newbilius.com.online_comics_reader.UI.IComicsOnListClickListener; import newbilius.com.online_comics_reader.UI.IOnStatusChangeListener; import newbilius.com.online_comics_reader.UI.NetMessage; class SearchListAdapter extends RecyclerView.Adapter { private final FirebaseEventsHelper firebaseEventsHelper; private IComicsOnListClickListener onComicsOnListClickListener; private IOnStatusChangeListener onStatusChangeListener; private Activity activity; private List<ComicsListData> data = new ArrayList<>(); private SearchAsyncTask searchAsyncTask; private String currentSearchText; //todo ссылка на activity - мягко говоря, не айс SearchListAdapter(IComicsOnListClickListener IComicsOnListClickListener, IOnStatusChangeListener onStatusChangeListener, Activity activity) { this.onComicsOnListClickListener = IComicsOnListClickListener; this.onStatusChangeListener = onStatusChangeListener; this.activity = activity; this.firebaseEventsHelper = new FirebaseEventsHelper(activity); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.cell_comics_list, parent, false); ListsViewHolder holder = new ListsViewHolder(view); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int pos = (int) view.getTag(); onComicsOnListClickListener.onClick(getItem(pos)); } }); return holder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((ListsViewHolder) holder).changeData(getItem(position), position); } private ComicsListData getItem(int position) { return data.get(position); } @Override public int getItemCount() { return data.size(); } //todo вот тут ОЧЕНЬ пригодилось бы реактивное программирование synchronized void search(String searchText) { onStatusChangeListener.onChange(true); currentSearchText = searchText; if (searchAsyncTask == null) { searchAsyncTask = new SearchAsyncTask(); searchAsyncTask.execute(searchText); } } public void reload() { if (searchAsyncTask == null) { searchAsyncTask = new SearchAsyncTask(); searchAsyncTask.execute(currentSearchText); } } private class SearchAsyncTask extends AsyncTask<String, Void, Void> { private String searchText; @Override protected Void doInBackground(String... strings) { searchText = strings[0]; String url = null; try { if (searchText == null || searchText.isEmpty()) url = "https://acomics.ru/comics"; else url = "https://acomics.ru/search?keyword=" + URLEncoder.encode(searchText, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RuntimeException(e); } try { Document doc = Jsoup.connect(url).get(); Elements items = doc.select("table.catalog-elem"); data.clear(); for (Element item : items) { if (item.id().equals("catalog-header")) continue; ComicsListData newComicsListData = new ComicsListData(); newComicsListData.Rating = item.select("div.also a").first().text(); String pages = item.select("span.total").first().text().split(" ")[0]; newComicsListData.Pages = SimpleComicsReaderApplication.getAppContext().getString(R.string.pagesPlaceholder, pages); newComicsListData.Description = item.select("div.about").first().text(); newComicsListData.Title = item.select("div.title").first().text(); newComicsListData.Url = item.select("div a").first().attr("href") .replace(BaseUrls.BASE_URL, "") + "/"; newComicsListData.Url = newComicsListData.Url.replace("//", "/"); newComicsListData.CoverUrl = item.select("td.catdata1 img").attr("src").replace(BaseUrls.BASE_URL, ""); newComicsListData.Completed = !item.select("span.closed").isEmpty(); try { if (Integer.valueOf(pages) > 0) data.add(newComicsListData); } catch (NumberFormatException ignored) { } } } catch (IOException e) { e.printStackTrace(); if (!NetHelpers.NetworkIsAvailable()) NetMessage.showAlertForNetworkNotAvailable(activity); else doInBackground(url); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (searchText.equals(currentSearchText)) { firebaseEventsHelper.search(searchText); searchAsyncTask = null; notifyDataSetChanged(); onStatusChangeListener.onChange(false); } else { searchAsyncTask = new SearchAsyncTask(); searchAsyncTask.execute(currentSearchText); } } } }
40.890244
137
0.614673
22c402058619fc416be027f9b6eeab3052425a36
4,250
package com.example.fm; import static com.example.fm.ContactHelper.CREATION; import static com.example.fm.ContactHelper.MODIFICATION; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import com.example.tests.ContactData; import com.example.utils.SortedListOf; public class ContactHelper extends HelperBase { private SortedListOf<ContactData> cachedContacts; public static boolean CREATION = true; public static boolean MODIFICATION = false; public ContactHelper(ApplicationManager manager) { super(manager); } public SortedListOf<ContactData> getContacts() { if (cachedContacts == null) { rebuildCacheContacts(); } return cachedContacts; } public void rebuildCacheContacts() { cachedContacts = new SortedListOf<ContactData>(); List<WebElement> rows = driver.findElements(By.name("entry")); for (WebElement row : rows) { ContactData contact = new ContactData(); String emails = row.findElement(By.xpath(".//td[1]/input")).getAttribute("accept"); int indexStr = emails.indexOf(";"); contact.withFirstName(row.findElement(By.xpath(".//td[2]")).getText()) .withLastName(row.findElement(By.xpath(".//td[3]")).getText()) .withEmail1(row.findElement(By.xpath(".//td[4]")).getText()) .withPhoneHome(row.findElement(By.xpath(".//td[5]")).getText()); if (indexStr == -1) { contact.withEmail2(""); } else { contact.withEmail2(emails.substring(indexStr + 1,emails.length())); } cachedContacts.add(contact); } } public ContactHelper createContact(ContactData contact) { initNewContactCreation(); fillContactForm(contact,CREATION); submitContactCreation(); gotoHomePage(); rebuildCacheContacts(); return this; } public ContactHelper midifyContact(int index, ContactData contact) { initContactModificationViaEdit(index + 1); fillContactForm(contact,MODIFICATION); submitContactModification(); gotoHomePage(); rebuildCacheContacts(); return this; } public ContactHelper deleteContact(int index) { initContactModificationViaEdit(index + 1); submitContactRemoving(); gotoHomePage(); rebuildCacheContacts(); return this; } //------------------------------------------------------------------ public ContactHelper submitContactCreation() { click(By.name("submit")); cachedContacts = null; return this; } public ContactHelper fillContactForm(ContactData contact, boolean formType) { type(By.name("firstname"), contact.getFirstName()); type(By.name("lastname"), contact.getLastName()); type(By.name("address"), contact.getAddress1()); type(By.name("home"), contact.getPhoneHome()); type(By.name("mobile"), contact.getPhoneMobile()); type(By.name("work"), contact.getPhoneWork()); type(By.name("email"), contact.getEmail1()); type(By.name("email2"), contact.getEmail2()); selectByText(By.name("bday"), contact.getBirthDay()); selectByText(By.name("bmonth"), contact.getBirthMonth()); type(By.name("byear"), contact.getBirthYear()); if (formType == CREATION) { } else { } type(By.name("address2"), contact.getAddress2()); type(By.name("phone2"), contact.getPhoneHome2()); return this; } public ContactHelper initNewContactCreation() { click(By.linkText("add new")); return this; } public ContactHelper initContactModify() { click(By.name("modifiy")); return this; } public ContactHelper initContactModificationViaEdit(int index) { click(By.xpath("//tr[" + (index + 1) + "]/td/a/img[@alt='Edit']")); return this; } public ContactHelper initContactModificationViaDetails(int index) { click(By.xpath("//tr[" + (index + 1) + "]/td/a/img[@alt='Details']")); return this; } public ContactHelper submitContactModification() { click(By.xpath("//input[@value='Update']")); cachedContacts = null; return this; } public ContactHelper submitContactRemoving() { click(By.xpath("//input[@value='Delete']")); cachedContacts = null; return this; } public ContactHelper gotoHomePage() { click(By.linkText("home")); return this; } }
29.513889
93
0.670118
714a336c729c8133c7f14b74516ac5031c4a5169
5,628
/* Class: CISC 3130 * Section: TY9 * EmplId: ****8149 * Name: Elena Tarasova */ import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import com.opencsv.CSVWriter; import com.opencsv.exceptions.CsvException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; //Main class shows output data to the executive and VIP client public class Main { private static final String FILE_NAME = "data/regional-global-weekly-2020-01-17--2020-01-24.csv"; public static void main(String[] args) throws Exception { //create Map to store name of artists and how many times they appear in chart Map<String, Integer> chart = createChart(readCSVFile(FILE_NAME)); //create List to get artists ratings List<ArtistRating> artistRatings = getArtistRatings(chart); //sort chart by artist ratings artistRatings.sort(new ArtistRatingComparator()); //write sorted chart in file writeCSVFile("output/Artist_Ratings.csv", artistRatings); //sort chart by artist name artistRatings.sort(new ArtistNameComparator()); //write sorted chart in file writeCSVFile("output/Artist_Sorted.csv", artistRatings); } //read csv file using openCSV library private static List<String[]> readCSVFile(String filename) throws IOException, CsvException { //Start reading from line number 2 (line numbers start from zero) CSVReader reader = new CSVReaderBuilder(new FileReader(filename)) .withSkipLines(2) .build(); //Read all rows at once return reader.readAll(); } //write artist ratings to file private static void writeCSVFile(String filename, List<ArtistRating> artistRatings) throws IOException { try (CSVWriter writer = new CSVWriter(new FileWriter(filename))) { writer.writeNext(new String[]{"Artist Name", "Rating"}); writer.writeAll(artistRatingsToRows(artistRatings)); } } //convert artist ratings to rows private static List<String[]> artistRatingsToRows(List<ArtistRating> artistRatings) { // alternative implementation in Java 8 // return artistRatings.stream().map(ArtistRating::toRow).collect(Collectors.toList()); List<String[]> rows = new ArrayList<>(artistRatings.size()); for (ArtistRating artistRating : artistRatings) { rows.add(artistRating.toRow()); } return rows; } //create chart from file private static Map<String, Integer> createChart(List<String[]> rows) throws Exception { Map<String, Integer> chart = new HashMap<>(); for (String[] columns : rows) { String artistName = columns[2]; //if the map contains the artistsName if (chart.containsKey(artistName)) { int count = chart.get(artistName); chart.put(artistName, count + 1); } else { chart.put(artistName, 1); } } return chart; } //get artist ratings private static List<ArtistRating> getArtistRatings(Map<String, Integer> chart) { List<ArtistRating> artistRatings = new LinkedList<>(); for (String artistName : chart.keySet()) { artistRatings.add(new ArtistRating(artistName, chart.get(artistName))); } return artistRatings; } //display artist ratings private static void displayArtistRatings(List<ArtistRating> artistRatings) { // alternative implementation in Java 8 //artistRatings.forEach(System.out::println); for (ArtistRating artistRating : artistRatings) { System.out.println(artistRating); } } } class ArtistRating { private String artistName; private int rating; ArtistRating(String artistName, int rating) { this.artistName = artistName.trim(); this.rating = rating; } String getArtistName() { return artistName; } int getRating() { return rating; } String[] toRow() { // alternative implementation in Java 8 //return new String[]{artistName, Integer.toString(rating)}; String[] row = new String[2]; row[0] = artistName; row[1] = Integer.toString(rating); return row; } public String toString() { return String.format("%-35s %d%n", getArtistName(), getRating()); } } class ArtistNameComparator implements Comparator<ArtistRating> { @Override public int compare(ArtistRating artistRating1, ArtistRating artistRating2) { // sort by name int result = artistRating1.getArtistName().compareToIgnoreCase(artistRating2.getArtistName()); // then sort by rating if name is the same if (result == 0) { result = -(artistRating1.getRating() - artistRating2.getRating()); } return result; } } class ArtistRatingComparator implements Comparator<ArtistRating> { @Override public int compare(ArtistRating artistRating1, ArtistRating artistRating2) { // sort by rating first int result = -(artistRating1.getRating() - artistRating2.getRating()); // then sort by name if rating is the same if (result == 0) { result = artistRating1.getArtistName().compareToIgnoreCase(artistRating2.getArtistName()); } return result; } }
33.301775
108
0.652274
628e277b0a456d9f43610faeb2b0f1d43d8569b9
4,982
package fun.maxs.wheel.util; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Objects; /** * 比较工具 * @author maxs */ public class CompareUtils { private CompareUtils() { } /** * 非空校验 */ private static boolean paramNonNull(BigDecimal a, BigDecimal b){ return Objects.nonNull(a) && Objects.nonNull(b); } /** * 非空校验 */ private static boolean paramNonNull(LocalDateTime a, LocalDateTime b){ return Objects.nonNull(a) && Objects.nonNull(b); } /** * 非空校验 */ private static boolean paramNonNull(LocalDate a, LocalDate b){ return Objects.nonNull(a) && Objects.nonNull(b); } /** * 非空校验 */ private static boolean paramNonNull(LocalTime a, LocalTime b){ return Objects.nonNull(a) && Objects.nonNull(b); } /** * BigDecimal比较 */ public static class BigDecimals { private BigDecimals() { } /** * a > b */ public static boolean gt(BigDecimal a, BigDecimal b) { return paramNonNull(a, b) && a.compareTo(b) > 0; } /** * a >= b */ public static boolean gte(BigDecimal a, BigDecimal b) { return paramNonNull(a, b) && a.compareTo(b) >= 0; } /** * a < b */ public static boolean lt(BigDecimal a, BigDecimal b) { return paramNonNull(a, b) && a.compareTo(b) < 0; } /** * a <= b */ public static boolean lte(BigDecimal a, BigDecimal b) { return paramNonNull(a, b) && a.compareTo(b) <= 0; } /** * a == b */ public static boolean eq(BigDecimal a, BigDecimal b) { return paramNonNull(a, b) && a.compareTo(b) == 0; } } /** * LocalDateTime比较 */ public static class LocalDateTimes { private LocalDateTimes() { } /** * a > b */ public static boolean gt(LocalDateTime a, LocalDateTime b) { return paramNonNull(a, b) && a.compareTo(b) > 0; } /** * a >= b */ public static boolean gte(LocalDateTime a, LocalDateTime b) { return paramNonNull(a, b) && a.compareTo(b) >= 0; } /** * a < b */ public static boolean lt(LocalDateTime a, LocalDateTime b) { return paramNonNull(a, b) && a.compareTo(b) < 0; } /** * a <= b */ public static boolean lte(LocalDateTime a, LocalDateTime b) { return paramNonNull(a, b) && a.compareTo(b) <= 0; } /** * a == b */ public static boolean eq(LocalDateTime a, LocalDateTime b) { return paramNonNull(a, b) && a.compareTo(b) == 0; } } /** * LocalDateTime比较 */ public static class LocalDates { private LocalDates() { } /** * a > b */ public static boolean gt(LocalDate a, LocalDate b) { return paramNonNull(a, b) && a.compareTo(b) > 0; } /** * a >= b */ public static boolean gte(LocalDate a, LocalDate b) { return paramNonNull(a, b) && a.compareTo(b) >= 0; } /** * a < b */ public static boolean lt(LocalDate a, LocalDate b) { return paramNonNull(a, b) && a.compareTo(b) < 0; } /** * a <= b */ public static boolean lte(LocalDate a, LocalDate b) { return paramNonNull(a, b) && a.compareTo(b) <= 0; } /** * a == b */ public static boolean eq(LocalDate a, LocalDate b) { return paramNonNull(a, b) && a.compareTo(b) == 0; } } /** * LocalDateTime比较 */ public static class LocalTimes { private LocalTimes() { } /** * a > b */ public static boolean gt(LocalTime a, LocalTime b) { return paramNonNull(a, b) && a.compareTo(b) > 0; } /** * a >= b */ public static boolean gte(LocalTime a, LocalTime b) { return paramNonNull(a, b) && a.compareTo(b) >= 0; } /** * a < b */ public static boolean lt(LocalTime a, LocalTime b) { return paramNonNull(a, b) && a.compareTo(b) < 0; } /** * a <= b */ public static boolean lte(LocalTime a, LocalTime b) { return paramNonNull(a, b) && a.compareTo(b) <= 0; } /** * a == b */ public static boolean eq(LocalTime a, LocalTime b) { return paramNonNull(a, b) && a.compareTo(b) == 0; } } }
22.958525
74
0.476917
893d409a2fcc6db4d59943633c676a4b1bf4f11c
433
package co.yiiu.plugin; import co.yiiu.domain.Model; import freemarker.template.TemplateException; import io.undertow.server.HttpServerExchange; import java.io.IOException; /** * Created by tomoya at 2019/4/9 * <p> * 视图解析插件,这个插件还要拆,要抽出一个接口定义视图的渲染方法 */ public interface ViewResolvePlugin extends IPlugin { void render(HttpServerExchange exchange, String templatePath, Model model) throws IOException, TemplateException; }
24.055556
117
0.792148
1e422296f9795ccd2a2d38b3f269078a987d222c
2,170
/** * Copyright (c) 2015-present, Horcrux. * All rights reserved. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ package abi14_0_0.host.exp.exponent.modules.api.components.svg; import abi14_0_0.com.facebook.react.ReactPackage; import abi14_0_0.com.facebook.react.bridge.JavaScriptModule; import abi14_0_0.com.facebook.react.bridge.NativeModule; import abi14_0_0.com.facebook.react.bridge.ReactApplicationContext; import abi14_0_0.com.facebook.react.uimanager.ViewManager; import java.util.Arrays; import java.util.Collections; import java.util.List; public class RNSvgPackage implements ReactPackage { @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Arrays.<ViewManager>asList( RNSVGRenderableViewManager.createRNSVGGroupViewManager(), RNSVGRenderableViewManager.createRNSVGPathViewManager(), RNSVGRenderableViewManager.createRNSVGCircleViewManager(), RNSVGRenderableViewManager.createRNSVGEllipseViewManager(), RNSVGRenderableViewManager.createRNSVGLineViewManager(), RNSVGRenderableViewManager.createRNSVGRectViewManager(), RNSVGRenderableViewManager.createRNSVGTextViewManager(), RNSVGRenderableViewManager.createRNSVGImageViewManager(), RNSVGRenderableViewManager.createRNSVGClipPathViewManager(), RNSVGRenderableViewManager.createRNSVGDefsViewManager(), RNSVGRenderableViewManager.createRNSVGUseViewManager(), RNSVGRenderableViewManager.createRNSVGViewBoxViewManager(), RNSVGRenderableViewManager.createRNSVGLinearGradientManager(), RNSVGRenderableViewManager.createRNSVGRadialGradientManager(), new RNSVGSvgViewManager()); } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
39.454545
89
0.759447
cd07ba6b3cd9beabe65dadf68d11b33abc0bfcf4
16,771
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package DECL|package|org.apache.hadoop.mapred.gridmix.emulators.resourceusage package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|mapred operator|. name|gridmix operator|. name|emulators operator|. name|resourceusage package|; end_package begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|annotations operator|. name|VisibleForTesting import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|mapred operator|. name|gridmix operator|. name|Progressive import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|tools operator|. name|rumen operator|. name|ResourceUsageMetrics import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|util operator|. name|ResourceCalculatorPlugin import|; end_import begin_comment comment|/** *<p>A {@link ResourceUsageEmulatorPlugin} that emulates the total heap * usage by loading the JVM heap memory. Adding smaller chunks of data to the * heap will essentially use up some heap space thus forcing the JVM to expand * its heap and thus resulting into increase in the heap usage.</p> * *<p>{@link TotalHeapUsageEmulatorPlugin} emulates the heap usage in steps. * The frequency of emulation can be configured via * {@link #HEAP_EMULATION_PROGRESS_INTERVAL}. * Heap usage values are matched via emulation only at specific interval * boundaries. *</p> * * {@link TotalHeapUsageEmulatorPlugin} is a wrapper program for managing * the heap usage emulation feature. It internally uses an emulation algorithm * (called as core and described using {@link HeapUsageEmulatorCore}) for * performing the actual emulation. Multiple calls to this core engine should * use up some amount of heap. */ end_comment begin_class DECL|class|TotalHeapUsageEmulatorPlugin specifier|public class|class name|TotalHeapUsageEmulatorPlugin implements|implements name|ResourceUsageEmulatorPlugin block|{ comment|// Configuration parameters comment|// the core engine to emulate heap usage DECL|field|emulatorCore specifier|protected name|HeapUsageEmulatorCore name|emulatorCore decl_stmt|; comment|// the progress bar DECL|field|progress specifier|private name|Progressive name|progress decl_stmt|; comment|// decides if this plugin can emulate heap usage or not DECL|field|enabled specifier|private name|boolean name|enabled init|= literal|true decl_stmt|; comment|// the progress boundaries/interval where emulation should be done DECL|field|emulationInterval specifier|private name|float name|emulationInterval decl_stmt|; comment|// target heap usage to emulate DECL|field|targetHeapUsageInMB specifier|private name|long name|targetHeapUsageInMB init|= literal|0 decl_stmt|; comment|/** * The frequency (based on task progress) with which memory-emulation code is * run. If the value is set to 0.1 then the emulation will happen at 10% of * the task's progress. The default value of this parameter is * {@link #DEFAULT_EMULATION_PROGRESS_INTERVAL}. */ DECL|field|HEAP_EMULATION_PROGRESS_INTERVAL specifier|public specifier|static specifier|final name|String name|HEAP_EMULATION_PROGRESS_INTERVAL init|= literal|"gridmix.emulators.resource-usage.heap.emulation-interval" decl_stmt|; comment|// Default value for emulation interval DECL|field|DEFAULT_EMULATION_PROGRESS_INTERVAL specifier|private specifier|static specifier|final name|float name|DEFAULT_EMULATION_PROGRESS_INTERVAL init|= literal|0.1F decl_stmt|; comment|// 10 % DECL|field|prevEmulationProgress specifier|private name|float name|prevEmulationProgress init|= literal|0F decl_stmt|; comment|/** * The minimum buffer reserved for other non-emulation activities. */ DECL|field|MIN_HEAP_FREE_RATIO specifier|public specifier|static specifier|final name|String name|MIN_HEAP_FREE_RATIO init|= literal|"gridmix.emulators.resource-usage.heap.min-free-ratio" decl_stmt|; DECL|field|minFreeHeapRatio specifier|private name|float name|minFreeHeapRatio decl_stmt|; DECL|field|DEFAULT_MIN_FREE_HEAP_RATIO specifier|private specifier|static specifier|final name|float name|DEFAULT_MIN_FREE_HEAP_RATIO init|= literal|0.3F decl_stmt|; comment|/** * Determines the unit increase per call to the core engine's load API. This * is expressed as a percentage of the difference between the expected total * heap usage and the current usage. */ DECL|field|HEAP_LOAD_RATIO specifier|public specifier|static specifier|final name|String name|HEAP_LOAD_RATIO init|= literal|"gridmix.emulators.resource-usage.heap.load-ratio" decl_stmt|; DECL|field|heapLoadRatio specifier|private name|float name|heapLoadRatio decl_stmt|; DECL|field|DEFAULT_HEAP_LOAD_RATIO specifier|private specifier|static specifier|final name|float name|DEFAULT_HEAP_LOAD_RATIO init|= literal|0.1F decl_stmt|; DECL|field|ONE_MB specifier|public specifier|static specifier|final name|int name|ONE_MB init|= literal|1024 operator|* literal|1024 decl_stmt|; comment|/** * Defines the core heap usage emulation algorithm. This engine is expected * to perform certain memory intensive operations to consume some * amount of heap. {@link #load(long)} should load the current heap and * increase the heap usage by the specified value. This core engine can be * initialized using the {@link #initialize(ResourceCalculatorPlugin, long)} * API to suit the underlying hardware better. */ DECL|interface|HeapUsageEmulatorCore specifier|public interface|interface name|HeapUsageEmulatorCore block|{ comment|/** * Performs some memory intensive operations to use up some heap. */ DECL|method|load (long sizeInMB) specifier|public name|void name|load parameter_list|( name|long name|sizeInMB parameter_list|) function_decl|; comment|/** * Initialize the core. */ DECL|method|initialize (ResourceCalculatorPlugin monitor, long totalHeapUsageInMB) specifier|public name|void name|initialize parameter_list|( name|ResourceCalculatorPlugin name|monitor parameter_list|, name|long name|totalHeapUsageInMB parameter_list|) function_decl|; comment|/** * Reset the resource usage */ DECL|method|reset () specifier|public name|void name|reset parameter_list|() function_decl|; block|} comment|/** * This is the core engine to emulate the heap usage. The only responsibility * of this class is to perform certain memory intensive operations to make * sure that some desired value of heap is used. */ DECL|class|DefaultHeapUsageEmulator specifier|public specifier|static class|class name|DefaultHeapUsageEmulator implements|implements name|HeapUsageEmulatorCore block|{ comment|// store the unit loads in a list DECL|field|heapSpace specifier|private specifier|static specifier|final name|ArrayList argument_list|< name|Object argument_list|> name|heapSpace init|= operator|new name|ArrayList argument_list|< name|Object argument_list|> argument_list|() decl_stmt|; comment|/** * Increase heap usage by current process by the given amount. * This is done by creating objects each of size 1MB. */ DECL|method|load (long sizeInMB) specifier|public name|void name|load parameter_list|( name|long name|sizeInMB parameter_list|) block|{ for|for control|( name|long name|i init|= literal|0 init|; name|i operator|< name|sizeInMB condition|; operator|++ name|i control|) block|{ comment|// Create another String object of size 1MB name|heapSpace operator|. name|add argument_list|( operator|( name|Object operator|) operator|new name|byte index|[ name|ONE_MB index|] argument_list|) expr_stmt|; block|} block|} comment|/** * Gets the total number of 1mb objects stored in the emulator. * * @return total number of 1mb objects. */ annotation|@ name|VisibleForTesting DECL|method|getHeapSpaceSize () specifier|public name|int name|getHeapSpaceSize parameter_list|() block|{ return|return name|heapSpace operator|. name|size argument_list|() return|; block|} comment|/** * This will initialize the core and check if the core can emulate the * desired target on the underlying hardware. */ DECL|method|initialize (ResourceCalculatorPlugin monitor, long totalHeapUsageInMB) specifier|public name|void name|initialize parameter_list|( name|ResourceCalculatorPlugin name|monitor parameter_list|, name|long name|totalHeapUsageInMB parameter_list|) block|{ name|long name|maxPhysicalMemoryInMB init|= name|monitor operator|. name|getPhysicalMemorySize argument_list|() operator|/ name|ONE_MB decl_stmt|; if|if condition|( name|maxPhysicalMemoryInMB operator|< name|totalHeapUsageInMB condition|) block|{ throw|throw operator|new name|RuntimeException argument_list|( literal|"Total heap the can be used is " operator|+ name|maxPhysicalMemoryInMB operator|+ literal|" bytes while the emulator is configured to emulate a total of " operator|+ name|totalHeapUsageInMB operator|+ literal|" bytes" argument_list|) throw|; block|} block|} comment|/** * Clear references to all the GridMix-allocated special objects so that * heap usage is reduced. */ annotation|@ name|Override DECL|method|reset () specifier|public name|void name|reset parameter_list|() block|{ name|heapSpace operator|. name|clear argument_list|() expr_stmt|; block|} block|} DECL|method|TotalHeapUsageEmulatorPlugin () specifier|public name|TotalHeapUsageEmulatorPlugin parameter_list|() block|{ name|this argument_list|( operator|new name|DefaultHeapUsageEmulator argument_list|() argument_list|) expr_stmt|; block|} comment|/** * For testing. */ DECL|method|TotalHeapUsageEmulatorPlugin (HeapUsageEmulatorCore core) specifier|public name|TotalHeapUsageEmulatorPlugin parameter_list|( name|HeapUsageEmulatorCore name|core parameter_list|) block|{ name|emulatorCore operator|= name|core expr_stmt|; block|} DECL|method|getTotalHeapUsageInMB () specifier|protected name|long name|getTotalHeapUsageInMB parameter_list|() block|{ return|return name|Runtime operator|. name|getRuntime argument_list|() operator|. name|totalMemory argument_list|() operator|/ name|ONE_MB return|; block|} DECL|method|getMaxHeapUsageInMB () specifier|protected name|long name|getMaxHeapUsageInMB parameter_list|() block|{ return|return name|Runtime operator|. name|getRuntime argument_list|() operator|. name|maxMemory argument_list|() operator|/ name|ONE_MB return|; block|} annotation|@ name|Override DECL|method|getProgress () specifier|public name|float name|getProgress parameter_list|() block|{ return|return name|enabled condition|? name|Math operator|. name|min argument_list|( literal|1f argument_list|, operator|( operator|( name|float operator|) name|getTotalHeapUsageInMB argument_list|() operator|) operator|/ name|targetHeapUsageInMB argument_list|) else|: literal|1.0f return|; block|} annotation|@ name|Override DECL|method|emulate () specifier|public name|void name|emulate parameter_list|() throws|throws name|IOException throws|, name|InterruptedException block|{ if|if condition|( name|enabled condition|) block|{ name|float name|currentProgress init|= name|progress operator|. name|getProgress argument_list|() decl_stmt|; if|if condition|( name|prevEmulationProgress operator|< name|currentProgress operator|&& operator|( operator|( name|currentProgress operator|- name|prevEmulationProgress operator|) operator|>= name|emulationInterval operator||| name|currentProgress operator|== literal|1 operator|) condition|) block|{ name|long name|maxHeapSizeInMB init|= name|getMaxHeapUsageInMB argument_list|() decl_stmt|; name|long name|committedHeapSizeInMB init|= name|getTotalHeapUsageInMB argument_list|() decl_stmt|; comment|// Increase committed heap usage, if needed comment|// Using a linear weighing function for computing the expected usage name|long name|expectedHeapUsageInMB init|= name|Math operator|. name|min argument_list|( name|maxHeapSizeInMB argument_list|, call|( name|long call|) argument_list|( name|targetHeapUsageInMB operator|* name|currentProgress argument_list|) argument_list|) decl_stmt|; if|if condition|( name|expectedHeapUsageInMB operator|< name|maxHeapSizeInMB operator|&& name|committedHeapSizeInMB operator|< name|expectedHeapUsageInMB condition|) block|{ name|long name|bufferInMB init|= call|( name|long call|) argument_list|( name|minFreeHeapRatio operator|* name|expectedHeapUsageInMB argument_list|) decl_stmt|; name|long name|currentDifferenceInMB init|= name|expectedHeapUsageInMB operator|- name|committedHeapSizeInMB decl_stmt|; name|long name|currentIncrementLoadSizeInMB init|= call|( name|long call|) argument_list|( name|currentDifferenceInMB operator|* name|heapLoadRatio argument_list|) decl_stmt|; comment|// Make sure that at least 1 MB is incremented. name|currentIncrementLoadSizeInMB operator|= name|Math operator|. name|max argument_list|( literal|1 argument_list|, name|currentIncrementLoadSizeInMB argument_list|) expr_stmt|; while|while condition|( name|committedHeapSizeInMB operator|+ name|bufferInMB operator|< name|expectedHeapUsageInMB condition|) block|{ comment|// add blocks in order of X% of the difference, X = 10% by default name|emulatorCore operator|. name|load argument_list|( name|currentIncrementLoadSizeInMB argument_list|) expr_stmt|; name|committedHeapSizeInMB operator|= name|getTotalHeapUsageInMB argument_list|() expr_stmt|; block|} block|} comment|// store the emulation progress boundary name|prevEmulationProgress operator|= name|currentProgress expr_stmt|; block|} comment|// reset the core so that the garbage is reclaimed name|emulatorCore operator|. name|reset argument_list|() expr_stmt|; block|} block|} annotation|@ name|Override DECL|method|initialize (Configuration conf, ResourceUsageMetrics metrics, ResourceCalculatorPlugin monitor, Progressive progress) specifier|public name|void name|initialize parameter_list|( name|Configuration name|conf parameter_list|, name|ResourceUsageMetrics name|metrics parameter_list|, name|ResourceCalculatorPlugin name|monitor parameter_list|, name|Progressive name|progress parameter_list|) block|{ name|this operator|. name|progress operator|= name|progress expr_stmt|; comment|// get the target heap usage name|targetHeapUsageInMB operator|= name|metrics operator|. name|getHeapUsage argument_list|() operator|/ name|ONE_MB expr_stmt|; if|if condition|( name|targetHeapUsageInMB operator|<= literal|0 condition|) block|{ name|enabled operator|= literal|false expr_stmt|; return|return; block|} else|else block|{ comment|// calibrate the core heap-usage utility name|emulatorCore operator|. name|initialize argument_list|( name|monitor argument_list|, name|targetHeapUsageInMB argument_list|) expr_stmt|; name|enabled operator|= literal|true expr_stmt|; block|} name|emulationInterval operator|= name|conf operator|. name|getFloat argument_list|( name|HEAP_EMULATION_PROGRESS_INTERVAL argument_list|, name|DEFAULT_EMULATION_PROGRESS_INTERVAL argument_list|) expr_stmt|; name|minFreeHeapRatio operator|= name|conf operator|. name|getFloat argument_list|( name|MIN_HEAP_FREE_RATIO argument_list|, name|DEFAULT_MIN_FREE_HEAP_RATIO argument_list|) expr_stmt|; name|heapLoadRatio operator|= name|conf operator|. name|getFloat argument_list|( name|HEAP_LOAD_RATIO argument_list|, name|DEFAULT_HEAP_LOAD_RATIO argument_list|) expr_stmt|; name|prevEmulationProgress operator|= literal|0 expr_stmt|; block|} block|} end_class end_unit
20.603194
936
0.800489
705670f0894b3e99530c29ea4fd4595ac48e7eee
173
package org.polkadot.types.primitive; /** * An 8-bit signed integer */ public class I8 extends Int { public I8(Object value) { super(value, 8, true); } }
15.727273
37
0.624277
a632b34d74efda24a433489422b279d3c930b9e9
5,034
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2019-2019 the original author or authors. */ package org.quickperf.sql.batch; import org.assertj.core.api.SoftAssertions; import org.junit.Test; import org.junit.experimental.results.PrintableResult; public class ExpectJdbcBatchingTest { @Test public void a_method_annotated_with_jdbc_batches_and_with_batch_size_a_multiple_of_rows_to_insert() { // GIVEN Class<?> testClass = AClassHavingAMethodAnnotatedWithJdbcBatchAndWithBatchSizeAMultipleOfRowsToInsert.class; // WHEN PrintableResult printableResult = PrintableResult.testResult(testClass); // THEN SoftAssertions softAssertions = new SoftAssertions(); softAssertions.assertThat(printableResult.failureCount()) .isEqualTo(0); softAssertions.assertAll(); } @Test public void should_not_fail_if_last_batch_execution_has_a_batch_size_different_from_the_expected_batch_size() { // GIVEN Class<?> testClass = AClassHavingAMethodAnnotatedWithJdbcBatchAndWithBatchSizeNOTAMultipleOfRowsToInsert.class; // WHEN PrintableResult printableResult = PrintableResult.testResult(testClass); // THEN SoftAssertions softAssertions = new SoftAssertions(); softAssertions.assertThat(printableResult.failureCount()) .isEqualTo(0); softAssertions.assertAll(); } @Test public void a_method_annotated_with_jdbc_batches_and_insert_not_batched_in_new_jvm() { // GIVEN Class<?> testClass = AClassHavingAMethodAnnotatedWithExpectJdbcBatchingAndExecutingANotBatchedInsertInNewJvm.class; // WHEN PrintableResult printableResult = PrintableResult.testResult(testClass); // THEN SoftAssertions softAssertions = new SoftAssertions(); softAssertions.assertThat(printableResult.failureCount()) .isEqualTo(1); softAssertions.assertAll(); } @Test public void a_method_annotated_with_jdbc_batches_in_new_jvm() { // GIVEN Class<?> testClass = AClassHavingAMethodAnnotatedExpectJdbcBatchingInNewJvm.class; // WHEN PrintableResult printableResult = PrintableResult.testResult(testClass); // THEN SoftAssertions softAssertions = new SoftAssertions(); softAssertions.assertThat(printableResult.failureCount()) .isEqualTo(0); softAssertions.assertAll(); } @Test public void should_fail_with_a_method_annotated_with_jdbc_batches_and_query_not_batched() { // GIVEN Class<?> testClass = AClassHavingAMethodAnnotatedWithExpectJdbcBatchingAndExecutingANotBatchedInsert.class; // WHEN PrintableResult printableResult = PrintableResult.testResult(testClass); // THEN SoftAssertions softAssertions = new SoftAssertions(); softAssertions.assertThat(printableResult.failureCount()) .isEqualTo(1); softAssertions.assertThat(printableResult.toString()) .contains("[PERF] Expected batch size <30> but is <0>."); softAssertions.assertAll(); } @Test public void should_verify_that_sql_orders_are_batched_without_checking_batch_size() { // GIVEN Class<?> testClass = AClassHavingAPassingMethodAnnotatedExpectJdbcBatchingWithoutBatchSize.class; // WHEN PrintableResult printableResult = PrintableResult.testResult(testClass); // THEN SoftAssertions softAssertions = new SoftAssertions(); softAssertions.assertThat(printableResult.failureCount()) .isEqualTo(0); softAssertions.assertAll(); } @Test public void should_fail_with_not_batched_query_and_no_batch_size_parameter_in_expect_jdbc_batching_annotation() { // GIVEN Class<?> testClass = AClassHavingAFailingMethodAnnotatedExpectJdbcBatchingWithoutBatchSize.class; // WHEN PrintableResult printableResult = PrintableResult.testResult(testClass); // THEN SoftAssertions softAssertions = new SoftAssertions(); softAssertions.assertThat(printableResult.failureCount()) .isEqualTo(1); softAssertions.assertThat(printableResult.toString()) .contains("[PERF] SQL executions were supposed to be batched."); softAssertions.assertAll(); } }
33.785235
123
0.701828
89a339ff426b294107c80b45bfbdb92fdea0912e
5,179
/* * Copyright (c) 2008-2012, Matthias Mann * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Matthias Mann 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 OWNER 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 de.matthiasmann.twlthemeeditor.properties; import de.matthiasmann.twl.model.Property; import de.matthiasmann.twl.model.StringModel; import de.matthiasmann.twl.utils.CallbackSupport; import de.matthiasmann.twlthemeeditor.datamodel.Utils; import de.matthiasmann.twlthemeeditor.dom.Attribute; import de.matthiasmann.twlthemeeditor.dom.AttributeList.AttributeListListener; import de.matthiasmann.twlthemeeditor.dom.Element; import de.matthiasmann.twlthemeeditor.dom.Namespace; /** * * @author Matthias Mann */ public class AttributeProperty implements Property<String>, StringModel { private final Element element; private final String attribute; private final String name; private final boolean canBeNull; private final AttributeListListener all; private Runnable[] callbacks = null; public AttributeProperty(Element element, String attribute) { this(element, attribute, Utils.capitalize(attribute), false); } public AttributeProperty(Element element, String attribute, String name, boolean canBeNull) { this.element = element; this.attribute = attribute; this.name = name; this.canBeNull = canBeNull; this.all = new ALL(); } public String getName() { return name; } public boolean isReadOnly() { return false; } public boolean canBeNull() { return canBeNull; } public Class<String> getType() { return String.class; } public String getValue() { return element.getAttributeValue(attribute); } public void setValue(String value) throws IllegalArgumentException { if(!canBeNull && value == null) { throw new NullPointerException("value"); } String curValue = element.getAttributeValue(attribute); if(!Utils.equals(curValue, value)) { if(value == null) { element.removeAttribute(attribute); } else { element.setAttribute(attribute, value); } } } public String getPropertyValue() { return getValue(); } public void setPropertyValue(String value) throws IllegalArgumentException { setValue(value); } public void addCallback(Runnable cb) { boolean wasEmpty = (callbacks == null); callbacks = CallbackSupport.addCallbackToList(callbacks, cb, Runnable.class); if(wasEmpty) { element.getAttributes().addListener(all); } } public void removeCallback(Runnable cb) { callbacks = CallbackSupport.removeCallbackFromList(callbacks, cb); if(callbacks == null) { element.getAttributes().removeListener(all); } } public void addValueChangedCallback(Runnable cb) { addCallback(cb); } public void removeValueChangedCallback(Runnable cb) { removeCallback(cb); } void check(Attribute attribute) { if(attribute.equals(this.attribute, Namespace.NO_NAMESPACE)) { CallbackSupport.fireCallbacks(callbacks); } } class ALL implements AttributeListListener { public void attributeAdded(Element element, Attribute attribute, int index) { check(attribute); } public void attributeChanged(Element element, Attribute attribute, String oldValue, String newValue) { check(attribute); } public void attributeRemoved(Element element, Attribute attribute, int index) { check(attribute); } } }
34.758389
110
0.68855
9ae6b8b3c2e06120b7cbcbc4e3c74c6e39cc8c19
4,226
/** * Copyright 2018 eussence.com and contributors * 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.namba.arrays; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import io.namba.arrays.data.tuple.Three; import io.namba.arrays.data.tuple.Two; /** * * @author Ernest Kiwele * */ public class CategoryList implements NambaList { private final String[] levels; private final int[] value; private final Map<Integer, String> mapping; protected CategoryList(List<String> is) { Three<String[], int[], Map<Integer, String>> map = toCategory(is); this.levels = map.a(); this.value = map.b(); this.mapping = map.c(); } protected CategoryList(String[] levels, int[] value, Map<Integer, String> mapping) { this.levels = levels; this.value = value; this.mapping = mapping; } public static CategoryList of(StringList sl) { return new CategoryList(sl.value); } private static Three<String[], int[], Map<Integer, String>> toCategory(List<String> list) { Map<String, Integer> cats = new HashMap<>(); int[] res = new int[list.size()]; int[] v = { 0 }; for (int i = 0; i < list.size(); i++) { String s = list.get(i); int position = cats.computeIfAbsent(s, a -> v[0]++); res[i] = position; } String[] levels = cats.entrySet().stream().sorted(Map.Entry.comparingByValue()).map(Map.Entry::getKey) .toArray(i -> new String[i]); Map<Integer, String> levelMapping = cats.entrySet().stream().map(vv -> Two.of(vv.getValue(), vv.getKey())) .collect(Collectors.toMap(Two::a, Two::b)); return Three.of(levels, res, levelMapping); } @Override public DataType dataType() { return DataType.CATEGORY; } @Override public Index index() { return null; } @Override public CategoryList repeat(int n) { int[] v = new int[n * this.value.length]; for (int i = 0; i < n; i++) { System.arraycopy(this.value, 0, v, i * this.value.length, this.value.length); } return new CategoryList(this.levels, v, this.mapping); } @Override public int size() { return this.value.length; } @Override public StringList string() { return StringList.of(Arrays.stream(this.value).mapToObj(this.mapping::get).collect(Collectors.toList())); } @Override public StringList getAt(int[] loc) { return StringList.of(Arrays.stream(loc).mapToObj(i -> mapping.get(this.value[i])).collect(Collectors.toList())); } public CategoryList addCategories(String... newCategories) { if (null == newCategories || 0 == newCategories.length) { return this; } List<String> all = new ArrayList<>(Arrays.asList(this.levels)); all.addAll(Arrays.asList(newCategories)); Three<String[], int[], Map<Integer, String>> th = toCategory(all); Map<Integer, String> newMap = new LinkedHashMap<>(this.mapping); newMap.putAll(th.c()); return new CategoryList(th.a(), this.value, newMap); } public CategoryList reorder(List<String> newOrder) { // TODO: implement return null; } public CategoryList sorted() { // TODO: implement return null; } public CategoryList sortedReverse() { // TODO: implement return null; } public List<String> levels() { return Arrays.asList(this.levels); } @Override public IntList asInt() { return null; } @Override public LongList asLong() { return null; } @Override public DoubleList asDouble() { return null; } @Override public Mask asMask() { return null; } // public CategoryList renameCategories(Map<String, String> nameMapping) { // // } // // public CategoryList renameCategory(String oldName, String newName) { // // } }
24.011364
114
0.689541
281085ba50b3a36659cdb4b004a4eb2690338ecf
2,343
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.hadoopathome.intellij.viewer.table; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; public class TableFormatterTest { @Test @DisplayName("Assert that JSON records can be correctly extracted and formatted") public void testFormatTable() { List<String> jsonRecords = Arrays.asList( "{\"name\" : \"Joe Cole\", \"subject\" : \"Science\"}", "{\"name\" : \"Susan Jones\", \"subject\" : \"Chemistry\"}"); TableFormatter tableFormatter = new TableFormatter(jsonRecords); Set<String> outputColumns = new HashSet<>(Arrays.asList(tableFormatter.getColumns())); Set<String> expectedColumns = new HashSet<>(Arrays.asList("name", "subject")); assertThat(expectedColumns).isEqualTo(outputColumns); String[][] rows = tableFormatter.getRows(); Set<String> outputFirstRow = new HashSet<>(Arrays.asList(rows[0])); Set<String> expectedFirstRow = new HashSet<>(Arrays.asList("Joe Cole", "Science")); assertThat(expectedFirstRow).isEqualTo(outputFirstRow); } @Test @DisplayName("Assert that invalid JSON records are not formatted and an empty table is produced") public void testFormatTableInvalidJson() { List<String> jsonRecords = Arrays.asList("{\"name\" : \"Joe Cole\", \"subject\" : \"Science\"}", "{invalid}"); TableFormatter tableFormatter = new TableFormatter(jsonRecords); Set<String> outputColumns = new HashSet<>(Arrays.asList(tableFormatter.getColumns())); assertThat(outputColumns).isEmpty(); String[][] rows = tableFormatter.getRows(); assertThat(rows).isEmpty(); } }
39.711864
99
0.711908
66ef837465dd03a5a57b068477636368b4c096ff
616
package com.battlelancer.seriesguide.settings; import android.content.Context; import android.preference.PreferenceManager; /** * Settings related to the Now tab. */ public class NowSettings { public static final String KEY_DISPLAY_RELEASED_TODAY = "com.battlelancer.seriesguide.now.releasedtoday"; /** * Whether the Now tab should display episodes released today. */ public static boolean isDisplayingReleasedToday(Context context) { return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(KEY_DISPLAY_RELEASED_TODAY, true); } }
28
70
0.733766
4ce72fa7ad670f7a1ba86f68479a53291c2d8a2c
10,906
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.messaging.eventhubs.implementation; import com.azure.core.amqp.AmqpEndpointState; import com.azure.core.amqp.AmqpLink; import com.azure.core.amqp.CBSNode; import com.azure.core.amqp.Retry; import com.azure.core.implementation.util.ImplUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.EventHubProducer; import com.azure.messaging.eventhubs.implementation.handler.ReceiveLinkHandler; import com.azure.messaging.eventhubs.implementation.handler.SendLinkHandler; import com.azure.messaging.eventhubs.implementation.handler.SessionHandler; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.UnknownDescribedType; import org.apache.qpid.proton.amqp.messaging.Source; import org.apache.qpid.proton.amqp.messaging.Target; import org.apache.qpid.proton.amqp.transport.ReceiverSettleMode; import org.apache.qpid.proton.amqp.transport.SenderSettleMode; import org.apache.qpid.proton.engine.BaseHandler; import org.apache.qpid.proton.engine.EndpointState; import org.apache.qpid.proton.engine.Receiver; import org.apache.qpid.proton.engine.Sender; import org.apache.qpid.proton.engine.Session; import reactor.core.Disposable; import reactor.core.Disposables; import reactor.core.publisher.Mono; import java.io.IOException; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; class ReactorSession extends EndpointStateNotifierBase implements EventHubSession { private static final Symbol EPOCH = Symbol.valueOf(AmqpConstants.VENDOR + ":epoch"); private static final Symbol RECEIVER_IDENTIFIER_NAME = Symbol.valueOf(AmqpConstants.VENDOR + ":receiver-name"); private final ConcurrentMap<String, AmqpSendLink> openSendLinks = new ConcurrentHashMap<>(); private final ConcurrentMap<String, AmqpReceiveLink> openReceiveLinks = new ConcurrentHashMap<>(); private final Session session; private final SessionHandler sessionHandler; private final String sessionName; private final ReactorProvider provider; private final TokenResourceProvider audienceProvider; private final Duration openTimeout; private final Disposable.Composite subscriptions; private final ReactorHandlerProvider handlerProvider; private final Mono<CBSNode> cbsNodeSupplier; ReactorSession(Session session, SessionHandler sessionHandler, String sessionName, ReactorProvider provider, ReactorHandlerProvider handlerProvider, Mono<CBSNode> cbsNodeSupplier, TokenResourceProvider audienceProvider, Duration openTimeout) { super(new ClientLogger(ReactorSession.class)); this.session = session; this.sessionHandler = sessionHandler; this.handlerProvider = handlerProvider; this.sessionName = sessionName; this.provider = provider; this.cbsNodeSupplier = cbsNodeSupplier; this.audienceProvider = audienceProvider; this.openTimeout = openTimeout; this.subscriptions = Disposables.composite( this.sessionHandler.getEndpointStates().subscribe( this::notifyEndpointState, this::notifyError, () -> notifyEndpointState(EndpointState.CLOSED)), this.sessionHandler.getErrors().subscribe( this::notifyError, this::notifyError, () -> notifyEndpointState(EndpointState.CLOSED))); session.open(); } Session session() { return this.session; } @Override public void close() { openReceiveLinks.forEach((key, link) -> { try { link.close(); } catch (IOException e) { logger.asError().log("Error closing send link: " + key, e); } }); openReceiveLinks.clear(); openSendLinks.forEach((key, link) -> { try { link.close(); } catch (IOException e) { logger.asError().log("Error closing receive link: " + key, e); } }); openSendLinks.clear(); subscriptions.dispose(); super.close(); } @Override public String getSessionName() { return sessionName; } @Override public Duration getOperationTimeout() { return openTimeout; } @Override public Mono<AmqpLink> createProducer(String linkName, String entityPath, Duration timeout, Retry retry) { final ActiveClientTokenManager tokenManager = createTokenManager(entityPath); return getConnectionStates().takeUntil(state -> state == AmqpEndpointState.ACTIVE) .timeout(timeout) .then(tokenManager.authorize().then(Mono.create(sink -> { final AmqpSendLink existingSender = openSendLinks.get(linkName); if (existingSender != null) { sink.success(existingSender); return; } final Sender sender = session.sender(linkName); final Target target = new Target(); target.setAddress(entityPath); sender.setTarget(target); final Source source = new Source(); sender.setSource(source); sender.setSenderSettleMode(SenderSettleMode.UNSETTLED); final SendLinkHandler sendLinkHandler = handlerProvider.createSendLinkHandler( sessionHandler.getConnectionId(), sessionHandler.getHostname(), linkName, entityPath); BaseHandler.setHandler(sender, sendLinkHandler); try { provider.getReactorDispatcher().invoke(() -> { sender.open(); final ReactorSender reactorSender = new ReactorSender(entityPath, sender, sendLinkHandler, provider, tokenManager, timeout, retry, EventHubProducer.MAX_MESSAGE_LENGTH_BYTES); openSendLinks.put(linkName, reactorSender); sink.success(reactorSender); }); } catch (IOException e) { sink.error(e); } }))); } @Override public Mono<AmqpLink> createConsumer(String linkName, String entityPath, Duration timeout, Retry retry) { return createConsumer(linkName, entityPath, "", timeout, retry, null, null); } @Override public Mono<AmqpLink> createConsumer(String linkName, String entityPath, String eventPositionExpression, Duration timeout, Retry retry, Long ownerLevel, String consumerIdentifier) { final ActiveClientTokenManager tokenManager = createTokenManager(entityPath); return getConnectionStates().takeUntil(state -> state == AmqpEndpointState.ACTIVE) .timeout(timeout) .then(tokenManager.authorize().then(Mono.create(sink -> { final AmqpReceiveLink existingReceiver = openReceiveLinks.get(linkName); if (existingReceiver != null) { sink.success(existingReceiver); return; } final Receiver receiver = session.receiver(linkName); final Source source = new Source(); source.setAddress(entityPath); if (!ImplUtils.isNullOrEmpty(eventPositionExpression)) { final Map<Symbol, UnknownDescribedType> filter = new HashMap<>(); filter.put(AmqpConstants.STRING_FILTER, new UnknownDescribedType(AmqpConstants.STRING_FILTER, eventPositionExpression)); source.setFilter(filter); } //TODO (conniey): support creating a filter when we've already received some events. I believe this in // the cause of recreating a failing link. // final Map<Symbol, UnknownDescribedType> filterMap = MessageReceiver.this.settingsProvider.getFilter(MessageReceiver.this.lastReceivedMessage); // if (filterMap != null) { // source.setFilter(filterMap); // } receiver.setSource(source); final Target target = new Target(); receiver.setTarget(target); // Use explicit settlement via dispositions (not pre-settled) receiver.setSenderSettleMode(SenderSettleMode.UNSETTLED); receiver.setReceiverSettleMode(ReceiverSettleMode.SECOND); Map<Symbol, Object> properties = new HashMap<>(); if (ownerLevel != null) { properties.put(EPOCH, ownerLevel); } if (!ImplUtils.isNullOrEmpty(consumerIdentifier)) { properties.put(RECEIVER_IDENTIFIER_NAME, consumerIdentifier); } if (!properties.isEmpty()) { receiver.setProperties(properties); } // TODO (conniey): After preview 1 feature to enable keeping partition information updated. // static final Symbol ENABLE_RECEIVER_RUNTIME_METRIC_NAME = Symbol.valueOf(VENDOR + ":enable-receiver-runtime-metric"); // if (keepPartitionInformationUpdated) { // receiver.setDesiredCapabilities(new Symbol[]{ENABLE_RECEIVER_RUNTIME_METRIC_NAME}); // } final ReceiveLinkHandler receiveLinkHandler = handlerProvider.createReceiveLinkHandler( sessionHandler.getConnectionId(), sessionHandler.getHostname(), linkName, entityPath); BaseHandler.setHandler(receiver, receiveLinkHandler); try { provider.getReactorDispatcher().invoke(() -> { receiver.open(); final ReactorReceiver reactorReceiver = new ReactorReceiver(entityPath, receiver, receiveLinkHandler, tokenManager); openReceiveLinks.put(linkName, reactorReceiver); sink.success(reactorReceiver); }); } catch (IOException e) { sink.error(e); } }))); } /** * {@inheritDoc} */ @Override public boolean removeLink(String linkName) { return (openSendLinks.remove(linkName) != null) || openReceiveLinks.remove(linkName) != null; } private ActiveClientTokenManager createTokenManager(String entityPath) { final String tokenAudience = audienceProvider.getResourceString(entityPath); return new ActiveClientTokenManager(cbsNodeSupplier, tokenAudience); } }
43.106719
198
0.643316
3b6e2851815d8cc43aa0d93392240a0beaa192bc
363
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package packages; /** * * @author Matias */ public class Console { public static void log(Object log){ System.out.println(log); } }
20.166667
101
0.688705
a4701e4b2ed2ab61cb77de7ef07ab45f2daafdca
5,431
package seedu.clinic.model.warehouse; import static java.util.Objects.requireNonNull; import static seedu.clinic.commons.util.CollectionUtil.requireAllNonNull; import java.util.Iterator; import java.util.List; import java.util.Optional; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import seedu.clinic.model.attribute.Name; import seedu.clinic.model.warehouse.exceptions.DuplicateWarehouseException; import seedu.clinic.model.warehouse.exceptions.WarehouseNotFoundException; /** * A list of warehouses that enforces uniqueness between its elements and does not allow nulls. * A warehouse is considered unique by comparing using {@code Warehouse#isSameWarehouse(Warehouse)}. As such, adding * and updating of warehouses uses Warehouse#isSameWarehouse(Warehouse) for equality so as to ensure that the warehouse * being added or updated is unique in terms of identity in the UniqueWarehouseList. * However, the removal of a warehouse uses Warehouse#equals(Object) so as to ensure that the warehouse with * exactly the same fields will be removed. * * Supports a minimal set of list operations. * * @see Warehouse#isSameWarehouse(Warehouse) */ public class UniqueWarehouseList implements Iterable<Warehouse> { private final ObservableList<Warehouse> internalList = FXCollections.observableArrayList(); private final ObservableList<Warehouse> internalUnmodifiableList = FXCollections.unmodifiableObservableList(internalList); /** * Returns true if the list contains an equivalent warehouses as the given argument. */ public boolean contains(Warehouse toCheck) { requireNonNull(toCheck); return internalList.stream().anyMatch(toCheck::isSameWarehouse); } /** * Adds a warehouse to the list. * The warehouse must not already exist in the list. */ public void add(Warehouse warehouseToAdd) { requireNonNull(warehouseToAdd); if (contains(warehouseToAdd)) { throw new DuplicateWarehouseException(); } internalList.add(warehouseToAdd); } /** * Returns the warehouse corresponding to the name specified in an optional wrapper if it exists, * and an empty optional otherwise. */ public Optional<Warehouse> getWarehouse(Name warehouseName) { requireNonNull(warehouseName); return internalList.stream().filter((Warehouse warehouse)->warehouse.getName() .equals(warehouseName)).findFirst(); } /** * Replaces the warehouse {@code target} in the list with {@code editedWarehouse}. * {@code target} must exist in the list. * The warehouse identity of {@code editedWarehouse} must not be the same as another existing warehouse in the list. */ public void setWarehouse(Warehouse target, Warehouse editedWarehouse) { requireAllNonNull(target, editedWarehouse); int index = internalList.indexOf(target); if (index == -1) { throw new WarehouseNotFoundException(); } if (!target.isSameWarehouse(editedWarehouse) && contains(editedWarehouse)) { throw new DuplicateWarehouseException(); } internalList.set(index, editedWarehouse); } /** * Removes the equivalent warehouse from the list. * The warehouse must exist in the list. */ public void remove(Warehouse toRemove) { requireNonNull(toRemove); if (!internalList.remove(toRemove)) { throw new WarehouseNotFoundException(); } } /** * Replaces the current list of warehouses in {@code internalList} with a new {@code replacement}. */ public void setWarehouses(UniqueWarehouseList replacement) { requireNonNull(replacement); internalList.setAll(replacement.internalList); } /** * Replaces the contents of this list with {@code warehouses}. * {@code warehouses} must not contain duplicate warehouses. */ public void setWarehouses(List<Warehouse> warehouses) { requireAllNonNull(warehouses); if (!warehousesAreUnique(warehouses)) { throw new DuplicateWarehouseException(); } internalList.setAll(warehouses); } /** * Returns the backing list as an unmodifiable {@code ObservableList}. */ public ObservableList<Warehouse> asUnmodifiableObservableList() { return internalUnmodifiableList; } @Override public Iterator<Warehouse> iterator() { return internalList.iterator(); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof UniqueWarehouseList // instanceof handles nulls && internalList.equals(((UniqueWarehouseList) other).internalList)); } @Override public int hashCode() { return internalList.hashCode(); } /** * Returns true if {@code warehouses} contains only unique warehouses. */ private boolean warehousesAreUnique(List<Warehouse> warehouses) { for (int i = 0; i < warehouses.size() - 1; i++) { for (int j = i + 1; j < warehouses.size(); j++) { if (warehouses.get(i).isSameWarehouse(warehouses.get(j))) { return false; } } } return true; } }
35.266234
120
0.679249
6f40fa52b1c17dcd5f227fdfb99a1abf7cc41100
390
public class LogicOperation { public static void main(String args[]) { boolean a = true; boolean b = false; System.out.println("a && b = " + (a && b)); System.out.println("a || b = " + (a || b)); System.out.println("!a = " + (!a)); System.out.println("a ^ b = " + (a ^ b)); } }
35.454545
59
0.405128
b9102d8905e248085bba717bb5c7415389c69bff
3,681
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT Project | | | | 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.conqat.engine.java.library; import java.io.OutputStream; import org.apache.log4j.Level; import org.apache.log4j.Logger; /** * This class is an adapter to log information written to an outputstream with * log4j. It processes all data written to the stream and logs it line-wise * everytime a linebreak (\n, \r or \r\n) is written to the stream. * * @author Florian Deissenboeck * @author $Author: kinnen $ * * @version $Rev: 41751 $ * @ConQAT.Rating GREEN Hash: BC46B289E4597AEF11819A69D1DDF150 */ /* package */class Stream2LoggerAdapter extends OutputStream { /** current line */ private StringBuilder line = new StringBuilder(); /** * this is or handling \r\n linebreaks. Set to <code>true</code> if last * character written to the stream was an \r. So it can look ahead and check * if the next character is \n */ private boolean inR; /** The logger to write the ouput to. */ private final Logger logger; /** The log level to use. */ private final Level level; /** The line prefix for logging. */ private final String prefix; /** * Create a new adapter. * * @param logger * The logger to write output to. * @param level * The log level to use. */ public Stream2LoggerAdapter(Logger logger, Level level) { this(logger, level, null); } /** * Create a new adapter. * * @param logger * The logger to write output to. * @param level * The log level to use. * @param prefix * A prefix for every log message. */ public Stream2LoggerAdapter(Logger logger, Level level, String prefix) { this.logger = logger; this.level = level; this.prefix = prefix; } /** * Write a single byte. If the byte is not a line terminator it will be * append to the current line. If it's a line terminator. The current line * will be logged and cleared. */ @Override public void write(int b) { char c = (char) b; if (c == '\n') { printLine(); inR = false; return; } else if (c == '\r') { inR = true; return; } // was a single '\r' if (inR) { inR = false; printLine(); return; } line.append(c); } /** Log the current line and clear it. */ private void printLine() { String message; if (prefix == null) { message = line.toString(); } else { message = prefix + ": " + line.toString(); } logger.log(level, message); line = new StringBuilder(); } }
29.448
78
0.545776
81dd99d88e12bf2d6e0e9c61c358214c7b6d7864
1,352
package ch.awae.datasocket; import java.io.IOException; import java.io.Serializable; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.function.Function; class ServersideImpl extends BaseSocket { private final ServerImpl server; private final TypedMapping<Function<Serializable, Serializable>> processorMappings; ServersideImpl(ServerImpl server, Socket socket, ExecutorService service, TypedMapping<Function<Serializable, Serializable>> processorMappings) throws IOException { super(socket, service); this.server = server; this.processorMappings = processorMappings; } @Override protected void handleMessage(Message message) throws IOException { if (message.getType() == MessageType.QUERY) { try { Function<Serializable, Serializable> function = processorMappings.get(message.getPayload().getClass()); Serializable response = function.apply(message.getPayload()); send(new Message(MessageType.RESPONSE, message.getUuid(), response)); } catch (RuntimeException rex) { send(new Message(MessageType.RESPONSE, message.getUuid(), rex)); } } } @Override protected void onConnectionClosed() { server.connectionClosed(this); } }
35.578947
168
0.693787
ceb8e1f535d416148b9a9fcdad08a972755f3dcd
1,141
package nrt.boot.prefs; import org.nutz.dao.entity.annotation.ColDefine; import org.nutz.dao.entity.annotation.ColType; import org.nutz.dao.entity.annotation.Column; import org.nutz.dao.entity.annotation.Name; import org.nutz.dao.entity.annotation.Table; @Table("core_preferences") public class Preference { @Name @Column("pref_key") @ColDefine(notNull=true, update=false, width=200) private String key; @Column("pref_value") @ColDefine(type=ColType.TEXT) private String value; @Column("descriptions") @ColDefine(width=200) private String description; @Column("pref_ns") @ColDefine(update=false, width=200) private String namespace; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } }
21.942308
76
0.744084
edd47e778e02d8e82b501408f1c159586799f468
937
package dm.audiostreamerdemo.network; public class Like { String act; String al; String from; String hash; String object; String wall; public String getAct() { return act; } public void setAct(String act) { this.act = act; } public String getAl() { return al; } public void setAl(String al) { this.al = al; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getHash() { return hash; } public void setHash(String hash) { this.hash = hash; } public String getObject() { return object; } public void setObject(String object) { this.object = object; } public String getWall() { return wall; } public void setWall(String wall) { this.wall = wall; } }
15.616667
42
0.543223
e3a26e5368b018e39a7a02c08f55618132d179d0
546
package org.cybcode.stix.core.compiler; import org.cybcode.stix.api.StiXtractor; import org.cybcode.stix.api.StiXtractor.Parameter; public class SlotLink { public final RegularParserSlot target; public final StiXtractor.Parameter<?> parameter; public SlotLink(RegularParserSlot target, Parameter<?> parameter) { this.target = target; this.parameter = parameter; } @Override public String toString() { if (target == null) return "RESULT"; return parameter.toNameString() + "=" + target.toNameString(); } }
24.818182
67
0.71978
43ff228353614e288fd632606c8f21e8b49d8e6d
450
package com.javaeedev.util; import org.junit.Test; import static org.junit.Assert.assertEquals; public class GZipUtilTest { @Test public void testGzipAndUngzip() { final String text = "abcdefg \r\n hijklmn \t opqrst \u3000 uvwxyz"; byte[] data = text.getBytes(); byte[] gzipped = GZipUtil.gzip(data); byte[] gunzipped = GZipUtil.gunzip(gzipped); assertEquals(text, new String(gunzipped)); } }
23.684211
75
0.66
a3530af264f7b0e9a16773f9669c95eeb3d7a28d
1,270
package data_structures.linked_list; public class Main { private static int NUMBER_OF_NODES = 24; public static void main(String[] args) { // testing reverse linked list function Node head1 = new Node(); Node next1 = new Node(); head1.next = next1; int i = 0; while(i < NUMBER_OF_NODES) { next1.next = new Node(); next1 = next1.next; i++; } print_linked_list(head1); Node new_head1 = Reverse.reverse_linked_list(head1); print_linked_list(new_head1); // testing sort linked list function Node head2 = new Node(3); head2.next = new Node(2); head2.next.next = new Node(5); head2.next.next.next = new Node(4); head2.next.next.next.next = new Node(1); head2.next.next.next.next.next = new Node(6); print_linked_list(head2); Node new_head2 = Sort.merge_sort_linked_list(head2); print_linked_list(new_head2); } private static void print_linked_list(Node node) { Node copy = node.copy(); while(copy != null) { System.out.print(copy.data + " -> "); copy = copy.next; } System.out.println("null"); } }
28.863636
60
0.571654
d57eb5f8b31cf70baab3c83b166f71f4310b1439
540
import java.util.*; public class Wildcards{ public static void main(String[] args){ List<String> ls = new ArrayList(); ls.add("String1"); ls.add("String2"); print(ls); Collection<Planet> cp = new ArrayList(); cp.add(new Planet("Mercury", 0.06)); cp.add(new Planet("Venus", 0.82)); print(cp); } public static void print(Collection<?> collection){ for (Object o : collection){ System.out.println(o); } } }
22.5
56
0.518519
77012d37baa605600a7158ce8a5818ecb92c6fb5
243
package chkui.springcore.example.hybrid.profile.service.konami; import chkui.springcore.example.hybrid.profile.service.Konami; public class Castlevania implements Konami { @Override public String getName() { return "Castlevania"; } }
18.692308
63
0.786008
0217273c3e3fea068bc0eed85acc9d9b2b089ec8
1,745
// automatically generated by the FlatBuffers compiler, do not modify package ppx; import java.nio.*; import java.lang.*; import java.util.*; import com.google.flatbuffers.*; @SuppressWarnings("unused") public final class Normal extends Table { public static Normal getRootAsNormal(ByteBuffer _bb) { return getRootAsNormal(_bb, new Normal()); } public static Normal getRootAsNormal(ByteBuffer _bb, Normal obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public void __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; } public Normal __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } public Tensor mean() { return mean(new Tensor()); } public Tensor mean(Tensor obj) { int o = __offset(4); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } public Tensor stddev() { return stddev(new Tensor()); } public Tensor stddev(Tensor obj) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } public static int createNormal(FlatBufferBuilder builder, int meanOffset, int stddevOffset) { builder.startObject(2); Normal.addStddev(builder, stddevOffset); Normal.addMean(builder, meanOffset); return Normal.endNormal(builder); } public static void startNormal(FlatBufferBuilder builder) { builder.startObject(2); } public static void addMean(FlatBufferBuilder builder, int meanOffset) { builder.addOffset(0, meanOffset, 0); } public static void addStddev(FlatBufferBuilder builder, int stddevOffset) { builder.addOffset(1, stddevOffset, 0); } public static int endNormal(FlatBufferBuilder builder) { int o = builder.endObject(); return o; } }
43.625
179
0.724355
3ff28a1b80a313cf5adbfe876e8153aea85c8111
570
package com.liushaoming.jseckill.backend.dto; import java.io.Serializable; public class SeckillMsgBody implements Serializable { private static final long serialVersionUID = -4206751408398568444L; private long seckillId; private long userPhone; public long getSeckillId() { return seckillId; } public void setSeckillId(long seckillId) { this.seckillId = seckillId; } public long getUserPhone() { return userPhone; } public void setUserPhone(long userPhone) { this.userPhone = userPhone; } }
24.782609
71
0.694737
74da0da00977b1031a2546eb51dca5f0a37933cc
1,233
package com.dnsimple.data; import java.time.OffsetDateTime; public class DomainPush { private final Long id; private final Long domainId; private final Long contactId; private final Long accountId; private final OffsetDateTime acceptedAt; private final OffsetDateTime createdAt; private final OffsetDateTime updatedAt; public DomainPush(Long id, Long domainId, Long contactId, Long accountId, OffsetDateTime acceptedAt, OffsetDateTime createdAt, OffsetDateTime updatedAt) { this.id = id; this.domainId = domainId; this.contactId = contactId; this.accountId = accountId; this.acceptedAt = acceptedAt; this.createdAt = createdAt; this.updatedAt = updatedAt; } public Long getId() { return id; } public Long getDomainId() { return domainId; } public Long getContactId() { return contactId; } public Long getAccountId() { return accountId; } public OffsetDateTime getAcceptedAt() { return acceptedAt; } public OffsetDateTime getCreatedAt() { return createdAt; } public OffsetDateTime getUpdatedAt() { return updatedAt; } }
23.711538
158
0.660178
715f7c90372100bfcb761c5ad0ebcd842eb7354f
30,911
package astro.tool.box.module; import static astro.tool.box.function.NumericFunctions.*; import static astro.tool.box.function.PhotometricFunctions.*; import static astro.tool.box.module.ModuleHelper.*; import static astro.tool.box.module.tab.SettingsTab.*; import astro.tool.box.container.BatchResult; import astro.tool.box.container.catalog.AllWiseCatalogEntry; import astro.tool.box.container.catalog.CatalogEntry; import astro.tool.box.container.catalog.SimbadCatalogEntry; import astro.tool.box.container.catalog.WhiteDwarf; import astro.tool.box.container.lookup.BrownDwarfLookupEntry; import astro.tool.box.container.lookup.SpectralTypeLookup; import astro.tool.box.container.lookup.SpectralTypeLookupEntry; import astro.tool.box.enumeration.Epoch; import astro.tool.box.facade.CatalogQueryFacade; import astro.tool.box.module.tab.ImageViewerTab; import astro.tool.box.service.CatalogQueryService; import astro.tool.box.service.SpectralTypeLookupService; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Image; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.ColumnText; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfPageEventHelper; import com.itextpdf.text.pdf.PdfWriter; import java.awt.Cursor; import java.awt.Desktop; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.swing.JFrame; import javax.swing.JTextField; public class InfoSheet { private static final Font HEADER_FONT = FontFactory.getFont(FontFactory.HELVETICA, 16, BaseColor.DARK_GRAY); private static final Font LARGE_FONT = FontFactory.getFont(FontFactory.HELVETICA, 9, BaseColor.BLACK); private static final Font MEDIUM_FONT = FontFactory.getFont(FontFactory.HELVETICA, 7.5f, BaseColor.BLACK); private static final Font SMALL_FONT = FontFactory.getFont(FontFactory.HELVETICA, 6, BaseColor.BLACK); private static final Font SMALL_BOLD_FONT = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 6, BaseColor.BLACK); private static final Font SMALL_GREEN_FONT = FontFactory.getFont(FontFactory.HELVETICA, 6, BaseColor.GREEN.darker()); private static final Font SMALL_ORANGE_FONT = FontFactory.getFont(FontFactory.HELVETICA, 6, BaseColor.ORANGE.darker()); private static final Font SMALL_RED_FONT = FontFactory.getFont(FontFactory.HELVETICA, 6, BaseColor.RED.darker()); private static final Font SMALL_WHITE_FONT = FontFactory.getFont(FontFactory.HELVETICA, 6, BaseColor.WHITE); private final double targetRa; private final double targetDec; private final int size; private final ImageViewerTab imageViewerTab; private final Map<String, CatalogEntry> catalogInstances; private final CatalogQueryFacade catalogQueryFacade; private final SpectralTypeLookupService mainSequenceLookupService; private final SpectralTypeLookupService brownDwarfsLookupService; public InfoSheet(double targetRa, double targetDec, int size, ImageViewerTab imageViewerTab) { this.targetRa = targetRa; this.targetDec = targetDec; this.size = size; this.imageViewerTab = imageViewerTab; catalogInstances = getCatalogInstances(); catalogQueryFacade = new CatalogQueryService(); InputStream input = getClass().getResourceAsStream("/SpectralTypeLookupTable.csv"); try (Stream<String> stream = new BufferedReader(new InputStreamReader(input)).lines()) { List<SpectralTypeLookup> entries = stream.skip(1).map(line -> { return new SpectralTypeLookupEntry(line.split(",", -1)); }).collect(Collectors.toList()); mainSequenceLookupService = new SpectralTypeLookupService(entries); } input = getClass().getResourceAsStream("/BrownDwarfLookupTable.csv"); try (Stream<String> stream = new BufferedReader(new InputStreamReader(input)).lines()) { List<SpectralTypeLookup> entries = stream.skip(1).map(line -> { return new BrownDwarfLookupEntry(line.split(",", -1)); }).collect(Collectors.toList()); brownDwarfsLookupService = new SpectralTypeLookupService(entries); } } public Boolean create(JFrame baseFrame) { imageViewerTab.setWaitCursor(false); JTextField coordsField = imageViewerTab.getCoordsField(); ActionListener actionListener = coordsField.getActionListeners()[0]; coordsField.removeActionListener(actionListener); coordsField.setText(roundTo7DecNZ(targetRa) + " " + roundTo7DecNZ(targetDec)); coordsField.addActionListener(actionListener); JTextField sizeField = imageViewerTab.getSizeField(); actionListener = sizeField.getActionListeners()[0]; sizeField.removeActionListener(actionListener); sizeField.setText(String.valueOf(size)); sizeField.addActionListener(actionListener); try { imageViewerTab.getZoomSlider().setValue(250); imageViewerTab.getEpochs().setSelectedItem(Epoch.YEAR); baseFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); File tmpFile = File.createTempFile("Target_" + roundTo2DecNZ(targetRa) + addPlusSign(roundDouble(targetDec, PATTERN_2DEC_NZ)) + "_", ".pdf"); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(tmpFile)); DocumentFooter event = new DocumentFooter(); writer.setPageEvent(event); document.open(); Chunk chunk = new Chunk("Target: " + roundTo6DecNZ(targetRa) + " " + addPlusSign(roundDouble(targetDec, PATTERN_6DEC_NZ)) + " FoV: " + size + "\"", HEADER_FONT); document.add(chunk); document.add(new Paragraph(" ")); List<String> imageLabels = new ArrayList<>(); List<BufferedImage> bufferedImages = new ArrayList<>(); BufferedImage bufferedImage = retrieveImage(targetRa, targetDec, size, "dss", "dss_bands=poss1_blue&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("poss1_blue"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "dss", "dss_bands=poss1_red&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("poss1_red"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "dss", "dss_bands=poss2ukstu_blue&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("poss2ukstu_blue"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "dss", "dss_bands=poss2ukstu_red&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("poss2ukstu_red"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "dss", "dss_bands=poss2ukstu_ir&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("poss2ukstu_ir"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "dss", "file_type=colorimage"); if (bufferedImage != null) { imageLabels.add("dss2IR-dss1Red-dss1Blue"); bufferedImages.add(bufferedImage); } createPdfTable("DSS", imageLabels, bufferedImages, writer, document); imageLabels = new ArrayList<>(); bufferedImages = new ArrayList<>(); bufferedImage = retrieveImage(targetRa, targetDec, size, "2mass", "twomass_bands=j&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("J"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "2mass", "twomass_bands=h&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("H"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "2mass", "twomass_bands=k&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("K"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "2mass", "file_type=colorimage"); if (bufferedImage != null) { imageLabels.add("K-H-J"); bufferedImages.add(bufferedImage); } createPdfTable("2MASS", imageLabels, bufferedImages, writer, document); imageLabels = new ArrayList<>(); bufferedImages = new ArrayList<>(); bufferedImage = retrieveImage(targetRa, targetDec, size, "sdss", "sdss_bands=u&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("u"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "sdss", "sdss_bands=g&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("g"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "sdss", "sdss_bands=r&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("r"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "sdss", "sdss_bands=i&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("i"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "sdss", "sdss_bands=z&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("z"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "sdss", "file_type=colorimage"); if (bufferedImage != null) { imageLabels.add("z-g-u"); bufferedImages.add(bufferedImage); } createPdfTable("SDSS", imageLabels, bufferedImages, writer, document); imageLabels = new ArrayList<>(); bufferedImages = new ArrayList<>(); bufferedImage = retrieveImage(targetRa, targetDec, size, "seip", "seip_bands=spitzer.seip_science:IRAC1&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("IRAC1"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "seip", "seip_bands=spitzer.seip_science:IRAC2&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("IRAC2"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "seip", "seip_bands=spitzer.seip_science:IRAC3&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("IRAC3"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "seip", "seip_bands=spitzer.seip_science:IRAC4&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("IRAC4"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "seip", "seip_bands=spitzer.seip_science:MIPS24&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("MIPS24"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "seip", "file_type=colorimage"); if (bufferedImage != null) { imageLabels.add("3-color"); bufferedImages.add(bufferedImage); } createPdfTable("Spitzer (SEIP)", imageLabels, bufferedImages, writer, document); imageLabels = new ArrayList<>(); bufferedImages = new ArrayList<>(); bufferedImage = retrieveImage(targetRa, targetDec, size, "wise", "wise_bands=1&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("W1"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "wise", "wise_bands=2&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("W2"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "wise", "wise_bands=3&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("W3"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "wise", "wise_bands=4&type=jpgurl"); if (bufferedImage != null) { imageLabels.add("W4"); bufferedImages.add(bufferedImage); } bufferedImage = retrieveImage(targetRa, targetDec, size, "wise", "file_type=colorimage"); if (bufferedImage != null) { imageLabels.add("W4-W2-W1"); bufferedImages.add(bufferedImage); } createPdfTable("AllWISE", imageLabels, bufferedImages, writer, document); SortedMap<String, String> imageInfos = getPs1FileNames(targetRa, targetDec); if (!imageInfos.isEmpty()) { imageLabels = new ArrayList<>(); bufferedImages = new ArrayList<>(); imageLabels.add("g"); bufferedImages.add(retrievePs1Image(String.format("red=%s", imageInfos.get("g")), targetRa, targetDec, size)); imageLabels.add("r"); bufferedImages.add(retrievePs1Image(String.format("red=%s", imageInfos.get("r")), targetRa, targetDec, size)); imageLabels.add("i"); bufferedImages.add(retrievePs1Image(String.format("red=%s", imageInfos.get("i")), targetRa, targetDec, size)); imageLabels.add("z"); bufferedImages.add(retrievePs1Image(String.format("red=%s", imageInfos.get("z")), targetRa, targetDec, size)); imageLabels.add("y"); bufferedImages.add(retrievePs1Image(String.format("red=%s", imageInfos.get("y")), targetRa, targetDec, size)); imageLabels.add("y-i-g"); bufferedImages.add(retrievePs1Image(String.format("red=%s&green=%s&blue=%s", imageInfos.get("y"), imageInfos.get("i"), imageInfos.get("g")), targetRa, targetDec, size)); createPdfTable("Pan-STARRS", imageLabels, bufferedImages, writer, document); } imageLabels = new ArrayList<>(); bufferedImages = new ArrayList<>(); bufferedImage = retrieveDecalsImage(targetRa, targetDec, size, "g"); if (bufferedImage != null) { imageLabels.add("g"); bufferedImage = convertToGray(bufferedImage); bufferedImages.add(bufferedImage); } bufferedImage = retrieveDecalsImage(targetRa, targetDec, size, "r"); if (bufferedImage != null) { imageLabels.add("r"); bufferedImage = convertToGray(bufferedImage); bufferedImages.add(bufferedImage); } bufferedImage = retrieveDecalsImage(targetRa, targetDec, size, "z"); if (bufferedImage != null) { imageLabels.add("z"); bufferedImage = convertToGray(bufferedImage); bufferedImages.add(bufferedImage); } bufferedImage = retrieveDecalsImage(targetRa, targetDec, size, "grz"); if (bufferedImage != null) { imageLabels.add("g-r-z"); bufferedImages.add(bufferedImage); } createPdfTable("DECaLS", imageLabels, bufferedImages, writer, document); imageLabels = new ArrayList<>(); bufferedImages = new ArrayList<>(); for (FlipbookComponent component : imageViewerTab.getFlipbook()) { imageLabels.add(component.getTitle()); bufferedImages.add(imageViewerTab.processImage(component)); } createPdfTable("NeoWISE", imageLabels, bufferedImages, writer, document); int searchRadius = size / 3; List<CatalogEntry> catalogEntries = new ArrayList<>(); List<String> selectedCatalogs = getSelectedCatalogs(catalogInstances); for (CatalogEntry catalogEntry : catalogInstances.values()) { if (selectedCatalogs.contains(catalogEntry.getCatalogName())) { catalogEntry.setRa(targetRa); catalogEntry.setDec(targetDec); catalogEntry.setSearchRadius(searchRadius); List<CatalogEntry> results = performQuery(catalogEntry); if (results != null) { catalogEntries.addAll(results); } } } document.add(new Paragraph(" ")); String mainHeader = "CATALOG ENTRIES (Search radius = " + roundTo1DecNZ(searchRadius) + "\")"; document.add(createCatalogEntriesTable(mainSequenceLookupService, catalogEntries, "Main sequence spectral type evaluation (**)", mainHeader)); document.add(createCatalogEntriesTable(brownDwarfsLookupService, catalogEntries, "M, L & T dwarfs spectral type evaluation (***)", null)); PdfPTable table = new PdfPTable(3); table.setTotalWidth(new float[]{11, 40, 100}); table.setLockedWidth(true); table.setSpacingBefore(10); table.setKeepTogether(true); table.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(createTableCell("(*)", SMALL_FONT)); table.addCell(createTableCell("Match probability", SMALL_BOLD_FONT)); table.addCell(createTableCell("Constraint", SMALL_BOLD_FONT)); PdfPCell cell = new PdfPCell(); cell.setBackgroundColor(BaseColor.GREEN.darker()); table.addCell(cell); table.addCell(createTableCell("High", SMALL_FONT)); table.addCell(createTableCell("0 <= target distance < 3", SMALL_FONT)); cell = new PdfPCell(); cell.setBackgroundColor(BaseColor.ORANGE.darker()); table.addCell(cell); table.addCell(createTableCell("Medium", SMALL_FONT)); table.addCell(createTableCell("3 <= target distance < 6", SMALL_FONT)); cell = new PdfPCell(); cell.setBackgroundColor(BaseColor.RED.darker()); table.addCell(cell); table.addCell(createTableCell("Low", SMALL_FONT)); table.addCell(createTableCell("6 <= target distance", SMALL_FONT)); document.add(table); document.add(new Paragraph("(**) Uses colors from: A Modern Mean Dwarf Stellar Color & Effective Temperature Sequence (Eric Mamajek)", SMALL_FONT)); document.add(new Paragraph("(***) Uses colors from: Best et al. (2018), Carnero Rosell et al. (2019), Skrzypek et al. (2015), Skrzypek et al. (2016) and Kiman et al. (2019)", SMALL_FONT)); document.close(); Desktop.getDesktop().open(tmpFile); } catch (Exception ex) { showExceptionDialog(baseFrame, ex); } finally { imageViewerTab.setWaitCursor(true); baseFrame.setCursor(Cursor.getDefaultCursor()); coordsField.setCursor(Cursor.getDefaultCursor()); sizeField.setCursor(Cursor.getDefaultCursor()); } return true; } private PdfPTable createCatalogEntriesTable(SpectralTypeLookupService spectralTypeLookupService, List<CatalogEntry> catalogEntries, String header, String mainHeader) throws Exception { List<BatchResult> batchResults = new ArrayList<>(); for (CatalogEntry catalogEntry : catalogEntries) { List<String> spectralTypes = lookupSpectralTypes(catalogEntry.getColors(true), spectralTypeLookupService, true); if (catalogEntry instanceof SimbadCatalogEntry) { SimbadCatalogEntry simbadEntry = (SimbadCatalogEntry) catalogEntry; StringBuilder simbadType = new StringBuilder(); simbadType.append(simbadEntry.getObjectType()); if (!simbadEntry.getSpectralType().isEmpty()) { simbadType.append(" ").append(simbadEntry.getSpectralType()); } simbadType.append("; "); spectralTypes.add(0, simbadType.toString()); } if (catalogEntry instanceof AllWiseCatalogEntry) { AllWiseCatalogEntry entry = (AllWiseCatalogEntry) catalogEntry; if (isAPossibleAGN(entry.getW1_W2(), entry.getW2_W3())) { spectralTypes.add(AGN_WARNING); } } if (catalogEntry instanceof WhiteDwarf) { WhiteDwarf entry = (WhiteDwarf) catalogEntry; if (isAPossibleWD(entry.getAbsoluteGmag(), entry.getBP_RP())) { spectralTypes.add(WD_WARNING); } } BatchResult batchResult = new BatchResult.Builder() .setCatalogName(catalogEntry.getCatalogName()) .setTargetRa(targetRa) .setTargetDec(targetDec) .setTargetDistance(catalogEntry.getTargetDistance()) .setRa(catalogEntry.getRa()) .setDec(catalogEntry.getDec()) .setSourceId(catalogEntry.getSourceId() + " ") .setPlx(catalogEntry.getPlx()) .setPmra(catalogEntry.getPmra()) .setPmdec(catalogEntry.getPmdec()) .setMagnitudes(catalogEntry.getMagnitudes()) .setSpectralTypes(spectralTypes).build(); batchResults.add(batchResult); } int numberOfCols = 10; PdfPTable table = new PdfPTable(numberOfCols); table.setTotalWidth(new float[]{50, 30, 40, 40, 80, 30, 35, 35, 100, 100}); table.setLockedWidth(true); table.setSpacingBefore(10); table.setKeepTogether(true); table.setHorizontalAlignment(Element.ALIGN_LEFT); PdfPCell tableHeader; if (mainHeader != null) { tableHeader = new PdfPCell(new Phrase(mainHeader, LARGE_FONT)); tableHeader.setHorizontalAlignment(Element.ALIGN_LEFT); tableHeader.setColspan(numberOfCols); tableHeader.setBorderWidth(0); tableHeader.setPaddingBottom(10); table.addCell(tableHeader); } tableHeader = new PdfPCell(new Phrase(header, MEDIUM_FONT)); tableHeader.setHorizontalAlignment(Element.ALIGN_LEFT); tableHeader.setColspan(numberOfCols); tableHeader.setBorderWidth(0); tableHeader.setPaddingBottom(5); table.addCell(tableHeader); addHeaderCell(table, "Catalog", Element.ALIGN_LEFT); addHeaderCell(table, "Target dist. (*)", Element.ALIGN_RIGHT); addHeaderCell(table, "RA", Element.ALIGN_LEFT); addHeaderCell(table, "dec", Element.ALIGN_LEFT); addHeaderCell(table, "Source id", Element.ALIGN_LEFT); addHeaderCell(table, "Plx (mas)", Element.ALIGN_RIGHT); addHeaderCell(table, "pmRA (mas/yr)", Element.ALIGN_RIGHT); addHeaderCell(table, "pmdec (mas/yr)", Element.ALIGN_RIGHT); addHeaderCell(table, "Magnitudes", Element.ALIGN_LEFT); addHeaderCell(table, "Spectral types", Element.ALIGN_LEFT); for (int i = 0; i < batchResults.size(); i++) { BatchResult batchResult = batchResults.get(i); Font font; double targetDistance = batchResult.getTargetDistance(); if (targetDistance < 3) { font = SMALL_GREEN_FONT; } else if (targetDistance >= 3 && targetDistance < 6) { font = SMALL_ORANGE_FONT; } else { font = SMALL_RED_FONT; } addCell(table, batchResult.getCatalogName(), Element.ALIGN_LEFT, i, SMALL_FONT); addCell(table, roundTo3Dec(batchResult.getTargetDistance()), Element.ALIGN_RIGHT, i, font); addCell(table, roundTo6DecNZ(batchResult.getRa()), Element.ALIGN_LEFT, i, SMALL_FONT); addCell(table, roundTo6DecNZ(batchResult.getDec()), Element.ALIGN_LEFT, i, SMALL_FONT); addCell(table, batchResult.getSourceId(), Element.ALIGN_LEFT, i, SMALL_FONT); addCell(table, roundTo3Dec(batchResult.getPlx()), Element.ALIGN_RIGHT, i, SMALL_FONT); addCell(table, roundTo3Dec(batchResult.getPmra()), Element.ALIGN_RIGHT, i, SMALL_FONT); addCell(table, roundTo3Dec(batchResult.getPmdec()), Element.ALIGN_RIGHT, i, SMALL_FONT); addCell(table, batchResult.getMagnitudes(), Element.ALIGN_LEFT, i, SMALL_FONT); addCell(table, batchResult.joinSpetralTypes(), Element.ALIGN_LEFT, i, SMALL_FONT); } return table; } private void createPdfTable(String header, List<String> imageLabels, List<BufferedImage> bufferedImages, PdfWriter writer, Document document) throws Exception { int numberOfCells = imageLabels.size(); if (numberOfCells == 0) { return; } float[] widths = new float[numberOfCells]; for (int i = 0; i < numberOfCells; i++) { widths[i] = 75; } PdfPTable table = new PdfPTable(numberOfCells); table.setTotalWidth(widths); table.setLockedWidth(true); table.setKeepTogether(true); table.setHorizontalAlignment(Element.ALIGN_LEFT); PdfPCell tableHeader = new PdfPCell(new Phrase(header, LARGE_FONT)); tableHeader.setHorizontalAlignment(Element.ALIGN_LEFT); tableHeader.setColspan(numberOfCells); tableHeader.setBorderWidth(0); table.addCell(tableHeader); for (String imageLabel : imageLabels) { PdfPCell cell = new PdfPCell(new Phrase(imageLabel, SMALL_FONT)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(0); cell.setPadding(1); table.addCell(cell); } for (BufferedImage bi : bufferedImages) { bi = drawCenterShape(bi); Image image = Image.getInstance(writer, bi, 1); PdfPCell cell = new PdfPCell(image, true); cell.setBorderWidth(0); cell.setPadding(1); table.addCell(cell); } document.add(table); } private void addHeaderCell(PdfPTable table, Object value, int alignment) { PdfPCell cell = new PdfPCell(new Phrase(value.toString(), SMALL_WHITE_FONT)); cell.setHorizontalAlignment(alignment); cell.setBackgroundColor(BaseColor.DARK_GRAY); cell.setBorderColor(BaseColor.WHITE); cell.setBorderWidth(0.5f); cell.setPadding(2); table.addCell(cell); } private void addCell(PdfPTable table, Object value, int alignment, int rowIndex, Font font) { PdfPCell cell = new PdfPCell(new Phrase(value.toString(), font)); cell.setHorizontalAlignment(alignment); cell.setBackgroundColor(rowIndex % 2 == 0 ? BaseColor.WHITE : BaseColor.LIGHT_GRAY); cell.setBorderColor(BaseColor.WHITE); cell.setBorderWidth(0.5f); cell.setPadding(2); table.addCell(cell); } private PdfPCell createTableCell(String text, Font font) { PdfPCell cell = new PdfPCell(new Phrase(text, font)); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorderWidth(0); cell.setPadding(2); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); return cell; } private List<CatalogEntry> performQuery(CatalogEntry catalogQuery) throws IOException { List<CatalogEntry> catalogEntries = catalogQueryFacade.getCatalogEntriesByCoords(catalogQuery); catalogEntries.forEach(catalogEntry -> { catalogEntry.setTargetRa(catalogQuery.getRa()); catalogEntry.setTargetDec(catalogQuery.getDec()); }); if (!catalogEntries.isEmpty()) { catalogEntries.sort(Comparator.comparingDouble(CatalogEntry::getTargetDistance)); return catalogEntries; } return null; } class DocumentFooter extends PdfPageEventHelper { @Override public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); Phrase footer = new Phrase(PGM_NAME + " " + PGM_VERSION + " - Page " + writer.getPageNumber(), SMALL_FONT); ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 10, 0); } } }
49.696141
201
0.618874
4cd4415424ec077c43a85588c0979606a0004391
10,712
/* Glazed Lists (c) 2003-2006 */ /* http://publicobject.com/glazedlists/ publicobject.com,*/ /* O'Dell Engineering Ltd.*/ package ca.odell.glazedlists.io; // the core Glazed Lists packages import ca.odell.glazedlists.*; import ca.odell.glazedlists.event.*; // access to the volatile implementation pacakge import ca.odell.glazedlists.impl.rbp.*; import ca.odell.glazedlists.impl.io.*; // concurrency is similar to java.util.concurrent in J2SE 1.5 import ca.odell.glazedlists.util.concurrent.*; // NIO is used for BRP import java.util.*; import java.io.*; /** * An {@link EventList} that is either published to the network or subscribed from * the network. Since list elements must be transmitted over the network, each * {@link NetworkList} requires a {@link ByteCoder} to convert {@link Object}s to * and from bytes. * * <p>To instantiate a {@link NetworkList}, use the * {@link ListPeer#subscribe(String,int,String,ByteCoder) subscribe()} * and {@link ListPeer#publish(EventList,String,ByteCoder) publish()} methods * of a started {@link ListPeer}. * * <p>{@link NetworkList}s may be taken offline and brought back online with the * {@link #connect()} and {@link #disconnect()} methods. This allows an application * to use a {@link NetworkList} in spite of an unreliable network connection. * * <p>As a consequence of imperfect networks, {@link NetworkList}s may sometimes go * offline on their own. Some causes of this include the server program shutting * down or crashing, the local network connection becoming unavailable, or a * problem with the physical link, such as an unplugged cable. * * <p>{@link NetworkList}s use a subset of HTTP/1.1 for transport, including * chunked encoding. This protocol brings its own set of advantages: * <li>HTTP is a standard well-understood protocol * <li>Clients may be served even if they are behind NAT or Firewalls * <li>The connection could be proxied by a standard HTTP proxy server, if necessary * <li>In theory, the served port could be shared with another HTTP daemon such as Tomcat * * <p>And HTTP brings some disadvantages also: * <li>A persistent connection must be held, even if updates are infrequent * <li>It cannot be differentiated from web traffic for analysis * * <p><strong><font color="#FF0000">Warning:</font></strong> The protocol used by * this version of {@link NetworkList} will be incompatible with future versions. * Eventually the protocol will be finalized but the current protocol is a work * in progress. * * <p><strong><font color="#FF0000">Warning:</font></strong> This class * breaks the contract required by {@link java.util.List}. See {@link EventList} * for an example. * * <p><table border="1" width="100%" cellpadding="3" cellspacing="0"> * <tr class="TableHeadingColor"><td colspan=2><font size="+2"><b>EventList Overview</b></font></td></tr> * <tr><td class="TableSubHeadingColor"><b>Writable:</b></td><td>yes</td></tr> * <tr><td class="TableSubHeadingColor"><b>Concurrency:</b></td><td>Requires {@link ReadWriteLock} for every access, even for single-threaded use</td></tr> * <tr><td class="TableSubHeadingColor"><b>Performance:</b></td><td>N/A</td></tr> * <tr><td class="TableSubHeadingColor"><b>Memory:</b></td><td>O(N)</td></tr> * <tr><td class="TableSubHeadingColor"><b>Unit Tests:</b></td><td>N/A</td></tr> * <tr><td class="TableSubHeadingColor"><b>Issues:</b></td><td>N/A</td></tr> * </table> * * @author <a href="mailto:[email protected]">Jesse Wilson</a> */ public final class NetworkList extends TransformedList { /** listeners to resource changes */ private List resourceListeners = new ArrayList(); /** listeners to status changes */ private List statusListeners = new ArrayList(); /** how bytes are encoded and decoded */ private ByteCoder byteCoder; /** who manages this resource's connection */ private ResourceStatus resourceStatus = null; /** whether this NetworkList is writable via its own API */ private boolean writable = false; /** implementations of ResourceStatusListener and Resource */ private PrivateInterfaces privateInterfaces = new PrivateInterfaces(); /** * Create a {@link NetworkList} that brings the specified source online. */ NetworkList(EventList source, ByteCoder byteCoder) { super(source); this.byteCoder = byteCoder; source.addListEventListener(this); } /** * Sets the ResourceStatus to delegate connection information requests to. */ void setResourceStatus(ResourceStatus resourceStatus) { if(this.resourceStatus != null) throw new IllegalStateException(); this.resourceStatus = resourceStatus; resourceStatus.addResourceStatusListener(privateInterfaces); } /** * Set the NetworkList as writable. */ void setWritable(boolean writable) { this.writable = writable; } /** {@inheritDoc} */ public boolean isWritable() { return writable; } /** * Gets the {@link Resource} that is the peer of this NetworkList. */ Resource getResource() { return privateInterfaces; } /** {@inheritDoc} */ public void listChanged(ListEvent listChanges) { // notify resource listeners try { ListEvent listChangesCopy = listChanges.copy(); Bufferlo listChangesBytes = ListEventToBytes.toBytes(listChangesCopy, byteCoder); for(int r = 0; r < resourceListeners.size(); r++) { ResourceListener listener = (ResourceListener)resourceListeners.get(r); listener.resourceUpdated(privateInterfaces, listChangesBytes.duplicate()); } } catch(IOException e) { throw new IllegalStateException(e.getMessage()); } // forward the event updates.forwardEvent(listChanges); } /** * Returns true if this resource is on the network. For published lists, this * requires that the list is being served. For subscribed lists, this requires * that a connection to the server has been established. */ public boolean isConnected() { return resourceStatus.isConnected(); } /** * Attempts to bring this {@link NetworkList} online. When the connection attempt * is successful (or when it fails), all {@link ResourceStatusListener}s will be * notified. */ public void connect() { resourceStatus.connect(); } /** * Attempts to take this {@link NetworkList} offline. When the {@link NetworkList} * is fully disconnected, all {@link ResourceStatusListener}s will be notified. */ public void disconnect() { resourceStatus.disconnect(); } /** * Implementations of all private interfaces. */ private class PrivateInterfaces implements Resource, ResourceStatusListener { /** * Called each time a resource becomes connected. */ public void resourceConnected(ResourceStatus resource) { for(Iterator i = statusListeners.iterator(); i.hasNext(); ) { NetworkListStatusListener listener = (NetworkListStatusListener)i.next(); listener.connected(NetworkList.this); } } /** * Called each time a resource's disconnected status changes. This method may * be called for each attempt it makes to reconnect to the network. */ public void resourceDisconnected(ResourceStatus resource, Exception cause) { for(Iterator i = statusListeners.iterator(); i.hasNext(); ) { NetworkListStatusListener listener = (NetworkListStatusListener)i.next(); listener.disconnected(NetworkList.this, cause); } } /** {@inheritDoc} */ public Bufferlo toSnapshot() { getReadWriteLock().writeLock().lock(); try { return ListEventToBytes.toBytes(NetworkList.this, byteCoder); } catch(IOException e) { throw new IllegalStateException(e.getMessage()); } finally { getReadWriteLock().writeLock().unlock(); } } /** {@inheritDoc} */ public void fromSnapshot(Bufferlo snapshot) { applyCodedEvent(snapshot); } /** {@inheritDoc} */ private void applyCodedEvent(Bufferlo data) { getReadWriteLock().writeLock().lock(); try { updates.beginEvent(true); ListEventToBytes.toListEvent(data, source, byteCoder); updates.commitEvent(); } catch(IOException e) { throw new IllegalStateException(e.getMessage()); } finally { getReadWriteLock().writeLock().unlock(); } } /** {@inheritDoc} */ public void update(Bufferlo delta) { applyCodedEvent(delta); } /** {@inheritDoc} */ public void addResourceListener(ResourceListener listener) { resourceListeners.add(listener); } /** {@inheritDoc} */ public void removeResourceListener(ResourceListener listener) { for(int r = 0; r < resourceListeners.size(); r++) { if(resourceListeners.get(r) == listener) { resourceListeners.remove(r); return; } } } /** {@inheritDoc} */ public ReadWriteLock getReadWriteLock() { return NetworkList.this.getReadWriteLock(); } public String toString() { return NetworkList.this.toString(); } } /** * Registers the specified listener to receive events about the status of this * {@link NetworkList}. */ public void addStatusListener(NetworkListStatusListener listener) { statusListeners.add(listener); } /** * Deregisters the specified listener from receiving events about the status of * this {@link NetworkList}. */ public void removeStatusListener(NetworkListStatusListener listener) { statusListeners.remove(listener); } /** {@inheritDoc} */ public void dispose() { resourceStatus.removeResourceStatusListener(privateInterfaces); disconnect(); super.dispose(); } }
38.394265
155
0.628267
2717aaef97c3f7541aaa3ef92e9f5b99457574cc
2,215
package vuthanhvt.com.demogalaho; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Create by FRAMGIA\vu.anh.thanh on 24/12/2018. * Phone: 096.320.8650 * Email: [email protected] * <p> * TODO: Add a class header comment! */ public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> { private List<String> mList; private OnClickedListener mListener; public void setmListener(OnClickedListener mListener) { this.mListener = mListener; } public Adapter(List<String> mList, OnClickedListener mListener) { this.mList = mList; this.mListener = mListener; } public Adapter(List<String> mList) { if (mList == null) { this.mList = new ArrayList<>(); } else { this.mList = mList; } } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, final int i) { View itemView = LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.list_item, viewGroup, false); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { mListener.onClickedListener(mList.get(i), i); } } }); return new ViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { String item = mList.get(i); viewHolder.textView.setText(item); } @Override public int getItemCount() { return mList.size(); } class ViewHolder extends RecyclerView.ViewHolder { TextView textView; public ViewHolder(@NonNull View itemView) { super(itemView); textView = itemView.findViewById(R.id.expandedListItem); } } public interface OnClickedListener { void onClickedListener(String name, int position); } }
27.012195
85
0.639278
be373a453f58c876a202c84e002d0fdffb7e4762
1,114
package AlgoExSolutions.Hard.LongestCommonSubsequence; import java.util.*; /** * * Longest Common Subsequence */ class Program { /** * * TC: O(mn) * * SC: O(mn) */ public static List<Character> longestCommonSubsequence(String str1, String str2) { // Write your code here. int[][] lcs = new int[str1.length() + 1][str2.length() + 1]; for (int i = 1; i < lcs.length; i++) { for (int j = 1; j < lcs[i].length; j++) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) lcs[i][j] = 1 + lcs[i - 1][j - 1]; else lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]); } } return buildSequence(lcs, str1, str2); } private static List<Character> buildSequence(int[][] lcs, String str1, String str2) { List<Character> sequence = new ArrayList<>(); int i = lcs.length - 1, j = lcs[0].length - 1; while (i > 0 && j > 0) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) { sequence.add(0, str1.charAt(i - 1)); --i; --j; } else if (lcs[i - 1][j] > lcs[i][j - 1]) --i; else --j; } return sequence; } }
25.906977
88
0.528725
2eb4fca380df750ab82d626ee685719c05233aa6
2,013
package com.stupidtree.hita.views.pullextend; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ViewParent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; public class mRecyclerView extends RecyclerView { private float lastMotionY = -1; public mRecyclerView(@NonNull Context context) { super(context); } public mRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public mRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onTouchEvent(MotionEvent e) { ViewParent p = getParent(); PullExtendLayout parent; if (p instanceof PullExtendLayout) { parent = (PullExtendLayout) p; } else return super.onTouchEvent(e); switch (e.getAction()) { //触摸开始、结束时,更新父布局状态 case MotionEvent.ACTION_DOWN: lastMotionY = e.getY(); parent.onTouchEvent(e); break; // case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: lastMotionY = -1; parent.onTouchEvent(e); break; //触摸滑动时,若已达上下滑动边界,则只调用父布局的动作 //若未达上下边界,还是要更新以下父布局的状态(上次触摸位置)防止效果错位 case MotionEvent.ACTION_MOVE: float delta = e.getY() - lastMotionY; lastMotionY = e.getY(); if (delta > 0 && !canScrollVertically(-1)) { return parent.onTouchEvent(e); } else if (delta < 0 && !canScrollVertically(1)) { parent.pullFooterLayout(delta); } parent.callWhenChildScrolled(e); break; } return super.onTouchEvent(e); } }
30.969231
100
0.60159
22c2bec61f1460fb4eab781ef8b661e3ef0c69e6
4,133
package won.bot.valueflows.action; import org.apache.commons.lang3.StringUtils; import org.apache.jena.query.Dataset; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import won.bot.framework.eventbot.EventListenerContext; import won.bot.framework.eventbot.action.EventBotActionUtils; import won.bot.framework.eventbot.action.impl.atomlifecycle.AbstractCreateAtomAction; import won.bot.framework.eventbot.bus.EventBus; import won.bot.framework.eventbot.event.Event; import won.bot.framework.eventbot.event.impl.atomlifecycle.AtomCreatedEvent; import won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent; import won.bot.framework.eventbot.listener.EventListener; import won.bot.valueflows.context.ValueFlowsBotContextWrapper; import won.bot.valueflows.event.CreateHelperAtomEvent; import won.bot.valueflows.util.HelperAtomModelWrapper; import won.protocol.message.WonMessage; import won.protocol.service.WonNodeInformationService; import won.protocol.util.RdfUtils; import won.protocol.util.WonRdfUtils; import java.net.URI; public class CreateHelperAtomAction extends AbstractCreateAtomAction { private static final Logger logger = LoggerFactory.getLogger(CreateHelperAtomAction.class); public CreateHelperAtomAction(EventListenerContext eventListenerContext) { super(eventListenerContext); } @Override protected void doRun(Event event, EventListener executingListener) throws Exception { EventListenerContext ctx = getEventListenerContext(); if(!(ctx.getBotContextWrapper() instanceof ValueFlowsBotContextWrapper) || !(event instanceof CreateHelperAtomEvent)) { logger.error("CreateHelperAtomAction does not work without a ValueFlowsBotContextWrapper and CreateHelperAtomEvent"); throw new IllegalStateException( "CreateHelperAtomAction does not work without a ValueFlowsBotContextWrapper and CreateHelperAtomEvent"); } ValueFlowsBotContextWrapper botContextWrapper = (ValueFlowsBotContextWrapper) ctx.getBotContextWrapper(); CreateHelperAtomEvent createHelperAtomEvent = (CreateHelperAtomEvent) event; final URI wonNodeUri = ctx.getNodeURISource().getNodeURI(); WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService(); final URI helperAtomURI = wonNodeInformationService.generateAtomURI(wonNodeUri); Dataset dataset = new HelperAtomModelWrapper(helperAtomURI, createHelperAtomEvent.getAtomURI()).copyDataset(); logger.debug("creating atom on won node {} with content {} ", wonNodeUri, StringUtils.abbreviate(RdfUtils.toString(dataset), 150)); WonMessage createAtomMessage = ctx.getWonMessageSender().prepareMessage(createWonMessage(helperAtomURI, dataset)); botContextWrapper.rememberAtomUri(helperAtomURI); EventBus bus = ctx.getEventBus(); EventListener successCallback = event1 -> { logger.debug("atom creation successful, new atom URI is {}", helperAtomURI); bus.publish(new AtomCreatedEvent(helperAtomURI, wonNodeUri, dataset, null)); botContextWrapper.addHelperAtomUriEntry(createHelperAtomEvent.getAtomURI(), helperAtomURI); }; EventListener failureCallback = event12 -> { String textMessage = WonRdfUtils.MessageUtils .getTextMessage(((FailureResponseEvent) event12).getFailureMessage()); logger.error("atom creation failed for atom URI {}, original message URI {}: {}", helperAtomURI, ((FailureResponseEvent) event12).getOriginalMessageURI(), textMessage); botContextWrapper.removeAtomUri(helperAtomURI); }; EventBotActionUtils.makeAndSubscribeResponseListener(createAtomMessage, successCallback, failureCallback, ctx); logger.debug("registered listeners for response to message URI {}", createAtomMessage.getMessageURI()); ctx.getWonMessageSender().sendMessage(createAtomMessage); logger.debug("atom creation message sent with message URI {}", createAtomMessage.getMessageURI()); } }
58.211268
129
0.765304
fc1159f821b97bb98356a92d2debc102d6474efc
7,418
package pw.mihou.alisa.modules.database; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import com.mongodb.client.model.ReplaceOptions; import com.mongodb.client.model.Updates; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import org.bson.Document; import org.bson.conversions.Bson; import org.jetbrains.annotations.NotNull; import pw.mihou.alisa.interfaces.DatabaseModel; import pw.mihou.alisa.modules.database.modules.AlisaField; import pw.mihou.alisa.modules.database.modules.AlisaIndex; import pw.mihou.alisa.modules.database.modules.iterable.AlisaIterable; import pw.mihou.alisa.modules.database.modules.iterable.AlisaIterableOperations; import java.util.ArrayList; import java.util.Arrays; import java.util.Optional; import java.util.concurrent.CompletableFuture; public interface AlisaDatabase<Type> { /** * Gets the collection for this database. * * @return The collection of this database. */ MongoCollection<Document> collection(); /** * Translates a {@link Document} into a {@link Type} that is intended for this database. * * @param document The document to translate. * @return The {@link Type} instance of the document. */ @NotNull Type translate(Document document); /** * Upserts the model onto the database. * * @param model The model to upsert to the database. * @return The result of upserting to the database. */ default CompletableFuture<UpdateResult> upsert(DatabaseModel model) { return CompletableFuture.supplyAsync(() -> collection() .replaceOne( Filters.eq(model.index().key(), model.index().value()), model.document(), new ReplaceOptions().upsert(true) )); } /** * Gets a specific document from the database. * * @param index The index to use when querying the database. * @return The received {@link Type} form the database if present. */ default CompletableFuture<Optional<Type>> get(AlisaIndex index) { return CompletableFuture.supplyAsync(() -> { Document document = collection().find( Filters.eq(index.key(), index.value()) ).first(); if (document == null) { return Optional.empty(); } return Optional.of(translate(document)); }); } /** * Gets all documents that match the index. * * @param index The index to use when querying the database. * @return The received {@link Document} form the database if present. */ default AlisaIterable<Type> all(AlisaIndex index) { return new AlisaIterable<Type>(collection().find( Filters.eq(index.key(), index.value()) ), new ArrayList<>(), this::translate); } /** * Gets all documents that match the indexes. * * @param indexes The indexes to use when querying the database. * @return The received {@link Document} form the database if present. */ default AlisaIterable<Type> and(AlisaIndex... indexes) { return new AlisaIterable<>(collection().find( Filters.and(Arrays.stream(indexes).map(index -> Filters.eq(index.key(), index.value())).toList()) ), new ArrayList<>(), this::translate); } /** * Gets all documents that match the query. * * @param field The field to find the data from. * @param values The values that a document should match once. * @return The received {@link Document} form the database if present. */ default AlisaIterable<Type> all(String field, Object... values) { return new AlisaIterable<>(collection().find( Filters.all(field, values) ), new ArrayList<>(), this::translate); } /** * Gets all documents that match the indexes. * * @param indexes The indexes to use when querying the database. * @return The received {@link Document} form the database if present. */ default AlisaIterable<Type> or(AlisaIndex... indexes) { return or(Arrays.stream(indexes).map(index -> Filters.eq(index.key(), index.value())).toArray(Bson[]::new)); } /** * Gets all documents that match the filters. * * @param filters The filters to use when querying the database. * @return The received {@link Document} form the database if present. */ default AlisaIterable<Type> or(Bson... filters) { return new AlisaIterable<>(collection().find( Filters.and(filters) ), new ArrayList<>(), this::translate); } /** * Deletes a specific document from the database. * * @param model The model to delete. * @return The result from deleting the document. */ default CompletableFuture<DeleteResult> delete(DatabaseModel model) { return CompletableFuture.supplyAsync(() -> collection().deleteOne( Filters.eq(model.index().key(), model.index().value()) )); } /** * Updates one field of the specific database model. * * @param index The index of the model. * @param field The field to update on the model. * @return The result from updating the model. */ default CompletableFuture<UpdateResult> updateField(AlisaIndex index, AlisaField field) { return CompletableFuture.supplyAsync(() -> collection().updateOne( Filters.eq(index.key(), index.value()), Updates.set(field.key(), field.value()) )); } /** * Gets all the data of the collection. * * @return All the data of the collection. */ default AlisaIterable<Type> all() { return new AlisaIterable<>(collection().find(), new ArrayList<>(), this::translate); } /** * Sorts all the data by the latest order. * * @return An iterable that is sorted by the latest order. */ default AlisaIterable<Type> latest() { return all().addOperation(AlisaIterableOperations.LATEST).apply(); } /** * Sorts all the data by the latest order. * * @param iterable The iterable to use for sorting the data. * @return An iterable that is sorted by the latest order. */ default AlisaIterable<Type> latest(FindIterable<Document> iterable) { return new AlisaIterable<Type>(iterable, new ArrayList<>(), this::translate).addOperation(AlisaIterableOperations.LATEST); } /** * Sorts all the data by the oldest order. * * @param iterable The iterable to use for sorting the data. * @return An iterable that is sorted by the oldest order. */ default AlisaIterable<Type> oldest(FindIterable<Document> iterable) { return new AlisaIterable<>(iterable, new ArrayList<>(), this::translate).addOperation(AlisaIterableOperations.OLDEST); } /** * Sorts all the data by the oldest order. * * @return An iterable that is sorted by the oldest order. */ default AlisaIterable<Type> oldest() { return all().addOperation(AlisaIterableOperations.OLDEST); } }
35.156398
130
0.63265
66c938e9a57ca02f162ee3720dece1c3d775c837
3,653
package com.ngdesk.channels.sms; import javax.validation.Valid; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import javax.validation.constraints.Pattern.Flag; import com.fasterxml.jackson.annotation.JsonProperty; import com.ngdesk.annotations.UniqueCompany; public class TwilioRequest { @JsonProperty("COMPANY_SUBDOMAIN") @NotNull(message = "COMPANY_SUBDOMAIN_NOT_NULL") @Size(min = 1, max = 64, message = "COMPANY_SUBDOMAIN_NOT_EMPTY") @Pattern(regexp = "([A-Za-z0-9\\-]+)", message = "INVALID_SUBDOMAIN") @UniqueCompany(message = "COMPANY_NOT_UNIQUE") private String companySubdomain; @JsonProperty("EMAIL_ADDRESS") @NotNull(message = "EMAIL_ADDRESS_NOT_NULL") @Size(min = 1, max = 255, message = "EMAIL_ADDRESS_NOT_EMPTY") @Email(flags = Flag.CASE_INSENSITIVE, message = "EMAIL_INVALID") private String emailAddress; @JsonProperty("FIRST_NAME") @NotNull(message = "FIRST_NAME_NOT_NULL") @Size(min = 1, message = "FIRST_NAME_NOT_EMPTY") @Pattern(regexp = "^[A-Za-z0-9\\-_ ]*$", message = "FIRST_NAME_INVALID") private String firstName; @JsonProperty("LAST_NAME") @NotNull(message = "LAST_NAME_NOT_NULL") @Size(min = 1, message = "LAST_NAME_NOT_EMPTY") @Pattern(regexp = "^[A-Za-z0-9\\-_ ]*$", message = "LAST_NAME_INVALID") private String lastName; @JsonProperty("PHONE_NUMBER") @NotNull(message = "PHONE_NOT_NULL") private String phoneNumber; @JsonProperty("COUNTRY") @NotNull(message = "COUNTRY_NOT_NULL") @Valid private Country country; public TwilioRequest() { } public TwilioRequest( @NotNull(message = "COMPANY_SUBDOMAIN_NOT_NULL") @Size(min = 1, max = 64, message = "COMPANY_SUBDOMAIN_NOT_EMPTY") @Pattern(regexp = "([A-Za-z0-9\\-]+)", message = "INVALID_SUBDOMAIN") String companySubdomain, @NotNull(message = "EMAIL_ADDRESS_NOT_NULL") @Size(min = 1, max = 255, message = "EMAIL_ADDRESS_NOT_EMPTY") @Email(flags = Flag.CASE_INSENSITIVE, message = "EMAIL_INVALID") String emailAddress, @NotNull(message = "FIRST_NAME_NOT_NULL") @Size(min = 1, message = "FIRST_NAME_NOT_EMPTY") @Pattern(regexp = "^[A-Za-z0-9\\-_ ]*$", message = "FIRST_NAME_INVALID") String firstName, @NotNull(message = "LAST_NAME_NOT_NULL") @Size(min = 1, message = "LAST_NAME_NOT_EMPTY") @Pattern(regexp = "^[A-Za-z0-9\\-_ ]*$", message = "LAST_NAME_INVALID") String lastName, @NotNull(message = "PHONE_NOT_NULL") String phoneNumber, @NotNull(message = "COUNTRY_NOT_NULL") @Valid Country country) { super(); this.companySubdomain = companySubdomain; this.emailAddress = emailAddress; this.firstName = firstName; this.lastName = lastName; this.phoneNumber = phoneNumber; this.country = country; } public String getCompanySubdomain() { return companySubdomain; } public void setCompanySubdomain(String companySubdomain) { this.companySubdomain = companySubdomain; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } }
31.491379
212
0.740761
353761b1d953628bee18893fb45bf82bd1447cd6
230
package com.storedobject.chart.encoder; import com.storedobject.chart.coordinate_system.YAxis; public class YAxisEncoder extends AxisEncoder { public YAxisEncoder() { super("yAxis", YAxis.YAxisWrapper.class); } }
20.909091
55
0.752174
d11928788b8b666e6a58f8d8e2310ba163db974d
1,252
package com.udacity.vehicles.conf; import java.util.Collections; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() // .useDefaultResponseMessages(false) .apiInfo(apiInfo()); } //https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api private ApiInfo apiInfo() { return new ApiInfo("Vehicles API", "Description of Cars backend system API.", "API TOS", "", new Contact("Tasneem Ibraheem", "", "[email protected]"), "License of API", "http://www.apache.org/licenses/LICENSE-2.0",Collections.emptyList()); } }
32.947368
94
0.78115
75f64aaa2b2d693aa98e54ab22ebf5d96d961077
3,697
package runner; import java.util.List; import constants.KidsFriendlyStatus; import constants.UserType; import controllers.BookmarkController; import entities.Bookmark; import entities.User; import partner.Shareable; public class View { public static void browse(User user, List<List<Bookmark>> bookmarks){ System.out.println("\n " + user.getEmail()+ " is browsing items....."); //System.out.println(View.class.getName()); int bookmarkCount = 0; for (List<Bookmark>bookmarkList : bookmarks) { for(Bookmark bookmark : bookmarkList){ //Bookmarking //if(bookmarkCount < DataStore.USER_BOOKMARK_LIMIT ){ //get bookmark decision and pass the bookmark boolean isBookmarked = getBookmarkDecision(bookmark); //if its true means user wants to bookmark if(isBookmarked){ bookmarkCount++; BookmarkController.getInstance().saveUserBookmark(user,bookmark); System.out.println(" New Item Bookmarked --" + bookmark); // }//if ends here }//if ends here //Logic for marking kidsFriendly if(user.getUserType().equals(UserType.EDITOR) ||user.getUserType().equals(UserType.CHIEF_EDITOR)){ if(bookmark.isKidsFriendlyEligible() && bookmark.getKidsFriendlyStatus().equals(KidsFriendlyStatus.UNKNOWN)){ String kidsFriendlyStatus = getKidsFriendlyStatusDecision(bookmark); //now if the status is other than Unknown only then we need to set status if(!kidsFriendlyStatus.equals(KidsFriendlyStatus.UNKNOWN) ){ //should pass the implementation to controller and Manager classes BookmarkController.getInstance().setKidsFriendlyStatus(user,kidsFriendlyStatus,bookmark); }//inner inner if ends here }//inner if ends here if(bookmark.getKidsFriendlyStatus().equals(KidsFriendlyStatus.APPROVED) && bookmark instanceof Shareable){ boolean isShared = getShareDecision(); //after he decides and click the share link we send info to controller if(isShared){ BookmarkController .getInstance().share(user,bookmark); } }//if ends here }//if ends here }//inner for }//outer for } // TODO: will be done after IO from console user input private static boolean getShareDecision() { //so if Math.random() return less the 0.5 user wants to bookmark other wise no return Math.random() < 0.5 ? true : false; } private static String getKidsFriendlyStatusDecision(Bookmark bookmark) { //ternery operator are very good /*return Math.random() <0.4 ? KidsFriendlyStatus.APPROVED : (Math.random() >= 0.4 && Math.random()<0.8) ? KidsFriendlyStatus.REJECTED: KidsFriendlyStatus.UNKNOWN;*/ double decision = Math.random(); return decision < 0.4 ? KidsFriendlyStatus.APPROVED : (decision >= 0.4 && decision < 0.8) ? KidsFriendlyStatus.REJECTED : KidsFriendlyStatus.UNKNOWN; } private static boolean getBookmarkDecision(Bookmark bookmark) { //so if Math.random() return less the 0.5 user wants to bookmark other wise no return Math.random() < 0.5 ? true : false; } /*public static void bookmark(User user, Bookmark [][] bookmarks){ System.out.println("\n " + user.getEmail()+ " is bookmarking.."); for(int i = 0 ; i< DataStore.USER_BOOKMARK_LIMIT;i++){ int typeOffset = (int)(Math.random() * DataStore.BOOKMARK_TYPES_COUNT); int bookmarkOffset = (int) (Math.random() *DataStore.BOOKMARK_COUNT_PER_TYPE); Bookmark bookmark = bookmarks[typeOffset][bookmarkOffset]; BookmarkController.getInstance().saveUserBookmark(user,bookmark); System.out.println(bookmark); }//for ends here }*/ }
29.34127
113
0.695699
7e4f5543f6d968d1fc57ca46298ed8bcc07b94b6
2,778
package dev.sukanya.gamecourtbooking.service.impls; import dev.sukanya.gamecourtbooking.dto.game.GameDTO; import dev.sukanya.gamecourtbooking.exceptions.GameAlreadyExistsException; import dev.sukanya.gamecourtbooking.model.courts.Game; import dev.sukanya.gamecourtbooking.repository.GameRepository; import dev.sukanya.gamecourtbooking.service.interfaces.GameService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; @SpringBootTest public class GameServiceImplTests { @Autowired private GameService gameService; @MockBean private GameRepository gameRepository; private static Game game; @BeforeAll public static void createDummies(){ game = new Game(); game.setId(7); game.setGameName("Shuttle"); } @Test @DisplayName("Test add Game Success") public void testAddGameSuccess() throws Exception { doReturn(game).when(gameRepository).save(any()); GameDTO gameDTO = new GameDTO(); gameDTO.setGameName("Shuttle"); Game gameDB = gameService.addGame(gameDTO); assertThat(gameDB.getId()).isEqualTo(game.getId()); } @Test @DisplayName("Test add Game Failure") public void testAddGameFailure() throws Exception { doReturn(game).when(gameRepository).findGameByGameName(any()); GameDTO gameDTO = new GameDTO(); gameDTO.setGameName("Shuttle"); String actualMessage=""; try{ Game gameDB = gameService.addGame(gameDTO); } catch(GameAlreadyExistsException gameAlreadyExistsException){ actualMessage = gameAlreadyExistsException.getMessage(); } assertThat(actualMessage.equals("Game already exists!")); } @Test @DisplayName("Test add Multiple Games") public void testAddMultipleGames() throws Exception { //mock the method doReturn(game).when(gameRepository).save(any()); List<GameDTO> games = new ArrayList<>(); GameDTO gameDTO1 = new GameDTO(); gameDTO1.setGameName("Shuttle"); GameDTO gameDTO2 = new GameDTO(); gameDTO2.setGameName("Carrom"); games.add(gameDTO1); games.add(gameDTO2); List<String> statuses = gameService.addMultipleGames(games); assertThat(statuses.size()).isEqualTo(2); } }
30.866667
74
0.708063
dd4ac37afbbda0df37978bb458fbe86c2842e043
225
package com.quorum.tessera.discovery.internal; import com.quorum.tessera.discovery.NetworkStore; public class NetworkStoreProvider { public static NetworkStore provider() { return DefaultNetworkStore.INSTANCE; } }
20.454545
49
0.795556
6fb9ce9a2884c2a00117f7a0eb93bf2b24f922e5
1,396
package JavaAdvanced.DefiningClasses.Exercise.CarSalesman_05; public class Car { private String model; private Engine engine; private int weight; private String color; public Car(String model, Engine engine){ this(model, engine,-1, "n/a"); } public Car(String model, Engine engine, String color){ this(model, engine,-1, color); } public Car(String model, Engine engine, int weight){ this(model, engine, weight, "n/a"); } public Car(String model, Engine engine, int weight, String color) { this.model = model; this.engine = engine; this.weight = weight; this.color = color; } // FordFocus: // V4-33: // Power: 140 // Displacement: 28 // Efficiency: B // Weight: 1300 // Color: Silver // FordMustang: @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(this.model).append(":").append("\n"); stringBuilder.append(this.engine).append("\n"); if(this.weight == -1){ stringBuilder.append("Weight: ").append("n/a").append("\n"); }else { stringBuilder.append("Weight: ").append(this.weight).append("\n"); } stringBuilder.append("Color: ").append(this.color).append("\n"); return stringBuilder.toString(); } }
25.381818
78
0.597421
f836f88b0cfa74b15e3d48caf8a3444092311296
12,032
package com.bullhornsdk.data.model.entity.file; import com.bullhornsdk.data.model.entity.core.standard.CorporateUser; import com.bullhornsdk.data.model.entity.core.standard.CorporationDepartment; import com.bullhornsdk.data.model.entity.core.type.AbstractEntity; import com.bullhornsdk.data.model.entity.core.type.QueryEntity; import com.bullhornsdk.data.model.entity.core.type.UpdateEntity; import com.bullhornsdk.data.model.entity.embedded.OneToMany; import com.bullhornsdk.data.util.ReadOnly; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.DateTime; import javax.validation.constraints.Size; /** * @author Murray * @since 11/08/2017 */ public abstract class EntityFileAttachment extends AbstractEntity implements QueryEntity, UpdateEntity { private Integer id; @Size(max = 64) private String contentSubType; @Size(max = 64) private String contentType; private DateTime dateAdded; private OneToMany<CorporationDepartment> departmentsSharedWith; private String description; @Size(max = 150) private String directory; @Size(max = 8) private String distribution; @Size(max = 100) private String externalID; @Size(max = 10) private String fileExtension; private Integer fileSize; @Size(max = 15) private String fileType; private CorporateUser fileOwner; private Boolean isCopied; private Boolean isDeleted; private Boolean isEncrypted; private Boolean isExternal; private Boolean isOpen; private Boolean isPrivate; private Boolean isSendOut; private String name; @Size(max = 50) private String type; @JsonIgnore private OneToMany<CorporateUser> usersSharedWith; @JsonIgnore @Size(max = 36) private String uuid; @Override @JsonProperty("id") public Integer getId() { return id; } @ReadOnly @Override @JsonProperty("id") public void setId(Integer id) { this.id = id; } @JsonProperty("contentSubType") public String getContentSubType() { return contentSubType; } @JsonProperty("contentSubType") public void setContentSubType(String contentSubType) { this.contentSubType = contentSubType; } @JsonProperty("contentType") public String getContentType() { return contentType; } @JsonProperty("contentType") public void setContentType(String contentType) { this.contentType = contentType; } @JsonProperty("dateAdded") public DateTime getDateAdded() { return dateAdded; } @JsonProperty("dateAdded") public void setDateAdded(DateTime dateAdded) { this.dateAdded = dateAdded; } @JsonProperty("departmentsSharedWith") public OneToMany<CorporationDepartment> getDepartmentsSharedWith() { return departmentsSharedWith; } @JsonProperty("departmentsSharedWith") public void setDepartmentsSharedWith(OneToMany<CorporationDepartment> departmentsSharedWith) { this.departmentsSharedWith = departmentsSharedWith; } @JsonProperty("description") public String getDescription() { return description; } @JsonProperty("description") public void setDescription(String description) { this.description = description; } @JsonProperty("directory") public String getDirectory() { return directory; } @JsonProperty("directory") public void setDirectory(String directory) { this.directory = directory; } @JsonProperty("distribution") public String getDistribution() { return distribution; } @JsonProperty("distribution") public void setDistribution(String distribution) { this.distribution = distribution; } @JsonProperty("externalID") public String getExternalID() { return externalID; } @JsonProperty("externalID") public void setExternalID(String externalID) { this.externalID = externalID; } @JsonProperty("fileExtension") public String getFileExtension() { return fileExtension; } @JsonProperty("fileExtension") public void setFileExtension(String fileExtension) { this.fileExtension = fileExtension; } @JsonProperty("fileOwner") public CorporateUser getFileOwner() { return fileOwner; } @JsonProperty("fileOwner") public void setFileOwner(CorporateUser fileOwner) { this.fileOwner = fileOwner; } @JsonProperty("fileSize") public Integer getFileSize() { return fileSize; } @JsonProperty("fileSize") public void setFileSize(Integer fileSize) { this.fileSize = fileSize; } @JsonProperty("fileType") public String getFileType() { return fileType; } @JsonProperty("fileType") public void setFileType(String fileType) { this.fileType = fileType; } @JsonProperty("isCopied") public Boolean getCopied() { return isCopied; } @JsonProperty("isCopied") public void setCopied(Boolean isCopied) { this.isCopied = isCopied; } @JsonProperty("isDeleted") public Boolean getDeleted() { return isDeleted; } @JsonProperty("isDeleted") public void setDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } @JsonProperty("isEncrypted") public Boolean getEncrypted() { return isEncrypted; } @JsonProperty("isEncrypted") public void setEncrypted(Boolean isEncrypted) { this.isEncrypted = isEncrypted; } @JsonProperty("isExternal") public Boolean getExternal() { return isExternal; } @JsonProperty("isExternal") public void setExternal(Boolean isExternal) { this.isExternal = isExternal; } @JsonProperty("isOpen") public Boolean getOpen() { return isOpen; } @JsonProperty("isOpen") public void setOpen(Boolean isOpen) { this.isOpen = isOpen; } @JsonProperty("isPrivate") public Boolean getPrivate() { return isPrivate; } @JsonProperty("isPrivate") public void setPrivate(Boolean isPrivate) { this.isPrivate = isPrivate; } @JsonProperty("isSendOut") public Boolean getSendOut() { return isSendOut; } @JsonProperty("isSendOut") public void setSendOut(Boolean isSendOut) { this.isSendOut = isSendOut; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("type") public String getType() { return type; } @JsonProperty("type") public void setType(String type) { this.type = type; } @JsonProperty("usersSharedWith") public OneToMany<CorporateUser> getUsersSharedWith() { return usersSharedWith; } @JsonProperty("usersSharedWith") public void setUsersSharedWith(OneToMany<CorporateUser> usersSharedWith) { this.usersSharedWith = usersSharedWith; } @JsonProperty("uuid") public String getUuid() { return uuid; } @JsonProperty("uuid") public void setUuid(String uuid) { this.uuid = uuid; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EntityFileAttachment that = (EntityFileAttachment) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (contentSubType != null ? !contentSubType.equals(that.contentSubType) : that.contentSubType != null) return false; if (contentType != null ? !contentType.equals(that.contentType) : that.contentType != null) return false; if (dateAdded != null ? !dateAdded.equals(that.dateAdded) : that.dateAdded != null) return false; if (departmentsSharedWith != null ? !departmentsSharedWith.equals(that.departmentsSharedWith) : that.departmentsSharedWith != null) return false; if (description != null ? !description.equals(that.description) : that.description != null) return false; if (directory != null ? !directory.equals(that.directory) : that.directory != null) return false; if (distribution != null ? !distribution.equals(that.distribution) : that.distribution != null) return false; if (externalID != null ? !externalID.equals(that.externalID) : that.externalID != null) return false; if (fileExtension != null ? !fileExtension.equals(that.fileExtension) : that.fileExtension != null) return false; if (fileSize != null ? !fileSize.equals(that.fileSize) : that.fileSize != null) return false; if (fileType != null ? !fileType.equals(that.fileType) : that.fileType != null) return false; if (fileOwner != null ? !fileOwner.equals(that.fileOwner) : that.fileOwner != null) return false; if (isCopied != null ? !isCopied.equals(that.isCopied) : that.isCopied != null) return false; if (isDeleted != null ? !isDeleted.equals(that.isDeleted) : that.isDeleted != null) return false; if (isExternal != null ? !isExternal.equals(that.isExternal) : that.isExternal != null) return false; if (isOpen != null ? !isOpen.equals(that.isOpen) : that.isOpen != null) return false; if (isPrivate != null ? !isPrivate.equals(that.isPrivate) : that.isPrivate != null) return false; if (isSendOut != null ? !isSendOut.equals(that.isSendOut) : that.isSendOut != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; if (usersSharedWith != null ? !usersSharedWith.equals(that.usersSharedWith) : that.usersSharedWith != null) return false; return uuid != null ? uuid.equals(that.uuid) : that.uuid == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (contentSubType != null ? contentSubType.hashCode() : 0); result = 31 * result + (contentType != null ? contentType.hashCode() : 0); result = 31 * result + (dateAdded != null ? dateAdded.hashCode() : 0); result = 31 * result + (departmentsSharedWith != null ? departmentsSharedWith.hashCode() : 0); result = 31 * result + (description != null ? description.hashCode() : 0); result = 31 * result + (directory != null ? directory.hashCode() : 0); result = 31 * result + (distribution != null ? distribution.hashCode() : 0); result = 31 * result + (externalID != null ? externalID.hashCode() : 0); result = 31 * result + (fileExtension != null ? fileExtension.hashCode() : 0); result = 31 * result + (fileSize != null ? fileSize.hashCode() : 0); result = 31 * result + (fileType != null ? fileType.hashCode() : 0); result = 31 * result + (fileOwner != null ? fileOwner.hashCode() : 0); result = 31 * result + (isCopied != null ? isCopied.hashCode() : 0); result = 31 * result + (isDeleted != null ? isDeleted.hashCode() : 0); result = 31 * result + (isExternal != null ? isExternal.hashCode() : 0); result = 31 * result + (isOpen != null ? isOpen.hashCode() : 0); result = 31 * result + (isPrivate != null ? isPrivate.hashCode() : 0); result = 31 * result + (isSendOut != null ? isSendOut.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (usersSharedWith != null ? usersSharedWith.hashCode() : 0); result = 31 * result + (uuid != null ? uuid.hashCode() : 0); return result; } }
31.010309
139
0.649518
0991decd206c9c0905b67b23faf93398f7d8424b
2,185
package com.linghangcloud.android; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import com.onegravity.rteditor.RTEditText; import com.onegravity.rteditor.RTManager; import com.onegravity.rteditor.RTToolbar; import com.onegravity.rteditor.api.RTApi; import com.onegravity.rteditor.api.RTMediaFactoryImpl; import com.onegravity.rteditor.api.RTProxyImpl; import com.onegravity.rteditor.fonts.FontManager; public class ReleaseActivity extends AppCompatActivity { private Button back; private RTManager mrtManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.ThemeLight); getSupportActionBar().hide(); setContentView(R.layout.activity_release); back=findViewById(R.id.back_home); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); // create RTManager RTApi rtApi = new RTApi(this, new RTProxyImpl(this), new RTMediaFactoryImpl(this, true)); mrtManager = new RTManager(rtApi, savedInstanceState); // register toolbar ViewGroup toolbarContainer = (ViewGroup) findViewById(R.id.rte_toolbar_container); RTToolbar rtToolbar = (RTToolbar) findViewById(R.id.rte_toolbar); if (rtToolbar != null) { mrtManager.registerToolbar(toolbarContainer, rtToolbar); } // register editor & set text RTEditText rtEditText = (RTEditText) findViewById(R.id.rtEditText); mrtManager.registerEditor(rtEditText, true); FontManager.preLoadFonts(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mrtManager.onSaveInstanceState(outState); } @Override public void onDestroy() { super.onDestroy(); mrtManager.onDestroy(isFinishing()); } }
36.416667
98
0.686957
9805a225ede4e3618afe8e2b2d429bc66113dbd3
4,522
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package fredboat.command.util; import fredboat.FredBoat; import fredboat.commandmeta.abs.Command; import fredboat.commandmeta.abs.CommandContext; import fredboat.commandmeta.abs.IUtilCommand; import fredboat.messaging.CentralMessaging; import fredboat.messaging.internal.Context; import fredboat.util.ArgumentUtil; import fredboat.util.TextUtils; import fredboat.util.ratelimit.Ratelimiter; import net.dv8tion.jda.core.entities.Member; import javax.annotation.Nonnull; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; /** * Created by midgard on 17/01/20. */ public class UserInfoCommand extends Command implements IUtilCommand { public UserInfoCommand(String name, String... aliases) { super(name, aliases); } @Override public void onInvoke(@Nonnull CommandContext context) { Member target; StringBuilder knownServers = new StringBuilder(); List<String> matchedGuildNames = new ArrayList<>(); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy"); if (!context.hasArguments()) { target = context.invoker; } else { target = ArgumentUtil.checkSingleFuzzyMemberSearchResult(context, context.rawArgs, true); } if (target == null) return; FredBoat.getAllGuilds().forEach(guild -> { if (guild.getMemberById(target.getUser().getId()) != null) { matchedGuildNames.add(guild.getName()); } }); if (matchedGuildNames.size() >= 30) { knownServers.append(matchedGuildNames.size()); } else { int i = 0; for (String guildName : matchedGuildNames) { i++; knownServers.append(guildName); if (i < matchedGuildNames.size()) { knownServers.append(",\n"); } } } //DMify if I can context.reply(CentralMessaging.getClearThreadLocalEmbedBuilder() .setColor(target.getColor()) .setThumbnail(target.getUser().getAvatarUrl()) .setTitle(context.i18nFormat("userinfoTitle", target.getEffectiveName()), null) .addField(context.i18n("userinfoUsername"), TextUtils.escapeMarkdown(target.getUser().getName()) + "#" + target.getUser().getDiscriminator(), true) .addField(context.i18n("userinfoId"), target.getUser().getId(), true) .addField(context.i18n("userinfoNick"), TextUtils.escapeMarkdown(target.getEffectiveName()), true) //Known Nickname .addField(context.i18n("userinfoKnownServer"), knownServers.toString(), true) //Known Server .addField(context.i18n("userinfoJoinDate"), target.getJoinDate().format(dtf), true) .addField(context.i18n("userinfoCreationTime"), target.getUser().getCreationTime().format(dtf), true) .addField(context.i18n("userinfoBlacklisted"), Boolean.toString(Ratelimiter.getRatelimiter().isBlacklisted(context.invoker.getUser().getIdLong())), true) .build() ); } @Nonnull @Override public String help(@Nonnull Context context) { return "{0}{1} OR {0}{1} <user>\n#" + context.i18n("helpUserInfoCommand"); } }
42.261682
131
0.666962
cb097d3e1032b9ab2ba433d8c8f504e8d29629c4
6,939
package com.uet.beman.fragment; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.uet.beman.R; import com.uet.beman.common.BM_Utils; import com.uet.beman.common.SharedPreferencesHelper; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link BM_FragmentPhoneNumber.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link BM_FragmentPhoneNumber#newInstance} factory method to * create an instance of this fragment. */ public class BM_FragmentPhoneNumber extends Fragment implements View.OnClickListener{ public static final int PICK_CONTACT = 1; private OnFragmentInteractionListener mListener; SharedPreferencesHelper sharedPreferencesHelper; Button button; TextView headline, result; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment BM_FragmentPhoneNumber. */ // TODO: Rename and change types and number of parameters public static BM_FragmentPhoneNumber newInstance() { BM_FragmentPhoneNumber fragment = new BM_FragmentPhoneNumber(); return fragment; } public BM_FragmentPhoneNumber() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedPreferencesHelper = SharedPreferencesHelper.getInstance(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_phone_number, container, false); button = (Button)view.findViewById(R.id.numberBtn); headline = (TextView)view.findViewById(R.id.phone_number_headline); result = (TextView)view.findViewById(R.id.phone_number_bottom); button.setOnClickListener(this); String userName = sharedPreferencesHelper.getUserName(); String name = sharedPreferencesHelper.getDestName(); String no = sharedPreferencesHelper.getDestNumber(); BM_Utils.updateNameReferences(headline,getResources(),R.string.line_fragment_number,userName); BM_Utils.updateNameReferences(result,getResources(),R.string.line_fragment_info_result2, name, no); if(name.isEmpty() && no.isEmpty()) { // onFragmentChange(false); } else { button.setText(name +"\n"+no); } // Inflate the layout for this fragment return view; } @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT); } // TODO: Rename method, update argument and hook method into UI event public void onFragmentChange(boolean status) { if (mListener != null) { mListener.onFragmentInteraction(status); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(boolean status); } private String getGirlNumber() { return sharedPreferencesHelper.getDestNumber(); } private void setGirlNumber(String number) { sharedPreferencesHelper.setDestNumber(number); } private String getGirlName() { return sharedPreferencesHelper.getDestName(); } private void setGirlName(String name) { sharedPreferencesHelper.setDestName(name); } @Override public void onActivityResult(int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data); switch (reqCode) { case (PICK_CONTACT) : if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); Cursor c = getActivity().getContentResolver().query(contactData, null, null, null, null); ContentResolver contentResolver = getActivity().getContentResolver(); if (c.moveToFirst()) { String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); String name = ""; String no = ""; Cursor phoneCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null); if(phoneCursor.moveToFirst()) { name = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); no = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); } // String number = c.getString(c.getColumnIndex(ContactsContract.Data.DATA1)); // TODO Whatever you want to do with the selected contact name. setGirlName(name); setGirlNumber(no); String displayResult = name + "\n" + no; button.setText(displayResult); BM_Utils.updateNameReferences(result,getResources(),R.string.line_fragment_info_result2, name, no); onFragmentChange(true); } c.close(); } break; } } }
38.55
212
0.657155
d308461bfe4088a220b51655c835f0b53b89e7df
1,998
package com.github.mikephil.charting.utils; import android.content.Context; import android.graphics.Color; import java.util.ArrayList; import java.util.Collection; public class MulticolorDrawingSpec extends DrawingSpec { private ArrayList<Integer> mColors = new ArrayList<Integer>(); // 3D colors private ArrayList<Integer> mTopColors = new ArrayList<Integer>(); private ArrayList<Integer> mSideColors = new ArrayList<Integer>(); public boolean hasMultipleColors() { return !mColors.isEmpty(); } public int getColor(int idx) { return mColors.get(idx % mColors.size()); } public int getTopColor(int idx) { return mTopColors.get(idx % mTopColors.size()); } public int getSideColor(int idx) { return mSideColors.get(idx % mSideColors.size()); } public int getColorsCount() { return mColors.size(); } public void setColors(int... colors) { mColors.clear(); for (int color : colors) { mColors.add(color); } calculate3DColors(); } public void setColors(Collection<Integer> colors) { mColors.clear(); mColors.addAll(colors); } public static int[] fromResources(Context ctx, int... resId) { int[] ret = new int[resId.length]; for (int i = 0; i < resId.length; ++i) { ret[i] = ctx.getResources().getColor(resId[i]); } return ret; } private void calculate3DColors() { mTopColors.clear(); mSideColors.clear(); float[] hsv = new float[3]; for (int color : mColors) { // extract the color Color.colorToHSV(color, hsv); // convert to hsv // make brighter hsv[1] = hsv[1] - 0.1f; // less saturation hsv[2] = hsv[2] + 0.1f; // more brightness // assign mTopColors.add(Color.HSVToColor(hsv)); // convert Color.colorToHSV(color, hsv); // make darker hsv[1] = hsv[1] + 0.1f; // more saturation hsv[2] = hsv[2] - 0.1f; // less brightness mSideColors.add(Color.HSVToColor(hsv)); } } }
23.505882
68
0.63964
99a2e1484ec10de47193cd89417f01b2f48cd2ec
13,224
package com.bdoemu.gameserver.model.actions.templates; import com.bdoemu.commons.io.FileBinaryReader; import com.bdoemu.gameserver.model.actions.enums.*; import com.bdoemu.gameserver.model.actions.templates.frameevents.FrameEvent; import com.bdoemu.gameserver.model.creature.Creature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ActionChartActionT { private static final Logger log = LoggerFactory.getLogger(ActionChartActionT.class); public static float FRAME_RATE = 33.333332f; private final String actionName; private final long actionHash; private final int skillId; private final int vehicleSkillKey; private final int indexedActionCount; private final int addDvForMonster; private final int addPvForMonster; private final int varyWP; private final int varySRP; private final int addDv; private final int addPv; private final int attackAbsorbAmount1; private final int attackAbsorbAmount2; private final int hpPerDamage; private final int mpPerDamage; private final int stunPerDamage; private final int applySp; private final int combineWavePoint; private final int needCombineWavePoint; private final Map<String, ActionBranchT> branches; private final List<FrameEvent> frameEvents; private final List<FrameEvent> indexedFrameEvents; private final EActionType actionType; private final ESpUseType spUseType; private final int navigationTypes; private final float moveSpeed; private final float minMoveSpeed; private final float maxMoveSpeed; private final float staminaSpeed; private final float startFrame; private final float endFrame; private final float animationSpeed; private final float animationTime; private final EAttackAbsorbType attackAbsorbType1; private final EAttackAbsorbType attackAbsorbType2; private final EBattleAimedActionType battleAimedActionType; private final EApplySpeedBuffType applySpeedBuffType; private final EMoveDirectionType moveDirectionType; private final EAttachTerrainType attachTerrainType; private final EGuardType guardType; private int actionTime; private List<ETargetType> targetTypes; private boolean isDoBranch; private boolean isForceMove; private boolean isSwimmingAction; private boolean isNoDelayAI; private boolean isParkingAction; private boolean isEvadeEmergency; public ActionChartActionT(final FileBinaryReader reader) { this.branches = new HashMap<>(); this.frameEvents = new ArrayList<>(); this.indexedFrameEvents = new ArrayList<>(); this.targetTypes = ETargetType.valueof(reader.readD()); this.actionHash = reader.readDQ(); this.actionName = reader.readS(); this.actionType = EActionType.valueof(reader.readCD()); this.battleAimedActionType = EBattleAimedActionType.valueof(reader.readCD()); this.applySpeedBuffType = EApplySpeedBuffType.valueof(reader.readCD()); this.minMoveSpeed = reader.readF(); this.maxMoveSpeed = reader.readF(); this.moveSpeed = reader.readF(); this.startFrame = reader.readF(); this.endFrame = reader.readF(); this.animationSpeed = reader.readF(); this.animationTime = reader.readF(); this.combineWavePoint = reader.readHD(); this.needCombineWavePoint = reader.readHD(); this.hpPerDamage = reader.readHD(); this.mpPerDamage = reader.readHD(); this.stunPerDamage = reader.readHD(); this.addDvForMonster = reader.readHD(); this.addPvForMonster = reader.readHD(); this.varyWP = reader.readHD(); this.varySRP = reader.readD(); this.applySp = reader.readHD(); this.staminaSpeed = reader.readF(); this.addDv = reader.readCD(); this.addPv = reader.readCD(); this.attackAbsorbAmount1 = reader.readH(); this.attackAbsorbAmount2 = reader.readH(); this.attackAbsorbType1 = EAttackAbsorbType.valueOf(reader.readCD()); this.attackAbsorbType2 = EAttackAbsorbType.valueOf(reader.readCD()); this.spUseType = ESpUseType.values()[reader.readCD()]; this.guardType = EGuardType.values()[reader.readCD()]; this.skillId = reader.readHD(); this.vehicleSkillKey = reader.readCD(); this.navigationTypes = reader.readD(); this.moveDirectionType = EMoveDirectionType.values()[reader.readC()]; this.attachTerrainType = EAttachTerrainType.values()[reader.readC()]; this.indexedActionCount = reader.readHD(); final int bitData1 = reader.readCD(); final int bitData2 = reader.readCD(); this.isNoDelayAI = ((bitData2 & 0x40) == 0x40); final int bitData3 = reader.readCD(); this.isParkingAction = ((bitData3 & 0x20) == 0x20); final int bitData4 = reader.readCD(); final int bitData5 = reader.readCD(); this.isDoBranch = ((bitData5 & 0x1) == 0x1); this.isSwimmingAction = ((bitData5 & 0x10) == 0x10); final int bitData6 = reader.readCD(); this.isEvadeEmergency = ((bitData6 & 0x10) == 0x10); final int bitData7 = reader.readCD(); this.isForceMove = ((bitData7 & 0x2) == 0x2); for (int branchCount = reader.readD(), branchIndex = 0; branchIndex < branchCount; ++branchIndex) { final ActionBranchT actionBranchT = new ActionBranchT(reader); this.branches.put(actionBranchT.getCondition(), actionBranchT); } final float totalFrames = this.animationTime * 1000.0f / ActionChartActionT.FRAME_RATE; final float fps = this.animationTime * 1000.0f * this.animationSpeed / totalFrames; this.actionTime = (int) ((((this.endFrame == -1.0f) ? totalFrames : this.endFrame) - this.startFrame) * fps); float delay = 0.0f; final int frameCount = reader.readD(); float currentFrame = this.startFrame; float currentDelay = 0.0f; int prevFrameTime = 0; for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { final EFrameEventType frameEventType = EFrameEventType.valueof(reader.readCD()); final FrameEvent frameEvent = frameEventType.getNewFrameEventInstance(); if (frameEvent != null) { frameEvent.read(reader); if (currentFrame != frameEvent.getFrame()) { delay += currentDelay; currentDelay = 0.0f; currentFrame = frameEvent.getFrame(); } currentDelay += frameEvent.getDelay(); final int frameTime = (int) ((frameEvent.getFrame() - this.startFrame) * fps + delay); frameEvent.setFrameTime(frameTime - prevFrameTime); prevFrameTime = frameTime; if (!frameEventType.isSpeed()) { this.indexedFrameEvents.add(frameEvent); } this.frameEvents.add(frameEvent); } else { ActionChartActionT.log.error("Found non server-side FrameEvent in binary data: type={}", (Object) frameEventType.toString()); } } this.actionTime += (int) (delay + currentDelay); this.actionTime -= prevFrameTime; } public int getSpeedRate(final Creature owner) { switch (this.applySpeedBuffType) { case Move: { return owner.getGameStats().getMoveSpeedRate().getMoveSpeedRate(); } case Attack: { return owner.getGameStats().getAttackSpeedRate().getAttackSpeedRate(); } case Cast: { return owner.getGameStats().getCastingSpeedRate().getCastingSpeedRate(); } default: { return 0; } } } public int getSlowSpeedRate(final Creature owner) { int slowRate = 0; final long weightPercentage = owner.getGameStats().getWeight().getWeightPercentage(); switch (this.applySpeedBuffType) { case Move: { if (weightPercentage >= 150L) { slowRate = 950000; break; } if (weightPercentage >= 125L) { slowRate = 650000; break; } if (weightPercentage >= 100L) { slowRate = 300000; break; } break; } case Attack: case Cast: { if (weightPercentage >= 150L) { slowRate = 500000; break; } if (weightPercentage >= 125L) { slowRate = 300000; break; } if (weightPercentage >= 100L) { slowRate = 150000; break; } break; } } return slowRate; } public boolean isParkingAction() { return this.isParkingAction; } public boolean isForceMove() { return this.isForceMove; } public boolean isSwimmingAction() { return this.isSwimmingAction; } public boolean isDoBranch() { return this.isDoBranch; } public boolean isNoDelayAI() { return this.isNoDelayAI; } public int getVarySRP() { return this.varySRP; } public int getVaryWP() { return this.varyWP; } public EMoveDirectionType getMoveDirectionType() { return this.moveDirectionType; } public EAttachTerrainType getAttachTerrainType() { return this.attachTerrainType; } public int getIndexedActionCount() { return this.indexedActionCount; } public EApplySpeedBuffType getApplySpeedBuffType() { return this.applySpeedBuffType; } public EBattleAimedActionType getBattleAimedActionType() { return this.battleAimedActionType; } public ActionBranchT getBranch(final String condition) { return this.branches.get(condition); } public Map<String, ActionBranchT> getBranches() { return this.branches; } public float getMinMoveSpeed() { return this.minMoveSpeed; } public float getMaxMoveSpeed() { return this.maxMoveSpeed; } public float getMoveSpeed() { return this.moveSpeed; } public int getAttackAbsorbAmount2() { return this.attackAbsorbAmount2; } public int getAttackAbsorbAmount1() { return this.attackAbsorbAmount1; } public EAttackAbsorbType getAttackAbsorbType2() { return this.attackAbsorbType2; } public EAttackAbsorbType getAttackAbsorbType1() { return this.attackAbsorbType1; } public List<FrameEvent> getFrameEvents() { return this.frameEvents; } public List<FrameEvent> getIndexedFrameEvents() { return this.indexedFrameEvents; } public EActionType getActionType() { return this.actionType; } public int getNavigationTypes() { return this.navigationTypes; } public ESpUseType getSpUseType() { return this.spUseType; } public EGuardType getGuardType() { return this.guardType; } public int getApplySp() { return this.applySp; } public int getSkillId() { return this.skillId; } public int getSkillLevel() { return (this.skillId > 0) ? 1 : 0; } public int getVehicleSkillKey() { return this.vehicleSkillKey; } public int getHpPerDamage() { return this.hpPerDamage; } public int getMpPerDamage() { return this.mpPerDamage; } public int getStunPerDamage() { return this.stunPerDamage; } public long getActionHash() { return this.actionHash; } public int getCombineWavePoint() { return this.combineWavePoint; } public int getNeedCombineWavePoint() { return this.needCombineWavePoint; } public String getActionName() { return this.actionName; } public float getStaminaSpeed() { return this.staminaSpeed; } public float getStartFrame() { return this.startFrame; } public float getEndFrame() { return this.endFrame; } public float getAnimationSpeed() { return this.animationSpeed; } public float getAnimationTime() { return this.animationTime; } public int getActionTime() { return this.actionTime; } public boolean isEvadeEmergency() { return this.isEvadeEmergency; } public int getAddDv() { return this.addDv; } public int getAddPv() { return this.addPv; } public int getAddDvForMonster() { return this.addDvForMonster; } public int getAddPvForMonster() { return this.addPvForMonster; } }
32.097087
141
0.626664
1b6118a9598b5cee89b4f3554245810747dc37e7
309
/* * Copyright 2002 Felix Pahl. All rights reserved. * Use is subject to license terms. */ package info.joriki.sfnt; public class EncodingPair { public int code; public int glyphIndex; public EncodingPair (int code,int glyphIndex) { this.code = code; this.glyphIndex = glyphIndex; } }
16.263158
50
0.695793
e69d05428a9fede1a574799c9dc536f4336da139
655
/** * Copyright (C) 2017 Baidu, Inc. All Rights Reserved. */ package io.iamhaha.cms.module.service; import io.iamhaha.cms.model.user.Student; import io.iamhaha.cms.module.model.request.StudentCreateReq; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Student service interface. * * @author dingshenglong */ public interface StudentService { Student get(String id); List<Student> list(); List<Student> list(List<String> ids); List<Student> listByClass(String cid); @Transactional void create(StudentCreateReq req); @Transactional void delete(List<String> ids); }
19.848485
64
0.723664
1987474077596337996c4f4e9b2eff93d94f74be
2,919
package com.gymnast.view.personal.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import com.gymnast.R; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.personal.adapter.AddressAdapter; import java.util.ArrayList; import java.util.List; /** * Created by yf928 on 2016/7/25. */ public class PersonalAddressActivity extends ImmersiveActivity { private RecyclerView listitem; private List<LiveItems> packItems=new ArrayList<>(); private AddressAdapter packAdapter; private CheckBox checkbox; private ImageView back; private TextView add; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal_address); setview(); LinearLayoutManager LinearLayout = new LinearLayoutManager(this); packAdapter = new AddressAdapter(this, packItems); listitem.setLayoutManager(LinearLayout); listitem.setAdapter(packAdapter); initView(); } private void setview() { back= (ImageView)findViewById(R.id.personal_back); add = (TextView)findViewById(R.id.add); listitem=(RecyclerView)findViewById(R.id.recycler_address); checkbox=(CheckBox)findViewById(R.id.address_checkBox); } private void initView() { back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i=new Intent(PersonalAddressActivity.this,PersonalAddressAddActivity.class); startActivity(i); } }); } public PersonalAddressActivity() { for (int i = 0; i < 10; i++) { LiveItems liveItem = new LiveItems("测试", null, "12345" + i, "谁VS谁" + i); packItems.add(liveItem); } } public static PersonalAddressActivity newInstance(String param1, String param2) { PersonalAddressActivity acitvity = new PersonalAddressActivity(); return acitvity; } public static class LiveItems { public final String liveUrl; public final String livePicture; public final String liveViewer; public final String liveTitle; public LiveItems(String liveUrl, String livePicture, String liveViewer, String liveTitle) { this.liveUrl = liveUrl; this.livePicture = livePicture; this.liveViewer = liveViewer; this.liveTitle = liveTitle; } } }
35.597561
99
0.67112
3197e01c6df674b7b663167ca045f64e25ba0dc2
9,238
package nl.bos.utils; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.Window; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; /** * Class that contains UI util methods */ public final class UIUtils { public static final String INVALID_STYLE_STRING = "-fx-border-color: red;-fx-border-style: solid;"; /** * Private constructor that hides the default public constructor */ private UIUtils() { //Do nothing, just hide the default constructor } /** * Shows an alert with an expendable box to show the stacktrace of the exception * * @param title Shown in the title bar of the alert * @param header Shown in the header bar of the alert * @param content The normal content (summary of what happened) * @param ex The exception to show */ public static void showExpendableExceptionAlert(String title, String header, String content, Exception ex) { //Create the alert final Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle(title); alert.setHeaderText(header); alert.setContentText(content); // Get the stacktrace of the exception final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); final String exceptionText = sw.toString(); //Create the expendable stacktrace box final Label label = new Label("The exception stacktrace was:"); final TextArea textArea = new TextArea(exceptionText); textArea.setEditable(false); textArea.setWrapText(true); textArea.setMaxWidth(Double.MAX_VALUE); textArea.setMaxHeight(Double.MAX_VALUE); GridPane.setVgrow(textArea, Priority.ALWAYS); GridPane.setHgrow(textArea, Priority.ALWAYS); final GridPane expContent = new GridPane(); expContent.setMaxWidth(Double.MAX_VALUE); expContent.add(label, 0, 0); expContent.add(textArea, 0, 1); //Add expandable stacktrace box to the dialog pane. alert.getDialogPane().setExpandableContent(expContent); alert.showAndWait(); } /** * Loads and opens a new window. This method should only be used when you explicitly want to open a new window. * When you want to open a new window and close the current one, use the loadAndShowInCurrentWindow method. * * @param fxmlPath The path to the fxml file with the resource directory as root * @param windowTitle The title to be used for the window * @param modality The modality to initialize the stage with. Owner should be set when the modality is * WINDOW_MODAL * @param owner The owner window of the window to create. This is only needed when setting the modality to * WINDOW_MODAL * @throws IOException Thrown if something goes wrong while loading the fxml window */ public static void loadAndShowNewWindow(String fxmlPath, String windowTitle, Modality modality, Window owner) throws IOException { final FXMLLoader fxmlLoader = new FXMLLoader(Thread.currentThread().getContextClassLoader().getResource(fxmlPath)); final Parent root = fxmlLoader.load(); final Stage stage = new Stage(); stage.initOwner(owner); stage.initModality(modality); stage.setTitle(windowTitle); stage.setScene(new Scene(root)); stage.show(); } /** * Loads and opens a new window. This method should only be used when you explicitly want to open a new window. * When you want to open a new window and close the current one, use the loadAndShowInCurrentWindow method. * * @param fxmlPath The path to the fxml file with the resource directory as root * @param windowTitle The title to be used for the window * @param modality The modality to initialize the stage with. Owner should be set when the modality is * WINDOW_MODAL, else it will be treated if set to NONE * @throws IOException Thrown if something goes wrong while loading the fxml window */ public static void loadAndShowNewWindow(String fxmlPath, String windowTitle, Modality modality) throws IOException { loadAndShowNewWindow(fxmlPath, windowTitle, modality, null); } /** * Loads and opens a new window. This method should only be used when you explicitly want to open a new window. * When you want to open a new window and close the current one, use the loadAndShowInCurrentWindow method. * * @param fxmlPath The path to the fxml file with the resource directory as root * @param windowTitle The title to be used for the window * @throws IOException Thrown if something goes wrong while loading the fxml window */ public static void loadAndShowNewWindow(String fxmlPath, String windowTitle) throws IOException { loadAndShowNewWindow(fxmlPath, windowTitle, Modality.NONE, null); } /** * Loads the given fxml in the window in which the node resides * * @param node The node that is in the window that should be used to load the next window in * @param fxmlPath The path to the FXML that should be used */ public static void loadAndShowInCurrentWindow(Node node, String fxmlPath) throws IOException { final FXMLLoader fxmlLoader = new FXMLLoader(Thread.currentThread().getContextClassLoader().getResource(fxmlPath)); final Stage stage = (Stage) node.getScene().getWindow(); final double width = stage.getWidth(); final double height = stage.getHeight(); stage.setScene(new Scene(fxmlLoader.load())); stage.setWidth(width); stage.setHeight(height); } /** * Checks whether or not a textfield is filled. If it is not, a style element is added to it. * * @param textField The textfield from which to validate the input. * @return Whether or not the input is valid */ public static boolean validateTextInput(TextField textField) { if (textField.getText() == null || textField.getText().isEmpty()) { addInvalidInputStyle(textField); return false; } else { removeInvalidInputStyle(textField); return true; } } /** * Checks whether or not a choice is made in the choicebox. If it is not, a style element to show it isn't will * be added. * * @param choiceBox The choicebox to validate the input from * @return Whether the input is valid or not */ public static boolean validateChoiceBoxInput(ChoiceBox choiceBox) { if (choiceBox.getSelectionModel().isEmpty()) { addInvalidInputStyle(choiceBox); return false; } else { removeInvalidInputStyle(choiceBox); return true; } } /** * Checks whether or not a choice is made in the choicebox. If it is not, a style element to show it isn't will * be added. * * @param comboBox The comboBox to validate the input from * @return Whether the input is valid or not */ public static boolean validateComboBoxInput(ComboBox comboBox) { if (comboBox.getSelectionModel().isEmpty()) { addInvalidInputStyle(comboBox); return false; } else { removeInvalidInputStyle(comboBox); return true; } } /** * Checks whether or not a textarea is filled. If it is not, a style element is added to it. * * @param textArea The textarea to validate the input of. * @return Wether the input is valid or not */ public static boolean validateTextAreaInput(TextArea textArea) { if (textArea.getText().isEmpty()) { addInvalidInputStyle(textArea); return false; } else { removeInvalidInputStyle(textArea); return true; } } /** * Adds a invalid input style element to the control, making it have a red border. * * @param control The control to add the style elements to */ public static void addInvalidInputStyle(Control control) { String style = control.getStyle(); if (!style.isEmpty() && !style.endsWith(";")) { style = style + ';'; } style = style + INVALID_STYLE_STRING; control.setStyle(style); } /** * Removes the invalid input style element to the control, making it have a red border. * * @param control The control to remove the style elements from */ public static void removeInvalidInputStyle(Control control) { String style = control.getStyle(); style = style.replace(INVALID_STYLE_STRING, ""); control.setStyle(style); } }
39.478632
123
0.660533
cb192b8408650457b63a5f1503960a9bcc2386de
3,688
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.servicebus.security; import java.time.Instant; import java.util.concurrent.CompletableFuture; import com.microsoft.azure.servicebus.security.AzureActiveDirectoryTokenProvider.AuthenticationCallback; /** * This abstract class defines the contract of a token provider. All token providers should inherit from this class. * An instance of token provider is used to obtain a security token for a given audience. * @since 1.2.0 * */ public abstract class TokenProvider { /** * Asynchronously gets a security token for the given audience. Implementations of this method may choose to create a new token for every call * or return a cached token. But the token returned must be valid. * @param audience path of the entity for which this security token is to be presented * @return an instance of CompletableFuture which returns a {@link SecurityToken} on completion. */ public abstract CompletableFuture<SecurityToken> getSecurityTokenAsync(String audience); /** * Creates a Shared Access Signature token provider with the given key name and key value. Returned token provider creates tokens * with validity of 20 minutes. This is a utility method. * @param sasKeyName SAS key name * @param sasKey SAS key value * @return an instance of Shared Access Signature token provider with the given key name, key value. */ public static TokenProvider createSharedAccessSignatureTokenProvider(String sasKeyName, String sasKey) { return new SharedAccessSignatureTokenProvider(sasKeyName, sasKey, SecurityConstants.DEFAULT_SAS_TOKEN_VALIDITY_IN_SECONDS); } /** * Creates a Shared Access Signature token provider that always returns an already created token. This is a utility method. * @param sasToken Already created Shared Access Signature token to be returned by {@link #getSecurityTokenAsync(String)} method. * @param sasTokenValidUntil Instant when the token expires * @return an instance of Shared Access Signature token provider that always returns an already created token. */ public static TokenProvider createSharedAccessSignatureTokenProvider(String sasToken, Instant sasTokenValidUntil) { return new SharedAccessSignatureTokenProvider(sasToken, sasTokenValidUntil); } /** * Creates a Azure Active Directory token provider that creates a token with the user defined AuthenticationCallback. This is a utility method. * @param callback A custom AuthenticationCallback that takes in the target resource and address of the authority * to issue token and provides a security token for the target url * @param authority URL of the Azure Active Directory instance * @param callbackState Custom parameter that may be provided to the AuthenticationCallback * @return an instance of Azure Active Directory token provider */ public static TokenProvider createAzureActiveDirectoryTokenProvider(AuthenticationCallback callback, String authority, Object callbackState) { if (callback == null) { throw new IllegalArgumentException("The callback provided cannot be null."); } return new AzureActiveDirectoryTokenProvider(callback, authority, callbackState); } /** * Creates a Managed Identity token provider. This is a utility method. * @return an instance of Managed Identity token provider */ public static TokenProvider createManagedIdentityTokenProvider() { return new ManagedIdentityTokenProvider(); } }
53.449275
147
0.754067
847f718a96fa853ac233af5ae61ebd7a0261d11a
10,868
package gov.nih.nci.evs.owl.visitor; import java.util.Set; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; import org.semanticweb.owlapi.model.OWLAnnotationPropertyDomainAxiom; import org.semanticweb.owlapi.model.OWLAnnotationPropertyRangeAxiom; import org.semanticweb.owlapi.model.OWLAsymmetricObjectPropertyAxiom; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLAxiomVisitorEx; import org.semanticweb.owlapi.model.OWLClassAssertionAxiom; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLDataPropertyAssertionAxiom; import org.semanticweb.owlapi.model.OWLDataPropertyDomainAxiom; import org.semanticweb.owlapi.model.OWLDataPropertyRangeAxiom; import org.semanticweb.owlapi.model.OWLDatatypeDefinitionAxiom; import org.semanticweb.owlapi.model.OWLDeclarationAxiom; import org.semanticweb.owlapi.model.OWLDifferentIndividualsAxiom; import org.semanticweb.owlapi.model.OWLDisjointClassesAxiom; import org.semanticweb.owlapi.model.OWLDisjointDataPropertiesAxiom; import org.semanticweb.owlapi.model.OWLDisjointObjectPropertiesAxiom; import org.semanticweb.owlapi.model.OWLDisjointUnionAxiom; import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom; import org.semanticweb.owlapi.model.OWLEquivalentDataPropertiesAxiom; import org.semanticweb.owlapi.model.OWLEquivalentObjectPropertiesAxiom; import org.semanticweb.owlapi.model.OWLFunctionalDataPropertyAxiom; import org.semanticweb.owlapi.model.OWLFunctionalObjectPropertyAxiom; import org.semanticweb.owlapi.model.OWLHasKeyAxiom; import org.semanticweb.owlapi.model.OWLInverseFunctionalObjectPropertyAxiom; import org.semanticweb.owlapi.model.OWLInverseObjectPropertiesAxiom; import org.semanticweb.owlapi.model.OWLIrreflexiveObjectPropertyAxiom; import org.semanticweb.owlapi.model.OWLNegativeDataPropertyAssertionAxiom; import org.semanticweb.owlapi.model.OWLNegativeObjectPropertyAssertionAxiom; import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom; import org.semanticweb.owlapi.model.OWLObjectPropertyDomainAxiom; import org.semanticweb.owlapi.model.OWLObjectPropertyRangeAxiom; import org.semanticweb.owlapi.model.OWLReflexiveObjectPropertyAxiom; import org.semanticweb.owlapi.model.OWLSameIndividualAxiom; import org.semanticweb.owlapi.model.OWLSubAnnotationPropertyOfAxiom; import org.semanticweb.owlapi.model.OWLSubClassOfAxiom; import org.semanticweb.owlapi.model.OWLSubDataPropertyOfAxiom; import org.semanticweb.owlapi.model.OWLSubObjectPropertyOfAxiom; import org.semanticweb.owlapi.model.OWLSubPropertyChainOfAxiom; import org.semanticweb.owlapi.model.OWLSymmetricObjectPropertyAxiom; import org.semanticweb.owlapi.model.OWLTransitiveObjectPropertyAxiom; import org.semanticweb.owlapi.model.SWRLRule; /** * https://github.com/owlcollab/owltools/blob/master/OWLTools-Core/src/main/java * /owltools/graph/AxiomAnnotationTools.java#L329 * * * Visitor which returns a new axiom of the same type with the new annotations. * */ public class AxiomAnnotationsChanger implements OWLAxiomVisitorEx<OWLAxiom> { private final Set<OWLAnnotation> annotations; private final OWLDataFactory factory; public AxiomAnnotationsChanger(Set<OWLAnnotation> annotations, OWLDataFactory factory) { this.annotations = annotations; this.factory = factory; } @Override public OWLAxiom visit(OWLSubAnnotationPropertyOfAxiom axiom) { return this.factory.getOWLSubAnnotationPropertyOfAxiom( axiom.getSubProperty(), axiom.getSuperProperty(), this.annotations); } @Override public OWLAxiom visit(OWLAnnotationPropertyDomainAxiom axiom) { return this.factory.getOWLAnnotationPropertyDomainAxiom( axiom.getProperty(), axiom.getDomain(), this.annotations); } @Override public OWLAxiom visit(OWLAnnotationPropertyRangeAxiom axiom) { return this.factory.getOWLAnnotationPropertyRangeAxiom( axiom.getProperty(), axiom.getRange(), this.annotations); } @Override public OWLAxiom visit(OWLSubClassOfAxiom axiom) { return this.factory.getOWLSubClassOfAxiom(axiom.getSubClass(), axiom.getSuperClass(), this.annotations); } @Override public OWLAxiom visit(OWLNegativeObjectPropertyAssertionAxiom axiom) { return this.factory.getOWLNegativeObjectPropertyAssertionAxiom( axiom.getProperty(), axiom.getSubject(), axiom.getObject(), this.annotations); } @Override public OWLAxiom visit(OWLAsymmetricObjectPropertyAxiom axiom) { return this.factory.getOWLAsymmetricObjectPropertyAxiom( axiom.getProperty(), this.annotations); } @Override public OWLAxiom visit(OWLReflexiveObjectPropertyAxiom axiom) { return this.factory.getOWLReflexiveObjectPropertyAxiom( axiom.getProperty(), this.annotations); } @Override public OWLAxiom visit(OWLDisjointClassesAxiom axiom) { return this.factory.getOWLDisjointClassesAxiom( axiom.getClassExpressions(), this.annotations); } @Override public OWLAxiom visit(OWLDataPropertyDomainAxiom axiom) { return this.factory.getOWLDataPropertyDomainAxiom(axiom.getProperty(), axiom.getDomain(), this.annotations); } @Override public OWLAxiom visit(OWLObjectPropertyDomainAxiom axiom) { return this.factory.getOWLObjectPropertyDomainAxiom( axiom.getProperty(), axiom.getDomain(), this.annotations); } @Override public OWLAxiom visit(OWLEquivalentObjectPropertiesAxiom axiom) { return this.factory.getOWLEquivalentObjectPropertiesAxiom( axiom.getProperties(), this.annotations); } @Override public OWLAxiom visit(OWLNegativeDataPropertyAssertionAxiom axiom) { return this.factory.getOWLNegativeDataPropertyAssertionAxiom( axiom.getProperty(), axiom.getSubject(), axiom.getObject(), this.annotations); } @Override public OWLAxiom visit(OWLDifferentIndividualsAxiom axiom) { return this.factory.getOWLDifferentIndividualsAxiom( axiom.getIndividuals(), this.annotations); } @Override public OWLAxiom visit(OWLDisjointDataPropertiesAxiom axiom) { return this.factory.getOWLDisjointDataPropertiesAxiom( axiom.getProperties(), this.annotations); } @Override public OWLAxiom visit(OWLDisjointObjectPropertiesAxiom axiom) { return this.factory.getOWLDisjointObjectPropertiesAxiom( axiom.getProperties(), this.annotations); } @Override public OWLAxiom visit(OWLObjectPropertyRangeAxiom axiom) { return this.factory.getOWLObjectPropertyRangeAxiom(axiom.getProperty(), axiom.getRange(), this.annotations); } @Override public OWLAxiom visit(OWLObjectPropertyAssertionAxiom axiom) { return this.factory.getOWLObjectPropertyAssertionAxiom( axiom.getProperty(), axiom.getSubject(), axiom.getObject(), this.annotations); } @Override public OWLAxiom visit(OWLFunctionalObjectPropertyAxiom axiom) { return this.factory.getOWLFunctionalObjectPropertyAxiom( axiom.getProperty(), this.annotations); } @Override public OWLAxiom visit(OWLSubObjectPropertyOfAxiom axiom) { return this.factory.getOWLSubObjectPropertyOfAxiom( axiom.getSubProperty(), axiom.getSuperProperty(), this.annotations); } @Override public OWLAxiom visit(OWLDisjointUnionAxiom axiom) { return this.factory.getOWLDisjointUnionAxiom(axiom.getOWLClass(), axiom.getClassExpressions(), this.annotations); } @Override public OWLAxiom visit(OWLDeclarationAxiom axiom) { return this.factory.getOWLDeclarationAxiom(axiom.getEntity(), this.annotations); } @Override public OWLAxiom visit(OWLAnnotationAssertionAxiom axiom) { return this.factory.getOWLAnnotationAssertionAxiom(axiom.getProperty(), axiom.getSubject(), axiom.getValue(), this.annotations); } @Override public OWLAxiom visit(OWLSymmetricObjectPropertyAxiom axiom) { return this.factory.getOWLSymmetricObjectPropertyAxiom( axiom.getProperty(), this.annotations); } @Override public OWLAxiom visit(OWLDataPropertyRangeAxiom axiom) { return this.factory.getOWLDataPropertyRangeAxiom(axiom.getProperty(), axiom.getRange(), this.annotations); } @Override public OWLAxiom visit(OWLFunctionalDataPropertyAxiom axiom) { return this.factory.getOWLFunctionalDataPropertyAxiom( axiom.getProperty(), this.annotations); } @Override public OWLAxiom visit(OWLEquivalentDataPropertiesAxiom axiom) { return this.factory.getOWLEquivalentDataPropertiesAxiom( axiom.getProperties(), this.annotations); } @Override public OWLAxiom visit(OWLClassAssertionAxiom axiom) { return this.factory.getOWLClassAssertionAxiom( axiom.getClassExpression(), axiom.getIndividual(), this.annotations); } @Override public OWLAxiom visit(OWLEquivalentClassesAxiom axiom) { return this.factory.getOWLEquivalentClassesAxiom( axiom.getClassExpressions(), this.annotations); } @Override public OWLAxiom visit(OWLDataPropertyAssertionAxiom axiom) { return this.factory.getOWLDataPropertyAssertionAxiom( axiom.getProperty(), axiom.getSubject(), axiom.getObject(), this.annotations); } @Override public OWLAxiom visit(OWLTransitiveObjectPropertyAxiom axiom) { return this.factory.getOWLTransitiveObjectPropertyAxiom( axiom.getProperty(), this.annotations); } @Override public OWLAxiom visit(OWLIrreflexiveObjectPropertyAxiom axiom) { return this.factory.getOWLIrreflexiveObjectPropertyAxiom( axiom.getProperty(), this.annotations); } @Override public OWLAxiom visit(OWLSubDataPropertyOfAxiom axiom) { return this.factory.getOWLSubDataPropertyOfAxiom( axiom.getSubProperty(), axiom.getSuperProperty(), this.annotations); } @Override public OWLAxiom visit(OWLInverseFunctionalObjectPropertyAxiom axiom) { return this.factory.getOWLInverseFunctionalObjectPropertyAxiom( axiom.getProperty(), this.annotations); } @Override public OWLAxiom visit(OWLSameIndividualAxiom axiom) { return this.factory.getOWLSameIndividualAxiom(axiom.getIndividuals(), this.annotations); } @Override public OWLAxiom visit(OWLSubPropertyChainOfAxiom axiom) { return this.factory.getOWLSubPropertyChainOfAxiom( axiom.getPropertyChain(), axiom.getSuperProperty(), this.annotations); } @Override public OWLAxiom visit(OWLInverseObjectPropertiesAxiom axiom) { return this.factory.getOWLInverseObjectPropertiesAxiom( axiom.getFirstProperty(), axiom.getSecondProperty(), this.annotations); } @Override public OWLAxiom visit(OWLHasKeyAxiom axiom) { return this.factory.getOWLHasKeyAxiom(axiom.getClassExpression(), axiom.getDataPropertyExpressions(), this.annotations); } @Override public OWLAxiom visit(OWLDatatypeDefinitionAxiom axiom) { return this.factory.getOWLDatatypeDefinitionAxiom(axiom.getDatatype(), axiom.getDataRange(), this.annotations); } @Override public OWLAxiom visit(SWRLRule rule) { return this.factory.getSWRLRule(rule.getBody(), rule.getHead(), this.annotations); } }
34.833333
80
0.815237
dc9b2b3cc885213e45b0ec1baf431de40043c4fe
5,484
package mercy.digital.transfer.domain; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable; import lombok.Generated; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Id; import javax.persistence.Column; import javax.persistence.JoinColumn; import java.sql.Timestamp; import java.util.Collection; import java.util.Objects; @Generated @DatabaseTable(tableName = "CLIENT_ACCOUNT") @Entity @Table(name = "CLIENT_ACCOUNT", schema = "TRANSFER", catalog = "H2") public class ClientAccountEntity { @DatabaseField(generatedId = true, columnName = "CLIENT_ACCOUNT_ID") private int clientAccountId; @DatabaseField(columnName = "ACCOUNT_NO") private Integer accountNo; @DatabaseField(columnName = "BALANCE") private Double balance; @DatabaseField(columnName = "CURRENCY") private String currency; @DatabaseField(columnName = "CREATED_AT") private Timestamp createdAt; @DatabaseField(columnName = "UPDATED_AT") private Timestamp updatedAt; @DatabaseField(columnName = "ACCOUNT_NAME") private String accountName; @DatabaseField(columnName = "COUNTRY_OF_ISSUE") private String countryOfIssue; @ForeignCollectionField private Collection<BalanceEntity> balanceHistoriesByClientAccountId; @DatabaseField(foreign = true, columnName = "CLIENT_ID") private ClientEntity clientByClientId; private Collection<BalanceEntity> balancesByClientAccountId; @Id @Column(name = "CLIENT_ACCOUNT_ID", nullable = false) public int getClientAccountId() { return clientAccountId; } public void setClientAccountId(int clientAccountId) { this.clientAccountId = clientAccountId; } @Basic @Column(name = "ACCOUNT_NO", nullable = false) public Integer getAccountNo() { return accountNo; } public void setAccountNo(Integer accountNo) { this.accountNo = accountNo; } @Basic @Column(name = "BALANCE", nullable = true, precision = 0) public Double getBalance() { return balance; } public void setBalance(Double balance) { this.balance = balance; } @Basic @Column(name = "CURRENCY", nullable = true, length = 3) public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } @Basic @Column(name = "CREATED_AT", nullable = true) public Timestamp getCreatedAt() { return createdAt; } public void setCreatedAt(Timestamp createdAt) { this.createdAt = createdAt; } @Basic @Column(name = "UPDATED_AT", nullable = true) public Timestamp getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Timestamp updatedAt) { this.updatedAt = updatedAt; } @Basic @Column(name = "ACCOUNT_NAME", nullable = true, length = 50) public String getAccountName() { return accountName; } public void setAccountName(String name) { this.accountName = name; } @Basic @Column(name = "COUNTRY_OF_ISSUE", nullable = true, length = 20) public String getCountryOfIssue() { return countryOfIssue; } public void setCountryOfIssue(String countryOfIssue) { this.countryOfIssue = countryOfIssue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClientAccountEntity that = (ClientAccountEntity) o; return clientAccountId == that.clientAccountId && accountNo.equals(that.accountNo) && Objects.equals(balance, that.balance) && Objects.equals(currency, that.currency) && Objects.equals(createdAt, that.createdAt) && Objects.equals(updatedAt, that.updatedAt) && Objects.equals(accountName, that.accountName) && Objects.equals(countryOfIssue, that.countryOfIssue); } @Override public int hashCode() { return Objects.hash(clientAccountId, accountNo, balance, currency, createdAt, updatedAt, accountName, countryOfIssue); } @OneToMany(mappedBy = "clientAccountByAccountId") public Collection<BalanceEntity> getBalanceHistoriesByClientAccountId() { return balanceHistoriesByClientAccountId; } public void setBalanceHistoriesByClientAccountId(Collection<BalanceEntity> balanceHistoriesByClientAccountId) { this.balanceHistoriesByClientAccountId = balanceHistoriesByClientAccountId; } @ManyToOne @JoinColumn(name = "CLIENT_ID", referencedColumnName = "CLIENT_ID", nullable = false) public ClientEntity getClientByClientId() { return clientByClientId; } public void setClientByClientId(ClientEntity clientByClientId) { this.clientByClientId = clientByClientId; } @OneToMany(mappedBy = "clientAccountByAccountId") public Collection<BalanceEntity> getBalancesByClientAccountId() { return balancesByClientAccountId; } public void setBalancesByClientAccountId(Collection<BalanceEntity> balancesByClientAccountId) { this.balancesByClientAccountId = balancesByClientAccountId; } }
30.636872
126
0.697119
576d69de0b9248dc83fc9f77668960d1f70cf5e0
408
package trivia; import org.javalite.activejdbc.Base; import trivia.User; /** * Hello world! * */ public class App { public static void main( String[] args ) { Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/trivia", "root", "muva"); User u = new User(); u.set("username", "Maradona"); u.set("password", "messi"); u.saveIt(); Base.close(); } }
17.73913
90
0.580882
40ed8020b60fd6ab0a54615e2bff55f79b931803
1,147
package com.alipay.api.domain; import java.util.List; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; /** * 单个主记录+对应资金明细信息模型 * * @author auto create * @since 1.0, 2016-10-26 17:31:15 */ public class SingleFundDetailItemAOPModel extends AlipayObject { private static final long serialVersionUID = 8348822312928365483L; /** * 批次资金明细模型列表 */ @ApiListField("batch_fund_item_model_list") @ApiField("batch_fund_item_a_o_p_model") private List<BatchFundItemAOPModel> batchFundItemModelList; /** * 消费记录主记录 */ @ApiField("consume_record") private ConsumeRecordAOPModel consumeRecord; public List<BatchFundItemAOPModel> getBatchFundItemModelList() { return this.batchFundItemModelList; } public void setBatchFundItemModelList(List<BatchFundItemAOPModel> batchFundItemModelList) { this.batchFundItemModelList = batchFundItemModelList; } public ConsumeRecordAOPModel getConsumeRecord() { return this.consumeRecord; } public void setConsumeRecord(ConsumeRecordAOPModel consumeRecord) { this.consumeRecord = consumeRecord; } }
24.404255
92
0.79163
a3cdd16d565e27ddc1ee3b987494bceb8aff87e0
1,124
public class Fig4_4 { public static void main (String[] args) { mainQ(Integer.parseInt(args[0]), Integer.parseInt(args[1])); } public static int mainQ(int n, int m){ assert (m>0); assert (n>0); int i = n; int t = 0; int h = n/m; /* int h = 0; */ /* while(m*h<=n){ */ /* h++; */ /* } */ /* h--; */ while(i>0){ if (i < m) { i--; }else{ i = i-m; } t++; } /* assert(n%m==0); */ /* int i = n; */ /* int t = 0; */ /* while(i>0){ */ /* if (i < m) { */ /* i--; */ /* }else{ */ /* i = i-m; */ /* } */ /* t++; */ /* } */ //%%%traces: int n, int m, int t, int h //dig2: l26: -c2 <= -1, c2*m - c2 - n + t == 0, c1 - m <= -1, -t <= -2, c1 + c2 - t == 0, c2 - t <= 0 //Note: I got the above results which I think are right. But I have to manually pass in the flag -maxdeg 3 (i.e., DIG attempts to use maxdeg 4 automatically, but this requires many traces that it wasn't able to get). return 0; } }
19.37931
220
0.402135
2e736337057c3d86dc9b7f0692e3978bfd4df3c0
603
package fr.aumgn.diamondrush.stage; import org.bukkit.ChatColor; import fr.aumgn.diamondrush.DiamondRush; public class TransitionStage extends StaticStage { protected Stage nextStage; private int duration; public TransitionStage(DiamondRush dr, Stage nextStage, int duration) { super(dr); this.nextStage = nextStage; this.duration = duration; } @Override public void start() { super.start(); dr.getGame().sendMessage(ChatColor.YELLOW + "C'est le moment de changer de canal."); scheduleNextStage(duration, nextStage); } }
24.12
92
0.68325
91e1d59dd328e84204f4708835f2e2295dac1102
1,535
package co.featureflags.spring; import co.featureflags.commons.model.FFCUser; import co.featureflags.server.exterior.FFCClient; import co.featureflags.server.integrations.FFCUserContextHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class FFCUserFilter implements Filter { private final static Logger LOG = LoggerFactory.getLogger(FFCUserFilter.class); private final FFCClient client; public FFCUserFilter(FFCClient client) { this.client = client; } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; FFCUser user; try { user = FFCUserUtils.captureUser(httpServletRequest, client); if (user != null) { LOG.debug("capture {}", user); FFCUserContextHolder.setCurrentUser(user, true); } filterChain.doFilter(servletRequest, servletResponse); } finally { user = FFCUserContextHolder.getCurrentUser(); LOG.debug("remove {}", user); FFCUserContextHolder.remove(); } } }
33.369565
113
0.712052
6ef7d8468de9d5bbc07d308e850adc012434abe2
2,331
package org.packt.microservice.hrs.controller; import java.sql.Date; import java.util.Arrays; import java.util.List; import org.packt.microservice.hrs.model.data.Employee; import org.packt.microservice.hrs.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController public class RestServiceController { @Autowired private EmployeeService employeeServiceImpl; @RequestMapping("/objectSampleRest") public String exposeString() { return "Hello World"; } @GetMapping("/monoSampleRest") public Mono<String> exposeMono() { return Mono.just("Hello World"); } @GetMapping("/fluxSampleRest") public Flux<String> exposeFlux() { List<String> names = Arrays.asList("Anna", "John", "Lucy"); return Flux.fromIterable(names).map((str) -> str.toUpperCase() + "---"); } @GetMapping("/fluxJpaEmps") public Flux<Employee> exposeJpaEmps() { return Flux.fromIterable(employeeServiceImpl.findAllEmps()); } // Reactor Framework part below..... @GetMapping("/fluxEmpsList") public Flux<Employee> exposeFluxEmpsList() { return null; } @GetMapping(path = "/fluxAddEmp") public Flux<String> addMonoEmp(){ Employee newEmp = new Employee(); newEmp.setEmpid(56758); newEmp.setAge(43); newEmp.setBirthday(new Date(88, 10,10)); newEmp.setDeptid(362); newEmp.setEmail("[email protected]"); newEmp.setFirstname("John"); newEmp.setLastname("Lowell"); employeeServiceImpl.saveEmployeeRec(newEmp); Flux<String> status = Flux.just("OK"); return status; } @PostMapping(path = "/fluxSelectEmps", consumes = MediaType.APPLICATION_JSON_VALUE) public List<Employee> exposeFluxEmps(@RequestBody Flux<Integer> ids){ return null; } @PostMapping(path = "/fluxSelectById", consumes = MediaType.APPLICATION_JSON_VALUE) public List<Employee> exposeEmpById(@RequestBody Integer id){ return null; } }
28.084337
85
0.751609
553899de4781224751eb9364812cf6deedc9d051
2,328
package com.dxj.common.constant; /** * 常量 * * @author Sinkiang */ public interface CommonConstant { /** * 用户默认头像 */ String USER_DEFAULT_AVATAR = "https://i.loli.net/2019/04/28/5cc5a71a6e3b6.png"; /** * 用户正常状态 */ Integer USER_STATUS_NORMAL = 0; /** * 用户禁用状态 */ Integer USER_STATUS_LOCK = -1; /** * 普通用户 */ Integer USER_TYPE_NORMAL = 0; /** * 管理员 */ Integer USER_TYPE_ADMIN = 1; /** * 全部数据权限 */ Integer DATA_TYPE_ALL = 0; /** * 自定义数据权限 */ Integer DATA_TYPE_CUSTOM = 1; /** * 正常状态 */ Integer STATUS_NORMAL = 0; /** * 禁用状态 */ Integer STATUS_DISABLE = -1; /** * 删除标志 */ Integer DEL_FLAG = 1; /** * 限流标识 */ String LIMIT_ALL = "SKADMIN_LIMIT_ALL"; /** * 顶部菜单类型权限 */ Integer PERMISSION_NAV = -1; /** * 页面类型权限 */ Integer PERMISSION_PAGE = 0; /** * 操作类型权限 */ Integer PERMISSION_OPERATION = 1; /** * 1级菜单父id */ String PARENT_ID = "0"; /** * 0级菜单 */ Integer LEVEL_ZERO = 0; /** * 1级菜单 */ Integer LEVEL_ONE = 1; /** * 2级菜单 */ Integer LEVEL_TWO = 2; /** * 3级菜单 */ Integer LEVEL_THREE = 3; /** * 消息发送范围 */ Integer MESSAGE_RANGE_ALL = 0; /** * 未读 */ Integer MESSAGE_STATUS_UNREAD = 0; /** * 已读 */ Integer MESSAGE_STATUS_READ = 1; /** * github登录 */ Integer SOCIAL_TYPE_GITHUB = 0; /** * qq登录 */ Integer SOCIAL_TYPE_QQ = 1; /** * 微博登录 */ Integer SOCIAL_TYPE_WEIBO = 2; /** * 短信验证码key前缀 */ String PRE_SMS = "SKADMIN_PRE_SMS:"; /** * 邮件验证码key前缀 */ String PRE_EMAIL = "SKADMIN_PRE_EMAIL:"; /** * 本地文件存储 */ Integer OSS_LOCAL = 0; /** * 七牛云OSS存储 */ Integer OSS_QINIU = 1; /** * 阿里云OSS存储 */ Integer OSS_ALI = 2; /** * 腾讯云COS存储 */ Integer OSS_TENCENT = 3; /** * MINIO存储 */ Integer OSS_MINIO = 4; /** * 部门负责人类型 主负责人 */ Integer HEADER_TYPE_MAIN = 0; /** * 部门负责人类型 副负责人 */ Integer HEADER_TYPE_VICE = 1; }
12.933333
83
0.462199
2611855b3fb657b895a4359d0067c806c6fda23c
12,324
/* * Copyright 2004-2009 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.struts.config; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.seasar.framework.util.StringUtil; import org.seasar.struts.enums.SaveType; import org.seasar.struts.exception.IllegalInputPatternRuntimeException; import org.seasar.struts.exception.IllegalUrlPatternRuntimeException; import org.seasar.struts.util.URLEncoderUtil; /** * Actionの実行メソッド用の設定です。 * * @author higa * */ public class S2ExecuteConfig implements Serializable { private static final long serialVersionUID = 1L; private static final String METHOD_NAME = "SAStruts.method"; /** * メソッドです。 */ protected Method method; /** * 検証メソッドです。 */ protected List<S2ValidationConfig> validationConfigs; /** * エラーメッセージの保存場所です。 */ protected SaveType saveErrors = SaveType.REQUEST; /** * 検証エラー時の遷移先です。 */ protected String input; /** * 検証エラー時遷移先のパラメータ名のリストです。 */ protected List<String> inputParamNames = new ArrayList<String>(); /** * URLのパターンです。 */ protected String urlPattern; /** * URLのパターンのコンパイル結果です。 */ protected Pattern urlPatternRegexp; /** * URLパターンが{id}のように全選択かどうかです。 */ protected boolean urlPatternAllSelected = false; /** * URLのパラメータ名のリストです。 */ protected List<String> urlParamNames = new ArrayList<String>(); /** * ロールの配列です。 */ protected String[] roles; /** * trueの場合、バリデータや検証メソッドで検証エラーがあるとそこで検証がとまります。 * falseの場合、検証エラーがあっても後続の検証を続行します。 どちらの場合も検証エラーがあると実行メソッドは呼び出されません。 */ protected boolean stopOnValidationError = true; /** * 実行メソッドの正常終了時にセッションからアクションフォームを削除するかどうかです。 trueの場合、アクションフォームを削除します。 */ protected boolean removeActionForm = false; /** * リセットメソッドです。 */ protected Method resetMethod; /** * 正常終了時に遷移先にリダイレクトするかどうかです。 */ protected boolean redirect = false; /** * インスタンスを構築します。 * * @param method * メソッド * @param validator * バリデータを呼び出すかどうか * @param validateMethod * 検証メソッド * @param saveErrors * エラーメッセージの保存場所 * @param input * 検証エラー時の遷移先 * @param urlPattern * URLのパターン */ public S2ExecuteConfig() { } /** * メソッドを返します。 * * @return メソッド */ public Method getMethod() { return method; } /** * メソッドを設定します。 * * @param method * メソッド */ public void setMethod(Method method) { this.method = method; setUrlPattern(method.getName()); } /** * バリデータを呼び出すかどうかを返します。 * * @return バリデータを呼び出すかどうか */ public boolean isValidator() { if (validationConfigs != null) { for (S2ValidationConfig cfg : validationConfigs) { if (cfg.isValidator()) { return true; } } } return false; } /** * 検証設定のリストを返します。 * * @return 検証設定のリスト */ public List<S2ValidationConfig> getValidationConfigs() { return validationConfigs; } /** * 検証設定のリストを設定します。 * * @param validationConfigs * 検証設定のリスト */ public void setValidationConfigs(List<S2ValidationConfig> validationConfigs) { this.validationConfigs = validationConfigs; } /** * エラーメッセージの保存場所を返します。 * * @return エラーメッセージの保存場所 */ public SaveType getSaveErrors() { return saveErrors; } /** * エラーメッセージの保存場所を設定します。 * * @param saveErrors * エラーメッセージの保存場所 */ public void setSaveErrors(SaveType saveErrors) { this.saveErrors = saveErrors; } /** * 検証エラー時の遷移先を返します。 * * @return 検証エラー時の遷移先 */ public String getInput() { return input; } /** * 検証エラー時の遷移先を設定します。 * * @param input * 検証エラー時の遷移先 */ public void setInput(String input) { this.input = input; if (StringUtil.isEmpty(input)) { return; } char[] chars = input.toCharArray(); int length = chars.length; int index = -1; for (int i = 0; i < length; i++) { if (chars[i] == '{') { index = i; } else if (chars[i] == '}') { if (index >= 0) { inputParamNames.add(input.substring(index + 1, i)); index = -1; } else { throw new IllegalInputPatternRuntimeException(input); } } } if (index >= 0) { throw new IllegalInputPatternRuntimeException(input); } } /** * パラメータを解決した検証エラー時の遷移先を返します。 * * @param actionMapping * アクションマッピング * * @return 検証エラー時の遷移先 */ public String resolveInput(S2ActionMapping actionMapping) { String s = input; for (String name : inputParamNames) { s = s.replace("{" + name + "}", actionMapping .getPropertyAsString(name)); } return s; } /** * URLのパターンを返します。 * * @return URLのパターン */ public String getUrlPattern() { return urlPattern; } /** * URLのパターンを設定します。 * * @param urlPattern * URLのパターン */ public void setUrlPattern(String urlPattern) { if (StringUtil.isEmpty(urlPattern)) { return; } this.urlPattern = urlPattern; StringBuilder sb = new StringBuilder(50); char[] chars = urlPattern.toCharArray(); int length = chars.length; int index = -1; for (int i = 0; i < length; i++) { if (chars[i] == '{') { index = i; } else if (chars[i] == '}') { if (index >= 0) { sb.append("([^/]+)"); urlParamNames.add(urlPattern.substring(index + 1, i)); index = -1; } else { throw new IllegalUrlPatternRuntimeException(urlPattern); } } else if (index < 0) { sb.append(chars[i]); } } if (index >= 0) { throw new IllegalUrlPatternRuntimeException(urlPattern); } String pattern = sb.toString(); urlPatternAllSelected = pattern.equals("([^/]+)"); urlPatternRegexp = Pattern.compile("^" + pattern + "$"); } /** * URLパターンが{id}のように全選択かどうかを返します。 * * @return URLパターンが{id}のように全選択かどうか */ public boolean isUrlPatternAllSelected() { return urlPatternAllSelected; } /** * ロールの配列を返します。 * * @return ロールの配列 */ public String[] getRoles() { return roles; } /** * ロールの配列を設定します。 * * @param roles * ロールの配列 */ public void setRoles(String[] roles) { this.roles = roles; } /** * 検証エラーがあった場合にそこで検証をやめるかどうかを返します。 * * @return 検証エラーがあった場合にそこで検証をやめるかどうか */ public boolean isStopOnValidationError() { return stopOnValidationError; } /** * 検証エラーがあった場合にそこで検証をやめるかどうかを設定します。 * * @param stopOnValidationError * 検証エラーがあった場合にそこで検証をやめるかどうか */ public void setStopOnValidationError(boolean stopOnValidationError) { this.stopOnValidationError = stopOnValidationError; } /** * 実行メソッドの正常終了時にセッションからアクションフォームを削除するかどうか返します。 * * @return 実行メソッドの正常終了時にセッションからアクションフォームを削除するかどうか */ public boolean isRemoveActionForm() { return removeActionForm; } /** * 実行メソッドの正常終了時にセッションからアクションフォームを削除するかどうかを設定します。 * * @param removeActionForm * 実行メソッドの正常終了時にセッションからアクションフォームを削除するかどうか */ public void setRemoveActionForm(boolean removeActionForm) { this.removeActionForm = removeActionForm; } /** * リセットメソッドを返します。 * * @return リセットメソッド */ public Method getResetMethod() { return resetMethod; } /** * リセットメソッドを設定します。 * * @param resetMethod * リセットメソッド */ public void setResetMethod(Method resetMethod) { this.resetMethod = resetMethod; } /** * 正常終了時に遷移先にリダイレクトするかどうかを返します。 * * @return 正常終了時に遷移先にリダイレクトするかどうか */ public boolean isRedirect() { return redirect; } /** * 正常終了時に遷移先にリダイレクトするかどうかを設定します。 * * @param redirect * 正常終了時に遷移先にリダイレクトするかどうか */ public void setRedirect(boolean redirect) { this.redirect = redirect; } /** * 実行メソッドの対象かどうかを返します。 * * @param paramPath * パラメータ用のパス * @return 実行メソッドの対象かどうか */ public boolean isTarget(String paramPath) { if (!StringUtil.isEmpty(paramPath)) { return urlPatternRegexp.matcher(paramPath).find(); } return "index".equals(urlPattern); } /** * 実行メソッドの対象かどうかを返します。 * * @param request * リクエスト * @return リクエストが実行メソッドの対象かどうか */ public boolean isTarget(HttpServletRequest request) { String[] methodNames = request.getParameterValues(METHOD_NAME); if (methodNames != null && methodNames.length > 0) { return methodNames[0].equals(method.getName()); } return !StringUtil.isEmpty(request.getParameter(method.getName())) || !StringUtil.isEmpty(request.getParameter(method.getName() + ".x")) || !StringUtil.isEmpty(request.getParameter(method.getName() + ".y")); } /** * クエリストリングを返します。 * * @param paramPath * パラメータ用のパス * @return クエリストリング */ public String getQueryString(String paramPath) { String urlEncodedMethodName = URLEncoderUtil.encode(method.getName()); if (StringUtil.isEmpty(paramPath)) { return "?" + METHOD_NAME + "=" + urlEncodedMethodName; } Matcher matcher = urlPatternRegexp.matcher(paramPath); if (!matcher.find()) { return "?" + METHOD_NAME + "=" + urlEncodedMethodName; } if (urlParamNames.size() == 0) { return "?" + METHOD_NAME + "=" + urlEncodedMethodName; } StringBuilder sb = new StringBuilder(50); sb.append("?"); int index = 1; for (String name : urlParamNames) { if (index != 1) { sb.append("&"); } sb.append(URLEncoderUtil.encode(name)).append("=").append( URLEncoderUtil.encode(matcher.group(index++))); } sb.append("&").append(METHOD_NAME).append("=").append( urlEncodedMethodName); return sb.toString(); } }
25.515528
83
0.533187
0ea1dbdd69890b6f3048b51746ab25ca12eeddf8
284
/** * */ package author.view.util.undo; import game_data.Sprite; /** * @author Cleveland Thompson V (ct168) * */ public interface IRevertManagerInternal { public void addHistory(GameChangeEvent gameChangeEvent); public void addFuture(GameChangeEvent gameChangeEvent); }
14.947368
57
0.742958