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
d2cdeeeb2f5d36ee75b4a451cebb5ffdb30df368
1,740
package com.kangec.vcms.utils.logging; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; /** * @author kangec */ @Component public class LogManager { private ThreadPoolTaskExecutor executor; /** * 异步执行日志处理操作 */ public void submit(Runnable task) { executor.execute(task); } /** * 比较两个对象内的属性是否改变,记录他们前后变化的值。 * * @param oldObj 旧对象 * @param newObj 新对象 * @return 发生变化的字段 */ public static Map<String, String> diffObj(Object oldObj, Object newObj) { HashMap<String, String> diffData = new HashMap<>(); try { Class<?> oldClazz = oldObj.getClass(); Class<?> newClazz = newObj.getClass(); if (oldClazz.equals(newClazz)) { Field[] oldClazzDeclaredFields = oldClazz.getDeclaredFields(); for (Field field : oldClazzDeclaredFields) { field.setAccessible(true); Object oldVal = field.get(oldObj); Object newVal = field.get(newObj); if ((oldVal == null && newVal != null) || (oldVal != null && oldVal.equals(newVal))) { diffData.put(field.getName(), "from " + oldVal + " to " + newVal); } } } } catch (IllegalAccessException e) { e.printStackTrace(); } return diffData; } @Autowired public void setExecutor(ThreadPoolTaskExecutor executor) { this.executor = executor; } }
29.491525
106
0.59023
b1602077e976bbf5c5e3a6b96106d28a070bf0aa
2,364
/* * Copyright 2020 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.processors.cache.persistence.pagemem; import java.nio.ByteBuffer; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.pagemem.PageMemory; import org.apache.ignite.internal.pagemem.store.PageStore; /** */ public interface PageReadWriteManager { /** * Reads a page for the given cache ID. Cache ID may be {@code 0} if the page is a meta page. * * @param grpId Cache group ID. * @param pageId PageID to read. * @param pageBuf Page buffer to write to. * @param keepCrc Keep CRC flag. * @throws IgniteCheckedException If failed to read the page. */ public void read(int grpId, long pageId, ByteBuffer pageBuf, boolean keepCrc) throws IgniteCheckedException; /** * Writes the page for the given cache ID. Cache ID may be {@code 0} if the page is a meta page. * * @param grpId Cache group ID. * @param pageId Page ID. * @param pageBuf Page buffer to write. * @throws IgniteCheckedException If failed to write page. */ public PageStore write(int grpId, long pageId, ByteBuffer pageBuf, int tag, boolean calculateCrc) throws IgniteCheckedException; /** * Allocates a page for the given page space. * * @param grpId Cache group ID. * @param partId Partition ID. Used only if {@code flags} is equal to {@link PageMemory#FLAG_DATA}. * @param flags Page allocation flags. * @return Allocated page ID. * @throws IgniteCheckedException If IO exception occurred while allocating a page ID. */ public long allocatePage(int grpId, int partId, byte flags) throws IgniteCheckedException; }
40.758621
132
0.719543
2b3aa0f8a8f3c2c1d88225e6b721109df34c17da
857
package scar; import org.spongycastle.crypto.prng.*; import org.spongycastle.crypto.digests.SHA256Digest; import org.spongycastle.crypto.macs.HMac; //Used to generate random bytes of various lengths based on keys as seed public class RndKeyGen { SP800SecureRandom rnd; public RndKeyGen() { SP800SecureRandomBuilder rndbuild = new SP800SecureRandomBuilder(); rnd = rndbuild.buildHMAC(new HMac(new SHA256Digest()), null, false); } public byte[] genBytes(int bytes) { byte[] ret = new byte[bytes]; rnd.nextBytes(ret); return ret; } public byte nextByte(int max) { byte n = genBytes(1)[0]; return (byte)(n % max); } public int nextInt(int max) { return rnd.nextInt(max); } public void seed(byte[] seed) { rnd.setSeed(seed); } public void seed(long seed) { rnd.setSeed(seed); } }
21.974359
72
0.677946
18e5e301d3a4b3a58667bce7298fce96e986435c
1,526
package com.litesuits.http.request; import android.graphics.Bitmap; import com.litesuits.http.parser.DataParser; import com.litesuits.http.parser.impl.BitmapParser; import com.litesuits.http.request.param.HttpParamModel; import com.litesuits.http.request.param.NonHttpParam; import java.io.File; /** * @author MaTianyu * @date 2015-04-18 */ public class BitmapRequest extends AbstractRequest<Bitmap> { @NonHttpParam protected File saveToFile; public BitmapRequest(HttpParamModel model) { super(model); } public BitmapRequest(HttpParamModel model, File saveToFile) { super(model); this.saveToFile = saveToFile; } public BitmapRequest(HttpParamModel model, String saveToPath) { super(model); setFileSavePath(saveToPath); } public BitmapRequest(String url) { super(url); } public BitmapRequest(String url, File saveToFile) { super(url); this.saveToFile = saveToFile; } public BitmapRequest(String url, String saveToPath) { super(url); setFileSavePath(saveToPath); } public BitmapRequest setFileSavePath(String savaToPath) { if (savaToPath != null) { saveToFile = new File(savaToPath); } return this; } public File getCachedFile() { return saveToFile != null ? saveToFile : super.getCachedFile(); } @Override public DataParser<Bitmap> createDataParser() { return new BitmapParser(saveToFile); } }
23.476923
71
0.67038
549e6ef9bd8513c5850067d82723dd61dab56fee
3,728
package org.docksidestage.dockside.dbflute.whitebox.entity; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import org.dbflute.util.DfTypeUtil; import org.docksidestage.dockside.dbflute.bsentity.customize.dbmeta.ForcedTypeDbm; import org.docksidestage.dockside.dbflute.bsentity.customize.dbmeta.SimpleVendorCheckDbm; import org.docksidestage.dockside.dbflute.exentity.customize.ForcedType; import org.docksidestage.dockside.dbflute.exentity.customize.SimpleMember; import org.docksidestage.dockside.dbflute.exentity.customize.SimpleVendorCheck; import org.docksidestage.dockside.unit.UnitContainerTestCase; /** * @author jflute * @since 0.9.5 (2009/04/08 Wednesday) */ public class WxCustomizeEntityTest extends UnitContainerTestCase { // =================================================================================== // Attribute // ========= // =================================================================================== // Byte Type // ========= public void test_BLOB_equals_CustomizeEntity_nonPrimaryKey_sameByte() { // ## Arrange ## assertFalse(SimpleVendorCheckDbm.getInstance().hasPrimaryKey()); SimpleVendorCheck vendorCheck = new SimpleVendorCheck(); vendorCheck.setTypeOfText("FOO"); try { vendorCheck.setTypeOfBlob("BAR".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } SimpleVendorCheck other = new SimpleVendorCheck(); other.setTypeOfText("FOO"); try { other.setTypeOfBlob("BAR".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } // ## Act ## boolean actual = vendorCheck.equals(other); // expects no exception // ## Assert ## log("actual=" + actual); assertTrue(actual); } // =================================================================================== // Forced Type // =========== public void test_Sql2Entity_forcedType() { // ## Arrange ## ForcedType forcedType = new ForcedType(); // ## Act ## BigInteger maxMemberId = forcedType.getMaxMemberId(); // ## Assert ## assertNull(maxMemberId); assertEquals(BigInteger.class, ForcedTypeDbm.getInstance().columnMaxMemberId().getObjectNativeType()); } // =================================================================================== // Serializable // ============ public void test_serializable_basic() { // ## Arrange ## SimpleMember member = new SimpleMember(); member.setMemberName("Stojkovic"); member.setBirthdate(currentLocalDate()); // ## Act ## byte[] binary = DfTypeUtil.toBinary(member); Serializable serializable = DfTypeUtil.toSerializable(binary); // ## Assert ## log(serializable); assertNotNull(serializable); assertEquals(member.toString(), serializable.toString()); } }
42.363636
110
0.492221
047c651d2dcf702cd51d3c380093658d96be1bce
2,970
/* */ package org.springframework.context.config; /* */ /* */ import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; /* */ import org.springframework.beans.factory.support.BeanDefinitionBuilder; /* */ import org.springframework.beans.factory.xml.ParserContext; /* */ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /* */ import org.springframework.util.StringUtils; /* */ import org.w3c.dom.Element; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ class PropertyPlaceholderBeanDefinitionParser /* */ extends AbstractPropertyLoadingBeanDefinitionParser /* */ { /* */ private static final String SYSTEM_PROPERTIES_MODE_ATTRIBUTE = "system-properties-mode"; /* */ private static final String SYSTEM_PROPERTIES_MODE_DEFAULT = "ENVIRONMENT"; /* */ /* */ protected Class<?> getBeanClass(Element element) { /* 48 */ if ("ENVIRONMENT".equals(element.getAttribute("system-properties-mode"))) { /* 49 */ return PropertySourcesPlaceholderConfigurer.class; /* */ } /* */ /* */ /* */ /* 54 */ return PropertyPlaceholderConfigurer.class; /* */ } /* */ /* */ /* */ protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { /* 59 */ super.doParse(element, parserContext, builder); /* */ /* 61 */ builder.addPropertyValue("ignoreUnresolvablePlaceholders", /* 62 */ Boolean.valueOf(element.getAttribute("ignore-unresolvable"))); /* */ /* 64 */ String systemPropertiesModeName = element.getAttribute("system-properties-mode"); /* 65 */ if (StringUtils.hasLength(systemPropertiesModeName) && /* 66 */ !systemPropertiesModeName.equals("ENVIRONMENT")) { /* 67 */ builder.addPropertyValue("systemPropertiesModeName", "SYSTEM_PROPERTIES_MODE_" + systemPropertiesModeName); /* */ } /* */ /* 70 */ if (element.hasAttribute("value-separator")) { /* 71 */ builder.addPropertyValue("valueSeparator", element.getAttribute("value-separator")); /* */ } /* 73 */ if (element.hasAttribute("trim-values")) { /* 74 */ builder.addPropertyValue("trimValues", element.getAttribute("trim-values")); /* */ } /* 76 */ if (element.hasAttribute("null-value")) /* 77 */ builder.addPropertyValue("nullValue", element.getAttribute("null-value")); /* */ } /* */ } /* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/context/config/PropertyPlaceholderBeanDefinitionParser.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
34.941176
166
0.588552
4fa20fff576578b9599773444c464018532c0a7f
647
/** * 严肃声明: * 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究! * 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护! * 可正常分享和学习源码,不得用于违法犯罪活动,违者必究! * Copyright (c) 2020 十三 all rights reserved. * 版权所有,侵权必究! */ package ltd.newbee.mall.dao; import ltd.newbee.mall.entity.MallUserToken; public interface NewBeeMallUserTokenMapper { int deleteByPrimaryKey(Long userId); int insert(MallUserToken record); int insertSelective(MallUserToken record); MallUserToken selectByPrimaryKey(Long userId); MallUserToken selectByToken(String token); int updateByPrimaryKeySelective(MallUserToken record); int updateByPrimaryKey(MallUserToken record); }
23.962963
58
0.771252
6685658114a1c0dfc1fc37fdc65f48cdeb61f1ba
275
package com.klaus3d3.xDripwatchface.resource; import com.ingenic.iwds.slpt.view.digital.SlptTimeView; public class SlptAnalogAmPmView extends SlptTimeView { public SlptAnalogAmPmView() { } protected short initType() { return SVIEW_ANALOG_AM_PM; } }
22.916667
55
0.745455
ce3101a9699b9e1e210cabaafc12a99c64e7f2a4
6,461
/* * The MIT License * * Copyright 2013-2015 "Osric Wilkinson" <[email protected]>. * Copyright 2015 Linagora * * 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 com.fluffypeople.managesieve; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Store the response from the Manage Sieve server. <p> Generally this will be * either OK (indicating success), NO (indicating failure) or BYE (indicating * the server is closing the connection). Some responses include a <code>Code</code> * giving more detail (which may have a <code>subCode()</code>. * * @author "Osric Wilkinson" &lt;[email protected]&gt; * @author Linagora */ public class ManageSieveResponse { private static final Logger log = LoggerFactory.getLogger(ManageSieveResponse.class); /** * Type of the response. */ public enum Type { OK, NO, BYE } /** * Primary response code. */ public enum Code { AUTH_TOO_WEAK(false), ENCRYPT_NEEDED(false), SASL(true), REFERRAL(true), TRANSITION_NEEDED(false), TRYLATER(false), ACTIVE(false), NONEXISTENT(false), ALREADYEXITS(false), WARNINGS(false), TAG(true), QUOTA(false), extension(false); private final boolean hasParam; Code(boolean hasParam) { this.hasParam = hasParam; } public boolean hasParam() { return hasParam; } public static Code fromString(final String raw) { log.debug("Constructing code from string: {}", raw); String tweaked = raw.replaceAll("-", "_"); log.debug("Tweaked version is {}", tweaked); try { return Code.valueOf(tweaked.toUpperCase()); } catch (IllegalArgumentException ex) { return Code.extension; } } } private Type type; private Code code; private String[] subCodes; private String message; private String param; /** * Package only constructor. Users are not expected to make instances of * this class. */ ManageSieveResponse() { } /** * Is this an OK response. Shorthand for (this.getType() == * SieveResponse.Type.OK) * * @return true if is an OK response, false otherwise */ public boolean isOk() { return type == Type.OK; } /** * Is this a NO response. Shorthand for (this.getType() == * SieveResponse.Type.NO) * * @return true if is an OK response, false otherwise */ public boolean isNo() { return type == Type.NO; } /** * Is this a BYE response. Shorthand for (this.getType() == * SieveResponse.Type.BYE) * * @return true if is an OK response, false otherwise */ public boolean isBye() { return type == Type.BYE; } public Type getType() { return type; } public Code getCode() { return code; } /** * Get the list of any sub-codes that makeup this response. May be null. If * this is not null the first element will be the string representation of * {@link #getCode()}. * * @return Array of String sub-codes. May be null. */ public String[] getSubCodes() { return Arrays.copyOf(subCodes, subCodes.length); } /** * Return any "Human readable" message from the response. */ public String getMessage() { return message; } /** * Parse a string to set the type of this response. * * @param type String potential type, should be one of "OK", "NO", "BYE". * @throws ParseException if the response type is not recognised. */ void setType(final String type) throws ParseException { try { this.type = Type.valueOf(type.toUpperCase()); } catch (IllegalArgumentException ex) { throw new ParseException("Invalid response type: " + type); } } /** * Parse a string to set the code of this response. Sets both {@link #code} * and {@link #subCodes}. * * @param raw */ void setCode(final String raw) { log.debug("Raw code: {}", raw); subCodes = raw.split("/"); this.code = Code.fromString(subCodes[0]); } /** * Set any parameters associated with the code * * @param param String to use */ void setParam(final String param) { this.param = param; } public String getParam() { return param; } /** * Set the "Human readable" message. This message SHOULD be shown to the * user. */ void setMessage(String message) { this.message = message; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(type.toString()); if (code != null) { result.append(" (").append(code.toString()).append(")"); } if (message != null) { result.append(" \"").append(message).append("\""); } return result.toString(); } }
28.973094
90
0.588763
2917245d59adabf7a08d37e6dc1931dd8d0579ed
552
package factory; public class Calculator { public static double calculate(String operation , double o1,double o2){ switch (operation){ case "add": return o1+o2; case "sub": return o1-o2; case "multiply": return o1*o2; case "divide": return o1/o2; } throw new IllegalArgumentException("..."); } public static void main(String[] args) { double answer = Calculator.calculate("add", 1, 2); } }
25.090909
75
0.51087
3402d2126c25da72c38b4eea9b11802aa7d44d70
2,291
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.memory.api.binarystorage.sorted; import com.hazelcast.jet.memory.spi.binarystorage.BinaryComparator; import com.hazelcast.jet.memory.api.binarystorage.BinaryKeyValueStorage; import com.hazelcast.jet.memory.spi.binarystorage.sorted.OrderingDirection; import com.hazelcast.jet.memory.api.binarystorage.iterator.BinarySlotSortedIterator; /** * Represents API for sorted binary key-value storage */ public interface BinaryKeyValueSortedStorage<T> extends BinaryKeyValueStorage<T> { /** * @param direction - * ASC - 1; * DESC - 0; * @return address of the first slot address in accordance with direction; */ long first(OrderingDirection direction); /** * @param slotAddress - slot address to start from; * @param direction - * ASC - 1; * DESC - 0; * @return next slot address in accordance with direction; */ long getNext(long slotAddress, OrderingDirection direction); /** * Sort storage with corresponding direction; * * @param direction ASC - 1; * DESC - 0; * @return iterator with iterating direction corresponding to direction; */ BinarySlotSortedIterator slotIterator(OrderingDirection direction); /** * Set default comparator to be used; * * @param comparator - comparator to be used; */ void setComparator(BinaryComparator comparator); /** * Initialize current object as flight-weight object under sorted storage; */ void setSorted(OrderingDirection direction); }
34.19403
84
0.678306
f395adcd05d942d90c78b3c345c9b976ba5cadc4
11,940
package com.pushtorefresh.storio3.sqlite.operations.put; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.pushtorefresh.storio3.test.ToStringChecker; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.Collections; import java.util.HashSet; import java.util.Set; import nl.jqno.equalsverifier.EqualsVerifier; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.startsWith; public class PutResultTest { @Rule public ExpectedException expectedException = ExpectedException.none(); private void checkCreateInsertResult( long insertedId, @NonNull Set<String> affectedTables, @Nullable Set<?> affectedTags, @NonNull PutResult insertResult ) { assertThat(insertResult.wasInserted()).isTrue(); assertThat(insertResult.wasUpdated()).isFalse(); assertThat(insertResult.wasNotInserted()).isFalse(); assertThat(insertResult.wasNotUpdated()).isTrue(); //noinspection ConstantConditions assertThat((long) insertResult.insertedId()).isEqualTo(insertedId); assertThat(insertResult.affectedTables()).isEqualTo(affectedTables); assertThat(insertResult.affectedTags()).isEqualTo(affectedTags); assertThat(insertResult.numberOfRowsUpdated()).isNull(); } @Test public void createInsertResultWithSeveralAffectedTables() { final int insertedId = 10; final Set<String> affectedTables = new HashSet<String>(asList("table1", "table2", "table3")); checkCreateInsertResult( insertedId, affectedTables, Collections.<String>emptySet(), PutResult.newInsertResult(insertedId, affectedTables) ); } @Test public void createInsertResultWithSeveralAffectedTags() { final int insertedId = 10; final Set<String> affectedTables = new HashSet<String>(asList("table1", "table2", "table3")); final Set<String> affectedTags = new HashSet<String>(asList("tag1", "tag2", "tag3")); checkCreateInsertResult( insertedId, affectedTables, affectedTags, PutResult.newInsertResult(insertedId, affectedTables, affectedTags) ); } @Test public void createInsertResultWithOneAffectedTables() { final int insertedId = 10; final String affectedTable = "table"; checkCreateInsertResult( insertedId, singleton(affectedTable), Collections.<String>emptySet(), PutResult.newInsertResult(insertedId, affectedTable) ); } @Test public void createInsertResultWithOneAffectedTag() { final int insertedId = 10; final String affectedTable = "table"; final String affectedTag = "tag"; checkCreateInsertResult( insertedId, singleton(affectedTable), singleton(affectedTag), PutResult.newInsertResult(insertedId, affectedTable, affectedTag) ); } @Test public void shouldNotCreateInsertResultWithNullAffectedTables() { expectedException.expect(NullPointerException.class); expectedException.expectMessage(equalTo("affectedTables must not be null")); expectedException.expectCause(nullValue(Throwable.class)); //noinspection ConstantConditions PutResult.newInsertResult(1, (Set<String>) null); } @Test public void shouldNotCreateInsertResultWithEmptyAffectedTables() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(equalTo("affectedTables must contain at least one element")); expectedException.expectCause(nullValue(Throwable.class)); PutResult.newInsertResult(1, new HashSet<String>()); } @Test public void shouldNotCreateInsertResultWithNullAffectedTable() { expectedException.expect(NullPointerException.class); expectedException.expectMessage(equalTo("Please specify affected table")); expectedException.expectCause(nullValue(Throwable.class)); //noinspection ConstantConditions PutResult.newInsertResult(1, (String) null); } @Test public void shouldNotCreateInsertResultWithEmptyAffectedTable() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage(startsWith("affectedTable must not be null or empty, affectedTables = ")); expectedException.expectCause(nullValue(Throwable.class)); PutResult.newInsertResult(1, ""); } @Test public void shouldNotCreateInsertResultWithNullAffectedTag() { expectedException.expect(NullPointerException.class); expectedException.expectMessage(startsWith("affectedTag must not be null or empty, affectedTags = ")); expectedException.expectCause(nullValue(Throwable.class)); //noinspection ConstantConditions PutResult.newInsertResult(1, "table", (String) null); } @Test public void shouldNotCreateInsertResultWithEmptyAffectedTag() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage(startsWith("affectedTag must not be null or empty, affectedTags = ")); expectedException.expectCause(nullValue(Throwable.class)); PutResult.newInsertResult(1, "table", ""); } private void checkCreateUpdateResult( int numberOfRowsUpdated, @NonNull Set<String> affectedTables, @Nullable Set<String> affectedTags, @NonNull PutResult updateResult ) { assertThat(updateResult.wasUpdated()).isTrue(); assertThat(updateResult.wasInserted()).isFalse(); assertThat(updateResult.wasNotUpdated()).isFalse(); assertThat(updateResult.wasNotInserted()).isTrue(); //noinspection ConstantConditions assertThat((int) updateResult.numberOfRowsUpdated()).isEqualTo(numberOfRowsUpdated); assertThat(updateResult.affectedTables()).isEqualTo(affectedTables); assertThat(updateResult.affectedTags()).isEqualTo(affectedTags); assertThat(updateResult.insertedId()).isNull(); } @Test public void createUpdateResultWithSeveralAffectedTables() { final int numberOfRowsUpdated = 10; final Set<String> affectedTables = new HashSet<String>(asList("table1", "table2", "table3")); checkCreateUpdateResult( numberOfRowsUpdated, affectedTables, Collections.<String>emptySet(), PutResult.newUpdateResult(numberOfRowsUpdated, affectedTables) ); } @Test public void createUpdateResultWithSeveralAffectedTags() { final int numberOfRowsUpdated = 10; final Set<String> affectedTables = new HashSet<String>(asList("table1", "table2", "table3")); final Set<String> affectedTags = new HashSet<String>(asList("tag1", "tag2", "tag3")); checkCreateUpdateResult( numberOfRowsUpdated, affectedTables, affectedTags, PutResult.newUpdateResult(numberOfRowsUpdated, affectedTables, affectedTags) ); } @Test public void createUpdateResultWithOneAffectedTable() { final int numberOfRowsUpdated = 10; final String affectedTable = "table"; checkCreateUpdateResult( numberOfRowsUpdated, singleton(affectedTable), Collections.<String>emptySet(), PutResult.newUpdateResult(numberOfRowsUpdated, affectedTable) ); } @Test public void createUpdateResultWithOneAffectedTag() { final int numberOfRowsUpdated = 10; final String affectedTable = "table"; final String affectedTag = "tag"; checkCreateUpdateResult( numberOfRowsUpdated, singleton(affectedTable), singleton(affectedTag), PutResult.newUpdateResult(numberOfRowsUpdated, affectedTable, affectedTag) ); } @Test public void shouldAllowCreatingUpdateResultWith0RowsUpdated() { PutResult putResult = PutResult.newUpdateResult(0, "table"); assertThat(putResult.wasUpdated()).isFalse(); assertThat(putResult.wasInserted()).isFalse(); assertThat(putResult.numberOfRowsUpdated()).isEqualTo(Integer.valueOf(0)); } @Test public void shouldNotCreateUpdateResultWithNegativeNumberOfRowsUpdated() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(equalTo("Number of rows updated must be >= 0, but was: -1")); expectedException.expectCause(nullValue(Throwable.class)); PutResult.newUpdateResult(-1, "table"); } @Test public void shouldNotCreateUpdateResultWithNullAffectedTables() { expectedException.expect(NullPointerException.class); expectedException.expectMessage(equalTo("affectedTables must not be null")); expectedException.expectCause(nullValue(Throwable.class)); //noinspection ConstantConditions PutResult.newUpdateResult(1, (Set<String>) null); } @Test public void shouldNotCreateUpdateResultWithEmptyAffectedTables() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(equalTo("affectedTables must contain at least one element")); expectedException.expectCause(nullValue(Throwable.class)); PutResult.newUpdateResult(1, new HashSet<String>()); } @Test public void shouldNotCreateUpdateResultWithNullAffectedTable() { expectedException.expect(NullPointerException.class); expectedException.expectMessage(equalTo("Please specify affected table")); expectedException.expectCause(nullValue(Throwable.class)); //noinspection ConstantConditions PutResult.newUpdateResult(1, (String) null); } @Test public void shouldNotCreateUpdateResultWithEmptyAffectedTable() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage(startsWith("affectedTable must not be null or empty, affectedTables = ")); expectedException.expectCause(nullValue(Throwable.class)); PutResult.newUpdateResult(1, ""); } @Test public void shouldNotCreateUpdateResultWithNullAffectedTag() { expectedException.expect(NullPointerException.class); expectedException.expectMessage(startsWith("affectedTag must not be null or empty, affectedTags = ")); expectedException.expectCause(nullValue(Throwable.class)); //noinspection ConstantConditions PutResult.newUpdateResult(1, "tag", (String) null); } @Test public void shouldNotCreateUpdateResultWithEmptyAffectedTag() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage(startsWith("affectedTag must not be null or empty, affectedTags = ")); expectedException.expectCause(nullValue(Throwable.class)); PutResult.newUpdateResult(1, "table", ""); } @Test public void verifyEqualsAndHashCodeImplementation() { EqualsVerifier .forClass(PutResult.class) .allFieldsShouldBeUsed() .verify(); } @Test public void checkToStringImplementation() { ToStringChecker .forClass(PutResult.class) .check(); } }
36.738462
114
0.68727
8ff65aa289358bbe72ba154bfbbe9e90098c7229
446
package final2020_2021; import static java.util.Arrays.*; import java.util.*; import java.util.ArrayList; public class RadixSort { /** * Sorts the list of student IDs as defined in the description. * * @param studentIds - list of student IDs * @return sorted list of student IDs */ static List<String> sortStudentIds(List<String> studentIds) { return null; } }
22.3
71
0.609865
7b69416bcba7d05d320207f2d077290333b49eed
6,690
/* (*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Nomadic Development, Inc. <[email protected]> *) (* *) (* 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 com.tezos.ui.activity; import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.appcompat.widget.Toolbar; import android.util.DisplayMetrics; import android.util.Log; import android.view.Window; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.iid.FirebaseInstanceId; import com.tezos.core.models.CustomTheme; import com.tezos.ui.R; import net.glxn.qrgen.android.QRCode; public class PublicKeyHashActivity extends BaseSecureActivity { public static final String PKH_KEY = "pkh_key"; private String mPublicKeyHash; public static Intent getStartIntent(Context context, String publicKeyHash, Bundle themeBundle) { Intent starter = new Intent(context, PublicKeyHashActivity.class); starter.putExtra(CustomTheme.TAG, themeBundle); starter.putExtra(PKH_KEY, publicKeyHash); return starter; } public static void start(Activity activity, String publicKeyHash, CustomTheme theme) { Intent starter = getStartIntent(activity, publicKeyHash, theme.toBundle()); ActivityCompat.startActivityForResult(activity, starter, -1, null); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_public_key); Bundle themeBundle = getIntent().getBundleExtra(CustomTheme.TAG); CustomTheme theme = CustomTheme.fromBundle(themeBundle); initToolbar(theme); if (savedInstanceState == null) {} DisplayMetrics dm = getResources().getDisplayMetrics(); int width = dm.widthPixels / 2; mPublicKeyHash = getIntent().getStringExtra(PKH_KEY); Bitmap myBitmap = QRCode.from(mPublicKeyHash).withSize(width, width).bitmap(); ImageView myImage = findViewById(R.id.qr_code); myImage.setImageBitmap(myBitmap); LinearLayout mLinearLayout = findViewById(R.id.pkh_info_layout); mLinearLayout.setOnTouchListener((view, motionEvent) -> { view.performClick(); ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText(getString(R.string.copied_pkh), mPublicKeyHash); clipboard.setPrimaryClip(clip); Toast.makeText(PublicKeyHashActivity.this, getString(R.string.copied_your_pkh), Toast.LENGTH_SHORT).show(); return false; }); Button mShareButton = findViewById(R.id.shareButton); mShareButton.setOnClickListener(view -> { Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(Intent.EXTRA_TEXT, mPublicKeyHash); startActivity(Intent.createChooser(sharingIntent, getString(R.string.share_via))); }); String pkhash = getIntent().getStringExtra(PKH_KEY); TextView mPkhTextview = findViewById(R.id.pkh_textview); mPkhTextview.setText(pkhash); } @Override protected void onResume() { super.onResume(); } private void initToolbar(CustomTheme theme) { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setBackgroundColor(ContextCompat.getColor(this, theme.getColorPrimaryId())); //toolbar.setTitleTextColor(ContextCompat.getColor(this, theme.getTextColorPrimaryId())); Window window = getWindow(); window.setStatusBarColor(ContextCompat.getColor(this, theme.getColorPrimaryDarkId())); try { getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); } catch (Exception e) { Log.getStackTraceString(e); } ImageButton mCloseButton = findViewById(R.id.close_button); mCloseButton.setColorFilter((ContextCompat.getColor(this, theme.getTextColorPrimaryId()))); mCloseButton.setOnClickListener(v -> { //requests stop in onDestroy. finish(); }); TextView mTitleBar = findViewById(R.id.barTitle); mTitleBar.setTextColor(ContextCompat.getColor(this, theme.getTextColorPrimaryId())); } }
40.301205
119
0.634828
b99d28f958951f234d96103949c71cb1e7fd3d8c
216
package com.subho.wipro.pjp.tm03.ac.q1; public class KotMBank extends GeneralBank { public double getFixedDepositInterestRate() { return 6; } public double getSavingsInterestRate() { return 9; } }
14.4
46
0.717593
1ea4b443f2d25d22bfcd0ec65a8aa585821db9bd
1,493
package com.example.clipboard.client.repository.model; import org.springframework.context.ApplicationEvent; import java.util.Date; public class ClipboardContentEvent extends ApplicationEvent { private final String id; private final Integer type; private final Date version; public ClipboardContentEvent(String id, String account, ClipboardContentEventType type, Date version) { super(account); this.id = id; this.type = type.EVENT; this.version = version; } public String getId() { return id; } public Integer getType() { return type; } public Date getVersion() { return version; } @Override public String getSource() { return (String) super.getSource(); } @Override public String toString() { return "ClipboardContentEvent{" + "id='" + id + '\'' + ", type=" + type + ", version=" + version + ", source=" + source + '}'; } public static enum ClipboardContentEventType { CONTENT_CREATE_EVENT(0), CONTENT_UPDATE_EVENT(1), CONTENT_STAR_EVENT(2), CONTENT_UNSTAR_EVENT(3), CONTENT_DELETE_EVENT(4); public int EVENT; ClipboardContentEventType(int event) { this.EVENT = event; } } }
22.969231
64
0.54722
53b0def718986870fae7c653dc947178697632e0
3,315
package koopa.trees.antlr.dtd; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import koopa.grammars.generator.KGLexer; import koopa.grammars.generator.KGParser; import koopa.util.ASTFrame; import org.antlr.runtime.ANTLRReaderStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.tree.CommonTree; import org.antlr.runtime.tree.CommonTreeNodeStream; import org.antlr.stringtemplate.StringTemplateGroup; import org.antlr.stringtemplate.language.DefaultTemplateLexer; public class KGToDTD { private static final boolean SHOW_AST = false; public static void main(String[] args) throws IOException, RecognitionException { String name = args[0]; String path = args[1]; String outputPath = args[2]; if (!path.endsWith("/")) path += "/"; if (!outputPath.endsWith("/")) outputPath += "/"; CommonTree ast = getKoopaAST(path + name + ".kg"); if (ast != null) { generateDTD(ast, name, outputPath + name + ".dtd"); } } private static CommonTree getKoopaAST(String filename) throws FileNotFoundException, IOException, RecognitionException { System.out.println("Reading " + filename); Reader reader = new FileReader(filename); KGLexer lexer = new KGLexer(new ANTLRReaderStream(reader)); CommonTokenStream tokens = new CommonTokenStream(lexer); KGParser parser = new KGParser(tokens); KGParser.koopa_return koopa = parser.koopa(); CommonTree ast = (CommonTree) koopa.getTree(); if (SHOW_AST) { new ASTFrame("KG", ast).setVisible(true); } return ast; } public static void generateDTD(CommonTree ast, String name, String filename) throws RecognitionException, IOException { Reader templatesIn = new InputStreamReader(KGToDTD.class .getResourceAsStream("/koopa/trees/antlr/dtd/dtd.stg")); StringTemplateGroup templates = new StringTemplateGroup(templatesIn, DefaultTemplateLexer.class); CommonTreeNodeStream nodes = new CommonTreeNodeStream(ast); KGToDTDForSerializedANTLR walker = new KGToDTDForSerializedANTLR(nodes); walker.setTemplateLib(templates); String dtd = walker.koopa().toString(); dtd = simplify(dtd); System.out.println("Generating " + filename); FileWriter writer = new FileWriter(filename); writer.append(dtd); writer.append('\n'); writer.close(); } private static String simplify(String dtd) { // This doesn't do a full analysis on what expressions can be // simplified, but it does take care of some of the more annoying // things. int len; do { len = dtd.length(); // System.out.println("DTD length: " + len); dtd = dtd.replaceAll("t\\|(t\\|)+", "t\\|"); dtd = dtd.replaceAll("t,(t,)+", "t\\+,"); dtd = dtd.replaceAll("t\\|t\\)", "t\\)"); dtd = dtd.replaceAll("\\(\\(t\\)", "\\(t"); dtd = dtd.replaceAll("\\(t\\)\\)", "t\\)"); dtd = dtd.replaceAll("\\(t\\),", "t,"); dtd = dtd.replaceAll("\\(t\\)\\?", "t\\?"); dtd = dtd.replaceAll("\\(t\\)\\+", "t\\+"); dtd = dtd.replaceAll("\\(t\\)\\*", "t\\*"); dtd = dtd.replaceAll("t\\+,t\\?", "t\\+"); dtd = dtd.replaceAll("t\\?,t\\+", "t\\+"); } while (len != dtd.length()); return dtd; } }
27.396694
77
0.685973
1a66142e0dd405c2678edc45edb1eafe48f5b36b
3,771
package com.project.group18.limberup; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.support.v7.widget.GridLayout; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.HashMap; public class CategoryActivity extends AppCompatActivity { private ArrayList<Activity> activities = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Button Functionality setContentView(R.layout.activity_category); SharedPreferences sharedPref = CategoryActivity.this.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE); String token = sharedPref.getString("token", null); HashMap params = new HashMap<>(); params.put("token", token); ServerOp serverOp = ServerOp.getInstance(getApplicationContext()); serverOp.addToRequestQueue(serverOp.postRequest("https://limberup.herokuapp.com/api/activity/read", params, (s) ->{ try { JSONArray response = new JSONArray(s); setActivities(response); setupActivityGrid(); } catch(JSONException e){ Log.i("---->", "setActivities: " + e.toString()); } })); } public void setActivities(JSONArray activities) throws JSONException{ for (int i = 0; i < activities.length(); i++) { this.activities.add(new Activity(activities.getJSONObject(i))); } Log.i("---->", "setActivities: " + this.activities.size()); } // Functions to definition of the category button private void setupActivityGrid() { GridLayout gridLayout = (GridLayout) findViewById(R.id.activityGrid); gridLayout.removeAllViews(); int total = activities.size(); int column = 2; if(column > total && total != 0){ column = total; } int row = total / column; gridLayout.setColumnCount(column); gridLayout.setRowCount(row + 1); for (int i = 0, c = 0, r = 0; i < total; i++, c++) { if (c == column) { c = 0; r++; } final Activity currentActivity = activities.get(i); Button button = new Button(this); button.setWidth(gridLayout.getWidth()/2); button.setText(currentActivity.name); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(CategoryActivity.this, EventListActivity.class); intent.putExtra("id", currentActivity.id); intent.putExtra("activity", currentActivity.name); startActivity(intent); } }); button.setLayoutParams(new GridLayout.LayoutParams()); GridLayout.Spec rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 1); GridLayout.Spec colspan = GridLayout.spec(GridLayout.UNDEFINED, 1); if (r == 0 && c == 0) { Log.e("", "spec"); colspan = GridLayout.spec(GridLayout.UNDEFINED, 2); rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 2); } GridLayout.LayoutParams gridParam = new GridLayout.LayoutParams( rowSpan, colspan); gridLayout.addView(button, gridParam); } } }
34.916667
145
0.607531
a88f7fa1ccf1d72cc91b3b4d93886bf7a5d34174
571
/* * Copyright (c) 2014 mgamelabs * To see our full license terms, please visit https://github.com/mgamelabs/mengine/blob/master/LICENSE.md * All rights reserved. */ package mEngine.graphics.gui; import java.util.ArrayList; import java.util.List; public class GUIScreenController { private static List<GUIScreen> guiScreens = new ArrayList<>(); public static void addGUIScreen(GUIScreen screen) { guiScreens.add(screen); } public static boolean isScreenActive(GUIScreen screen) { return screen != null && screen.active; } }
22.84
106
0.711033
bee286debde2a55d5302f0c454f28fef3206d507
1,959
package com.wlgdo.avatar.web.common; import org.junit.Test; /** * Author: Ligang.Wang[[email protected]] * Date: 2019/6/5 16:35 */ public class RSAEncryptTest { @Test public void encrypt() { String message = "ItryMYbesttoLoveU"; try { String cryptoStr = RSAEncrypt.encrypt(message, "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDThbPs5yxP4sBtV/eSu+YweW18Optlg5YoAn5xZGwLAQyQ1QCvloDdHVSr3ijkF/+vAPu1MhkMwxPd8G0vGRh7wPQq0B3iyslltWJrlWrtwtqy5Fh5FqFNkOME7OoF6S2DQ8vCbiVwevVBQazQ0odag5Xvd9+3O5oOzeuNX1bvPwIDAQAB"); System.out.println(cryptoStr); } catch (Exception e) { e.printStackTrace(); } } @Test public void decrypt() { String cyptoStr = "y2K/yDKZs5s3rZX1ZfKf8+LmTPuzlvCoGltnfdpGF8yCAmFfLv0+0ccbzhXjUB8YG2zGL31Q6ys6Xm/8LDd8UupAXETlhC726CmHgKEodB/LxN1OfTqOUFBI0kk6zCPuAmifPbIAu1A4WkHI46owJq2h9TMjHhYm9jGmATlRtgk="; try { String deCrypt = RSAEncrypt.decrypt(cyptoStr, "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANOFs+znLE/iwG1X95K75jB5bXw6m2WDligCfnFkbAsBDJDVAK+WgN0dVKveKOQX/68A+7UyGQzDE93wbS8ZGHvA9CrQHeLKyWW1YmuVau3C2rLkWHkWoU2Q4wTs6gXpLYNDy8JuJXB69UFBrNDSh1qDle9337c7mg7N641fVu8/AgMBAAECgYB1fqt3SOJAbcBd/KM1CtLO0mSSwStYtENQbjI2YoXxht+oA+mhn4RtTsGdxoYITZxlZbJr8Cwh/qqmecrsgpAqCyFGsFoZzYgGa5LmLoVq0lLYnbpD86zMVKVPrUkvDL49HHkkjRD104YKOWtxe0FRGBkwgBqKetZDJA0DH+mY4QJBAPUjN/alcm3T0lsKRgpHjOGRoQ+RaBq4lHA5Q7UYCUIbyHnTqgD4T+Zf0U/MYYFRhiy9YiCppx4yzolXnIL3KAsCQQDc5SkSAPX6NuQV12rCKTEQG61hF4C524CpuRxdeog9/8xvS1I+YzLVI+WyGNc77Nxm+cvOOxRv3yZt7RY1l/IdAkEAoe5t3YRVHq+6WWFj+w5gxfEJT9thxaUAiVGKpGoIU58+wxtLRfDB9xB8mBYOovpTg+Jmm+T1/EDbpmY1gV37GQJAD21Ntf0tMKFewou93/uCeq6EKFC8474JuVC9Q2YIV9Qike8/ui2xYiNUqmCDv6KmLebqLegAYGPESk8RiwKmnQJBAJvkafHLfhft7gmGB9MWjZ3W8I1w8ApZE1pcnHBdRqsd/crzruiZAb1rGLiz5nZdTHIOph49D+VruAZC+U+tR0o="); System.out.println(deCrypt); } catch (Exception e) { e.printStackTrace(); } } }
55.971429
910
0.810107
0f32f591339d9509e611dcba1cde946cf87e6d84
6,696
package com.code.server.game.mahjong.util; import java.util.Comparator; public class MyComparator implements Comparator<String> { // 重定義排序方法 @Override // 1 小到大 public int compare(String s1, String s2) { if (s1.startsWith("wan")) { if (s2.startsWith("wan")) { if (Integer .parseInt(s1.substring(s1.length() - 1, s1.length())) > Integer .parseInt(s2.substring(s2.length() - 1, s2.length()))) { return 1; } else { return -1; } } else if (s2.startsWith("tiao")) { return -1; } else if (s2.startsWith("tong")) { return -1; } else if (s2.startsWith("dong")) { return -1; } else if (s2.startsWith("nan")) { return -1; } else if (s2.startsWith("xi")) { return -1; } else if (s2.startsWith("bei")) { return -1; } else if (s2.startsWith("zhong")) { return -1; } else if (s2.startsWith("fa")) { return -1; } else if (s2.startsWith("bai")) { return -1; } else { return -1; } } else if (s1.startsWith("tiao")) { if (s2.startsWith("wan")) { return 1; } else if (s2.startsWith("tiao")) { if (Integer .parseInt(s1.substring(s1.length() - 1, s1.length())) > Integer .parseInt(s2.substring(s2.length() - 1, s2.length()))) { return 1; } else { return -1; } } else if (s2.startsWith("tong")) { return -1; } else if (s2.startsWith("dong")) { return -1; } else if (s2.startsWith("nan")) { return -1; } else if (s2.startsWith("xi")) { return -1; } else if (s2.startsWith("bei")) { return -1; } else if (s2.startsWith("zhong")) { return -1; } else if (s2.startsWith("fa")) { return -1; } else if (s2.startsWith("bai")) { return -1; } else { return -1; } } else if (s1.startsWith("tong")) { if (s2.startsWith("wan")) { return 1; } else if (s2.startsWith("tiao")) { return 1; } else if (s2.startsWith("tong")) { if (Integer .parseInt(s1.substring(s1.length() - 1, s1.length())) > Integer .parseInt(s2.substring(s2.length() - 1, s2.length()))) { return 1; } else { return -1; } } else if (s2.startsWith("dong")) { return -1; } else if (s2.startsWith("nan")) { return -1; } else if (s2.startsWith("xi")) { return -1; } else if (s2.startsWith("bei")) { return -1; } else if (s2.startsWith("zhong")) { return -1; } else if (s2.startsWith("fa")) { return -1; } else if (s2.startsWith("bai")) { return -1; } else { return -1; } } else if (s1.startsWith("dong")) { if (s2.startsWith("wan")) { return 1; } else if (s2.startsWith("tiao")) { return 1; } else if (s2.startsWith("tong")) { return 1; } else if (s2.startsWith("dong")) { return -1; } else if (s2.startsWith("nan")) { return -1; } else if (s2.startsWith("xi")) { return -1; } else if (s2.startsWith("bei")) { return -1; } else if (s2.startsWith("zhong")) { return -1; } else if (s2.startsWith("fa")) { return -1; } else if (s2.startsWith("bai")) { return -1; } else { return -1; } } else if (s1.startsWith("nan")) { if (s2.startsWith("wan")) { return 1; } else if (s2.startsWith("tiao")) { return 1; } else if (s2.startsWith("tong")) { return 1; } else if (s2.startsWith("dong")) { return 1; } else if (s2.startsWith("nan")) { return -1; } else if (s2.startsWith("xi")) { return -1; } else if (s2.startsWith("bei")) { return -1; } else if (s2.startsWith("zhong")) { return -1; } else if (s2.startsWith("fa")) { return -1; } else if (s2.startsWith("bai")) { return -1; } else { return -1; } } else if (s1.startsWith("xi")) { if (s2.startsWith("wan")) { return 1; } else if (s2.startsWith("tiao")) { return 1; } else if (s2.startsWith("tong")) { return 1; } else if (s2.startsWith("dong")) { return 1; } else if (s2.startsWith("nan")) { return 1; } else if (s2.startsWith("xi")) { return -1; } else if (s2.startsWith("bei")) { return -1; } else if (s2.startsWith("zhong")) { return -1; } else if (s2.startsWith("fa")) { return -1; } else if (s2.startsWith("bai")) { return -1; } else { return -1; } } else if (s1.startsWith("bei")) { if (s2.startsWith("wan")) { return 1; } else if (s2.startsWith("tiao")) { return 1; } else if (s2.startsWith("tong")) { return 1; } else if (s2.startsWith("dong")) { return 1; } else if (s2.startsWith("nan")) { return 1; } else if (s2.startsWith("xi")) { return 1; } else if (s2.startsWith("bei")) { return -1; } else if (s2.startsWith("zhong")) { return -1; } else if (s2.startsWith("fa")) { return -1; } else if (s2.startsWith("bai")) { return -1; } else { return -1; } } else if (s1.startsWith("zhong")) { if (s2.startsWith("wan")) { return 1; } else if (s2.startsWith("tiao")) { return 1; } else if (s2.startsWith("tong")) { return 1; } else if (s2.startsWith("dong")) { return 1; } else if (s2.startsWith("nan")) { return 1; } else if (s2.startsWith("xi")) { return 1; } else if (s2.startsWith("bei")) { return 1; } else if (s2.startsWith("zhong")) { return -1; } else if (s2.startsWith("fa")) { return -1; } else if (s2.startsWith("bai")) { return -1; } else { return -1; } } else if (s1.startsWith("fa")) { if (s2.startsWith("wan")) { return 1; } else if (s2.startsWith("tiao")) { return 1; } else if (s2.startsWith("tong")) { return 1; } else if (s2.startsWith("dong")) { return 1; } else if (s2.startsWith("nan")) { return 1; } else if (s2.startsWith("xi")) { return 1; } else if (s2.startsWith("bei")) { return 1; } else if (s2.startsWith("zhong")) { return 1; } else if (s2.startsWith("fa")) { return -1; } else if (s2.startsWith("bai")) { return -1; } else { return -1; } } else if (s1.startsWith("bai")) { if (s2.startsWith("wan")) { return 1; } else if (s2.startsWith("tiao")) { return 1; } else if (s2.startsWith("tong")) { return 1; } else if (s2.startsWith("dong")) { return 1; } else if (s2.startsWith("nan")) { return 1; } else if (s2.startsWith("xi")) { return 1; } else if (s2.startsWith("bei")) { return 1; } else if (s2.startsWith("zhong")) { return 1; } else if (s2.startsWith("fa")) { return -1; } else if (s2.startsWith("bai")) { return -1; } else { return -1; } } else { return -1; } } }
24.617647
69
0.53405
5013c407742c1ec681844f25a0216be38c6ae361
1,925
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mycode.seiyugoods.source.entity; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity // (1) @Table(name = "amiami_title") // (2) public class AmiamiTitle { public AmiamiTitle(Long id, String amiamiTitle) { this.id = id; this.amiamiTitle = amiamiTitle; } public AmiamiTitle() { } @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "amiami_title_id_seq") @SequenceGenerator(name = "amiami_title_id_seq", sequenceName = "amiami_title_id_seq", allocationSize = 1) private Long id; @Column(nullable = false) private String amiamiTitle; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "amiami_wiki", joinColumns = @JoinColumn(name = "amiami_title_id"), inverseJoinColumns = @JoinColumn(name = "wiki_title_id")) private Set<WikiTitle> wikiTitles; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAmiamiTitle() { return amiamiTitle; } public void setAmiamiTitle(String amiamiTitle) { this.amiamiTitle = amiamiTitle; } public Set<WikiTitle> getWikiTitles() { return wikiTitles; } public void setWikiTitles(Set<WikiTitle> wikiTitles) { this.wikiTitles = wikiTitles; } }
28.308824
110
0.710649
576a7b9d3e86295a6d44c7c364824b823625351d
11,921
package com.raizlabs.android.debugmodule.url; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.TypedArray; import android.support.annotation.ArrayRes; import android.support.annotation.LayoutRes; import android.util.Patterns; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.raizlabs.android.debugmodule.Critter; import com.raizlabs.android.debugmodule.R; import java.util.ArrayList; import java.util.List; /** * Description: Stores a list of URLS in internal preferences. It allows you to add and test custom endpoints in an app, * and select one for the app to use. In your implementing application, call {@link #getCurrentUrl()} * for the beginning of the URL for any request and this module will (if enabled) allow you to swap the standard one * with one a tester can type in. */ public class UrlCritter implements Critter { /** * Is called when a URL has changed */ public interface UrlChangeListener { /** * Called when the user chooses a different url endpoint. * * @param url The new URL to use */ void onUrlChanged(String url); } private ViewHolder viewHolder; private String baseUrl; private List<UrlChangeListener> urlChangeListeners; private transient UrlManager urlManager; UrlAdapter adapter; /** * Constructs this class with the specified URL as a base url. We will allow the user to change URLS in the app. * * @param name The name of this critter that will show up in the {@link com.raizlabs.android.debugmodule.Debugger} menu. * @param baseUrlString * @param context */ public UrlCritter(String baseUrlString, Context context) { baseUrl = baseUrlString; urlManager = new UrlManager(context); urlChangeListeners = new ArrayList<>(); } /** * Adds a URL to the singleton list of URL data. * * @param url The url to add to list * @param context The context of application * @return This instance for chaining */ @SuppressWarnings("unchecked") public UrlCritter addUrl(String url, Context context) { List<String> urls = urlManager.getUrls(context); if (!urls.contains(url)) { urls.add(url); urlManager.saveUrls(context, urls); } return this; } /** * Adds a list of urls to the saved list * * @param urls The list of urls to add * @param context The context of application * @return This instance for chaining */ public UrlCritter addUrlList(List<String> urls, Context context) { List<String> savedUrls = urlManager.getUrls(context); for (String url : urls) { if (!savedUrls.contains(url)) { savedUrls.add(url); } } urlManager.saveUrls(context, savedUrls); return this; } /** * Adds a varg of urls to the saved list * * @param context The context of application * @param urls The varg of urls to add * @return This instance for chaining */ public UrlCritter addUrls(Context context, String... urls) { List<String> savedUrls = urlManager.getUrls(context); for (String url : urls) { if (!savedUrls.contains(url)) { savedUrls.add(url); } } urlManager.saveUrls(context, savedUrls); return this; } /** * Adds a typed array of urls * * @param typedArray The typed array to use * @param context The context of application * @return This instance for chaining */ public UrlCritter addUrlTypedArray(TypedArray typedArray, Context context) { List<String> savedUrls = urlManager.getUrls(context); int length = typedArray.length(); for (int i = 0; i < length; i++) { String url = typedArray.getString(i); if (!savedUrls.contains(url)) { savedUrls.add(url); } } urlManager.saveUrls(context, savedUrls); return this; } /** * Adds a typed array of urls from the specified resource * * @param typedArrayRes The typed array resource to use * @param context The context of application * @return This instance for chaining */ public UrlCritter addUrlTypedArray(@ArrayRes int typedArrayRes, Context context) { return addUrlTypedArray(context.getResources().obtainTypedArray(typedArrayRes), context); } @Override public int getLayoutResId() { return R.layout.view_debug_module_url_critter; } @Override public void handleView(@LayoutRes int layoutResource, View view) { viewHolder = new ViewHolder(view); viewHolder.setupHolder(view.getContext()); } @Override public void cleanup() { } /** * Clears all URL data from disk */ public void clearData(Context context) { urlManager.clear(context); } /** * Registers the listener for when URL changes. * * @param urlChangeListener The listener that gets called back */ public void registerUrlChangeListener(UrlChangeListener urlChangeListener) { if (!urlChangeListeners.contains(urlChangeListener)) { urlChangeListeners.add(urlChangeListener); } } /** * Un registers the listener * * @param urlChangeListener The listener to remove */ public void removeUrlChangeListener(UrlChangeListener urlChangeListener) { urlChangeListeners.remove(urlChangeListener); } /** * @return the current url to use for this application. */ public String getCurrentUrl() { return urlManager.getCurrentUrl(baseUrl); } public class ViewHolder { TextView urlTitleText; TextView urlSpinnerText; Spinner storedUrlSpinner; EditText addUrlOption; Button saveUrlOption; Button clearUrlsOption; public ViewHolder(View view) { urlTitleText = (TextView) view.findViewWithTag(R.id.urlTitleText); urlSpinnerText = (TextView) view.findViewById(R.id.urlSpinnerText); storedUrlSpinner = (Spinner) view.findViewById(R.id.storedUrlSpinner); addUrlOption = (EditText) view.findViewById(R.id.addUrlOption); saveUrlOption = (Button) view.findViewById(R.id.saveUrlOption); clearUrlsOption = (Button) view.findViewById(R.id.clearData); } void setupHolder(Context context) { adapter = new UrlAdapter(context); // prefill with current base url option addUrlOption.setText(adapter.getItem(adapter.mUrls.indexOf(getCurrentUrl()))); storedUrlSpinner.setAdapter(adapter); storedUrlSpinner.setSelection(adapter.mUrls.indexOf(getCurrentUrl())); storedUrlSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { boolean isFirst = true; @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(!isFirst) { String url = adapter.getItem(position); urlManager.setCurrentUrl(url); Toast.makeText(view.getContext(), "Now using " + url, Toast.LENGTH_SHORT).show(); if (urlChangeListeners != null) { for (UrlChangeListener listener : urlChangeListeners) { listener.onUrlChanged(url); } } } else { isFirst = false; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); saveUrlOption.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = addUrlOption.getText().toString(); if (!Patterns.WEB_URL.matcher(url).matches()) { Toast.makeText(v.getContext(), "Please enter a valid base url", Toast.LENGTH_SHORT).show(); } else if (!url.isEmpty()) { if(!urlManager.getUrls(v.getContext()).contains(url)) { Toast.makeText(v.getContext(), "Added " + url + " to list", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(v.getContext(), "Duplicate URL entered", Toast.LENGTH_SHORT).show(); } addUrl(url, v.getContext()); adapter.refresh(v.getContext()); } } }); clearUrlsOption.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()) .setTitle("Are you sure you want to clear all custom urls?") .setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { urlManager.clear(v.getContext()); adapter.refresh(v.getContext()); } }) .setNegativeButton("no", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } }); } } /** * Retrieves the list of Urls from the corresponding list of urls. */ class UrlAdapter extends BaseAdapter { List<String> mUrls; @SuppressWarnings("unchecked") public UrlAdapter(Context context) { addUrl(baseUrl, context); mUrls = urlManager.getUrls(context); } public void refresh(Context context) { mUrls = urlManager.getUrls(context); notifyDataSetChanged(); } @Override public int getCount() { return mUrls != null ? mUrls.size() : 0; } @Override public String getItem(int position) { return mUrls.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView textView; if (convertView == null) { textView = new TextView(parent.getContext()); int pad = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, parent.getResources().getDisplayMetrics()); textView.setPadding(pad, pad, pad, pad); } else { textView = (TextView) convertView; } textView.setText(getItem(position)); return textView; } } }
34.453757
133
0.579733
59bffa9f6806c07b1495943aa2cd9cdb688bcbe8
2,060
package org.redquark.leetcode.challenge; /** * @author Anirudh Sharma * <p> * Implement the StreamChecker class as follows: * <p> * StreamChecker(words): Constructor, init the data structure with the given words. * query(letter): returns true if and only if for some k >= 1, the last k characters queried * (in order from oldest to newest, including this letter just queried) spell one of the words * in the given list. * <p> * Note: * <p> * 1. 1 <= words.length <= 2000 * 2. 1 <= words[i].length <= 2000 * 3. Words will only consist of lowercase English letters. * 4. Queries will only consist of lowercase English letters. * 5. The number of queries is at most 40000. */ public class Problem23_StreamOfCharacters { private final Trie trie; private final StringBuilder sb; public Problem23_StreamOfCharacters(String[] words) { trie = new Trie(); sb = new StringBuilder(); for (String word : words) { insert(word); } } private void insert(String word) { Trie current = trie; for (int i = word.length() - 1; i >= 0; i--) { char c = word.charAt(i); Trie next = current.children[c - 'a']; if (next == null) { current.children[c - 'a'] = next = new Trie(); } current = next; } current.endOfWord = true; } public boolean query(char letter) { boolean result = false; sb.append(letter); Trie current = trie; for (int i = sb.length() - 1; i >= 0; i--) { char c = sb.charAt(i); if (current.children[c - 'a'] == null) { return false; } current = current.children[c - 'a']; if (current.endOfWord) { return true; } } return false; } static class Trie { boolean endOfWord; Trie[] children; Trie() { endOfWord = false; children = new Trie[26]; } } }
27.837838
94
0.546602
174012c502057daf74dacf3ff27a4e8df3ed4354
10,336
package gridwhack; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferStrategy; import java.text.DecimalFormat; import javax.swing.JFrame; /** * Core game engine class file. * @author Christoffer Niska <[email protected]> */ public abstract class CGameEngine extends JFrame implements Runnable { protected int pWidth, pHeight; private Thread animator; // for the animation private volatile boolean running = false; // stops the animation private volatile boolean ended = false; // ensures that the application is not terminated multiple times private volatile boolean gameOver = false; // for game termination private long period; // period in between drawing in nanoseconds protected CScreenManager screen; private static final int NUM_BUFFERS = 2; // number of buffers to use with the buffer strategy private static final int NO_DELAYS_PER_YIELD = 16; private static final int MAX_FRAME_SKIPS = 5; private static final long MAX_STATS_INTERVAL = 1000L; // record stats every second private static final int NUM_FPS = 10; // number of FPS values sorted to get an average private long statsInterval = 0L; // in nanoseconds private long prevStatsTime; private long totalElapsedTime = 0L; private long gameStartTime; protected int timeSpentInGame = 0; // in seconds private long frameCount = 0; private double fpsStore[]; private long statsCount = 0; protected double averageFPS = 0.0; private long framesSkipped = 0L; private long totalFramesSkipped = 0L; private double upsStore[]; protected double averageUPS = 0.0; private long prevUpdateTime; // in nanoseconds protected DecimalFormat df = new DecimalFormat("0.##"); // 2 decimal precision protected DecimalFormat timedf = new DecimalFormat("0.####"); // 4 decimal precision protected Font font; protected FontMetrics metrics; /** * Creates the game engine. * @param title the application frame title. * @param period the period (in nanoseconds). */ public CGameEngine(String title, long period) { super(title); // Create the screen manager. this.screen = new CScreenManager(this); this.period = period; // Initialize the full-screen mode. screen.initFullScreen(NUM_BUFFERS); // Set an appropriate display mode. //screen.setDisplayMode(1920, 1080, 32); // Get the width and height after changing the display mode. pWidth = screen.getWidth(); pHeight = screen.getHeight(); // Allow for terminating the application. readyForTermination(); // Set up message font. font = new Font("SansSerif", Font.BOLD, 12); metrics = this.getFontMetrics(font); // Initialize the timing elements. fpsStore = new double[NUM_FPS]; upsStore = new double[NUM_FPS]; for( int i=0; i<NUM_FPS; i++ ) { fpsStore[i] = 0.0; upsStore[i] = 0.0; } gameInit(); // initialize the game gameStart(); // start the thread } /** * Allows for terminating the application. */ private void readyForTermination() { // Add a key listener to listen for termination key presses. addKeyListener( new KeyAdapter() { /** * Actions to be taken when a key is pressed. * @param e the key event. */ public void keyPressed(KeyEvent e) { if( e.getKeyCode()==KeyEvent.VK_C && e.isControlDown() ) { gameStop(); } e.consume(); } } ); // Add a shutdown hook to be called when game is terminated. Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { gameStop(); endClean(); } } ); } /** * Starts the game. */ private void gameStart() { // Start the game if it is not already started. if( animator==null || !running ) { animator = new Thread(this); animator.start(); } } /** * Stops the game. */ public void gameStop() { running = false; // exit the game loop } /** * Runs the game. */ public void run() { long beforeTime, afterTime, timeDiff, sleepTime; long overSleepTime = 0L; int noDelays = 0; long excess = 0L; gameStartTime = System.nanoTime(); prevStatsTime = gameStartTime; beforeTime = gameStartTime; running = true; while( running ) { stateUpdate(); // game state is updated screenUpdate(); // screen is updated afterTime = System.nanoTime(); timeDiff = afterTime - beforeTime; sleepTime = (period - timeDiff) - overSleepTime; // We have time to sleep. if( sleepTime>0 ) { try { Thread.sleep(sleepTime/1000000L); // ns -> ms } catch( InterruptedException e ) {} overSleepTime = (System.nanoTime() - afterTime) - sleepTime; } // We do not have time to sleep, frame took longer than the period. else { excess -= sleepTime; // store excess time value overSleepTime = 0L; // Let other threads run if necessary. if( ++noDelays>=NO_DELAYS_PER_YIELD ) { Thread.yield(); noDelays = 0; } } beforeTime = System.nanoTime(); int skips = 0; while( excess>period && skips<MAX_FRAME_SKIPS ) { excess -= period; stateUpdate(); // update the state but do not render skips++; } framesSkipped += skips; storeStats(); } // End the application. endClean(); } /** * Updates the game state. */ private void stateUpdate() { // Make sure that the game is not over. if( !gameOver ) { // Get the amount of time passed since the last update. long timePassed = getTimeSinceLastUpdate(); // Update the game state. gameUpdate(timePassed); } } /** * Returns the time passed since the last update. * @return the time passed in nanoseconds. */ private long getTimeSinceLastUpdate() { long timePassed, timeNow; timeNow = System.nanoTime(); // Calculate the time passed based on // when the last previous update time. prevUpdateTime = prevUpdateTime>0 ? prevUpdateTime : timeNow; timePassed = timeNow - prevUpdateTime; prevUpdateTime = timeNow; return timePassed; } /** * Updates the screen. */ private void screenUpdate() { try { BufferStrategy bs = getBufferStrategy(); // Get the content from the buffer strategy, // render it dispose of it after its been rendered. Graphics2D g = (Graphics2D) bs.getDrawGraphics(); gameRender(g); g.dispose(); // Make sure that the content of the buffer strategy is not lost. if( !bs.contentsLost() ) { bs.show(); } else { // Content was lost. This might happen if the OS overwrites // the content in the buffer strategy. System.out.println("Buffer strategy content lost"); } Toolkit.getDefaultToolkit().sync(); // sync the display on *nix OS } catch( Exception e ) { // Could not update the screen, print the exception // and terminate the game loop. e.printStackTrace(); running = false; } } /** * Ends the application properly. */ protected void endClean() { // Make sure that we do not call this multiple times. if( !ended ) { ended = true; printStats(); screen.restoreScreen(); System.exit(0); } } /** * Stores the runtime statistics. */ private void storeStats() { frameCount++; statsInterval += period; // Make sure we should collect the stats. if( statsInterval>=MAX_STATS_INTERVAL ) { long timeNow = System.nanoTime(); timeSpentInGame = (int) ((timeNow - gameStartTime) / 1000000000L); // ns -> seconds long realElapsedTime = timeNow - prevStatsTime; // time since last stats collection totalElapsedTime += realElapsedTime; //double timingError = (double) ((realElapsedTime - statsInterval) / statsInterval) * 100.0; totalFramesSkipped += framesSkipped; // Calculate the latest FPS and UPS. double actualFPS = 0; double actualUPS = 0; if( totalElapsedTime>0 ) { actualFPS = ((double) frameCount / totalElapsedTime) * 1000000000L; // ns -> seconds actualUPS = ((double) (frameCount + totalFramesSkipped) / totalElapsedTime) * 1000000000L; } // Store the latest FPS and UPS. fpsStore[ (int) statsCount % NUM_FPS ] = actualFPS; upsStore[ (int) statsCount % NUM_FPS ] = actualUPS; statsCount++; double totalFPS = 0.0; double totalUPS = 0.0; for( int i=0; i<NUM_FPS; i++ ) { totalFPS += fpsStore[i]; totalUPS += upsStore[i]; } if( statsCount<NUM_FPS ) { averageFPS = totalFPS/statsCount; averageUPS = totalUPS/statsCount; } else { averageFPS = totalFPS/NUM_FPS; averageUPS = totalUPS/NUM_FPS; } // For debugging purposes only. /* System.out.println( timedf.format( (double) statsInterval/1000000000L) + " " + timedf.format( (double) realElapsedTime/1000000000) + "s " + df.format(timingError) + "% " + frameCount + "c " + framesSkipped + "/" + totalFramesSkipped + " skip; " + df.format(actualFPS) + " " + df.format(averageFPS) + " afps; " + df.format(actualUPS) + " " + df.format(averageUPS) + " aups"); */ framesSkipped = 0; prevStatsTime = timeNow; statsInterval = 0L; // reset } } /** * Prints the runtime statistics. */ private void printStats() { System.out.println("Frame Count/Loss: " + frameCount + " / " + totalFramesSkipped); System.out.println("Average FPS: " + df.format(averageFPS)); System.out.println("Average UPS: " + df.format(averageUPS)); System.out.println("Time Spent: " + timeSpentInGame + " secs"); } /** * Initializes the game. */ public abstract void gameInit(); /** * Updates the game state. * @param timePassed the time passed since the last update. */ public abstract void gameUpdate(long timePassed); /** * Renders the game. * @param g the graphics context. */ public abstract void gameRender(Graphics2D g); }
24.377358
106
0.627322
0df97f50f53df94f20a9d686d19cea22b3697ea5
5,839
/** * Copyright 2019 ForgeRock AS. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.forgerock.openbanking.common.model.openbanking.obie.pain001; import javax.annotation.Generated; import javax.xml.bind.annotation.*; import java.util.ArrayList; import java.util.List; /** * <p>Java class for RegulatoryReporting3 complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="RegulatoryReporting3"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="DbtCdtRptgInd" type="{urn:iso:std:iso:20022:tech:xsd:pain.001.001.08}RegulatoryReportingType1Code" minOccurs="0"/> * &lt;element name="Authrty" type="{urn:iso:std:iso:20022:tech:xsd:pain.001.001.08}RegulatoryAuthority2" minOccurs="0"/> * &lt;element name="Dtls" type="{urn:iso:std:iso:20022:tech:xsd:pain.001.001.08}StructuredRegulatoryReporting3" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RegulatoryReporting3", namespace = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.08", propOrder = { "dbtCdtRptgInd", "authrty", "dtls" }) @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2019-01-07T09:44:17+00:00", comments = "JAXB RI v2.2.8-b130911.1802") public class RegulatoryReporting3 { @XmlElement(name = "DbtCdtRptgInd", namespace = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.08") @XmlSchemaType(name = "string") @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2019-01-07T09:44:17+00:00", comments = "JAXB RI v2.2.8-b130911.1802") protected RegulatoryReportingType1Code dbtCdtRptgInd; @XmlElement(name = "Authrty", namespace = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.08") @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2019-01-07T09:44:17+00:00", comments = "JAXB RI v2.2.8-b130911.1802") protected RegulatoryAuthority2 authrty; @XmlElement(name = "Dtls", namespace = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.08") @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2019-01-07T09:44:17+00:00", comments = "JAXB RI v2.2.8-b130911.1802") protected List<StructuredRegulatoryReporting3> dtls; /** * Gets the value of the dbtCdtRptgInd property. * * @return * possible object is * {@link RegulatoryReportingType1Code } * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2019-01-07T09:44:17+00:00", comments = "JAXB RI v2.2.8-b130911.1802") public RegulatoryReportingType1Code getDbtCdtRptgInd() { return dbtCdtRptgInd; } /** * Sets the value of the dbtCdtRptgInd property. * * @param value * allowed object is * {@link RegulatoryReportingType1Code } * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2019-01-07T09:44:17+00:00", comments = "JAXB RI v2.2.8-b130911.1802") public void setDbtCdtRptgInd(RegulatoryReportingType1Code value) { this.dbtCdtRptgInd = value; } /** * Gets the value of the authrty property. * * @return * possible object is * {@link RegulatoryAuthority2 } * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2019-01-07T09:44:17+00:00", comments = "JAXB RI v2.2.8-b130911.1802") public RegulatoryAuthority2 getAuthrty() { return authrty; } /** * Sets the value of the authrty property. * * @param value * allowed object is * {@link RegulatoryAuthority2 } * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2019-01-07T09:44:17+00:00", comments = "JAXB RI v2.2.8-b130911.1802") public void setAuthrty(RegulatoryAuthority2 value) { this.authrty = value; } /** * Gets the value of the dtls property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the dtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDtls().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link StructuredRegulatoryReporting3 } * * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2019-01-07T09:44:17+00:00", comments = "JAXB RI v2.2.8-b130911.1802") public List<StructuredRegulatoryReporting3> getDtls() { if (dtls == null) { dtls = new ArrayList<StructuredRegulatoryReporting3>(); } return this.dtls; } }
38.163399
158
0.660387
77c147869095635366c1bc21418507783390445d
544
package io.github.mongoshaman.core.exceptions; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ShamanExecutionException extends ShamanException { private static final Logger LOGGER = LoggerFactory.getLogger(ShamanExecutionException.class); public ShamanExecutionException(final List<Exception> exceptions) { super(exceptions.stream().map(Exception::getLocalizedMessage).collect(Collectors.joining("\n"))); LOGGER.error(this.getMessage()); } }
28.631579
101
0.795956
e16ee6fc96ec13d5e099812f3309e81e4531d695
2,394
package internal.org.springframework.content.docx4j; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.docx4j.Docx4J; import org.docx4j.Docx4jProperties; import org.docx4j.convert.out.HTMLSettings; import org.docx4j.convert.out.html.AbstractHtmlExporter; import org.docx4j.convert.out.html.HtmlExporterNG2; import org.docx4j.model.fields.FieldUpdater; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.springframework.content.commons.io.FileRemover; import org.springframework.content.commons.io.ObservableInputStream; import org.springframework.content.commons.renditions.RenditionProvider; import org.springframework.stereotype.Service; import java.io.*; import java.nio.file.Files; import java.nio.file.attribute.FileAttribute; import static java.lang.String.format; @Service public class WordToHtmlRenditionProvider implements RenditionProvider { private static final Log logger = LogFactory.getLog(WordToHtmlRenditionProvider.class); @Override public String consumes() { return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } @Override public String[] produces() { return new String[] { "text/html" }; } @Override public InputStream convert(InputStream fromInputSource, String toMimeType) { try { WordprocessingMLPackage pkg = WordprocessingMLPackage.load(fromInputSource); FieldUpdater updater = new FieldUpdater(pkg); updater.update(true); AbstractHtmlExporter exporter = new HtmlExporterNG2(); HTMLSettings htmlSettings = Docx4J.createHTMLSettings(); htmlSettings.setWmlPackage(pkg); Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML", true); File tmpFile = Files.createTempFile(null, null, new FileAttribute<?>[]{}).toFile(); OutputStream os = new FileOutputStream(tmpFile); Docx4J.toHTML(htmlSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL); IOUtils.closeQuietly(os); if (pkg.getMainDocumentPart().getFontTablePart() != null) { pkg.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles(); } htmlSettings = null; pkg = null; return new ObservableInputStream(new FileInputStream(tmpFile), new FileRemover(tmpFile)); } catch (Exception e) { logger.warn(format("%s rendition failed", toMimeType), e); } return null; } }
31.5
92
0.787803
53f6041268170581a746d745756429862de64281
1,061
package datadog.trace.instrumentation.grizzly.client; import static datadog.trace.bootstrap.instrumentation.api.DDComponents.GRIZZLY_HTTP_ASYNC_CLIENT; import com.ning.http.client.Request; import com.ning.http.client.Response; import datadog.trace.bootstrap.instrumentation.decorator.HttpClientDecorator; import java.net.URI; import java.net.URISyntaxException; public class ClientDecorator extends HttpClientDecorator<Request, Response> { public static final ClientDecorator DECORATE = new ClientDecorator(); @Override protected String[] instrumentationNames() { return new String[] {"grizzly-client", "ning"}; } @Override protected String component() { return GRIZZLY_HTTP_ASYNC_CLIENT; } @Override protected String method(final Request request) { return request.getMethod(); } @Override protected URI url(final Request request) throws URISyntaxException { return request.getUri().toJavaNetURI(); } @Override protected Integer status(final Response response) { return response.getStatusCode(); } }
26.525
97
0.773798
b5acc054257403257fd6b320d7bcfab04c047985
5,021
package test; import java.io.*; import java.util.*; import java.util.jar.*; import junit.framework.*; import aQute.lib.osgi.*; public class AttributesTest extends TestCase { /** * Remove a version attribute * * A mandatory attribute adds the common and tst properties to the * import. We remove them using remove:=* * @throws Exception */ public void testRemoveDirective() throws Exception { Jar javax = new Jar("test"); Manifest m = new Manifest(); m.getMainAttributes().putValue("Export-Package", "javax.microedition.io;a1=exp-1;a2=exp-2;a3=exp-3;x1=x1;x2=x2;x3=x3;mandatory:=\"a1,a2,a3,x1,x2,x3\""); javax.setManifest(m); Jar cp[] = { javax, new Jar(new File("jar/osgi.jar")) }; Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Import-Package", "javax.microedition.io;-remove-attribute:=a1|x?;a2=imp-2,*"); p.put("Export-Package", "org.osgi.service.io"); bmaker.setClasspath(cp); bmaker.setProperties(p); Jar jar = bmaker.build(); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); Manifest manifest = jar.getManifest(); Attributes main = manifest.getMainAttributes(); String imprt = main.getValue("Import-Package"); assertNotNull("Import package header", imprt ); Map<String,Map<String,String>> map = Processor.parseHeader(imprt, null); Map<String,String> attrs = map.get("javax.microedition.io"); assertNotNull(attrs); assertNull(attrs.get("a1")); assertNull(attrs.get("x1")); assertNull(attrs.get("x2")); assertNull(attrs.get("x3")); assertEquals("imp-2", attrs.get("a2")); assertEquals("exp-3", attrs.get("a3")); } /** * Remove a version attribute * * @throws Exception */ public void testRemoveAttribute() throws Exception { Jar javax = new Jar("test"); Manifest m = new Manifest(); m.getMainAttributes().putValue("Export-Package", "javax.microedition.io;common=split;test=abc;mandatory:=\"common,test\""); javax.setManifest(m); Jar cp[] = { javax, new Jar(new File("jar/osgi.jar")) }; Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Import-Package", "javax.microedition.io;common=!;test=abc,*"); p.put("Export-Package", "org.osgi.service.io"); bmaker.setClasspath(cp); bmaker.setProperties(p); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); Manifest manifest = jar.getManifest(); Attributes main = manifest.getMainAttributes(); String imprt = main.getValue("Import-Package"); assertNotNull("Import package header", imprt ); Map<String,Map<String,String>> map = Processor.parseHeader(imprt, null); Map<String,String> attrs = map.get("javax.microedition.io"); assertNotNull(attrs); assertNull(attrs.get("common")); } /** * Override a version attribute * * @throws Exception */ public void testOverrideAttribute() throws Exception { File cp[] = { new File("jar/osgi.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Export-Package", "org.osgi.framework;version=1.1"); bmaker.setClasspath(cp); bmaker.setProperties(p); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); Manifest manifest = jar.getManifest(); Attributes main = manifest.getMainAttributes(); String export = main.getValue("Export-Package"); assertNotNull("Export package header", export ); Map<String,Map<String,String>> map = Processor.parseHeader(export, null); assertEquals( "1.1", map.get("org.osgi.framework").get("version")); } /** * See if we inherit the version from the osgi.jar file. * * @throws Exception */ public void testSimple() throws Exception { File cp[] = { new File("jar/osgi.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Export-Package", "org.osgi.framework"); bmaker.setClasspath(cp); bmaker.setProperties(p); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); Manifest manifest = jar.getManifest(); Attributes main = manifest.getMainAttributes(); String export = main.getValue("Export-Package"); assertNotNull("Export package header", export ); Map<String,Map<String,String>> map = Processor.parseHeader(export, null); assertEquals( "1.3", map.get("org.osgi.framework").get("version")); } }
35.864286
154
0.690102
4e87e8c79a65593fd888cebae27afd1bc1bb02bd
305
package com.bornium.security.oauth2openid.providers; import com.bornium.security.oauth2openid.server.TimingContext; import java.time.Duration; public interface TimingProvider { Duration getShortTokenValidFor(TimingContext context); Duration getRefreshTokenValidFor(TimingContext context); }
21.785714
62
0.82623
6e367448df65ceb8dc655eee4c267954da0f2da9
503
/* * This software is available under Apache License * Copyright (c) 2020 */ package org.pixel.commons.logger; public interface LoggerStrategy { /** * Creates a logger object based on the given class. * * @return Logger instance. */ Logger createLogger(Class<?> classRef); /** * Creates a logger object based on the given context. * * @param context Logger context. * @return Logger instance. */ Logger createLogger(String context); }
20.12
58
0.638171
9b6b4c548ecb3d70bd1d1c41867894ac563340a0
899
package net.jeebiz.boot.demo.web.mvc; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import net.jeebiz.boot.demo.setup.rocketmq.LogProducer; @RestController public class RocketMQController { @Autowired private LogProducer logProducer; @GetMapping("/rocketmq/send") public String activemq(HttpServletRequest request, String msg) { msg = StringUtils.isEmpty(msg) ? "This is Empty Msg." : msg; try { logProducer.send(msg); } catch (Exception e) { e.printStackTrace(); } return "Rocketmq has sent OK."; } }
28.09375
71
0.656285
6f0feab6b103f1a6c742890e2c9b967c3b52c2ba
4,146
package com.bloodl1nez.analytics.vk.job.analyser.friends; import com.bloodl1nez.analytics.vk.api.friends.FriendsService; import com.bloodl1nez.analytics.vk.api.likes.LikeType; import com.bloodl1nez.analytics.vk.api.likes.LikesFetcher; import com.bloodl1nez.analytics.vk.api.photos.PhotosFetcher; import com.bloodl1nez.analytics.vk.api.posts.PostsFetcher; import com.bloodl1nez.analytics.vk.job.analyser.Analyser; import com.bloodl1nez.analytics.vk.model.entity.AnalyseResult; import com.bloodl1nez.analytics.vk.model.entity.LikedUser; import com.bloodl1nez.analytics.vk.model.entity.Photo; import com.bloodl1nez.analytics.vk.model.entity.Post; import com.bloodl1nez.analytics.vk.model.entity.User; import com.bloodl1nez.analytics.vk.web.request.AnalyseSettings; import com.bloodl1nez.analytics.vk.web.request.FriendsAnalyseSettings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.BiConsumer; import java.util.stream.Collectors; @Component public class FriendsAnalyser implements Analyser { private final FriendsService friendsService; private final PostsFetcher postsFetcher; private final LikesFetcher likesFetcher; private final PhotosFetcher photosFetcher; @Autowired public FriendsAnalyser( FriendsService friendsService, PostsFetcher postsFetcher, LikesFetcher likesFetcher, PhotosFetcher photosFetcher) { this.friendsService = friendsService; this.postsFetcher = postsFetcher; this.likesFetcher = likesFetcher; this.photosFetcher = photosFetcher; } @Override public void analyse( User user, AnalyseResult result, AnalyseSettings analyseSettings, BiConsumer<Integer, Integer> progressUpdater, String token) { long userId = user.getId(); Optional<FriendsAnalyseSettings> friendsSettings = analyseSettings.getFriendsSettings(); friendsSettings.ifPresent( settings -> { List<User> friends = friendsService.getFriends(userId, token); List<LikedUser> likedUsers = new ArrayList<>(); for (int i = 0; i < friends.size(); i++) { User friend = friends.get(i); LikedUser likedUser = new LikedUser(friend); if (settings.getPostsAmount() != null) { List<Post> likedPosts = getLikedPosts(user, friend, settings, token); likedUser.setLikedPosts(likedPosts); } if (settings.getPhotosAmount() != null) { List<Photo> likedPhotos = getLikedPhotos(user, friend, settings, token); likedUser.setLikedPhotos(likedPhotos); } if (!isLikedUserEmpty(likedUser)) { likedUsers.add(likedUser); } progressUpdater.accept(i * 100 / friends.size(), (i + 1) * 100 / friends.size()); } result.setLikedUsers(likedUsers); }); } private boolean isLikedUserEmpty(LikedUser likedUser) { return CollectionUtils.isEmpty(likedUser.getLikedPhotos()) && CollectionUtils.isEmpty(likedUser.getLikedPosts()); } private List<Post> getLikedPosts(User user, User friend, FriendsAnalyseSettings settings, String token) { return postsFetcher.getPostIds(friend.getId(), settings.getPostsAmount(), token).stream() .filter( postId -> likesFetcher.didUserLike(user.getId(), postId, friend.getId(), LikeType.POST, token)) .map(postId -> new Post(postId, friend.getId(), false)) .collect(Collectors.toList()); } private List<Photo> getLikedPhotos(User user, User friend, FriendsAnalyseSettings settings, String token) { return photosFetcher.getProfilePhotoIds(friend.getId(), settings.getPhotosAmount(), token).stream() .filter( postId -> likesFetcher.didUserLike(user.getId(), postId, friend.getId(), LikeType.PHOTO, token)) .map(photoId -> new Photo(photoId, friend.getId())) .collect(Collectors.toList()); } }
41.46
109
0.714906
ff459a089beabf041eea3827e4376a68a95a405b
1,957
import java.util.LinkedList; import java.util.Queue; /* You need to supply the following class in your solution Pair Complete the following class in your solution: */ /** * @version 0.1 * @author TomRokickiii * This is the Grid Class */ public class Grid { private static final int SIZE = 10; /** * provided array */ int[][] pixels = new int[SIZE][SIZE]; /** * Flood fill, starting with the given row and column. * @param row the row * @param column the column */ public void floodfill(int row, int column) { Queue<Pair> q = new LinkedList<>(); int start = 0; int index = 1; // Exit statement if (pixels[row][column] != start) { return; } q.add(new Pair(column, row)); while (!q.isEmpty()) { Pair p = q.remove(); if (pixels[p.getyCord()][p.getxCord()] == start) { pixels[p.getyCord()][p.getxCord()] = index; index++; // search and destroy >:D if (p.getyCord() > 0) { q.add(new Pair(p.getxCord(), p.getyCord() - 1)); } if (p.getxCord() < SIZE - 1) { q.add(new Pair(p.getxCord() + 1, p.getyCord())); } if (p.getyCord() < SIZE - 1) { q.add(new Pair(p.getxCord(), p.getyCord() + 1)); } if (p.getxCord() > 0) { q.add(new Pair(p.getxCord() - 1, p.getyCord())); } } } } /** * Converts to string. * * @return r a string */ public String toString() { String r = ""; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { r = r + String.format("%3d", pixels[i][j]); } r = r + "\n"; } return r; } }
25.75
68
0.443536
87b3498d9edd1e38b0e67fcc4a5b38c98b656b6d
18,162
/** */ package org.sheepy.lily.vulkan.extra.model.mesh.util; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; import org.sheepy.lily.core.model.maintainer.Maintainable; import org.sheepy.lily.core.model.maintainer.Maintainer; import org.sheepy.lily.core.model.types.LNamedElement; import org.sheepy.lily.vulkan.extra.model.mesh.*; import org.sheepy.lily.vulkan.extra.model.rendering.GenericRenderer; import org.sheepy.lily.vulkan.extra.model.rendering.Presentation; import org.sheepy.lily.vulkan.extra.model.rendering.Structure; import org.sheepy.lily.vulkan.model.IResourceContainer; import org.sheepy.lily.vulkan.model.process.AbstractPipeline; import org.sheepy.lily.vulkan.model.process.TaskPipeline; import org.sheepy.lily.vulkan.model.process.VkPipeline; import org.sheepy.lily.vulkan.model.process.graphic.GraphicsPipeline; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see org.sheepy.lily.vulkan.extra.model.mesh.MeshPackage * @generated */ public class MeshSwitch<T1> extends Switch<T1> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static MeshPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MeshSwitch() { if (modelPackage == null) { modelPackage = MeshPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T1 doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case MeshPackage.MESH: { Mesh mesh = (Mesh)theEObject; T1 result = caseMesh(mesh); if (result == null) result = casePresentation(mesh); if (result == null) result = defaultCase(theEObject); return result; } case MeshPackage.MESH_RENDERER: { MeshRenderer meshRenderer = (MeshRenderer)theEObject; T1 result = caseMeshRenderer(meshRenderer); if (result == null) result = caseGenericRenderer(meshRenderer); if (result == null) result = caseGraphicsPipeline(meshRenderer); if (result == null) result = caseMaintainer(meshRenderer); if (result == null) result = caseVkPipeline(meshRenderer); if (result == null) result = caseMaintainable(meshRenderer); if (result == null) result = caseTaskPipeline(meshRenderer); if (result == null) result = caseAbstractPipeline(meshRenderer); if (result == null) result = caseIResourceContainer(meshRenderer); if (result == null) result = caseLNamedElement(meshRenderer); if (result == null) result = defaultCase(theEObject); return result; } case MeshPackage.MESH_STRUCTURE: { MeshStructure<?> meshStructure = (MeshStructure<?>)theEObject; T1 result = caseMeshStructure(meshStructure); if (result == null) result = caseIMeshStructure(meshStructure); if (result == null) result = caseStructure(meshStructure); if (result == null) result = defaultCase(theEObject); return result; } case MeshPackage.IMESH_STRUCTURE: { IMeshStructure iMeshStructure = (IMeshStructure)theEObject; T1 result = caseIMeshStructure(iMeshStructure); if (result == null) result = caseStructure(iMeshStructure); if (result == null) result = defaultCase(theEObject); return result; } case MeshPackage.GEOMETRIC_STRUCTURE: { GeometricStructure geometricStructure = (GeometricStructure)theEObject; T1 result = caseGeometricStructure(geometricStructure); if (result == null) result = caseMeshStructure(geometricStructure); if (result == null) result = caseIMeshStructure(geometricStructure); if (result == null) result = caseStructure(geometricStructure); if (result == null) result = defaultCase(theEObject); return result; } case MeshPackage.GEOMETRIC_MESH: { GeometricMesh geometricMesh = (GeometricMesh)theEObject; T1 result = caseGeometricMesh(geometricMesh); if (result == null) result = caseMesh(geometricMesh); if (result == null) result = casePresentation(geometricMesh); if (result == null) result = defaultCase(theEObject); return result; } case MeshPackage.ICOSAHEDRON: { Icosahedron icosahedron = (Icosahedron)theEObject; T1 result = caseIcosahedron(icosahedron); if (result == null) result = caseGeometricStructure(icosahedron); if (result == null) result = caseMeshStructure(icosahedron); if (result == null) result = caseIMeshStructure(icosahedron); if (result == null) result = caseStructure(icosahedron); if (result == null) result = defaultCase(theEObject); return result; } case MeshPackage.SPHERE: { Sphere sphere = (Sphere)theEObject; T1 result = caseSphere(sphere); if (result == null) result = caseGeometricStructure(sphere); if (result == null) result = caseMeshStructure(sphere); if (result == null) result = caseIMeshStructure(sphere); if (result == null) result = caseStructure(sphere); if (result == null) result = defaultCase(theEObject); return result; } case MeshPackage.ICO_SPHERE: { IcoSphere icoSphere = (IcoSphere)theEObject; T1 result = caseIcoSphere(icoSphere); if (result == null) result = caseGeometricStructure(icoSphere); if (result == null) result = caseMeshStructure(icoSphere); if (result == null) result = caseIMeshStructure(icoSphere); if (result == null) result = caseStructure(icoSphere); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Mesh</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Mesh</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseMesh(Mesh object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Renderer</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Renderer</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseMeshRenderer(MeshRenderer object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Structure</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Structure</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public <T extends Mesh> T1 caseMeshStructure(MeshStructure<T> object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IMesh Structure</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IMesh Structure</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIMeshStructure(IMeshStructure object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Geometric Structure</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Geometric Structure</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseGeometricStructure(GeometricStructure object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Geometric Mesh</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Geometric Mesh</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseGeometricMesh(GeometricMesh object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Icosahedron</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Icosahedron</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIcosahedron(Icosahedron object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Sphere</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Sphere</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseSphere(Sphere object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Ico Sphere</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Ico Sphere</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIcoSphere(IcoSphere object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Presentation</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Presentation</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 casePresentation(Presentation object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LNamed Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LNamed Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseLNamedElement(LNamedElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Abstract Pipeline</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Abstract Pipeline</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseAbstractPipeline(AbstractPipeline object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IResource Container</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IResource Container</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIResourceContainer(IResourceContainer object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Task Pipeline</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Task Pipeline</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseTaskPipeline(TaskPipeline object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Vk Pipeline</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Vk Pipeline</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseVkPipeline(VkPipeline object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Maintainable</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Maintainable</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public <T extends Maintainable<T>> T1 caseMaintainable(Maintainable<T> object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Graphics Pipeline</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Graphics Pipeline</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseGraphicsPipeline(GraphicsPipeline object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Maintainer</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Maintainer</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public <T extends Maintainable<T>> T1 caseMaintainer(Maintainer<T> object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Generic Renderer</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Generic Renderer</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public <T extends Structure> T1 caseGenericRenderer(GenericRenderer<T> object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Structure</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Structure</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseStructure(Structure object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T1 defaultCase(EObject object) { return null; } } //MeshSwitch
34.926923
118
0.695133
0f9d859e4037a5f4c67cb42df8bdf9f44401a689
1,115
/* * Copyright (C) 2012 Christopher Peisert. 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 org.closureant.types; /** * Data type for simple nested elements that have a generic string value * attribute. * * @author cpeisert{at}gmail{dot}com (Christopher Peisert) */ public final class StringNestedElement { private String value; public StringNestedElement() { this.value = ""; } /** * @param value the attribute value */ public void setValue(String value) { this.value = value; } public String getValue() { return this.value; } }
25.930233
78
0.712108
b26f475071e699474001d0fa74f51997108442d7
236
package mops.util; import java.lang.annotation.*; /** * Interface for marking a class with Aggregate Root for testing. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface AggregateRoot { }
18.153846
65
0.766949
69d4eb07b797c9c0bd0705da8271aeeb7cb493a6
2,105
/******************************************************************************* * Copyright (c) 2006, 2012 Wind River Systems, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Markus Schorn - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.dom; import org.eclipse.cdt.core.dom.ast.IASTFileLocation; import org.eclipse.cdt.core.dom.ast.IASTNode; /** * Common interface for names in the index and the AST. * @since 4.0 * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ public interface IName { /** * @since 5.2 */ public static final IName[] EMPTY_ARRAY= {}; /** * Returns the name without qualification and without template arguments. * @since 5.1 */ public char[] getSimpleID(); /** * @deprecated Using this method is problematic, because for names from the * index never contain qualification or template arguments, which is different * for names from the AST. * Use {@link #getSimpleID()}, instead. * @noreference This method is not intended to be referenced by clients. */ @Deprecated public char[] toCharArray(); /** * Is this name being used in the AST as the introduction of a declaration? * @return boolean */ public boolean isDeclaration(); /** * Is this name being used in the AST as a reference rather than a declaration? * @return boolean */ public boolean isReference(); /** * Is this name being used in the AST as a reference rather than a declaration? * @return boolean */ public boolean isDefinition(); /** * Same as {@link IASTNode#getFileLocation()} * @return the file location of this name. */ public IASTFileLocation getFileLocation(); }
30.071429
83
0.647506
f408ec9a7eda0ebcbb98e4b018fb6c5e0edce583
2,749
/* * Copyright 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 dev.nokee.model.internal.core; import lombok.EqualsAndHashCode; public abstract class ModelComponentReference<T> { public abstract T get(ModelNode entity); public static <T> ModelComponentReference<T> of(Class<T> componentType) { return ofInstance(ModelComponentType.componentOf(componentType)); } public static <T> ModelComponentReference<T> ofInstance(ModelComponentType<T> componentType) { return new OfInstanceReference<>(componentType); } @EqualsAndHashCode(callSuper = false) private static final class OfInstanceReference<T> extends ModelComponentReference<T> implements ModelComponentReferenceInternal { private final ModelComponentType<T> componentType; private OfInstanceReference(ModelComponentType<T> componentType) { this.componentType = componentType; } @Override public boolean isSatisfiedBy(ModelComponentTypes componentTypes) { return componentTypes.contains(componentType); } @Override public boolean isSatisfiedBy(ModelComponentType<?> otherComponentType) { return componentType.equals(otherComponentType); } @Override public T get(ModelNode entity) { return entity.getComponent(componentType); } } public static <T> ModelComponentReference<T> ofAny(ModelComponentType<T> componentType) { return new OfAnyReference<>(componentType); } private static final class OfAnyReference<T> extends ModelComponentReference<T> implements ModelComponentReferenceInternal { private final ModelComponentType<T> componentType; private OfAnyReference(ModelComponentType<T> componentType) { this.componentType = componentType; } @Override public boolean isSatisfiedBy(ModelComponentTypes componentTypes) { return componentTypes.anyMatch(componentType::isSupertypeOf); } @Override public boolean isSatisfiedBy(ModelComponentType<?> otherComponentType) { return componentType.isSupertypeOf(otherComponentType); } @Override public T get(ModelNode entity) { return (T) entity.getComponents().filter(it -> componentType.isSupertypeOf(ModelComponentType.ofInstance(it))).findFirst().orElseThrow(RuntimeException::new); } } }
33.52439
161
0.781375
fa58222bd5742b3a43f255bfc31b63cb1abf521c
596
package cn.org.wyxxt.singleton; /** * @author xingzhiwei * @createBy IntelliJ IDEA * @time 2021/2/23 1:59 下午 * @email [email protected] */ /** * 简单实用,推荐使用 * Class.forName("") */ public class Mgr01 { private static final Mgr01 INSTANCE = new Mgr01(); private Mgr01() { } public static Mgr01 getInstance() { return INSTANCE; } public void m() { System.out.println("m"); } public static void main(String[] args) { Mgr01 m1 = Mgr01.getInstance(); Mgr01 m2 = Mgr01.getInstance(); System.out.println(m1 == m2); } }
17.529412
54
0.583893
d227b7eabe64a12e09fe15cfe0741c556af7792f
12,164
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import com.google.common.collect.ImmutableList; import com.google.common.net.HostAndPort; import io.airlift.units.DataSize; import io.airlift.units.Duration; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.io.orc.OrcFile.OrcTableProperties; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.net.DNSToSwitchMapping; import org.apache.hadoop.net.SocksSocketFactory; import parquet.hadoop.ParquetOutputFormat; import javax.inject.Inject; import javax.net.SocketFactory; import java.io.File; import java.util.List; import static com.facebook.hive.orc.OrcConf.ConfVars.HIVE_ORC_COMPRESSION; import static com.facebook.presto.hive.util.ConfigurationUtils.copy; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.Math.toIntExact; import static java.util.Objects.requireNonNull; import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.COMPRESSRESULT; import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.HIVE_ORC_DEFAULT_COMPRESS; import static org.apache.hadoop.io.SequenceFile.CompressionType.BLOCK; public class HdfsConfigurationUpdater { private final HostAndPort socksProxy; private final Duration ipcPingInterval; private final Duration dfsTimeout; private final Duration dfsConnectTimeout; private final int dfsConnectMaxRetries; private final String domainSocketPath; private final Configuration resourcesConfiguration; private final HiveCompressionCodec compressionCodec; private final int fileSystemMaxCacheSize; private final String s3AwsAccessKey; private final String s3AwsSecretKey; private final String s3Endpoint; private final PrestoS3SignerType s3SignerType; private final boolean s3UseInstanceCredentials; private final boolean s3SslEnabled; private final boolean s3SseEnabled; private final PrestoS3SseType s3SseType; private final String s3EncryptionMaterialsProvider; private final String s3KmsKeyId; private final String s3SseKmsKeyId; private final int s3MaxClientRetries; private final int s3MaxErrorRetries; private final Duration s3MaxBackoffTime; private final Duration s3MaxRetryTime; private final Duration s3ConnectTimeout; private final Duration s3SocketTimeout; private final int s3MaxConnections; private final DataSize s3MultipartMinFileSize; private final DataSize s3MultipartMinPartSize; private final File s3StagingDirectory; private final boolean pinS3ClientToCurrentRegion; private final String s3UserAgentPrefix; @Inject public HdfsConfigurationUpdater(HiveClientConfig hiveClientConfig, HiveS3Config s3Config) { requireNonNull(hiveClientConfig, "hiveClientConfig is null"); checkArgument(hiveClientConfig.getDfsTimeout().toMillis() >= 1, "dfsTimeout must be at least 1 ms"); this.socksProxy = hiveClientConfig.getMetastoreSocksProxy(); this.ipcPingInterval = hiveClientConfig.getIpcPingInterval(); this.dfsTimeout = hiveClientConfig.getDfsTimeout(); this.dfsConnectTimeout = hiveClientConfig.getDfsConnectTimeout(); this.dfsConnectMaxRetries = hiveClientConfig.getDfsConnectMaxRetries(); this.domainSocketPath = hiveClientConfig.getDomainSocketPath(); this.resourcesConfiguration = readConfiguration(hiveClientConfig.getResourceConfigFiles()); this.compressionCodec = hiveClientConfig.getHiveCompressionCodec(); this.fileSystemMaxCacheSize = hiveClientConfig.getFileSystemMaxCacheSize(); this.s3AwsAccessKey = s3Config.getS3AwsAccessKey(); this.s3AwsSecretKey = s3Config.getS3AwsSecretKey(); this.s3Endpoint = s3Config.getS3Endpoint(); this.s3SignerType = s3Config.getS3SignerType(); this.s3UseInstanceCredentials = s3Config.isS3UseInstanceCredentials(); this.s3SslEnabled = s3Config.isS3SslEnabled(); this.s3SseEnabled = s3Config.isS3SseEnabled(); this.s3SseType = s3Config.getS3SseType(); this.s3EncryptionMaterialsProvider = s3Config.getS3EncryptionMaterialsProvider(); this.s3KmsKeyId = s3Config.getS3KmsKeyId(); this.s3SseKmsKeyId = s3Config.getS3SseKmsKeyId(); this.s3MaxClientRetries = s3Config.getS3MaxClientRetries(); this.s3MaxErrorRetries = s3Config.getS3MaxErrorRetries(); this.s3MaxBackoffTime = s3Config.getS3MaxBackoffTime(); this.s3MaxRetryTime = s3Config.getS3MaxRetryTime(); this.s3ConnectTimeout = s3Config.getS3ConnectTimeout(); this.s3SocketTimeout = s3Config.getS3SocketTimeout(); this.s3MaxConnections = s3Config.getS3MaxConnections(); this.s3MultipartMinFileSize = s3Config.getS3MultipartMinFileSize(); this.s3MultipartMinPartSize = s3Config.getS3MultipartMinPartSize(); this.s3StagingDirectory = s3Config.getS3StagingDirectory(); this.pinS3ClientToCurrentRegion = s3Config.isPinS3ClientToCurrentRegion(); this.s3UserAgentPrefix = s3Config.getS3UserAgentPrefix(); } private static Configuration readConfiguration(List<String> resourcePaths) { Configuration result = new Configuration(false); if (resourcePaths == null) { return result; } for (String resourcePath : resourcePaths) { Configuration resourceProperties = new Configuration(false); resourceProperties.addResource(new Path(resourcePath)); copy(resourceProperties, result); } return result; } public void updateConfiguration(Configuration config) { copy(resourcesConfiguration, config); // this is to prevent dfs client from doing reverse DNS lookups to determine whether nodes are rack local config.setClass("topology.node.switch.mapping.impl", NoOpDNSToSwitchMapping.class, DNSToSwitchMapping.class); if (socksProxy != null) { config.setClass("hadoop.rpc.socket.factory.class.default", SocksSocketFactory.class, SocketFactory.class); config.set("hadoop.socks.server", socksProxy.toString()); } if (domainSocketPath != null) { config.setStrings("dfs.domain.socket.path", domainSocketPath); } // only enable short circuit reads if domain socket path is properly configured if (!config.get("dfs.domain.socket.path", "").trim().isEmpty()) { config.setBooleanIfUnset("dfs.client.read.shortcircuit", true); } config.setInt("dfs.socket.timeout", toIntExact(dfsTimeout.toMillis())); config.setInt("ipc.ping.interval", toIntExact(ipcPingInterval.toMillis())); config.setInt("ipc.client.connect.timeout", toIntExact(dfsConnectTimeout.toMillis())); config.setInt("ipc.client.connect.max.retries", dfsConnectMaxRetries); // re-map filesystem schemes to match Amazon Elastic MapReduce config.set("fs.s3.impl", PrestoS3FileSystem.class.getName()); config.set("fs.s3a.impl", PrestoS3FileSystem.class.getName()); config.set("fs.s3n.impl", PrestoS3FileSystem.class.getName()); // set AWS credentials for S3 if (s3AwsAccessKey != null) { config.set(PrestoS3FileSystem.S3_ACCESS_KEY, s3AwsAccessKey); } if (s3AwsSecretKey != null) { config.set(PrestoS3FileSystem.S3_SECRET_KEY, s3AwsSecretKey); } if (s3Endpoint != null) { config.set(PrestoS3FileSystem.S3_ENDPOINT, s3Endpoint); } if (s3SignerType != null) { config.set(PrestoS3FileSystem.S3_SIGNER_TYPE, s3SignerType.name()); } config.setInt("fs.cache.max-size", fileSystemMaxCacheSize); configureCompression(config, compressionCodec); // set config for S3 config.setBoolean(PrestoS3FileSystem.S3_USE_INSTANCE_CREDENTIALS, s3UseInstanceCredentials); config.setBoolean(PrestoS3FileSystem.S3_SSL_ENABLED, s3SslEnabled); config.setBoolean(PrestoS3FileSystem.S3_SSE_ENABLED, s3SseEnabled); config.set(PrestoS3FileSystem.S3_SSE_TYPE, s3SseType.name()); if (s3EncryptionMaterialsProvider != null) { config.set(PrestoS3FileSystem.S3_ENCRYPTION_MATERIALS_PROVIDER, s3EncryptionMaterialsProvider); } if (s3KmsKeyId != null) { config.set(PrestoS3FileSystem.S3_KMS_KEY_ID, s3KmsKeyId); } if (s3SseKmsKeyId != null) { config.set(PrestoS3FileSystem.S3_SSE_KMS_KEY_ID, s3SseKmsKeyId); } config.setInt(PrestoS3FileSystem.S3_MAX_CLIENT_RETRIES, s3MaxClientRetries); config.setInt(PrestoS3FileSystem.S3_MAX_ERROR_RETRIES, s3MaxErrorRetries); config.set(PrestoS3FileSystem.S3_MAX_BACKOFF_TIME, s3MaxBackoffTime.toString()); config.set(PrestoS3FileSystem.S3_MAX_RETRY_TIME, s3MaxRetryTime.toString()); config.set(PrestoS3FileSystem.S3_CONNECT_TIMEOUT, s3ConnectTimeout.toString()); config.set(PrestoS3FileSystem.S3_SOCKET_TIMEOUT, s3SocketTimeout.toString()); config.set(PrestoS3FileSystem.S3_STAGING_DIRECTORY, s3StagingDirectory.toString()); config.setInt(PrestoS3FileSystem.S3_MAX_CONNECTIONS, s3MaxConnections); config.setLong(PrestoS3FileSystem.S3_MULTIPART_MIN_FILE_SIZE, s3MultipartMinFileSize.toBytes()); config.setLong(PrestoS3FileSystem.S3_MULTIPART_MIN_PART_SIZE, s3MultipartMinPartSize.toBytes()); config.setBoolean(PrestoS3FileSystem.S3_PIN_CLIENT_TO_CURRENT_REGION, pinS3ClientToCurrentRegion); config.set(PrestoS3FileSystem.S3_USER_AGENT_PREFIX, s3UserAgentPrefix); } public static void configureCompression(Configuration config, HiveCompressionCodec compressionCodec) { boolean compression = compressionCodec != HiveCompressionCodec.NONE; config.setBoolean(COMPRESSRESULT.varname, compression); config.setBoolean("mapred.output.compress", compression); config.setBoolean(FileOutputFormat.COMPRESS, compression); // For DWRF config.set(HIVE_ORC_DEFAULT_COMPRESS.varname, compressionCodec.getOrcCompressionKind().name()); config.set(HIVE_ORC_COMPRESSION.varname, compressionCodec.getOrcCompressionKind().name()); // For ORC config.set(OrcTableProperties.COMPRESSION.getPropName(), compressionCodec.getOrcCompressionKind().name()); // For RCFile and Text if (compressionCodec.getCodec().isPresent()) { config.set("mapred.output.compression.codec", compressionCodec.getCodec().get().getName()); config.set(FileOutputFormat.COMPRESS_CODEC, compressionCodec.getCodec().get().getName()); } else { config.unset("mapred.output.compression.codec"); config.unset(FileOutputFormat.COMPRESS_CODEC); } // For Parquet config.set(ParquetOutputFormat.COMPRESSION, compressionCodec.getParquetCompressionCodec().name()); // For SequenceFile config.set(FileOutputFormat.COMPRESS_TYPE, BLOCK.toString()); } public static class NoOpDNSToSwitchMapping implements DNSToSwitchMapping { @Override public List<String> resolve(List<String> names) { // dfs client expects an empty list as an indication that the host->switch mapping for the given names are not known return ImmutableList.of(); } @Override public void reloadCachedMappings() { // no-op } } }
47.515625
128
0.731832
0cf729028ef1e509c01a009e7e9c58de9b4d784d
342
/** * This packages contains classes and interface to configure the JEngine. * email templates can be set from here. * And there is an additional REST-Interface. * <p/> * There might be more options in the future: * configuring data attributes for an activity * configuring users and roles */ package de.hpi.bpt.chimera.configuration;
34.2
73
0.751462
267ce9993cf6a453aaadbbf6789a80d9dd6ec95b
9,599
/* * DiSNI: Direct Storage and Networking Interface * * Author: Patrick Stuedi <[email protected]> * * Copyright (C) 2016, IBM Corporation * * 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.ibm.disni.rdma.verbs; // TODO: Auto-generated Javadoc //struct ibv_wc { // uint64_t wr_id; // enum ibv_wc_status status; // enum ibv_wc_opcode opcode; // uint32_t vendor_err; // uint32_t byte_len; // uint32_t imm_data; /* in network byte order */ // uint32_t qp_num; // uint32_t src_qp; // int wc_flags; // uint16_t pkey_index; // uint16_t slid; // uint8_t sl; // uint8_t dlid_path_bits; //}; /** * Represents a work completion event. Application will use the pollCQ verbs call to query for completion events. */ public class IbvWC { public static int CSIZE = 48; public enum IbvWcStatus { IBV_WC_SUCCESS, IBV_WC_LOC_LEN_ERR, IBV_WC_LOC_QP_OP_ERR, IBV_WC_LOC_EEC_OP_ERR, IBV_WC_LOC_PROT_ERR, IBV_WC_WR_FLUSH_ERR, IBV_WC_MW_BIND_ERR, IBV_WC_BAD_RESP_ERR, IBV_WC_LOC_ACCESS_ERR, IBV_WC_REM_INV_REQ_ERR, IBV_WC_REM_ACCESS_ERR, IBV_WC_REM_OP_ERR, IBV_WC_RETRY_EXC_ERR, IBV_WC_RNR_RETRY_EXC_ERR, IBV_WC_LOC_RDD_VIOL_ERR, IBV_WC_REM_INV_RD_REQ_ERR, IBV_WC_REM_ABORT_ERR, IBV_WC_INV_EECN_ERR, IBV_WC_INV_EEC_STATE_ERR, IBV_WC_FATAL_ERR, IBV_WC_RESP_TIMEOUT_ERR, IBV_WC_GENERAL_ERR; public static IbvWcStatus valueOf(int value) { /* this is slow but ok for debugging purposes */ for (IbvWcStatus status : values()) { if (status.ordinal() == value) { return status; } } throw new IllegalArgumentException(); } }; public enum IbvWcOpcode { IBV_WC_SEND(0), IBV_WC_RDMA_WRITE(1), IBV_WC_RDMA_READ(2), IBV_WC_COMP_SWAP(3), IBV_WC_FETCH_ADD(4), IBV_WC_BIND_MW(5), IBV_WC_RECV(128), IBV_WC_RECV_RDMA_WITH_IMM(129); private int opcode; IbvWcOpcode(int opcode) { this.opcode = opcode; } public int getOpcode() { return opcode; } public static IbvWcOpcode valueOf(int value) { for (IbvWcOpcode opcode : values()) { if (opcode.getOpcode() == value) { return opcode; } } throw new IllegalArgumentException(); } } public static int CQ_OK = 0; public static int CQ_EMPTY = -1; public static int CQ_POLL_ERR = -2; protected long wr_id; protected int status; protected int opcode; protected int vendor_err; protected int byte_len; protected int imm_data; /* in network byte order */ protected int qp_num; protected int src_qp; protected int wc_flags; protected short pkey_index; protected short slid; protected short sl; protected short dlid_path_bits; protected int err; protected boolean isSend; protected short wqIndex; protected short tail1; protected short tail2; protected short tail3; protected short diff; protected int wrIndex; protected int sqcqn; public IbvWC() { err = CQ_OK; isSend = false; wqIndex = -1; } public IbvWC clone(){ IbvWC wc = new IbvWC(); wc.byte_len = this.byte_len; wc.diff = this.diff; wc.dlid_path_bits = this.dlid_path_bits; wc.err = this.err; wc.imm_data = this.imm_data; wc.isSend = this.isSend; wc.opcode = this.opcode; wc.pkey_index = this.pkey_index; wc.qp_num = this.qp_num; wc.sl = this.sl; wc.slid = this.slid; wc.wc_flags = this.wc_flags; wc.status = this.status; wc.wqIndex = this.wqIndex; wc.wr_id = this.wr_id; return wc; } /** * Gets the work request id. This matches with the id of IbvSendWR or IbvRecvWR and allows application to refer back to the original work request. * * @return the wr_id */ public long getWr_id() { return wr_id; } /** * Unsupported. * * @param wr_id the new wr_id */ public void setWr_id(long wr_id) { this.wr_id = wr_id; } /** * The status of this work completion. Will be of type IbvWcStatus. * * @return the status */ public int getStatus() { return status; } /** * Unsupported. * * @param status the new status */ public void setStatus(int status) { this.status = status; } /** * Represents the opcode of the original operation for this completion event. * * @return the opcode */ public int getOpcode() { return opcode; } /** * Unsupported. * * @param opcode the new opcode */ public void setOpcode(int opcode) { this.opcode = opcode; } /** * Vendor specific error. * * @return the vendor_err */ public int getVendor_err() { return vendor_err; } /** * Unsupported. * * @param vendor_err the new vendor_err */ public void setVendor_err(int vendor_err) { this.vendor_err = vendor_err; } /** * The number of bytes sent or received. * * @return the byte_len */ public int getByte_len() { return byte_len; } /** * Unsupported. * * @param byte_len the new byte_len */ public void setByte_len(int byte_len) { this.byte_len = byte_len; } /** * Unsupported. * * @return the imm_data */ public int getImm_data() { return imm_data; } /** * Unsupported. * * @param imm_data the new imm_data */ public void setImm_data(int imm_data) { this.imm_data = imm_data; } /** * The identifier of the QP where the work request was originally posted. * * @return the qp_num */ public int getQp_num() { return qp_num; } /** * Unsupported. * * @param qp_num the new qp_num */ public void setQp_num(int qp_num) { this.qp_num = qp_num; } /** * The identifier of the shared receive queue where the work request was originally posted. Unsupported. * * @return the src_qp */ public int getSrc_qp() { return src_qp; } /** * Unsupported. * * @param src_qp the new src_qp */ public void setSrc_qp(int src_qp) { this.src_qp = src_qp; } /** * Unsupported. * * @return the wc_flags */ public int getWc_flags() { return wc_flags; } /** * Unsupported. * * @param wc_flags the new wc_flags */ public void setWc_flags(int wc_flags) { this.wc_flags = wc_flags; } /** * Unsupported. * * @return the pkey_index */ public short getPkey_index() { return pkey_index; } /** * Unsupported. * * @param pkey_index the new pkey_index */ public void setPkey_index(short pkey_index) { this.pkey_index = pkey_index; } /** * Unsupported. * * @return the slid */ public short getSlid() { return slid; } /** * Unsupported. * * @param slid the new slid */ public void setSlid(short slid) { this.slid = slid; } /** * Unsupported. * * @return the sl */ public short getSl() { return sl; } /** * Unsupported. * * @param sl the new sl */ public void setSl(short sl) { this.sl = sl; } /** * Unsupported. * * @return the dlid_path_bits */ public short getDlid_path_bits() { return dlid_path_bits; } /** * Unsupported. * * @param dlid_path_bits the new dlid_path_bits */ public void setDlid_path_bits(short dlid_path_bits) { this.dlid_path_bits = dlid_path_bits; } public String getClassName() { return IbvWC.class.getCanonicalName(); } /** * Unsupported. * * @return the err */ public int getErr() { return err; } /** * Unsupported. * * @param err the new err */ public void setErr(int err) { this.err = err; } /** * Checks if this completion event is due to a send operation. * * @return true, if is send */ public boolean isSend() { return isSend; } /** * Unsupported. * * @param isSend the new send */ public void setSend(boolean isSend) { this.isSend = isSend; } /** * The queue index of this work completion event. * * @return the wq index */ public short getWqIndex() { return wqIndex; } /** * Unsupported. * * @param wqIndex the new wq index */ public void setWqIndex(short wqIndex) { this.wqIndex = wqIndex; } /** * Unsupported. * * @return the tail1 */ public short getTail1() { return tail1; } /** * Unsupported. * * @param tail1 the new tail1 */ public void setTail1(short tail1) { this.tail1 = tail1; } /** * Unsupported. * * @return the tail2 */ public short getTail2() { return tail2; } /** * Unsupported. * * @param tail2 the new tail2 */ public void setTail2(short tail2) { this.tail2 = tail2; } /** * Unsupported. * * @return the tail3 */ public short getTail3() { return tail3; } /** * Unsupported. * * @param tail3 the new tail3 */ public void setTail3(short tail3) { this.tail3 = tail3; } /** * Unsupported. * * @param diff the new diff */ public void setDiff(short diff) { this.diff = diff; } /** * Unsupported. * * @return the diff */ public short getDiff(){ return diff; } /** * Unsupported. * * @return the sqcqn */ public int getSqcqn() { return sqcqn; } /** * Unsupported. * * @param sqcqn the new sqcqn */ public void setSqcqn(int sqcqn) { this.sqcqn = sqcqn; } }
18.353728
486
0.645588
ac442a1d0d503c3eb00d60eb9ecbe8660b9759de
695
/* * Created on 24 Oct 2015 ( Time 23:23:56 ) * Generated by Telosys Tools Generator ( version 2.1.1 ) */ package com.kumasi.journal.web.listitem; import com.kumasi.journal.domain.Entrytype; import com.kumasi.journal.web.common.ListItem; public class EntrytypeListItem implements ListItem { private final String value ; private final String label ; public EntrytypeListItem(Entrytype entrytype) { super(); this.value = "" + entrytype.getId() ; //TODO : Define here the attributes to be displayed as the label this.label = entrytype.toString(); } @Override public String getValue() { return value; } @Override public String getLabel() { return label; } }
18.783784
66
0.71223
858f1a93bf14a10762d569b4e5ff43f789660cef
293
/* * AddCast1.java * * Created on March 12, 2005, 8:10 PM */ package org.netbeans.test.java.hints; /** * * @author lahvac */ public class AddCast1 { /** Creates a new instance of AddCast1 */ public AddCast1() { Object x = null; String s = x; } }
13.318182
45
0.549488
fc906d878f1ea549343f7975b501d073363a6af4
1,887
package org.jboss.rhiot.scoreboard; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; /** * Created by starksm on 6/22/16. */ public class TopScoresController { @FXML private GridPane gridPane; private List<TopScoreController> scoreControllers = new ArrayList<>(); @FXML private void initialize() throws IOException { URL fxml = TopScoreController.class.getResource("topscore.fxml"); for(int row = 0; row < 3; row ++) { for(int col = 0; col < 3; col ++) { FXMLLoader loader = new FXMLLoader(fxml); Pane scorePane = loader.load(); TopScoreController controller = loader.getController(); scoreControllers.add(controller); gridPane.add(scorePane, col, row); int rank = row*3+col; String name = "TBD#"+rank; String address = "00:01:02:03:04:0"+rank; controller.setTopScore(name, address, 0, rank); } } } public synchronized void updateTopScores(List<GameScore> scores) { int last = Math.min(scores.size(), scoreControllers.size()); for (int rank = 0; rank < last; rank ++) { GameScore gs = scores.get(rank); TopScoreController tsc = scoreControllers.get(rank); tsc.updateScore(gs.getName(), gs.getAddress(), gs.getScore()); } } public void updateTopScore(String name, String address, int score, int rank) { TopScoreController tsc = scoreControllers.get(rank); tsc.updateScore(name, address, score); } public GridPane getGridPane() { return gridPane; } }
32.534483
82
0.618972
04bd1aff821da886406544429faea051882718a5
1,687
/* * 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.ambari.logsearch.converter; import org.apache.ambari.logsearch.model.request.impl.BaseLogRequest; import org.apache.ambari.logsearch.model.request.impl.CommonSearchRequest; public class AbstractRequestConverterTest { public void fillBaseLogRequestWithTestData(BaseLogRequest request) { fillCommonRequestWithTestData(request); request.setFrom("2016-09-13T22:00:01.000Z"); request.setTo("2016-09-14T22:00:01.000Z"); request.setMustBe("logsearch_app,secure_log"); request.setMustNot("hst_agent,system_message"); request.setIncludeQuery("[{\"log_message\" : \"myincludemessage\"}]"); request.setExcludeQuery("[{\"log_message\" : \"myexcludemessage\"}]"); } public void fillCommonRequestWithTestData(CommonSearchRequest request) { request.setStartIndex("0"); request.setPage("0"); request.setPageSize("25"); } }
39.232558
74
0.752816
76a56b6209e4c5ffbd8c9f0df4901a242dfa735b
2,622
/* * * 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.comcast.cdn.traffic_control.traffic_router.secure; import org.apache.log4j.Logger; import java.math.BigInteger; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.spec.RSAPrivateCrtKeySpec; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Base64.getDecoder; public class BindPrivateKey { private static final Logger LOGGER = Logger.getLogger(BindPrivateKey.class); private BigInteger decodeBigInt(final String s) { return new BigInteger(1, getDecoder().decode(s.getBytes())); } private Map<String, BigInteger> decodeBigIntegers(final String s) { final List<String> bigIntKeys = Arrays.asList( "Modulus", "PublicExponent", "PrivateExponent", "Prime1", "Prime2", "Exponent1", "Exponent2", "Coefficient" ); final Map<String, BigInteger> bigIntegerMap = new HashMap<>(); for (final String line : s.split("\n")) { final String[] tokens = line.split(": "); if (bigIntKeys.stream().filter(k -> k.equals(tokens[0])).findFirst().isPresent()) { bigIntegerMap.put(tokens[0], decodeBigInt(tokens[1])); } } return bigIntegerMap; } public PrivateKey decode(final String data) { final Map<String, BigInteger> map = decodeBigIntegers(data); final BigInteger modulus = map.get("Modulus"); final BigInteger publicExponent = map.get("PublicExponent"); final BigInteger privateExponent = map.get("PrivateExponent"); final BigInteger prime1 = map.get("Prime1"); final BigInteger prime2 = map.get("Prime2"); final BigInteger exp1 = map.get("Exponent1"); final BigInteger exp2 = map.get("Exponent2"); final BigInteger coeff = map.get("Coefficient"); final RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus,publicExponent,privateExponent,prime1,prime2,exp1,exp2,coeff); try { return KeyFactory.getInstance("RSA").generatePrivate(keySpec); } catch (Exception e) { LOGGER.error("Failed to decode Bind Private Key data: " + e.getMessage(), e); } return null; } }
33.189873
134
0.737223
6cdd85ce48bedd2acaf205d25ce01d9175f1a90a
515
package edu.psu.sweng500.emrms.service; import edu.psu.sweng500.emrms.model.HAuditRecord; import edu.psu.sweng500.emrms.model.Policy; import java.util.List; public interface AuditEventService { public int auditEvent(HAuditRecord auditRecord); public List<Policy> getAuditPolicies(); public List<HAuditRecord> getAuditRecords(String sDateTime, String eDateTime, int polId); public List<HAuditRecord> getAuditRecordsByPolicyId(int polId); public void deleteAuditRecordsByPolicyId(int polId); }
34.333333
93
0.798058
0d547ec410b9a91f937519b7337d813775d2d5cc
1,626
package com.palyrobotics.frc2022.behavior.routines.superstructure.intake; import java.util.*; import com.palyrobotics.frc2022.behavior.TimeoutRoutineBase; import com.palyrobotics.frc2022.robot.Commands; import com.palyrobotics.frc2022.robot.ReadOnly; import com.palyrobotics.frc2022.robot.RobotState; import com.palyrobotics.frc2022.subsystems.Indexer; import com.palyrobotics.frc2022.subsystems.Intake; import com.palyrobotics.frc2022.subsystems.SubsystemBase; /* * This routine will stow the intake, then set it to idle. */ public class IntakeRezeroRoutine extends TimeoutRoutineBase { boolean canFinish = false; public IntakeRezeroRoutine(double duration) { super(duration); } public IntakeRezeroRoutine() { super(0.3); } @Override public void start(Commands commands, @ReadOnly RobotState state) { super.start(commands, state); commands.intakeDeployWantedState = Intake.DeployState.RE_ZERO; // System.out.println("rezero start"); } @Override public boolean checkIfFinishedEarly(@ReadOnly RobotState state) { return false; } @Override protected void update(Commands commands, @ReadOnly RobotState state) { // System.out.println("rezero routine"); // if (commands.intakeDeployWantedState == Intake.DeployState.STOWED) { // canFinish = true; // } } @Override protected void stop(Commands commands, @ReadOnly RobotState state) { //commands.intakeDeployWantedState = Intake.DeployState.STOWED; commands.intakeWantedState = Intake.State.OFF; } @Override public Set<Class<? extends SubsystemBase>> getRequiredSubsystems() { return Set.of(Intake.class, Indexer.class); } }
26.655738
73
0.775523
5f8a914508311ffd358557df314a0a82ff3418a2
308
package com.safou.issueManager.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.safou.issueManager.models.IssueNumeric; import com.safou.issueManager.models.IssueNumericId; public interface IssueNumericRepository extends JpaRepository<IssueNumeric, IssueNumericId> { }
30.8
93
0.857143
1a4650892e0b63ac84f55899894e1bf57a997832
698
/** * T: O(logN) S: O(1) * * <p>Binary search through the array, check if the next element is the same as the current one. If * so - this means that the single element is further into array, if not - it is either current * element or some of the elements before. We only need to check the even indexes to avoid redundant * computation. */ class Solution { public int singleNonDuplicate(int[] nums) { int lo = 0; int hi = nums.length - 1; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (mid % 2 == 1) { mid--; } if (nums[mid] == nums[mid + 1]) { lo = mid + 2; } else { hi = mid; } } return nums[lo]; } }
25.851852
100
0.558739
e82bbeffe69f16ba37bdb6d9eeeb164655bfce96
12,286
/* * Copyright (C) 2017 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.redhat.red.build.finder.report; import static j2html.TagCreator.a; import static j2html.TagCreator.attrs; import static j2html.TagCreator.body; import static j2html.TagCreator.caption; import static j2html.TagCreator.div; import static j2html.TagCreator.document; import static j2html.TagCreator.each; import static j2html.TagCreator.footer; import static j2html.TagCreator.h1; import static j2html.TagCreator.head; import static j2html.TagCreator.header; import static j2html.TagCreator.html; import static j2html.TagCreator.li; import static j2html.TagCreator.main; import static j2html.TagCreator.ol; import static j2html.TagCreator.span; import static j2html.TagCreator.style; import static j2html.TagCreator.table; import static j2html.TagCreator.tbody; import static j2html.TagCreator.td; import static j2html.TagCreator.text; import static j2html.TagCreator.th; import static j2html.TagCreator.thead; import static j2html.TagCreator.title; import static j2html.TagCreator.tr; import static j2html.TagCreator.ul; import java.io.File; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import com.redhat.red.build.finder.BuildFinder; import com.redhat.red.build.finder.KojiBuild; import com.redhat.red.build.finder.KojiLocalArchive; import com.redhat.red.build.koji.model.xmlrpc.KojiArchiveInfo; import com.redhat.red.build.koji.model.xmlrpc.KojiRpmInfo; import com.redhat.red.build.koji.model.xmlrpc.KojiTagInfo; import j2html.attributes.Attr; import j2html.tags.ContainerTag; import j2html.tags.Tag; public class HTMLReport extends Report { private static final String NAME = "Koji Build Finder"; private static final String HTML_STYLE = "" + "body { font-family: Verdana, Helvetica, Arial, sans-serif; font-size: 13px; }\n" + "table { width: 100%; border-style: solid; border-width: 1px; border-collapse: collapse; }\n" + "caption { background: lemonchiffon; caption-side: top; font-weight: bold; font-size: larger; text-align: left; margin-top: 50px; }\n" + "th { border-style: solid; border-width: 1px; background-color: darkgrey; text-align: left; font-weight: bold; }\n" + "tr { border-style: solid; border-width: 1px; }\n" + "tr:nth-child(even) { background-color: lightgrey; }\n" + "td { border-style: solid; border-width: 1px; text-align: left; vertical-align: top; font-size: small; }\n" + "footer { font-size: smaller; }"; private URL kojiwebUrl; private URL pncUrl; private List<KojiBuild> builds; private List<Report> reports; public HTMLReport(File outputDirectory, Collection<File> files, List<KojiBuild> builds, URL kojiwebUrl, URL pncUrl, List<Report> reports) { setName("Build Report for " + files.stream().map(File::getName).collect(Collectors.joining(", "))); setDescription("List of analyzed artifacts whether or not they were found in a Koji build"); setBaseFilename("output"); setOutputDirectory(outputDirectory); this.builds = builds; this.kojiwebUrl = kojiwebUrl; this.pncUrl = pncUrl; this.reports = reports; } private static ContainerTag errorText(String text) { return span(text).withStyle("color: red; font-weight: bold;"); } private Tag<?> linkBuild(KojiBuild build) { int id = build.getBuildInfo().getId(); if (build.isPnc()) { return a().withHref(pncUrl + "/pnc-web/#/projects/" + build.getBuildInfo().getExtra().get("external_project_id") + "/build-configs/" + build.getBuildInfo().getExtra().get("external_build_configuration_id") + "/build-records/" + build.getBuildInfo().getExtra().get("external_build_id")).with(text(Integer.toString(id))); } return a().withHref(kojiwebUrl + "/buildinfo?buildID=" + id).with(text(Integer.toString(id))); } private Tag<?> linkPackage(KojiBuild build) { String name = build.getBuildInfo().getName(); if (build.isPnc()) { return a().withHref(pncUrl + "/pnc-web/#/projects/" + build.getBuildInfo().getExtra().get("external_project_id") + "/build-configs/" + build.getBuildInfo().getExtra().get("external_build_configuration_id")).with(text(name)); } int id = build.getBuildInfo().getPackageId(); return a().withHref(kojiwebUrl + "/packageinfo?packageID=" + id).with(text(name)); } private Tag<?> linkArchive(KojiBuild build, KojiArchiveInfo archive, Collection<String> unmatchedFilenames) { String name = archive.getFilename(); Integer id = archive.getArchiveId(); boolean validId = id != null && id > 0; if (!unmatchedFilenames.isEmpty()) { String archives = String.join(", ", unmatchedFilenames); name += " (unmatched files: " + archives + ")"; } boolean error = !unmatchedFilenames.isEmpty() || build.isImport() || !validId; if (build.isPnc()) { return error ? errorText(name) : a().withHref(pncUrl + "/pnc-web/#/projects/" + build.getBuildInfo().getExtra().get("external_project_id") + "/build-configs/" + build.getBuildInfo().getExtra().get("external_build_configuration_id") + "/build-records/" + build.getBuildInfo().getExtra().get("external_build_id") + "/artifacts").with(text(name)); } String href = "/archiveinfo?archiveID=" + id; if (error) { if (validId) { return a().withHref(kojiwebUrl + href).with(errorText(name)); } return errorText(name); } return a().withHref(kojiwebUrl + href).with(text(name)); } private Tag<?> linkArchive(KojiBuild build, KojiArchiveInfo archive) { return linkArchive(build, archive, Collections.emptyList()); } private Tag<?> linkRpm(KojiBuild build, KojiRpmInfo rpm) { String name = rpm.getName() + "-" + rpm.getVersion() + "-" + rpm.getRelease() + "." + rpm.getArch() + ".rpm"; Integer id = rpm.getId(); String href = "/rpminfo?rpmID=" + id; boolean error = build.isImport() || id <= 0; return error ? errorText(name) : a().withHref(kojiwebUrl + href).with(text(name)); } private Tag<?> linkLocalArchive(KojiBuild build, KojiLocalArchive localArchive) { KojiArchiveInfo archive = localArchive.getArchive(); KojiRpmInfo rpm = localArchive.getRpm(); Collection<String> unmatchedFilenames = localArchive.getUnmatchedFilenames(); if (rpm != null) { return linkRpm(build, rpm); } else if (archive != null) { return linkArchive(build, archive, unmatchedFilenames); } else { return errorText("Error linking local archive with files: " + localArchive.getFilenames()); } } private Tag<?> linkTag(KojiBuild build, KojiTagInfo tag) { int id = tag.getId(); String name = tag.getName(); if (build.isPnc()) { return li(a().withHref(pncUrl + "/pnc-web/#/product/" + build.getBuildInfo().getExtra().get("external_product_id") + "/version/" + build.getBuildInfo().getExtra().get("external_version_id")).with(text(name))); } return li(a().withHref(kojiwebUrl + "/taginfo?tagID=" + id).with(text(name))); } private Tag<?> linkSource(KojiBuild build) { String source = build.getSource(); return span(source); } @Override public ContainerTag toHTML() { return html( head(style().withText(HTML_STYLE)).with( title().withText(getName()) ), body().with( header( h1(getName()) ), main( div(attrs("#div-reports"), table(caption(text("Reports")), thead(tr(th(text("Name")), th(text("Description")))), tbody(tr(td(a().withHref("#div-" + getBaseFilename()).with(text("Builds"))), td(text(getDescription()))), each(reports, report -> tr(td(a().withHref("#div-" + report.getBaseFilename()).with(text(report.getName()))), td(text(report.getDescription()))))))), div(attrs("#div-" + getBaseFilename()), table(caption(text("Builds")), thead(tr(th(text("#")), th(text("ID")), th(text("Name")), th(text("Version")), th(text("Artifacts")), th(text("Tags")), th(text("Type")), th(text("Sources")), th(text("Patches")), th(text("SCM URL")), th(text("Options")), th(text("Extra")))), tbody(each(builds, build -> tr( td(text(Integer.toString(builds.indexOf(build)))), td(build.getBuildInfo().getId() > 0 ? linkBuild(build) : errorText(String.valueOf(build.getBuildInfo().getId()))), td(build.getBuildInfo().getId() > 0 ? linkPackage(build) : text("")), td(build.getBuildInfo().getId() > 0 ? text(build.getBuildInfo().getVersion().replace('_', '-')) : text("")), td(build.getArchives() != null ? ol(each(build.getArchives(), archive -> li(linkLocalArchive(build, archive), text(": "), text(String.join(", ", archive.getFilenames()))))) : text("")), td(build.getTags() != null ? ul(each(build.getTags(), tag -> linkTag(build, tag))) : text("")), td(build.getMethod() != null ? text(build.getMethod()) : build.getBuildInfo().getId() > 0 ? errorText("imported build") : text("")), td(build.getScmSourcesZip() != null ? linkArchive(build, build.getScmSourcesZip()) : text("")), td(build.getPatchesZip() != null ? linkArchive(build, build.getPatchesZip()) : text("")), td(build.getSource() != null ? linkSource(build) : build.getBuildInfo().getId() == 0 ? text("") : errorText("missing URL")), td(build.getTaskInfo() != null && build.getTaskInfo().getMethod() != null && build.getTaskInfo().getMethod().equals("maven") && build.getTaskRequest() != null && build.getTaskRequest().asMavenBuildRequest().getProperties() != null && build.getTaskRequest().asMavenBuildRequest() != null ? each(build.getTaskRequest().asMavenBuildRequest().getProperties().entrySet(), entry -> text(entry.getKey() + (entry.getValue() != null ? "=" + entry.getValue() + "; " : "; "))) : text("")), td(build.getBuildInfo().getExtra() != null ? each(build.getBuildInfo().getExtra().entrySet(), entry -> text(entry.getKey() + (entry.getValue() != null ? "=" + entry.getValue() + "; " : "; "))) : text("")) )) ) )), each(reports, report -> div(attrs("#div-" + report.getBaseFilename()), report.toHTML())) ), div(attrs("#div-footer"), footer().attr(Attr.CLASS, "footer").attr(Attr.ID, "footer").with(text("Created: " + new Date() + " by "), a().withHref("https://github.com/release-engineering/koji-build-finder/").with(text(NAME)), text(" " + BuildFinder.getVersion() + " (SHA: "), a().withHref("https://github.com/release-engineering/koji-build-finder/commit/" + BuildFinder.getScmRevision()).with(text(BuildFinder.getScmRevision() + ")")))) ) ); } @Override public String renderText() { return document().render() + toHTML().render(); } }
51.621849
514
0.621602
813f01c99750670e0485c088e1160bed8bfbea3c
8,300
/* * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.helidon.microprofile.reactive; import java.util.Objects; import java.util.concurrent.Flow.Processor; import java.util.concurrent.Flow.Subscriber; import java.util.concurrent.Flow.Subscription; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import io.helidon.common.reactive.Multi; /** * A processor that once subscribed by the downstream and connected to the upstream, * relays signals between the two. * @param <T> the element type of the flow */ final class DeferredProcessor<T> implements Multi<T>, Processor<T, T>, Subscription { private final AtomicBoolean once = new AtomicBoolean(); private final AtomicReference<Subscription> upstreamDeferred = new AtomicReference<>(); private final AtomicReference<Subscription> upstreamActual = new AtomicReference<>(); private final AtomicLong requested = new AtomicLong(); private final AtomicReference<Subscriber<? super T>> downstream = new AtomicReference<>(); private final AtomicInteger wip = new AtomicInteger(); private Throwable error; @Override public void onSubscribe(Subscription s) { if (downstream.get() != null) { upstreamActual.lazySet(SubscriptionHelper.CANCELED); SubscriptionHelper.deferredSetOnce(upstreamDeferred, requested, s); } else { if (SubscriptionHelper.setOnce(upstreamActual, s)) { if (downstream.get() != null) { if (upstreamActual.compareAndSet(s, SubscriptionHelper.CANCELED)) { SubscriptionHelper.deferredSetOnce(upstreamDeferred, requested, s); } } } } } @Override public void onNext(T t) { Objects.requireNonNull(t, "t is null"); downstream.get().onNext(t); } @Override public void onError(Throwable t) { Objects.requireNonNull(t, "t is null"); error = t; // null -> DONE: deliver onError later // s -> DONE: deliver error now // CANCELED -> DONE_CANCELED: RxJavaPlugins.onError for (;;) { Subscriber<? super T> s = downstream.get(); Subscriber<? super T> u; if (s == TerminatedSubscriber.CANCELED) { u = TerminatedSubscriber.DONE_CANCELED; } else if (s == TerminatedSubscriber.DONE_CANCELED) { break; } else { u = TerminatedSubscriber.DONE; } if (downstream.compareAndSet(s, u)) { if (s == TerminatedSubscriber.CANCELED) { pluginError(t); } else if (s != null) { s.onError(t); } break; } } } @Override public void onComplete() { // null -> DONE: deliver onComplete later // s -> DONE: deliver onComplete now // CANCELED -> DONE_CANCELED -> ignore onComplete for (;;) { Subscriber<? super T> s = downstream.get(); Subscriber<? super T> u; if (s == TerminatedSubscriber.CANCELED) { u = TerminatedSubscriber.DONE_CANCELED; } else if (s == TerminatedSubscriber.DONE_CANCELED) { break; } else { u = TerminatedSubscriber.DONE; } if (downstream.compareAndSet(s, u)) { if (s != null && s != TerminatedSubscriber.CANCELED) { s.onComplete(); } break; } } } boolean isDone() { Subscriber<? super T> s = downstream.get(); return s == TerminatedSubscriber.DONE || s == TerminatedSubscriber.DONE_CANCELED; } @Override public void subscribe( Subscriber<? super T> subscriber) { Objects.requireNonNull(subscriber, "subscriber is null"); if (once.compareAndSet(false, true)) { subscriber.onSubscribe(this); if (downstream.compareAndSet(null, subscriber)) { Subscription s = upstreamActual.get(); if (s != null && s != SubscriptionHelper.CANCELED && upstreamActual.compareAndSet(s, SubscriptionHelper.CANCELED)) { SubscriptionHelper.deferredSetOnce(upstreamDeferred, requested, s); } } else { // CANCELED || DONE_CANCELED : ignore // DONE -> DONE_CANCELED : signal terminal event for (;;) { Subscriber<? super T> s = downstream.get(); if (s == TerminatedSubscriber.CANCELED || s == TerminatedSubscriber.DONE_CANCELED) { break; } if (downstream.compareAndSet(s, TerminatedSubscriber.DONE_CANCELED)) { Throwable ex = error; if (ex != null) { subscriber.onError(ex); } else { subscriber.onComplete(); } break; } } } } else { subscriber.onSubscribe(SubscriptionHelper.EMPTY); subscriber.onError(new IllegalStateException("Only one Subscriber allowed")); } } @Override public void request(long n) { if (n <= 0L && upstreamDeferred.get() == null) { onError(new IllegalArgumentException("Rule §3.9 violated: non-positive requests are forbidden")); } else { SubscriptionHelper.deferredRequest(upstreamDeferred, requested, n); } } @Override public void cancel() { // null -> CANCEL : do nothing // s -> CANCEL : do nothing // DONE -> DONE_CANCEL : RxJavaPlugins.onError if error != null for (;;) { Subscriber<? super T> s = downstream.get(); Subscriber<? super T> u; if (s == TerminatedSubscriber.CANCELED || s == TerminatedSubscriber.DONE_CANCELED) { break; } if (s == TerminatedSubscriber.DONE) { u = TerminatedSubscriber.DONE_CANCELED; } else { u = TerminatedSubscriber.CANCELED; } if (downstream.compareAndSet(s, u)) { if (s == TerminatedSubscriber.DONE) { Throwable ex = error; if (ex != null) { pluginError(ex); } } break; } } SubscriptionHelper.cancel(upstreamActual); SubscriptionHelper.cancel(upstreamDeferred); } enum TerminatedSubscriber implements Subscriber<Object> { DONE, CANCELED, DONE_CANCELED; @Override public void onSubscribe(Subscription s) { // deliberately no-op } @Override public void onNext(Object t) { // deliberately no-op } @Override public void onError(Throwable t) { // deliberately no-op } @Override public void onComplete() { // deliberately no-op } } static void pluginError(Throwable ex) { Thread t = Thread.currentThread(); t.getUncaughtExceptionHandler().uncaughtException(t, ex); } }
34.439834
109
0.557108
32bf6fc11f543c24de48e2ea716ecad5ca24d1d6
1,090
package com.fererlab.wowzajersey.core.controller; import com.fererlab.wowzajersey.core.config.Configurable; import com.fererlab.wowzajersey.app.model.Client; import com.fererlab.wowzajersey.app.model.HttpSession; /** * Controller for module operations */ public interface ModuleController extends Controller, Configurable { /** * this method calls an authenticator and returns its result * * @param client {@link Client} * @return true if client is authenticated, otherwise false */ boolean authorizeClient(Client client); /** * this method calls an authorizer and returns its result * * @param httpSession {@link HttpSession} * @return true if httpSession is authorized, otherwise false */ boolean authenticateHttpSession(HttpSession httpSession); /** * handle client connect * * @param client {@link Client} */ void clientConnected(Client client); /** * handle client disconnect * * @param client {@link Client} */ void clientDisconnected(Client client); }
25.348837
68
0.686239
b8ab8e17f28f248a56d5c8fa9b3f9d320c18f214
17,341
package guis; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListSelectionModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import gameplay.Company; import gameplay.GameFrame; import gameplay.User; import listeners.TableModel; import listeners.TextFieldFocusListener; import messages.AuctionBidUpdateMessage; import utility.AppearanceConstants; import utility.AppearanceSettings; import utility.Constants; /* * Author: Danny Pan */ public class AuctionBidScreen extends JPanel { /** * */ private static final long serialVersionUID = 1L; private JLabel timer, companyPicture, companyName, minimumBid, maximumBidLabel, maximumBidIcon, maximumBidAmount; private JTable companyStatistics; private JTextArea companyBio; private JLabel[] firmPicture, firmName, firmBid; private JButton bidButton; private JTextField bidAmount; private JPanel[] firmPanels; public Company company; private GameFrame gameFrame; private double bidAmountNumber[]; public double bidMin; private Vector<User> userVect; public String currentBidder; public AuctionBidScreen(GameFrame gameFrame, Company company){ this.company = company; this.gameFrame = gameFrame; initializeVariables(); createGUI(); addActionListeners(); this.bidMin = company.getAskingPrice(); bidButton.setEnabled(false); System.out.println(bidMin); } private void initializeVariables(){ bidAmountNumber = new double[4]; //Timer Panel timer = new JLabel("0:45"); //Middle Panel Variables companyPicture = new JLabel(); companyPicture.setIcon(new ImageIcon(company.getCompanyLogo().getScaledInstance((int)(150*company.getAspectRatio()), 150, Image.SCALE_SMOOTH))); companyName = new JLabel(company.getName()); minimumBid = new JLabel("Minimum Bid: " + String.format("%.2f", company.getAskingPrice()) + Constants.million); companyBio = new JTextArea(company.getDescription()); companyBio.setLineWrap(true); companyBio.setWrapStyleWord(true); companyBio.setEditable(false); //Table code Object[][] companyData = { {"Name", company.getName()}, {"Tier", company.getTierLevel()}, {"Current Worth", company.getCurrentWorth()}, }; String[] columnNames = {"",""}; TableModel dtm = new TableModel(); dtm.setDataVector(companyData, columnNames); companyStatistics = new JTable(dtm); companyStatistics.setForeground(AppearanceConstants.darkBlue); companyStatistics.setFont(AppearanceConstants.fontSmallest); companyStatistics.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION); //Firm bidding panel Variables intializeFirms(); bidButton = new JButton("BID"); bidAmount = new JTextField(); maximumBidAmount = new JLabel(); maximumBidLabel = new JLabel("CURRENT MAX BID"); maximumBidIcon = new JLabel(); } //Function to allocate information for each user. //This is probably going to be rewritten once the back end is connected. private void intializeFirms(){ //I'll auto allocate 4 for spacing purposes and then just hide unused ones firmPicture = new JLabel[4]; firmName = new JLabel[4]; firmBid = new JLabel[4]; for(int i = 0; i < 4; i++){ firmPicture[i] = new JLabel(); firmName[i] = new JLabel(""); firmBid[i] = new JLabel(""); AppearanceSettings.setBackground(AppearanceConstants.darkBlue, firmPicture[i],firmName[i],firmBid[i]); AppearanceSettings.setForeground(AppearanceConstants.offWhite,firmName[i],firmBid[i]); firmName[i].setFont(AppearanceConstants.fontFirmName); firmBid[i].setFont(AppearanceConstants.fontBidAmount); AppearanceSettings.setCenterAlignment(firmPicture[i],firmName[i],firmBid[i]); AppearanceSettings.setSize(100,100,firmPicture[i]); firmPicture[i].setMaximumSize(new Dimension(100,100)); firmName[i].setBorder(new EmptyBorder(5,5,5,5)); firmBid[i].setBorder(new EmptyBorder(5,5,5,5)); } userVect = gameFrame.game.getUsers(); int i = 0; int j = 0; while(i < 4){ if (j < userVect.size()){ if (i == 0){ firmPicture[i].setIcon(new ImageIcon(gameFrame.user.getUserIcon().getScaledInstance(100, 100, Image.SCALE_SMOOTH))); firmName[i].setText(gameFrame.user.getCompanyName()); firmBid[i].setText("0 Million"); i++; } else if (!userVect.get(j).getUsername().equals(gameFrame.user.getUsername())){ firmPicture[i].setIcon(new ImageIcon(userVect.get(j).getUserIcon().getScaledInstance(100, 100, Image.SCALE_SMOOTH))); firmName[i].setText(userVect.get(j).getCompanyName()); firmBid[i].setText("0 Million"); i++; j++; }else{ j++; } } else{ firmPicture[i].setText(""); firmName[i].setText(""); firmBid[i].setText(""); i++; } } } private void createGUI(){ //Size accounts for chat window setPreferredSize(new Dimension(1280,504)); setBackground(AppearanceConstants.lightBlue); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); JPanel timePanel = createTimePanel(); JPanel companyInfoPanel = createCompanyInfoPanel(); JPanel firmBiddingPanel = createFirmBiddingPanel(); add(Box.createGlue()); add(timePanel); add(Box.createGlue()); add(companyInfoPanel); add(Box.createGlue()); add(firmBiddingPanel); add(Box.createGlue()); } private JPanel createTimePanel(){ JPanel timePanel = new JPanel(); timePanel.setLayout(new BoxLayout(timePanel,BoxLayout.PAGE_AXIS)); timePanel.setBackground(AppearanceConstants.darkBlue); timePanel.setPreferredSize(new Dimension(200,60)); timePanel.setMaximumSize(new Dimension(200,60)); timer.setForeground(AppearanceConstants.offWhite); timer.setFont(AppearanceConstants.fontTimerMedium); AppearanceSettings.setCenterAlignment(timer); timePanel.add(timer); return timePanel; } private JPanel createCompanyInfoPanel(){ JPanel companyInfoPanel = new JPanel(); JPanel companyLabelsPanel = new JPanel(); JPanel companyStatisticsPanel = new JPanel(); JScrollPane companyTablePane = new JScrollPane(companyStatistics); JScrollPane companyBioPane = new JScrollPane(companyBio); JLabel statisticsLabel = new JLabel("Statistics"); //remove borders companyTablePane.setFocusable(false); companyTablePane.setBorder(BorderFactory.createEmptyBorder()); companyTablePane.getViewport().setBackground(AppearanceConstants.darkBlue); companyBioPane.setFocusable(false); companyBioPane.setBorder(new EmptyBorder(5,5,5,5)); //Set padding companyName.setBorder(new EmptyBorder(5,5,5,5)); minimumBid.setBorder(new EmptyBorder(5,5,5,5)); companyStatistics.setBorder(new EmptyBorder(5,5,5,5)); //Set layouts AppearanceSettings.setBoxLayout(BoxLayout.PAGE_AXIS, companyStatisticsPanel); AppearanceSettings.setBoxLayout(BoxLayout.LINE_AXIS, companyInfoPanel); companyLabelsPanel.setLayout(new BorderLayout()); //Set Sizes AppearanceSettings.setSize(1200, 200, companyInfoPanel); companyInfoPanel.setMaximumSize(new Dimension(1200, 200)); AppearanceSettings.setSize(600, 150, companyLabelsPanel); companyLabelsPanel.setMaximumSize(new Dimension(600, 150)); AppearanceSettings.setSize(300, 150, companyTablePane); companyBioPane.setMaximumSize(new Dimension(300, 150)); AppearanceSettings.setSize(300, 200, companyStatisticsPanel); companyStatisticsPanel.setMaximumSize(new Dimension(300, 200)); AppearanceSettings.setBackground(AppearanceConstants.darkBlue, companyInfoPanel,companyLabelsPanel, companyTablePane, companyBioPane, companyBio, companyStatisticsPanel,statisticsLabel); AppearanceSettings.setForeground(AppearanceConstants.offWhite, companyName, companyBio, minimumBid, statisticsLabel); AppearanceSettings.setFont(AppearanceConstants.fontSmall,companyName, minimumBid, statisticsLabel); AppearanceSettings.setCenterAlignment(statisticsLabel); companyBio.setFont(AppearanceConstants.fontSmallest); companyLabelsPanel.add(companyName, BorderLayout.NORTH); companyLabelsPanel.add(companyBioPane, BorderLayout.CENTER); companyLabelsPanel.add(minimumBid, BorderLayout.SOUTH); AppearanceSettings.addGlue(companyStatisticsPanel, BoxLayout.PAGE_AXIS, true, statisticsLabel, companyTablePane); AppearanceSettings.addGlue(companyInfoPanel, BoxLayout.LINE_AXIS, true, companyPicture, companyLabelsPanel); companyInfoPanel.add(companyStatisticsPanel); companyInfoPanel.add(Box.createHorizontalStrut(30)); return companyInfoPanel; } private JPanel createFirmBiddingPanel(){ JPanel firmBiddingPanel = new JPanel(); firmPanels = new JPanel[4]; JPanel maxBidPanel = new JPanel(); JPanel maxBidFirmPanel = new JPanel(); //Set Sizes AppearanceSettings.setSize(1200, 200, firmBiddingPanel); firmBiddingPanel.setMaximumSize(new Dimension(1200,200)); AppearanceSettings.setSize(300, 200, maxBidPanel); maxBidPanel.setMaximumSize(new Dimension(300,150)); //Set Layouts AppearanceSettings.setBoxLayout(BoxLayout.LINE_AXIS, firmBiddingPanel, maxBidFirmPanel); AppearanceSettings.setBoxLayout(BoxLayout.PAGE_AXIS, maxBidPanel); //Set Appearance Settings AppearanceSettings.setForeground(AppearanceConstants.offWhite, maximumBidAmount, maximumBidLabel); AppearanceSettings.setBackground(AppearanceConstants.lightBlue, firmBiddingPanel); AppearanceSettings.setBackground(AppearanceConstants.darkBlue, maxBidPanel, maxBidFirmPanel); AppearanceSettings.setFont(AppearanceConstants.fontSmall, maximumBidAmount, maximumBidLabel); AppearanceSettings.setCenterAlignment(maximumBidLabel); //Create all the user and their max bids createFirmsPanels(firmBiddingPanel); maxBidFirmPanel.add(Box.createHorizontalStrut(20)); AppearanceSettings.addGlue(maxBidFirmPanel, BoxLayout.LINE_AXIS, false, maximumBidIcon, maximumBidAmount); maxBidPanel.add(Box.createVerticalStrut(20)); AppearanceSettings.addGlue(maxBidPanel, BoxLayout.PAGE_AXIS, false, maximumBidLabel, maxBidFirmPanel); //Add AppearanceSettings.addGlue(firmBiddingPanel, BoxLayout.LINE_AXIS, true, firmPanels[0], firmPanels[1], maxBidPanel, firmPanels[2], firmPanels[3]); return firmBiddingPanel; } private void createFirmsPanels(JPanel firmBiddingPanel){ //Constructing each firm's auction Icon //I can write a if statement that makes the selected user for(int i = 0; i < 4; i++){ firmPanels[i] = new JPanel(); AppearanceSettings.setBoxLayout(BoxLayout.PAGE_AXIS, firmPanels[i]); AppearanceSettings.setBackground(AppearanceConstants.lightBlue, firmPanels[i]); AppearanceSettings.setSize(150, 200, firmPanels[i]); firmPanels[i].add(firmName[i]); firmPanels[i].add(Box.createVerticalStrut(5)); firmPanels[i].add(firmPicture[i]); firmPanels[i].add(Box.createVerticalStrut(5)); if (i == 0){ JPanel buttonTextPanel = new JPanel(); buttonTextPanel.setLayout(new BoxLayout(buttonTextPanel,BoxLayout.LINE_AXIS)); AppearanceSettings.setSize(150, 30, buttonTextPanel); JPanel buttonPanel = new JPanel(); //buttonPanel.setLayout(new BorderLayout()); bidButton.setOpaque(true); bidButton.setForeground(AppearanceConstants.offWhite); bidButton.setFont(AppearanceConstants.fontSmallBidButton); bidButton.setBackground(new Color(51,102,0)); bidButton.setBorderPainted(false); bidButton.setVerticalAlignment(SwingConstants.TOP); buttonPanel.setMinimumSize(new Dimension(40,30)); buttonPanel.setMaximumSize(new Dimension(40,30)); buttonPanel.add(bidButton); JPanel textPanel = new JPanel(); textPanel.setLayout(new BorderLayout()); AppearanceSettings.setBackground(AppearanceConstants.lightBlue, textPanel, buttonPanel); textPanel.setMinimumSize(new Dimension(100,30)); textPanel.setMaximumSize(new Dimension(100,30)); textPanel.add(bidAmount); buttonTextPanel.add(textPanel); buttonTextPanel.add(buttonPanel, BorderLayout.CENTER); firmPanels[i].add(buttonTextPanel); } else{ firmPanels[i].add(firmBid[i]); } } } private void addActionListeners(){ bidButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { int amount = (int) (Double.parseDouble(bidAmount.getText().trim()) * 100); double amount2 = ((double) amount) / 100; gameFrame.getClient().sendMessage(new AuctionBidUpdateMessage(gameFrame.user.getCompanyName(), amount2)); bidAmount.setText(""); } }); bidAmount.addFocusListener(new TextFieldFocusListener("Enter Bid", bidAmount)); bidAmount.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { int intBidAmount = (int) (Double.parseDouble(bidAmount.getText().trim()) * 100); int intBidMin = (int) (bidMin * 100); int intCurrentCapital = (int) (gameFrame.user.getCurrentCapital() * 100); boolean greaterThanCurrent = intBidAmount > intBidMin; boolean lessThanBank = intCurrentCapital >= intBidAmount; if (greaterThanCurrent && lessThanBank) { int amount = (int) (Double.parseDouble(bidAmount.getText().trim()) * 100); double amount2 = ((double) amount) / 100; gameFrame.getClient().sendMessage(new AuctionBidUpdateMessage(gameFrame.user.getCompanyName(), amount2)); } bidAmount.setText(""); } } }); bidAmount.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { changed(); } @Override public void removeUpdate(DocumentEvent e) { changed(); } @Override public void changedUpdate(DocumentEvent e) { changed(); } private void changed() { try { if (bidAmount.getText().equals("Enter Bid") || bidAmount.getText().trim().isEmpty()) { bidButton.setEnabled(false); } else { int intBidAmount = (int) (Double.parseDouble(bidAmount.getText().trim()) * 100); int intBidMin = (int) (bidMin * 100); int intCurrentCapital = (int) (gameFrame.user.getCurrentCapital() * 100); boolean greaterThanCurrent = intBidAmount > intBidMin; boolean lessThanBank = intCurrentCapital >= intBidAmount; bidButton.setEnabled(greaterThanCurrent && lessThanBank); } } catch (NumberFormatException nfe) { bidButton.setEnabled(false); } } }); } public void setCompany(Company company) { this.company = company; } public void refresh() { companyName.setText(company.getName()); minimumBid.setText("Minimum Bid: " + String.format("%.2f", company.getAskingPrice()) + Constants.million); companyBio.setText(company.getDescription()); companyPicture.setIcon(new ImageIcon(company.getCompanyLogo().getScaledInstance((int)(150*company.getAspectRatio()), 150, Image.SCALE_SMOOTH))); Object[][] companyData = { {"Name", company.getName()}, {"Tier", company.getTierLevel()}, {"Current Worth", company.getCurrentWorth()}, }; String[] columnNames = {"",""}; TableModel dtm = new TableModel(); dtm.setDataVector(companyData, columnNames); companyStatistics.setModel(dtm); maximumBidAmount.setText(""); maximumBidIcon.setIcon(null); maximumBidIcon.revalidate(); for(int i = 0; i < 4; i++){ firmBid[i].setText(""); } } public void updateBet(String companyName, double amount){ int index = 0; for(int i = 0; i < 4; i++){ if(firmName[i].getText().equals(companyName)){ index = i; break; } } bidAmountNumber[index] = amount; firmBid[index].setText(String.format("%.2f", amount) + Constants.million); bidMin = amount; findMaxBet(companyName); currentBidder = companyName; } private void findMaxBet(String companyName){ // int maxBetIndex = 0; // for(int i = 0; i < 4; i++){ // if(bidAmountNumber[0] > bidAmountNumber[i]){ // maxBetIndex = i; // } // } maximumBidAmount.setText(String.format("%.2f", bidMin) + Constants.million); // for(int i = 0; i < userVect.size(); i++){ // if(userVect.get(i).getCompanyName().equals(firmName[maxBetIndex].getText())){ // maximumBidIcon.setIcon(new ImageIcon(userVect.get(i).getUserIcon().getScaledInstance(75, 75, Image.SCALE_SMOOTH))); // } // } for(User user : gameFrame.getClient().getUsers()) { if (user.getCompanyName().equals(companyName)) { maximumBidIcon.setIcon(new ImageIcon(user.getUserIcon().getScaledInstance(75, 75, Image.SCALE_SMOOTH))); } } } public void updateTimer(String display) { timer.setText(display); this.revalidate(); this.repaint(); } }
34.682
146
0.736117
de040f6769eab38a695ba062cd6ffdd65d11c53e
5,469
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual 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 org.hibernate.validator.test.internal.constraintvalidators; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.hibernate.validator.constraints.SafeHtml; import org.hibernate.validator.constraints.SafeHtml.WhiteListType; import org.hibernate.validator.internal.constraintvalidators.SafeHtmlValidator; import org.hibernate.validator.internal.util.annotationfactory.AnnotationDescriptor; import org.hibernate.validator.internal.util.annotationfactory.AnnotationFactory; import org.hibernate.validator.testutil.TestForIssue; import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertNumberOfViolations; import static org.hibernate.validator.testutil.ValidatorUtil.getValidator; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /** * Unit test for {@link SafeHtmlValidator}. * * @author George Gastaldi * @author Hardy Ferentschik */ public class SafeHtmlValidatorTest { private AnnotationDescriptor<SafeHtml> descriptor; @BeforeMethod public void setUp() { descriptor = new AnnotationDescriptor<SafeHtml>( SafeHtml.class ); } @Test public void testNullValue() throws Exception { descriptor.setValue( "whitelistType", WhiteListType.BASIC ); assertTrue( getSafeHtmlValidator().isValid( null, null ) ); } @Test public void testInvalidScriptTagIncluded() throws Exception { descriptor.setValue( "whitelistType", WhiteListType.BASIC ); assertFalse( getSafeHtmlValidator().isValid( "Hello<script>alert('Doh')</script>World !", null ) ); } @Test public void testValid() throws Exception { descriptor.setValue( "whitelistType", WhiteListType.BASIC ); assertTrue( getSafeHtmlValidator().isValid( "<p><a href='http://example.com/'>Link</a></p>", null ) ); } @Test public void testAdditionalTags() throws Exception { descriptor.setValue( "additionalTags", new String[] { "script" } ); assertTrue( getSafeHtmlValidator().isValid( "Hello<script>alert('Doh')</script>World !", null ) ); } @Test @TestForIssue(jiraKey = "HV-817") public void testDivNotAllowedInBasicWhiteList() throws Exception { descriptor.setValue( "whitelistType", WhiteListType.BASIC ); SafeHtmlValidator validator = getSafeHtmlValidator(); assertFalse( validator.isValid( "<div>test</div>", null ) ); } @Test @TestForIssue(jiraKey = "HV-817") public void testDivAllowedInRelaxedWhiteList() throws Exception { descriptor.setValue( "whitelistType", WhiteListType.RELAXED ); assertTrue( getSafeHtmlValidator().isValid( "<div>test</div>", null ) ); } @Test @TestForIssue(jiraKey = "HV-817") public void testDivWithWhiteListedClassAttribute() throws Exception { descriptor.setValue( "whitelistType", WhiteListType.RELAXED ); AnnotationDescriptor<SafeHtml.Tag> tagDescriptor = new AnnotationDescriptor<SafeHtml.Tag>( SafeHtml.Tag.class ); tagDescriptor.setValue( "name", "div" ); tagDescriptor.setValue( "attributes", new String[] { "class" } ); SafeHtml.Tag tag = AnnotationFactory.create( tagDescriptor ); descriptor.setValue( "additionalTagsWithAttributes", new SafeHtml.Tag[] { tag } ); assertTrue( getSafeHtmlValidator().isValid( "<div class='foo'>test</div>", null ), "class attribute should be white listed" ); assertFalse( getSafeHtmlValidator().isValid( "<div style='foo'>test</div>", null ), "style attribute is not white listed" ); } @Test @TestForIssue(jiraKey = "HV-817") public void testDivWithWhiteListedStyleAttribute() throws Exception { Validator validator = getValidator(); Set<ConstraintViolation<Foo>> constraintViolations = validator.validate( new Foo( "<div style='foo'>test</div>" ) ); assertNumberOfViolations( constraintViolations, 0 ); // the attributes are optional - allowing <div class> also allows just <div> constraintViolations = validator.validate( new Foo( "<div>test</div>" ) ); assertNumberOfViolations( constraintViolations, 0 ); constraintViolations = validator.validate( new Foo( "<div class='foo'>test</div>" ) ); assertNumberOfViolations( constraintViolations, 1 ); } private SafeHtmlValidator getSafeHtmlValidator() { SafeHtml p = AnnotationFactory.create( descriptor ); SafeHtmlValidator validator = new SafeHtmlValidator(); validator.initialize( p ); return validator; } public static class Foo { @SafeHtml( whitelistType = WhiteListType.BASIC, additionalTagsWithAttributes = @SafeHtml.Tag(name = "div", attributes = { "style" }) ) String source; public Foo(String source) { this.source = source; } } }
35.745098
118
0.756445
f8420bf14891ecd8ea011f2608c804220ae436ba
5,397
package com.ptoceti.osgi.modbus.impl; /* * #%L * ********************************************************************** * ORGANIZATION : ptoceti * PROJECT : Modbus * FILENAME : Activator.java * * This file is part of the Ptoceti project. More information about * this project can be found here: http://www.ptoceti.com/ * ********************************************************************** * %% * Copyright (C) 2013 - 2015 ptoceti * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceEvent; import org.osgi.framework.BundleException; import org.osgi.framework.InvalidSyntaxException; import org.osgi.service.log.LogService; /** * Activator class implement the BundleActivator interface. This class load the bundle in the framework. * Its main task is to create an instance of the ModbusDriverFactory ans ask it to register itself in the * the framework. * * @author Laurent Thil * @version 1.0b */ public class Activator implements BundleActivator { // a reference to this service bundle context. static BundleContext bc = null; // a reference to the logging service. static LogService logSer; // the name of the logging service in the osgi framework. static private final String logServiceName = org.osgi.service.log.LogService.class.getName(); // a reference to the ModbusDriverFactory service created by this bundle. private ModbusDriverFactory modbusDFact = null; /** * Called by the framework for initialisation when the Activator class is loaded. * The method first get a service reference on the osgi logging service, used for * logging whithin the bundle. Then it creates an instance of the ModbusDriverFactory * and asks it to register itself. * * If the method cannot get a reference to the logging service, a NullPointerException is thrown. * Similarly, a BundleException exception is thrown if the ModbusDriverFactory cannot be started. * @param context the bundle context * @throws BundleException thrown when factory could not be instanciated */ public void start(BundleContext context) throws BundleException { Activator.bc = context; // we construct a listener to detect if the log service appear or disapear. String filter = "(objectclass=" + logServiceName + ")"; ServiceListener logServiceListener = new LogServiceListener(); try { bc.addServiceListener( logServiceListener, filter); // in case the service is already registered, we send a REGISTERED event to its listener. ServiceReference srLog = bc.getServiceReference( logServiceName ); if( srLog != null ) { logServiceListener.serviceChanged(new ServiceEvent( ServiceEvent.REGISTERED, srLog )); } } catch ( InvalidSyntaxException e ) { throw new BundleException("Error in filter string while registering LogServiceListener." + e.toString()); } log(LogService.LOG_INFO, "Starting version " + bc.getBundle().getHeaders().get("Bundle-Version")); try { modbusDFact = new ModbusDriverFactory(); } catch ( Exception e ) { throw new BundleException( e.toString() ); } } /** * Called by the framework when the bundle is stopped. The method first forward the stop * message to the ModbusDriverFactory instance, then stop the log service. * * @param context the bundle context */ public void stop( BundleContext context ) { if( modbusDFact != null ) modbusDFact.stop(); log(LogService.LOG_INFO, "Stopping"); Activator.bc = null; } /** * Class method for logging to the logservice. This method can be accessed from every class * in the bundle by simply invoking Activator.log(..). * * @param logLevel : the level to use when togging this message. * @param message : the message to log. */ static public void log( int logLevel, String message ) { if( logSer != null ) logSer.log( logLevel, message ); } /** * Internel listener class that receives framework event when the log service is registered * in the the framework and when it is being removed from it. The framework is a dynamic place * and it is important to note when services appear and disappear. * This inner class update the outer class reference to the log service in concordance. * */ public class LogServiceListener implements ServiceListener { /** * Unique method of the ServiceListener interface. * */ public void serviceChanged( ServiceEvent event ) { ServiceReference sr = event.getServiceReference(); switch(event.getType()) { case ServiceEvent.REGISTERED: { logSer = (LogService) bc.getService(sr); } break; case ServiceEvent.UNREGISTERING: { logSer = null; } break; } } } }
35.27451
108
0.710395
42d49499d822c0c7273fd8ca6d5b99bb21515028
9,196
/******************************************************************************* * Copyright (c) 2010-2011 VIVO Harvester Team. For full list of contributors, please see the AUTHORS file provided. * All rights reserved. * This program and the accompanying materials are made available under the terms of the new BSD license which accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.html ******************************************************************************/ package org.vivoweb.harvester.translate; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vivoweb.harvester.util.InitLog; import org.vivoweb.harvester.util.args.ArgDef; import org.vivoweb.harvester.util.args.ArgList; import org.vivoweb.harvester.util.args.ArgParser; import org.vivoweb.harvester.util.args.UsageException; import org.vivoweb.harvester.util.repo.Record; import org.vivoweb.harvester.util.repo.RecordHandler; import com.hp.gloze.Gloze; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; /** * Gloze Tranlator This class translates XML into its own natural RDF ontology using the gloze library. Translation into * the VIVO ontology is completed using the RDF Translator. TODO Stephen: Identify additional parameters required for * translation TODO Stephen: Identify methods to invoke in the gloze library * @author Stephen V. Williams [email protected] */ public class GlozeTranslator { /** * the log property for logging errors, information, debugging */ private static Logger log = LoggerFactory.getLogger(GlozeTranslator.class); /** * the file to be translated FIXME Stephen: remove this and use the incoming stream */ protected File incomingXMLFile; /** * The incoming schema to help gloze translate the xml file */ protected File incomingSchema; /** * the uri base for relative nodes in the xml file */ protected URI uriBase; /** * in stream is the stream containing the file (xml) that we are going to translate */ private InputStream inStream; /** * out stream is the stream that the controller will be handling and were we will dump the translation */ private OutputStream outStream; /** * record handler for incoming records */ protected RecordHandler inStore; /** * record handler for storing records */ protected RecordHandler outStore; /** * Constructor * @param args commandline arguments * @throws IOException error parsing options * @throws UsageException user requested usage message */ private GlozeTranslator(String... args) throws IOException, UsageException { this(getParser().parse(args)); } /** * @param argList <ul> * <li><em>inRecordHandler</em> the incoming record handler when record handlers are due</li> * <li><em>schema</em> the incoming schema for gloze translation</li> * <li><em>outRecordHandler</em> the out record handler</li> * <li><em>uriBase</em> required for gloze translation the unset URIBASE used is * http://vivoweb.org/glozeTranslation/noURI/</li> * </ul> * @throws IOException error connecting to record handlers */ private GlozeTranslator(ArgList argList) throws IOException { this( argList.get("u"), argList.get("z"), RecordHandler.parseConfig(argList.get("i"), argList.getValueMap("I")), RecordHandler.parseConfig(argList.get("o"), argList.getValueMap("O")) ); } /** * Constructor * @param uriBase the base for all URIs generated * @param xmlSchema the xml schema for gloze to use while translating * @param inStore the input recordhandler * @param outStore the output recordhandler */ public GlozeTranslator(String uriBase, String xmlSchema, RecordHandler inStore, RecordHandler outStore) { if(uriBase == null) { throw new IllegalArgumentException("Must provide a uri base"); } setURIBase(uriBase); if(xmlSchema == null) { throw new IllegalArgumentException("Must provide a xml schema"); } setIncomingSchema(new File(xmlSchema));//FIXME: use FileAide and Streams! if(inStore == null) { throw new IllegalArgumentException("Must provide an input recordhandler"); } this.inStore = inStore; if(outStore == null) { throw new IllegalArgumentException("Must provide an output recordhandler"); } this.outStore = outStore; } /** * Setter for xmlFile * @param xmlFile the file to translate */ public void setIncomingXMLFile(File xmlFile) { this.incomingXMLFile = xmlFile; } /** * Setter for schema * @param schema the schema that gloze can use, but doesn't need to translate the xml */ public void setIncomingSchema(File schema) { this.incomingSchema = schema; } /** * Setter for uriBase * @param base the base uri to apply to all relative entities */ public void setURIBase(String base) { try { this.uriBase = new URI(base); } catch(URISyntaxException e) { throw new IllegalArgumentException(e); } } /** * The main translation method for the gloze translation class setups up the necessary conditions for using the * gloze library then executes its translation class */ public void translateFile() { Gloze gl = new Gloze(); Model outputModel = ModelFactory.createDefaultModel(); try { // Create a temporary file to use for translation File tempFile = new File("temp"); FileOutputStream tempWrite = new FileOutputStream(tempFile); while(true) { int bytedata = this.inStream.read(); if(bytedata == -1) { break; } tempWrite.write(bytedata); } this.inStream.close(); tempWrite.close(); gl.xml_to_rdf(tempFile, this.incomingSchema, this.uriBase, outputModel); tempFile.delete(); } catch(Exception e) { log.error(e.getMessage()); log.debug("Stacktrace:",e); } outputModel.write(this.outStream); } /*** * */ public void execute() { if((this.uriBase != null) && (this.inStream != null)) { try { // create a output stream for writing to the out store ByteArrayOutputStream buff = new ByteArrayOutputStream(); // get from the in record and translate for(Record r : this.inStore) { if(r.needsProcessed(this.getClass())) { this.inStream = new ByteArrayInputStream(r.getData().getBytes()); this.outStream = buff; translateFile(); buff.flush(); this.outStore.addRecord(r.getID(), buff.toString(), this.getClass()); r.setProcessed(this.getClass()); buff.reset(); } } buff.close(); } catch(Exception e) { log.error(e.getMessage()); log.debug("Stacktrace:",e); } } else { log.error("Invalid Arguments: Gloze Translation requires a URIBase and XMLFile"); throw new IllegalArgumentException(); } } /** * Get the ArgParser for this task * @return the ArgParser */ protected static ArgParser getParser() { ArgParser parser = new ArgParser("GlozeTranslator"); parser.addArgument(new ArgDef().setShortOption('i').setLongOpt("input").withParameter(true, "CONFIG_FILE").setDescription("config file for input record handler").setRequired(false)); parser.addArgument(new ArgDef().setShortOption('I').setLongOpt("inputOverride").withParameterValueMap("RH_PARAM", "VALUE").setDescription("override the RH_PARAM of input record handler config using VALUE").setRequired(false)); parser.addArgument(new ArgDef().setShortOption('o').setLongOpt("output").withParameter(true, "CONFIG_FILE").setDescription("config file for output record handler").setRequired(false)); parser.addArgument(new ArgDef().setShortOption('O').setLongOpt("outputOverride").withParameterValueMap("RH_PARAM", "VALUE").setDescription("override the RH_PARAM of output record handler config using VALUE").setRequired(false)); parser.addArgument(new ArgDef().setShortOption('z').setLongOpt("xmlSchema").withParameter(false, "XML_SCHEMA").setDescription("xsl file").setRequired(true)); parser.addArgument(new ArgDef().setShortOption('u').setLongOpt("uriBase").withParameter(false, "URI_BASE").setDescription("uri base").setRequired(true)); return parser; } /** * Main Method * @param args list of arguments required to execute glozetranslate */ public static void main(String... args) { Exception error = null; try { InitLog.initLogger(args, getParser()); log.info(getParser().getAppName() + ": Start"); new GlozeTranslator(args).execute(); } catch(IllegalArgumentException e) { log.error(e.getMessage()); log.debug("Stacktrace:",e); System.out.println(getParser().getUsage()); error = e; } catch(UsageException e) { log.info("Printing Usage:"); System.out.println(getParser().getUsage()); error = e; } catch(Exception e) { log.error(e.getMessage()); log.debug("Stacktrace:",e); error = e; } finally { log.info(getParser().getAppName() + ": End"); if(error != null) { System.exit(1); } } } }
34.833333
230
0.703349
f4262837d1cdfcb41e28b80ebf0af1c696c2fbd0
1,268
package com.twu.biblioteca.entity; import java.util.Objects; public class Book extends Article { String name; String author; String publishedYear; public Book( String name, String author, String publishedYear) { this.name = name; this.author = author; this.publishedYear = publishedYear; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublishedYear() { return publishedYear; } public void setPublishedYear(String publishedYear) { this.publishedYear = publishedYear; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Book book = (Book) o; return Objects.equals(name, book.name) && Objects.equals(author, book.author) && Objects.equals(publishedYear, book.publishedYear); } @Override public int hashCode() { return Objects.hash(name, author, publishedYear); } }
22.245614
68
0.604101
bf26d3e398e81131cb1a2e0fc06b4ff32fb43313
1,549
/** * Copyright 2018 chengfan(fanhub.cn) * * 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 cn.fanhub.placidium.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * * @author chengfan * @version $Id: CORSConfiguration.java, v 0.1 2018年06月12日 下午9:34 chengfan Exp $ */ @Configuration public class CORSConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedHeaders("*") .allowedMethods("*") .allowedOrigins("*"); } }; } }
35.204545
81
0.693996
f80160efe23ae9fc5752e046fdb54ca4b5ac44f8
5,420
/** * Copyright 2019 Pramati Prism, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.srujankujmar.commons.framework.patch; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.io.StringReader; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; import javax.json.Json; import javax.json.JsonObject; import org.json.JSONException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.skyscreamer.jsonassert.JSONAssert; import com.github.srujankujmar.commons.exception.CommonErrorCode; import com.github.srujankujmar.commons.exception.HyscaleError; import com.github.srujankujmar.commons.exception.HyscaleException; import com.github.srujankujmar.commons.io.HyscaleFilesUtil; public class StrategicPatchTest { private static String sourceData; private static String patchData; private static String mergedData; @BeforeAll public static void init() throws HyscaleException { sourceData = getData("/patch/source.json"); patchData = getData("/patch/patch.json"); mergedData = getData("/patch/merged.json"); } public static Stream<Arguments> getApplyInput() { TestFieldDataProvider fieldDataProvider = new TestFieldDataProvider(); return Stream.of(Arguments.of(sourceData, patchData, fieldDataProvider, mergedData), Arguments.of(null, null, null, null), Arguments.of(null, patchData, null, patchData), Arguments.of(sourceData, null, null, sourceData)); } @ParameterizedTest @MethodSource(value = "getApplyInput") public void testApply(String source, String patch, TestFieldDataProvider fieldDataMap, String expectedMergedData) { try { String actualMergedData = StrategicPatch.apply(source, patch, fieldDataMap); if (expectedMergedData == null) { assertNull(actualMergedData); } else { JSONAssert.assertEquals(expectedMergedData, actualMergedData, false); } } catch (JSONException | HyscaleException e) { fail(); } } public static Stream<Arguments> getApplyExceptionInput() { return Stream.of(Arguments.of("{test:abc}", "{test:def test1:abc}", null, CommonErrorCode.INVALID_JSON_FORMAT), Arguments.of("{test:def test1:abc}", "{test:abc}", null, CommonErrorCode.INVALID_JSON_FORMAT), Arguments.of(sourceData, patchData, null, CommonErrorCode.STRATEGIC_MERGE_KEY_NOT_FOUND)); } @ParameterizedTest @MethodSource(value = "getApplyExceptionInput") public void testException(String source, String patch, TestFieldDataProvider fieldDataProvider, HyscaleError errorCode) { try { StrategicPatch.apply(source, patch, fieldDataProvider); fail(); } catch (HyscaleException e) { assertEquals(errorCode, e.getHyscaleError()); } } public static Stream<Arguments> getMergeNullInput() { JsonObject input = Json.createReader(new StringReader("{\"test\":\"abc\"}")).readObject(); return Stream.of(Arguments.of(null, null, null), Arguments.of(input, null, input), Arguments.of(null, input, input)); } @ParameterizedTest @MethodSource(value = "getMergeNullInput") public void nullMergeChecks(JsonObject source, JsonObject patch, JsonObject expected) { try { JsonObject merged = StrategicPatch.mergeJsonObjects(source, patch, null); if (expected == null) { assertNull(merged); } else { assertEquals(expected,merged); } } catch (HyscaleException e) { fail(); } } private static String getData(String path) throws HyscaleException { URL urlPath = StrategicPatchTest.class.getResource(path); return HyscaleFilesUtil.readFileData(new File(urlPath.getFile())); } private static class TestFieldDataProvider implements FieldMetaDataProvider{ private static Map<String, String> fieldMap = new HashMap<String, String>(); static { fieldMap.put("patchTestModelList", "key"); } @Override public FieldMetaData getMetaData(String field) { FieldMetaData fieldMetaData = new FieldMetaData(); fieldMetaData.setKey(fieldMap.get(field)); return fieldMetaData; } } }
38.169014
119
0.684871
353c323e894720311e6f550e7e6f5235ee5e77fa
2,687
package com.txlidat.dao.hibernate; import com.txlcommon.dao.hibernate.TXLAbstractSiteCheckingDao; import com.txlcommon.domain.psn.TXLPsn; import com.txlidat.dao.TXLClientDao; import com.txlidat.domain.TXLClient; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projection; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import java.util.List; /** * Created by lucas on 22/08/15. */ public class TXLClientDaoImpl extends TXLAbstractSiteCheckingDao implements TXLClientDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession() { return sessionFactory.getCurrentSession(); } @Override public TXLClient save(TXLClient client) { Session session = getSession(); session.saveOrUpdate(client); return client; } @Override public TXLClient findById(Long id) { return null; } @Override public TXLClient update(TXLClient o) { return null; } @Override public void remove(TXLClient o) { } @Override public TXLPsn fetchEIDForUsername(String username) { TXLPsn result = null; Criteria criteria = sessionFactory.getCurrentSession().createCriteria(TXLClient.class); Projection counterPartPsnProjection; criteria.createAlias("endClientUsers", "endClientUsersList"); criteria.add(Restrictions.eq("endClientUsersList.username", username)); counterPartPsnProjection = Projections.property("eid"); criteria.setProjection(counterPartPsnProjection); List<TXLPsn> resultList = criteria.list(); if (!resultList.isEmpty()) { result = resultList.get(0); } return result; } @Override public List<TXLClient> listClients() { List<TXLClient> result; Criteria criteria = sessionFactory.getCurrentSession().createCriteria(TXLClient.class); result = criteria.list(); return result; } @Override public List<TXLClient> listClients(int start, int maxResult) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(TXLClient.class); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.addOrder(Order.desc("id")); criteria.setFirstResult(start); criteria.setMaxResults(maxResult); List<TXLClient> result = criteria.list(); return result; } }
27.418367
95
0.701898
c1cffad94843a21a6495fd20e7802698d9143aac
1,934
package com.ironhack.demobakingapp.service.impl.Users; import com.ironhack.demobakingapp.controller.DTO.Users.AccountHolderDTO; import com.ironhack.demobakingapp.enums.UserRole; import com.ironhack.demobakingapp.model.Users.AccountHolder; import com.ironhack.demobakingapp.model.Users.Role; import com.ironhack.demobakingapp.repository.Users.AccountHolderRepository; import com.ironhack.demobakingapp.service.interfaces.Users.IAccountHolderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @Service public class AccountHolderService implements IAccountHolderService { @Autowired private AccountHolderRepository accountHolderRepository; /** Add a new account holder **/ public AccountHolder add(AccountHolderDTO accountHolderDTO){ AccountHolder accountHolder = new AccountHolder( accountHolderDTO.getName(), accountHolderDTO.getPassword(), accountHolderDTO.getUsername(), accountHolderDTO.getBirthDate(), accountHolderDTO.getMailingAddressDTO(), accountHolderDTO.getMailingAddressDTO() ); Role role = new Role(UserRole.ACCOUNT_HOLDER, accountHolder); Set<Role> roles = Stream.of(role).collect(Collectors.toCollection(HashSet::new)); accountHolder.setRoles(roles); accountHolderRepository.save(accountHolder); return accountHolder; } /** Find an account holder by Id **/ public AccountHolder findById(Long id){ return accountHolderRepository.getOne(id); } /** Find an account holder by username **/ public AccountHolder findByUsername(String username){ return accountHolderRepository.findByUsername(username).get(); } }
35.814815
89
0.737849
0bb7b1ebdee4b2d9debedf31bd7ea00b11cccd21
1,726
package Dec2020Leetcode; public class _0329LongestIncreasingPathInAMatrix { public static void main(String[] args) { System.out.println(longestIncreasingPath( new int[][] { new int[] { 9, 9, 4 }, new int[] { 6, 6, 8 }, new int[] { 2, 1, 1 } })); System.out.println(longestIncreasingPath( new int[][] { new int[] { 3, 4, 5 }, new int[] { 3, 2, 6 }, new int[] { 2, 2, 1 } })); } public static int longestIncreasingPath(int[][] matrix) { if (matrix == null || matrix.length == 0) return 0; int[][] cache = new int[matrix.length][matrix[0].length]; int out = 1; boolean[][] visited = new boolean[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { out = Math.max(out, dfs(i, j, matrix, cache, visited)); } } return out; } public static int dfs(int x, int y, int[][] matrix, int[][] cache, boolean[][] visited) { if (cache[x][y] != 0) return cache[x][y]; visited[x][y] = true; int leftVal = 1; if (x - 1 >= 0 && !visited[x - 1][y] && matrix[x - 1][y] > matrix[x][y]) { leftVal = dfs(x - 1, y, matrix, cache, visited) + 1; } if (y - 1 >= 0 && !visited[x][y - 1] && matrix[x][y - 1] > matrix[x][y]) { leftVal = Math.max(leftVal, dfs(x, y - 1, matrix, cache, visited) + 1); } if (x + 1 < matrix.length && !visited[x + 1][y] && matrix[x + 1][y] > matrix[x][y]) { leftVal = Math.max(leftVal, dfs(x + 1, y, matrix, cache, visited) + 1); } if (y + 1 < matrix[0].length && !visited[x][y + 1] && matrix[x][y + 1] > matrix[x][y]) { leftVal = Math.max(leftVal, dfs(x, y + 1, matrix, cache, visited) + 1); } cache[x][y] = leftVal; visited[x][y] = false; return leftVal; } }
30.821429
90
0.559676
bfa550c5867f4c2981ea8e417b82f052fb9e87ef
2,486
package io.github.incplusplus.bigtoolbox.network; import io.github.incplusplus.bigtoolbox.network.interfaces.WiFiAdapter; import io.github.incplusplus.bigtoolbox.network.interop.lin.dbushelpers.PropertiesExtractor; import io.github.incplusplus.bigtoolbox.network.interop.lin.nm.NMInterop; import io.github.incplusplus.bigtoolbox.network.interop.lin.nm.org.freedesktop.NetworkManager; import io.github.incplusplus.bigtoolbox.network.interop.lin.nm.org.freedesktop.networkmanager.Device; import io.github.incplusplus.bigtoolbox.network.interop.lin.nm.org.freedesktop.networkmanager.types.NMDeviceType; import io.github.incplusplus.bigtoolbox.os.UnsupportedOSException; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import org.freedesktop.dbus.exceptions.DBusException; import org.freedesktop.dbus.types.Variant; public class Main { public static void main(String[] args) throws UnsupportedOSException, IOException, DBusException { // getAllProps(); try (NetworkController controller = NetworkControllerFactory.createNetworkController()) { Interface[] ifaces = controller.getInterfaces(); for (Interface i : Arrays.stream(ifaces).filter(Objects::nonNull).toArray(Interface[]::new)) { if (i instanceof WiFiAdapter) { WiFiAdapter adapter = (WiFiAdapter) i; System.out.println(Arrays.toString(((WiFiAdapter) i).getAccessPoints())); } } } } private static void getAllProps() throws UnsupportedOSException, IOException, DBusException { // try (NetworkController controller = NetworkControllerFactory.createNetworkController()) { // System.out.println(Arrays.toString(controller.getInterfaces())); NetworkManager nm = NMInterop.getActiveInstance() .getDbusConn() .getRemoteObject( "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", NetworkManager.class); List<Device> devices = nm.GetDevices().stream() .map(NMDeviceType::dbusInterfaceToNMDevice) .collect(Collectors.toList()); Map<Device, Map<String, Map<String, Variant<?>>>> props = new HashMap<>(); for (Device device : devices) { props.put(device, PropertiesExtractor.GetAllFromDevice(device)); } System.out.println(props.size()); // } } }
44.392857
113
0.730491
338db9a24d93f7d5d9752deb28d7301aabacdf65
1,470
package ca.ghandalf.urban.mobility.dto; import java.io.Serializable; import java.util.UUID; public class AgencyDTO implements Serializable { private static final long serialVersionUID = -5110247213639696407L; private UUID id; private String agencyId; private String name; private String url; private String timezone; private String language; private String phone; private String fareUrl; private String email; public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getAgencyId() { return agencyId; } public void setAgencyId(String agencyId) { this.agencyId = agencyId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTimezone() { return timezone; } public void setTimezone(String timezone) { this.timezone = timezone; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getFareUrl() { return fareUrl; } public void setFareUrl(String fareUrl) { this.fareUrl = fareUrl; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
14.7
68
0.702041
e8541270e5da76ddc719a6fdb8470ea236bdbb41
574
package org.simplity.fm.example.gen.list; import org.simplity.fm.core.validn.ValueList; public class Religion extends ValueList { private static final Object[][] VALUES = { {"Hindu", "Hindu"}, {"Muslim", "Muslim"}, {"Christian", "Christian"}, {"Sikh", "Sikh"}, {"Jain", "Jain"}, {"Others", "Other"} }; private static final String NAME = "religion"; /** * * @param name * @param valueList */ public Religion(String name, Object[][] valueList) { super(name, valueList); } /** *religion */ public Religion() { super(NAME, VALUES); } }
18.516129
53
0.621951
b58b0f9e5395b48fc8d186f979789213db392a28
693
package model; public class Categoria { private Integer codigo; private String categoria; private String descricao; public Categoria(String categoria, String descricao) { this.categoria = categoria; this.descricao = descricao; } public Integer getCodigo() { return codigo; } public void setCodigo(Integer codigo) { this.codigo = codigo; } public String getCategoria() { return categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public String toString() { return this.categoria; } }
16.5
55
0.724387
363e154280a6f4123f7ed54ab5ea6eb3f2b1c3ed
2,017
package pl.mprzybylak.presentation.rxjavaquick; import io.reactivex.Observable; import org.junit.Test; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.assertj.core.api.Assertions.assertThat; public class ObservableUtilsTest { @Test public void delay() throws InterruptedException { // given List<LocalDateTime> dates = new ArrayList<>(10); LocalDateTime beforeSubscription = null; // when Observable<Integer> o = Observable.range(1, 10) .delay(1, TimeUnit.SECONDS); beforeSubscription = LocalDateTime.now(); o.subscribe(integer -> dates.add(LocalDateTime.now())); Thread.sleep(1100); // then int between = (int) beforeSubscription.until(dates.get(0), ChronoUnit.SECONDS); assertThat(between).isBetween(1, 2); } @Test public void actionOnFinish() { // given AtomicBoolean b = new AtomicBoolean(false); // when Observable.range(1, 10) .doOnComplete(() -> b.set(true)) .subscribe(); // then assertThat(b.get()).isTrue(); } @Test public void actionOnError() { // given AtomicBoolean b = new AtomicBoolean(false); // when Observable.error(new NullPointerException()) .doOnError(throwable -> b.set(true)) .subscribe(); // then assertThat(b.get()).isTrue(); } @Test public void actionOnEachElement() {} { // given List<AtomicBoolean> booleans = new ArrayList<>(); // when Observable.range(1, 10) .doOnEach(i -> booleans.add(new AtomicBoolean(true))) .subscribe(); // then booleans.forEach(b -> assertThat(b.get()).isTrue()); } }
23.729412
87
0.596926
3eff82fdf52b8efccfe2e9b1797af71425e8e5c7
11,227
package com.africultures.seed.Action; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import android.util.Base64; import android.util.Log; import com.commonsware.cwac.cam2.AbstractCameraActivity; import com.commonsware.cwac.cam2.CameraActivity; import com.commonsware.cwac.cam2.VideoRecorderActivity; import com.commonsware.cwac.cam2.ZoomStyle; import com.africultures.seed.Helper.JasonHelper; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; public class JasonMediaAction { /********************************** * * Play * **********************************/ public void play(final JSONObject action, JSONObject data, final JSONObject event, final Context context) { try { if(action.has("options")){ Intent intent = new Intent(Intent.ACTION_VIEW); if(action.getJSONObject("options").has("url")){ intent.setDataAndType(Uri.parse(action.getJSONObject("options").getString("url")), "video/mp4"); } if(action.getJSONObject("options").has("muted")){ AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0); } else { am.setStreamMute(AudioManager.STREAM_MUSIC, true); } } JSONObject callback = new JSONObject(); callback.put("class", "JasonMediaAction"); callback.put("method", "finishplay"); JasonHelper.dispatchIntent(action, data, event, context, intent, callback); } } catch (Exception e) { Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString()); } } // Util for play public void finishplay(Intent intent, final JSONObject options) { try { JSONObject action = options.getJSONObject("action"); JSONObject event = options.getJSONObject("event"); Context context = (Context) options.get("context"); // revert mute if(action.getJSONObject("options").has("muted")){ AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0); } else { am.setStreamMute(AudioManager.STREAM_MUSIC, false); } } JasonHelper.next("success", action, new JSONObject(), event, context); } catch (Exception e) { Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString()); } } /********************************** * * Picker + Camera * **********************************/ public void picker(final JSONObject action, JSONObject data, final JSONObject event, final Context context) { // Image picker intent try { String type = "image"; if(action.has("options")){ if(action.getJSONObject("options").has("type")){ type = action.getJSONObject("options").getString("type"); } } Intent intent; if(type.equalsIgnoreCase("video")){ // video intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI); } else { // image intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); } // dispatchIntent method // 1. triggers an external Intent // 2. attaches a callback with all the payload so that we can pick it up where we left off when the intent returns // the callback needs to specify the class name and the method name we wish to trigger after the intent returns JSONObject callback = new JSONObject(); callback.put("class", "JasonMediaAction"); callback.put("method", "process"); JasonHelper.dispatchIntent(action, data, event, context, intent, callback); } catch (SecurityException e){ JasonHelper.permission_exception("$media.picker", context); } catch (Exception e) { Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString()); } } public void camera(final JSONObject action, JSONObject data, final JSONObject event, final Context context) { // Image picker intent try { AbstractCameraActivity.Quality q = AbstractCameraActivity.Quality.LOW; String type = "photo"; Boolean edit = false; if(action.has("options")) { JSONObject options = action.getJSONObject("options"); // type if (options.has("type")) { type = options.getString("type"); } // quality if(type.equalsIgnoreCase("video")) { // video // high by default q = AbstractCameraActivity.Quality.HIGH; } else { // photo // high by default q = AbstractCameraActivity.Quality.HIGH; } if (options.has("quality")) { String quality = options.getString("quality"); if (quality.equalsIgnoreCase("low")) { q = AbstractCameraActivity.Quality.LOW; } else if (quality.equalsIgnoreCase("medium")) { q = AbstractCameraActivity.Quality.HIGH; } } // edit if (options.has("edit")) { edit = true; } } Intent intent; if(type.equalsIgnoreCase("video")) { // video VideoRecorderActivity.IntentBuilder builder =new VideoRecorderActivity.IntentBuilder(context) .to(createFile("video", context)) .zoomStyle(ZoomStyle.SEEKBAR) .updateMediaStore() .quality(q); intent = builder.build(); } else { // photo CameraActivity.IntentBuilder builder = new CameraActivity.IntentBuilder(context) .to(createFile("image", context)) .zoomStyle(ZoomStyle.SEEKBAR) .updateMediaStore() .quality(q); if(!edit){ builder.skipConfirm(); } intent = builder.build(); } // dispatchIntent method // 1. triggers an external Intent // 2. attaches a callback with all the payload so that we can pick it up where we left off when the intent returns // the callback needs to specify the class name and the method name we wish to trigger after the intent returns JSONObject callback = new JSONObject(); callback.put("class", "JasonMediaAction"); callback.put("method", "process"); JasonHelper.dispatchIntent(action, data, event, context, intent, callback); } catch (SecurityException e){ JasonHelper.permission_exception("$media.camera", context); } catch (Exception e) { Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString()); } } // util public void process(Intent intent, final JSONObject options) { try { JSONObject action = options.getJSONObject("action"); JSONObject data = options.getJSONObject("data"); JSONObject event = options.getJSONObject("event"); Context context = (Context)options.get("context"); Uri uri = intent.getData(); // handling image String type = "image"; if(action.has("options")) { if (action.getJSONObject("options").has("type")) { type = action.getJSONObject("options").getString("type"); } } if(type.equalsIgnoreCase("video")){ // video try { JSONObject ret = new JSONObject(); ret.put("file_url", uri.toString()); ret.put("content_type", "video/mp4"); JasonHelper.next("success", action, ret, event, context); } catch (Exception e) { Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString()); } } else { // image InputStream stream = context.getContentResolver().openInputStream(uri); byte[] byteArray = JasonHelper.readBytes(stream); String encoded = Base64.encodeToString(byteArray, Base64.NO_WRAP); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("data:image/jpeg;base64,"); stringBuilder.append(encoded); String data_uri = stringBuilder.toString(); try { JSONObject ret = new JSONObject(); ret.put("data", encoded); ret.put("data_uri", data_uri); ret.put("content_type", "image/jpeg"); JasonHelper.next("success", action, ret, event, context); } catch (Exception e) { Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString()); } } } catch (Exception e) { Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString()); } } private File createFile(String type, Context context) throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String fileName = "" + timeStamp + "_"; File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); File f; if(type.equalsIgnoreCase("image")) { f = File.createTempFile( fileName, ".jpg", storageDir ); } else if(type.equalsIgnoreCase("video")){ f = File.createTempFile( fileName, ".mp4", storageDir ); } else { f = File.createTempFile( fileName, ".txt", storageDir ); } return f; } }
39.53169
126
0.539325
ec98bd351149a6a4b2645aa78b57091e5d9572e9
5,885
/** Copyright 2008 University of Rochester 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 edu.ur.hibernate.ir.researcher.db; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import edu.ur.hibernate.HbCrudDAO; import edu.ur.ir.researcher.ResearcherInstitutionalItem; import edu.ur.ir.researcher.ResearcherInstitutionalItemDAO; /** * Hibernate implementation of researcher institutional Item data access and storage. * * @author Sharmila Ranganathan * */ public class HbResearcherInstitutionalItemDAO implements ResearcherInstitutionalItemDAO { /** eclipse generated id */ private static final long serialVersionUID = 1439886971641958964L; /** * Helper for persisting information using hibernate. */ private final HbCrudDAO<ResearcherInstitutionalItem> hbCrudDAO; /** Logger for add files to item action */ private static final Logger log = Logger.getLogger(HbResearcherInstitutionalItemDAO.class); /** * Default Constructor */ public HbResearcherInstitutionalItemDAO() { hbCrudDAO = new HbCrudDAO<ResearcherInstitutionalItem>(ResearcherInstitutionalItem.class); } /** * Set the session factory. * * @param sessionFactory */ public void setSessionFactory(SessionFactory sessionFactory) { hbCrudDAO.setSessionFactory(sessionFactory); } /** * Return ResearcherInstitutionalItem by id */ public ResearcherInstitutionalItem getById(Long id, boolean lock) { return hbCrudDAO.getById(id, lock); } /** * * @see edu.ur.dao.CrudDAO#makePersistent(java.lang.Object) */ public void makePersistent(ResearcherInstitutionalItem entity) { hbCrudDAO.makePersistent(entity); } /** * * @see edu.ur.dao.CrudDAO#makeTransient(java.lang.Object) */ public void makeTransient(ResearcherInstitutionalItem entity) { hbCrudDAO.makeTransient(entity); } /** * Get the root researcher institutional Items for given researcher * * @see edu.ur.ir.researcher.ResearcherInstitutionalItemDAO#getRootResearcherInstitutionalItems(Long) */ @SuppressWarnings("unchecked") public List<ResearcherInstitutionalItem> getRootResearcherInstitutionalItems(final Long researcherId) { log.debug("getRootResearcherInstitutionalItems::"); Criteria criteria = hbCrudDAO.getSessionFactory().getCurrentSession().createCriteria(hbCrudDAO.getClazz()); criteria.createCriteria("researcher").add(Restrictions.idEq(researcherId)); criteria.add(Restrictions.isNull("parentFolder")); return criteria.list(); } /** * Get researcher institutional Items for specified researcher and specified parent folder * * @see edu.ur.ir.researcher.ResearcherInstitutionalItemDAO#getSubResearcherInstitutionalItems(Long, Long) */ @SuppressWarnings("unchecked") public List<ResearcherInstitutionalItem> getSubResearcherInstitutionalItems(final Long researcherId, final Long parentCollectionId) { log.debug("getSubResearcherInstitutionalItems::"); Criteria criteria = hbCrudDAO.getSessionFactory().getCurrentSession().createCriteria(hbCrudDAO.getClazz()); criteria.createCriteria("researcher").add(Restrictions.idEq(researcherId)); criteria.createCriteria("parentFolder").add(Restrictions.idEq(parentCollectionId)); return criteria.list(); } /** * Find the specified items for the given researcher. * * @see edu.ur.ir.researcher.ResearcherInstitutionalItemDAO#getResearcherInstitutionalItems(java.lang.Long, java.util.List) */ @SuppressWarnings("unchecked") public List<ResearcherInstitutionalItem> getResearcherInstitutionalItems(final Long researcherId, final List<Long> itemIds) { List<ResearcherInstitutionalItem> foundItems = new LinkedList<ResearcherInstitutionalItem>(); if( itemIds.size() > 0 ) { Criteria criteria = hbCrudDAO.getSessionFactory().getCurrentSession().createCriteria(hbCrudDAO.getClazz()); criteria.createCriteria("researcher").add(Restrictions.idEq(researcherId)); criteria.add(Restrictions.in("id", itemIds)); foundItems = criteria.list(); } return foundItems; } /** * Get a count of the researcher institutional Items containing this item * * @see edu.ur.ir.researcher.ResearcherInstitutionalItemDAO#getResearcherInstitutionalItemCount(Long) */ public Long getResearcherInstitutionalItemCount(Long itemId) { Query q = hbCrudDAO.getSessionFactory().getCurrentSession().getNamedQuery("getResearcherInstitutionalItemCount"); q.setLong("institutionalItemId", itemId); return (Long)q.uniqueResult(); } /** * Get a researcher institutional Items containing this item * * @see edu.ur.ir.researcher.ResearcherInstitutionalItemDAO#getResearcherInstitutionalItem(Long) */ @SuppressWarnings("unchecked") public List<ResearcherInstitutionalItem> getResearcherInstitutionalItem(Long itemId) { Query q = hbCrudDAO.getSessionFactory().getCurrentSession().getNamedQuery("getResearcherInstitutionalItem"); q.setLong("institutionalItemId", itemId); return (List<ResearcherInstitutionalItem>) q.list(); } }
35.884146
133
0.747494
3d40430050fc248364c926cf82277c218342615d
8,172
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.07.06 at 03:14:07 오후 KST // package net.herit.iot.onem2m.resource; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://www.onem2m.org/xml/protocols}announcedSubordinateResource"> * &lt;sequence> * &lt;element name="stateTag" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger"/> * &lt;element name="contentInfo" type="{http://www.onem2m.org/xml/protocols}contentInfo" minOccurs="0"/> * &lt;element name="contentSize" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/> * &lt;element name="ontologyRef" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/> * &lt;element name="content" type="{http://www.w3.org/2001/XMLSchema}anyType" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "stateTag", "contentInfo", "contentSize", "ontologyRef", "content", "childResource", // added in CDT-2.7.0 "semanticDescriptor" // added in CDT-2.7.0 }) //@XmlRootElement(name = "contentInstanceAnnc") @XmlRootElement(name = Naming.CONTENTINSTANCEANNC) public class ContentInstanceAnnc extends AnnouncedSubordinateResource { // public final static String SCHEMA_LOCATION = "CDT-contentInstance-v1_2_0.xsd"; // public final static String SCHEMA_LOCATION = "CDT-contentInstance-v1_6_0.xsd"; public final static String SCHEMA_LOCATION = "CDT-contentInstance-v2_7_0.xsd"; public static final List<String> MA = new ArrayList<String>( Arrays.asList(Naming.RESOURCEID_SN, Naming.RESOURCENAME_SN, Naming.LABELS_SN ) ); public static final Set<String> OA = new HashSet<String>( Arrays.asList(Naming.STATETAG_SN, Naming.CONTENTINFO_SN, Naming.CONTENTSIZE_SN, Naming.ONTOLOGYREF_SN, Naming.CONTENT_SN ) ); //@XmlElement(required = true) @XmlElement(name = Naming.STATETAG_SN) @XmlSchemaType(name = "nonNegativeInteger") protected Integer stateTag; @XmlElement(name = Naming.CONTENTINFO_SN) protected String contentInfo; @XmlElement(name = Naming.CONTENTSIZE_SN) @XmlSchemaType(name = "nonNegativeInteger") protected Integer contentSize; @XmlElement(name = Naming.ONTOLOGYREF_SN) @XmlSchemaType(name = "anyURI") protected String ontologyRef; @XmlElement(name = Naming.CONTENT_SN) protected String content; protected List<ChildResourceRef> childResource; @XmlElement(namespace = "http://www.onem2m.org/xml/protocols") protected List<SemanticDescriptor> semanticDescriptor; /** * Gets the value of the stateTag property. * * @return * possible object is * {@link Integer } * */ public Integer getStateTag() { return stateTag; } /** * Sets the value of the stateTag property. * * @param value * allowed object is * {@link Integer } * */ public void setStateTag(Integer value) { this.stateTag = value; } /** * Gets the value of the contentInfo property. * * @return * possible object is * {@link String } * */ public String getContentInfo() { return contentInfo; } /** * Sets the value of the contentInfo property. * * @param value * allowed object is * {@link String } * */ public void setContentInfo(String value) { this.contentInfo = value; } /** * Gets the value of the contentSize property. * * @return * possible object is * {@link Integer } * */ public Integer getContentSize() { return contentSize; } /** * Sets the value of the contentSize property. * * @param value * allowed object is * {@link Integer } * */ public void setContentSize(Integer value) { this.contentSize = value; } /** * Gets the value of the ontologyRef property. * * @return * possible object is * {@link String } * */ public String getOntologyRef() { return ontologyRef; } /** * Sets the value of the ontologyRef property. * * @param value * allowed object is * {@link String } * */ public void setOntologyRef(String value) { this.ontologyRef = value; } /** * Gets the value of the content property. * * @return * possible object is * {@link Object } * */ public String getContent() { return content; } /** * Sets the value of the content property. * * @param value * allowed object is * {@link Object } * */ public void setContent(String value) { this.content = value; } /** * Gets the value of the childResource property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the childResource property. * * <p> * For example, to add a new item, do as follows: * <pre> * getChildResource().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ChildResourceRef } * * */ public List<ChildResourceRef> getChildResource() { // if (childResource == null) { // childResource = new ArrayList<ChildResourceRef>(); // } return this.childResource; } public void addChildResource(ChildResourceRef value) { if (childResource == null) { childResource = new ArrayList<ChildResourceRef>(); } this.childResource.add(value); } /** * Gets the value of the semanticDescriptor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the semanticDescriptor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSemanticDescriptor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SemanticDescriptor } * * */ public List<SemanticDescriptor> getSemanticDescriptor() { // if (semanticDescriptor == null) { // semanticDescriptor = new ArrayList<SemanticDescriptor>(); // } return this.semanticDescriptor; } public void addSemanticDescriptor(SemanticDescriptor value) { if (semanticDescriptor == null) { semanticDescriptor = new ArrayList<SemanticDescriptor>(); } this.semanticDescriptor.add(value); } }
27.701695
124
0.61723
efb6bdf37202fc9369212d4597e76d528df02ba2
1,240
package com.liefeng.property.repository.fee; import java.util.List; import javax.transaction.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import com.liefeng.property.po.fee.MeterSettingPo; /** * * <pre> * Title 仪表设置存储层: * Description: * Company:广州列丰科技有限公司 * Copyright: Copyright (c) 2015 * @author wuzhijing * @version 1.0 * @created 2016年2月18日下午4:12:28 * </pre> */ @Transactional public interface MeterSettingRepository extends JpaRepository<MeterSettingPo, String> { /** * 查询查表(分页) * @param projectId * @param pageable * @return */ public Page<MeterSettingPo> findByProjectId(String projectId, Pageable pageable); /** * 根据项目id仪表类型查询仪表设置 * @param projectId * @param type * @return */ public MeterSettingPo findByProjectIdAndType(String projectId, String type); /** * 根据id查询仪表设置 * @param id * @return */ public MeterSettingPo findById(String id); /** * 获取项目下要抄的表 * @param projectId * @param chargeableYes * @return */ public List<MeterSettingPo> findByProjectIdAndChargeable(String projectId, String chargeableYes); }
20
87
0.716129
6ac72136c51c61f74f5b6d2161b15f02c12c7fd0
2,440
package net.consensys.eventeum.chain.service.strategy; import net.consensys.eventeum.chain.service.BlockchainException; import net.consensys.eventeum.chain.service.domain.TransactionReceipt; import net.consensys.eventeum.chain.service.domain.wrapper.Web3jTransactionReceipt; import net.consensys.eventeum.dto.block.BlockDetails; import net.consensys.eventeum.service.AsyncTaskService; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.DefaultBlockParameterNumber; import org.web3j.protocol.core.methods.response.EthBlock; import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt; import org.web3j.protocol.websocket.events.NewHead; import org.web3j.utils.Numeric; import rx.Subscription; import java.io.IOException; import java.math.BigInteger; public class PubSubBlockSubscriptionStrategy extends AbstractBlockSubscriptionStrategy { public PubSubBlockSubscriptionStrategy(Web3j web3j, AsyncTaskService asyncTaskService) { super(web3j, asyncTaskService); } @Override public Subscription subscribe() { blockSubscription = web3j.newHeadsNotifications().subscribe(newHead -> { blockListeners.forEach(listener -> asyncTaskService.execute(() -> listener.onBlock(newHeadToBlockDetails(newHead.getParams().getResult())))); }); return blockSubscription; } private BlockDetails newHeadToBlockDetails(NewHead newHead) { final EthBlock ethBlock = getEthBlock(Numeric.decodeQuantity(newHead.getNumber())); return blockToBlockDetails(ethBlock); } private EthBlock getEthBlock(BigInteger blockNumber) { final DefaultBlockParameterNumber blockParameterNumber = new DefaultBlockParameterNumber(blockNumber); try { final EthBlock ethBlock = web3j.ethGetBlockByNumber(blockParameterNumber, false).send(); return ethBlock; } catch (IOException e) { throw new BlockchainException( String.format("Unable to obtain block with number: %s", blockNumber.toString()), e); } } private BlockDetails blockToBlockDetails(EthBlock ethBlock) { final EthBlock.Block block = ethBlock.getBlock(); final BlockDetails blockDetails = new BlockDetails(); blockDetails.setNumber(block.getNumber()); blockDetails.setHash(block.getHash()); return blockDetails; } }
36.969697
126
0.736475
aece90e1df52d25bf8a6b10c53bd90c1557c918c
492
package de.polocloud.bootstrap.config; import de.polocloud.api.config.IConfig; import de.polocloud.bootstrap.config.messages.Messages; import de.polocloud.bootstrap.config.properties.Properties; public class MasterConfig implements IConfig { private Properties properties = new Properties(); private Messages messages = new Messages(); public Properties getProperties() { return properties; } public Messages getMessages() { return messages; } }
23.428571
59
0.739837
3e8912f7e2c25452ab726b8479425da4ed43e5f7
818
package de.tu_dresden.selis.pubsub; import com.google.gson.annotations.SerializedName; import java.math.BigDecimal; /** * Possible type of the values stored in the Message. */ public enum ValueType { @SerializedName("string") STRING(String.class), @SerializedName("float") FLOAT(Float.class), @SerializedName("float") DOUBLE(Double.class), @SerializedName("int") INTEGER(Integer.class), @SerializedName("boolean") BOOLEAN(Boolean.class); private Class clazz; ValueType(Class clazz) { this.clazz = clazz; } public static ValueType byObjectType(Class clazz) { for (ValueType vt : ValueType.values()) { if (vt.clazz.isAssignableFrom(clazz)) { return vt; } } return null; } }
19.023256
55
0.624694
d181471663d826acc45d96e01153ab681272f6d1
566
package com.happy; import com.happy.Common.TreeNode; import org.junit.Test; /** * 第106题 从中序与后序遍历序列构造二叉树 * * @author qgl * @date 2019/07/01 */ public class Test106 { @Test public void test106() { ConstructTreeByInPostTraversal106 builderTree106 = new ConstructTreeByInPostTraversal106(); int[] inOder = {9, 3, 15, 20, 7}; int[] postOrder = {9, 15, 7, 20, 3}; TreeNode root = builderTree106.buildTree(inOder, postOrder); System.out.println("层序遍历二叉树:" + new LevelOrderTraversalTree102().levelOrder(root)); } }
25.727273
99
0.662544
8857ef5cc60772170a8c609020618b83113b00d1
8,748
/* * Copyright (C) 2010 ZXing 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 * * 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.yzq.zxinglibrary.camera; import android.content.Context; import android.graphics.Point; import android.hardware.Camera; import android.util.Log; import android.view.Display; import android.view.WindowManager; import java.util.regex.Pattern; final class CameraConfigurationManager { private static final String TAG = CameraConfigurationManager.class.getSimpleName(); private static final int TEN_DESIRED_ZOOM = 5; private static final int DESIRED_SHARPNESS = 30; private static final Pattern COMMA_PATTERN = Pattern.compile(","); private final Context context; private Point screenResolution; private Point cameraResolution; CameraConfigurationManager(Context context) { this.context = context; } void initFromCameraParameters(Camera camera) { Camera.Parameters parameters = camera.getParameters(); WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); screenResolution = new Point(display.getWidth(), display.getHeight()); Log.d(TAG, "Screen resolution: " + screenResolution); Point screenResolutionForCamera = new Point(); screenResolutionForCamera.x = screenResolution.x; screenResolutionForCamera.y = screenResolution.y; if (screenResolution.x < screenResolution.y) { screenResolutionForCamera.x = screenResolution.y; screenResolutionForCamera.y = screenResolution.x; } cameraResolution = getCameraResolution(parameters, screenResolutionForCamera); } void setDesiredCameraParameters(Camera camera) { Camera.Parameters parameters = camera.getParameters(); Log.d(TAG, "Setting preview size: " + cameraResolution); parameters.setPreviewSize(cameraResolution.x, cameraResolution.y); setZoom(parameters); //setSharpness(parameters); //modify here camera.setDisplayOrientation(90); camera.setParameters(parameters); } Point getCameraResolution() { return cameraResolution; } Point getScreenResolution() { return screenResolution; } private static Point getCameraResolution(Camera.Parameters parameters, Point screenResolution) { String previewSizeValueString = parameters.get("preview-size-values"); // saw this on Xperia if (previewSizeValueString == null) { previewSizeValueString = parameters.get("preview-size-value"); } Point cameraResolution = null; if (previewSizeValueString != null) { Log.d(TAG, "preview-size-values parameter: " + previewSizeValueString); cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution); } Log.e("cocoa", "cocoa x"+ screenResolution.x +" "+ ((screenResolution.x >> 3) << 3)); if (cameraResolution == null) { // Ensure that the camera resolution is a multiple of 8, as the screen may not be. cameraResolution = new Point( (screenResolution.x >> 3) << 3, (screenResolution.y >> 3) << 3); } return cameraResolution; } private static Point findBestPreviewSizeValue(CharSequence previewSizeValueString, Point screenResolution) { int bestX = 0; int bestY = 0; int diff = Integer.MAX_VALUE; for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) { previewSize = previewSize.trim(); int dimPosition = previewSize.indexOf('x'); if (dimPosition < 0) { Log.w(TAG, "Bad preview-size: " + previewSize); continue; } int newX; int newY; try { newX = Integer.parseInt(previewSize.substring(0, dimPosition)); newY = Integer.parseInt(previewSize.substring(dimPosition + 1)); } catch (NumberFormatException nfe) { Log.w(TAG, "Bad preview-size: " + previewSize); continue; } int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y); if (newDiff == 0) { bestX = newX; bestY = newY; break; } else if (newDiff < diff) { bestX = newX; bestY = newY; diff = newDiff; } } if (bestX > 0 && bestY > 0) { return new Point(bestX, bestY); } return null; } private static int findBestMotZoomValue(CharSequence stringValues, int tenDesiredZoom) { Log.i("CameraManager","findBestMotZoomValue"); int tenBestValue = 0; for (String stringValue : COMMA_PATTERN.split(stringValues)) { stringValue = stringValue.trim(); double value; try { value = Double.parseDouble(stringValue); } catch (NumberFormatException nfe) { return tenDesiredZoom; } int tenValue = (int) (10.0 * value); if (Math.abs(tenDesiredZoom - value) < Math.abs(tenDesiredZoom - tenBestValue)) { tenBestValue = tenValue; } } Log.i("findBestMotZoomValue",tenBestValue+""); return tenBestValue; } private void setZoom(Camera.Parameters parameters) { Log.i("CameraManager","setZoom"); String zoomSupportedString = parameters.get("zoom-supported"); if (zoomSupportedString != null && !Boolean.parseBoolean(zoomSupportedString)) { return; } int tenDesiredZoom = TEN_DESIRED_ZOOM; String maxZoomString = parameters.get("max-zoom"); if (maxZoomString != null) { try { int tenMaxZoom = (int) (10.0 * Double.parseDouble(maxZoomString)); if (tenDesiredZoom > tenMaxZoom) { tenDesiredZoom = tenMaxZoom; } } catch (NumberFormatException nfe) { Log.w(TAG, "Bad max-zoom: " + maxZoomString); } } String takingPictureZoomMaxString = parameters.get("taking-picture-zoom-max"); if (takingPictureZoomMaxString != null) { try { int tenMaxZoom = Integer.parseInt(takingPictureZoomMaxString); if (tenDesiredZoom > tenMaxZoom) { tenDesiredZoom = tenMaxZoom; } } catch (NumberFormatException nfe) { Log.w(TAG, "Bad taking-picture-zoom-max: " + takingPictureZoomMaxString); } } String motZoomValuesString = parameters.get("mot-zoom-values"); if (motZoomValuesString != null) { tenDesiredZoom = findBestMotZoomValue(motZoomValuesString, tenDesiredZoom); } String motZoomStepString = parameters.get("mot-zoom-step"); if (motZoomStepString != null) { try { double motZoomStep = Double.parseDouble(motZoomStepString.trim()); int tenZoomStep = (int) (10.0 * motZoomStep); if (tenZoomStep > 1) { tenDesiredZoom -= tenDesiredZoom % tenZoomStep; } } catch (NumberFormatException nfe) { // continue } } // Set zoom. This helps encourage the user to pull back. // Some devices like the Behold have a zoom parameter if (maxZoomString != null || motZoomValuesString != null) { parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0)); } // Most devices, like the Hero, appear to expose this zoom parameter. // It takes on values like "27" which appears to mean 2.7x zoom if (takingPictureZoomMaxString != null) { parameters.set("taking-picture-zoom", tenDesiredZoom); } } public static int getDesiredSharpness() { return DESIRED_SHARPNESS; } }
33.906977
112
0.610768
b3ab9ecaa16686b8085f23d91baafd3c4e58e371
279
package net.loganford.noideaengine.entity; public class SimpleEntityStore extends EntityStore<Entity> { @Override protected Entity unwrap(Entity item) { return item; } @Override protected Entity wrap(Entity entity) { return entity; } }
18.6
60
0.677419
df0c0a72d3de97eb570d71294ad3eeb720b09863
1,521
package com.nicolasdu.MyFlikz.common.adapter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.nicolasdu.MyFlikz.fragment.ShowsListFragment; import com.nicolasdu.MyFlikz.showsFilter; /** * Created by Nicolas on 2/17/2016. */ public class ShowsPagerAdapter extends FragmentPagerAdapter { private int numTabs; public ShowsPagerAdapter(FragmentManager fm, int numTabs) { super(fm); this.numTabs = numTabs; } @Override public Fragment getItem(int pos) { Bundle bundle = new Bundle(); ShowsListFragment showsListFragment = new ShowsListFragment(); switch (pos) { case 0: bundle.putSerializable("filter", showsFilter.IN_THEATERS); showsListFragment.setArguments(bundle); return showsListFragment; case 1: bundle.putSerializable("filter", showsFilter.COMING_SOON); showsListFragment.setArguments(bundle); return showsListFragment; case 2: bundle.putSerializable("filter", showsFilter.TOP); showsListFragment.setArguments(bundle); return showsListFragment; default: return null; } } @Override public int getCount() { return this.numTabs; } }
29.823529
75
0.619329
281d3977c5063b0065d84ae66fe76b6137c8626a
1,184
/* * Copyright 2014 Open mHealth * * 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.openmhealth.data.generator.service; import org.openmhealth.data.generator.domain.MeasureGenerationRequest; import org.openmhealth.data.generator.domain.TimestampedValueGroup; /** * A service that generates timestamped value groups. * * @author Emerson Farrugia */ public interface TimestampedValueGroupGenerationService { /** * @param request a request to generate measures * @return a list of timestamped value groups from which measures can be built */ Iterable<TimestampedValueGroup> generateValueGroups(MeasureGenerationRequest request); }
32.888889
90
0.760135
b05218f172caed427c940e79a2b150427057cf5a
2,322
/* * Copyright (C) 2013 The Android Open Source 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 com.example.android.supportv4.content; //BEGIN_INCLUDE(complete) import android.app.IntentService; import android.content.Intent; import android.os.SystemClock; import android.util.Log; public class SimpleWakefulService extends IntentService { public SimpleWakefulService() { super("SimpleWakefulService"); } @Override protected void onHandleIntent(Intent intent) { // At this point SimpleWakefulReceiver is still holding a wake lock // for us. We can do whatever we need to here and then tell it that // it can release the wakelock. This sample just does some slow work, // but more complicated implementations could take their own wake // lock here before releasing the receiver's. // // Note that when using this approach you should be aware that if your // service gets killed and restarted while in the middle of such work // (so the Intent gets re-delivered to perform the work again), it will // at that point no longer be holding a wake lock since we are depending // on SimpleWakefulReceiver to that for us. If this is a concern, you can // acquire a separate wake lock here. for (int i=0; i<5; i++) { Log.i("SimpleWakefulReceiver", "Running service " + (i+1) + "/5 @ " + SystemClock.elapsedRealtime()); try { Thread.sleep(5000); } catch (InterruptedException e) { } } Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime()); SimpleWakefulReceiver.completeWakefulIntent(intent); } } //END_INCLUDE(complete)
40.736842
95
0.677864
f548e560e861bcace24a53a9814edc43b0820e87
957
package kr.co.popone.fitts.feature.category; import androidx.viewpager.widget.ViewPager; import io.reactivex.functions.BiConsumer; import kotlin.Unit; import kotlin.jvm.internal.Intrinsics; import kr.co.popone.fitts.C0010R$id; final class CategorySearchActivity$onCreate$2<T1, T2> implements BiConsumer<Unit, Throwable> { final /* synthetic */ CategorySearchActivity this$0; CategorySearchActivity$onCreate$2(CategorySearchActivity categorySearchActivity) { this.this$0 = categorySearchActivity; } public final void accept(Unit unit, Throwable th) { int intExtra = this.this$0.getIntent().getIntExtra(CategorySearchActivity.KEY_SUB_CATEGORY_POSITION, 0); ViewPager viewPager = (ViewPager) this.this$0._$_findCachedViewById(C0010R$id.pagerCategorySearch); Intrinsics.checkExpressionValueIsNotNull(viewPager, "pagerCategorySearch"); viewPager.setCurrentItem(intExtra); } }
41.608696
113
0.755486
b04733594adc1577ad9658ceeda485daf215d15e
9,052
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.execution.engine.fetch; import com.carrotsearch.hppc.IntContainer; import com.carrotsearch.hppc.IntObjectHashMap; import com.carrotsearch.hppc.IntObjectMap; import com.carrotsearch.hppc.IntSet; import com.carrotsearch.hppc.cursors.IntCursor; import com.carrotsearch.hppc.cursors.IntObjectCursor; import io.crate.concurrent.CompletableFutures; import io.crate.data.BatchAccumulator; import io.crate.data.Bucket; import io.crate.data.Input; import io.crate.data.Row; import io.crate.data.UnsafeArrayRow; import io.crate.expression.InputRow; import io.crate.expression.symbol.Symbol; import io.crate.metadata.TransactionContext; import io.crate.metadata.Functions; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.CompletableFuture; public class FetchBatchAccumulator implements BatchAccumulator<Row, Iterator<? extends Row>> { private static final Logger LOGGER = LogManager.getLogger(FetchBatchAccumulator.class); private final FetchOperation fetchOperation; private final FetchProjectorContext context; private final int fetchSize; private final FetchRowInputSymbolVisitor.Context collectRowContext; private final InputRow outputRow; private final ArrayList<Object[]> inputValues = new ArrayList<>(); public FetchBatchAccumulator(TransactionContext txnCtx, FetchOperation fetchOperation, Functions functions, List<Symbol> outputSymbols, FetchProjectorContext fetchProjectorContext, int fetchSize) { this.fetchOperation = fetchOperation; this.context = fetchProjectorContext; this.fetchSize = fetchSize; FetchRowInputSymbolVisitor rowInputSymbolVisitor = new FetchRowInputSymbolVisitor(txnCtx, functions); this.collectRowContext = new FetchRowInputSymbolVisitor.Context(fetchProjectorContext.tableToFetchSource); List<Input<?>> inputs = new ArrayList<>(outputSymbols.size()); for (Symbol symbol : outputSymbols) { inputs.add(rowInputSymbolVisitor.process(symbol, collectRowContext)); } outputRow = new InputRow(inputs); } @Override public void onItem(Row row) { Object[] cells = row.materialize(); collectRowContext.inputRow().cells(cells); for (int i : collectRowContext.fetchIdPositions()) { Object fetchId = cells[i]; if (fetchId != null) { context.require((long) fetchId); } } inputValues.add(cells); } @Override public CompletableFuture<Iterator<? extends Row>> processBatch(boolean isLastBatch) { List<CompletableFuture<IntObjectMap<? extends Bucket>>> futures = new ArrayList<>(); Iterator<Map.Entry<String, IntSet>> it = context.nodeToReaderIds.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, IntSet> entry = it.next(); IntObjectHashMap<IntContainer> toFetch = generateToFetch(entry.getValue()); if (toFetch.isEmpty() && !isLastBatch) { continue; } final String nodeId = entry.getKey(); try { futures.add(fetchOperation.fetch(nodeId, toFetch, isLastBatch)); } catch (Throwable t) { futures.add(CompletableFuture.failedFuture(t)); } if (isLastBatch) { it.remove(); } } return CompletableFutures.allAsList(futures).thenApply(this::getRows); } @Override public void close() { for (String nodeId : context.nodeToReaderIds.keySet()) { fetchOperation.fetch(nodeId, new IntObjectHashMap<>(0), true) .exceptionally(e -> { LOGGER.error("Error sending close fetchRequest to node={}", e, nodeId); return null; }); } } @Override public void reset() { context.clearBuckets(); inputValues.clear(); } private Iterator<? extends Row> getRows(List<IntObjectMap<? extends Bucket>> results) { applyResultToReaderBuckets(results); return new Iterator<Row>() { final int[] fetchIdPositions = collectRowContext.fetchIdPositions(); final UnsafeArrayRow inputRow = collectRowContext.inputRow(); final UnsafeArrayRow[] fetchRows = collectRowContext.fetchRows(); final UnsafeArrayRow[] partitionRows = collectRowContext.partitionRows(); final Object[][] nullCells = collectRowContext.nullCells(); int idx = 0; @Override public boolean hasNext() { return idx < inputValues.size(); } @Override public Row next() { if (!hasNext()) { throw new NoSuchElementException("Iterator is exhausted"); } Object[] cells = inputValues.get(idx); inputRow.cells(cells); for (int i = 0; i < fetchIdPositions.length; i++) { Object fetchIdObj = cells[fetchIdPositions[i]]; if (fetchIdObj == null) { fetchRows[i].cells(nullCells[i]); continue; } long fetchId = (long) fetchIdObj; int readerId = FetchId.decodeReaderId(fetchId); int docId = FetchId.decodeDocId(fetchId); ReaderBucket readerBucket = context.getReaderBucket(readerId); assert readerBucket != null : "readerBucket must not be null"; setPartitionRow(partitionRows, i, readerBucket); fetchRows[i].cells(readerBucket.get(docId)); assert !readerBucket.fetchRequired() || fetchRows[i].cells() != null : "readerBucket doesn't require fetch or row is fetched"; } idx++; if (!hasNext()) { // free up memory - in case we're streaming data to the client // this would otherwise grow to hold the whole result in-memory reset(); } return outputRow; } }; } @Override public int batchSize() { return fetchSize; } private void applyResultToReaderBuckets(List<IntObjectMap<? extends Bucket>> results) { for (IntObjectMap<? extends Bucket> result : results) { if (result == null) { continue; } for (IntObjectCursor<? extends Bucket> cursor : result) { ReaderBucket readerBucket = context.getReaderBucket(cursor.key); readerBucket.fetched(cursor.value); } } } private IntObjectHashMap<IntContainer> generateToFetch(IntSet readerIds) { IntObjectHashMap<IntContainer> toFetch = new IntObjectHashMap<>(readerIds.size()); for (IntCursor readerIdCursor : readerIds) { ReaderBucket readerBucket = context.readerBucket(readerIdCursor.value); if (readerBucket != null && readerBucket.fetchRequired() && readerBucket.docs.size() > 0) { toFetch.put(readerIdCursor.value, readerBucket.docs.keys()); } } return toFetch; } private void setPartitionRow(UnsafeArrayRow[] partitionRows, int i, ReaderBucket readerBucket) { if (partitionRows != null && partitionRows[i] != null) { assert readerBucket.partitionValues != null : "readerBucket's partitionValues must not be null"; partitionRows[i].cells(readerBucket.partitionValues); } } }
40.959276
114
0.628038
3b4fb128db1a0256a376e8636c4d583fdf9c3a40
10,319
/* * Copyright (c) 2017 by Gerrit Grunwald * * 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 eu.hansolo.tilesfx.tools; import eu.hansolo.tilesfx.events.TreeNodeEvent; import eu.hansolo.tilesfx.events.TreeNodeEvent.EventType; import eu.hansolo.tilesfx.events.TreeNodeEventListener; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; import java.util.stream.Stream; public class TreeNode<T> { private final TreeNodeEvent PARENT_CHANGED = new TreeNodeEvent(TreeNode.this, EventType.PARENT_CHANGED); private final TreeNodeEvent CHILDREN_CHANGED = new TreeNodeEvent(TreeNode.this, EventType.CHILDREN_CHANGED); private final TreeNodeEvent CHILD_ADDED = new TreeNodeEvent(TreeNode.this, EventType.CHILD_ADDED); private final TreeNodeEvent CHILD_REMOVED = new TreeNodeEvent(TreeNode.this, EventType.CHILD_REMOVED); private T item; private TreeNode parent; private TreeNode myRoot; private TreeNode treeRoot; private int depth; private ObservableList<TreeNode<T>> children; private List<TreeNodeEventListener> listeners; private ListChangeListener<TreeNode> childNodeListener; // ******************** Constructors ************************************** public TreeNode(final T ITEM) { this(ITEM, null); } public TreeNode(final T ITEM, final TreeNode<T> PARENT) { item = ITEM; parent = PARENT; depth = -1; children = FXCollections.observableArrayList(); listeners = new CopyOnWriteArrayList<>(); childNodeListener = c -> { TreeNode<T> treeRoot = getTreeRoot(); while (c.next()) { if (c.wasAdded()) { c.getAddedSubList().forEach(addedNode -> { addedNode.getNodes().forEach(node -> { if (null != treeRoot) { treeRoot.fireTreeNodeEvent(CHILD_ADDED); } }); }); } else if (c.wasRemoved()) { c.getRemoved().forEach(removedNode -> { removedNode.getNodes().forEach(node -> { if (null != treeRoot) { treeRoot.fireTreeNodeEvent(CHILD_REMOVED); } }); }); } } if (null != treeRoot) { treeRoot.fireTreeNodeEvent(CHILDREN_CHANGED); } }; init(); } // ******************** Methods ******************************************* private void init() { // Add this node to parents children if (null != parent && !parent.getChildren().contains(TreeNode.this)) { parent.getChildren().add(TreeNode.this); } children.addListener(childNodeListener); } public boolean isRoot() { return null == parent; } public boolean isLeaf() { return (null == children || children.isEmpty()); } public boolean hasParent() { return null != parent; } public void removeParent() { parent = null; myRoot = null; treeRoot = null; depth = -1; getTreeRoot().fireTreeNodeEvent(PARENT_CHANGED); } public TreeNode<T> getParent() { return parent; } public void setParent(final TreeNode<T> PARENT) { if (null == PARENT || PARENT.getChildren().contains(TreeNode.this)) { return; } PARENT.getChildren().add(TreeNode.this); parent = PARENT; myRoot = null; treeRoot = null; depth = -1; getTreeRoot().fireTreeNodeEvent(PARENT_CHANGED); } public T getItem() { return item; } public void setItem(final T ITEM) { item = ITEM; } public List<TreeNode<T>> getChildrenUnmodifiable() { return Collections.unmodifiableList(children); } public List<TreeNode<T>> getChildren() { return children; } public void setChildren(final List<TreeNode<T>> CHILDREN) { children.setAll(new LinkedHashSet<>(CHILDREN)); } public void addNode(final T ITEM) { TreeNode<T> child = new TreeNode<>(ITEM); child.setParent(this); children.add(child); } public void addNode(final TreeNode<T> NODE) { if (children.contains(NODE)) { return; } NODE.setParent(this); } public void removeNode(final TreeNode<T> NODE) { if (children.contains(NODE)) { children.removeListener(childNodeListener); children.remove(NODE); children.addListener(childNodeListener); return; } children.removeListener(childNodeListener); for (int i = 0, size = children.size() ; i < size ; i++) { TreeNode<T> n = children.get(i); if (n.getChildren().contains(NODE)) { n.getChildren().remove(NODE); children.addListener(childNodeListener); return; } } children.addListener(childNodeListener); } public void addNodes(final TreeNode<T>... NODES) { addNodes(Arrays.asList(NODES)); } public void addNodes(final List<TreeNode<T>> NODES) { NODES.forEach(node -> addNode(node)); } public void removeNodes(final TreeNode<T>... NODES) { removeNodes(Arrays.asList(NODES)); } public void removeNodes(final List<TreeNode<T>> NODES) { NODES.forEach(node -> removeNode(node)); } public void removeAllNodes() { children.clear(); } public Stream<TreeNode<T>> stream() { if (isLeaf()) { return Stream.of(this); } else { return getChildren().stream() .map(child -> child.stream()) .reduce(Stream.of(this), (s1, s2) -> Stream.concat(s1, s2)); } } public Stream<TreeNode<T>> lazyStream() { if (isLeaf()) { return Stream.of(this); } else { return Stream.concat(Stream.of(this), getChildren().stream().flatMap(TreeNode::stream)); } } public Stream<TreeNode<T>> flattened() { return Stream.concat(Stream.of(this), children.stream().flatMap(TreeNode::flattened)); } public List<TreeNode<T>> getAll() { return flattened().collect(Collectors.toList()); } public List<T> getAllItems() { return flattened().map(TreeNode::getItem).collect(Collectors.toList()); } public List<TreeNode<T>> getNodes() { return flattened().collect(Collectors.toList()); } public int getNoOfNodes() { return flattened().map(TreeNode::getItem).collect(Collectors.toList()).size(); } public int getNoOfLeafNodes() { return flattened().filter(node -> node.isLeaf()).map(TreeNode::getItem).collect(Collectors.toList()).size(); } public boolean contains(final TreeNode<T> NODE) { return flattened().anyMatch(n -> n.equals(NODE)); } public boolean containsData(final T ITEM) { return flattened().anyMatch(n -> n.item.equals(ITEM)); } public TreeNode<T> getMyRoot() { if (null == myRoot) { if (null != getParent() && getParent().isRoot()) { myRoot = this; } else { myRoot = getMyRoot(getParent()); } } return myRoot; } private TreeNode<T> getMyRoot(final TreeNode<T> NODE) { if (NODE.getParent().isRoot()) { return NODE; } return getMyRoot(NODE.getParent()); } public TreeNode<T> getTreeRoot() { if (null == treeRoot) { if (isRoot()) { treeRoot = this; } else { treeRoot = getTreeRoot(getParent()); } } return treeRoot; } private TreeNode<T> getTreeRoot(final TreeNode<T> NODE) { if (NODE.isRoot()) { return NODE; } return getTreeRoot(NODE.getParent()); } public int getDepth() { if (depth == -1) { if (isRoot()) { depth = 0; } else { depth = getDepth(getParent(), 0); } } return depth; } private int getDepth(final TreeNode<T> NODE, int depth) { depth++; if (NODE.isRoot()) { return depth; } return getDepth(NODE.getParent(), depth); } public int getMaxLevel() { return getTreeRoot().stream().map(TreeNode::getDepth).max(Comparator.naturalOrder()).orElse(0); } public List<TreeNode<T>> getSiblings() { return null == getParent() ? new ArrayList<>() : getParent().getChildren(); } public List<TreeNode<T>> nodesAtSameLevel() { final int LEVEL = getDepth(); return getTreeRoot().stream().filter(node -> node.getDepth() == LEVEL).collect(Collectors.toList()); } // ******************** Event handling ************************************ public void setOnTreeNodeEvent(final TreeNodeEventListener LISTENER) { addTreeNodeEventListener(LISTENER); } public void addTreeNodeEventListener(final TreeNodeEventListener LISTENER) { if (!listeners.contains(LISTENER)) listeners.add(LISTENER); } public void removeTreeNodeEventListener(final TreeNodeEventListener LISTENER) { if (listeners.contains(LISTENER)) listeners.remove(LISTENER); } public void removeAllTreeNodeEventListeners() { listeners.clear(); } public void fireTreeNodeEvent(final TreeNodeEvent EVENT) { for (TreeNodeEventListener listener : listeners) { listener.onTreeNodeEvent(EVENT); } } }
40.308594
147
0.601512
881be3a96aa907149093bf892fcafe0647b153c8
2,949
package com.smartpro.mis.modular.system.controller; import com.baomidou.mybatisplus.mapper.SqlRunner; import com.baomidou.mybatisplus.plugins.Page; import com.smartpro.mis.core.base.controller.BaseController; import com.smartpro.mis.core.common.annotion.BussinessLog; import com.smartpro.mis.core.common.annotion.Permission; import com.smartpro.mis.core.common.constant.Const; import com.smartpro.mis.core.common.constant.factory.PageFactory; import com.smartpro.mis.core.common.constant.state.BizLogType; import com.smartpro.mis.core.support.BeanKit; import com.smartpro.mis.modular.system.model.OperationLog; import com.smartpro.mis.modular.system.service.IOperationLogService; import com.smartpro.mis.modular.system.warpper.LogWarpper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; import java.util.Map; /** * 日志管理的控制器 * * @author mengiy * @Date 2017年4月5日 19:45:36 */ @Controller @RequestMapping("/log") public class LogController extends BaseController { private static String PREFIX = "/system/log/"; @Autowired private IOperationLogService operationLogService; /** * 跳转到日志管理的首页 */ @RequestMapping("") public String index() { return PREFIX + "log.html"; } /** * 查询操作日志列表 */ @RequestMapping("/list") // @Permission(Const.ADMIN_NAME) @ResponseBody public Object list(@RequestParam(required = false) String beginTime, @RequestParam(required = false) String endTime, @RequestParam(required = false) String logName, @RequestParam(required = false) Integer logType) { Page<OperationLog> page = new PageFactory<OperationLog>().defaultPage(); List<Map<String, Object>> result = operationLogService.getOperationLogs(page, beginTime, endTime, logName, BizLogType.valueOf(logType), page.getOrderByField(), page.isAsc()); page.setRecords((List<OperationLog>) new LogWarpper(result).warp()); return super.packForBT(page); } /** * 查询操作日志详情 */ @RequestMapping("/detail/{id}") @Permission(Const.ADMIN_NAME) @ResponseBody public Object detail(@PathVariable Integer id) { OperationLog operationLog = operationLogService.selectById(id); Map<String, Object> stringObjectMap = BeanKit.beanToMap(operationLog); return super.warpObject(new LogWarpper(stringObjectMap)); } /** * 清空日志 */ @BussinessLog(value = "清空业务日志") @RequestMapping("/delLog") @Permission(Const.ADMIN_NAME) @ResponseBody public Object delLog() { SqlRunner.db().delete("delete from sys_operation_log"); return SUCCESS_TIP; } }
34.694118
219
0.736521
e64ad51482cf05a0e1a9dc4faddca3e82fd6ab31
2,185
package cfvbaibai.cardfantasy.engine.skill; import cfvbaibai.cardfantasy.GameUI; import cfvbaibai.cardfantasy.Randomizer; import cfvbaibai.cardfantasy.data.Skill; import cfvbaibai.cardfantasy.engine.*; import java.util.List; public final class TaoistNature { public static void apply(SkillResolver resolver, SkillUseInfo skillUseInfo, CardInfo attacker, Player defender) throws HeroDieSignal { StageInfo stage = resolver.getStage(); GameUI ui = stage.getUI(); List<CardInfo> livingCards = attacker.getOwner().getField().getAliveCards(); /*天:1,地:10,人:100 1.死亡链接,2.古神的低语3.圣炎,10.全体送还,20.地裂,30:全体阻碍2,100:祈愿2,200:集结,300:全体加速2*/ int judgeNumber = 0; for(CardInfo liveCard:livingCards){ if("天".equals(liveCard.getName())){ judgeNumber += 1; } else if("地".equals(liveCard.getName())){ judgeNumber += 10; } else if("人".equals(liveCard.getName())){ judgeNumber += 100; } } if(judgeNumber >=300){ AllSpeedUp.apply(skillUseInfo, resolver, attacker); } else if(judgeNumber >=200){ HandCardAddSkillNormalType.apply(resolver,skillUseInfo.getAttachedUseInfo1(),attacker,skillUseInfo.getAttachedUseInfo1().getAttachedUseInfo1().getSkill(),1,1); } else if(judgeNumber >=100){ Supplication.apply(resolver, skillUseInfo, attacker, defender); } else if(judgeNumber >=30){ AllDelay.apply(skillUseInfo, resolver, attacker, defender); } else if(judgeNumber >=20){ GiantEarthquakesLandslides.apply(resolver, skillUseInfo.getSkill(), attacker, defender, 1); } else if(judgeNumber >=10){ ReturnNumber.apply(resolver, skillUseInfo.getSkill(), attacker, defender, -1); } else if(judgeNumber >=3){ HolyFire.apply(skillUseInfo.getSkill(), resolver, attacker, defender); } else if(judgeNumber >=2){ Ancient.apply(resolver, skillUseInfo, attacker, defender, 3, 1); } else if(judgeNumber >=1){ SoulLink.apply(resolver, skillUseInfo, attacker, defender, 5, 3); } } }
44.591837
171
0.645767
113417b2d46f7530721644836a2377dcf6f499aa
3,884
package com.dse.dseMod.block; import net.minecraft.block.BlockSlab; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.IStringSerializable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public abstract class BlockDirectionedSlab extends BlockSlab { public static final PropertyEnum<Variant> VARIANT = PropertyEnum.<Variant>create("variant", Variant.class); public BlockDirectionedSlab() { super(Material.WOOD); IBlockState iblockstate = this.blockState.getBaseState().withProperty(VARIANT, Variant.DEFAULT); if(!this.isDouble()) { iblockstate.withProperty(HALF, BlockSlab.EnumBlockHalf.BOTTOM); } this.setDefaultState(iblockstate); this.useNeighborBrightness = !this.isDouble(); } @Override public String getUnlocalizedName(int meta) { // TODO 自動生成されたメソッド・スタブ return this.getUnlocalizedName(); } @Override public boolean isDouble() { // TODO 自動生成されたメソッド・スタブ return true; } @Override public IProperty<?> getVariantProperty() { // TODO 自動生成されたメソッド・スタブ return VARIANT; } @Override public Comparable<?> getTypeForItem(ItemStack stack) { // TODO 自動生成されたメソッド・スタブ return Variant.byMetadata(stack.getMetadata() & 1); } public Comparable<?> getTypeForItemByDirection(EnumFacing facing){ return Variant.byEnumFacing(facing); } @Override public final IBlockState getStateFromMeta(final int meta) { IBlockState blockstate = this.blockState.getBaseState().withProperty(VARIANT, Variant.byMetadata(meta & 1)); if(!this.isDouble()) { blockstate = blockstate.withProperty(HALF, ((meta&8)!=0)?EnumBlockHalf.TOP:EnumBlockHalf.BOTTOM); } return blockstate; } @Override public final int getMetaFromState(final IBlockState state) { int meta = 0; if(!this.isDouble()&& state.getValue(HALF)==EnumBlockHalf.TOP) { meta |= 8; } if(state.getValue(VARIANT) == Variant.ROTATE) { meta |= 1; } return meta; } @Override protected BlockStateContainer createBlockState() { if(!this.isDouble()){ return new BlockStateContainer(this, new IProperty[] {VARIANT, HALF}); } return new BlockStateContainer(this, new IProperty[] {VARIANT}); } //@Override //public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) //{ //} @Override public IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { IBlockState state = super.getStateForPlacement(worldIn, pos, facing, hitX, hitY, hitZ, meta, placer); if(placer.getHorizontalFacing() == EnumFacing.EAST || placer.getHorizontalFacing() == EnumFacing.WEST) { state = state.withProperty(VARIANT, Variant.DEFAULT); }else { state = state.withProperty(VARIANT, Variant.ROTATE); } return state; } public static enum Variant implements IStringSerializable { DEFAULT("default"), ROTATE("rotate"); private String direction; private Variant(String name) { this.direction = name; } public static Variant byMetadata(int meta) { if (meta == 0) { return Variant.DEFAULT; } return Variant.ROTATE; } public static Variant byEnumFacing(EnumFacing facing) { if(facing == EnumFacing.EAST || facing == EnumFacing.WEST) { return Variant.DEFAULT; }else { return Variant.ROTATE; } } @Override public String getName() { return this.direction; } } }
26.786207
162
0.709835
b2648b519cb72b4f479a49afb9f1534a4998bb42
1,308
package com.stylefeng.guns.api.controller.order; import com.baomidou.mybatisplus.plugins.pagination.PageHelper; import com.stylefeng.guns.api.order.OrderService; import com.stylefeng.guns.api.order.VO.OrderVO; import com.alibaba.dubbo.config.annotation.Reference; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("/order") public class Order1Controller { @Reference(interfaceClass = OrderService.class ,check = false) OrderService orderService; @RequestMapping("getOrderInfo") public Map<String, Object> getOrderInfo(int nowPage,int pageSize,Integer userId) { PageHelper.startPage(nowPage,pageSize); Map<String, Object> map = new HashMap<>(); List<OrderVO> orderList = orderService.getOrderByUserId(userId); if(orderList.size()==0){ map.put("status",1); map.put("msg","订单列表为空哦!~"); }else if(orderList.size()>0){ map.put("status",0); map.put("msg",""); }else { map.put("status",999); map.put("msg","系统出现异常,请联系管理员"); } map.put("data",orderList); return map; } }
33.538462
86
0.678135
36a4f48cd16ceaf7d2989f489506c4e0249857c1
759
package br.com.jornadacolaborativa.microservice.payment.saga.payment.model; import br.com.jornadacolaborativa.microservice.payment.saga.payment.enums.TransactionStatus; import lombok.Getter; import lombok.ToString; @ToString @Getter public class TransactionEvent implements Event { private static final String EVENT = "Transaction"; private Integer orderId; private TransactionStatus status; public TransactionEvent() { } public TransactionEvent orderId(Integer orderId) { this.orderId = orderId; return this; } public TransactionEvent status(TransactionStatus status) { this.status = status; return this; } @Override public String getEvent() { return EVENT; } }
22.323529
92
0.714097
10f1bfbeb5290f2378c14d1936f80ec1070716ff
49,614
package annotator; import annotator.find.AnnotationInsertion; import annotator.find.CastInsertion; import annotator.find.ConstructorInsertion; import annotator.find.Criteria; import annotator.find.GenericArrayLocationCriterion; import annotator.find.Insertion; import annotator.find.Insertions; import annotator.find.NewInsertion; import annotator.find.ReceiverInsertion; import annotator.find.TreeFinder; import annotator.find.TypedInsertion; import annotator.scanner.LocalVariableScanner; import annotator.scanner.TreePathUtil; import annotator.specification.IndexFileSpecification; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.tree.JCTree; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.objectweb.asm.TypePath; import org.plumelib.options.Option; import org.plumelib.options.OptionGroup; import org.plumelib.options.Options; import org.plumelib.reflection.ReflectionPlume; import org.plumelib.util.FileIOException; import org.plumelib.util.FilesPlume; import org.plumelib.util.Pair; import scenelib.annotations.Annotation; import scenelib.annotations.el.ABlock; import scenelib.annotations.el.AClass; import scenelib.annotations.el.ADeclaration; import scenelib.annotations.el.AElement; import scenelib.annotations.el.AExpression; import scenelib.annotations.el.AField; import scenelib.annotations.el.AMethod; import scenelib.annotations.el.AScene; import scenelib.annotations.el.ATypeElement; import scenelib.annotations.el.ATypeElementWithType; import scenelib.annotations.el.AnnotationDef; import scenelib.annotations.el.DefException; import scenelib.annotations.el.ElementVisitor; import scenelib.annotations.el.LocalLocation; import scenelib.annotations.el.TypePathEntry; import scenelib.annotations.io.ASTIndex; import scenelib.annotations.io.ASTPath; import scenelib.annotations.io.ASTRecord; import scenelib.annotations.io.DebugWriter; import scenelib.annotations.io.IndexFileParser; import scenelib.annotations.io.IndexFileWriter; import scenelib.annotations.util.CommandLineUtils; import scenelib.annotations.util.coll.VivifyingMap; /** * This is the main class for the annotator, which inserts annotations in Java source code. You can * call it as {@code java annotator.Main} or by using the shell script {@code * insert-annotations-to-source}. * * <p>It takes as input * * <ul> * <li>annotation (index) files, which indicate the annotations to insert * <li>Java source files, into which the annotator inserts annotations * </ul> * * Annotations that are not for the specified Java files are ignored. * * <p>The <a id="command-line-options">command-line options</a> are as follows: * <!-- start options doc (DO NOT EDIT BY HAND) --> * * <ul> * <li id="optiongroup:General-options">General options * <ul> * <li id="option:outdir"><b>-d</b> <b>--outdir=</b><i>directory</i>. Directory in which * output files are written. [default annotated/] * <li id="option:in-place"><b>-i</b> <b>--in-place=</b><i>boolean</i>. If true, overwrite * original source files (making a backup first). Furthermore, if the backup files * already exist, they are used instead of the .java files. This behavior permits a user * to tweak the {@code .jaif} file and re-run the annotator. * <p>Note that if the user runs the annotator with --in-place, makes edits, and then * re-runs the annotator with this --in-place option, those edits are lost. Similarly, * if the user runs the annotator twice in a row with --in-place, only the last set of * annotations will appear in the codebase at the end. * <p>To preserve changes when using the --in-place option, first remove the backup * files. Or, use the {@code -d .} option, which makes (and reads) no backup, instead of * --in-place. [default false] * <li id="option:abbreviate"><b>-a</b> <b>--abbreviate=</b><i>boolean</i>. If true, insert * {@code import} statements as necessary. [default true] * <li id="option:comments"><b>-c</b> <b>--comments=</b><i>boolean</i>. Insert annotations * in comments [default false] * <li id="option:omit-annotation"><b>-o</b> <b>--omit-annotation=</b><i>string</i>. Omit * given annotation * <li id="option:nowarn"><b>--nowarn=</b><i>boolean</i>. Suppress warnings about disallowed * insertions [default false] * <li id="option:convert-jaifs"><b>--convert-jaifs=</b><i>boolean</i>. Convert JAIFs to AST * Path format [default false] * <li id="option:help"><b>-h</b> <b>--help=</b><i>boolean</i>. Print usage information and * exit [default false] * </ul> * <li id="optiongroup:Debugging-options">Debugging options * <ul> * <li id="option:verbose"><b>-v</b> <b>--verbose=</b><i>boolean</i>. Verbose (print * progress information) [default false] * <li id="option:debug"><b>--debug=</b><i>boolean</i>. Debug (print debug information) * [default false] * <li id="option:print-error-stack"><b>--print-error-stack=</b><i>boolean</i>. Print error * stack [default false] * </ul> * </ul> * * <!-- end options doc --> */ public class Main { /** The system-specific file separator. */ private static String fileSep = System.getProperty("file.separator"); // Options /** Directory in which output files are written. */ @OptionGroup("General options") @Option("-d <directory> Directory in which output files are written") public static String outdir = "annotated/"; /** * If true, overwrite original source files (making a backup first). Furthermore, if the backup * files already exist, they are used instead of the .java files. This behavior permits a user to * tweak the {@code .jaif} file and re-run the annotator. * * <p>Note that if the user runs the annotator with --in-place, makes edits, and then re-runs the * annotator with this --in-place option, those edits are lost. Similarly, if the user runs the * annotator twice in a row with --in-place, only the last set of annotations will appear in the * codebase at the end. * * <p>To preserve changes when using the --in-place option, first remove the backup files. Or, use * the {@code -d .} option, which makes (and reads) no backup, instead of --in-place. */ @Option("-i Overwrite original source files") public static boolean in_place = false; /** If true, insert {@code import} statements as necessary. */ @Option("-a Abbreviate annotation names") public static boolean abbreviate = true; @Option("-c Insert annotations in comments") public static boolean comments = false; @Option("-o Omit given annotation") public static String omit_annotation; @Option("Suppress warnings about disallowed insertions") public static boolean nowarn; // Instead of doing insertions, create new JAIFs using AST paths // extracted from existing JAIFs and source files they match @Option("Convert JAIFs to AST Path format, but do no insertion into source") public static boolean convert_jaifs = false; @Option("-h Print usage information and exit") public static boolean help = false; // Debugging options go below here. @OptionGroup("Debugging options") @Option("-v Verbose (print progress information)") public static boolean verbose = false; @Option("Debug (print debug information)") public static boolean debug = false; @Option("Print error stack") public static boolean print_error_stack = false; // TODO: remove this. public static boolean temporaryDebug = false; private static ElementVisitor<Void, AElement> classFilter = new ElementVisitor<Void, AElement>() { <K, V extends AElement> Void filter(VivifyingMap<K, V> vm0, VivifyingMap<K, V> vm1) { for (Map.Entry<K, V> entry : vm0.entrySet()) { entry.getValue().accept(this, vm1.getVivify(entry.getKey())); } return null; } @Override public Void visitAnnotationDef(AnnotationDef def, AElement el) { // not used, since package declarations not handled here return null; } @Override public Void visitBlock(ABlock el0, AElement el) { ABlock el1 = (ABlock) el; filter(el0.locals, el1.locals); return visitExpression(el0, el); } @Override public Void visitClass(AClass el0, AElement el) { AClass el1 = (AClass) el; filter(el0.methods, el1.methods); filter(el0.fields, el1.fields); filter(el0.fieldInits, el1.fieldInits); filter(el0.staticInits, el1.staticInits); filter(el0.instanceInits, el1.instanceInits); return visitDeclaration(el0, el); } @Override public Void visitDeclaration(ADeclaration el0, AElement el) { ADeclaration el1 = (ADeclaration) el; VivifyingMap<ASTPath, ATypeElement> insertAnnotations = el1.insertAnnotations; VivifyingMap<ASTPath, ATypeElementWithType> insertTypecasts = el1.insertTypecasts; for (Map.Entry<ASTPath, ATypeElement> entry : el0.insertAnnotations.entrySet()) { ASTPath p = entry.getKey(); ATypeElement e = entry.getValue(); insertAnnotations.put(p, e); // visitTypeElement(e, insertAnnotations.getVivify(p)); } for (Map.Entry<ASTPath, ATypeElementWithType> entry : el0.insertTypecasts.entrySet()) { ASTPath p = entry.getKey(); ATypeElementWithType e = entry.getValue(); scenelib.type.Type type = e.getType(); if (type instanceof scenelib.type.DeclaredType && ((scenelib.type.DeclaredType) type).getName().isEmpty()) { insertAnnotations.put(p, e); // visitTypeElement(e, insertAnnotations.getVivify(p)); } else { insertTypecasts.put(p, e); // visitTypeElementWithType(e, insertTypecasts.getVivify(p)); } } return null; } @Override public Void visitExpression(AExpression el0, AElement el) { AExpression el1 = (AExpression) el; filter(el0.typecasts, el1.typecasts); filter(el0.instanceofs, el1.instanceofs); filter(el0.news, el1.news); return null; } @Override public Void visitField(AField el0, AElement el) { return visitDeclaration(el0, el); } @Override public Void visitMethod(AMethod el0, AElement el) { AMethod el1 = (AMethod) el; filter(el0.bounds, el1.bounds); el0.returnType.accept(this, el1.returnType); el0.receiver.accept(this, el1.receiver); filter(el0.parameters, el1.parameters); filter(el0.throwsException, el1.throwsException); filter(el0.preconditions, el1.preconditions); filter(el0.postconditions, el1.postconditions); el0.body.accept(this, el1.body); return visitDeclaration(el0, el); } @Override public Void visitTypeElement(ATypeElement el0, AElement el) { ATypeElement el1 = (ATypeElement) el; filter(el0.innerTypes, el1.innerTypes); return null; } @Override public Void visitTypeElementWithType(ATypeElementWithType el0, AElement el) { ATypeElementWithType el1 = (ATypeElementWithType) el; el1.setType(el0.getType()); return visitTypeElement(el0, el); } @Override public Void visitElement(AElement el, AElement arg) { return null; } }; private static AScene filteredScene(final AScene scene) { final AScene filtered = new AScene(); filtered.packages.putAll(scene.packages); filtered.imports.putAll(scene.imports); for (Map.Entry<String, AClass> entry : scene.classes.entrySet()) { String key = entry.getKey(); AClass clazz0 = entry.getValue(); AClass clazz1 = filtered.classes.getVivify(key); clazz0.accept(classFilter, clazz1); } filtered.prune(); return filtered; } private static ATypeElement findInnerTypeElement( ASTRecord rec, ADeclaration decl, Insertion ins) { ASTPath astPath = rec.astPath; GenericArrayLocationCriterion galc = ins.getCriteria().getGenericArrayLocation(); assert astPath != null && galc != null; List<TypePathEntry> tpes = galc.getLocation(); ASTPath.ASTEntry entry; for (TypePathEntry tpe : tpes) { switch (tpe.step) { case TypePath.ARRAY_ELEMENT: if (!astPath.isEmpty()) { entry = astPath.getLast(); if (entry.getTreeKind() == Tree.Kind.NEW_ARRAY && entry.childSelectorIs(ASTPath.TYPE)) { entry = new ASTPath.ASTEntry(Tree.Kind.NEW_ARRAY, ASTPath.TYPE, entry.getArgument() + 1); break; } } entry = new ASTPath.ASTEntry(Tree.Kind.ARRAY_TYPE, ASTPath.TYPE); break; case TypePath.INNER_TYPE: entry = new ASTPath.ASTEntry(Tree.Kind.MEMBER_SELECT, ASTPath.EXPRESSION); break; case TypePath.TYPE_ARGUMENT: entry = new ASTPath.ASTEntry( Tree.Kind.PARAMETERIZED_TYPE, ASTPath.TYPE_ARGUMENT, tpe.argument); break; case TypePath.WILDCARD_BOUND: entry = new ASTPath.ASTEntry(Tree.Kind.UNBOUNDED_WILDCARD, ASTPath.BOUND); break; default: throw new IllegalArgumentException("unknown type tag " + tpe.step); } astPath = astPath.extend(entry); } return decl.insertAnnotations.getVivify(astPath); } private static void convertInsertion( String pkg, JCTree.JCCompilationUnit tree, ASTRecord rec, Insertion ins, AScene scene, Multimap<Insertion, Annotation> insertionSources) { Collection<Annotation> annos = insertionSources.get(ins); if (rec == null) { if (ins.getCriteria().isOnPackage()) { for (Annotation anno : annos) { scene.packages.get(pkg).tlAnnotationsHere.add(anno); } } } else if (scene != null && rec.className != null) { AClass clazz = scene.classes.getVivify(rec.className); ADeclaration decl = null; // insertion target if (ins.getCriteria().onBoundZero()) { int n = rec.astPath.size(); if (!rec.astPath.get(n - 1).childSelectorIs(ASTPath.BOUND)) { ASTPath astPath = ASTPath.empty(); for (int i = 0; i < n; i++) { astPath = astPath.extend(rec.astPath.get(i)); } astPath = astPath.extend(new ASTPath.ASTEntry(Tree.Kind.TYPE_PARAMETER, ASTPath.BOUND, 0)); rec = rec.replacePath(astPath); } } if (rec.methodName == null) { decl = rec.varName == null ? clazz : clazz.fields.getVivify(rec.varName); } else { AMethod meth = clazz.methods.getVivify(rec.methodName); if (rec.varName == null) { decl = meth; // ? } else { try { int i = Integer.parseInt(rec.varName); decl = i < 0 ? meth.receiver : meth.parameters.getVivify(i); } catch (NumberFormatException e) { TreePath path = ASTIndex.getTreePath(tree, rec); JCTree.JCVariableDecl varTree = null; JCTree.JCMethodDecl methTree = null; loop: while (path != null) { Tree leaf = path.getLeaf(); switch (leaf.getKind()) { case VARIABLE: varTree = (JCTree.JCVariableDecl) leaf; break; case METHOD: methTree = (JCTree.JCMethodDecl) leaf; break; case ANNOTATION: case CLASS: case ENUM: case INTERFACE: break loop; default: path = path.getParentPath(); } } while (path != null) { Tree leaf = path.getLeaf(); Tree.Kind kind = leaf.getKind(); if (kind == Tree.Kind.METHOD) { methTree = (JCTree.JCMethodDecl) leaf; int i = LocalVariableScanner.indexOfVarTree(path, varTree, rec.varName); int m = methTree.getStartPosition(); int a = varTree.getStartPosition(); int b = varTree.getEndPosition(tree.endPositions); LocalLocation loc = new LocalLocation(i, a - m, b - a); decl = meth.body.locals.getVivify(loc); break; } if (ASTPath.isClassEquiv(kind)) { // classTree = (JCTree.JCClassDecl) leaf; // ??? break; } path = path.getParentPath(); } } } } if (decl != null) { AElement el; if (rec.astPath.isEmpty()) { el = decl; } else if (ins.getKind() == Insertion.Kind.CAST) { scenelib.annotations.el.ATypeElementWithType elem = decl.insertTypecasts.getVivify(rec.astPath); elem.setType(((CastInsertion) ins).getType()); el = elem; } else { el = decl.insertAnnotations.getVivify(rec.astPath); } for (Annotation anno : annos) { el.tlAnnotationsHere.add(anno); } if (ins instanceof TypedInsertion) { TypedInsertion ti = (TypedInsertion) ins; if (!rec.astPath.isEmpty()) { // addInnerTypePaths(decl, rec, ti, insertionSources); } for (Insertion inner : ti.getInnerTypeInsertions()) { Tree t = ASTIndex.getNode(tree, rec); if (t != null) { ATypeElement elem = findInnerTypeElement(rec, decl, inner); for (Annotation a : insertionSources.get(inner)) { elem.tlAnnotationsHere.add(a); } } } } } } } // Implementation details: // 1. The annotator partially compiles source // files using the compiler API (JSR-199), obtaining an AST. // 2. The annotator reads the specification file, producing a set of // annotator.find.Insertions. Insertions completely specify what to // write (as a String, which is ultimately translated according to the // keyword file) and how to write it (as annotator.find.Criteria). // 3. It then traverses the tree, looking for nodes that satisfy the // Insertion Criteria, translating the Insertion text against the // keyword file, and inserting the annotations into the source file. /** * Runs the annotator, parsing the source and spec files and applying the annotations. * * @param args .jaif files and/or .java files and/or @arg-files, in any order */ @SuppressWarnings({ "ReferenceEquality", // interned operand "EmptyCatch", // TODO }) public static void main(String[] args) throws IOException { if (verbose) { System.out.printf( "insert-annotations-to-source (%s)%n", scenelib.annotations.io.classfile.ClassFileReader.INDEX_UTILS_VERSION); } Options options = new Options( "java annotator.Main [options] { jaif-file | java-file | @arg-file } ..." + System.lineSeparator() + "(Contents of argfiles are expanded into the argument list.)", Main.class); String[] cl_args; String[] file_args; try { cl_args = CommandLineUtils.parseCommandLine(args); file_args = options.parse(true, cl_args); } catch (Exception ex) { System.err.println(ex); System.err.println("(For non-argfile beginning with \"@\", use \"@@\" for initial \"@\"."); System.err.println("Alternative for filenames: indicate directory, e.g. as './@file'."); System.err.println("Alternative for flags: use '=', as in '-o=@Deprecated'.)"); System.exit(1); throw new Error("Unreachable"); } DebugWriter dbug = new DebugWriter(debug); DebugWriter verb = new DebugWriter(verbose); TreeFinder.warn.setEnabled(!nowarn); TreeFinder.dbug.setEnabled(debug); Criteria.dbug.setEnabled(debug); if (help) { options.printUsage(); System.exit(0); } if (in_place && outdir != "annotated/") { // interned System.out.println("The --outdir and --in-place options are mutually exclusive."); options.printUsage(); System.exit(1); } if (file_args.length < 2) { System.out.printf("Supplied %d arguments, at least 2 needed%n", file_args.length); System.out.printf("Supplied arguments: %s%n", Arrays.toString(args)); System.out.printf( " (After javac parsing, remaining arguments = %s)%n", Arrays.toString(cl_args)); System.out.printf(" (File arguments = %s)%n", Arrays.toString(file_args)); options.printUsage(); System.exit(1); } // The names of annotation files (.jaif files). List<String> jaifFiles = new ArrayList<>(); // The Java files into which to insert. List<String> javafiles = new ArrayList<>(); for (String arg : file_args) { if (arg.endsWith(".java")) { javafiles.add(arg); } else if (arg.endsWith(".jaif") || arg.endsWith(".jann")) { jaifFiles.add(arg); } else { System.out.println("Unrecognized file extension: " + arg); System.exit(1); throw new Error("unreachable"); } } computeConstructors(javafiles); // The insertions specified by the annotation files. Insertions insertions = new Insertions(); // Indices to maintain insertion source traces. Map<String, Multimap<Insertion, Annotation>> insertionIndex = new HashMap<>(); Map<Insertion, String> insertionOrigins = new HashMap<>(); Map<String, AScene> scenes = new HashMap<>(); // maintain imports info for annotations field // Key: fully-qualified annotation name. e.g. "com.foo.Bar" for annotation @com.foo.Bar(x). // Value: names of packages this annotation needs. Map<String, Set<String>> annotationImports = new HashMap<>(); IndexFileParser.setAbbreviate(abbreviate); for (String jaifFile : jaifFiles) { IndexFileSpecification spec = new IndexFileSpecification(jaifFile); try { List<Insertion> parsedSpec = spec.parse(); if (temporaryDebug) { System.out.printf("parsedSpec (size %d):%n", parsedSpec.size()); for (Insertion insertion : parsedSpec) { System.out.printf(" %s, isInserted=%s%n", insertion, insertion.isInserted()); } } AScene scene = spec.getScene(); Collections.sort( parsedSpec, new Comparator<Insertion>() { @Override public int compare(Insertion i1, Insertion i2) { ASTPath p1 = i1.getCriteria().getASTPath(); ASTPath p2 = i2.getCriteria().getASTPath(); return p1 == null ? p2 == null ? 0 : -1 : p2 == null ? 1 : p1.compareTo(p2); } }); if (convert_jaifs) { scenes.put(jaifFile, filteredScene(scene)); for (Insertion ins : parsedSpec) { insertionOrigins.put(ins, jaifFile); } if (!insertionIndex.containsKey(jaifFile)) { insertionIndex.put(jaifFile, LinkedHashMultimap.<Insertion, Annotation>create()); } insertionIndex.get(jaifFile).putAll(spec.insertionSources()); } verb.debug("Read %d annotations from %s%n", parsedSpec.size(), jaifFile); if (omit_annotation != null) { List<Insertion> filtered = new ArrayList<Insertion>(parsedSpec.size()); for (Insertion insertion : parsedSpec) { // TODO: this won't omit annotations if the insertion is more than // just the annotation (such as if the insertion is a cast // insertion or a 'this' parameter in a method declaration). if (!omit_annotation.equals(insertion.getText())) { filtered.add(insertion); } } parsedSpec = filtered; verb.debug("After filtering: %d annotations from %s%n", parsedSpec.size(), jaifFile); } // if (dbug.isEnabled()) { // dbug.debug("parsedSpec:%n"); // for (Insertion insertion : parsedSpec) { // dbug.debug(" %s, isInserted=%s%n", insertion, insertion.isInserted()); // } // } insertions.addAll(parsedSpec); annotationImports.putAll(spec.annotationImports()); } catch (RuntimeException e) { if (e.getCause() != null && e.getCause() instanceof FileNotFoundException) { System.err.println("File not found: " + jaifFile); System.exit(1); } else { throw e; } } catch (FileIOException e) { // Add 1 to the line number since line numbers in text editors are usually one-based. System.err.println( "Error while parsing annotation file " + jaifFile + " at line " + (e.lineNumber + 1) + ":"); if (e.getMessage() != null) { System.err.println(" " + e.getMessage()); } if (e.getCause() != null && e.getCause().getMessage() != null) { String causeMessage = e.getCause().getMessage(); System.err.println(" " + causeMessage); if (causeMessage.startsWith("Could not load class: ")) { System.err.println( "To fix the problem, add class " + causeMessage.substring(22) + " to the classpath."); System.err.println("The classpath is:"); System.err.println(ReflectionPlume.classpathToString()); } } if (print_error_stack) { e.printStackTrace(); } System.exit(1); } } if (dbug.isEnabled()) { dbug.debug("In annotator.Main:%n"); dbug.debug("%d insertions, %d .java files%n", insertions.size(), javafiles.size()); dbug.debug("Insertions:%n"); for (Insertion insertion : insertions) { dbug.debug(" %s, isInserted=%s%n", insertion, insertion.isInserted()); } } for (String javafilename : javafiles) { verb.debug("Processing %s%n", javafilename); File javafile = new File(javafilename); File unannotated = new File(javafilename + ".unannotated"); if (in_place) { // It doesn't make sense to check timestamps; // if the .java.unannotated file exists, then just use it. // A user can rename that file back to just .java to cause the // .java file to be read. if (unannotated.exists()) { verb.debug("Renaming %s to %s%n", unannotated, javafile); boolean success = unannotated.renameTo(javafile); if (!success) { throw new Error(String.format("Failed renaming %s to %s", unannotated, javafile)); } } } Source src = fileToSource(javafilename); if (src == null) { return; } else { verb.debug("Parsed %s%n", javafilename); } String fileLineSep; try { // fileLineSep is set here so that exceptions can be caught fileLineSep = FilesPlume.inferLineSeparator(javafilename); } catch (IOException e) { throw new Error("Cannot read " + javafilename, e); } // Imports required to resolve annotations (when abbreviate==true). LinkedHashSet<String> imports = new LinkedHashSet<>(); int num_insertions = 0; String pkg = ""; for (CompilationUnitTree cut : src.parse()) { JCTree.JCCompilationUnit tree = (JCTree.JCCompilationUnit) cut; ExpressionTree pkgExp = cut.getPackageName(); pkg = pkgExp == null ? "" : pkgExp.toString(); // Create a finder, and use it to get positions. TreeFinder finder = new TreeFinder(tree); SetMultimap<Pair<Integer, ASTPath>, Insertion> positions = finder.getPositions(tree, insertions); if (dbug.isEnabled()) { dbug.debug("In annotator.Main:%n"); dbug.debug("positions (for %d insertions) = %s%n", insertions.size(), positions); } if (convert_jaifs) { // With --convert-jaifs command-line option, the program is used only for JAIF conversion. // Execute the following block and then skip the remainder of the loop. Multimap<ASTRecord, Insertion> astInsertions = finder.getPaths(); for (Map.Entry<ASTRecord, Collection<Insertion>> entry : astInsertions.asMap().entrySet()) { ASTRecord rec = entry.getKey(); for (Insertion ins : entry.getValue()) { if (ins.getCriteria().getASTPath() != null) { continue; } String arg = insertionOrigins.get(ins); AScene scene = scenes.get(arg); Multimap<Insertion, Annotation> insertionSources = insertionIndex.get(arg); // String text = // ins.getText(comments, abbreviate, false, 0, '\0'); // TODO: adjust for missing end of path (?) if (insertionSources.containsKey(ins)) { convertInsertion(pkg, tree, rec, ins, scene, insertionSources); } } } continue; } // Apply the positions to the source file. verb.debug( "getPositions returned %d positions in tree for %s%n", positions.size(), javafilename); Set<Pair<Integer, ASTPath>> positionKeysUnsorted = positions.keySet(); Set<Pair<Integer, ASTPath>> positionKeysSorted = new TreeSet<Pair<Integer, ASTPath>>( new Comparator<Pair<Integer, ASTPath>>() { @Override public int compare(Pair<Integer, ASTPath> p1, Pair<Integer, ASTPath> p2) { int c = Integer.compare(p2.a, p1.a); if (c != 0) { return c; } return p2.b == null ? (p1.b == null ? 0 : -1) : (p1.b == null ? 1 : p2.b.compareTo(p1.b)); } }); positionKeysSorted.addAll(positionKeysUnsorted); for (Pair<Integer, ASTPath> pair : positionKeysSorted) { boolean receiverInserted = false; boolean newInserted = false; boolean constructorInserted = false; Set<String> seen = new TreeSet<>(); List<Insertion> toInsertList = new ArrayList<>(positions.get(pair)); // The Multimap interface doesn't seem to have a way to specify the order of elements in // the collection, so sort them here. toInsertList.sort(insertionSorter); dbug.debug("insertion pos: %d%n", pair.a); dbug.debug("insertions sorted: %s%n", toInsertList); assert pair.a >= 0 : "pos is negative: " + pair.a + " " + toInsertList.get(0) + " " + javafilename; for (Insertion iToInsert : toInsertList) { // Possibly add whitespace after the insertion String trailingWhitespace = ""; boolean gotSeparateLine = false; int pos = pair.a; // reset each iteration in case of dyn adjustment if (iToInsert.isSeparateLine()) { // System.out.printf("isSeparateLine=true for insertion at pos %d: %s%n", pos, // iToInsert); // If an annotation should have its own line, first check that the insertion location // is the first non-whitespace on its line. If so, then the insertion content should // be the annotation, followed, by a line break, followed by a copy of the indentation // of the line being inserted onto. This puts the annotation on its own line aligned // with the contents of the next line. // Number of whitespace characters preceeding the insertion position on the same line // (tabs count as one). int indentation = 0; while ((pos - indentation != 0) // horizontal whitespace && (src.charAt(pos - indentation - 1) == ' ' || src.charAt(pos - indentation - 1) == '\t')) { // System.out.printf("src.charAt(pos-indentation-1 == %d-%d-1)='%s'%n", // pos, indentation, src.charAt(pos-indentation-1)); indentation++; } // Checks that insertion position is the first non-whitespace on the line it occurs // on. if ((pos - indentation == 0) || (src.charAt(pos - indentation - 1) == '\f' || src.charAt(pos - indentation - 1) == '\n' || src.charAt(pos - indentation - 1) == '\r')) { trailingWhitespace = fileLineSep + src.substring(pos - indentation, pos); gotSeparateLine = true; } } char precedingChar; if (pos != 0) { precedingChar = src.charAt(pos - 1); } else { precedingChar = '\0'; } if (iToInsert.getKind() == Insertion.Kind.ANNOTATION) { AnnotationInsertion ai = (AnnotationInsertion) iToInsert; if (ai.isGenerateBound()) { // avoid multiple ampersands try { String s = src.substring(pos, pos + 9); if ("Object & ".equals(s)) { ai.setGenerateBound(false); precedingChar = '.'; // suppress leading space } } catch (StringIndexOutOfBoundsException e) { } } if (ai.isGenerateExtends()) { // avoid multiple "extends" try { String s = src.substring(pos, pos + 9); if (" extends ".equals(s)) { ai.setGenerateExtends(false); pos += 8; } } catch (StringIndexOutOfBoundsException e) { } } } else if (iToInsert.getKind() == Insertion.Kind.CAST) { ((CastInsertion) iToInsert).setOnArrayLiteral(src.charAt(pos) == '{'); } else if (iToInsert.getKind() == Insertion.Kind.RECEIVER) { ReceiverInsertion ri = (ReceiverInsertion) iToInsert; ri.setAnnotationsOnly(receiverInserted); receiverInserted = true; } else if (iToInsert.getKind() == Insertion.Kind.NEW) { NewInsertion ni = (NewInsertion) iToInsert; ni.setAnnotationsOnly(newInserted); newInserted = true; } else if (iToInsert.getKind() == Insertion.Kind.CONSTRUCTOR) { ConstructorInsertion ci = (ConstructorInsertion) iToInsert; if (constructorInserted) { ci.setAnnotationsOnly(true); } constructorInserted = true; } String toInsert = iToInsert.getText(comments, abbreviate, gotSeparateLine, pos, precedingChar) + trailingWhitespace; // eliminate duplicates if (seen.contains(toInsert)) { continue; } seen.add(toInsert); // If it's an annotation and already there, don't re-insert. This is a hack! // Also, I think this is already checked when constructing the // insertions. if (toInsert.startsWith("@")) { int precedingTextPos = pos - toInsert.length() - 1; if (precedingTextPos >= 0) { String precedingTextPlusChar = src.getString().substring(precedingTextPos, pos); if (toInsert.equals(precedingTextPlusChar.substring(0, toInsert.length())) || toInsert.equals(precedingTextPlusChar.substring(1))) { dbug.debug( "Inserting '%s' at %d in code of length %d with preceding text '%s'%n", toInsert, pos, src.getString().length(), precedingTextPlusChar); dbug.debug("Already present, skipping%n"); continue; } } int followingTextEndPos = pos + toInsert.length(); if (followingTextEndPos < src.getString().length()) { String followingText = src.getString().substring(pos, followingTextEndPos); dbug.debug("followingText=\"%s\"%n", followingText); dbug.debug("toInsert=\"%s\"%n", toInsert); // toInsertNoWs does not contain the trailing whitespace. String toInsertNoWs = toInsert.substring(0, toInsert.length() - 1); if (followingText.equals(toInsert) || (followingText.substring(0, followingText.length() - 1).equals(toInsertNoWs) // Untested. Is there an off-by-one error here? && Character.isWhitespace(src.getString().charAt(followingTextEndPos)))) { dbug.debug("Already present, skipping %s%n", toInsertNoWs); continue; } } } // TODO: Neither the above hack nor this check should be // necessary. Find out why re-insertions still occur and // fix properly. if (iToInsert.isInserted()) { continue; } src.insert(pos, toInsert); if (verbose && !debug) { System.out.print("."); num_insertions++; if ((num_insertions % 50) == 0) { System.out.println(); // terminate the line that contains dots } } dbug.debug("Post-insertion source: %s%n", src.getString()); Collection<String> packageNames = nonJavaLangClasses(iToInsert.getPackageNames()); if (!packageNames.isEmpty()) { dbug.debug("Need import %s%n due to insertion %s%n", packageNames, toInsert); imports.addAll(packageNames); } if (iToInsert instanceof AnnotationInsertion) { AnnotationInsertion annoToInsert = (AnnotationInsertion) iToInsert; Set<String> annoImports = annotationImports.get(annoToInsert.getAnnotationFullyQualifiedName()); if (annoImports != null) { imports.addAll(annoImports); } } } } } if (convert_jaifs) { for (Map.Entry<String, AScene> entry : scenes.entrySet()) { String filename = entry.getKey(); AScene scene = entry.getValue(); try { IndexFileWriter.write(scene, filename + ".converted"); } catch (DefException e) { System.err.println(filename + ": " + " format error in conversion"); if (print_error_stack) { e.printStackTrace(); } } } return; // done with conversion } if (dbug.isEnabled()) { dbug.debug("%d imports to insert%n", imports.size()); for (String classname : imports) { dbug.debug(" %s%n", classname); } } // insert import statements { Pattern importPattern = Pattern.compile("(?m)^import\\b"); Pattern packagePattern = Pattern.compile("(?m)^package\\b.*;(\\n|\\r\\n?)"); int importIndex = 0; // default: beginning of file String srcString = src.getString(); Matcher m = importPattern.matcher(srcString); Set<String> inSource = new TreeSet<>(); if (m.find()) { importIndex = m.start(); do { int i = m.start(); int j = srcString.indexOf(System.lineSeparator(), i) + 1; if (j <= 0) { j = srcString.length(); } String s = srcString.substring(i, j); inSource.add(s); } while (m.find()); } else { // Debug.info("Didn't find import in " + srcString); m = packagePattern.matcher(srcString); if (m.find()) { importIndex = m.end(); } } for (String classname : imports) { String toInsert = "import " + classname + ";" + fileLineSep; if (!inSource.contains(toInsert)) { inSource.add(toInsert); src.insert(importIndex, toInsert); importIndex += toInsert.length(); } } } // Write the source file. File outfile = null; try { if (in_place) { outfile = javafile; if (verbose) { System.out.printf("Renaming %s to %s%n", javafile, unannotated); } boolean success = javafile.renameTo(unannotated); if (!success) { throw new Error(String.format("Failed renaming %s to %s", javafile, unannotated)); } } else { if (pkg.isEmpty()) { outfile = new File(outdir, javafile.getName()); } else { @SuppressWarnings("StringSplitter") // false positive because pkg is non-empty String[] pkgPath = pkg.split("\\."); StringBuilder sb = new StringBuilder(outdir); for (int i = 0; i < pkgPath.length; i++) { sb.append(fileSep).append(pkgPath[i]); } outfile = new File(sb.toString(), javafile.getName()); } outfile.getParentFile().mkdirs(); } OutputStream output = new FileOutputStream(outfile); if (verbose) { System.out.printf("Writing %s%n", outfile); } src.write(output); output.close(); } catch (IOException e) { System.err.println("Problem while writing file " + outfile); e.printStackTrace(); System.exit(1); } } } /** * Given a Java file name, creates a Source, or returns null. * * @param javaFileName a Java file name * @return a Source for the Java file, or null */ private static Source fileToSource(String javaFileName) { Source src; // Get the source file, and use it to obtain parse trees. try { src = new Source(javaFileName); return src; } catch (Source.CompilerException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } /** * Primary sort criterion: put declaration annotations (which go on a separate line) last, so that * they *precede* type annotations when inserted. * * <p>Secondary sort criterion: for determinism, put annotations in reverse alphabetic order (so * that they are alphabetized when inserted). */ private static Comparator<Insertion> insertionSorter = new Comparator<Insertion>() { @Override public int compare(Insertion i1, Insertion i2) { boolean separateLine1 = i1.isSeparateLine(); boolean separateLine2 = i2.isSeparateLine(); if (separateLine1 && !separateLine2) { return 1; } else if (separateLine2 && !separateLine1) { return -1; } else { return -i1.getText().compareTo(i2.getText()); } } }; /** Maps from binary class name to whether the class has any explicit constructor. */ public static Map<String, Boolean> hasExplicitConstructor = new HashMap<>(); /** * Fills in the {@link hasExplicitConstructor} map. * * @param javaFiles the Java files that were passed on the command line */ static void computeConstructors(List<String> javaFiles) { for (String javaFile : javaFiles) { Source src = fileToSource(javaFile); if (src == null) { continue; } for (CompilationUnitTree cut : src.parse()) { TreePathScanner<Void, Void> constructorsScanner = new TreePathScanner<Void, Void>() { @Override public Void visitClass(ClassTree ct, Void p) { String className = TreePathUtil.getBinaryName(getCurrentPath()); hasExplicitConstructor.put(className, TreePathUtil.hasConstructor(ct)); return super.visitClass(ct, p); } }; constructorsScanner.scan(cut, null); } } } /** A regular expression for classes in the java.lang package. */ private static Pattern javaLangClassPattern = Pattern.compile("^java\\.lang\\.[A-Za-z0-9_]+$"); /** * Return true iff the class is a top-level class in the java.lang package. * * @param classname the class to test * @return true iff the class is a top-level class in the java.lang package */ private static boolean isJavaLangClass(String classname) { Matcher m = javaLangClassPattern.matcher(classname); return m.matches(); } /** * Filters out classes in the java.lang package from the given collection. * * @param classnames a collection of class names * @return the class names that are not in the java.lang package */ private static Collection<String> nonJavaLangClasses(Collection<String> classnames) { // Don't side-effect the argument List<String> result = new ArrayList<>(); for (String classname : classnames) { if (!isJavaLangClass(classname)) { result.add(classname); } } return result; } /** * Return the representation of the leaf of the path. * * @param path a path whose leaf to format * @return the representation of the leaf of the path */ public static String leafString(TreePath path) { if (path == null) { return "null path"; } return treeToString(path.getLeaf()); } /** * Return the first 80 characters of the tree's printed representation, on one line. * * @param node a tree to format with truncation * @return the first 80 characters of the tree's printed representation, on one line */ public static String treeToString(Tree node) { String asString = node.toString(); String oneLine = first80(asString); if (oneLine.endsWith(" ")) { oneLine = oneLine.substring(0, oneLine.length() - 1); } // return "\"" + oneLine + "\""; return oneLine; } /** * Return the first non-empty line of the string, adding an ellipsis (...) if the string was * truncated. * * @param s a string to truncate * @return the first non-empty line of the argument */ public static String firstLine(String s) { while (s.startsWith("\n")) { s = s.substring(1); } int newlineIndex = s.indexOf('\n'); if (newlineIndex == -1) { return s; } else { return s.substring(0, newlineIndex) + "..."; } } /** * Return the first 80 characters of the string, adding an ellipsis (...) if the string was * truncated. * * @param s a string to truncate * @return the first 80 characters of the string */ public static String first80(String s) { StringBuilder sb = new StringBuilder(); int i = 0; while (i < s.length() && Character.isWhitespace(s.charAt(i))) { i++; } while (i < s.length() && sb.length() < 80) { if (s.charAt(i) == '\n') { i++; while (i < s.length() && Character.isWhitespace(s.charAt(i))) { i++; } sb.append(' '); } if (i < s.length()) { sb.append(s.charAt(i)); } i++; } if (i < s.length()) { sb.append("..."); } return sb.toString(); } /** * Separates the annotation class from its arguments. * * @param s the string representation of an annotation * @return given <code>@foo(bar)</code> it returns the pair <code>{ @foo, (bar) }</code>. */ public static Pair<String, String> removeArgs(String s) { int pidx = s.indexOf("("); return (pidx == -1) ? Pair.of(s, (String) null) : Pair.of(s.substring(0, pidx), s.substring(pidx)); } }
39.501592
100
0.591607
a920c371a7c242f04e6b9038f44556566ef188a7
929
package com.xiaoTools.core.convert.pathConverter; import java.io.File; import java.net.URI; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import com.xiaoTools.core.convert.abstractConverter.AbstractConverter; /** * [字符串转换器](String converter) * @description zh - 字符串转换器 * @description en - String converter * @version V1.0 * @author XiaoXunYao * @since 2021-10-20 16:59:40 */ public class PathConverter extends AbstractConverter<Path>{ private static final long serialVersionUID = 1L; @Override protected Path convertInternal(Object value) { try { if(value instanceof URI){ return Paths.get((URI)value); } if(value instanceof URL){ return Paths.get(((URL)value).toURI()); } if(value instanceof File){ return ((File)value).toPath(); } return Paths.get(convertToStr(value)); } catch (Exception e) { // Ignore Exception } return null; } }
20.195652
70
0.703983
fc9b7b3656802e4c8d4c25a0212facc374a0f2f2
5,374
package com.github.stazxr.zblog.base.manager; import com.github.stazxr.zblog.base.domain.entity.Permission; import com.github.stazxr.zblog.base.domain.entity.Router; import com.github.stazxr.zblog.base.service.PermissionService; import com.github.stazxr.zblog.base.service.RouterService; import com.github.stazxr.zblog.base.util.Constants; import com.github.stazxr.zblog.base.util.GenerateIdUtils; import com.github.stazxr.zblog.core.base.BaseConst; import com.github.stazxr.zblog.util.collection.ArrayUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition; import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 路由管理,系统启动时加载一次 * * @author SunTao * @since 2020-11-15 */ @Slf4j @Component @RequiredArgsConstructor public class RouterManager { private static final int SPLIT_SIZE = 100; private final WebApplicationContext applicationContext; private final PermissionService permissionService; private final RouterService routerService; /** * 系统启动时,初始化路由信息 */ @Transactional(rollbackFor = Exception.class) public void initRouter() { List<Router> routeList = parseRouter(); log.info("router list: {}", routeList); routerService.clearRouter(); if (routeList.size() < SPLIT_SIZE) { routerService.saveBatch(routeList); } else { List<List<Router>> routers = ArrayUtils.averageAssign(routeList); routers.forEach(routerService::saveBatch); } } /** * 解析所有的路由信息 * * @return 路由列表 */ private List<Router> parseRouter() { List<Router> routes = new ArrayList<>(); // 获取路由白名单 Map<String, String> whiteList = routerService.getRouterWhiteList(); // 获取url与类和方法的对应信息 RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class); Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods(); for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) { RequestMappingInfo info = m.getKey(); HandlerMethod handlerMethod = m.getValue(); PatternsRequestCondition p = info.getPatternsCondition(); if (p == null) { continue; } // 获取HTTP URI String uri = ""; for (String pattern : p.getPatterns()) { // 默认只有一个URL uri = pattern; } // 禁止path风格的路由配置 if (uri.contains("{") && uri.contains("}")) { throw new IllegalStateException("禁止使用PathVariable型URI > " + uri); } // 白名单检查 if (whiteList.containsValue(uri)) { continue; } Method method = handlerMethod.getMethod(); RequestMapping isReqMapper = method.getAnnotation(RequestMapping.class); if (isReqMapper != null) { throw new IllegalStateException("禁止使用RequestMapping注解 > " + uri); } // 获取Router注解 com.github.stazxr.zblog.core.annotation.Router routeInfo = method.getAnnotation( com.github.stazxr.zblog.core.annotation.Router.class ); Router router; if (routeInfo == null) { // 该类别的路由登录即可访问 router = new Router(); router.setName(method.getName()); router.setCode(method.getName()); router.setLevel(BaseConst.PermLevel.PUBLIC); router.setRemark("系统自动识别"); } else { router = new Router(routeInfo); } // HttpUrl and HttpMethod router.setUrl(uri); RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition(); for (RequestMethod requestMethod : methodsCondition.getMethods()) { // 默认一个方法只有一个HttpMethod router.setMethod(requestMethod.toString()); break; } // 设置路由状态 Permission permission = permissionService.selectPermByPath(router.getUrl()); if (permission == null) { router.setStatus(Constants.RouterStatus.NONE); } else { router.setLevel(permission.getLevel()); router.setStatus( permission.getEnabled() ? Constants.RouterStatus.OK : Constants.RouterStatus.DISABLED ); } router.setId(GenerateIdUtils.getId()); routes.add(router); } return routes; } }
35.355263
110
0.638817
8fdebaaacbf89e6232ccf7cf4251720c83c6856c
437
package ag.algorithms.leetcode.solutions.strings; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class LongestHappyStringTest { @Test void getLongestHappyString() { LongestHappyString longestHappyString = new LongestHappyString(); Assertions.assertThat(longestHappyString.getLongestHappyString(1,1,7)).isEqualTo("ccaccbcc"); } }
31.214286
101
0.768879
52719ce6157d18602f354f6607557e1ca6bb3dd7
2,770
package com.jameslin.progression; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import net.minecraft.world.biome.Biome; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.List; public class ProgressionConfig { public boolean disableEndDimension; public boolean disableNetherDimension; public boolean displayDisableMessages; public String endDisabledMessage; public String netherDisabledMessage; public boolean isDefaultSettings; private static String configPath = "config/progression.json"; public ProgressionConfig(boolean disableEndDimension, boolean disableNetherDimension, boolean displayDisableMessages, String endDisabledMessage, String netherDisabledMessage) { this.disableEndDimension = disableEndDimension; this.disableNetherDimension = disableNetherDimension; this.displayDisableMessages = displayDisableMessages; this.endDisabledMessage = endDisabledMessage; this.netherDisabledMessage = netherDisabledMessage; } public ProgressionConfig(boolean disableEndDimension, boolean disableNetherDimension, boolean displayDisableMessages, String endDisabledMessage, String netherDisabledMessage, boolean isDefaultSettings) { this.disableEndDimension = disableEndDimension; this.disableNetherDimension = disableNetherDimension; this.displayDisableMessages = displayDisableMessages; this.endDisabledMessage = endDisabledMessage; this.netherDisabledMessage = netherDisabledMessage; this.isDefaultSettings = isDefaultSettings; } public static ProgressionConfig getDefaultConfig() { boolean defaultEnd = true; boolean defaultNether = false; boolean defaultDisplayMessages = true; String defaultEndMessage = "-[ The End Dimension is currently disabled by your Server Admin ]-"; String defaultNetherMessage = "-[ The Nether Dimension is currently disabled by your Server Admin ]-"; return new ProgressionConfig(defaultEnd, defaultNether, defaultDisplayMessages, defaultEndMessage, defaultNetherMessage,false); } public static boolean getBoolValueFromEntry(String entry) throws FileNotFoundException { Object obj = new JsonParser().parse(new FileReader(configPath)); JsonObject jo = (JsonObject) obj; return jo.get(entry).getAsBoolean(); } public static String getStringValueFromEntry(String entry) throws FileNotFoundException { Object obj = new JsonParser().parse(new FileReader(configPath)); JsonObject jo = (JsonObject) obj; return jo.get(entry).getAsString(); } }
41.969697
135
0.74657
ba021b888edaffcbd36989d1e3ba50c078cd2a60
4,939
package com.ebgolden.domain.locationservice.dal; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.ebgolden.common.Location; import com.ebgolden.common.Visibility; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.ebgolden.domain.locationservice.bll.bo.LocationAndPlayerBo; import com.ebgolden.domain.locationservice.bll.bo.LocationAndVisibilityBo; import com.ebgolden.domain.locationservice.dal.dao.LocationDao; import com.ebgolden.domain.locationservice.dal.dao.LocationAndVisibilityDao; import java.util.HashMap; import java.util.Map; public class LocationDataAccessConverterImpl implements LocationDataAccessConverter { public LocationDao getLocationDaoFromLocationAndPlayerBo(LocationAndPlayerBo locationAndPlayerBo) { Location location = locationAndPlayerBo.getLocation(); ObjectMapper objectMapper = new ObjectMapper(); String locationJson = "{}"; try { locationJson = objectMapper.writeValueAsString(location); } catch (JsonProcessingException e) { e.printStackTrace(); } return LocationDao .builder() .locationJson(locationJson) .build(); } public LocationAndVisibilityDao getLocationAndVisibilityDaoFromLocationAndVisibilityBo(LocationAndVisibilityBo locationAndVisibilityBo) { Location location = locationAndVisibilityBo.getLocation(); Map<String, Visibility> visibilityMap = locationAndVisibilityBo.getVisibilityMap(); ObjectMapper objectMapper = new ObjectMapper(); String locationJson = "{}"; String visibilityJson = "{}"; try { locationJson = objectMapper.writeValueAsString(location); visibilityJson = objectMapper.writeValueAsString(visibilityMap); } catch (JsonProcessingException e) { e.printStackTrace(); } String locationAndVisibilityJson = "{}"; if ((!locationJson.equals("{}") && (!locationJson.equals("null"))) || (!visibilityJson.equals("{}") && (!visibilityJson.equals("null")))) locationAndVisibilityJson = "{" + "location:" + locationJson + ",visibility:" + visibilityJson + "}"; return LocationAndVisibilityDao .builder() .locationAndVisibilityJson(locationAndVisibilityJson) .build(); } public LocationAndVisibilityBo getLocationAndVisibilityBoFromLocationAndVisibilityDao(LocationAndVisibilityDao locationAndVisibilityDao) { String locationAndVisibilityJson = locationAndVisibilityDao.getLocationAndVisibilityJson(); if (locationAndVisibilityJson == null) locationAndVisibilityJson = "{}"; JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = new JSONObject(); try { jsonObject = (JSONObject)jsonParser.parse(locationAndVisibilityJson); } catch (ParseException e) { e.printStackTrace(); } ObjectMapper objectMapper = new ObjectMapper(); String locationJson; Location location = null; if (jsonObject.get("location") != null) { locationJson = ((JSONObject) jsonObject.get("location")).toJSONString(); location = Location .builder() .build(); try { location = objectMapper.readValue(locationJson, Location.class); } catch (JsonProcessingException e) { e.printStackTrace(); } } String visibilityJson; Map<String, Visibility> visibilityMap = null; if (jsonObject.get("visibility") != null) { visibilityJson = ((JSONObject)jsonObject.get("visibility")).toJSONString(); visibilityMap = new HashMap<>(); try { TypeReference<Map<String, Visibility>> visibilityMapTypeReference = new TypeReference<Map<String, Visibility>>(){}; visibilityMap = objectMapper.readValue(visibilityJson, visibilityMapTypeReference); } catch (JsonProcessingException e) { e.printStackTrace(); } } return LocationAndVisibilityBo .builder() .location(location) .visibilityMap(visibilityMap) .build(); } public LocationAndVisibilityDao getLocationAndVisibilityDaoFromLocationAndVisibilityJson(String locationAndVisibilityJson) { return LocationAndVisibilityDao .builder() .locationAndVisibilityJson(locationAndVisibilityJson) .build(); } }
44.9
145
0.652966
65ada536db4ca40f3a334a820323be4ba51ed539
1,524
package com.coderqian.eurekaorder.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; /** * @author qianliqing * @date 2018-09-28 下午7:56 * mail: [email protected] */ @RestController @RequestMapping(value = "/test") @Api(value = "测试", description = "测试模块", position = 1) public class TestController { @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } @Autowired RestTemplate restTemplate; @ApiOperation(value = "返回用户输入的结果", notes = "返回用户输入的结果") @RequestMapping(value = "/result", method = RequestMethod.GET) public String test(@RequestParam(value = "text") String text) { return text; } @ApiOperation(value = "测试服务链路追踪", notes = "测试服务链路追踪") @RequestMapping(value = "/zipkin", method = RequestMethod.GET) public String testCustomer(@RequestParam(value = "text") String text) { return restTemplate.getForObject("http://service-customer/test/result?text=" + text, String.class); } }
33.130435
107
0.744751
24d1a1ceea7423946caa538f4215a9b2a7fe0acc
3,871
/* * 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.inlong.manager.common.pojo.stream; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.Data; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.inlong.manager.common.util.Preconditions; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; /** * Stream pipeline, save stream node relation list. */ @Data public class StreamPipeline { private List<StreamNodeRelation> pipeline; public StreamPipeline() { this(Lists.newArrayList()); } public StreamPipeline(List<StreamNodeRelation> pipeline) { Preconditions.checkNotNull(pipeline, "Pipeline should not be null"); this.pipeline = pipeline; } public void addRelation(StreamNodeRelation relation) { pipeline.add(relation); } /** * Check if a pipeline has a circle, if it has, return circled node names */ public Pair<Boolean, Pair<String, String>> hasCircle() { Map<String, Set<String>> priorityMap = Maps.newHashMap(); for (StreamNodeRelation relation : pipeline) { Set<String> inputNodes = relation.getInputNodes(); Set<String> outputNodes = relation.getOutputNodes(); for (String inputNode : inputNodes) { for (String outputNode : outputNodes) { priorityMap.computeIfAbsent(inputNode, key -> Sets.newHashSet()).add(outputNode); if (CollectionUtils.isEmpty(priorityMap.get(outputNode))) { continue; } Set<String> priorityNodesOfOutput = priorityMap.get(outputNode); if (priorityNodesOfOutput.contains(inputNode)) { return Pair.of(true, Pair.of(inputNode, outputNode)); } else { if (isReach(priorityMap, priorityNodesOfOutput, inputNode)) { return Pair.of(true, Pair.of(inputNode, outputNode)); } } } } } return Pair.of(false, null); } private boolean isReach(Map<String, Set<String>> paths, Set<String> inputs, String output) { Queue<String> queue = new LinkedList<>(inputs); Set<String> preNodes = new HashSet<>(inputs); while (!queue.isEmpty()) { String node = queue.remove(); if (paths.get(node) == null) { continue; } Set<String> postNodes = paths.get(node); if (postNodes.contains(output)) { return true; } for (String postNode : postNodes) { if (!preNodes.contains(postNode)) { preNodes.add(postNode); queue.add(postNode); } } } return false; } }
36.518868
101
0.622578