hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e0f2185d8868f2172984215804bc933209fa94e
3,580
java
Java
test/org/jivesoftware/smack/filter/PacketTypeFilterTest.java
dupes/smack_src_3_3_1
091f7bd2138fd4d836ed1b4e278c9c6b0a7201d2
[ "Apache-2.0", "Unlicense" ]
53
2015-02-09T17:32:23.000Z
2021-11-14T13:23:27.000Z
test/org/jivesoftware/smack/filter/PacketTypeFilterTest.java
dupes/smack_src_3_3_1
091f7bd2138fd4d836ed1b4e278c9c6b0a7201d2
[ "Apache-2.0", "Unlicense" ]
5
2015-05-19T21:17:21.000Z
2020-10-23T10:14:26.000Z
test/org/jivesoftware/smack/filter/PacketTypeFilterTest.java
dupes/smack_src_3_3_1
091f7bd2138fd4d836ed1b4e278c9c6b0a7201d2
[ "Apache-2.0", "Unlicense" ]
25
2015-02-14T13:24:43.000Z
2019-04-09T07:37:53.000Z
31.130435
116
0.627374
6,428
/** * $RCSfile$ * $Revision: 13604 $ * $Date: 2013-04-07 12:15:32 -0700 (Sun, 07 Apr 2013) $ * * Copyright 2003 Jive Software. * * 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.jivesoftware.smack.filter; import junit.framework.TestCase; import org.jivesoftware.smack.packet.*; /** * Test cases for the PacketTypeFilter class. */ public class PacketTypeFilterTest extends TestCase { private class InnerClassDummy { public class DummyPacket extends Packet { public String toXML() { return null; } } public DummyPacket getInnerInstance() { return new DummyPacket(); } } private static class StaticInnerClassDummy { public static class StaticDummyPacket extends Packet { public String toXML() { return null; } } public static StaticDummyPacket getInnerInstance() { return new StaticDummyPacket(); } } /** * Test case for the constructor of PacketTypeFilter objects. */ public void testConstructor() { // We dont need to test this since PacketTypeFilter(Class<? extends Packet> packetType) only excepts Packets // Test a class that is not a subclass of Packet // try { // new PacketTypeFilter(Dummy.class); // fail("Parameter must be a subclass of Packet."); // } // catch (IllegalArgumentException e) {} // Test a class that is a subclass of Packet try { new PacketTypeFilter(MockPacket.class); } catch (IllegalArgumentException e) { fail(); } // Test another class which is a subclass of Packet try { new PacketTypeFilter(IQ.class); } catch (IllegalArgumentException e) { fail(); } // Test an internal class which is a subclass of Packet try { new PacketTypeFilter(InnerClassDummy.DummyPacket.class); } catch (IllegalArgumentException e) { fail(); } // Test an internal static class which is a static subclass of Packet try { new PacketTypeFilter(StaticInnerClassDummy.StaticDummyPacket.class); } catch (IllegalArgumentException e) { fail(); } } /** * Test case to test the accept() method of PacketTypeFilter objects. */ public void testAccept() { Packet packet = new MockPacket(); PacketTypeFilter filter = new PacketTypeFilter(MockPacket.class); assertTrue(filter.accept(packet)); packet = (new InnerClassDummy()).getInnerInstance(); filter = new PacketTypeFilter(InnerClassDummy.DummyPacket.class); assertTrue(filter.accept(packet)); packet = StaticInnerClassDummy.getInnerInstance(); filter = new PacketTypeFilter(StaticInnerClassDummy.StaticDummyPacket.class); assertTrue(filter.accept(packet)); } }
3e0f21a16fd8f31e6ba0987a73a7094e9ce383c9
2,787
java
Java
app/src/main/java/com/kongzue/find/FirstActivity.java
kongzue/FindApp
30081a2b75c6b1dce31b5a50c36a117f18f01553
[ "Apache-2.0" ]
6
2019-03-02T16:07:45.000Z
2021-06-01T03:36:30.000Z
app/src/main/java/com/kongzue/find/FirstActivity.java
kongzue/FindApp
30081a2b75c6b1dce31b5a50c36a117f18f01553
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/kongzue/find/FirstActivity.java
kongzue/FindApp
30081a2b75c6b1dce31b5a50c36a117f18f01553
[ "Apache-2.0" ]
null
null
null
27.323529
80
0.617151
6,429
package com.kongzue.find; import android.content.Intent; import android.os.Bundle; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageView; import com.facebook.drawee.backends.pipeline.Fresco; import com.kongzue.find.util.BaseActivity; import cn.bmob.push.BmobPush; import cn.bmob.v3.Bmob; import cn.bmob.v3.BmobInstallation; public class FirstActivity extends BaseActivity { private ImageView imgFirstBkg; private ImageView imgFirstLogo; private void assignViews() { imgFirstBkg = (ImageView) findViewById(R.id.imgFirstBkg); imgFirstLogo = (ImageView) findViewById(R.id.imgFirstLogo); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); assignViews(); init(); } private void init() { //背景渐变 AlphaAnimation am = new AlphaAnimation(0f, 1.0f); am.setDuration(1600); am.setFillAfter(true); imgFirstLogo.startAnimation(am); //延时跳转到下一个界面 AlphaAnimation am2 = new AlphaAnimation(0.9f, 1.0f); am2.setDuration(100); imgFirstBkg.startAnimation(am2); am2.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { initSDK(); } @Override public void onAnimationRepeat(Animation animation) { } }); am.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { Intent intent=new Intent(FirstActivity.this,MainActivity.class); startActivity(intent); int version = Integer.valueOf(android.os.Build.VERSION.SDK); if (version > 5) { overridePendingTransition(R.anim.fade, R.anim.hold); } finish(); } @Override public void onAnimationRepeat(Animation animation) { } }); } private void initSDK() { //CrashReport.initCrashReport(this, "900015045", false); Bmob.initialize(this, "b7730ed724833736a020a688d97f18d8"); //初始化推送 // 使用推送服务时的初始化操作 BmobInstallation.getCurrentInstallation(this).save(); // 启动推送服务 BmobPush.startWork(this); //初始化Fresco Fresco.initialize(this); } }
3e0f21f0ede628b03afa9ef8267676c3b4b710ba
6,134
java
Java
sdk/core/src/main/java/com/google/cloud/trace/core/SpanContextFactory.java
GoogleCloudPlatform/gcloud-trace-java
9aa2f22e571577887053a86d2236830b3922421b
[ "Apache-2.0" ]
64
2016-02-29T08:14:50.000Z
2021-10-09T16:53:54.000Z
sdk/core/src/main/java/com/google/cloud/trace/core/SpanContextFactory.java
GoogleCloudPlatform/cloud-trace-java
9aa2f22e571577887053a86d2236830b3922421b
[ "Apache-2.0" ]
24
2016-09-27T01:39:59.000Z
2019-07-12T08:14:50.000Z
sdk/core/src/main/java/com/google/cloud/trace/core/SpanContextFactory.java
GoogleCloudPlatform/cloud-trace-java
9aa2f22e571577887053a86d2236830b3922421b
[ "Apache-2.0" ]
44
2016-01-28T10:32:05.000Z
2021-03-21T10:55:58.000Z
34.852273
98
0.705249
6,430
// Copyright 2016 Google 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.google.cloud.trace.core; import com.google.common.primitives.UnsignedLongs; import java.math.BigInteger; /** * A class that generates span contexts. * * @see IdFactory * @see RandomSpanIdFactory * @see RandomTraceIdFactory * @see SpanId * @see SpanContext * @see TraceId * @see TraceOptionsFactory */ public class SpanContextFactory { private final TraceOptionsFactory traceOptionsFactory; private final IdFactory<TraceId> traceIdFactory; private final IdFactory<SpanId> spanIdFactory; /** * Returns the name of the span context header. * * @return the name of the span context header. */ public static String headerKey() { return "X-Cloud-Trace-Context"; } /** * Creates a span context factory that uses the given trace options factory and new random trace * and span identifier factory to generate span contexts. * * @param traceOptionsFactory a trace options factory used to generate trace options. */ public SpanContextFactory(TraceOptionsFactory traceOptionsFactory) { this(traceOptionsFactory, new RandomTraceIdFactory(), new RandomSpanIdFactory()); } /** * Creates a span context factory that uses the given trace options factory and trace and span * identifier factories to generate span contexts. * * @param traceOptionsFactory a trace options factory used to generate trace options. * @param traceIdFactory a trace identifier factory used to generate trace identifiers. * @param spanIdFactory a span identifier factory used to generate span identifiers. */ public SpanContextFactory(TraceOptionsFactory traceOptionsFactory, IdFactory<TraceId> traceIdFactory, IdFactory<SpanId> spanIdFactory) { this.traceOptionsFactory = traceOptionsFactory; this.traceIdFactory = traceIdFactory; this.spanIdFactory = spanIdFactory; } /** * Generates a new span context based on the parent context with a new span identifier. If the * parent context has an invalid trace identifier, the new span context will also have a new * trace identifier, and a sampling decision will be made. * * @param parentContext a span context that is the parent of the new span context. * @return the new span context. */ public SpanContext childContext(SpanContext parentContext) { if (parentContext.getTraceId().isValid()) { return new SpanContext(parentContext.getTraceId(), spanIdFactory.nextId(), traceOptionsFactory.create(parentContext.getTraceOptions())); } return new SpanContext(traceIdFactory.nextId(), spanIdFactory.nextId(), traceOptionsFactory.create()); } /** * Generates a new span context with invalid trace and span identifiers and default trace * options. This method does not invoke the trace options factory, so no sampling decision is * made. * * @return the new span context. */ public SpanContext initialContext() { return new SpanContext(TraceId.invalid(), SpanId.invalid(), new TraceOptions()); } /** * Generates a new span context based on the value of a span context header. * * @param header a string that is the value of a span context header. * @return the new span context. */ public SpanContext fromHeader(String header) { int index = header.indexOf('/'); if (index == -1) { TraceId traceId = parseTraceId(header); return new SpanContext(traceId, SpanId.invalid(), traceOptionsFactory.create()); } TraceId traceId = parseTraceId(header.substring(0, index)); if (!traceId.isValid()) { return new SpanContext(traceId, SpanId.invalid(), traceOptionsFactory.create()); } String[] afterTraceId = header.substring(index + 1).split(";"); SpanId spanId = parseSpanId(afterTraceId[0]); TraceOptions traceOptions = null; for (int i = 1; i < afterTraceId.length; i++) { if (afterTraceId[i].startsWith("o=")) { traceOptions = parseTraceOptions(afterTraceId[i].substring(2)); } } // Invoke the factory here only after we have determined that there is no options argument in // the header, in order to avoid making an extra sampling decision. if (traceOptions == null) { traceOptions = traceOptionsFactory.create(); } return new SpanContext(traceId, spanId, traceOptions); } private TraceId parseTraceId(String input) { try { return new TraceId(new BigInteger(input, 16)); } catch (NumberFormatException ex) { return TraceId.invalid(); } } private SpanId parseSpanId(String input) { try { return new SpanId(UnsignedLongs.parseUnsignedLong(input)); } catch (NumberFormatException ex) { return SpanId.invalid(); } } private TraceOptions parseTraceOptions(String input) { try { return traceOptionsFactory.create(new TraceOptions(Integer.parseInt(input))); } catch (NumberFormatException ex) { return traceOptionsFactory.create(); } } /** * Transforms this context into an HTTP request header. * * @param context the span context to convert to a header. * @return this context as a header. */ public static String toHeader(SpanContext context) { StringBuilder builder = new StringBuilder() .append(context.getTraceId().getApiString()) .append('/') .append(context.getSpanId().getApiString()) .append(";o=") .append(context.getTraceOptions().getOptionsMask()); return builder.toString(); } }
3e0f22126c27aa8fd1d2f8eacc487b7c2a521036
540
java
Java
src/main/java/com/oskiapps/shopsapp/engine/services/CustomerAccountEmailService.java
oskarzarzecki/shopsapp
8223205246759e3b1339c579ae4eda3f65d8b55b
[ "MIT" ]
null
null
null
src/main/java/com/oskiapps/shopsapp/engine/services/CustomerAccountEmailService.java
oskarzarzecki/shopsapp
8223205246759e3b1339c579ae4eda3f65d8b55b
[ "MIT" ]
null
null
null
src/main/java/com/oskiapps/shopsapp/engine/services/CustomerAccountEmailService.java
oskarzarzecki/shopsapp
8223205246759e3b1339c579ae4eda3f65d8b55b
[ "MIT" ]
null
null
null
28.421053
81
0.783333
6,431
package com.oskiapps.shopsapp.engine.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CustomerAccountEmailService { @Autowired public EmailService emailService; public void sendRegistrationMessage(String to) { String subject = "Welcome to ShopsApp"; String text = "Welcome to ShopsApp " + to + ". You have created your account, you can login using your email address."; emailService.sendSimpleMessage(to, subject, text); } }
3e0f22a1a36783b093e23216153c1e785ef4f78f
3,562
java
Java
replicator/test/java/com/continuent/tungsten/replicator/extractor/TestExtractorPlugin.java
SriSivaC/tungsten-replicator_clone
f9027543c92826634f9fdc66fb471ac525c3f7ad
[ "Apache-2.0" ]
15
2019-02-21T15:13:55.000Z
2021-08-25T15:17:56.000Z
replicator/test/java/com/continuent/tungsten/replicator/extractor/TestExtractorPlugin.java
SriSivaC/tungsten-replicator_clone
f9027543c92826634f9fdc66fb471ac525c3f7ad
[ "Apache-2.0" ]
null
null
null
replicator/test/java/com/continuent/tungsten/replicator/extractor/TestExtractorPlugin.java
SriSivaC/tungsten-replicator_clone
f9027543c92826634f9fdc66fb471ac525c3f7ad
[ "Apache-2.0" ]
17
2019-03-06T10:45:57.000Z
2021-12-05T13:45:17.000Z
30.02521
99
0.644556
6,432
/** * VMware Continuent Tungsten Replicator * Copyright (C) 2015 VMware, 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. * * Initial developer(s): Teemu Ollakka * Contributor(s): */ package com.continuent.tungsten.replicator.extractor; import org.apache.log4j.Logger; import com.continuent.tungsten.replicator.event.DBMSEvent; import com.continuent.tungsten.replicator.plugin.PluginLoader; import junit.framework.Assert; import junit.framework.TestCase; /** * * This class checks extractor loading using the DummyExtractor. * * @author <a href="mailto:ychag@example.com">Teemu Ollakka</a> * @version 1.0 */ public class TestExtractorPlugin extends TestCase { static Logger logger = null; public void setUp() throws Exception { if (logger == null) logger = Logger.getLogger(TestExtractorPlugin.class); } /* * Test that dummy extractor works like expected, */ public void testExtractorBasic() throws Exception { RawExtractor extractor = (RawExtractor) PluginLoader.load(DummyExtractor.class.getName()); extractor.configure(null); extractor.prepare(null); DBMSEvent event = extractor.extract(); Assert.assertEquals(event.getEventId(), "0"); event = extractor.extract(); Assert.assertEquals(event.getEventId(), "1"); extractor.setLastEventId("0"); event = extractor.extract(); Assert.assertEquals(event.getEventId(), "1"); extractor.setLastEventId(null); event = extractor.extract(); Assert.assertEquals(event.getEventId(), "0"); for (Integer i = 1; i < 5; ++i) { event = extractor.extract(); Assert.assertEquals(event.getEventId(), i.toString()); } event = extractor.extract("0"); Assert.assertEquals(event.getEventId(), "0"); event = extractor.extract("4"); Assert.assertEquals(event.getEventId(), "4"); event = extractor.extract("5"); Assert.assertEquals(event, null); extractor.release(null); } /* * Test test that event ID calls work as expected */ public void testExtractorEventID() throws Exception { RawExtractor extractor = (RawExtractor) PluginLoader.load(DummyExtractor.class.getName()); extractor.configure(null); extractor.prepare(null); DBMSEvent event = extractor.extract(); String currentEventId = extractor.getCurrentResourceEventId(); Assert.assertEquals(event.getEventId(), currentEventId); event = extractor.extract(); Assert.assertTrue(event.getEventId().compareTo(currentEventId) > 0); currentEventId = extractor.getCurrentResourceEventId(); Assert.assertTrue(event.getEventId().compareTo(currentEventId) == 0); extractor.release(null); } }
3e0f2309748c9d151cef532e1e117f51691df8dd
1,483
java
Java
persistence/jdo/datanucleus-5/src/main/java/org/apache/isis/persistence/jdo/datanucleus5/exceprecog/JdoNestedExceptionResolver.java
stitheridge/isis
1a24310c01c6c4d52cd2a451c7a97d4e28f6dd59
[ "Apache-2.0" ]
null
null
null
persistence/jdo/datanucleus-5/src/main/java/org/apache/isis/persistence/jdo/datanucleus5/exceprecog/JdoNestedExceptionResolver.java
stitheridge/isis
1a24310c01c6c4d52cd2a451c7a97d4e28f6dd59
[ "Apache-2.0" ]
null
null
null
persistence/jdo/datanucleus-5/src/main/java/org/apache/isis/persistence/jdo/datanucleus5/exceprecog/JdoNestedExceptionResolver.java
stitheridge/isis
1a24310c01c6c4d52cd2a451c7a97d4e28f6dd59
[ "Apache-2.0" ]
1
2020-12-22T03:26:18.000Z
2020-12-22T03:26:18.000Z
32.23913
81
0.718813
6,433
/* * 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.isis.persistence.jdo.datanucleus5.exceprecog; import java.util.stream.Stream; import javax.jdo.JDODataStoreException; import org.apache.isis.commons.internal.base._NullSafe; import lombok.val; /** * @since 2.0 */ final class JdoNestedExceptionResolver { static Stream<Throwable> streamNestedExceptionsOf(Throwable throwable) { if(throwable instanceof JDODataStoreException) { val jdoDataStoreException = (JDODataStoreException) throwable; return _NullSafe.stream(jdoDataStoreException.getNestedExceptions()); } return Stream.empty(); } }
3e0f23984f098f0e9717c4797e9606019be52dc3
643
java
Java
tnxjeex/tnxjeex-payment/tnxjeex-payment-core/src/main/java/org/truenewx/tnxjeex/payment/core/gateway/PaymentChannel.java
truenewx/truenewx
7b3564d96f54ae7f564343a4bef4b91b8b39bab7
[ "Apache-2.0" ]
null
null
null
tnxjeex/tnxjeex-payment/tnxjeex-payment-core/src/main/java/org/truenewx/tnxjeex/payment/core/gateway/PaymentChannel.java
truenewx/truenewx
7b3564d96f54ae7f564343a4bef4b91b8b39bab7
[ "Apache-2.0" ]
null
null
null
tnxjeex/tnxjeex-payment/tnxjeex-payment-core/src/main/java/org/truenewx/tnxjeex/payment/core/gateway/PaymentChannel.java
truenewx/truenewx
7b3564d96f54ae7f564343a4bef4b91b8b39bab7
[ "Apache-2.0" ]
null
null
null
15.682927
54
0.620529
6,434
package org.truenewx.tnxjeex.payment.core.gateway; import org.truenewx.tnxjee.core.caption.Caption; import org.truenewx.tnxjee.model.annotation.EnumValue; /** * 支付渠道 * * @author jianglei */ public enum PaymentChannel { @Caption("支付宝") @EnumValue("alipay") ALIPAY, @Caption("财付通") @EnumValue("tenpay") TENPAY, @Caption("微信支付") @EnumValue("weixin") WEIXIN, @Caption("QQ钱包") @EnumValue("qpay") QPAY, @Caption("PayPal") @EnumValue("paypal") PAYPAL, @Caption("Apple Pay") @EnumValue("apple") APPLE, @Caption("Google支付") @EnumValue("google") GOOGLE; }
3e0f23d21e9b3183980d5614cba40f838b733412
807
java
Java
src/main/java/cz/freemanovec/malinus/planets/biomegenbases/BiomeGenBaseOrion.java
freemanovec/Malinus-Solar-System---GC-Addon
8c315349e6653eabe01cb17f760f54fd99245391
[ "MIT" ]
null
null
null
src/main/java/cz/freemanovec/malinus/planets/biomegenbases/BiomeGenBaseOrion.java
freemanovec/Malinus-Solar-System---GC-Addon
8c315349e6653eabe01cb17f760f54fd99245391
[ "MIT" ]
null
null
null
src/main/java/cz/freemanovec/malinus/planets/biomegenbases/BiomeGenBaseOrion.java
freemanovec/Malinus-Solar-System---GC-Addon
8c315349e6653eabe01cb17f760f54fd99245391
[ "MIT" ]
1
2019-12-22T10:23:08.000Z
2019-12-22T10:23:08.000Z
26.032258
130
0.795539
6,435
package cz.freemanovec.malinus.planets.biomegenbases; import cz.freemanovec.malinus.ConfigurationCLS; import cz.freemanovec.malinus.planets.biomegenflags.BiomeGenFlagOrion; import net.minecraft.world.biome.BiomeGenBase; public class BiomeGenBaseOrion extends BiomeGenBase{ public static final BiomeGenBase orionFlat = new BiomeGenFlagOrion(ConfigurationCLS.biomeID_orionFlat).setBiomeName("orionFlat"); public BiomeGenBaseOrion(int var1) { super(var1); this.spawnableMonsterList.clear(); this.spawnableWaterCreatureList.clear(); this.spawnableCreatureList.clear(); this.rainfall = 0; this.flowers.clear(); } @Override public BiomeGenBaseOrion setColor(int var1){ return (BiomeGenBaseOrion) super.setColor(var1); } @Override public float getSpawningChance(){ return 0; } }
3e0f241b9cec126dbb277a8b4dbfb08eae2c3346
5,042
java
Java
fwmf-module-user-role/fwmf-module-user-role-api/src/main/java/cn/faury/fwmf/module/api/user/service/ShopRUserService.java
fzyycp/fwmf-module
36d39a312ad73b0f9a77e96acd614b0ff8cebe4f
[ "Apache-2.0" ]
null
null
null
fwmf-module-user-role/fwmf-module-user-role-api/src/main/java/cn/faury/fwmf/module/api/user/service/ShopRUserService.java
fzyycp/fwmf-module
36d39a312ad73b0f9a77e96acd614b0ff8cebe4f
[ "Apache-2.0" ]
null
null
null
fwmf-module-user-role/fwmf-module-user-role-api/src/main/java/cn/faury/fwmf/module/api/user/service/ShopRUserService.java
fzyycp/fwmf-module
36d39a312ad73b0f9a77e96acd614b0ff8cebe4f
[ "Apache-2.0" ]
null
null
null
21.547009
114
0.638834
6,436
package cn.faury.fwmf.module.api.user.service; import cn.faury.fdk.common.anotation.permission.Read; import cn.faury.fdk.common.anotation.permission.Write; import cn.faury.fdk.common.db.PageInfo; import cn.faury.fdk.common.db.PageParam; import cn.faury.fwmf.module.api.user.bean.ShopRUserBean; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 商店用户关联 */ public interface ShopRUserService { /** * 插入商店用户关联表(通过用户ID获取用户信息,然后商店用户关联) * * @param shopId * 商店ID * @param shopUserId * 商店用户ID * @param isSelfCreate * 是否自建 * @param isAdmin * 是否是店主 * @return */ @Write public Integer insertShopRUserById(final Long shopId, final Long shopUserId, final String isSelfCreate, final String isAdmin); /** * 删除用户表、用户密码表、商店用户关联表 * * @param shopUserIds * 【必填】多个用户IDS * @param shopId * 【必填】商店ID * @param isSelfCreate * 【必填】是否自己创建:true,自建 * @return Integer */ @Write public Integer deleteUser(final List<Long> shopUserIds, final Long shopId, final Boolean isSelfCreate); /** * 通过商店用户ID查询商店用户信息 * * @param shopUserId * 【必填】商店用户ID * @param shopId * 【必填】商店ID * @return 商店用户信息 */ @Read public ShopRUserBean getShopRUserInfoById(final Long shopUserId, final Long shopId); /** * 通过条件查询商店用户信息 * * * @param pageParam * 分页参数 * @param paramter * 查询条件 * * <pre> * 【可选】String systemCode 系统Code * 【可选】Long shopId 商店ID * 【可选】String shopName 商店名称 * 【可选】String ShortName 商店简称 * 【可选】String shopUserName 商店用户姓名 * 【可选】String shopUserLoginName 商店用户登录名 * 【可选】List<Long> userIds 商店用户IDs * </pre> * @return 商店用户信息 */ @Read public PageInfo<ShopRUserBean> getShopInfo(final PageParam pageParam, final Map<String, Object> paramter); /** * 通过商店ID查询商店用户信息 * * @param pageParam * 分页参数 * @param shopId * 商店ID * @return 商店用户信息 */ @Read default public PageInfo<ShopRUserBean> getShopInfoByShopId(final PageParam pageParam, final Long shopId){ Map<String, Object> paramter = new HashMap<String, Object>(); paramter.put("shopId", shopId); return getShopInfo(pageParam, paramter); } /** * 通过商店名称查询商店用户信息 * * @param pageParam * 分页参数 * @param shopName * 商店名称 * @return 商店用户信息 */ @Read default public PageInfo<ShopRUserBean> getShopInfoByShopName(final PageParam pageParam, final String shopName){ Map<String, Object> paramter = new HashMap<String, Object>(); paramter.put("shopName", shopName); return getShopInfo(pageParam, paramter); } /** * 通过商店简称查询商店用户信息 * * @param pageParam * 分页参数 * @param shortName * 商店简称 * @return 商店用户信息 */ @Read default public PageInfo<ShopRUserBean> getShopInfoByShortName(final PageParam pageParam, final String shortName){ Map<String, Object> paramter = new HashMap<String, Object>(); paramter.put("shortName", shortName); return getShopInfo(pageParam, paramter); } /** * 插入商店用户关联表(先插入用户表(密码获取系统参数),然后商店用户关联) * * <pre> * shopUserLoginName 【必填】商店用户登录名 * shopUserName 【必填】商店用户姓名 * isSelfCreate 【必填】是否自己创建 * isAdmin【必填】是否店主 * shopId 【必填】商店ID * systemId 【必填】所属系统ID * password 【必填】密码 * </pre> * * @param bean * @return */ @Write public Long insertShopRUser(final ShopRUserBean bean); /** * * @param 【必填】shopUserIds 多个用户IDS * @param 【必填】shopId 商店ID * @return */ @Write public Integer deleteShopRUser(final List<Long> shopUserIds, final Long shopId); /** * 通过商店id查询商店用户 =======分页 * * <pre> * @param 【可选】shopUserLoginName shopUserLoginName * @param 【可选】shopUserName 商店用户姓名 * @param 【必填】shopId 商店ID * @param 【必填】systrmId 系统ID * </pre> * * @param map * @return */ @Read public PageInfo<ShopRUserBean> queryShopRUserInfoPage(final Map<String, Object> map); /** * 通过商店id查询商店用户 * * <pre> * @param 【可选】shopUserLoginName shopUserLoginName * @param 【可选】shopUserName 商店用户姓名 * @param 【必填】shopId 商店ID * @param 【必填】systrmId 系统ID * </pre> * * @param map * @return */ @Read public List<ShopRUserBean> queryShopRUserInfoList(final Map<String, Object> map); /** * 获取未关联商店用户 * * <pre> * 参数说明: * page:分页参数 * rows:分页参数 * 【必选】shopId:商店ID * 【必选】systemId:业务系统ID或者APP ID * </pre> * * @return */ @Read public PageInfo<ShopRUserBean> getShopUnUserList(final Map<String, Object> parameters); /** * 判断用户是否关联其他表(授权系统、APP,用户组,测试用户,角色) * * @param shopUserId * 商店用户ID * @return */ @Read public Boolean isShopUserR(final Long shopUserId); /** * 修改商店用户关联信息(修改用户表,修改商店用户关联) * * <pre> * shopUserId 【必填】商店用户ID * shopUserLoginName 【必填】商店用户登录名 * shopUserName 【必填】商店用户姓名 * isSelfCreate 【必填】是否自己创建1,自建 * </pre> * * @param bean * @return Integer */ @Write public Integer updateShopRUser(final ShopRUserBean bean); }
3e0f24e0bac698b45aaab5b5b37d71511e45e646
2,917
java
Java
spring-boot-security-saml-demo-static-metadata/src/main/java/com/github/ulisesbocchio/demo/SpringBootSecuritySAMLDemoApplication.java
sbante/spring-boot-security-saml-samples
9ef34b596d6f5ffe9ddad04cabdc896cad73e4f9
[ "MIT" ]
53
2016-09-14T03:49:11.000Z
2022-02-22T04:58:43.000Z
spring-boot-security-saml-demo-static-metadata/src/main/java/com/github/ulisesbocchio/demo/SpringBootSecuritySAMLDemoApplication.java
sbante/spring-boot-security-saml-samples
9ef34b596d6f5ffe9ddad04cabdc896cad73e4f9
[ "MIT" ]
24
2016-11-11T22:43:11.000Z
2022-02-05T17:35:13.000Z
spring-boot-security-saml-demo-static-metadata/src/main/java/com/github/ulisesbocchio/demo/SpringBootSecuritySAMLDemoApplication.java
sbante/spring-boot-security-saml-samples
9ef34b596d6f5ffe9ddad04cabdc896cad73e4f9
[ "MIT" ]
61
2016-08-11T14:55:06.000Z
2022-03-23T17:38:27.000Z
38.893333
102
0.634556
6,437
package com.github.ulisesbocchio.demo; import com.github.ulisesbocchio.spring.boot.security.saml.annotation.EnableSAMLSSO; import com.github.ulisesbocchio.spring.boot.security.saml.configurer.ServiceProviderBuilder; import com.github.ulisesbocchio.spring.boot.security.saml.configurer.ServiceProviderConfigurerAdapter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootApplication @EnableSAMLSSO public class SpringBootSecuritySAMLDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSecuritySAMLDemoApplication.class, args); } @Configuration public static class MvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); registry.addViewController("/protected").setViewName("protected"); } } @Configuration public static class MyServiceProviderConfig extends ServiceProviderConfigurerAdapter { @Override public void configure(ServiceProviderBuilder serviceProvider) throws Exception { // @formatter:off serviceProvider .metadataGenerator() .entityId("localhost-demo") .and() .sso() .defaultSuccessURL("/home") .idpSelectionPageURL("/idpselection") .and() .logout() .defaultTargetURL("/") .and() .metadataManager() .metadataLocations("classpath:/idp-ssocircle.xml") .localMetadataLocation("classpath:/sp-ssocircle.xml") .refreshCheckInterval(0) .and() .extendedMetadata() .idpDiscoveryEnabled(true) .and() .localExtendedMetadata() .securityProfile("metaiop") .sslSecurityProfile("pkix") .signMetadata(true) .signingKey("localhost") .encryptionKey("localhost") .requireArtifactResolveSigned(false) .requireLogoutRequestSigned(false) .idpDiscoveryEnabled(true) .and() //This Keystore contains also the public key of idp.ssocircle.com .keyManager() .storeLocation("classpath:/localhost.jks") .storePass("foobar") .defaultKey("localhost") .keyPassword("localhost", "foobar"); // @formatter:on } } }
3e0f24ea7be9a43dbabd24b65408235099d1b2b5
7,684
java
Java
kie-wb-common-screens/kie-wb-common-datasource-mgmt/kie-wb-common-datasource-mgmt-client/src/main/java/org/kie/workbench/common/screens/datasource/management/client/explorer/project/ModuleSelector.java
alepintus/kie-wb-common
52f4225b6fa54d04435c8f5f59bee5894af23b7e
[ "Apache-2.0" ]
34
2017-05-21T11:28:40.000Z
2021-07-03T13:15:03.000Z
kie-wb-common-screens/kie-wb-common-datasource-mgmt/kie-wb-common-datasource-mgmt-client/src/main/java/org/kie/workbench/common/screens/datasource/management/client/explorer/project/ModuleSelector.java
alepintus/kie-wb-common
52f4225b6fa54d04435c8f5f59bee5894af23b7e
[ "Apache-2.0" ]
2,576
2017-03-14T00:57:07.000Z
2022-03-29T07:52:38.000Z
kie-wb-common-screens/kie-wb-common-datasource-mgmt/kie-wb-common-datasource-mgmt-client/src/main/java/org/kie/workbench/common/screens/datasource/management/client/explorer/project/ModuleSelector.java
alepintus/kie-wb-common
52f4225b6fa54d04435c8f5f59bee5894af23b7e
[ "Apache-2.0" ]
158
2017-03-15T08:55:40.000Z
2021-11-19T14:07:17.000Z
42.453039
106
0.640942
6,438
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.screens.datasource.management.client.explorer.project; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import org.guvnor.common.services.project.model.Module; import org.guvnor.structure.organizationalunit.OrganizationalUnit; import org.guvnor.structure.repositories.Repository; import org.gwtbootstrap3.client.ui.AnchorListItem; import org.kie.workbench.common.screens.explorer.client.resources.i18n.ProjectExplorerConstants; import org.kie.workbench.common.screens.explorer.client.widgets.dropdown.CustomDropdown; import org.kie.workbench.common.screens.explorer.client.widgets.navigator.NavigatorBreadcrumbs; public class ModuleSelector extends Composite { private final FlowPanel container = new FlowPanel(); private final CustomDropdown organizationUnits = new CustomDropdown(); private final CustomDropdown repos = new CustomDropdown(); private final CustomDropdown modules = new CustomDropdown(); private NavigatorBreadcrumbs navigatorBreadcrumbs; private boolean isAlreadyInitialized = false; private List<ModuleSelectorHandler> handlers = new ArrayList<>(); public ModuleSelector() { initWidget(container); } public void loadOptions(final Collection<OrganizationalUnit> organizationalUnits, final OrganizationalUnit activeOrganizationalUnit, final Collection<Repository> repositories, final Repository activeRepository, final Collection<Module> modules, final Module activeModule) { this.organizationUnits.clear(); if (organizationalUnits != null) { if (activeOrganizationalUnit != null) { this.organizationUnits.setText(activeOrganizationalUnit.getName()); } for (final OrganizationalUnit ou : organizationalUnits) { this.organizationUnits.add(new AnchorListItem(ou.getName()) {{ addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { onOrganizationalUnitSelected(ou); } }); }}); } } this.repos.clear(); if (repositories != null) { if (activeRepository != null) { this.repos.setText(activeRepository.getAlias()); } else { this.repos.setText(ProjectExplorerConstants.INSTANCE.nullEntry()); } for (final Repository repository : repositories) { this.repos.add(new AnchorListItem(repository.getAlias()) {{ addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { onRepositorySelected(repository); } }); }}); } } this.modules.clear(); if (modules != null) { if (activeModule != null) { this.modules.setText(activeModule.getModuleName()); } else { this.modules.setText(ProjectExplorerConstants.INSTANCE.nullEntry()); } for (final Module module : modules) { this.modules.add(new AnchorListItem(module.getModuleName()) {{ addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { onModuleSelected(module); } }); }}); } } if (organizationalUnits != null && organizationalUnits.isEmpty()) { this.organizationUnits.setText(ProjectExplorerConstants.INSTANCE.nullEntry()); this.organizationUnits.add(new AnchorListItem(ProjectExplorerConstants.INSTANCE.nullEntry())); this.repos.setText(ProjectExplorerConstants.INSTANCE.nullEntry()); this.repos.add(new AnchorListItem(ProjectExplorerConstants.INSTANCE.nullEntry())); this.modules.setText(ProjectExplorerConstants.INSTANCE.nullEntry()); this.modules.add(new AnchorListItem(ProjectExplorerConstants.INSTANCE.nullEntry())); } else if (repositories != null && repositories.isEmpty()) { this.repos.setText(ProjectExplorerConstants.INSTANCE.nullEntry()); this.repos.add(new AnchorListItem(ProjectExplorerConstants.INSTANCE.nullEntry())); this.modules.setText(ProjectExplorerConstants.INSTANCE.nullEntry()); this.modules.add(new AnchorListItem(ProjectExplorerConstants.INSTANCE.nullEntry())); } else if (modules != null && modules.isEmpty()) { this.modules.setText(ProjectExplorerConstants.INSTANCE.nullEntry()); this.modules.add(new AnchorListItem(ProjectExplorerConstants.INSTANCE.nullEntry())); } if (!isAlreadyInitialized) { container.clear(); setupNavigatorBreadcrumbs(); addDivToAlignComponents(); isAlreadyInitialized = true; } } public void addModuleSelectorHandler(final ModuleSelectorHandler handler) { if (!handlers.contains(handler)) { handlers.add(handler); } } private void addDivToAlignComponents() { FlowPanel divClear = new FlowPanel(); divClear.getElement().getStyle().setClear(Style.Clear.BOTH); container.add(divClear); } private void setupNavigatorBreadcrumbs() { this.navigatorBreadcrumbs = new NavigatorBreadcrumbs(NavigatorBreadcrumbs.Mode.HEADER) {{ build(organizationUnits, repos, ModuleSelector.this.modules); }}; FlowPanel navigatorBreadcrumbsContainer = new FlowPanel(); navigatorBreadcrumbsContainer.getElement().getStyle().setFloat(Style.Float.LEFT); navigatorBreadcrumbsContainer.add(navigatorBreadcrumbs); container.add(navigatorBreadcrumbsContainer); } private void onOrganizationalUnitSelected(final OrganizationalUnit ou) { for (ModuleSelectorHandler handler : handlers) { handler.onOrganizationalUnitSelected(ou); } } private void onRepositorySelected(final Repository repository) { for (ModuleSelectorHandler handler : handlers) { handler.onRepositorySelected(repository); } } private void onModuleSelected(final Module module) { for (ModuleSelectorHandler handler : handlers) { handler.onModuleSelected(module); } } }
3e0f260aa4eebc0785d11210ffc82def692e4897
2,492
java
Java
analyzed_libs/jdk1.6.0_06_src/java/rmi/server/LoaderHandler.java
jgaltidor/VarJ
3a25102f8a1a406f5e458cb7d8945cc33b6a4fea
[ "MIT" ]
1
2017-01-26T20:25:00.000Z
2017-01-26T20:25:00.000Z
analyzed_libs/jdk1.6.0_06_src/java/rmi/server/LoaderHandler.java
jgaltidor/VarJ
3a25102f8a1a406f5e458cb7d8945cc33b6a4fea
[ "MIT" ]
null
null
null
analyzed_libs/jdk1.6.0_06_src/java/rmi/server/LoaderHandler.java
jgaltidor/VarJ
3a25102f8a1a406f5e458cb7d8945cc33b6a4fea
[ "MIT" ]
null
null
null
31.544304
76
0.657705
6,440
/* * @(#)LoaderHandler.java 1.19 05/11/17 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.rmi.server; import java.net.MalformedURLException; import java.net.URL; /** * <code>LoaderHandler</code> is an interface used internally by the RMI * runtime in previous implementation versions. It should never be accessed * by application code. * * @version 1.19, 11/17/05 * @author Ann Wollrath * @since JDK1.1 * * @deprecated no replacement */ @Deprecated public interface LoaderHandler { /** package of system <code>LoaderHandler</code> implementation. */ final static String packagePrefix = "sun.rmi.server"; /** * Loads a class from the location specified by the * <code>java.rmi.server.codebase</code> property. * * @param name the name of the class to load * @return the <code>Class</code> object representing the loaded class * @exception MalformedURLException * if the system property <b>java.rmi.server.codebase</b> * contains an invalid URL * @exception ClassNotFoundException * if a definition for the class could not * be found at the codebase location. * @since JDK1.1 * @deprecated no replacement */ @Deprecated Class<?> loadClass(String name) throws MalformedURLException, ClassNotFoundException; /** * Loads a class from a URL. * * @param codebase the URL from which to load the class * @param name the name of the class to load * @return the <code>Class</code> object representing the loaded class * @exception MalformedURLException * if the <code>codebase</code> paramater * contains an invalid URL * @exception ClassNotFoundException * if a definition for the class could not * be found at the specified URL * @since JDK1.1 * @deprecated no replacement */ @Deprecated Class<?> loadClass(URL codebase, String name) throws MalformedURLException, ClassNotFoundException; /** * Returns the security context of the given class loader. * * @param loader a class loader from which to get the security context * @return the security context * @since JDK1.1 * @deprecated no replacement */ @Deprecated Object getSecurityContext(ClassLoader loader); }
3e0f2650f8d402267aab48e30184f8a4a17ad462
3,896
java
Java
aliyun-java-sdk-sddp/src/main/java/com/aliyuncs/sddp/transform/v20190103/DescribeAuditLogsResponseUnmarshaller.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
3
2020-04-26T09:15:45.000Z
2020-05-09T03:10:26.000Z
aliyun-java-sdk-sddp/src/main/java/com/aliyuncs/sddp/transform/v20190103/DescribeAuditLogsResponseUnmarshaller.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
27
2021-06-11T21:08:40.000Z
2022-03-11T21:25:09.000Z
aliyun-java-sdk-sddp/src/main/java/com/aliyuncs/sddp/transform/v20190103/DescribeAuditLogsResponseUnmarshaller.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
1
2020-03-05T07:30:16.000Z
2020-03-05T07:30:16.000Z
58.149254
132
0.764117
6,441
/* * 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.aliyuncs.sddp.transform.v20190103; import java.util.ArrayList; import java.util.List; import com.aliyuncs.sddp.model.v20190103.DescribeAuditLogsResponse; import com.aliyuncs.sddp.model.v20190103.DescribeAuditLogsResponse.Log; import com.aliyuncs.transform.UnmarshallerContext; public class DescribeAuditLogsResponseUnmarshaller { public static DescribeAuditLogsResponse unmarshall(DescribeAuditLogsResponse describeAuditLogsResponse, UnmarshallerContext _ctx) { describeAuditLogsResponse.setRequestId(_ctx.stringValue("DescribeAuditLogsResponse.RequestId")); describeAuditLogsResponse.setPageSize(_ctx.integerValue("DescribeAuditLogsResponse.PageSize")); describeAuditLogsResponse.setCurrentPage(_ctx.integerValue("DescribeAuditLogsResponse.CurrentPage")); describeAuditLogsResponse.setTotalCount(_ctx.integerValue("DescribeAuditLogsResponse.TotalCount")); List<Log> items = new ArrayList<Log>(); for (int i = 0; i < _ctx.lengthValue("DescribeAuditLogsResponse.Items.Length"); i++) { Log log = new Log(); log.setId(_ctx.longValue("DescribeAuditLogsResponse.Items["+ i +"].Id")); log.setProductCode(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].ProductCode")); log.setProductId(_ctx.longValue("DescribeAuditLogsResponse.Items["+ i +"].ProductId")); log.setLogTime(_ctx.longValue("DescribeAuditLogsResponse.Items["+ i +"].LogTime")); log.setUserId(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].UserId")); log.setUserName(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].UserName")); log.setClientIp(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].ClientIp")); log.setClientPort(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].ClientPort")); log.setClientUa(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].ClientUa")); log.setInstanceName(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].InstanceName")); log.setCreationTime(_ctx.longValue("DescribeAuditLogsResponse.Items["+ i +"].CreationTime")); log.setDatabaseName(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].DatabaseName")); log.setTableName(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].TableName")); log.setColumnName(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].ColumnName")); log.setPackageName(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].PackageName")); log.setOssObjectKey(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].OssObjectKey")); log.setExecuteTime(_ctx.longValue("DescribeAuditLogsResponse.Items["+ i +"].ExecuteTime")); log.setEffectRow(_ctx.longValue("DescribeAuditLogsResponse.Items["+ i +"].EffectRow")); log.setOperateType(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].OperateType")); log.setRuleId(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].RuleId")); log.setRuleName(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].RuleName")); log.setWarnLevel(_ctx.stringValue("DescribeAuditLogsResponse.Items["+ i +"].WarnLevel")); log.setExecuteStatus(_ctx.integerValue("DescribeAuditLogsResponse.Items["+ i +"].ExecuteStatus")); items.add(log); } describeAuditLogsResponse.setItems(items); return describeAuditLogsResponse; } }
3e0f26881193d1b07625c4dfaa20951fb35f8c04
1,158
java
Java
src/java/com.leetcode/easy/array/PascalTriangle.java
ArchyXiao/leetcode-terminator
2a6751627dfc99c53d4c9ab098ba03f7aa96d397
[ "Apache-2.0" ]
3
2020-01-13T03:44:34.000Z
2021-12-28T01:27:21.000Z
src/java/com.leetcode/easy/array/PascalTriangle.java
ArchyXiao/leetcode-terminator
2a6751627dfc99c53d4c9ab098ba03f7aa96d397
[ "Apache-2.0" ]
null
null
null
src/java/com.leetcode/easy/array/PascalTriangle.java
ArchyXiao/leetcode-terminator
2a6751627dfc99c53d4c9ab098ba03f7aa96d397
[ "Apache-2.0" ]
null
null
null
25.173913
103
0.531952
6,442
package com.leetcode.easy.array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @Description: Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. * <p> * In Pascal's triangle, each number is the sum of the two numbers directly above it. * <p> * Example: * Input: 5 * Output: * [1], * [1,1], * [1,2,1], * [1,3,3,1], * [1,4,6,4,1] * <p> * Tips: a[i, j] = a[i - 1, j - 1] + a[i - 1, j] * @Auther: xiaoshude * @Date: 2019/10/15 20:07 */ public class PascalTriangle { // Time: O(n^2), Space: O(1) public List<List<Integer>> generate(int numRows) { List<List<Integer>> result = new ArrayList<>(); if (numRows < 1) { return result; } for (int i = 0; i < numRows; i++) { List<Integer> subList = Arrays.asList(new Integer[i + 1]); subList.set(0, 1); subList.set(i, 1); for (int j = 1; j < i; j++) { subList.set(j, result.get(i - 1).get(j - 1) + result.get(i - 1).get(j)); } result.add(subList); } return result; } }
3e0f2904067138c916e05149f838acbc6084debf
617
java
Java
src/main/java/com/zupacademy/propostas/commos/exceptions/RegraDeNegocioException.java
AlanaZUP/orange-talents-08-template-proposta
ecd82a3f4cfb3429ed41ef811d6d1801cf41d5df
[ "Apache-2.0" ]
null
null
null
src/main/java/com/zupacademy/propostas/commos/exceptions/RegraDeNegocioException.java
AlanaZUP/orange-talents-08-template-proposta
ecd82a3f4cfb3429ed41ef811d6d1801cf41d5df
[ "Apache-2.0" ]
null
null
null
src/main/java/com/zupacademy/propostas/commos/exceptions/RegraDeNegocioException.java
AlanaZUP/orange-talents-08-template-proposta
ecd82a3f4cfb3429ed41ef811d6d1801cf41d5df
[ "Apache-2.0" ]
null
null
null
20.566667
79
0.666126
6,443
package com.zupacademy.propostas.commos.exceptions; import org.springframework.http.HttpStatus; public class RegraDeNegocioException extends RuntimeException{ private String field; private String message; private Object value; public RegraDeNegocioException(String field, String message, Object value){ this.field = field; this.message = message; this.value = value; } public String getField() { return field; } @Override public String getMessage() { return message; } public Object getValue() { return value; } }
3e0f29a69edd226378ce1a4694b96f5781afb6be
7,760
java
Java
bundles/edu.kit.textannotation.annotationplugin/src/edu/kit/textannotation/annotationplugin/views/AnnotationControlsView.java
kit-sdq/textannotation
b3ad8e7a4ffee06a7d4d4ebb40e33b996e6afac5
[ "MIT" ]
1
2020-02-20T09:09:59.000Z
2020-02-20T09:09:59.000Z
bundles/edu.kit.textannotation.annotationplugin/src/edu/kit/textannotation/annotationplugin/views/AnnotationControlsView.java
lukasbach/textannotation
87b4cb44573f18686c47505b12e2dd991e786df6
[ "MIT" ]
2
2020-03-14T16:24:52.000Z
2020-03-14T16:28:08.000Z
bundles/edu.kit.textannotation.annotationplugin/src/edu/kit/textannotation/annotationplugin/views/AnnotationControlsView.java
kit-sdq/textannotation
b3ad8e7a4ffee06a7d4d4ebb40e33b996e6afac5
[ "MIT" ]
2
2020-03-11T15:32:21.000Z
2020-03-14T17:07:35.000Z
40
130
0.773325
6,444
package edu.kit.textannotation.annotationplugin.views; import java.util.Arrays; import java.util.List; import edu.kit.textannotation.annotationplugin.editor.AnnotationEditorFinder; import edu.kit.textannotation.annotationplugin.selectionstrategy.DefaultSelectionStrategy; import edu.kit.textannotation.annotationplugin.selectionstrategy.SelectionStrategy; import edu.kit.textannotation.annotationplugin.selectionstrategy.SentenceSelectionStrategy; import edu.kit.textannotation.annotationplugin.selectionstrategy.WordSelectionStrategy; import edu.kit.textannotation.annotationplugin.utils.EclipseUtils; import edu.kit.textannotation.annotationplugin.editor.AnnotationTextEditor; import edu.kit.textannotation.annotationplugin.profile.AnnotationProfileRegistry; import edu.kit.textannotation.annotationplugin.profile.ProfileNotFoundException; import edu.kit.textannotation.annotationplugin.textmodel.InvalidAnnotationProfileFormatException; import edu.kit.textannotation.annotationplugin.utils.LayoutUtilities; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.widgets.*; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.part.*; import edu.kit.textannotation.annotationplugin.profile.AnnotationClass; import edu.kit.textannotation.annotationplugin.profile.AnnotationProfile; import edu.kit.textannotation.annotationplugin.textmodel.TextModelData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.ui.*; import org.eclipse.swt.SWT; import javax.inject.Inject; /** * The control view which is contributed to the plugin. See the plugins documentation for more details on * its contributing views. */ public class AnnotationControlsView extends ViewPart { public static final String ID = "edu.kit.textannotation.annotationplugin.views.AnnotationControlsView"; private GridLayout layout; private AnnotationTextEditor editor; private AnnotationProfileRegistry registry; private AnnotationEditorFinder finder; private LayoutUtilities lu = new LayoutUtilities(); private List<SelectionStrategy> selectionStrategies; private SelectionStrategy activeSelectionStrategy; @Inject IWorkbench workbench; @Override public void createPartControl(Composite parent) { // TODO maybe checking ever 10-or-so seconds for profile updates might not be a bad idea loadSelectionStrategies(); finder = new AnnotationEditorFinder(workbench); finder.onAnnotationEditorActivated.addListener(editor -> rebuildContent(parent, editor.getTextModelData())); if (finder.getAnnotationEditor() != null) { rebuildContent(parent, finder.getAnnotationEditor().getTextModelData()); } } @Override public void setFocus() { } @Override public String getTitle() { return "Annotation Controls"; } private void loadSelectionStrategies() { selectionStrategies = Arrays.asList( new DefaultSelectionStrategy(), new WordSelectionStrategy(), new SentenceSelectionStrategy() ); activeSelectionStrategy = new DefaultSelectionStrategy(); } private void rebuildContent(Composite parent, TextModelData textModelData) { if (parent.isDisposed()) { return; } editor = finder.getAnnotationEditor(); registry = editor.getAnnotationProfileRegistry(); List<AnnotationProfile> profiles; AnnotationProfile profile; try { profiles = registry.getProfiles(); profile = registry.findProfile(textModelData.getProfileId()); } catch (InvalidAnnotationProfileFormatException e) { EclipseUtils.reportError("Invalid profile format: " + e.getMessage()); return; } catch (ProfileNotFoundException e) { EclipseUtils.reportError("Profile not found: " + e.getMessage()); return; } EclipseUtils.clearChildren(parent); layout = new GridLayout(1, false); parent.setLayout(layout); Header .withTitle(profile.getName()) .withButton("Change Profile", () -> { List<AnnotationProfile> newlyLoadedProfiles; try { newlyLoadedProfiles = registry.getProfiles(); } catch (InvalidAnnotationProfileFormatException e) { newlyLoadedProfiles = profiles; } ElementListSelectionDialog dialog = new ElementListSelectionDialog(parent.getShell(), new LabelProvider()); dialog.setTitle("Change Profile"); dialog.setMessage("Change Profile for the current annotation text file"); dialog.setElements(newlyLoadedProfiles.toArray()); dialog.open(); AnnotationProfile selectedProfile = (AnnotationProfile) dialog.getFirstResult(); if (selectedProfile != null) { textModelData.setProfileId(selectedProfile.getId()); try { editor.onProfileChange.fire(registry.findProfile(selectedProfile.getId())); editor.markDocumentAsDirty(); } catch (ProfileNotFoundException | InvalidAnnotationProfileFormatException e) { EclipseUtils.reportError("Profile change error: " + e.getMessage()); } rebuildContent(parent, textModelData); } }) .withButton("Edit Profile", () -> { EditProfileDialog.openWindow(registry, textModelData.getProfileId(), p -> { rebuildContent(parent, textModelData); editor.onProfileChange.fire(p); }, null); }) .render(parent); Label subtitleLabel = new Label(parent, SWT.WRAP | SWT.LEFT); subtitleLabel.setText(String.format("The annotatable text file currently uses the \"%s\" annotation profile, its ID is \"%s\".", profile.getName(), profile.getId())); subtitleLabel.setLayoutData(new GridData(SWT.HORIZONTAL, SWT.TOP, true, false, 1, 1)); FontData[] fD = subtitleLabel.getFont().getFontData(); fD[0].setHeight(10); subtitleLabel.setFont(new Font(Display.getDefault(), fD[0])); Header.withTitle("Selection Strategy").withSubTitle(activeSelectionStrategy.getDescription()).render(parent); Composite selectionStrategiesComposite = new Composite(parent, SWT.NONE); selectionStrategiesComposite.setLayoutData(lu.horizontalFillingGridData()); selectionStrategiesComposite.setLayout(lu.fillLayout().withHorizontal().get()); for (SelectionStrategy strategy : selectionStrategies) { Button strategyButton = new Button(selectionStrategiesComposite, SWT.PUSH); strategyButton.setEnabled(!strategy.getId().equals(activeSelectionStrategy.getId())); strategyButton.setText(strategy.getName()); strategyButton.setToolTipText(strategy.getDescription()); strategyButton.addListener(SWT.Selection, e -> { activeSelectionStrategy = strategy; rebuildContent(parent, textModelData); }); } Header .withTitle("Annotation Classes") .withSubTitle("Click on an annotation class to annotate the selected text as the chosen annotation") .render(parent); for (AnnotationClass a: profile.getAnnotationClasses()) { Composite aclContainer = new Composite(parent, SWT.NONE); aclContainer.setLayout(lu.gridLayout().withNumCols(2).withEqualColumnWidth(false).get()); aclContainer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); StyledText colorDisplay = new StyledText(aclContainer, SWT.BORDER); Button button = new Button(aclContainer, SWT.PUSH | SWT.FILL); button.setText(a.getName()); button.setToolTipText(a.getId()); button.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); button.addListener(SWT.Selection, event -> { new AnnotationEditorFinder(workbench).getAnnotationEditor().annotate(a, activeSelectionStrategy); }); colorDisplay.setLayoutData(lu.gridData().withWidthHint(12).withExcessVerticalSpace(true).get()); colorDisplay.setEditable(false); colorDisplay.setBackground(a.getColor()); } parent.layout(); } }
3e0f29c2c71f0c7ebd4bce74e046bd62854f1189
3,011
java
Java
src/test/java/nl/utwente/simulator/input/ExcelInputTest.java
dijkpah/C-L-RAFT-CC-Simulator
f2549ba94e96e5d16764c2f9f904fdf77e5f438b
[ "Apache-2.0" ]
null
null
null
src/test/java/nl/utwente/simulator/input/ExcelInputTest.java
dijkpah/C-L-RAFT-CC-Simulator
f2549ba94e96e5d16764c2f9f904fdf77e5f438b
[ "Apache-2.0" ]
1
2018-06-05T10:41:28.000Z
2018-06-05T10:41:28.000Z
src/test/java/nl/utwente/simulator/input/ExcelInputTest.java
dijkpah/C-L-RAFT-CC-Simulator
f2549ba94e96e5d16764c2f9f904fdf77e5f438b
[ "Apache-2.0" ]
null
null
null
38.113924
124
0.577217
6,445
package nl.utwente.simulator.input; import nl.utwente.simulator.ValidationTest; import nl.utwente.simulator.config.Settings; import org.junit.AfterClass; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.IOException; import static nl.utwente.simulator.config.Settings.log; import static nl.utwente.simulator.input.ExcelInput.*; import static nl.utwente.simulator.input.InputSource.TEST; @Category(ValidationTest.class) public class ExcelInputTest extends ValidationTest { @AfterClass public static void cleanup(){ ExcelInput.deleteExcel(TEST); } @Test public void testExcelGenerationAndReading() throws ExcelGenerationException, IOException, ReflectiveOperationException { Settings.INPUT_FILE = TEST.defaultFileName(); try { log.infoln("[---------------------------- VALIDATING INPUT CLASS -------------------------------]"); validate(InputClass.class); log.infoln("[------------------------ GENERATING EXCEL WITH NULL VALUES ------------------------]"); generateExcel(InputClass.class, TEST, true); log.infoln("[------------------------- READING EXCEL WITH NULL VALUES --------------------------]"); readExcel(InputClass.class, TEST, true); log.infoln("[----------------------- READING EXCEL WITHOUT NULL VALUES -------------------------]"); readExcel(InputClass.class, TEST, false); log.infoln("[---------------------- GENERATING EXCEL WITHOUT NULL VALUES -----------------------]"); generateExcel(InputClass.class, TEST, false); log.infoln("[------------------------- READING EXCEL WITH NULL VALUES --------------------------]"); readExcel(InputClass.class, TEST, true); log.infoln("[----------------------- READING EXCEL WITHOUT NULL VALUES -------------------------]"); readExcel(InputClass.class, TEST, false); } catch (ExcelGenerationException e) { log.errorln("[ERROR]" + e.getMessage()); throw e; } } public class TestClass { public class SubClass1 extends TestClass {} public class SubClass2 extends TestClass { public class SubClass3 extends SubClass2 {} } } public class LongClass { public class SubClass1 extends LongClass {} public class SubClass2 extends LongClass {} public class SubClass3 extends LongClass {} public class SubClass4 extends LongClass {} } public class AnnClass { @InputValue(value = "This is AnnotatedSubClass1", src = {TEST}) public class AnnSubClass1 extends AnnClass { @InputValue(value = "This is AnnotatedSubClass2", src = {TEST}) public class AnnSubClass2 extends AnnClass {} public class AnnSubClass3 extends AnnClass {} } } public enum TestEnum { VALUE_1, VALUE_2, VALUE_3 } }
3e0f2a4766b93793bdef900fde0c0469e73be00a
1,167
java
Java
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/factories/model/sequencing/UnaryTableSequenceConfig.java
marschall/eclipselink.runtime
3d59eaa9e420902d5347b9fb60fbe6c92310894b
[ "BSD-3-Clause" ]
null
null
null
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/factories/model/sequencing/UnaryTableSequenceConfig.java
marschall/eclipselink.runtime
3d59eaa9e420902d5347b9fb60fbe6c92310894b
[ "BSD-3-Clause" ]
2
2021-03-24T17:58:46.000Z
2021-12-14T20:59:52.000Z
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/factories/model/sequencing/UnaryTableSequenceConfig.java
marschall/eclipselink.runtime
3d59eaa9e420902d5347b9fb60fbe6c92310894b
[ "BSD-3-Clause" ]
null
null
null
34.323529
87
0.634961
6,446
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.internal.sessions.factories.model.sequencing; /** * INTERNAL: */ public class UnaryTableSequenceConfig extends SequenceConfig { private String m_counterField; public UnaryTableSequenceConfig() { super(); } public void setCounterField(String counterField) { m_counterField = counterField; } public String getCounterField() { return m_counterField; } }
3e0f2bd27df72e16f2ba54ebc9389444c7a636d1
2,348
java
Java
module1/Astar/src/module1/conf/ConfigReader.java
Bjox/IT3105-ai-programming
3349e23824f8b770f16b9f35524a1c6c2614a63e
[ "MIT" ]
null
null
null
module1/Astar/src/module1/conf/ConfigReader.java
Bjox/IT3105-ai-programming
3349e23824f8b770f16b9f35524a1c6c2614a63e
[ "MIT" ]
null
null
null
module1/Astar/src/module1/conf/ConfigReader.java
Bjox/IT3105-ai-programming
3349e23824f8b770f16b9f35524a1c6c2614a63e
[ "MIT" ]
null
null
null
27.302326
116
0.688671
6,447
package module1.conf; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; /** * * @author Bjox */ public class ConfigReader { @Deprecated public static Config readFileOld(String path) throws FileNotFoundException, IOException { BufferedReader reader = new BufferedReader(new FileReader(path)); Config conf = new Config(); String file = ""; String line = reader.readLine(); while (line != null) { file += line; line = reader.readLine(); } file = file.replaceAll(" ", ""); StringTokenizer tokenizer = new StringTokenizer(file, "() ", false); String[] a = tokenizer.nextToken().split(","); conf.size = new Dimension(Integer.parseInt(a[0]), Integer.parseInt(a[1])); a = tokenizer.nextToken().split(","); conf.start = new Point(Integer.parseInt(a[0]), Integer.parseInt(a[1])); a = tokenizer.nextToken().split(","); conf.goal = new Point(Integer.parseInt(a[0]), Integer.parseInt(a[1])); while (tokenizer.hasMoreTokens()) { a = tokenizer.nextToken().split(","); conf.obstacles.add( new Rectangle(Integer.parseInt(a[0]), Integer.parseInt(a[1]), Integer.parseInt(a[2]), Integer.parseInt(a[3]))); } return conf; } public static Config readFile(String path) throws FileNotFoundException, IOException { BufferedReader reader = new BufferedReader(new FileReader(path)); Config conf = new Config(); StringTokenizer st = new StringTokenizer(reader.readLine()); conf.size = new Dimension(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())); st = new StringTokenizer(reader.readLine()); conf.start = new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())); conf.goal = new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())); String line = reader.readLine(); while (line != null) { st = new StringTokenizer(line); conf.obstacles.add(new Rectangle( Integer.parseInt(st.nextToken()), // x pos Integer.parseInt(st.nextToken()), // y pos Integer.parseInt(st.nextToken()), // width Integer.parseInt(st.nextToken()) // height )); line = reader.readLine(); } return conf; } }
3e0f2c03bcedc36f890098e7b227b6c3f9f20107
4,389
java
Java
Source/Plugins/Core/com.equella.core/src/com/tle/web/spellcheck/servlet/SpellcheckServlet.java
mrblippy/Charliequella
f4d233d8e42dd72935b80c2abea06efb20cea989
[ "Apache-2.0" ]
14
2019-10-09T23:59:32.000Z
2022-03-01T08:34:56.000Z
Source/Plugins/Core/com.equella.core/src/com/tle/web/spellcheck/servlet/SpellcheckServlet.java
mrblippy/Charliequella
f4d233d8e42dd72935b80c2abea06efb20cea989
[ "Apache-2.0" ]
1,549
2019-08-16T01:07:16.000Z
2022-03-31T23:57:34.000Z
Source/Plugins/Core/com.equella.core/src/com/tle/web/spellcheck/servlet/SpellcheckServlet.java
mrblippy/Charliequella
f4d233d8e42dd72935b80c2abea06efb20cea989
[ "Apache-2.0" ]
24
2019-09-05T00:09:35.000Z
2021-10-19T05:10:39.000Z
34.289063
90
0.727273
6,448
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation 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.tle.web.spellcheck.servlet; import com.tle.common.Check; import com.tle.core.guice.Bind; import com.tle.web.spellcheck.SpellcheckRequest; import com.tle.web.spellcheck.SpellcheckRequest.SpellcheckRequestParams; import com.tle.web.spellcheck.SpellcheckResponse; import com.tle.web.spellcheck.SpellcheckService; import java.io.IOException; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; @SuppressWarnings("nls") @Bind @Singleton public class SpellcheckServlet extends HttpServlet { @Inject private SpellcheckService spellcheckService; private static final long serialVersionUID = 1L; @Override @SuppressWarnings("unchecked") protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String spellRequestJSON = req.getReader().readLine(); JSONObject jsonReqObject = JSONObject.fromObject(spellRequestJSON); jsonReqObject.get("params"); SpellcheckRequest spellRequest = new SpellcheckRequest(); spellRequest.setId(jsonReqObject.getString("id")); spellRequest.setMethod(jsonReqObject.getString("method")); SpellcheckRequestParams params = new SpellcheckRequestParams(); params.setLang(jsonReqObject.getJSONArray("params").getString(0)); Object object = jsonReqObject.getJSONArray("params").get(1); if (object instanceof String) { params.setStringList(Collections.singletonList(object.toString())); } else if (object instanceof JSONArray) { params.setStringList((JSONArray) object); } spellRequest.setParams(params); SpellcheckResponse spellResponse = spellcheckService.service(spellRequest); resp.setHeader("Cache-Control", "no-cache, no-store"); // $NON-NLS-1$//$NON-NLS-2$ resp.setContentType("application/json"); // $NON-NLS-1$ resp.getWriter().write(parseResponseToJSON(spellResponse)); } /** * Parses a SpellcheckResponse object to a JSON String that the TinyMCE spellchecker can * understand. This is because JSONlib returns a JSON that somehow TinyMCE doesn't like. * * @param response * @return JSONString */ private String parseResponseToJSON(SpellcheckResponse response) { String string = ""; String responseId = "null"; if (!Check.isEmpty(response.getId())) { responseId = response.getId(); } string += "{"; string += "\"id\":" + responseId; string += ","; String resultsText = listToJSONText(response.getResult()); if (resultsText.equals("null")) { resultsText = "[]"; } string += "\"result\":" + resultsText; string += ","; string += "\"error\":" + listToJSONText(response.getError()); string += "}"; return string; } private String listToJSONText(List<String> list) { if (Check.isEmpty(list)) { return "null"; } StringBuilder returnString = new StringBuilder(); returnString.append("["); for (String msg : list) { returnString.append("\""); returnString.append(msg); returnString.append("\","); } returnString.deleteCharAt(returnString.length() - 1); returnString.append("]"); return returnString.toString(); } public void setSpellcheckService(SpellcheckService spellcheckService) { this.spellcheckService = spellcheckService; } }
3e0f2c0ee6fd8f5dcc23fce62189e5b8fcbe617b
5,151
java
Java
flink-connector-examples/src/main/java/io/pravega/example/flink/primer/process/ExactlyOnceChecker.java
fyang86/pravega-samples
d49d9adf8785f56a4248fbc8dd498245d9f250aa
[ "Apache-2.0" ]
45
2017-05-10T16:34:06.000Z
2022-01-26T03:38:53.000Z
flink-connector-examples/src/main/java/io/pravega/example/flink/primer/process/ExactlyOnceChecker.java
fyang86/pravega-samples
d49d9adf8785f56a4248fbc8dd498245d9f250aa
[ "Apache-2.0" ]
207
2017-05-11T00:02:05.000Z
2022-02-17T13:35:34.000Z
flink-connector-examples/src/main/java/io/pravega/example/flink/primer/process/ExactlyOnceChecker.java
fyang86/pravega-samples
d49d9adf8785f56a4248fbc8dd498245d9f250aa
[ "Apache-2.0" ]
64
2017-05-11T11:30:27.000Z
2022-03-15T06:53:01.000Z
38.155556
125
0.625315
6,449
/* * Copyright (c) 2018 Dell Inc., or its subsidiaries. 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 * */ package io.pravega.example.flink.primer.process; import io.pravega.client.stream.Stream; import io.pravega.client.stream.impl.JavaSerializer; import io.pravega.connectors.flink.FlinkPravegaReader; import io.pravega.connectors.flink.PravegaConfig; import io.pravega.connectors.flink.serialization.PravegaDeserializationSchema; import io.pravega.example.flink.Utils; import io.pravega.example.flink.primer.datatype.Constants; import io.pravega.example.flink.primer.datatype.IntegerEvent; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.util.Collector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.*; /* * Parameters * -stream <pravega_scope>/<pravega_stream>, e.g., myscope/stream1 * -controller tcp://<controller_host>:<port>, e.g., tcp://localhost:9090 * */ public class ExactlyOnceChecker { private static Set<IntegerEvent> checker = new HashSet<>(); private static List<IntegerEvent> duplicates = new ArrayList<IntegerEvent>(); // Logger initialization private static final Logger LOG = LoggerFactory.getLogger(ExactlyOnceChecker.class); public static void main(String[] args) throws Exception { LOG.info("Starting ExactlyOnce checker ..."); // initialize the parameter utility tool in order to retrieve input parameters ParameterTool params = ParameterTool.fromArgs(args); PravegaConfig pravegaConfig = PravegaConfig .fromParams(params) .withControllerURI(URI.create(params.get(Constants.Default_URI_PARAM, Constants.Default_URI))) .withDefaultScope(params.get(Constants.SCOPE_PARAM, Constants.DEFAULT_SCOPE)); // create the Pravega input stream (if necessary) Stream stream = Utils.createStream( pravegaConfig, params.get(Constants.STREAM_PARAM, Constants.DEFAULT_STREAM)); // initialize Flink execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment .getExecutionEnvironment() .setParallelism(1); // create the Pravega source to read a stream of text FlinkPravegaReader<IntegerEvent> reader = FlinkPravegaReader.<IntegerEvent>builder() .withPravegaConfig(pravegaConfig) .forStream(stream) .withDeserializationSchema(new PravegaDeserializationSchema<>(IntegerEvent.class, new JavaSerializer<>())) .build(); DataStream<IntegerEvent> dataStream = env .addSource(reader) .setParallelism(1); // create output stream to data read from Pravega //dataStream.print(); DataStream<DuplicateEvent> duplicateStream = dataStream.flatMap(new FlatMapFunction<IntegerEvent, DuplicateEvent>() { @Override public void flatMap(IntegerEvent event, Collector<DuplicateEvent> out) throws Exception { if (event.isStart()) { // clear checker when the beginning of stream marker arrives checker.clear(); duplicates.clear(); System.out.println("\n============== Checker starts ==============="); } if (event.isEnd()) { if (duplicates.size() == 0) { System.out.println("No duplicate found. EXACTLY_ONCE!"); } else { System.out.println("Found duplicates"); checker.clear(); duplicates.clear(); } System.out.println("============== Checker ends ===============\n"); } if (checker.contains(event)) { duplicates.add(event); DuplicateEvent dup = new DuplicateEvent(event.getValue()); System.out.println(dup); out.collect(dup); } else { checker.add(event); } } }); // create output sink to print duplicates //duplicateStream.print(); // execute within the Flink environment env.execute("ExactlyOnceChecker"); LOG.info("Ending ExactlyOnceChecker..."); } private static class DuplicateEvent { private long value; DuplicateEvent(long value ) { this.value = value; } @Override public String toString() { return "Duplicate event: " + this.value; } } }
3e0f2c76dda7013bb95eb3190c87df029325141d
1,178
java
Java
src/main/java/com/viking/patterns/iterator/SongsOfThe90s.java
vikingden8/Algorithms-Patterns
c1bf3fbd0b726ac986e6934967e7ce4c4e8a8bc3
[ "Apache-2.0" ]
null
null
null
src/main/java/com/viking/patterns/iterator/SongsOfThe90s.java
vikingden8/Algorithms-Patterns
c1bf3fbd0b726ac986e6934967e7ce4c4e8a8bc3
[ "Apache-2.0" ]
null
null
null
src/main/java/com/viking/patterns/iterator/SongsOfThe90s.java
vikingden8/Algorithms-Patterns
c1bf3fbd0b726ac986e6934967e7ce4c4e8a8bc3
[ "Apache-2.0" ]
null
null
null
22.226415
77
0.712224
6,450
package com.viking.patterns.iterator; import java.util.Hashtable; import java.util.Iterator; public class SongsOfThe90s implements SongIterator{ // Create a Hashtable with an int as a key and SongInfo // Objects Hashtable<Integer, SongInfo> bestSongs = new Hashtable<Integer, SongInfo>(); // Will increment the Hashtable key int hashKey = 0; public SongsOfThe90s() { addSong("Losing My Religion", "REM", 1991); addSong("Creep", "Radiohead", 1993); addSong("Walk on the Ocean", "Toad The Wet Sprocket", 1991); } // Add a new SongInfo Object to the Hashtable and then increment // the Hashtable key public void addSong(String songName, String bandName, int yearReleased){ SongInfo songInfo = new SongInfo(songName, bandName, yearReleased); bestSongs.put(hashKey, songInfo); hashKey++; } // This is replaced by the Iterator // Return a Hashtable full of SongInfo Objects public Hashtable<Integer, SongInfo> getBestSongs(){ return bestSongs; } // NEW By adding this method I'll be able to treat all // collections the same public Iterator createIterator() { return bestSongs.values().iterator(); } }
3e0f2cfd79979b2b5939c7a52d98b1402fda77fe
2,960
java
Java
mneme-project/mneme/mneme-impl/impl/src/java/org/etudes/mneme/impl/FormatMatchChoiceDelegate.java
mpellicer/sakai
cbccc0a810107050f284e7213183b2ecdfc1dd3a
[ "ECL-2.0" ]
4
2017-03-22T16:57:42.000Z
2020-04-07T17:34:41.000Z
mneme-project/mneme/mneme-impl/impl/src/java/org/etudes/mneme/impl/FormatMatchChoiceDelegate.java
mpellicer/sakai
cbccc0a810107050f284e7213183b2ecdfc1dd3a
[ "ECL-2.0" ]
216
2016-06-23T14:02:32.000Z
2021-08-31T17:11:24.000Z
mneme-project/mneme/mneme-impl/impl/src/java/org/etudes/mneme/impl/FormatMatchChoiceDelegate.java
mpellicer/sakai
cbccc0a810107050f284e7213183b2ecdfc1dd3a
[ "ECL-2.0" ]
4
2016-07-26T07:23:42.000Z
2020-10-07T12:21:53.000Z
27.407407
104
0.651014
6,451
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2008 Etudes, Inc. * * Portions completed before September 1, 2008 * Copyright (c) 2007, 2008 The Regents of the University of Michigan & Foothill College, ETUDES Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.etudes.mneme.impl; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.etudes.ambrosia.api.Context; import org.etudes.ambrosia.util.FormatDelegateImpl; import org.etudes.mneme.api.Question; import org.etudes.mneme.api.TypeSpecificQuestion; import org.etudes.mneme.impl.MatchQuestionImpl.MatchQuestionPair; /** * The "FormatMatchChoice" format delegate for the mneme tool. */ public class FormatMatchChoiceDelegate extends FormatDelegateImpl { /** Our log. */ private static Log M_log = LogFactory.getLog(FormatMatchChoiceDelegate.class); /** * Shutdown. */ public void destroy() { M_log.info("destroy()"); } /** * {@inheritDoc} */ public String format(Context context, Object value) { // value is the choice id if (value == null) return null; if (!(value instanceof String)) return value.toString(); String choiceId = (String) value; // "question" is the Question Object o = context.get("question"); if (o == null) return value.toString(); if (!(o instanceof Question)) return value.toString(); Question question = (Question) o; TypeSpecificQuestion tsq = question.getTypeSpecificQuestion(); if (!(tsq instanceof MatchQuestionImpl)) return value.toString(); MatchQuestionImpl plugin = (MatchQuestionImpl) tsq; List<MatchQuestionPair> pairs = plugin.getPairs(); if ((plugin.distractor != null) && (plugin.distractor.getChoiceId().equals(choiceId))) { return plugin.distractor.getChoice(); } for (MatchQuestionPair pair : pairs) { if (pair.getChoiceId().equals(choiceId)) { return pair.getChoice(); } } return null; } /** * {@inheritDoc} */ public Object formatObject(Context context, Object value) { return value; } /** * Final initialization, once all dependencies are set. */ public void init() { super.init(); M_log.info("init()"); } }
3e0f2d3003ca8772f0362130cd22c79072ae5d76
580
java
Java
storage/db/src/main/java/org/artifactory/storage/db/aql/parser/elements/high/level/domain/sensitive/CriteriaEqualsValuePropertyElement.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
3
2016-01-21T11:49:08.000Z
2018-12-11T21:02:11.000Z
storage/db/src/main/java/org/artifactory/storage/db/aql/parser/elements/high/level/domain/sensitive/CriteriaEqualsValuePropertyElement.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
null
null
null
storage/db/src/main/java/org/artifactory/storage/db/aql/parser/elements/high/level/domain/sensitive/CriteriaEqualsValuePropertyElement.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
5
2015-12-08T10:22:21.000Z
2021-06-15T16:14:00.000Z
26.363636
97
0.743103
6,452
package org.artifactory.storage.db.aql.parser.elements.high.level.domain.sensitive; import org.artifactory.storage.db.aql.parser.elements.ParserElement; import static org.artifactory.storage.db.aql.parser.AqlParser.*; /** * @author Gidi Shabat */ public class CriteriaEqualsValuePropertyElement extends DomainSensitiveParserElement { @Override protected ParserElement init() { return forward(quotes, provide(DynamicStar.class), quotes, colon, quotes, value, quotes); } @Override public boolean isVisibleInResult() { return true; } }
3e0f2d700abd03ccd37a85f380198110cad4fad6
28,753
java
Java
src/test/java/com/floragunn/searchguard/IndexIntegrationTests.java
raoshihong/search-guard
51e22e3ea7185a06e2fb59d17a67be176e464b67
[ "Apache-2.0" ]
1
2018-07-03T07:53:54.000Z
2018-07-03T07:53:54.000Z
src/test/java/com/floragunn/searchguard/IndexIntegrationTests.java
raoshihong/search-guard
51e22e3ea7185a06e2fb59d17a67be176e464b67
[ "Apache-2.0" ]
null
null
null
src/test/java/com/floragunn/searchguard/IndexIntegrationTests.java
raoshihong/search-guard
51e22e3ea7185a06e2fb59d17a67be176e464b67
[ "Apache-2.0" ]
null
null
null
63.332599
211
0.648732
6,453
/* * Copyright 2015-2017 floragunn GmbH * * 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.floragunn.searchguard; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import org.apache.http.HttpStatus; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest.AliasActions; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.support.WriteRequest.RefreshPolicy; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.InvalidIndexNameException; import org.elasticsearch.indices.InvalidTypeNameException; import org.junit.Assert; import org.junit.Test; import com.floragunn.searchguard.support.ConfigConstants; import com.floragunn.searchguard.test.DynamicSgConfig; import com.floragunn.searchguard.test.SingleClusterTest; import com.floragunn.searchguard.test.helper.rest.RestHelper; import com.floragunn.searchguard.test.helper.rest.RestHelper.HttpResponse; public class IndexIntegrationTests extends SingleClusterTest { @Test public void testComposite() throws Exception { setup(Settings.EMPTY, new DynamicSgConfig().setSgConfig("sg_composite_config.yml").setSgRoles("sg_roles_composite.yml"), Settings.EMPTY, true); final RestHelper rh = nonSslRestHelper(); try (TransportClient tc = getInternalTransportClient()) { tc.index(new IndexRequest("starfleet").type("ships").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("klingonempire").type("ships").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("public").type("legends").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); } String msearchBody = "{\"index\":\"starfleet\", \"type\":\"ships\", \"ignore_unavailable\": true}"+System.lineSeparator()+ "{\"size\":10, \"query\":{\"bool\":{\"must\":{\"match_all\":{}}}}}"+System.lineSeparator()+ "{\"index\":\"klingonempire\", \"type\":\"ships\", \"ignore_unavailable\": true}"+System.lineSeparator()+ "{\"size\":10, \"query\":{\"bool\":{\"must\":{\"match_all\":{}}}}}"+System.lineSeparator()+ "{\"index\":\"public\", \"ignore_unavailable\": true}"+System.lineSeparator()+ "{\"size\":10, \"query\":{\"bool\":{\"must\":{\"match_all\":{}}}}}"+System.lineSeparator(); HttpResponse resc = rh.executePostRequest("_msearch", msearchBody, encodeBasicHeader("worf", "worf")); Assert.assertEquals(200, resc.getStatusCode()); Assert.assertTrue(resc.getBody(), resc.getBody().contains("\"_index\":\"klingonempire\"")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("hits")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("no permissions for [indices:data/read/search]")); } @Test public void testBulkShards() throws Exception { setup(Settings.EMPTY, new DynamicSgConfig().setSgRoles("sg_roles_bs.yml"), Settings.EMPTY, true); final RestHelper rh = nonSslRestHelper(); try (TransportClient tc = getInternalTransportClient()) { //create indices and mapping upfront tc.index(new IndexRequest("test").type("type1").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"field2\":\"init\"}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("lorem").type("type1").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"field2\":\"init\"}", XContentType.JSON)).actionGet(); } String bulkBody = "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }"+System.lineSeparator()+ "{ \"field2\" : \"value1\" }" +System.lineSeparator()+ "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"2\" } }"+System.lineSeparator()+ "{ \"field2\" : \"value2\" }"+System.lineSeparator()+ "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"3\" } }"+System.lineSeparator()+ "{ \"field2\" : \"value2\" }"+System.lineSeparator()+ "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"4\" } }"+System.lineSeparator()+ "{ \"field2\" : \"value2\" }"+System.lineSeparator()+ "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"5\" } }"+System.lineSeparator()+ "{ \"field2\" : \"value2\" }"+System.lineSeparator()+ "{ \"index\" : { \"_index\" : \"lorem\", \"_type\" : \"type1\", \"_id\" : \"1\" } }"+System.lineSeparator()+ "{ \"field2\" : \"value2\" }"+System.lineSeparator()+ "{ \"index\" : { \"_index\" : \"lorem\", \"_type\" : \"type1\", \"_id\" : \"2\" } }"+System.lineSeparator()+ "{ \"field2\" : \"value2\" }"+System.lineSeparator()+ "{ \"index\" : { \"_index\" : \"lorem\", \"_type\" : \"type1\", \"_id\" : \"3\" } }"+System.lineSeparator()+ "{ \"field2\" : \"value2\" }"+System.lineSeparator()+ "{ \"index\" : { \"_index\" : \"lorem\", \"_type\" : \"type1\", \"_id\" : \"4\" } }"+System.lineSeparator()+ "{ \"field2\" : \"value2\" }"+System.lineSeparator()+ "{ \"index\" : { \"_index\" : \"lorem\", \"_type\" : \"type1\", \"_id\" : \"5\" } }"+System.lineSeparator()+ "{ \"field2\" : \"value2\" }"+System.lineSeparator()+ "{ \"delete\" : { \"_index\" : \"lorem\", \"_type\" : \"type1\", \"_id\" : \"5\" } }"+System.lineSeparator(); System.out.println("############ _bulk"); HttpResponse res = rh.executePostRequest("_bulk?refresh=true&pretty=true", bulkBody, encodeBasicHeader("worf", "worf")); System.out.println(res.getBody()); Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); Assert.assertTrue(res.getBody().contains("\"errors\" : true")); Assert.assertTrue(res.getBody().contains("\"status\" : 201")); Assert.assertTrue(res.getBody().contains("no permissions for")); System.out.println("############ check shards"); System.out.println(rh.executeGetRequest("_cat/shards?v", encodeBasicHeader("nagilum", "nagilum"))); } @Test public void testCreateIndex() throws Exception { setup(); RestHelper rh = nonSslRestHelper(); HttpResponse res; Assert.assertEquals("Unable to create index 'nag'", HttpStatus.SC_OK, rh.executePutRequest("nag1", null, encodeBasicHeader("nagilum", "nagilum")).getStatusCode()); Assert.assertEquals("Unable to create index 'starfleet_library'", HttpStatus.SC_OK, rh.executePutRequest("starfleet_library", null, encodeBasicHeader("nagilum", "nagilum")).getStatusCode()); clusterHelper.waitForCluster(ClusterHealthStatus.GREEN, TimeValue.timeValueSeconds(10), clusterInfo.numNodes); Assert.assertEquals("Unable to close index 'starfleet_library'", HttpStatus.SC_OK, rh.executePostRequest("starfleet_library/_close", null, encodeBasicHeader("nagilum", "nagilum")).getStatusCode()); Assert.assertEquals("Unable to open index 'starfleet_library'", HttpStatus.SC_OK, (res = rh.executePostRequest("starfleet_library/_open", null, encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()); Assert.assertTrue("open index 'starfleet_library' not acknowledged", res.getBody().contains("acknowledged")); Assert.assertFalse("open index 'starfleet_library' not acknowledged", res.getBody().contains("false")); clusterHelper.waitForCluster(ClusterHealthStatus.GREEN, TimeValue.timeValueSeconds(10), clusterInfo.numNodes); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, rh.executePutRequest("public", null, encodeBasicHeader("spock", "spock")).getStatusCode()); } @Test public void testFilteredAlias() throws Exception { setup(); try (TransportClient tc = getInternalTransportClient()) { tc.index(new IndexRequest("theindex").type("type1").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("otherindex").type("type1").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().alias("alias1").filter(QueryBuilders.termQuery("_type", "type1")).index("theindex"))).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().alias("alias2").filter(QueryBuilders.termQuery("_type", "type2")).index("theindex"))).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().alias("alias3").filter(QueryBuilders.termQuery("_type", "type2")).index("otherindex"))).actionGet(); } RestHelper rh = nonSslRestHelper(); //sg_user1 -> worf //sg_user2 -> picard HttpResponse resc = rh.executeGetRequest("alias*/_search", encodeBasicHeader("worf", "worf")); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); resc = rh.executeGetRequest("theindex/_search", encodeBasicHeader("nagilum", "nagilum")); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); resc = rh.executeGetRequest("alias3/_search", encodeBasicHeader("nagilum", "nagilum")); Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); resc = rh.executeGetRequest("_cat/indices", encodeBasicHeader("nagilum", "nagilum")); Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); } @Test public void testIndexTypeEvaluation() throws Exception { setup(); try (TransportClient tc = getInternalTransportClient()) { tc.index(new IndexRequest("foo1").type("bar").id("1").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("foo2").type("bar").id("2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":2}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("foo").type("baz").id("3").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":3}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("fooba").type("z").id("4").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":4}", XContentType.JSON)).actionGet(); try { tc.index(new IndexRequest("x#a").type("xxx").id("4a").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":4}", XContentType.JSON)).actionGet(); Assert.fail("Indexname can contain #"); } catch (InvalidIndexNameException e) { //expected } try { tc.index(new IndexRequest("xa").type("x#a").id("4a").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":4}", XContentType.JSON)).actionGet(); Assert.fail("Typename can contain #"); } catch (InvalidTypeNameException e) { //expected } } RestHelper rh = nonSslRestHelper(); HttpResponse resc = rh.executeGetRequest("/foo1/bar/_search?pretty", encodeBasicHeader("baz", "worf")); Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); Assert.assertTrue(resc.getBody().contains("\"content\" : 1")); resc = rh.executeGetRequest("/foo2/bar/_search?pretty", encodeBasicHeader("baz", "worf")); Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); Assert.assertTrue(resc.getBody().contains("\"content\" : 2")); resc = rh.executeGetRequest("/foo/baz/_search?pretty", encodeBasicHeader("baz", "worf")); Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); Assert.assertTrue(resc.getBody().contains("\"content\" : 3")); resc = rh.executeGetRequest("/fooba/z/_search?pretty", encodeBasicHeader("baz", "worf")); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); resc = rh.executeGetRequest("/foo1/bar/1?pretty", encodeBasicHeader("baz", "worf")); Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); Assert.assertTrue(resc.getBody().contains("\"found\" : true")); Assert.assertTrue(resc.getBody().contains("\"content\" : 1")); resc = rh.executeGetRequest("/foo2/bar/2?pretty", encodeBasicHeader("baz", "worf")); Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); Assert.assertTrue(resc.getBody().contains("\"content\" : 2")); Assert.assertTrue(resc.getBody().contains("\"found\" : true")); resc = rh.executeGetRequest("/foo/baz/3?pretty", encodeBasicHeader("baz", "worf")); Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); Assert.assertTrue(resc.getBody().contains("\"content\" : 3")); Assert.assertTrue(resc.getBody().contains("\"found\" : true")); resc = rh.executeGetRequest("/fooba/z/4?pretty", encodeBasicHeader("baz", "worf")); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); resc = rh.executeGetRequest("/foo*/_search?pretty", encodeBasicHeader("baz", "worf")); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); resc = rh.executeGetRequest("/foo*,-fooba/bar/_search?pretty", encodeBasicHeader("baz", "worf")); Assert.assertEquals(200, resc.getStatusCode()); Assert.assertTrue(resc.getBody().contains("\"content\" : 1")); Assert.assertTrue(resc.getBody().contains("\"content\" : 2")); } @Test public void testIndices() throws Exception { setup(); try (TransportClient tc = getInternalTransportClient()) { tc.index(new IndexRequest("nopermindex").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-1").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-2").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-3").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-4").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); SimpleDateFormat sdf = new SimpleDateFormat("YYYY.MM.dd"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String date = sdf.format(new Date()); tc.index(new IndexRequest("logstash-"+date).type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); } RestHelper rh = nonSslRestHelper(); HttpResponse res = null; Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("/logstash-1/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); //nonexistent index with permissions Assert.assertEquals(HttpStatus.SC_NOT_FOUND, (res = rh.executeGetRequest("/logstash-nonex/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); //existent index without permissions Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/nopermindex/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); //nonexistent index without permissions Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/does-not-exist-and-no-perm/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); //existent index with permissions Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("/logstash-1/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); //nonexistent index with failed login Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, (res = rh.executeGetRequest("/logstash-nonex/_search", encodeBasicHeader("nouser", "nosuer"))).getStatusCode()); //nonexistent index with no login Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, (res = rh.executeGetRequest("/logstash-nonex/_search")).getStatusCode()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/_all/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/*/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/nopermindex,logstash-1,nonexist/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/logstash-1,nonexist/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/nonexist/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("/%3Clogstash-%7Bnow%2Fd%7D%3E/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/%3Cnonex-%7Bnow%2Fd%7D%3E/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("/%3Clogstash-%7Bnow%2Fd%7D%3E,logstash-*/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("/%3Clogstash-%7Bnow%2Fd%7D%3E,logstash-1/_search", encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_CREATED, (res = rh.executePutRequest("/logstash-b/logs/1", "{}",encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executePutRequest("/%3Clogstash-cnew-%7Bnow%2Fd%7D%3E", "{}",encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_CREATED, (res = rh.executePutRequest("/%3Clogstash-new-%7Bnow%2Fd%7D%3E/logs/1", "{}",encodeBasicHeader("logstash", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("/_cat/indices?v" ,encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()); System.out.println(res.getBody()); Assert.assertTrue(res.getBody().contains("logstash-b")); Assert.assertTrue(res.getBody().contains("logstash-new-20")); Assert.assertTrue(res.getBody().contains("logstash-cnew-20")); Assert.assertFalse(res.getBody().contains("<")); } @Test public void testAliases() throws Exception { final Settings settings = Settings.builder() .put(ConfigConstants.SEARCHGUARD_ROLES_MAPPING_RESOLUTION, "BOTH") .build(); setup(settings); try (TransportClient tc = getInternalTransportClient()) { tc.index(new IndexRequest("nopermindex").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-1").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-2").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-3").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-4").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-5").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-del").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("logstash-del-ok").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); String date = new SimpleDateFormat("YYYY.MM.dd").format(new Date()); tc.index(new IndexRequest("logstash-"+date).type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices("nopermindex").alias("nopermalias"))).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices("searchguard").alias("mysgi"))).actionGet(); } RestHelper rh = nonSslRestHelper(); HttpResponse res = null; Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executePostRequest("/mysgi/sg", "{}",encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("/mysgi/_search?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()); assertContains(res, "*\"hits\" : {*\"total\" : 0,*\"hits\" : [ ]*"); System.out.println("#### add alias to allowed index"); Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executePutRequest("/logstash-1/_alias/alog1", "",encodeBasicHeader("aliasmngt", "nagilum"))).getStatusCode()); System.out.println("#### add alias to not existing (no perm)"); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executePutRequest("/nonexitent/_alias/alnp", "",encodeBasicHeader("aliasmngt", "nagilum"))).getStatusCode()); System.out.println("#### add alias to not existing (with perm)"); Assert.assertEquals(HttpStatus.SC_NOT_FOUND, (res = rh.executePutRequest("/logstash-nonex/_alias/alnp", "",encodeBasicHeader("aliasmngt", "nagilum"))).getStatusCode()); System.out.println("#### add alias to not allowed index"); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executePutRequest("/nopermindex/_alias/alnp", "",encodeBasicHeader("aliasmngt", "nagilum"))).getStatusCode()); String aliasRemoveIndex = "{"+ "\"actions\" : ["+ "{ \"add\": { \"index\": \"logstash-del-ok\", \"alias\": \"logstash-del\" } },"+ "{ \"remove_index\": { \"index\": \"logstash-del\" } } "+ "]"+ "}"; System.out.println("#### remove_index"); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executePostRequest("/_aliases", aliasRemoveIndex,encodeBasicHeader("aliasmngt", "nagilum"))).getStatusCode()); System.out.println("#### get alias for permitted index"); Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("/logstash-1/_alias/alog1", encodeBasicHeader("aliasmngt", "nagilum"))).getStatusCode()); System.out.println("#### get alias for all indices"); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/_alias/alog1", encodeBasicHeader("aliasmngt", "nagilum"))).getStatusCode()); System.out.println("#### get alias no perm"); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("/_alias/nopermalias", encodeBasicHeader("aliasmngt", "nagilum"))).getStatusCode()); String alias = "{"+ "\"aliases\": {"+ "\"alias1\": {}"+ "}"+ "}"; System.out.println("#### create alias along with index"); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executePutRequest("/beats-withalias", alias,encodeBasicHeader("aliasmngt", "nagilum"))).getStatusCode()); } @Test public void testAliasResolution() throws Exception { final Settings settings = Settings.builder() .build(); setup(settings); final RestHelper rh = nonSslRestHelper(); try (TransportClient tc = getInternalTransportClient()) { tc.index(new IndexRequest("concreteindex-1").type("doc").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices("concreteindex-1").alias("calias-1"))).actionGet(); tc.index(new IndexRequest(".kibana-6").type("doc").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices(".kibana-6").alias(".kibana"))).actionGet(); } Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("calias-1/_search?pretty", encodeBasicHeader("aliastest", "nagilum")).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("calias-*/_search?pretty", encodeBasicHeader("aliastest", "nagilum")).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("*kibana/_search?pretty", encodeBasicHeader("aliastest", "nagilum")).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest(".ki*ana/_search?pretty", encodeBasicHeader("aliastest", "nagilum")).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest(".kibana/_search?pretty", encodeBasicHeader("aliastest", "nagilum")).getStatusCode()); } @Test public void testCCSIndexResolve() throws Exception { setup(); final RestHelper rh = nonSslRestHelper(); try (TransportClient tc = getInternalTransportClient()) { tc.index(new IndexRequest(".abc-6").type("logs").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); } HttpResponse res = rh.executeGetRequest("/*:.abc-6,.abc-6/_search", encodeBasicHeader("ccsresolv", "nagilum")); Assert.assertTrue(res.getBody(),res.getBody().contains("\"content\":1")); Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); } }
3e0f2d923ae639152fd2ac9fcce027013b6c970f
1,425
java
Java
src/main/java/com/user/model/entities/Theme.java
VictorHachard/user-api
8ffa2ebe25e9c838119e7e56687ade108f99b55a
[ "MIT" ]
null
null
null
src/main/java/com/user/model/entities/Theme.java
VictorHachard/user-api
8ffa2ebe25e9c838119e7e56687ade108f99b55a
[ "MIT" ]
null
null
null
src/main/java/com/user/model/entities/Theme.java
VictorHachard/user-api
8ffa2ebe25e9c838119e7e56687ade108f99b55a
[ "MIT" ]
null
null
null
16.011236
54
0.712982
6,454
package com.user.model.entities; import com.user.model.entities.commons.AbstractEntity; import lombok.*; import lombok.experimental.FieldDefaults; import javax.persistence.Column; import javax.persistence.Entity; /** * This class represents theme. */ @Entity // Lombok @ToString @NoArgsConstructor @FieldDefaults(level = AccessLevel.PRIVATE) @Getter @Setter public class Theme extends AbstractEntity { @Column(name = "name_a") String name; @Column String imageUrl; @Column() boolean active; @Column(name = "order_a") int order; @Column String primaryColor; @Column String secondaryColor; @Column String tertiaryColor; @Column String quaternaryColor; @Column String primaryTextColor; @Column String secondaryTextColor; @Column String primaryAlertSuccessColor; @Column String secondaryAlertSuccessColor; @Column String tertiaryAlertSuccessColor; @Column String primaryAlertWarningColor; @Column String secondaryAlertWarningColor; @Column String tertiaryAlertWarningColor; @Column String primaryAlertDangerColor; @Column String secondaryAlertDangerColor; @Column String tertiaryAlertDangerColor; @Column String primaryAlertPrimaryColor; @Column String secondaryAlertPrimaryColor; @Column String tertiaryAlertPrimaryColor; }
3e0f2db415a12d61bc65b459674f1f2d6ffe0c03
4,021
java
Java
reactor-core/src/main/java/reactor/alloc/ReferenceCountingAllocator.java
panzhiwei/reactor
38a37b4438f9a4e03d2232efbb1304b738857072
[ "Apache-2.0" ]
1
2018-10-10T13:04:28.000Z
2018-10-10T13:04:28.000Z
reactor-core/src/main/java/reactor/alloc/ReferenceCountingAllocator.java
panzhiwei/reactor
38a37b4438f9a4e03d2232efbb1304b738857072
[ "Apache-2.0" ]
null
null
null
reactor-core/src/main/java/reactor/alloc/ReferenceCountingAllocator.java
panzhiwei/reactor
38a37b4438f9a4e03d2232efbb1304b738857072
[ "Apache-2.0" ]
null
null
null
24.518293
112
0.676449
6,455
/* * Copyright (c) 2011-2014 Pivotal Software, 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 reactor.alloc; import reactor.function.Supplier; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.concurrent.locks.ReentrantLock; /** * An implementation of {@link reactor.alloc.Allocator} that uses reference counting to determine when an object * should * be recycled and placed back into the pool to be reused. * * @author Jon Brisbin * @since 1.1 */ public class ReferenceCountingAllocator<T extends Recyclable> implements Allocator<T> { private static final int DEFAULT_INITIAL_SIZE = 2048; private final ReentrantLock refLock = new ReentrantLock(); private final ReentrantLock leaseLock = new ReentrantLock(); private final ArrayList<Reference<T>> references = new ArrayList<Reference<T>>(); private final Supplier<T> factory; private volatile BitSet leaseMask; public ReferenceCountingAllocator(Supplier<T> factory) { this(DEFAULT_INITIAL_SIZE, factory); } public ReferenceCountingAllocator(int initialSize, Supplier<T> factory) { this.factory = factory; this.references.ensureCapacity(initialSize); this.leaseMask = new BitSet(initialSize); expand(initialSize); } @Override public Reference<T> allocate() { Reference<T> ref; int len = refCnt(); int next; leaseLock.lock(); try { next = leaseMask.nextClearBit(0); if (next >= len) { expand(len); } leaseMask.set(next); } finally { leaseLock.unlock(); } if (next < 0) { throw new RuntimeException("Allocator is exhausted."); } ref = references.get(next); if (null == ref) { // this reference has been nulled somehow. // that's not really critical, just replace it. refLock.lock(); try { ref = new ReferenceCountingAllocatorReference<T>(factory.get(), next); references.set(next, ref); } finally { refLock.unlock(); } } ref.retain(); return ref; } @Override public List<Reference<T>> allocateBatch(int size) { List<Reference<T>> refs = new ArrayList<Reference<T>>(size); for (int i = 0; i < size; i++) { refs.add(allocate()); } return refs; } @Override public void release(List<Reference<T>> batch) { if (null != batch && !batch.isEmpty()) { for (Reference<T> ref : batch) { ref.release(); } } } private int refCnt() { refLock.lock(); try { return references.size(); } finally { refLock.unlock(); } } private void expand(int num) { refLock.lock(); try { int len = references.size(); int newLen = len + num; for (int i = len; i <= newLen; i++) { references.add(new ReferenceCountingAllocatorReference<T>(factory.get(), i)); } BitSet newLeaseMask = new BitSet(newLen); int leases = leaseMask.length(); for (int i = 0; i < leases; i++) { newLeaseMask.set(i, leaseMask.get(i)); } leaseMask = newLeaseMask; } finally { refLock.unlock(); } } private class ReferenceCountingAllocatorReference<T extends Recyclable> extends AbstractReference<T> { private final int bit; private ReferenceCountingAllocatorReference(T obj, int bit) { super(obj); this.bit = bit; } @Override public void release(int decr) { leaseLock.lock(); try { super.release(decr); if (getReferenceCount() < 1) { // There won't be contention to clear this leaseMask.clear(bit); } } finally { leaseLock.unlock(); } } } }
3e0f2ddccfecbab4ed705ba46523bddbe21b89fc
7,198
java
Java
misc/eu.hansolo.enzo/src/main/java/eu/hansolo/enzo/simpleindicator/skin/SimpleIndicatorSkin.java
dhakehurst/net.akehurst.application.framework.examples
ff622351f295cc578f0305f68ea8528b66f043a3
[ "Apache-2.0" ]
52
2015-04-27T20:43:28.000Z
2021-09-06T16:16:25.000Z
misc/eu.hansolo.enzo/src/main/java/eu/hansolo/enzo/simpleindicator/skin/SimpleIndicatorSkin.java
dhakehurst/net.akehurst.application.framework.examples
ff622351f295cc578f0305f68ea8528b66f043a3
[ "Apache-2.0" ]
5
2015-01-21T18:35:15.000Z
2019-06-21T09:14:21.000Z
misc/eu.hansolo.enzo/src/main/java/eu/hansolo/enzo/simpleindicator/skin/SimpleIndicatorSkin.java
dhakehurst/net.akehurst.application.framework.examples
ff622351f295cc578f0305f68ea8528b66f043a3
[ "Apache-2.0" ]
25
2015-04-08T17:34:23.000Z
2021-03-10T12:29:56.000Z
42.845238
148
0.644901
6,456
/* * Copyright (c) 2013 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.enzo.simpleindicator.skin; import eu.hansolo.enzo.simpleindicator.SimpleIndicator; import javafx.scene.control.Skin; import javafx.scene.control.SkinBase; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; /** * Created by * User: hansolo * Date: 06.03.12 * Time: 13:53 */ public class SimpleIndicatorSkin extends SkinBase<SimpleIndicator> implements Skin<SimpleIndicator> { private static final double PREFERRED_SIZE = 48; private static final double MINIMUM_SIZE = 16; private static final double MAXIMUM_SIZE = 1024; private double size; private Pane pane; private Region outerFrame; private Region innerFrame; private Region mainBack; private Region main; private Region highlight; // ******************** Constructors ************************************** public SimpleIndicatorSkin(final SimpleIndicator CONTROL) { super(CONTROL); pane = new Pane(); init(); initGraphics(); registerListeners(); } // ******************** Initialization ************************************ private void init() { if (Double.compare(getSkinnable().getPrefWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getPrefHeight(), 0.0) <= 0 || getSkinnable().getWidth() <= 0 || getSkinnable().getHeight() <= 0) { getSkinnable().setPrefSize(PREFERRED_SIZE, PREFERRED_SIZE); } if (Double.compare(getSkinnable().getMinWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getMinHeight(), 0.0) <= 0) { getSkinnable().setMinSize(MINIMUM_SIZE, MINIMUM_SIZE); } if (Double.compare(getSkinnable().getMaxWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getMaxHeight(), 0.0) <= 0) { getSkinnable().setMaxSize(MAXIMUM_SIZE, MAXIMUM_SIZE); } } private void initGraphics() { outerFrame = new Region(); outerFrame.getStyleClass().setAll("outer-frame"); innerFrame = new Region(); innerFrame.getStyleClass().setAll("inner-frame"); mainBack = new Region(); mainBack.getStyleClass().setAll("main-back"); main = new Region(); main.getStyleClass().setAll("main"); highlight = new Region(); highlight.getStyleClass().setAll("highlight"); pane.getChildren().setAll(outerFrame, innerFrame, mainBack, main, highlight); getChildren().setAll(pane); } private void registerListeners() { getSkinnable().widthProperty().addListener(observable -> handleControlPropertyChanged("RESIZE") ); getSkinnable().heightProperty().addListener(observable -> handleControlPropertyChanged("RESIZE") ); getSkinnable().indicatorStyleProperty().addListener(observable -> handleControlPropertyChanged("UPDATE") ); } // ******************** Methods ******************************************* protected void handleControlPropertyChanged(final String PROPERTY) { if ("RESIZE".equals(PROPERTY)) { resize(); } else if ("UPDATE".equals(PROPERTY)) { update(); } } @Override protected double computeMinWidth(final double HEIGHT, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { return super.computeMinWidth(Math.max(MINIMUM_SIZE, HEIGHT - TOP_INSET - BOTTOM_INSET), TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } @Override protected double computeMinHeight(final double WIDTH, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { return super.computeMinHeight(Math.max(MINIMUM_SIZE, WIDTH - LEFT_INSET - RIGHT_INSET), TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } @Override protected double computeMaxWidth(final double HEIGHT, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { return super.computeMaxWidth(Math.min(MAXIMUM_SIZE, HEIGHT - TOP_INSET - BOTTOM_INSET), TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } @Override protected double computeMaxHeight(final double WIDTH, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { return super.computeMaxHeight(Math.min(MAXIMUM_SIZE, WIDTH - LEFT_INSET - RIGHT_INSET), TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } @Override protected double computePrefWidth(final double HEIGHT, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { double prefHeight = PREFERRED_SIZE; if (HEIGHT != -1) { prefHeight = Math.max(0, HEIGHT - TOP_INSET - BOTTOM_INSET); } return super.computePrefWidth(prefHeight, TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } @Override protected double computePrefHeight(final double WIDTH, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { double prefWidth = PREFERRED_SIZE; if (WIDTH != -1) { prefWidth = Math.max(0, WIDTH - LEFT_INSET - RIGHT_INSET); } return super.computePrefHeight(prefWidth, TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } // ******************** Private Methods *********************************** private void update() { getSkinnable().getStyleClass().setAll("indicator", getSkinnable().getIndicatorStyle().CLASS); } private void resize() { size = getSkinnable().getWidth() < getSkinnable().getHeight() ? getSkinnable().getWidth() : getSkinnable().getHeight(); if (size > 0) { outerFrame.setPrefSize(size, size); innerFrame.setPrefSize(size * 0.8, size * 0.8); innerFrame.setTranslateX((size - innerFrame.getPrefWidth()) * 0.5); innerFrame.setTranslateY((size - innerFrame.getPrefHeight()) * 0.5); mainBack.setPrefSize(size * 0.76, size * 0.76); mainBack.setTranslateX((size - mainBack.getPrefWidth()) * 0.5); mainBack.setTranslateY((size - mainBack.getPrefHeight()) * 0.5); main.setPrefSize(size * 0.76, size * 0.76); main.setTranslateX((size - main.getPrefWidth()) * 0.5); main.setTranslateY((size - main.getPrefHeight()) * 0.5); highlight.setPrefSize(size * 0.52, size * 0.30); highlight.setTranslateX((size - highlight.getPrefWidth()) * 0.5); highlight.setTranslateY((size - highlight.getPrefHeight()) * 0.2); } } }
3e0f2de1fff8da13ac376866000aa20c85955b68
431
java
Java
mobile_app1/module1255/src/main/java/module1255packageJava0/Foo46.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
70
2021-01-22T16:48:06.000Z
2022-02-16T10:37:33.000Z
mobile_app1/module1255/src/main/java/module1255packageJava0/Foo46.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
16
2021-01-22T20:52:52.000Z
2021-08-09T17:51:24.000Z
mobile_app1/module1255/src/main/java/module1255packageJava0/Foo46.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
5
2021-01-26T13:53:49.000Z
2021-08-11T20:10:57.000Z
11.342105
46
0.566125
6,457
package module1255packageJava0; import java.lang.Integer; public class Foo46 { Integer int0; Integer int1; public void foo0() { new module1255packageJava0.Foo45().foo6(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } public void foo5() { foo4(); } public void foo6() { foo5(); } }
3e0f2e4aeff5d266f44c2167931588581ecc77bf
146
java
Java
app/src/main/java/com/gmail/tarekmabdallah91/news/views/sections/SpinnerOnItemClickedListener.java
tarekmabdallah91/NewsFeedapp
e154d17634344ac91446196b13fce7c80e728f51
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/gmail/tarekmabdallah91/news/views/sections/SpinnerOnItemClickedListener.java
tarekmabdallah91/NewsFeedapp
e154d17634344ac91446196b13fce7c80e728f51
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/gmail/tarekmabdallah91/news/views/sections/SpinnerOnItemClickedListener.java
tarekmabdallah91/NewsFeedapp
e154d17634344ac91446196b13fce7c80e728f51
[ "Apache-2.0" ]
null
null
null
18.25
55
0.808219
6,458
package com.gmail.tarekmabdallah91.news.views.sections; public interface SpinnerOnItemClickedListener { void onSelectItem(int position); }
3e0f2f0f5283d25caf6dc214a5373e89fffd4cea
8,061
java
Java
squall-core/src/main/java/ch/epfl/data/squall/thetajoin/matrix_assignment/ContentInsensitiveMatrixAssignment.java
epfldata/squall
9b5c9f14ead726e7e7e6c452598f488657a5be18
[ "Apache-2.0" ]
169
2015-01-05T02:03:49.000Z
2021-11-29T13:59:28.000Z
squall-core/src/main/java/ch/epfl/data/squall/thetajoin/matrix_assignment/ContentInsensitiveMatrixAssignment.java
avitorovic/squall
9b5c9f14ead726e7e7e6c452598f488657a5be18
[ "Apache-2.0" ]
16
2015-03-29T11:15:17.000Z
2017-04-01T20:49:38.000Z
squall-core/src/main/java/ch/epfl/data/squall/thetajoin/matrix_assignment/ContentInsensitiveMatrixAssignment.java
avitorovic/squall
9b5c9f14ead726e7e7e6c452598f488657a5be18
[ "Apache-2.0" ]
75
2015-01-05T10:38:06.000Z
2020-03-19T09:07:42.000Z
30.078358
86
0.627714
6,459
/* * Copyright (c) 2011-2015 EPFL DATA Laboratory * Copyright (c) 2014-2015 The Squall Collaboration (see NOTICE) * * 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 ch.epfl.data.squall.thetajoin.matrix_assignment; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.log4j.Logger; /** * @author ElSeidy This class performs region assignments to Matrix. i.e. Given * the dimensions (S & T) & number of reducers (r), tries to find an * efficient mapping of regions, that would be equally divided among * "All" the reducers r. - More specifically find the dimension of the * regions (reducers) matrix. - The regions are NOT essentially squares * !! We are not following the same procedure of the Theta-join paper, * for fallacies. */ public class ContentInsensitiveMatrixAssignment<KeyType> implements Serializable, MatrixAssignment { public static boolean isDataMigrator(int row, int col, Dimension RowOrColumn, int taskID) { final int[][] regionsMatrix = new int[row][col]; for (int i = 0; i < row; i++) { final int ID = i * col; for (int j = 0; j < col; j++) regionsMatrix[i][j] = ID + j; } if (RowOrColumn == Dimension.ROW) { for (int i = 0; i < row; i++) if (regionsMatrix[i][0] == taskID) return true; } else if (RowOrColumn == Dimension.COLUMN) for (int i = 0; i < col; i++) if (regionsMatrix[0][i] == taskID) return true; return false; } public static void main(String[] args) { final ContentInsensitiveMatrixAssignment x = new ContentInsensitiveMatrixAssignment( 13, 7, 1, -1); LOG.info(x._r_S); LOG.info(x._r_T); final ArrayList<Integer> indices = x.getRegionIDs(Dimension.COLUMN); for (int i = 0; i < indices.size(); i++) LOG.info("Value: " + indices.get(i)); } /** * */ private static final long serialVersionUID = 1L; private static Logger LOG = Logger .getLogger(ContentInsensitiveMatrixAssignment.class); private long _sizeS, _sizeT; // dimensions of data.. row, column // respectively. private final int _r; // practically speaking usually a relatively small // value! public int _r_S = -1, _r_T = -1; // dimensions of reducers.. row, column // respectively. private int[][] regionsMatrix; private Random _rand; public ContentInsensitiveMatrixAssignment(int r_S, int r_T, long randomSeed) { if (randomSeed == -1) _rand = new Random(); else _rand = new Random(randomSeed); _r_S = r_S; _r_T = r_T; _r = _r_S * _r_T; createRegionMatrix(); } public ContentInsensitiveMatrixAssignment(long sizeS, long sizeT, int r, long randomSeed) { if (randomSeed == -1) _rand = new Random(); else _rand = new Random(randomSeed); _sizeS = sizeS; _sizeT = sizeT; _r = r; compute(); createRegionMatrix(); } public ContentInsensitiveMatrixAssignment(String dim, long randomSeed) { if (randomSeed == -1) _rand = new Random(); else _rand = new Random(randomSeed); final String[] dimensions = dim.split("-"); _r_S = Integer.parseInt(new String(dimensions[0])); _r_T = Integer.parseInt(new String(dimensions[1])); _r = _r_S * _r_T; createRegionMatrix(); } /** * This function computes the regions dimensionality */ private void compute() { /* * 1) IF S,T divisible by the number of r (squares) //Theorem 1 */ final double denominator = Math.sqrt((double) _sizeS * _sizeT / _r); if ((_sizeS % denominator) == 0 && (_sizeT % denominator) == 0) { _r_S = (int) (_sizeS / denominator); _r_T = (int) (_sizeT / denominator); } /* * 2)Else .. we find the best partition as rectangles !! */ else { int rs, rt = -1; // Find the prime factors of the _r. final List<Integer> primeFactors = Utilities.primeFactors(_r); // Get the Power Set, and iterate over it... for (final List<Integer> set : Utilities.powerSet(primeFactors)) { rs = Utilities.multiply(set); if ((_r % rs) != 0) // Assert rt should be integer LOG.info("errrrrrrrrrrrrrrrrrrrrrrrr"); rt = _r / rs; // always assign more reducers to the bigger data if ((_sizeS > _sizeT && rs < rt) || (_sizeS < _sizeT && rs > rt)) continue; if (_r_S == -1) { _r_S = rs; _r_T = rt; } else evaluateMinDifference(rs, rt); } } } /** * This function computes creates the regions Matrix */ private void createRegionMatrix() { regionsMatrix = new int[_r_S][_r_T]; for (int i = 0; i < _r_S; i++) { final int ID = i * _r_T; for (int j = 0; j < _r_T; j++) regionsMatrix[i][j] = ID + j; } } /** * This function evaluates rs,rt with the minimum difference with dimensions * S,T */ private void evaluateMinDifference(int rs, int rt) { final double ratio_S_T = (double) _sizeS / (double) _sizeT; final double ratio_rs_rt = (double) rs / (double) rt; final double currentBestRatio_rs_rt = (double) _r_S / (double) _r_T; final double diff_rs_rt = Math.abs(ratio_S_T - ratio_rs_rt); final double diff_CurrentBest_rs_rt = Math.abs(ratio_S_T - currentBestRatio_rs_rt); if (diff_rs_rt < diff_CurrentBest_rs_rt) { _r_S = rs; _r_T = rt; } } public String getMappingDimensions() { return _r_S + "-" + _r_T; } public int getNumberOfWorkerColumns() { return _r_T; } public int getNumberOfWorkerRows() { return _r_S; } /** * This function gets the indices of regions corresponding to a uniformly * random chosen row/column index. * * @param ROW * or COLUMN * @return region indices */ @Override public ArrayList<Integer> getRegionIDs(Dimension RowOrColumn) { final ArrayList<Integer> regions = new ArrayList<Integer>(); if (RowOrColumn == Dimension.ROW) { // uniformly distributed !! final int randomIndex = _rand.nextInt(_r_S); // LOG.info("random: "+randomIndex); for (int i = 0; i < _r_T; i++) regions.add(regionsMatrix[randomIndex][i]); } else if (RowOrColumn == Dimension.COLUMN) { // uniformly distributed !! final int randomIndex = _rand.nextInt(_r_T); // LOG.info("random: "+randomIndex); for (int i = 0; i < _r_S; i++) regions.add(regionsMatrix[i][randomIndex]); } else LOG.info("ERROR not a possible index (row or column) assignment."); return regions; } @Override public ArrayList getRegionIDs(Dimension RowOrColumn, Object key) { throw new RuntimeException("This method is content-insenstive"); } /** * decides whether this taskID will emit data for data migration. * * @param RowOrColumn * @param int taskID * @return boolean */ public boolean isDataMigrator(Dimension RowOrColumn, int taskID) { if (RowOrColumn == Dimension.ROW) { for (int i = 0; i < _r_S; i++) if (regionsMatrix[i][0] == taskID) return true; } else if (RowOrColumn == Dimension.COLUMN) for (int i = 0; i < _r_T; i++) if (regionsMatrix[0][i] == taskID) return true; return false; } @Override public String toString() { return getMappingDimensions(); } }
3e0f2f2b08548fc8ef770aadfa404de59cf93514
4,473
java
Java
core/src/main/java/com/huawei/openstack4j/openstack/manila/domain/ManilaShareNetworkCreate.java
wuchen-huawei/huaweicloud-sdk-java
1e4b76c737d23c5d5df59405015ea136651b6fc1
[ "Apache-2.0" ]
46
2018-09-30T08:55:22.000Z
2021-11-07T20:02:57.000Z
core/src/main/java/com/huawei/openstack4j/openstack/manila/domain/ManilaShareNetworkCreate.java
wuchen-huawei/huaweicloud-sdk-java
1e4b76c737d23c5d5df59405015ea136651b6fc1
[ "Apache-2.0" ]
18
2019-04-11T02:37:30.000Z
2021-04-30T09:03:38.000Z
core/src/main/java/com/huawei/openstack4j/openstack/manila/domain/ManilaShareNetworkCreate.java
wuchen-huawei/huaweicloud-sdk-java
1e4b76c737d23c5d5df59405015ea136651b6fc1
[ "Apache-2.0" ]
42
2019-01-22T07:54:00.000Z
2021-12-13T01:14:14.000Z
32.649635
98
0.571205
6,460
/******************************************************************************* * Copyright 2016 ContainX and OpenStack4j * * 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.huawei.openstack4j.openstack.manila.domain; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; import com.huawei.openstack4j.model.manila.ShareNetworkCreate; import com.huawei.openstack4j.model.manila.builder.ShareNetworkCreateBuilder; /** * Object used to create new share networks. * * @author Daniel Gonzalez Nothnagel */ @JsonRootName("share_network") public class ManilaShareNetworkCreate implements ShareNetworkCreate { @JsonProperty("neutron_net_id") private String neutronNetId; @JsonProperty("neutron_subnet_id") private String neutronSubnetId; @JsonProperty("nova_net_id") private String novaNetId; private String name; private String description; private ManilaShareNetworkCreate() {} /** * {@inheritDoc} */ @Override public String getNeutronNetId() { return neutronNetId; } /** * {@inheritDoc} */ @Override public String getNeutronSubnetId() { return neutronSubnetId; } /** * {@inheritDoc} */ @Override public String getNovaNetId() { return novaNetId; } /** * {@inheritDoc} */ @Override public String getName() { return name; } /** * {@inheritDoc} */ @Override public String getDescription() { return description; } public static ShareNetworkCreateBuilder builder() { return new ShareNetworkCreateConcreteBuilder(); } @Override public ShareNetworkCreateBuilder toBuilder() { return new ShareNetworkCreateConcreteBuilder(this); } public static class ShareNetworkCreateConcreteBuilder implements ShareNetworkCreateBuilder { ManilaShareNetworkCreate shareNetworkCreate; ShareNetworkCreateConcreteBuilder() { this(new ManilaShareNetworkCreate()); } ShareNetworkCreateConcreteBuilder(ManilaShareNetworkCreate shareNetworkCreate) { this.shareNetworkCreate = shareNetworkCreate; } @Override public ShareNetworkCreateBuilder neutronNet(String neutronNetId, String neutronSubnetId) { shareNetworkCreate.neutronNetId = neutronNetId; shareNetworkCreate.neutronSubnetId = neutronSubnetId; return this; } @Override public ShareNetworkCreateBuilder novaNet(String novaNetId) { shareNetworkCreate.novaNetId = novaNetId; return this; } @Override public ShareNetworkCreateBuilder name(String name) { shareNetworkCreate.name = name; return this; } @Override public ShareNetworkCreateBuilder description(String description) { shareNetworkCreate.description = description; return this; } @Override public ShareNetworkCreate build() { return shareNetworkCreate; } @Override public ShareNetworkCreateBuilder from(ShareNetworkCreate in) { shareNetworkCreate = (ManilaShareNetworkCreate) in; return this; } } }
3e0f2f84379509314785bcefb4c9c0c7018a8c1b
118
java
Java
android/src/main/java/boaventura/com/devel/br/flutteraudioquery/sortingtypes/StorageType.java
proghjy/flutter_audio_query
8abe812db5a38658c04d166a76b327a24227967a
[ "MIT" ]
null
null
null
android/src/main/java/boaventura/com/devel/br/flutteraudioquery/sortingtypes/StorageType.java
proghjy/flutter_audio_query
8abe812db5a38658c04d166a76b327a24227967a
[ "MIT" ]
null
null
null
android/src/main/java/boaventura/com/devel/br/flutteraudioquery/sortingtypes/StorageType.java
proghjy/flutter_audio_query
8abe812db5a38658c04d166a76b327a24227967a
[ "MIT" ]
null
null
null
19.666667
63
0.779661
6,461
package boaventura.com.devel.br.flutteraudioquery.sortingtypes; public enum StorageType { DEFAULT, INTERNAL }
3e0f2fbdba85b08af91e421179b6afa3da2765e8
898
java
Java
yoma-tools/src/main/java/com/github/yoma/tools/config/MultipartConfig.java
msh01/yoma
50b46bccf3e0b2885d451badbeeacf56d4b82777
[ "Apache-2.0" ]
164
2021-03-13T14:53:56.000Z
2022-03-29T01:59:38.000Z
yoma-tools/src/main/java/com/github/yoma/tools/config/MultipartConfig.java
chenguomeng/yoma
50b46bccf3e0b2885d451badbeeacf56d4b82777
[ "Apache-2.0" ]
1
2021-05-11T16:06:05.000Z
2022-03-26T08:10:32.000Z
yoma-tools/src/main/java/com/github/yoma/tools/config/MultipartConfig.java
chenguomeng/yoma
50b46bccf3e0b2885d451badbeeacf56d4b82777
[ "Apache-2.0" ]
12
2021-04-09T04:57:04.000Z
2022-03-29T01:59:39.000Z
28.0625
81
0.706013
6,462
package com.github.yoma.tools.config; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.MultipartConfigElement; import java.io.File; /** * @date 2018-12-28 * @author https://blog.csdn.net/llibin1024530411/article/details/79474953 */ @Configuration public class MultipartConfig { /** * 文件上传临时路径 */ @Bean MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); String location = System.getProperty("user.home") + "/.eladmin/file/tmp"; File tmpFile = new File(location); if (!tmpFile.exists()) { tmpFile.mkdirs(); } factory.setLocation(location); return factory.createMultipartConfig(); } }
3e0f316f21ccc67ddefd7e77b5808f5b8e215dc6
2,566
java
Java
hw12/bookStore/BookUI.java
FYLSunghwan/2020_ITE2037
9654274afa7a03e506a203551b28af5bc6930477
[ "MIT" ]
null
null
null
hw12/bookStore/BookUI.java
FYLSunghwan/2020_ITE2037
9654274afa7a03e506a203551b28af5bc6930477
[ "MIT" ]
null
null
null
hw12/bookStore/BookUI.java
FYLSunghwan/2020_ITE2037
9654274afa7a03e506a203551b28af5bc6930477
[ "MIT" ]
null
null
null
36.140845
71
0.399844
6,463
package bookStore; import java.util.Scanner; public class BookUI { public static void main(String[] args) { BookService serv = new BookService(); Scanner scanner = new Scanner(System.in); Boolean sw = true; while(sw) { System.out.println(""); System.out.println("작업할 내용을 선택하세요."); System.out.println("1. 새책입고"); System.out.println("2. 책재고량 증가"); System.out.println("3. 책구매"); System.out.println("4. 책조회"); System.out.println("5. 책 전체보기"); System.out.println("6. 종료"); System.out.print("UI>"); int cmd = scanner.nextInt(); scanner.nextLine(); String name; int money, disRate; double price; switch(cmd) { case 1: System.out.println("입고할 책 이름:"); name = scanner.nextLine(); System.out.println("가격"); price = scanner.nextInt(); System.out.println("중고인가요? Y=1/N=0"); cmd =scanner.nextInt(); if(cmd>0) { System.out.println("할인률(%)를 입력하세요."); disRate = scanner.nextInt(); serv.importBook(name, price, disRate); } else { serv.importBook(name, price); } break; case 2: System.out.println("증가할 책 이름:"); name = scanner.nextLine(); serv.incBook(name); break; case 3: System.out.println("구매할 책 이름:"); name = scanner.nextLine(); System.out.println("현재 돈:"); money = scanner.nextInt(); price = serv.buyBook(name); System.out.printf("남은 돈: %d\n",(int)(money-price)); break; case 4: System.out.println("조회할 책 이름:"); name = scanner.nextLine(); serv.searchBook(name); break; case 5: serv.listBook(); break; case 6: sw=false; break; default: System.out.println("UI>Invalid input."); break; } } } }
3e0f33a90d0b59d4c24f5a38ba86b34005623cac
3,879
java
Java
sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/EventDataPropertyName.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
1,350
2015-01-17T05:22:05.000Z
2022-03-29T21:00:37.000Z
sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/EventDataPropertyName.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
16,834
2015-01-07T02:19:09.000Z
2022-03-31T23:29:10.000Z
sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/EventDataPropertyName.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
1,586
2015-01-02T01:50:28.000Z
2022-03-31T11:25:34.000Z
45.635294
104
0.758185
6,464
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.monitor.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for EventDataPropertyName. */ public final class EventDataPropertyName extends ExpandableStringEnum<EventDataPropertyName> { /** Static value "authorization" for EventDataPropertyName. */ public static final EventDataPropertyName AUTHORIZATION = fromString("authorization"); /** Static value "claims" for EventDataPropertyName. */ public static final EventDataPropertyName CLAIMS = fromString("claims"); /** Static value "correlationId" for EventDataPropertyName. */ public static final EventDataPropertyName CORRELATIONID = fromString("correlationId"); /** Static value "description" for EventDataPropertyName. */ public static final EventDataPropertyName DESCRIPTION = fromString("description"); /** Static value "eventDataId" for EventDataPropertyName. */ public static final EventDataPropertyName EVENTDATAID = fromString("eventDataId"); /** Static value "eventName" for EventDataPropertyName. */ public static final EventDataPropertyName EVENTNAME = fromString("eventName"); /** Static value "eventTimestamp" for EventDataPropertyName. */ public static final EventDataPropertyName EVENTTIMESTAMP = fromString("eventTimestamp"); /** Static value "httpRequest" for EventDataPropertyName. */ public static final EventDataPropertyName HTTPREQUEST = fromString("httpRequest"); /** Static value "level" for EventDataPropertyName. */ public static final EventDataPropertyName LEVEL = fromString("level"); /** Static value "operationId" for EventDataPropertyName. */ public static final EventDataPropertyName OPERATIONID = fromString("operationId"); /** Static value "operationName" for EventDataPropertyName. */ public static final EventDataPropertyName OPERATIONNAME = fromString("operationName"); /** Static value "properties" for EventDataPropertyName. */ public static final EventDataPropertyName PROPERTIES = fromString("properties"); /** Static value "resourceGroupName" for EventDataPropertyName. */ public static final EventDataPropertyName RESOURCEGROUPNAME = fromString("resourceGroupName"); /** Static value "resourceProviderName" for EventDataPropertyName. */ public static final EventDataPropertyName RESOURCEPROVIDERNAME = fromString("resourceProviderName"); /** Static value "resourceId" for EventDataPropertyName. */ public static final EventDataPropertyName RESOURCEID = fromString("resourceId"); /** Static value "status" for EventDataPropertyName. */ public static final EventDataPropertyName STATUS = fromString("status"); /** Static value "submissionTimestamp" for EventDataPropertyName. */ public static final EventDataPropertyName SUBMISSIONTIMESTAMP = fromString("submissionTimestamp"); /** Static value "subStatus" for EventDataPropertyName. */ public static final EventDataPropertyName SUBSTATUS = fromString("subStatus"); /** Static value "subscriptionId" for EventDataPropertyName. */ public static final EventDataPropertyName SUBSCRIPTIONID = fromString("subscriptionId"); /** * Creates or finds a EventDataPropertyName from its string representation. * * @param name a name to look for * @return the corresponding WebhookAction */ @JsonCreator public static EventDataPropertyName fromString(String name) { return fromString(name, EventDataPropertyName.class); } /** @return known WebhookAction values */ public static Collection<EventDataPropertyName> values() { return values(EventDataPropertyName.class); } }
3e0f34562f6b9503d46f79c8b150dde651d6f9aa
3,699
java
Java
libiec61850/tools/model_generator/src/com/libiec61850/scl/types/DataObjectType.java
IOT-DSA/dslink-c-iec61850
ecb38fc79f8a877e1c9ac73f5bad9d49452a2b63
[ "Apache-2.0" ]
3
2016-12-10T09:55:25.000Z
2021-05-20T02:22:14.000Z
model_input_generator/src/com/libiec61850/scl/types/DataObjectType.java
robidev/iec61850_inputs
5c88dd7d6cf95590e7f0106104fdbebe0aa740ec
[ "Apache-2.0" ]
3
2020-04-16T12:32:51.000Z
2020-07-07T07:00:49.000Z
libiec61850/tools/model_generator/src/com/libiec61850/scl/types/DataObjectType.java
IOT-DSA/dslink-c-iec61850
ecb38fc79f8a877e1c9ac73f5bad9d49452a2b63
[ "Apache-2.0" ]
2
2017-06-18T15:19:40.000Z
2018-04-16T09:56:35.000Z
29.125984
89
0.699649
6,465
package com.libiec61850.scl.types; /* * Copyright 2013, 2014 Michael Zillgith * * This file is part of libIEC61850. * * libIEC61850 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * libIEC61850 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with libIEC61850. If not, see <http://www.gnu.org/licenses/>. * * See COPYING file for the complete license text. */ import java.util.LinkedList; import java.util.List; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.libiec61850.scl.DataAttributeDefinition; import com.libiec61850.scl.DataObjectDefinition; import com.libiec61850.scl.ParserUtils; import com.libiec61850.scl.SclParserException; public class DataObjectType extends SclType { private String cdc = null; private List<DataAttributeDefinition> dataAttributes = null; private List<DataObjectDefinition> subDataObjects = null; private DataAttributeDefinition getDataAttributeByName(String name) { for (DataAttributeDefinition dad : dataAttributes) { if (dad.getName().equals(name)) return dad; } return null; } private DataObjectDefinition getDataObjectByName(String name) { for (DataObjectDefinition dod : subDataObjects) { if (dod.getName().equals(name)) return dod; } return null; } public DataObjectType(Node xmlNode) throws SclParserException { super(xmlNode); this.cdc = ParserUtils.parseAttribute(xmlNode, "cdc"); if (this.cdc == null) throw new SclParserException(xmlNode, "cdc is missing!"); NodeList elementNodes = xmlNode.getChildNodes(); if (elementNodes != null) { this.dataAttributes = new LinkedList<DataAttributeDefinition>(); this.subDataObjects = new LinkedList<DataObjectDefinition>(); for (int i = 0; i < elementNodes.getLength(); i++) { Node elementNode = elementNodes.item(i); if (elementNode.getNodeName().equals("DA")) { DataAttributeDefinition dad = new DataAttributeDefinition(elementNode); DataAttributeDefinition otherDefinition = getDataAttributeByName(dad.getName()); if (otherDefinition != null) { if (otherDefinition.getFc() == dad.getFc()) throw new SclParserException(xmlNode, "DO type definition contains multiple elements of name \"" + dad.getName() + "\""); } if (getDataObjectByName(dad.getName()) != null) { throw new SclParserException(xmlNode, "DO type definition contains multiple elements of name \"" + dad.getName() + "\""); } dataAttributes.add(dad); } else if (elementNode.getNodeName().equals("SDO")) { DataObjectDefinition dod = new DataObjectDefinition(elementNode); if ((getDataAttributeByName(dod.getName()) != null) || (getDataObjectByName(dod.getName()) != null)) throw new SclParserException(xmlNode, "DO type definition contains multiple elements of name \"" + dod.getName() + "\""); this.subDataObjects.add(dod); } } } } public String getCdc() { return cdc; } public List<DataAttributeDefinition> getDataAttributes() { return dataAttributes; } public List<DataObjectDefinition> getSubDataObjects() { return subDataObjects; } }
3e0f35ea12aca1a2d613949fb7bbfbfe87f4d385
1,099
java
Java
gulj-app-blog/src/main/java/com/gulj/app/blog/web/aop/AppAuthAspect.java
gulijian/joingu
b4de6e03e2cccea6f5fc1ab632ceee17871be497
[ "MIT" ]
2
2017-06-16T09:31:39.000Z
2017-06-16T09:42:15.000Z
gulj-app-blog/src/main/java/com/gulj/app/blog/web/aop/AppAuthAspect.java
gulijian/joingu
b4de6e03e2cccea6f5fc1ab632ceee17871be497
[ "MIT" ]
null
null
null
gulj-app-blog/src/main/java/com/gulj/app/blog/web/aop/AppAuthAspect.java
gulijian/joingu
b4de6e03e2cccea6f5fc1ab632ceee17871be497
[ "MIT" ]
null
null
null
27.475
86
0.753412
6,466
package com.gulj.app.blog.web.aop; import com.alibaba.dubbo.config.annotation.Reference; import com.gulj.app.blog.api.service.BlogCategoryService; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * @author gulj * @create 2017-05-18 下午2:23 **/ @SuppressWarnings("ALL") @Aspect @Component public class AppAuthAspect extends AuthBaseAspect{ private final static Logger logger = LoggerFactory.getLogger(AppAuthAspect.class); @Reference(version = "1.0.0", timeout = 1200000) private BlogCategoryService blogCategoryService; @Pointcut("execution(public * com.gulj.app.blog.web.controller..*.*(..))") public void apiAuth() { } @Around("apiAuth()") public Object doAround(ProceedingJoinPoint point) throws Throwable { System.out.println(blogCategoryService); return process(point,blogCategoryService); } }
3e0f3624585e3940600e7b2cf81ccc07950b093f
821
java
Java
src/main/java/ch/so/agi/search/jsf/Theme.java
edigonzales/sogis-portal-search-jsf
454a513b6e8cea6952024f39b4004ecb74282c4c
[ "MIT" ]
null
null
null
src/main/java/ch/so/agi/search/jsf/Theme.java
edigonzales/sogis-portal-search-jsf
454a513b6e8cea6952024f39b4004ecb74282c4c
[ "MIT" ]
null
null
null
src/main/java/ch/so/agi/search/jsf/Theme.java
edigonzales/sogis-portal-search-jsf
454a513b6e8cea6952024f39b4004ecb74282c4c
[ "MIT" ]
null
null
null
17.847826
59
0.557856
6,467
package ch.so.agi.search.jsf; public class Theme { private int id; private String displayName; private String name; public Theme() {} public Theme(int id, String displayName, String name) { this.id = id; this.displayName = displayName; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return name; } }
3e0f385a19f26cca195ee38e9cbdbb7cf8a6a03a
857
java
Java
src/android/TestApi.java
navroopsinghsandhu/GnssClockPlugin
5cf6091450b09ad6111473106846ec3722821839
[ "MIT" ]
3
2021-10-19T17:30:01.000Z
2021-11-03T07:28:16.000Z
src/android/TestApi.java
navroopsinghsandhu/GnssClockPlugin
5cf6091450b09ad6111473106846ec3722821839
[ "MIT" ]
null
null
null
src/android/TestApi.java
navroopsinghsandhu/GnssClockPlugin
5cf6091450b09ad6111473106846ec3722821839
[ "MIT" ]
null
null
null
37.26087
73
0.798133
6,468
package com.navroopsingh.cordova.plugin; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PACKAGE; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates an API is exposed for use by CTS. * <p> * These APIs are not guaranteed to remain consistent release-to-release, * and are not for use by apps linking against the Android SDK. * </p> * * @hide */ @Target({TYPE, FIELD, METHOD, CONSTRUCTOR, ANNOTATION_TYPE, PACKAGE}) @Retention(RetentionPolicy.SOURCE) public @interface TestApi { }
3e0f38b511d244bb5bf01a930c2066b1fe8f94f9
8,340
java
Java
rocketmq-streams-state/src/main/java/org/apache/rocketmq/streams/state/kv/rocksdb/RocksdbState.java
keren123/rocketmq-streams.
fe3cc4e2015aeeb7b5ecc784828a27bfd403dae3
[ "Apache-2.0" ]
106
2021-07-13T13:09:03.000Z
2022-03-30T12:30:24.000Z
rocketmq-streams-state/src/main/java/org/apache/rocketmq/streams/state/kv/rocksdb/RocksdbState.java
keren123/rocketmq-streams.
fe3cc4e2015aeeb7b5ecc784828a27bfd403dae3
[ "Apache-2.0" ]
55
2021-08-02T07:53:48.000Z
2022-03-22T02:57:26.000Z
rocketmq-streams-state/src/main/java/org/apache/rocketmq/streams/state/kv/rocksdb/RocksdbState.java
keren123/rocketmq-streams.
fe3cc4e2015aeeb7b5ecc784828a27bfd403dae3
[ "Apache-2.0" ]
55
2021-07-22T01:39:17.000Z
2022-03-30T14:32:12.000Z
31.471698
109
0.592326
6,469
/* * 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.rocketmq.streams.state.kv.rocksdb; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.lang3.tuple.Pair; import org.apache.rocketmq.streams.common.utils.CollectionUtil; import org.apache.rocketmq.streams.common.utils.StringUtil; import org.apache.rocketmq.streams.state.LruState; import org.apache.rocketmq.streams.state.kv.IKvState; import org.rocksdb.ReadOptions; import org.rocksdb.RocksDBException; import org.rocksdb.RocksIterator; import org.rocksdb.WriteBatch; import org.rocksdb.WriteOptions; import static org.apache.rocketmq.streams.state.kv.rocksdb.RocksDBOperator.UTF8; /** * kv state based rocksdb * * @author arthur.liang */ public class RocksdbState implements IKvState<String, String> { private static RocksDBOperator operator = new RocksDBOperator(); private final LruState<String> cache = new LruState<>(100, ""); private final static Byte SIGN = 1; @Override public String get(String key) { try { return getValueFromByte(operator.getInstance().get(getKeyBytes(key))); } catch (Exception e) { return null; } } @Override public Map<String, String> getAll(List<String> keys) { if (CollectionUtil.isEmpty(keys)) { return new HashMap<>(4); } List<byte[]> keyByteList = new ArrayList<>(); List<String> keyStrList = new ArrayList<>(); for (String key : keys) { keyByteList.add(getKeyBytes(key)); keyStrList.add(key); } try { Map<String, String> resultMap = new HashMap<>(keys.size()); Map<byte[], byte[]> map = operator.getInstance().multiGet(keyByteList); Iterator<Map.Entry<byte[], byte[]>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<byte[], byte[]> entry = it.next(); String key = getValueFromByte(entry.getKey()); String value = getValueFromByte(entry.getValue()); resultMap.put(key, value); } return resultMap; } catch (RocksDBException e) { throw new RuntimeException("failed in getting all from rocksdb!", e); } } @Override public String put(String key, String value) { Map<String, String> map = new HashMap<String, String>(4) {{ put(key, value); }}; putAll(map); return null; } @Override public String putIfAbsent(String key, String value) { if (cache.search(key) > 0) { return null; } put(key, value); cache.add(key); return null; } @Override public void putAll(Map<? extends String, ? extends String> map) { if (map == null) { return; } try { WriteBatch writeBatch = new WriteBatch(); Iterator<? extends Map.Entry<? extends String, ? extends String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<? extends String, ? extends String> entry = it.next(); String key = entry.getKey(); String value = entry.getValue(); writeBatch.put(key.getBytes(UTF8), value.getBytes(UTF8)); } WriteOptions writeOptions = new WriteOptions(); writeOptions.setSync(false); writeOptions.setDisableWAL(true); operator.getInstance().write(writeOptions, writeBatch); writeBatch.close(); writeOptions.close(); } catch (Exception e) { throw new RuntimeException("failed in putting all into rocksdb!", e); } } @Override public String remove(String key) { try { operator.getInstance().delete(getKeyBytes(key)); } catch (RocksDBException e) { throw new RuntimeException("failed in removing all from rocksdb! " + key, e); } return null; } @Override public void removeAll(List<String> keys) { for (String key : keys) { try { operator.getInstance().delete(getKeyBytes(key)); } catch (RocksDBException e) { throw new RuntimeException("failed in removing all from rocksdb! " + key, e); } } } @Override public void clear() { } @Override public Iterator<String> keyIterator() { return null; } @Override public Iterator<Map.Entry<String, String>> entryIterator() { return null; } @Override public Iterator<Map.Entry<String, String>> entryIterator(String prefix) { return new RocksDBIterator(prefix); } /** * 把key转化成byte * * @param key * @return */ protected byte[] getKeyBytes(String key) { try { if (StringUtil.isEmpty(key)) { return null; } return key.getBytes(UTF8); } catch (UnsupportedEncodingException e) { throw new RuntimeException("failed in getting byte[] from key! " + key, e); } } /** * 把byte转化成值 * * @param bytes * @return */ protected static String getValueFromByte(byte[] bytes) { try { return new String(bytes, UTF8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static class RocksDBIterator implements Iterator<Map.Entry<String, String>> { protected AtomicBoolean hasInit = new AtomicBoolean(false); private ReadOptions readOptions = new ReadOptions(); private RocksIterator iter; protected String keyPrefix; public RocksDBIterator(String keyPrefix) { readOptions.setPrefixSameAsStart(true).setTotalOrderSeek(true); iter = operator.getInstance().newIterator(readOptions); this.keyPrefix = keyPrefix; } @Override public boolean hasNext() { if (hasInit.compareAndSet(false, true)) { iter.seek(keyPrefix.getBytes()); } return iter.isValid(); } @Override public Map.Entry<String, String> next() { String key = new String(iter.key()); if (!key.startsWith(keyPrefix)) { return null; } String value = getValueFromByte(iter.value()); iter.next(); return new Element(key, value); } } private static class Element implements Map.Entry<String, String> { private Pair<String, String> pair; private Element() { } public Element(String key, String value) { pair = Pair.of(key, value); } @Override public String getKey() { if (pair != null) { return pair.getKey(); } return null; } @Override public String getValue() { if (pair != null) { return pair.getRight(); } return null; } @Override public String setValue(String value) { if (pair != null) { String old = pair.getRight(); pair.setValue(value); return old; } return null; } } }
3e0f3af48d80cc815534347e2bb6a2c249872507
264
java
Java
tms/tms.core/src/main/java/com/chinaway/tms/utils/MyConstant.java
uwitec/tms
3303d96326dc0b8c344f12cec7ff493ec145deb3
[ "Apache-2.0" ]
9
2017-06-22T06:09:37.000Z
2020-04-30T08:15:01.000Z
tms/tms.core/src/main/java/com/chinaway/tms/utils/MyConstant.java
uwitec/tms
3303d96326dc0b8c344f12cec7ff493ec145deb3
[ "Apache-2.0" ]
1
2017-11-23T08:05:03.000Z
2017-11-23T08:05:03.000Z
tms/tms.core/src/main/java/com/chinaway/tms/utils/MyConstant.java
zhangbangpu/tms
826d4e965f6c6e93c56d8abc332f530bc98f5c0d
[ "Apache-2.0" ]
9
2017-01-08T06:10:54.000Z
2019-05-28T01:57:48.000Z
14.666667
45
0.640152
6,470
package com.chinaway.tms.utils; /** * 常量类 * @author shu * */ public class MyConstant { /**状态:可用*/ public static final String ENABLE ="1"; /**状态:不可用*/ public static final String DISABLE ="0"; /**状态:不可用*/ public static final String ORDER_START ="2"; }
3e0f3c244914216f6a32f0657dd90e319ff1dcdc
7,117
java
Java
core/src/com/darkhouse/gdefence/Level/Ability/Spell/EchoSmash.java
mrDarkHouse/GDefenceBeta
29e1100458edd290a8082b7bbd49ff2f89b16cca
[ "Apache-2.0" ]
7
2016-09-23T07:56:38.000Z
2021-03-18T23:06:34.000Z
core/src/com/darkhouse/gdefence/Level/Ability/Spell/EchoSmash.java
mrDarkHouse/GDefenceBeta
29e1100458edd290a8082b7bbd49ff2f89b16cca
[ "Apache-2.0" ]
38
2016-09-26T17:24:17.000Z
2018-03-24T12:44:10.000Z
core/src/com/darkhouse/gdefence/Level/Ability/Spell/EchoSmash.java
mrDarkHouse/GDefenceBeta
29e1100458edd290a8082b7bbd49ff2f89b16cca
[ "Apache-2.0" ]
1
2016-09-23T07:53:50.000Z
2016-09-23T07:53:50.000Z
37.457895
141
0.612196
6,471
package com.darkhouse.gdefence.Level.Ability.Spell; import com.badlogic.gdx.utils.Array; import com.darkhouse.gdefence.GDefence; import com.darkhouse.gdefence.Helpers.AssetLoader; import com.darkhouse.gdefence.Helpers.FontLoader; import com.darkhouse.gdefence.InventorySystem.inventory.Item; import com.darkhouse.gdefence.InventorySystem.inventory.ItemEnum; import com.darkhouse.gdefence.Level.Ability.Tools.DamageType; import com.darkhouse.gdefence.Level.Ability.Tools.Effect; import com.darkhouse.gdefence.Level.Ability.Tower.Ability; import com.darkhouse.gdefence.Level.Mob.Mob; import com.darkhouse.gdefence.Model.Effectable; import com.darkhouse.gdefence.Objects.SpellObject; import com.darkhouse.gdefence.User; import java.util.concurrent.atomic.AtomicReference; public class EchoSmash extends Spell{ public static class P extends SpellObject implements IAoe{ private AtomicReference<Integer> dmg; private AtomicReference<Float> stunDuration; private G g; private S s; private AtomicReference<Integer> aoe; public P(int energyCost, float cooldown, int dmg, float stunDuration, int aoe, G grader) { super(150, "echoSmash", energyCost, cooldown, grader.gemCap, Mob.class); this.dmg = new AtomicReference<Integer>(dmg); this.stunDuration = new AtomicReference<Float>(stunDuration); this.aoe = new AtomicReference<Integer>(aoe); this.g = grader; this.s = new S(dmg, stunDuration, aoe); // AssetLoader l = GDefence.getInstance().assetLoader; // gemBoost[0] = new BoostInteger(this.dmg, grader.dmgUp, l.getWord("echoSmashGrade1"), // true, BoostInteger.IntegerGradeFieldType.NONE); // gemBoost[1] = new BoostFloat(this.stunDuration, grader.stunDurationUp, l.getWord("echoSmashGrade2"), // true, BoostFloat.FloatGradeFieldType.TIME); // gemBoost[2] = new BoostInteger(this.aoe, grader.aoeUp, l.getWord("echoSmashGrade3"), // true, BoostInteger.IntegerGradeFieldType.NONE); initBoosts(GDefence.getInstance().assetLoader); } @Override public void flush() { this.dmg = new AtomicReference<Integer>(s.dmg); this.stunDuration = new AtomicReference<Float>(s.stunDuration); this.aoe = new AtomicReference<Integer>(s.aoe); initBoosts(GDefence.getInstance().assetLoader); } @Override protected void initBoosts(AssetLoader l) { gemBoost[0] = new BoostInteger(this.dmg, g.dmgUp, l.getWord("echoSmashGrade1"), true, BoostInteger.IntegerGradeFieldType.NONE); gemBoost[1] = new BoostFloat(this.stunDuration, g.stunDurationUp, l.getWord("echoSmashGrade2"), true, BoostFloat.FloatGradeFieldType.TIME); gemBoost[2] = new BoostInteger(this.aoe, g.aoeUp, l.getWord("echoSmashGrade3"), true, BoostInteger.IntegerGradeFieldType.NONE); } @Override public int getAoe() { return aoe.get(); } @Override protected String getChildTooltip() { AssetLoader l = GDefence.getInstance().assetLoader; return l.getWord("echoSmashTooltip1") + System.getProperty("line.separator") + l.getWord("echoSmashTooltip2") + System.getProperty("line.separator") + "(" + (FontLoader.colorString(dmg.get().toString(), User.GEM_TYPE.BLACK) + l.getWord("echoSmashTooltip3")) + " " + l.getWord("echoSmashTooltip4") + ") " + System.getProperty("line.separator") + l.getWord("echoSmashTooltip5") + " " + FontLoader.colorString(stunDuration.get().toString(), User.GEM_TYPE.GREEN) + " " + l.getWord("echoSmashTooltip6"); } @Override public Array<Class<? extends Ability.AbilityPrototype>> getAbilitiesToSaveOnCraft() { return null; } // @Override // public String getSaveCode() { // return super.getSaveCode() + ";" + dmg + ";" + stunDuration + ";" + g.dmgUp + ";" + g.stunDurationUp + ";" + g.aoeUp; // } @Override public Spell createSpell() { return new EchoSmash(this); } @Override public Ability.AbilityPrototype copy() { // AssetLoader l = GDefence.getInstance().assetLoader; // gemBoost[0] = new BoostInteger(this.dmg, g.dmgUp, l.getWord("echoSmashGrade1"), // true, BoostInteger.IntegerGradeFieldType.NONE); // gemBoost[1] = new BoostFloat(this.stunDuration, g.stunDurationUp, l.getWord("echoSmashGrade2"), // true, BoostFloat.FloatGradeFieldType.TIME); // gemBoost[2] = new BoostInteger(this.aoe, g.aoeUp, l.getWord("echoSmashGrade3"), // true, BoostInteger.IntegerGradeFieldType.NONE); return this; } @Override public int[] exp2nextLevel() { return new int[]{230, 780, 1550, 2250, 6000, 8000}; } @Override public Item getPrototype() { return ItemEnum.Spell.EchoSmash; } } public static class G extends Ability.AbilityGrader{ private int dmgUp; private float stunDurationUp; private int aoeUp; public G(int dmgUp, float stunDurationUp, int aoeUp, int[] gemCap) { super(gemCap); this.dmgUp = dmgUp; this.stunDurationUp = stunDurationUp; this.aoeUp = aoeUp; } } private static class S extends Ability.AbilitySaverStat{ private int dmg; private float stunDuration; private int aoe; public S(int dmg, float stunDuration, int aoe) { this.dmg = dmg; this.stunDuration = stunDuration; this.aoe = aoe; } } public class EchoSmashStun extends Effect<Mob>{ public EchoSmashStun(float duration) { super(false, true, duration, "bash"); } @Override public void apply() { owner.setState(Mob.State.stunned); } @Override public void dispell() { if(owner.getState() == Mob.State.stunned) owner.setState(Mob.State.normal); super.dispell(); } @Override public void act(float delta) { super.act(delta); addExp(delta * 2f); } } private int dmg; private float duration; public EchoSmash(P prototype) { super(prototype); this.dmg = prototype.dmg.get(); this.duration = prototype.stunDuration.get(); } @Override public void use(Array<? extends Effectable> targets) { int d = dmg*targets.size; for (Effectable m:targets){ hitMob(((Mob) m), DamageType.Magic, d); // getPrototype().addExp(d/2f); m.addEffect(new EchoSmashStun(duration).setOwner(((Mob) m))); } } }
3e0f3caa013d0515f491bc7fd7cb454822501eeb
17,631
java
Java
src/main/java/it/unimi/dsi/fastutil/bytes/AbstractByteList.java
LibertyLand/fastutil-lite
9b0dde4b5b8376d92b739ef918fe7a1a7edc1b0c
[ "Apache-2.0" ]
10
2016-04-04T20:11:26.000Z
2021-02-02T11:33:27.000Z
src/main/java/it/unimi/dsi/fastutil/bytes/AbstractByteList.java
LibertyLand/fastutil-lite
9b0dde4b5b8376d92b739ef918fe7a1a7edc1b0c
[ "Apache-2.0" ]
7
2018-10-24T06:42:51.000Z
2021-03-18T14:27:24.000Z
src/main/java/it/unimi/dsi/fastutil/bytes/AbstractByteList.java
LibertyLand/fastutil-lite
9b0dde4b5b8376d92b739ef918fe7a1a7edc1b0c
[ "Apache-2.0" ]
10
2016-12-05T18:56:12.000Z
2021-01-19T09:23:45.000Z
32.710575
164
0.662696
6,472
/* * Copyright (C) 2002-2017 Sebastiano Vigna * * 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 it.unimi.dsi.fastutil.bytes; import java.util.List; import java.util.Iterator; import java.util.ListIterator; import java.util.Collection; import java.util.NoSuchElementException; /** An abstract class providing basic methods for lists implementing a type-specific list interface. * * <p>As an additional bonus, this class implements on top of the list operations a type-specific stack. */ public abstract class AbstractByteList extends AbstractByteCollection implements ByteList , ByteStack { protected AbstractByteList() {} /** Ensures that the given index is nonnegative and not greater than the list size. * * @param index an index. * @throws IndexOutOfBoundsException if the given index is negative or greater than the list size. */ protected void ensureIndex(final int index) { if (index < 0) throw new IndexOutOfBoundsException("Index (" + index + ") is negative"); if (index > size()) throw new IndexOutOfBoundsException("Index (" + index + ") is greater than list size (" + (size()) + ")"); } /** Ensures that the given index is nonnegative and smaller than the list size. * * @param index an index. * @throws IndexOutOfBoundsException if the given index is negative or not smaller than the list size. */ protected void ensureRestrictedIndex(final int index) { if (index < 0) throw new IndexOutOfBoundsException("Index (" + index + ") is negative"); if (index >= size()) throw new IndexOutOfBoundsException("Index (" + index + ") is greater than or equal to list size (" + (size()) + ")"); } /** {@inheritDoc} * * <p>This implementation always throws an {@link UnsupportedOperationException}. */ @Override public void add(final int index, final byte k) { throw new UnsupportedOperationException(); } /** {@inheritDoc} * * <p>This implementation delegates to the type-specific version of {@link List#add(int, Object)}. */ @Override public boolean add(final byte k) { add(size(), k); return true; } /** {@inheritDoc} * * <p>This implementation always throws an {@link UnsupportedOperationException}. */ @Override public byte removeByte(final int i) { throw new UnsupportedOperationException(); } /** {@inheritDoc} * * <p>This implementation always throws an {@link UnsupportedOperationException}. */ @Override public byte set(final int index, final byte k) { throw new UnsupportedOperationException(); } /** Adds all of the elements in the specified collection to this list (optional operation). */ @Override public boolean addAll(int index, final Collection<? extends Byte> c) { ensureIndex(index); final Iterator<? extends Byte> i = c.iterator(); final boolean retVal = i.hasNext(); while(i.hasNext()) add(index++, (i.next()).byteValue()); return retVal; } /** {@inheritDoc} * * <p>This implementation delegates to the type-specific version of {@link List#addAll(int, Collection)}. */ @Override public boolean addAll(final Collection<? extends Byte> c) { return addAll(size(), c); } /** {@inheritDoc} * * <p>This implementation delegates to {@link #listIterator()}. */ @Override public ByteListIterator iterator() { return listIterator(); } /** {@inheritDoc} * * <p>This implementation delegates to {@link #listIterator(int) listIterator(0)}. */ @Override public ByteListIterator listIterator() { return listIterator(0); } /** {@inheritDoc} * <p>This implementation is based on the random-access methods. */ @Override public ByteListIterator listIterator(final int index) { ensureIndex(index); return new ByteListIterator () { int pos = index, last = -1; @Override public boolean hasNext() { return pos < AbstractByteList.this.size(); } @Override public boolean hasPrevious() { return pos > 0; } @Override public byte nextByte() { if (! hasNext()) throw new NoSuchElementException(); return AbstractByteList.this.getByte(last = pos++); } @Override public byte previousByte() { if (! hasPrevious()) throw new NoSuchElementException(); return AbstractByteList.this.getByte(last = --pos); } @Override public int nextIndex() { return pos; } @Override public int previousIndex() { return pos - 1; } @Override public void add(final byte k) { AbstractByteList.this.add(pos++, k); last = -1; } @Override public void set(final byte k) { if (last == -1) throw new IllegalStateException(); AbstractByteList.this.set(last, k); } @Override public void remove() { if (last == -1) throw new IllegalStateException(); AbstractByteList.this.removeByte(last); /* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */ if (last < pos) pos--; last = -1; } }; } /** Returns true if this list contains the specified element. * <p>This implementation delegates to {@code indexOf()}. * @see List#contains(Object) */ @Override public boolean contains(final byte k) { return indexOf(k) >= 0; } @Override public int indexOf(final byte k) { final ByteListIterator i = listIterator(); byte e; while(i.hasNext()) { e = i.nextByte(); if (( (k) == (e) )) return i.previousIndex(); } return -1; } @Override public int lastIndexOf(final byte k) { ByteListIterator i = listIterator(size()); byte e; while(i.hasPrevious()) { e = i.previousByte(); if (( (k) == (e) )) return i.nextIndex(); } return -1; } @Override public void size(final int size) { int i = size(); if (size > i) while(i++ < size) add(((byte)0)); else while(i-- != size) removeByte(i); } @Override public ByteList subList(final int from, final int to) { ensureIndex(from); ensureIndex(to); if (from > to) throw new IndexOutOfBoundsException("Start index (" + from + ") is greater than end index (" + to + ")"); return new ByteSubList (this, from, to); } /** {@inheritDoc} * * <p>This is a trivial iterator-based implementation. It is expected that * implementations will override this method with a more optimized version. */ @Override public void removeElements(final int from, final int to) { ensureIndex(to); ByteListIterator i = listIterator(from); int n = to - from; if (n < 0) throw new IllegalArgumentException("Start index (" + from + ") is greater than end index (" + to + ")"); while(n-- != 0) { i.nextByte(); i.remove(); } } /** {@inheritDoc} * * <p>This is a trivial iterator-based implementation. It is expected that * implementations will override this method with a more optimized version. */ @Override public void addElements(int index, final byte a[], int offset, int length) { ensureIndex(index); if (offset < 0) throw new ArrayIndexOutOfBoundsException("Offset (" + offset + ") is negative"); if (offset + length > a.length) throw new ArrayIndexOutOfBoundsException("End index (" + (offset + length) + ") is greater than array length (" + a.length + ")"); while(length-- != 0) add(index++, a[offset++]); } /** {@inheritDoc} * * <p>This implementation delegates to the analogous method for array fragments. */ @Override public void addElements(final int index, final byte a[]) { addElements(index, a, 0, a.length); } /** {@inheritDoc} * * <p>This is a trivial iterator-based implementation. It is expected that * implementations will override this method with a more optimized version. */ @Override public void getElements(final int from, final byte a[], int offset, int length) { ByteListIterator i = listIterator(from); if (offset < 0) throw new ArrayIndexOutOfBoundsException("Offset (" + offset + ") is negative"); if (offset + length > a.length) throw new ArrayIndexOutOfBoundsException("End index (" + (offset + length) + ") is greater than array length (" + a.length + ")"); if (from + length > size()) throw new IndexOutOfBoundsException("End index (" + (from + length) + ") is greater than list size (" + size() + ")"); while(length-- != 0) a[offset++] = i.nextByte(); } /** {@inheritDoc} * <p>This implementation delegates to {@link #removeElements(int, int)}.*/ @Override public void clear() { removeElements(0, size()); } private boolean valEquals(final Object a, final Object b) { return a == null ? b == null : a.equals(b); } /** Returns the hash code for this list, which is identical to {@link java.util.List#hashCode()}. * * @return the hash code for this list. */ @Override public int hashCode() { ByteIterator i = iterator(); int h = 1, s = size(); while (s-- != 0) { byte k = i.nextByte(); h = 31 * h + (k); } return h; } @Override public boolean equals(final Object o) { if (o == this) return true; if (! (o instanceof List)) return false; final List<?> l = (List<?>)o; int s = size(); if (s != l.size()) return false; if (l instanceof ByteList) { final ByteListIterator i1 = listIterator(), i2 = ((ByteList )l).listIterator(); while(s-- != 0) if (i1.nextByte() != i2.nextByte()) return false; return true; } final ListIterator<?> i1 = listIterator(), i2 = l.listIterator(); while(s-- != 0) if (! valEquals(i1.next(), i2.next())) return false; return true; } /** Compares this list to another object. If the * argument is a {@link java.util.List}, this method performs a lexicographical comparison; otherwise, * it throws a {@code ClassCastException}. * * @param l a list. * @return if the argument is a {@link java.util.List}, a negative integer, * zero, or a positive integer as this list is lexicographically less than, equal * to, or greater than the argument. * @throws ClassCastException if the argument is not a list. */ @Override public int compareTo(final List<? extends Byte> l) { if (l == this) return 0; if (l instanceof ByteList) { final ByteListIterator i1 = listIterator(), i2 = ((ByteList )l).listIterator(); int r; byte e1, e2; while(i1.hasNext() && i2.hasNext()) { e1 = i1.nextByte(); e2 = i2.nextByte(); if ((r = ( Byte.compare((e1),(e2)) )) != 0) return r; } return i2.hasNext() ? -1 : (i1.hasNext() ? 1 : 0); } ListIterator<? extends Byte> i1 = listIterator(), i2 = l.listIterator(); int r; while(i1.hasNext() && i2.hasNext()) { if ((r = ((Comparable<? super Byte>)i1.next()).compareTo(i2.next())) != 0) return r; } return i2.hasNext() ? -1 : (i1.hasNext() ? 1 : 0); } @Override public void push(final byte o) { add(o); } @Override public byte popByte() { if (isEmpty()) throw new NoSuchElementException(); return removeByte(size() - 1); } @Override public byte topByte() { if (isEmpty()) throw new NoSuchElementException(); return getByte(size() - 1); } @Override public byte peekByte(final int i) { return getByte(size() - 1 - i); } /** Removes a single instance of the specified element from this collection, if it is present (optional operation). * <p>This implementation delegates to {@code indexOf()}. * @see List#remove(Object) */ @Override public boolean rem(final byte k) { int index = indexOf(k); if (index == -1) return false; removeByte(index); return true; } @Override public boolean addAll(int index, final ByteCollection c) { ensureIndex(index); final ByteIterator i = c.iterator(); final boolean retVal = i.hasNext(); while(i.hasNext()) add(index++, i.nextByte()); return retVal; } /** {@inheritDoc} * * <p>This implementation delegates to the type-specific version of {@link List#addAll(int, Collection)}. */ @Override public boolean addAll(final int index, final ByteList l) { return addAll(index, (ByteCollection)l); } /** {@inheritDoc} * * <p>This implementation delegates to the type-specific version of {@link List#addAll(int, Collection)}. */ @Override public boolean addAll(final ByteCollection c) { return addAll(size(), c); } /** {@inheritDoc} * * <p>This implementation delegates to the type-specific list version of {@link List#addAll(int, Collection)}. */ @Override public boolean addAll(final ByteList l) { return addAll(size(), l); } @Override public String toString() { final StringBuilder s = new StringBuilder(); final ByteIterator i = iterator(); int n = size(); byte k; boolean first = true; s.append("["); while(n-- != 0) { if (first) first = false; else s.append(", "); k = i.nextByte(); s.append(String.valueOf(k)); } s.append("]"); return s.toString(); } /** A class implementing a sublist view. */ public static class ByteSubList extends AbstractByteList implements java.io.Serializable { private static final long serialVersionUID = -7046029254386353129L; /** The list this sublist restricts. */ protected final ByteList l; /** Initial (inclusive) index of this sublist. */ protected final int from; /** Final (exclusive) index of this sublist. */ protected int to; public ByteSubList(final ByteList l, final int from, final int to) { this.l = l; this.from = from; this.to = to; } private boolean assertRange() { assert from <= l.size(); assert to <= l.size(); assert to >= from; return true; } @Override public boolean add(final byte k) { l.add(to, k); to++; assert assertRange(); return true; } @Override public void add(final int index, final byte k) { ensureIndex(index); l.add(from + index, k); to++; assert assertRange(); } @Override public boolean addAll(final int index, final Collection<? extends Byte> c) { ensureIndex(index); to += c.size(); return l.addAll(from + index, c); } @Override public byte getByte(final int index) { ensureRestrictedIndex(index); return l.getByte(from + index); } @Override public byte removeByte(final int index) { ensureRestrictedIndex(index); to--; return l.removeByte(from + index); } @Override public byte set(final int index, final byte k) { ensureRestrictedIndex(index); return l.set(from + index, k); } @Override public int size() { return to - from; } @Override public void getElements(final int from, final byte[] a, final int offset, final int length) { ensureIndex(from); if (from + length > size()) throw new IndexOutOfBoundsException("End index (" + from + length + ") is greater than list size (" + size() + ")"); l.getElements(this.from + from, a, offset, length); } @Override public void removeElements(final int from, final int to) { ensureIndex(from); ensureIndex(to); l.removeElements(this.from + from, this.from + to); this.to -= (to - from); assert assertRange(); } @Override public void addElements(int index, final byte a[], int offset, int length) { ensureIndex(index); l.addElements(this.from + index, a, offset, length); this.to += length; assert assertRange(); } @Override public ByteListIterator listIterator(final int index) { ensureIndex(index); return new ByteListIterator () { int pos = index, last = -1; @Override public boolean hasNext() { return pos < size(); } @Override public boolean hasPrevious() { return pos > 0; } @Override public byte nextByte() { if (! hasNext()) throw new NoSuchElementException(); return l.getByte(from + (last = pos++)); } @Override public byte previousByte() { if (! hasPrevious()) throw new NoSuchElementException(); return l.getByte(from + (last = --pos)); } @Override public int nextIndex() { return pos; } @Override public int previousIndex() { return pos - 1; } @Override public void add(byte k) { if (last == -1) throw new IllegalStateException(); ByteSubList.this.add(pos++, k); last = -1; assert assertRange(); } @Override public void set(byte k) { if (last == -1) throw new IllegalStateException(); ByteSubList.this.set(last, k); } @Override public void remove() { if (last == -1) throw new IllegalStateException(); ByteSubList.this.removeByte(last); /* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */ if (last < pos) pos--; last = -1; assert assertRange(); } }; } @Override public ByteList subList(final int from, final int to) { ensureIndex(from); ensureIndex(to); if (from > to) throw new IllegalArgumentException("Start index (" + from + ") is greater than end index (" + to + ")"); return new ByteSubList (this, from, to); } @Override public boolean rem(final byte k) { int index = indexOf(k); if (index == -1) return false; to--; l.removeByte(from + index); assert assertRange(); return true; } @Override public boolean addAll(final int index, final ByteCollection c) { ensureIndex(index); return super.addAll(index, c); } @Override public boolean addAll(final int index, final ByteList l) { ensureIndex(index); return super.addAll(index, l); } } }
3e0f3d43bff4512e04fade2b4727a3500976cf5a
2,308
java
Java
src/main/java/io/choerodon/iam/infra/dto/payload/UserMemberEventPayload.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
5
2020-03-20T02:31:52.000Z
2020-07-25T02:35:23.000Z
src/main/java/io/choerodon/iam/infra/dto/payload/UserMemberEventPayload.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
2
2020-04-13T02:46:40.000Z
2020-07-30T07:13:51.000Z
src/main/java/io/choerodon/iam/infra/dto/payload/UserMemberEventPayload.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
15
2019-12-05T01:05:49.000Z
2020-09-27T02:43:39.000Z
20.069565
71
0.64948
6,473
package io.choerodon.iam.infra.dto.payload; import io.swagger.annotations.ApiModelProperty; import java.util.List; import java.util.Set; /** * @author flyleft * @since 2018/4/10 */ public class UserMemberEventPayload { private Long userId; private String username; private Long resourceId; private String resourceType; private Set<String> roleLabels; private Set<String> previousRoleLabels; private String uuid; private Boolean syncAll; @ApiModelProperty("用户包含的角色ids") private Set<Long> roleIds; @ApiModelProperty("已经删除角色的标签") private Set<String> deleteRoleLabels; public Set<String> getDeleteRoleLabels() { return deleteRoleLabels; } public void setDeleteRoleLabels(Set<String> deleteRoleLabels) { this.deleteRoleLabels = deleteRoleLabels; } public Set<Long> getRoleIds() { return roleIds; } public void setRoleIds(Set<Long> roleIds) { this.roleIds = roleIds; } public Set<String> getRoleLabels() { return roleLabels; } public void setRoleLabels(Set<String> roleLabels) { this.roleLabels = roleLabels; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Long getResourceId() { return resourceId; } public void setResourceId(Long resourceId) { this.resourceId = resourceId; } public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Boolean getSyncAll() { return syncAll; } public void setSyncAll(Boolean syncAll) { this.syncAll = syncAll; } public Set<String> getPreviousRoleLabels() { return previousRoleLabels; } public void setPreviousRoleLabels(Set<String> previousRoleLabels) { this.previousRoleLabels = previousRoleLabels; } }
3e0f3da2ab6b7c1cff2a5ea14e6e99d92331bb2a
1,150
java
Java
src/main/java/org/motometer/telegram/bot/core/spi/CoreModule.java
motometer/telegram-bot-core
5ff741683bf86cc442cde917cb0c4e77f86b2e53
[ "Apache-2.0" ]
null
null
null
src/main/java/org/motometer/telegram/bot/core/spi/CoreModule.java
motometer/telegram-bot-core
5ff741683bf86cc442cde917cb0c4e77f86b2e53
[ "Apache-2.0" ]
2
2019-12-14T09:45:02.000Z
2019-12-15T15:01:09.000Z
src/main/java/org/motometer/telegram/bot/core/spi/CoreModule.java
motometer/telegram-bot-core
5ff741683bf86cc442cde917cb0c4e77f86b2e53
[ "Apache-2.0" ]
null
null
null
32.857143
89
0.769565
6,474
package org.motometer.telegram.bot.core.spi; import java.util.ServiceLoader; import org.motometer.telegram.bot.Bot; import org.motometer.telegram.bot.core.api.UpdateListener; import org.motometer.telegram.bot.core.api.UpdateReader; import org.motometer.telegram.bot.core.api.WebHookListener; import org.motometer.telegram.bot.core.api.WebHookUpdateListener; import org.motometer.telegram.bot.core.update.UpdateListenerModule; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapterFactory; import dagger.Module; import dagger.Provides; @Module(includes = { UpdateListenerModule.class }) public class CoreModule { @Provides public WebHookListener webHookListener(UpdateListener listener, Bot bot) { return new WebHookUpdateListener(listener, bot, new UpdateReader(createGson())); } private static Gson createGson() { GsonBuilder gsonBuilder = new GsonBuilder(); for (TypeAdapterFactory factory : ServiceLoader.load(TypeAdapterFactory.class)) { gsonBuilder.registerTypeAdapterFactory(factory); } return gsonBuilder.create(); } }
3e0f3ff79f2e936812f939dd07604e9936703197
1,692
java
Java
ruoyi-system/src/main/java/com/ruoyi/medical/domain/CpoeSplitbed.java
bao20021024/ruoyi
542539a00bdd13bd436bb7f0d4585059e288aabe
[ "MIT" ]
null
null
null
ruoyi-system/src/main/java/com/ruoyi/medical/domain/CpoeSplitbed.java
bao20021024/ruoyi
542539a00bdd13bd436bb7f0d4585059e288aabe
[ "MIT" ]
null
null
null
ruoyi-system/src/main/java/com/ruoyi/medical/domain/CpoeSplitbed.java
bao20021024/ruoyi
542539a00bdd13bd436bb7f0d4585059e288aabe
[ "MIT" ]
null
null
null
20.634146
71
0.593381
6,475
package com.ruoyi.medical.domain; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; /** * 分床记录对象 t_medical_cpoe_splitbed * * @author bao * @date 2021-09-23 */ public class CpoeSplitbed extends BaseEntity { private static final long serialVersionUID = 1L; /** 分床记录id */ private String id; /** 患者id */ @Excel(name = "患者id") private String personId; /** 主治医师id */ @Excel(name = "主治医师id") private String doctorId; /** 床位id */ @Excel(name = "床位id") private String bedId; public void setId(String id) { this.id = id; } public String getId() { return id; } public void setPersonId(String personId) { this.personId = personId; } public String getPersonId() { return personId; } public void setDoctorId(String doctorId) { this.doctorId = doctorId; } public String getDoctorId() { return doctorId; } public void setBedId(String bedId) { this.bedId = bedId; } public String getBedId() { return bedId; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("personId", getPersonId()) .append("doctorId", getDoctorId()) .append("bedId", getBedId()) .append("createTime", getCreateTime()) .append("remark", getRemark()) .toString(); } }
3e0f400274d21c07e8cbbc2789d848a1acf19ea8
4,104
java
Java
src/main/java/com/builtbroken/atomic/CommonProxy.java
halvors/Atomic-Science
e81407b9940fd1ab1eca833b5787df6a0a3bb272
[ "MIT" ]
29
2018-04-28T17:48:59.000Z
2022-01-15T12:21:34.000Z
src/main/java/com/builtbroken/atomic/CommonProxy.java
halvors/Atomic-Science
e81407b9940fd1ab1eca833b5787df6a0a3bb272
[ "MIT" ]
77
2017-12-17T20:04:55.000Z
2021-12-29T02:32:32.000Z
src/main/java/com/builtbroken/atomic/CommonProxy.java
halvors/Atomic-Science
e81407b9940fd1ab1eca833b5787df6a0a3bb272
[ "MIT" ]
14
2018-05-02T20:49:36.000Z
2021-09-28T04:02:32.000Z
32.314961
134
0.672271
6,476
package com.builtbroken.atomic; import com.builtbroken.atomic.client.particles.AcceleratorParticleRenderData; import com.builtbroken.atomic.lib.gui.IGuiTile; import com.builtbroken.atomic.network.packet.client.PacketAcceleratorParticleSync; import com.builtbroken.atomic.proxy.ContentProxy; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Keyboard; import java.util.HashMap; import java.util.UUID; import java.util.concurrent.ConcurrentLinkedQueue; public abstract class CommonProxy extends ContentProxy implements IGuiHandler { public static final HashMap<UUID, AcceleratorParticleRenderData> PARTICLES_TO_RENDER = new HashMap(); //TODO add fly wheel pattern public static final ConcurrentLinkedQueue<PacketAcceleratorParticleSync> NEW_PARTICLE_PACKETS = new ConcurrentLinkedQueue(); public CommonProxy(String name) { super(name); } @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { if (ID == 10002) { return getServerGuiElement(y, player, x); } else if (ID == 10001) { return getServerGuiElement(y, player, world.getEntityByID(x)); } return getServerGuiElement(ID, player, world.getTileEntity(new BlockPos(x, y, z))); } public Object getServerGuiElement(int ID, EntityPlayer player, int slot) { ItemStack stack = player.inventory.getStackInSlot(slot); if (!stack.isEmpty() && stack.getItem() instanceof IGuiTile) { return ((IGuiTile) stack.getItem()).getServerGuiElement(ID, player); } return null; } public Object getServerGuiElement(int ID, EntityPlayer player, TileEntity tile) { if (tile instanceof IGuiTile) { return ((IGuiTile) tile).getServerGuiElement(ID, player); } return null; } public Object getServerGuiElement(int ID, EntityPlayer player, Entity entity) { if (entity instanceof IGuiTile) { return ((IGuiTile) entity).getServerGuiElement(ID, player); } return null; } @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { if (ID == 10002) { return getClientGuiElement(y, player, x); } else if (ID == 10001) { return getClientGuiElement(y, player, world.getEntityByID(x)); } return getClientGuiElement(ID, player, world.getTileEntity(new BlockPos(x, y, z))); } public Object getClientGuiElement(int ID, EntityPlayer player, int slot) { ItemStack stack = player.inventory.getStackInSlot(slot); if (!stack.isEmpty() && stack.getItem() instanceof IGuiTile) { return ((IGuiTile) stack.getItem()).getClientGuiElement(ID, player); } return null; } public Object getClientGuiElement(int ID, EntityPlayer player, TileEntity tile) { if (tile instanceof IGuiTile) { return ((IGuiTile) tile).getClientGuiElement(ID, player); } return null; } public Object getClientGuiElement(int ID, EntityPlayer player, Entity entity) { if (entity instanceof IGuiTile) { return ((IGuiTile) entity).getClientGuiElement(ID, player); } return null; } @SideOnly(Side.CLIENT) public boolean isShiftHeld() { return Keyboard.isKeyDown(Keyboard.KEY_RSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_LSHIFT); } public void spawnParticle(String particle, double x, double y, double z, double vx, double vy, double vz) { } }
3e0f41324c667aca93425ebd1bbf1a498a8f3178
3,622
java
Java
stack/core/src/main/java/org/apache/usergrid/persistence/SimpleEntityRef.java
soothsayerco/incubator-usergrid
a82f0fb347bcb42d7de9089b36c18ba4a54429cc
[ "Apache-2.0" ]
2
2015-08-28T22:49:24.000Z
2016-02-26T08:04:13.000Z
stack/core/src/main/java/org/apache/usergrid/persistence/SimpleEntityRef.java
soothsayerco/incubator-usergrid
a82f0fb347bcb42d7de9089b36c18ba4a54429cc
[ "Apache-2.0" ]
null
null
null
stack/core/src/main/java/org/apache/usergrid/persistence/SimpleEntityRef.java
soothsayerco/incubator-usergrid
a82f0fb347bcb42d7de9089b36c18ba4a54429cc
[ "Apache-2.0" ]
1
2018-12-03T14:35:12.000Z
2018-12-03T14:35:12.000Z
23.986755
77
0.553838
6,477
/* * 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.usergrid.persistence; import java.util.UUID; public class SimpleEntityRef implements EntityRef { public static final UUID NULL_ID = new UUID( 0, 0 ); protected final String type; protected final UUID id; public SimpleEntityRef( UUID id ) { this.id = id; type = null; } public SimpleEntityRef( String type, UUID id ) { this.type = type; this.id = id; } public SimpleEntityRef( EntityRef entityRef ) { type = entityRef.getType(); id = entityRef.getUuid(); } public static EntityRef ref() { return new SimpleEntityRef( null, null ); } @Override public UUID getUuid() { return id; } @Override public String getType() { return type; } public static EntityRef ref( String entityType, UUID entityId ) { return new SimpleEntityRef( entityType, entityId ); } public static EntityRef ref( UUID entityId ) { return new SimpleEntityRef( null, entityId ); } public static EntityRef ref( EntityRef ref ) { return new SimpleEntityRef( ref ); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( ( id == null ) ? 0 : id.hashCode() ); result = prime * result + ( ( type == null ) ? 0 : type.hashCode() ); return result; } @Override public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } SimpleEntityRef other = ( SimpleEntityRef ) obj; if ( id == null ) { if ( other.id != null ) { return false; } } else if ( !id.equals( other.id ) ) { return false; } if ( type == null ) { if ( other.type != null ) { return false; } } else if ( !type.equals( other.type ) ) { return false; } return true; } @Override public String toString() { if ( ( type == null ) && ( id == null ) ) { return "EntityRef(" + NULL_ID.toString() + ")"; } if ( type == null ) { return "EntityRef(" + id.toString() + ")"; } return type + "(" + id + ")"; } public static UUID getUuid( EntityRef ref ) { if ( ref == null ) { return null; } return ref.getUuid(); } public static String getType( EntityRef ref ) { if ( ref == null ) { return null; } return ref.getType(); } }
3e0f42ece5567d10da9bb6c9f1f3cb084b22f655
2,964
java
Java
ExtractedJars/Health_com.huawei.health/javafiles/com/autonavi/ae/gmap/gloverlay/GLOverlayTexture.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/Health_com.huawei.health/javafiles/com/autonavi/ae/gmap/gloverlay/GLOverlayTexture.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/Health_com.huawei.health/javafiles/com/autonavi/ae/gmap/gloverlay/GLOverlayTexture.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
30.244898
71
0.497301
6,478
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.autonavi.ae.gmap.gloverlay; public class GLOverlayTexture { public GLOverlayTexture(int i, int j, float f, float f1, int k, int l) { // 0 0:aload_0 // 1 1:invokespecial #19 <Method void Object()> mResId = 0; // 2 4:aload_0 // 3 5:iconst_0 // 4 6:putfield #21 <Field int mResId> mResId = i; // 5 9:aload_0 // 6 10:iload_1 // 7 11:putfield #21 <Field int mResId> mWidth = k; // 8 14:aload_0 // 9 15:iload 5 // 10 17:putfield #23 <Field int mWidth> mHeight = l; // 11 20:aload_0 // 12 21:iload 6 // 13 23:putfield #25 <Field int mHeight> mResWidth = k; // 14 26:aload_0 // 15 27:iload 5 // 16 29:putfield #27 <Field int mResWidth> mResHeight = l; // 17 32:aload_0 // 18 33:iload 6 // 19 35:putfield #29 <Field int mResHeight> mAnchor = j; // 20 38:aload_0 // 21 39:iload_2 // 22 40:putfield #31 <Field int mAnchor> mAnchorXRatio = f; // 23 43:aload_0 // 24 44:fload_3 // 25 45:putfield #33 <Field float mAnchorXRatio> mAnchorYRatio = f1; // 26 48:aload_0 // 27 49:fload 4 // 28 51:putfield #35 <Field float mAnchorYRatio> // 29 54:return } public GLOverlayTexture(int i, int j, int k, int l) { // 0 0:aload_0 // 1 1:invokespecial #19 <Method void Object()> mResId = 0; // 2 4:aload_0 // 3 5:iconst_0 // 4 6:putfield #21 <Field int mResId> mResId = i; // 5 9:aload_0 // 6 10:iload_1 // 7 11:putfield #21 <Field int mResId> mWidth = k; // 8 14:aload_0 // 9 15:iload_3 // 10 16:putfield #23 <Field int mWidth> mHeight = l; // 11 19:aload_0 // 12 20:iload 4 // 13 22:putfield #25 <Field int mHeight> mResWidth = k; // 14 25:aload_0 // 15 26:iload_3 // 16 27:putfield #27 <Field int mResWidth> mResHeight = l; // 17 30:aload_0 // 18 31:iload 4 // 19 33:putfield #29 <Field int mResHeight> mAnchor = j; // 20 36:aload_0 // 21 37:iload_2 // 22 38:putfield #31 <Field int mAnchor> // 23 41:return } public int mAnchor; public float mAnchorXRatio; public float mAnchorYRatio; public int mHeight; public int mResHeight; public int mResId; public int mResWidth; public int mWidth; }
3e0f43f6688c33774e083bddaad44cf46482eecf
9,562
java
Java
integration/src/main/java/uk/ac/ebi/biosamples/RestFacetIntegration.java
EBIBioSamples/biosamples-v4
0b8f70479b1937ff11e1e466a3cd17a25e3a2356
[ "Apache-2.0" ]
10
2016-08-30T15:42:52.000Z
2021-11-09T20:37:35.000Z
integration/src/main/java/uk/ac/ebi/biosamples/RestFacetIntegration.java
EBIBioSamples/biosamples-v4
0b8f70479b1937ff11e1e466a3cd17a25e3a2356
[ "Apache-2.0" ]
51
2018-02-28T09:15:15.000Z
2022-02-17T14:40:55.000Z
integration/src/main/java/uk/ac/ebi/biosamples/RestFacetIntegration.java
EBIBioSamples/biosamples-v4
0b8f70479b1937ff11e1e466a3cd17a25e3a2356
[ "Apache-2.0" ]
16
2017-02-08T11:10:24.000Z
2021-05-21T11:07:47.000Z
39.188525
139
0.691905
6,479
/* * Copyright 2021 EMBL - European Bioinformatics Institute * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package uk.ac.ebi.biosamples; import java.time.Instant; import java.util.Arrays; import java.util.SortedSet; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.hateoas.Resource; import org.springframework.stereotype.Component; import uk.ac.ebi.biosamples.client.BioSamplesClient; import uk.ac.ebi.biosamples.model.Attribute; import uk.ac.ebi.biosamples.model.ExternalReference; import uk.ac.ebi.biosamples.model.Sample; import uk.ac.ebi.biosamples.utils.IntegrationTestFailException; @Component @Order(3) // @Profile({"default","rest"}) public class RestFacetIntegration extends AbstractIntegration { private Logger log = LoggerFactory.getLogger(this.getClass()); private final IntegrationProperties integrationProperties; private final BioSamplesProperties bioSamplesProperties; public RestFacetIntegration( BioSamplesClient client, IntegrationProperties integrationProperties, BioSamplesProperties bioSamplesProperties) { super(client); this.integrationProperties = integrationProperties; this.bioSamplesProperties = bioSamplesProperties; } @Override protected void phaseOne() { Sample sampleTest1 = getSampleTest1(); Sample enaSampleTest = getEnaSampleTest(); Sample aeSampleTest = getArrayExpressSampleTest(); // put a sample Resource<Sample> resource = client.persistSampleResource(sampleTest1); sampleTest1 = Sample.Builder.fromSample(sampleTest1) .withAccession(resource.getContent().getAccession()) .build(); if (!sampleTest1.equals(resource.getContent())) { throw new IntegrationTestFailException( "Expected response (" + resource.getContent() + ") to equal submission (" + sampleTest1 + ")", Phase.ONE); } resource = client.persistSampleResource(enaSampleTest); enaSampleTest = Sample.Builder.fromSample(enaSampleTest) .withAccession(resource.getContent().getAccession()) .build(); if (!enaSampleTest.equals(resource.getContent())) { throw new IntegrationTestFailException( "Expected response (" + resource.getContent() + ") to equal submission (" + enaSampleTest + ")", Phase.ONE); } resource = client.persistSampleResource(aeSampleTest); aeSampleTest = Sample.Builder.fromSample(aeSampleTest) .withAccession(resource.getContent().getAccession()) .build(); if (!aeSampleTest.equals(resource.getContent())) { throw new IntegrationTestFailException( "Expected response (" + resource.getContent() + ") to equal submission (" + aeSampleTest + ")", Phase.ONE); } } @Override protected void phaseTwo() { /* * disable untill we can properly implement a facet format Map<String, Object> parameters = new HashMap<>(); parameters.put("text","TESTrestfacet1"); Traverson traverson = new Traverson(bioSamplesProperties.getBiosamplesClientUri(), MediaTypes.HAL_JSON); Traverson.TraversalBuilder builder = traverson.follow("samples", "facet").withTemplateParameters(parameters); Resources<Facet> facets = builder.toObject(new TypeReferences.ResourcesType<Facet>(){}); log.info("GETting from " + builder.asLink().expand(parameters).getHref()); if (facets.getContent().size() <= 0) { throw new RuntimeException("No facets found!"); } List<Facet> content = new ArrayList<>(facets.getContent()); FacetContent facetContent = content.get(0).getContent(); if (facetContent instanceof LabelCountListContent) { if (((LabelCountListContent) facetContent).size() <= 0) { throw new RuntimeException("No facet values found!"); } } */ // TODO check that the particular facets we expect are present } @Override protected void phaseThree() { /* * disable untill we can properly implement a facet format Sample enaSample = getEnaSampleTest(); SortedSet<ExternalReference> sampleExternalRefs = enaSample.getExternalReferences(); Map<String, Object> parameters = new HashMap<>(); parameters.put("text",enaSample.getAccession()); Traverson traverson = new Traverson(bioSamplesProperties.getBiosamplesClientUri(), MediaTypes.HAL_JSON); Traverson.TraversalBuilder builder = traverson.follow("samples", "facet").withTemplateParameters(parameters); Resources<Facet> facets = builder.toObject(new TypeReferences.ResourcesType<Facet>(){}); log.info("GETting from " + builder.asLink().expand(parameters).getHref()); if (facets.getContent().isEmpty()) { throw new RuntimeException("Facet endpoint does not contain the expected number of facet"); } List<ExternalReferenceDataFacet> externalDataFacetList = facets.getContent().stream() .filter(facet -> facet.getType().equals(FacetType.EXTERNAL_REFERENCE_DATA_FACET)) .map(facet -> (ExternalReferenceDataFacet) facet) .collect(Collectors.toList()); for (ExternalReferenceDataFacet facet: externalDataFacetList) { List<String> facetContentLabels = facet.getContent().stream().map(LabelCountEntry::getLabel).collect(Collectors.toList()); for (String extRefDataId: facetContentLabels) { boolean found = sampleExternalRefs.stream().anyMatch(extRef -> extRef.getUrl().toLowerCase().endsWith(extRefDataId.toLowerCase())); if (!found) { throw new RuntimeException("Facet content does not contain expected external reference data id"); } } } */ } @Override protected void phaseFour() {} @Override protected void phaseFive() {} private Sample getSampleTest1() { String name = "RestFacetIntegration_testRestFacet"; Instant update = Instant.parse("2016-05-05T11:36:57.00Z"); Instant release = Instant.parse("2016-04-01T11:36:57.00Z"); SortedSet<Attribute> attributes = new TreeSet<>(); attributes.add( Attribute.build( "organism", "Homo sapiens", "http://purl.obolibrary.org/obo/NCBITaxon_9606", null)); // use non alphanumeric characters in type attributes.add(Attribute.build("geographic location (country and/or sea)", "Land of Oz")); return new Sample.Builder(name) .withDomain(defaultIntegrationSubmissionDomain) .withRelease(release) .withUpdate(update) .withAttributes(attributes) .build(); } private Sample getEnaSampleTest() { String name = "RestFacetIntegration_testEnaRestFacet"; Instant update = Instant.parse("2015-03-22T08:30:23.00Z"); Instant release = Instant.parse("2015-03-22T08:30:23.00Z"); SortedSet<Attribute> attributes = new TreeSet<>(); attributes.add( Attribute.build( "organism", "Homo sapiens", "http://purl.obolibrary.org/obo/NCBITaxon_9606", null)); // use non alphanumeric characters in type attributes.add(Attribute.build("geographic location (country and/or sea)", "Land of Oz")); SortedSet<ExternalReference> externalReferences = new TreeSet<>(); externalReferences.add( ExternalReference.build( "https://www.ebi.ac.uk/ena/ERA123123", new TreeSet<>(Arrays.asList("DUO:0000005", "DUO:0000001", "DUO:0000007")))); externalReferences.add( ExternalReference.build("http://www.ebi.ac.uk/arrayexpress/experiments/E-MTAB-09123")); return new Sample.Builder(name) .withDomain(defaultIntegrationSubmissionDomain) .withRelease(release) .withUpdate(update) .withAttributes(attributes) .withExternalReferences(externalReferences) .build(); } private Sample getArrayExpressSampleTest() { String name = "RestFacetIntegration_testArrayExpressRestFacet"; Instant update = Instant.parse("2015-03-22T08:30:23.00Z"); Instant release = Instant.parse("2015-03-22T08:30:23.00Z"); SortedSet<Attribute> attributes = new TreeSet<>(); attributes.add( Attribute.build( "organism", "Homo sapiens", "http://purl.obolibrary.org/obo/NCBITaxon_9606", null)); // use non alphanumeric characters in type attributes.add(Attribute.build("geographic location (country and/or sea)", "Land of Oz")); SortedSet<ExternalReference> externalReferences = new TreeSet<>(); externalReferences.add( ExternalReference.build("http://www.ebi.ac.uk/arrayexpress/experiments/E-MTAB-5277")); return new Sample.Builder(name) .withDomain(defaultIntegrationSubmissionDomain) .withRelease(release) .withUpdate(update) .withAttributes(attributes) .withExternalReferences(externalReferences) .build(); } }
3e0f45aa91f84c5fb956d63dc2bc0e80d57a0b62
1,688
java
Java
app/src/main/java/com/example/graph_editor/model/graph_generators/GraphGeneratorGrid.java
aleksanderkatan/Graph-Editor
09d85ec299cfb87395a86f615d539c9fb4238673
[ "MIT" ]
null
null
null
app/src/main/java/com/example/graph_editor/model/graph_generators/GraphGeneratorGrid.java
aleksanderkatan/Graph-Editor
09d85ec299cfb87395a86f615d539c9fb4238673
[ "MIT" ]
null
null
null
app/src/main/java/com/example/graph_editor/model/graph_generators/GraphGeneratorGrid.java
aleksanderkatan/Graph-Editor
09d85ec299cfb87395a86f615d539c9fb4238673
[ "MIT" ]
null
null
null
31.259259
86
0.587085
6,480
package com.example.graph_editor.model.graph_generators; import com.example.graph_editor.model.Graph; import com.example.graph_editor.model.GraphImpl; import com.example.graph_editor.model.GraphType; import com.example.graph_editor.model.Vertex; import com.example.graph_editor.model.mathematics.Geometry; import java.util.ArrayList; import java.util.List; public class GraphGeneratorGrid implements GraphGenerator { @Override public List<Parameter> getParameters() { List<Parameter> parameters = new ArrayList<>(); parameters.add(new Parameter("Horizontal", 1, 32)); parameters.add(new Parameter("Vertical", 1, 32)); return parameters; } @Override public Graph generate(List<Integer> parameters) { int hor = parameters.get(0); int ver = parameters.get(1); Graph result = new GraphImpl(GraphType.UNDIRECTED); for (int i = 0; i< hor*ver; i++) result.addVertex(); List<Vertex> vertices = result.getVertices(); // horizontal edges for (int i = 0; i< ver; i++) { for (int j = 0; j< hor-1; j++) { result.addEdge(vertices.get(i*hor+j), vertices.get(i*hor+(j+1))); } } // vertical edges for (int i = 0; i< ver-1; i++) { for (int j = 0; j< hor; j++) { result.addEdge(vertices.get(i*hor+j), vertices.get((i+1)*hor+j)); } } // placement for (int i = 0; i< ver; i++) { for (int j = 0; j< hor; j++) { vertices.get(i*hor+j).setPoint(Geometry.getGridPoint(j, i, hor, ver)); } } return result; } }
3e0f460cddb44455d5a6b8b6fbfcd7a0b01cb6aa
5,072
java
Java
src/main/java/org/lobobrowser/gui/NavigationEngine.java
stlee42/LoboBrowser
9ed398484ff7ce97063e4ed03561d5b2a3d677ed
[ "MIT" ]
75
2017-04-05T05:38:25.000Z
2022-02-24T20:15:50.000Z
src/main/java/org/lobobrowser/gui/NavigationEngine.java
stlee42/LoboBrowser
9ed398484ff7ce97063e4ed03561d5b2a3d677ed
[ "MIT" ]
9
2017-03-15T15:36:58.000Z
2022-01-21T23:22:32.000Z
src/main/java/org/lobobrowser/gui/NavigationEngine.java
stlee42/LoboBrowser
9ed398484ff7ce97063e4ed03561d5b2a3d677ed
[ "MIT" ]
29
2017-08-13T18:52:00.000Z
2022-01-15T14:07:39.000Z
28.573034
110
0.661227
6,481
/* GNU GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either verion 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: upchh@example.com */ package org.lobobrowser.gui; import org.cobraparser.validation.DomainValidation; import org.cobraparser.ua.NavigationEntry; import org.cobraparser.util.Urls; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * This class stores navigation back/forward state for a frame. * <p> * Note: This class is not thread safe on its own. */ final public class NavigationEngine { private static final Logger logger = Logger.getLogger(NavigationEngine.class.getName()); private final ArrayList<NavigationEntry> history = new ArrayList<>(); private int currentIndex = -1; public NavigationEntry getCurrentEntry() { try { return this.history.get(this.currentIndex); } catch (final IndexOutOfBoundsException iob) { return null; } } public void addNavigationEntry(final NavigationEntry entry) { /* if (logger.isLoggable(Level.INFO)) { logger.info("addNavigationEntry(): entry=" + entry); } */ final int newIndex = this.currentIndex + 1; if (newIndex == this.history.size()) { this.history.add(entry); } else { if (newIndex > this.history.size()) { throw new IllegalStateException("currentIndex=" + this.currentIndex + ",size=" + this.history.size()); } this.history.set(newIndex, entry); } this.currentIndex = newIndex; final int nextIndex = newIndex + 1; while (nextIndex < this.history.size()) { this.history.remove(nextIndex); } } public boolean hasNext() { return (this.currentIndex + 1) < this.history.size(); } public boolean hasPrev() { return this.currentIndex > 0; } public boolean hasNextWithGET() { return this.hasNewEntryWithGET(+1); } public boolean hasPrevWithGET() { return this.hasNewEntryWithGET(-1); } public boolean hasNewEntryWithGET(final int offset) { int nextIndex = this.currentIndex; for (;;) { nextIndex += offset; if ((nextIndex >= 0) && (nextIndex < this.history.size())) { final NavigationEntry entry = this.history.get(nextIndex); if ("GET".equals(entry.getMethod())) { return true; } else { continue; } } else { return false; } } } public NavigationEntry back() { return this.move(-1); } public NavigationEntry forward() { return this.move(+1); } public NavigationEntry move(final int offset) { final int nextIndex = this.currentIndex + offset; if ((nextIndex >= 0) && (nextIndex < this.history.size())) { this.currentIndex = nextIndex; return this.history.get(this.currentIndex); } else { return null; } } public boolean moveTo(final NavigationEntry entry) { final int newIndex = this.history.indexOf(entry); if (newIndex == -1) { return false; } this.currentIndex = newIndex; return true; } public List<NavigationEntry> getForwardNavigationEntries() { final ArrayList<NavigationEntry> entries = new ArrayList<>(); int index = this.currentIndex + 1; final int size = this.history.size(); while (index < size) { entries.add(this.history.get(index)); index++; } return entries; } /** * Gets prior navigation entries, in descending order. */ public List<NavigationEntry> getBackNavigationEntries() { final ArrayList<NavigationEntry> entries = new ArrayList<>(); int index = this.currentIndex - 1; while (index >= 0) { entries.add(this.history.get(index)); index--; } return entries; } public NavigationEntry findEntry(final String absoluteURL) { try { final java.net.URL targetURL = DomainValidation.guessURL(absoluteURL); for (final NavigationEntry entry : this.history) { if (Urls.sameNoRefURL(targetURL, entry.getUrl())) { return entry; } } return null; } catch (final java.net.MalformedURLException mfu) { if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, "findEntry(): URL is malformed: " + absoluteURL, mfu); } return null; } } public int getLength() { return this.history.size(); } }
3e0f46981baf55a827817380f0cc202803a0578d
3,030
java
Java
src/test/java/tests/ProductsTest.java
Pavellys/SauceDemoTest
ce6dfd78fe28723fcccb592ff273a7da1262a1eb
[ "Info-ZIP" ]
null
null
null
src/test/java/tests/ProductsTest.java
Pavellys/SauceDemoTest
ce6dfd78fe28723fcccb592ff273a7da1262a1eb
[ "Info-ZIP" ]
null
null
null
src/test/java/tests/ProductsTest.java
Pavellys/SauceDemoTest
ce6dfd78fe28723fcccb592ff273a7da1262a1eb
[ "Info-ZIP" ]
null
null
null
42.083333
116
0.685149
6,482
package tests; import test_data.ExpResConst; import org.testng.Assert; import org.testng.annotations.Test; public class ProductsTest extends BaseTest { @Test(description = "Checking to adding product in the cart") public void addProductToCartTest() { productsPage.openPage() .addProductToCart(TEST_PRODUCT); cartPage.openPage(); Assert.assertEquals(cartPage.getQuantity(TEST_PRODUCT), ExpResConst.QUANTITY_IN_CART, "Quantity not right"); Assert.assertEquals(cartPage.getPrice(TEST_PRODUCT), ExpResConst.PRICE_IN_CART, "Price not right"); } @Test(description = "Checking sort panel 'low-high'") public void checkingSortPanelLowHigh() { productsPage.openPage() .changeSortLowHigh(); Assert.assertEquals(productsPage.checkingFirstProduct(), ExpResConst.FIRST_PRODUCT_HL, "error"); Assert.assertEquals(productsPage.checkingLastProduct(), ExpResConst.LAST_PRODUCT_HL, "error"); } @Test(description = "Checking sort panel 'high-low'") public void checkingSortPanelHighLow() { productsPage.openPage() .changeSortHighLow(); Assert.assertEquals(productsPage.checkingLastProduct(), ExpResConst.FIRST_PRODUCT_HL, "error"); Assert.assertEquals(productsPage.checkingFirstProduct(), ExpResConst.LAST_PRODUCT_HL, "error"); } @Test(description = "Checking sort panel 'Z-A'") public void checkingSortPanelZ_A() { productsPage.openPage() .changeSortZ_A(); Assert.assertEquals(productsPage.checkingFirstProduct(), ExpResConst.LAST_PRODUCT_AZ, "error"); Assert.assertEquals(productsPage.checkingLastProduct(), ExpResConst.FIRST_PRODUCT_AZ, "error"); } @Test(description = "Checking sort panel 'A-Z'") public void checkingSortPanelA_Z() { productsPage.openPage() .changeSortA_Z(); Assert.assertEquals(productsPage.checkingFirstProduct(), ExpResConst.FIRST_PRODUCT_AZ, "error"); Assert.assertEquals(productsPage.checkingLastProduct(), ExpResConst.LAST_PRODUCT_AZ, "error"); } @Test(description = "Checking of button 'AllItems' in the sidebar") public void sideBarCheckingAllItems() { productsPage.openPage() .clickSideBar() .clickAllItemFromSideBar(); Assert.assertEquals(productsPage.getActualURL(), PRODUCTS_URL); } @Test(description = "Checking of button 'About' in the sidebar") public void sideBarCheckingAbout() { productsPage.openPage() .clickSideBar() .clickAboutFromSideBar(); Assert.assertEquals(productsPage.getActualURL(), ABOUT_LINK_URL); } @Test(description = "Checking of button 'Logout' in the sidebar") public void sideBarCheckingLogout() { productsPage.openPage() .clickSideBar() .clickLogoutFromSideBar(); Assert.assertEquals(productsPage.getActualURL(), LOGOUT_LINK_URL); } }
3e0f46efec20a2f600c9465b2575b19e4a871239
208
java
Java
src/Player.java
mitchhuang777/GuessNum
fdc0ccebaf9f2a07380bccff658cb72369f5ea1f
[ "MIT" ]
1
2021-09-12T10:14:25.000Z
2021-09-12T10:14:25.000Z
src/Player.java
mitchhuang777/GuessNum
fdc0ccebaf9f2a07380bccff658cb72369f5ea1f
[ "MIT" ]
null
null
null
src/Player.java
mitchhuang777/GuessNum
fdc0ccebaf9f2a07380bccff658cb72369f5ea1f
[ "MIT" ]
null
null
null
14.857143
48
0.6875
6,483
public abstract class Player { private String name; public Player(String name) { this.name = name; } public String nameSelf() { return name; } public abstract int guessNum(int min, int max); }
3e0f4733f5652ef67a7a5fee965045bdd08c7602
110
java
Java
app/src/main/java/com/yooyor/photo/entity/PhotoBean.java
xuefengyang/Photos
0b46cd38079394d5ba04e01eaa4226277e64b5d4
[ "Apache-2.0" ]
3
2015-12-12T15:35:36.000Z
2017-03-09T09:02:36.000Z
app/src/main/java/com/yooyor/photo/entity/PhotoBean.java
xuefengyang/Photos
0b46cd38079394d5ba04e01eaa4226277e64b5d4
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/yooyor/photo/entity/PhotoBean.java
xuefengyang/Photos
0b46cd38079394d5ba04e01eaa4226277e64b5d4
[ "Apache-2.0" ]
null
null
null
13.75
40
0.7
6,484
package com.yooyor.photo.entity; /** * Created by xuefengyang on 2015/11/17. */ public class PhotoBean { }
3e0f4792f603905f5c71445b3b7e7b6d4daaccd3
351
java
Java
java/bypstest-ser/src-ser/byps/test/api/BResult_766441794.java
markusessigde/byps
b8099a54079823a8fbb156e3e5a3a13fb576d031
[ "MIT" ]
4
2018-10-19T08:50:40.000Z
2021-03-22T14:39:40.000Z
java/bypstest-ser/src-ser/byps/test/api/BResult_766441794.java
markusessigde/byps
b8099a54079823a8fbb156e3e5a3a13fb576d031
[ "MIT" ]
null
null
null
java/bypstest-ser/src-ser/byps/test/api/BResult_766441794.java
markusessigde/byps
b8099a54079823a8fbb156e3e5a3a13fb576d031
[ "MIT" ]
4
2015-07-17T16:31:10.000Z
2022-01-28T14:43:07.000Z
17.55
93
0.740741
6,485
package byps.test.api; /* * * THIS FILE HAS BEEN GENERATED BY class byps.gen.j.GenApiClass DO NOT MODIFY. */ import byps.*; import java.io.Serializable; /** */ @SuppressWarnings("all") public final class BResult_766441794 extends BMethodResult<float[]> implements Serializable { public final static long serialVersionUID = 1167917980L; }
3e0f488d4dba581339ee9d8c08093680992ab4fd
2,888
java
Java
src/test/java/com/hello/DynamicTestExamplesTest.java
PeterSolomons/spring-hello-world
e950321ab2dcf75841fde31b02754a32287b5843
[ "MIT" ]
null
null
null
src/test/java/com/hello/DynamicTestExamplesTest.java
PeterSolomons/spring-hello-world
e950321ab2dcf75841fde31b02754a32287b5843
[ "MIT" ]
null
null
null
src/test/java/com/hello/DynamicTestExamplesTest.java
PeterSolomons/spring-hello-world
e950321ab2dcf75841fde31b02754a32287b5843
[ "MIT" ]
null
null
null
31.736264
122
0.561634
6,486
package com.hello; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DynamicContainer; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.Random; import java.util.stream.LongStream; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.DynamicContainer.dynamicContainer; import static org.junit.jupiter.api.DynamicTest.dynamicTest; public class DynamicTestExamplesTest { @BeforeEach void setUp() { System.out.println("Before Each is only called once for each test factory, not twice even though 2 tests are run!"); } //Dynamic tests have no notion of the junit lifecycle! @BeforeAll/@AfterAll ect... @TestFactory Collection<DynamicTest> dynamicTestsFromCollection() { return Arrays.asList(dynamicTest("Collection Test Name", () -> assertEquals(1, 1) ), dynamicTest("Collection Test Name 2", () -> assertEquals(1, 1) )); } @TestFactory Iterator<DynamicTest> dynamicTestsFromIterator() { return Arrays.asList(dynamicTest("Iterator Test Name", () -> assertEquals(1, 1) ), dynamicTest("Iterator Test Name 2", () -> assertEquals(1, 1) )).iterator(); } @TestFactory Stream<DynamicTest> dynamicTestFromStream() { return getStreamOfRandomNumbers().limit(1000).mapToObj(randomId -> dynamicTest( "DisplayName With random number : " + randomId, () -> { assertTrue(randomId >= 1000); assertTrue(randomId <= 2000); } )); } private LongStream getStreamOfRandomNumbers() { Random r = new Random(); return r.longs(1000, 2000); } @TestFactory Stream<DynamicContainer> dynamicTestWithContainers() { return LongStream.range(1, 6).mapToObj(productId -> dynamicContainer( "Container for ID " + productId, Stream.of( dynamicTest( "Valid Id", () -> assertTrue(productId > 0) ), dynamicContainer( "Test", Stream.of( dynamicTest("Discount applied", () -> { System.out.println(productId); assertTrue(productId > 0); assertTrue(productId != 0); } ) ) ) ) )); } }
3e0f49572516d0fef5658034fbfc3127f7309997
11,781
java
Java
wildfly/wildfly-integration/src/main/java/org/teiid/jboss/JBossSecurityHelper.java
3DRaven/teiid
25d61e97bef7042a172275ee9d37fa98fd5a28c3
[ "Apache-2.0" ]
249
2015-01-04T12:32:56.000Z
2022-03-22T07:00:46.000Z
wildfly/wildfly-integration/src/main/java/org/teiid/jboss/JBossSecurityHelper.java
3DRaven/teiid
25d61e97bef7042a172275ee9d37fa98fd5a28c3
[ "Apache-2.0" ]
312
2015-01-06T19:01:51.000Z
2022-03-10T17:49:37.000Z
wildfly/wildfly-integration/src/main/java/org/teiid/jboss/JBossSecurityHelper.java
3DRaven/teiid
25d61e97bef7042a172275ee9d37fa98fd5a28c3
[ "Apache-2.0" ]
256
2015-01-06T18:14:39.000Z
2022-03-23T17:55:42.000Z
49.292887
181
0.64587
6,487
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * 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.teiid.jboss; import java.io.Serializable; import java.security.Principal; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.security.auth.Subject; import javax.security.auth.login.LoginException; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.jboss.as.security.plugins.SecurityDomainContext; import org.jboss.as.server.CurrentServiceContainer; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.security.AuthenticationManager; import org.jboss.security.PicketBoxLogger; import org.jboss.security.SecurityConstants; import org.jboss.security.SecurityContext; import org.jboss.security.SecurityRolesAssociation; import org.jboss.security.SimplePrincipal; import org.jboss.security.SubjectInfo; import org.jboss.security.identity.RoleGroup; import org.jboss.security.identity.plugins.SimpleRoleGroup; import org.jboss.security.mapping.MappingContext; import org.jboss.security.mapping.MappingManager; import org.jboss.security.mapping.MappingType; import org.jboss.security.negotiation.Constants; import org.jboss.security.negotiation.common.NegotiationContext; import org.jboss.security.negotiation.spnego.KerberosMessage; import org.teiid.logging.LogConstants; import org.teiid.logging.LogManager; import org.teiid.security.Credentials; import org.teiid.security.GSSResult; import org.teiid.security.SecurityHelper; public class JBossSecurityHelper implements SecurityHelper, Serializable { private static final long serialVersionUID = 3598997061994110254L; public static final String AT = "@"; //$NON-NLS-1$ @Override public SecurityContext associateSecurityContext(Object newContext) { SecurityContext context = SecurityActions.getSecurityContext(); if (newContext != context) { SecurityActions.setSecurityContext((SecurityContext)newContext); } return context; } @Override public void clearSecurityContext() { SecurityActions.clearSecurityContext(); } @Override public Object getSecurityContext(String securityDomain) { SecurityContext sc = SecurityActions.getSecurityContext(); if (sc != null && sc.getSecurityDomain().equals(securityDomain)) { return sc; } return null; } public SecurityContext createSecurityContext(String securityDomain, Principal p, Object credentials, Subject subject) { return SecurityActions.createSecurityContext(p, credentials, subject, securityDomain); } @Override public Subject getSubjectInContext(Object context) { if (!(context instanceof SecurityContext)) { return null; } SecurityContext sc = (SecurityContext)context; SubjectInfo si = sc.getSubjectInfo(); Subject subject = si.getAuthenticatedSubject(); return subject; } @Override public SecurityContext authenticate(String domain, String baseUsername, Credentials credentials, String applicationName) throws LoginException { // If username specifies a domain (user@domain) only that domain is authenticated against. SecurityDomainContext securityDomainContext = getSecurityDomainContext(domain); if (securityDomainContext != null) { Subject subject = new Subject(); boolean isValid = false; SecurityContext securityContext = null; AuthenticationManager authManager = securityDomainContext.getAuthenticationManager(); if (authManager != null) { Principal userPrincipal = new SimplePrincipal(baseUsername); Object cred = credentials==null?null:credentials.getCredentials(); isValid = authManager.isValid(userPrincipal, cred, subject); securityContext = createSecurityContext(domain, userPrincipal, cred, subject); LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"Logon successful for \"", baseUsername, "\" in security domain", domain}); //$NON-NLS-1$ //$NON-NLS-2$ } if (isValid) { MappingManager mappingManager = securityDomainContext.getMappingManager(); if (mappingManager != null) { MappingContext<RoleGroup> mc = mappingManager.getMappingContext(MappingType.ROLE.name()); if(mc != null && mc.hasModules()) { RoleGroup userRoles = securityContext.getUtil().getRoles(); if(userRoles == null) { userRoles = new SimpleRoleGroup(SecurityConstants.ROLES_IDENTIFIER); } Map<String,Object> contextMap = new HashMap<String,Object>(); contextMap.put(SecurityConstants.ROLES_IDENTIFIER, userRoles); //Append any deployment role->principals configuration done by the user contextMap.put(SecurityConstants.DEPLOYMENT_PRINCIPAL_ROLES_MAP, SecurityRolesAssociation.getSecurityRoles()); //Append the principals also contextMap.put(SecurityConstants.PRINCIPALS_SET_IDENTIFIER, subject.getPrincipals()); LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"Roles before mapping \"", userRoles.toString()}); //$NON-NLS-1$ PicketBoxLogger.LOGGER.traceRolesBeforeMapping(userRoles != null ? userRoles.toString() : ""); mc.performMapping(contextMap, userRoles); RoleGroup mappedRoles = mc.getMappingResult().getMappedObject(); LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"Roles after mapping \"", mappedRoles.toString()}); //$NON-NLS-1$ } } return securityContext; } } throw new LoginException(IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50072, baseUsername, domain )); } @Override public GSSResult negotiateGssLogin(String securityDomain, byte[] serviceTicket) throws LoginException { SecurityDomainContext securityDomainContext = getSecurityDomainContext(securityDomain); if (securityDomainContext != null) { AuthenticationManager authManager = securityDomainContext.getAuthenticationManager(); if (authManager != null) { Object previous = null; NegotiationContext context = new NegotiationContext(); context.setRequestMessage(new KerberosMessage(Constants.KERBEROS_V5, serviceTicket)); try { context.associate(); SecurityContext securityContext = createSecurityContext(securityDomain, new SimplePrincipal("temp"), null, new Subject()); //$NON-NLS-1$ previous = associateSecurityContext(securityContext); Subject subject = new Subject(); boolean isValid = authManager.isValid(null, null, subject); if (isValid) { Principal principal = null; for(Principal p:subject.getPrincipals()) { principal = p; break; } GSSCredential delegationCredential = null; //if isValid checked just the cache the context will be null if (context.getSchemeContext() == null) { Set<GSSCredential> credentials = subject.getPrivateCredentials(GSSCredential.class); if (credentials != null && !credentials.isEmpty()) { delegationCredential = credentials.iterator().next(); } } Object sc = createSecurityContext(securityDomain, principal, null, subject); LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"Logon successful though GSS API"}); //$NON-NLS-1$ GSSResult result = buildGSSResult(context, securityDomain, true, delegationCredential); result.setSecurityContext(sc); result.setUserName(principal.getName()); return result; } LoginException le = (LoginException)securityContext.getData().get("org.jboss.security.exception"); //$NON-NLS-1$ if (le != null) { if (le.getMessage().equals("Continuation Required.")) { //$NON-NLS-1$ return buildGSSResult(context, securityDomain, false, null); } throw le; } } finally { associateSecurityContext(previous); context.clear(); } } } throw new LoginException(IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50072, "GSS Auth", securityDomain)); //$NON-NLS-1$ } private GSSResult buildGSSResult(NegotiationContext context, String securityDomain, boolean validAuth, GSSCredential delegationCredential) throws LoginException { GSSContext securityContext = (GSSContext) context.getSchemeContext(); try { if (securityContext != null && securityContext.getCredDelegState()) { delegationCredential = securityContext.getDelegCred(); } if (context.getResponseMessage() == null && validAuth) { return new GSSResult(context.isAuthenticated(), delegationCredential); } if (context.getResponseMessage() instanceof KerberosMessage) { KerberosMessage km = (KerberosMessage)context.getResponseMessage(); return new GSSResult(km.getToken(), context.isAuthenticated(), delegationCredential); } } catch (GSSException e) { // login exception can not take exception throw new LoginException(e.getMessage()); } throw new LoginException(IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50103, securityDomain)); } protected SecurityDomainContext getSecurityDomainContext(String securityDomain) { if (securityDomain != null && !securityDomain.isEmpty()) { ServiceName name = ServiceName.JBOSS.append("security", "security-domain", securityDomain); //$NON-NLS-1$ //$NON-NLS-2$ ServiceController<SecurityDomainContext> controller = (ServiceController<SecurityDomainContext>) CurrentServiceContainer.getServiceContainer().getService(name); if (controller != null) { return controller.getService().getValue(); } } return null; } }
3e0f49c9d116a27a37f4ef570eaa2bb9a31257bc
132
java
Java
ThinkingInJava06/src/Test02.java
WuSicheng54321/Thinking-in-Java-4th
8a0dbc52a7f879f3c6998f32d0e8c88dfe143372
[ "Apache-2.0" ]
null
null
null
ThinkingInJava06/src/Test02.java
WuSicheng54321/Thinking-in-Java-4th
8a0dbc52a7f879f3c6998f32d0e8c88dfe143372
[ "Apache-2.0" ]
null
null
null
ThinkingInJava06/src/Test02.java
WuSicheng54321/Thinking-in-Java-4th
8a0dbc52a7f879f3c6998f32d0e8c88dfe143372
[ "Apache-2.0" ]
null
null
null
18.857143
49
0.712121
6,488
import Test02.Vector; public class Test02 { java.util.Vector vector=new java.util.Vector(); Vector vector2=new Vector(); }
3e0f4ad02ca53adc06af2508424c646b06f0780d
227
java
Java
src/top/ss007/reflection/methodhandler/HandleTargetGrandson.java
shusheng007/ToMasterJava
39264aa12e7928cd5dc467e598dd59263b625ee1
[ "Apache-2.0" ]
null
null
null
src/top/ss007/reflection/methodhandler/HandleTargetGrandson.java
shusheng007/ToMasterJava
39264aa12e7928cd5dc467e598dd59263b625ee1
[ "Apache-2.0" ]
null
null
null
src/top/ss007/reflection/methodhandler/HandleTargetGrandson.java
shusheng007/ToMasterJava
39264aa12e7928cd5dc467e598dd59263b625ee1
[ "Apache-2.0" ]
null
null
null
22.7
58
0.722467
6,489
package top.ss007.reflection.methodhandler; public class HandleTargetGrandson extends HandleTarget { @Override public void connectName(String name) { System.out.println("I come from grandson: "+name); } }
3e0f4b1c5175d346c510cd5a54013b54b59ff2d1
327
java
Java
learn-model/src/main/java/com/jacky/jpa/JpaApplication.java
Jacky-Yang/jpa
34d76a1ab0f357dbdcddccadf7c9cb666bd17217
[ "MIT" ]
null
null
null
learn-model/src/main/java/com/jacky/jpa/JpaApplication.java
Jacky-Yang/jpa
34d76a1ab0f357dbdcddccadf7c9cb666bd17217
[ "MIT" ]
null
null
null
learn-model/src/main/java/com/jacky/jpa/JpaApplication.java
Jacky-Yang/jpa
34d76a1ab0f357dbdcddccadf7c9cb666bd17217
[ "MIT" ]
null
null
null
27.25
68
0.792049
6,490
package com.jacky.jpa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JpaApplication { public static void main(String[] args) throws Exception { SpringApplication.run(JpaApplication.class, args); } }
3e0f4b61e1918a9eb36506f2837f5347d6f49df1
15,092
java
Java
src/main/java/org/dataone/annotator/generator/oa/OAAnnotationGenerator.java
DataONEorg/annotator
b4098bd927c2387f93a9bff034d50149e5d3e5fa
[ "Apache-2.0" ]
1
2017-03-29T15:06:24.000Z
2017-03-29T15:06:24.000Z
src/main/java/org/dataone/annotator/generator/oa/OAAnnotationGenerator.java
DataONEorg/annotator
b4098bd927c2387f93a9bff034d50149e5d3e5fa
[ "Apache-2.0" ]
null
null
null
src/main/java/org/dataone/annotator/generator/oa/OAAnnotationGenerator.java
DataONEorg/annotator
b4098bd927c2387f93a9bff034d50149e5d3e5fa
[ "Apache-2.0" ]
null
null
null
39.611549
135
0.72396
6,491
package org.dataone.annotator.generator.oa; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dataone.annotator.generator.AnnotationGenerator; import org.dataone.annotator.matcher.ConceptItem; import org.dataone.annotator.matcher.ConceptMatcher; import org.dataone.annotator.matcher.ConceptMatcherFactory; import org.dataone.client.v2.CNode; import org.dataone.client.v2.itk.D1Client; import org.dataone.service.types.v1.Identifier; import org.ecoinformatics.datamanager.parser.Attribute; import org.ecoinformatics.datamanager.parser.DataPackage; import org.ecoinformatics.datamanager.parser.Entity; import org.ecoinformatics.datamanager.parser.Party; import org.ecoinformatics.datamanager.parser.generic.DataPackageParserInterface; import org.ecoinformatics.datamanager.parser.generic.Eml200DataPackageParser; import com.hp.hpl.jena.ontology.AllValuesFromRestriction; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.ObjectProperty; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntDocumentManager; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.Ontology; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; public class OAAnnotationGenerator extends AnnotationGenerator { private static Log log = LogFactory.getLog(OAAnnotationGenerator.class); private ConceptMatcher conceptMatcher; private ConceptMatcher orcidMatcher; /** * Constructor initializes the */ public OAAnnotationGenerator() { super(); // initialize the concept matcher impl we will use conceptMatcher = ConceptMatcherFactory.getMatcher(ConceptMatcherFactory.BIOPORTAL); orcidMatcher = ConceptMatcherFactory.getMatcher(ConceptMatcherFactory.ORCID); } /** * Generate annotation for given metadata identifier * @param metadataPid */ @Override public Map<Identifier, String> generateAnnotations(Identifier metadataPid) throws Exception { DataPackage dataPackage = this.getDataPackage(metadataPid); String annotationUri = "http://annotation/" + metadataPid.getValue(); Identifier annotationPid = new Identifier(); annotationPid.setValue(annotationUri); OntModel m = ModelFactory.createOntologyModel(); Ontology ont = m.createOntology(annotationUri); ont.addImport(m.createResource(oboe)); m.addSubModel(OntDocumentManager.getInstance().getModel(oboe)); ont.addImport(m.createResource(oboe_sbc)); m.addSubModel(OntDocumentManager.getInstance().getModel(oboe_sbc)); ont.addImport(m.createResource(oa)); m.addSubModel(OntDocumentManager.getInstance().getModel(oa)); ont.addImport(m.createResource(dcterms)); m.addSubModel(OntDocumentManager.getInstance().getModel(dcterms)); ont.addImport(m.createResource(foaf)); m.addSubModel(OntDocumentManager.getInstance().getModel(foaf)); ont.addImport(m.createResource(prov)); //m.addSubModel(ModelFactory.createOntologyModel().read(prov_source)); ont.addImport(m.createResource(cito)); // properties ObjectProperty hasBodyProperty = m.getObjectProperty(oa + "hasBody"); ObjectProperty hasTargetProperty = m.getObjectProperty(oa + "hasTarget"); ObjectProperty hasSourceProperty = m.getObjectProperty(oa + "hasSource"); ObjectProperty hasSelectorProperty = m.getObjectProperty(oa + "hasSelector"); ObjectProperty annotatedByProperty = m.getObjectProperty(oa + "annotatedBy"); Property identifierProperty = m.getProperty(dcterms + "identifier"); Property conformsToProperty = m.getProperty(dcterms + "conformsTo"); Property wasAttributedTo = m.getProperty(prov + "wasAttributedTo"); Property nameProperty = m.getProperty(foaf + "name"); Property rdfValue = m.getProperty(rdf + "value"); ObjectProperty ofCharacteristic = m.getObjectProperty(oboe_core + "ofCharacteristic"); ObjectProperty usesStandard = m.getObjectProperty(oboe_core + "usesStandard"); ObjectProperty ofEntity = m.getObjectProperty(oboe_core + "ofEntity"); ObjectProperty hasMeasurement = m.getObjectProperty(oboe_core + "hasMeasurement"); // classes OntClass entityClass = m.getOntClass(oboe_core + "Entity"); OntClass observationClass = m.getOntClass(oboe_core + "Observation"); OntClass measurementClass = m.getOntClass(oboe_core + "Measurement"); OntClass characteristicClass = m.getOntClass(oboe_core + "Characteristic"); OntClass standardClass = m.getOntClass(oboe_core + "Standard"); Resource annotationClass = m.getOntClass(oa + "Annotation"); Resource specificResourceClass = m.getOntClass(oa + "SpecificResource"); Resource fragmentSelectorClass = m.getOntClass(oa + "FragmentSelector"); Resource provEntityClass = m.getResource(prov + "Entity"); Resource personClass = m.getResource(prov + "Person"); // these apply to every attribute annotation Individual meta1 = m.createIndividual(ont.getURI() + "#meta", provEntityClass); meta1.addProperty(identifierProperty, metadataPid.getValue()); // decide who should be credited with the package Individual p1 = null; // look up creators from the EML metadata List<Party> creators = dataPackage.getCreators(); //creators = Arrays.asList("Matthew Jones"); if (creators != null && creators.size() > 0) { // use an orcid if we can find one from their system String creatorText = creators.get(0).getOrganization() + " " + creators.get(0).getSurName() + " " + creators.get(0).getGivenNames(); List<ConceptItem> concepts = orcidMatcher.getConcepts(creatorText, null, null); if (concepts != null) { String orcidUri = concepts.get(0).getUri().toString(); p1 = m.createIndividual(orcidUri, personClass); p1.addProperty(identifierProperty, orcidUri); } else { p1 = m.createIndividual(ont.getURI() + "#person", personClass); } // include the name we have in the metadata if (creators.get(0).getSurName() != null) { p1.addProperty(nameProperty, creators.get(0).getSurName()); } else if (creators.get(0).getOrganization() != null) { p1.addProperty(nameProperty, creators.get(0).getOrganization()); } } // attribute the package to this creator if we have one if (p1 != null) { meta1.addProperty(wasAttributedTo, p1); } // loop through the tables and attributes int entityCount = 1; Entity[] entities = dataPackage.getEntityList(); if (entities != null) { for (Entity entity: entities) { String entityName = entity.getName(); Individual o1 = m.createIndividual(ont.getURI() + "#observation" + entityCount, observationClass); Resource entityConcept = lookupEntity(entityClass, entity); if (entityConcept != null) { AllValuesFromRestriction avfr = m.createAllValuesFromRestriction(null, ofEntity, entityConcept); o1.addOntClass(avfr); } log.debug("Entity name: " + entityName); Attribute[] attributes = entity.getAttributeList().getAttributes(); int attributeCount = 1; if (attributes != null) { for (Attribute attribute: attributes) { // for naming the individuals uniquely String cnt = entityCount + "_" + attributeCount; String attributeName = attribute.getName(); String attributeLabel = attribute.getLabel(); String attributeDefinition = attribute.getDefinition(); String attributeType = attribute.getAttributeType(); String attributeScale = attribute.getMeasurementScale(); String attributeUnitType = attribute.getUnitType(); String attributeUnit = attribute.getUnit(); String attributeDomain = attribute.getDomain().getClass().getSimpleName(); log.debug("Attribute name: " + attributeName); log.debug("Attribute label: " + attributeLabel); log.debug("Attribute definition: " + attributeDefinition); log.debug("Attribute type: " + attributeType); log.debug("Attribute scale: " + attributeScale); log.debug("Attribute unit type: " + attributeUnitType); log.debug("Attribute unit: " + attributeUnit); log.debug("Attribute domain: " + attributeDomain); // look up the characteristic or standard subclasses Resource standard = this.lookupStandard(standardClass, attribute); Resource characteristic = this.lookupCharacteristic(characteristicClass, attribute); if (standard != null || characteristic != null) { // instances Individual m1 = m.createIndividual(ont.getURI() + "#measurement" + cnt, measurementClass); Individual a1 = m.createIndividual(ont.getURI() + "#annotation" + cnt, annotationClass); Individual t1 = m.createIndividual(ont.getURI() + "#target" + cnt, specificResourceClass); String xpointer = "xpointer(/eml/dataSet/dataTable[" + entityCount + "]/attributeList/attribute[" + attributeCount + "])"; Individual s1 = m.createIndividual(ont.getURI() + "#" + xpointer, fragmentSelectorClass); s1.addLiteral(rdfValue, xpointer); s1.addProperty(conformsToProperty, "http://tools.ietf.org/rfc/rfc3023"); //s1.addProperty(conformsToProperty, "http://www.w3.org/TR/xptr/"); // statements about the annotation a1.addProperty(hasBodyProperty, m1); a1.addProperty(hasTargetProperty, t1); t1.addProperty(hasSourceProperty, meta1); t1.addProperty(hasSelectorProperty, s1); //a1.addProperty(annotatedByProperty, p1); // describe the measurement in terms of restrictions if (standard != null) { AllValuesFromRestriction avfr = m.createAllValuesFromRestriction(null, usesStandard, standard); m1.addOntClass(avfr); } if (characteristic != null) { AllValuesFromRestriction avfr = m.createAllValuesFromRestriction(null, ofCharacteristic, characteristic); m1.addOntClass(avfr); } // attach to the observation // TODO: evaluate whether the measurement can apply to the given observed entity o1.addProperty(hasMeasurement, m1); } attributeCount++; } } entityCount++; } } StringWriter sw = new StringWriter(); // only write the base model //m.write(sw, "RDF/XML-ABBREV"); m.write(sw, null); Map<Identifier, String> annotations = new HashMap<Identifier, String>(); annotations.put(annotationPid, sw.toString()); return annotations; } private Resource lookupStandard(OntClass standardClass, Attribute attribute) throws Exception { // what's our unit? String unit = attribute.getUnit().toLowerCase(); // look up the concept using the matcher List<ConceptItem> concepts = conceptMatcher.getConcepts(unit, null, null); return ResourceFactory.createResource(concepts.get(0).getUri().toString()); //return BioPortalService.lookupAnnotationClass(standardClass, unit, OBOE_SBC); } private Resource lookupCharacteristic(OntClass characteristicClass, Attribute attribute) throws Exception { // what are we looking for? String label = attribute.getLabel().toLowerCase(); String definition = attribute.getDefinition(); String text = label + " " + definition; // look up the concept using the matcher List<ConceptItem> concepts = conceptMatcher.getConcepts(text, null, null); return ResourceFactory.createResource(concepts.get(0).getUri().toString()); //return BioPortalService.lookupAnnotationClass(characteristicClass, text, OBOE_SBC); } private Resource lookupEntity(OntClass entityClass, Entity entity) throws Exception { // what's our description like? String name = entity.getName(); String definition = entity.getDefinition(); // look up the concept using the matcher List<ConceptItem> concepts = conceptMatcher.getConcepts(definition, null, null); return ResourceFactory.createResource(concepts.get(0).getUri().toString()); //return BioPortalService.lookupAnnotationClass(entityClass, definition, OBOE_SBC); } private DataPackage getDataPackage(Identifier pid) throws Exception { // get package from Member CNode cnode = D1Client.getCN(); InputStream emlStream = cnode.get(null, pid); // parse the metadata DataPackageParserInterface parser = new Eml200DataPackageParser(); parser.parse(emlStream); emlStream.close(); DataPackage dataPackage = parser.getDataPackage(); return dataPackage; } private void summarize(List<Identifier> identifiers) { for (Identifier pid: identifiers) { log.debug("Parsing pid: " + pid.getValue()); try { // get the package DataPackage dataPackage = this.getDataPackage(pid); String title = dataPackage.getTitle(); log.debug("Title: " + title); Entity[] entities = dataPackage.getEntityList(); if (entities != null) { for (Entity entity: entities) { String entityName = entity.getName(); log.debug("Entity name: " + entityName); Attribute[] attributes = entity.getAttributeList().getAttributes(); for (Attribute attribute: attributes) { String attributeName = attribute.getName(); String attributeLabel = attribute.getLabel(); String attributeDefinition = attribute.getDefinition(); String attributeType = attribute.getAttributeType(); String attributeScale = attribute.getMeasurementScale(); String attributeUnitType = attribute.getUnitType(); String attributeUnit = attribute.getUnit(); String attributeDomain = attribute.getDomain().getClass().getSimpleName(); log.debug("Attribute name: " + attributeName); log.debug("Attribute label: " + attributeLabel); log.debug("Attribute definition: " + attributeDefinition); log.debug("Attribute type: " + attributeType); log.debug("Attribute scale: " + attributeScale); log.debug("Attribute unit type: " + attributeUnitType); log.debug("Attribute unit: " + attributeUnit); log.debug("Attribute domain: " + attributeDomain); } } } } catch (Exception e) { log.warn("error parsing metadata for: " + pid.getValue(), e); } } } public static void main(String[] args) throws Exception { testGenerate(); // testSummary(); System.exit(0); } public static void testGenerate() throws Exception { Identifier metadataPid = new Identifier(); metadataPid.setValue("tao.1.4"); OAAnnotationGenerator ds = new OAAnnotationGenerator(); String rdfString = ds.generateAnnotations(metadataPid).values().iterator().next(); log.info("RDF annotation: \n" + rdfString); } public static void testSummary() throws Exception { // summarize the packages OAAnnotationGenerator ds = new OAAnnotationGenerator(); List<Identifier> identifiers = new ArrayList<Identifier>(); // TODO: populate with some ids! ds.summarize(identifiers); System.exit(0); } }
3e0f4bfc62ed78dd2f813651fe3ece57f450ee2e
2,676
java
Java
src/sim/Sim.java
cndracos/cellsociety_team19
640dbc20362f8a990d8ccc6c4498bc6c2e0f1bab
[ "MIT" ]
null
null
null
src/sim/Sim.java
cndracos/cellsociety_team19
640dbc20362f8a990d8ccc6c4498bc6c2e0f1bab
[ "MIT" ]
null
null
null
src/sim/Sim.java
cndracos/cellsociety_team19
640dbc20362f8a990d8ccc6c4498bc6c2e0f1bab
[ "MIT" ]
null
null
null
23.681416
70
0.63864
6,492
package sim; import java.util.HashMap; import java.util.Map; import java.util.Random; import cell.Cell; import grid.*; /** * This is the superclass of any simulation, which runs the simulation * based on the sim specified. It creates the corresponding grid which * interacts with its subclasses * @author charliedracos * */ public abstract class Sim { private HashMap<String, double[]> keys; private Grid grid; private Random rand; private boolean torus; /** * Constructor for the sim superclass * @param n number of rows * @param k number of cols * @param length of screen * @param width of screen * @param keys the values to be used in a specific simulation * @param grid the type of grid to be created */ public Sim (int n, int k, int length, int width, Map<String, double[]> keys, String grid, boolean torus) { this.keys = (HashMap<String, double[]>) keys; rand = new Random(); this.torus = torus; if (grid.equals("SQUARE")) { this.grid = new SquareGrid(n, k, length, width); } else if (grid.equals("TRIANGLE")) { this.grid = new TriangleGrid(n, k, length, width); } else { this.grid = new HexGrid(n, k, length, width); } } public abstract String[] getStateNames(); /** * @return the grid in the simulation */ public Grid getGrid() { return grid; } /** * @return the keys of values for a sim */ public Map<String, double[]> getKeys() { return keys; } /** * @return the rand that makes random values in generating cells */ public Random getRand() { return rand; } /** * @return the boolean if there is a torus simulation */ public boolean getTorus() { return torus; } /** * Iterates twice through the grid, once using the states to * update all cells, then setting the cells to that state * once all have been updated */ public Map<String, Double> update() { HashMap<String, Double> percentages = new HashMap<String, Double>(); for (int i = 0; i < grid.getRows(); i++) { for (int j = 0; j < grid.getCols(); j++) { grid.get(i, j).findState(); } } for (int i = 0; i < grid.getRows(); i++) { for (int j = 0; j < grid.getCols(); j++) { Cell c = grid.get(i, j); c.setState(); if (!percentages.containsKey(c.getState())) { percentages.put(c.getState(), 1.0/grid.getCols()*grid.getRows()); } else { percentages.put(c.getState(), (1.0/grid.getCols()*grid.getRows()) + percentages.get(c.getState())); } } } return percentages; } /** * initializer for any simulation */ public abstract void init(); /** * @return name of the sim being run */ public abstract String name(); }
3e0f4cf5a22f807f404fb4c90126f20588682860
911
java
Java
src/main/java/com/ems/system/service/SysRoleMenuService.java
ems-admin/ems-admin-boot
470f27b428ec2b1f033a95c6f162c39a81499b8b
[ "Apache-2.0" ]
1
2022-03-31T08:45:36.000Z
2022-03-31T08:45:36.000Z
src/main/java/com/ems/system/service/SysRoleMenuService.java
ems-admin/ems-admin-boot
470f27b428ec2b1f033a95c6f162c39a81499b8b
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ems/system/service/SysRoleMenuService.java
ems-admin/ems-admin-boot
470f27b428ec2b1f033a95c6f162c39a81499b8b
[ "Apache-2.0" ]
1
2022-01-10T08:11:55.000Z
2022-01-10T08:11:55.000Z
21.186047
64
0.635565
6,493
package com.ems.system.service; import com.ems.system.entity.SysRoleMenu; import com.ems.system.entity.dto.RoleMenuDto; import java.util.List; /** * @program: ems-admin-boot * @description: this is a interface * @author: starao * @create: 2021-11-27 14:26 **/ public interface SysRoleMenuService { /** * @Description: 通过角色ID获取对应的菜单 * @Param: [roleId] * @return: java.util.List<com.ems.system.entity.SysRoleMenu> * @Author: starao * @Date: 2021/11/27 */ List<SysRoleMenu> getMenuByRoleId(Long roleId); /** * @Description: 授权角色菜单 * @Param: [roleMenuDto] * @return: void * @Author: starao * @Date: 2021/11/27 */ void editMenuRoleByRoleId(RoleMenuDto roleMenuDto); /** * @Description: 删除与角色绑定的菜单 * @Param: [roleId] * @return: void * @Author: starao * @Date: 2021/11/27 */ void deleteByRoleId(Long roleId); }
3e0f4dd1a3a2f72fbb422e1586402469b13b31b8
5,601
java
Java
src/test/java/com/github/drapostolos/typeparser/HelperTest.java
shisheng-1/type-parser
9c9ca197366b3d24bb0adc45d1a1f5a9647230a4
[ "MIT" ]
59
2015-03-08T04:32:10.000Z
2022-02-06T01:03:06.000Z
src/test/java/com/github/drapostolos/typeparser/HelperTest.java
shisheng-1/type-parser
9c9ca197366b3d24bb0adc45d1a1f5a9647230a4
[ "MIT" ]
5
2016-07-09T20:13:39.000Z
2020-08-02T22:12:41.000Z
src/test/java/com/github/drapostolos/typeparser/HelperTest.java
shisheng-1/type-parser
9c9ca197366b3d24bb0adc45d1a1f5a9647230a4
[ "MIT" ]
15
2015-02-26T11:39:46.000Z
2021-11-11T12:00:56.000Z
31.466292
109
0.649348
6,494
package com.github.drapostolos.typeparser; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.net.URL; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; public class HelperTest extends TestBase { @Test public void canDecideIfRawTargetClassIsWithinAListOfRawTargetClassesWhenItIs() throws Exception { // given Class<?> type = Integer.class; Helper helper = new Helper(new TargetType(type)) {}; // when assertThat(helper.isRawTargetClassAnyOf(Integer.class, String.class)).isTrue(); } @Test public void canDecideIfRawTargetClassIsWithinAListOfRawTargetClassesWhenItIsNot() throws Exception { // given Class<?> type = Integer.class; Helper helper = new Helper(new TargetType(type)) {}; // when assertThat(helper.isRawTargetClassAnyOf(File.class, String.class)).isFalse(); } @Test public void toStringPrintsSameAsTypeToString() throws Exception { // given final GenericType<?> genType = new GenericType<String>() {}; setInputPreprocessor(new InputPreprocessor() { @Override public String prepare(String input, InputPreprocessorHelper helper) { assertThat(helper.toString()).contains(genType.toString()); return input; } }); parser = builder.build(); // when assertThat(parser.parse("null", genType)).isNull(); } @Test public void canDecideTargetTypeIsInstanceOfMapWhenTargetTypeIsMap() throws Exception { // given Type type = new GenericType<Map<String, URL>>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; // when assertThat(helper.isTargetTypeAssignableTo(Map.class)).isTrue(); } @Test public void canDecideTargetTypeIsNotAssignableToMapWhenTargetTypeIsList() throws Exception { // given Type type = new GenericType<List<String>>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; // when assertThat(helper.isTargetTypeAssignableTo(Map.class)).isFalse(); } @Test public void canDecideTargetTypeIsAssignableToSuperClassWhenTargetTypeIsSubclass() throws Exception { // given Type type = new GenericType<Integer>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; // when assertThat(helper.isTargetTypeAssignableTo(Number.class)).isTrue(); } @Test public void canDecideTargetTypeIsEqualToStringWhenTargetTypeIsString() throws Exception { // given Type type = new GenericType<String>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; // when assertThat(helper.isTargetTypeEqualTo(String.class)).isTrue(); } @Test public void canDecideTargetTypeIsNotEqualToStringWhenTargetTypeIsInteger() throws Exception { // given Type type = new GenericType<Integer>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; // when assertThat(helper.isTargetTypeEqualTo(String.class)).isFalse(); } @Test public void canDecideTargetTypeIsEqualToListOfStringWhenTargetTypeIsListOfString() throws Exception { // given Type type = new GenericType<List<String>>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; // when assertThat(helper.isTargetTypeEqualTo(new GenericType<List<String>>() {})).isTrue(); } @Test public void canDecideTargetTypeIsNotEqualToListOfStringWhenTargetTypeIsListOfInteger() throws Exception { // given Type type = new GenericType<List<String>>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; // when GenericType<List<Integer>> listOfInteger = new GenericType<List<Integer>>() {}; assertThat(helper.isTargetTypeEqualTo(listOfInteger)).isFalse(); } @Test public void canGetRawClassWhenTargetTypeIsClass() throws Exception { // given Type type = new GenericType<Integer>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; // when assertThat(helper.getRawTargetClass()).isSameAs(Integer.class); } @Test public void canGetRawClassWhenTargetTypeIsGenericType() throws Exception { // given Type type = new GenericType<Set<Integer>>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; // when assertThat(helper.getRawTargetClass()).isSameAs(Set.class); } @Test public <T> void canGetRawClassWhenTargetTypeIsGenericArray() throws Exception { // given Type type = new GenericType<String[]>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; // then assertThat(helper.getRawTargetClass()).isSameAs(String[].class); } @Test public <T> void canGetRawClassWhenTargetTypeIsGenericArrayOfParameterizedType() throws Exception { // given Type type = new GenericType<Class<?>[]>() {}.getType(); Helper helper = new Helper(new TargetType(type)) {}; Method m = getClass().getDeclaredMethod("m2"); // then assertThat(helper.getRawTargetClass()).isSameAs(m.getReturnType()); } Class<?>[] m2() { return null; } }
3e0f4e5620c957c1a4e54cc95a34cc757fb86bda
500
java
Java
test/org/traccar/protocol/TopflytechProtocolDecoderTest.java
alisol911/traccar
2841fc55a7b2f865f92d69a5bcf5897130ea4201
[ "Apache-2.0" ]
4
2020-05-09T11:43:47.000Z
2022-02-16T05:05:08.000Z
test/org/traccar/protocol/TopflytechProtocolDecoderTest.java
alisol911/traccar
2841fc55a7b2f865f92d69a5bcf5897130ea4201
[ "Apache-2.0" ]
2
2018-08-16T05:34:41.000Z
2018-12-25T02:46:17.000Z
test/org/traccar/protocol/TopflytechProtocolDecoderTest.java
alisol911/traccar
2841fc55a7b2f865f92d69a5bcf5897130ea4201
[ "Apache-2.0" ]
2
2020-11-26T13:27:14.000Z
2022-03-20T02:12:55.000Z
26.315789
135
0.768
6,495
package org.traccar.protocol; import org.junit.Test; import org.traccar.ProtocolTest; public class TopflytechProtocolDecoderTest extends ProtocolTest { @Test public void testDecode() throws Exception { TopflytechProtocolDecoder decoder = new TopflytechProtocolDecoder(new TopflytechProtocol()); verifyPosition(decoder, text( "(880316890094910BP00XG00b600000000L00074b54S00000000R0C0F0014000100f0130531152205A0706.1395S11024.0965E000.0251.25")); } }
3e0f4ef2e93010d40c4ebf49c7b0ec34e9efea38
407
java
Java
src/main/java/com/onurkus/graduationproject/customer/dto/CustomerDto.java
onurkus7/n11-talenthub-bootcamp-graduation-project-onurkus7
fd5d0566a0ef64d2c2c157ec0fa1dee94fa35973
[ "MIT" ]
null
null
null
src/main/java/com/onurkus/graduationproject/customer/dto/CustomerDto.java
onurkus7/n11-talenthub-bootcamp-graduation-project-onurkus7
fd5d0566a0ef64d2c2c157ec0fa1dee94fa35973
[ "MIT" ]
null
null
null
src/main/java/com/onurkus/graduationproject/customer/dto/CustomerDto.java
onurkus7/n11-talenthub-bootcamp-graduation-project-onurkus7
fd5d0566a0ef64d2c2c157ec0fa1dee94fa35973
[ "MIT" ]
1
2022-03-22T15:34:11.000Z
2022-03-22T15:34:11.000Z
19.380952
51
0.756757
6,496
package com.onurkus.graduationproject.customer.dto; import lombok.Data; import java.math.BigDecimal; import java.util.Date; @Data public class CustomerDto { private Long id; private Long identityId; private Date registrationDate; private String fullName; private Date birthdayDate; private String phoneNumber; private BigDecimal salary; private BigDecimal collateral; }
3e0f4efe0c842079469a0b3317c66ad9d43240e1
1,796
java
Java
cloud-repository/src/main/java/cn/threefishes/cloudrepository/entity/GoodsBrowse.java
threefishes/springCloudMainService
9b20cf8a955cc0e7f52e1a0550dac385866369f4
[ "MIT" ]
null
null
null
cloud-repository/src/main/java/cn/threefishes/cloudrepository/entity/GoodsBrowse.java
threefishes/springCloudMainService
9b20cf8a955cc0e7f52e1a0550dac385866369f4
[ "MIT" ]
9
2019-11-04T01:34:21.000Z
2022-02-01T01:00:16.000Z
cloud-repository/src/main/java/cn/threefishes/cloudrepository/entity/GoodsBrowse.java
threefishes/springCloudMainService
9b20cf8a955cc0e7f52e1a0550dac385866369f4
[ "MIT" ]
1
2022-03-29T07:44:37.000Z
2022-03-29T07:44:37.000Z
21.129412
63
0.673719
6,497
package cn.threefishes.cloudrepository.entity; import java.util.Date; public class GoodsBrowse { private Integer browseId; private Date addTime; private Integer commonId; private Integer goodsCategoryid; private Integer goodsCategoryid1; private Integer goodsCategoryid2; private Integer goodsCategoryid3; private Integer memberId; public Integer getBrowseId() { return browseId; } public void setBrowseId(Integer browseId) { this.browseId = browseId; } public Date getAddTime() { return addTime; } public void setAddTime(Date addTime) { this.addTime = addTime; } public Integer getCommonId() { return commonId; } public void setCommonId(Integer commonId) { this.commonId = commonId; } public Integer getGoodsCategoryid() { return goodsCategoryid; } public void setGoodsCategoryid(Integer goodsCategoryid) { this.goodsCategoryid = goodsCategoryid; } public Integer getGoodsCategoryid1() { return goodsCategoryid1; } public void setGoodsCategoryid1(Integer goodsCategoryid1) { this.goodsCategoryid1 = goodsCategoryid1; } public Integer getGoodsCategoryid2() { return goodsCategoryid2; } public void setGoodsCategoryid2(Integer goodsCategoryid2) { this.goodsCategoryid2 = goodsCategoryid2; } public Integer getGoodsCategoryid3() { return goodsCategoryid3; } public void setGoodsCategoryid3(Integer goodsCategoryid3) { this.goodsCategoryid3 = goodsCategoryid3; } public Integer getMemberId() { return memberId; } public void setMemberId(Integer memberId) { this.memberId = memberId; } }
3e0f5050eed2349220822cdecc10fb56d877f1eb
1,369
java
Java
gwt/vmchecker-gui/src/ro/pub/cs/vmchecker/client/ui/StatementWidget.java
calin-iorgulescu/vmchecker
050ec96495974f76c615e827ea68e2fc6430b1e9
[ "MIT" ]
19
2015-08-31T22:53:45.000Z
2020-07-15T12:02:13.000Z
gwt/vmchecker-gui/src/ro/pub/cs/vmchecker/client/ui/StatementWidget.java
calin-iorgulescu/vmchecker
050ec96495974f76c615e827ea68e2fc6430b1e9
[ "MIT" ]
28
2015-01-18T13:26:47.000Z
2021-06-29T13:51:09.000Z
gwt/vmchecker-gui/src/ro/pub/cs/vmchecker/client/ui/StatementWidget.java
calin-iorgulescu/vmchecker
050ec96495974f76c615e827ea68e2fc6430b1e9
[ "MIT" ]
16
2015-04-20T06:04:22.000Z
2017-04-15T19:39:54.000Z
27.938776
78
0.810811
6,498
package ro.pub.cs.vmchecker.client.ui; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Widget; import ro.pub.cs.vmchecker.client.presenter.AssignmentBoardPresenter; import ro.pub.cs.vmchecker.client.i18n.StatementConstants; public class StatementWidget extends Composite implements AssignmentBoardPresenter.StatementWidget { private static StatementWidgetUiBinder uiBinder = GWT .create(StatementWidgetUiBinder.class); private static StatementConstants constants = GWT.create( StatementConstants.class); interface StatementWidgetUiBinder extends UiBinder<Widget, StatementWidget> { } @UiField FlowPanel container; @UiField HTML statementDescription; @UiField Anchor statementAnchor; public StatementWidget() { initWidget(uiBinder.createAndBindUi(this)); statementDescription.setHTML(constants.statementDescription()); statementAnchor.setText(constants.statementLinkText()); statementAnchor.setTarget("_new"); } @Override public void setStatementHref(String statementHref) { statementAnchor.setHref(statementHref); } }
3e0f50cc487b9aba262687cf6bdafec6fed38404
415
java
Java
biblioteca3.0/src/bibliotecaUFMA/funcionario.java
Weked/JUnit_Test_Exercise
8a464835d05823813a6653755842f6c65f9a126d
[ "Apache-2.0" ]
null
null
null
biblioteca3.0/src/bibliotecaUFMA/funcionario.java
Weked/JUnit_Test_Exercise
8a464835d05823813a6653755842f6c65f9a126d
[ "Apache-2.0" ]
null
null
null
biblioteca3.0/src/bibliotecaUFMA/funcionario.java
Weked/JUnit_Test_Exercise
8a464835d05823813a6653755842f6c65f9a126d
[ "Apache-2.0" ]
null
null
null
20.75
89
0.720482
6,499
package bibliotecaUFMA; public class funcionario extends pessoa { private int matricula; funcionario(String nomeX, String sobrenomeX, long cpfX, conta contaX, int matriculaX) { super(nomeX, sobrenomeX, cpfX, contaX); this.setMatricula(matriculaX); } public int getMatriculo(){ return this.matricula; } public void setMatricula(int matriculaX){ this.matricula = matriculaX; } }
3e0f513633770daf096595d34b0044bb7f6eb33c
6,999
java
Java
logback/src/main/java/com/linecorp/armeria/common/logback/RequestContextExporterBuilder.java
SooJungDev/armeria
641c5d3fcf28ceaf82493c6cb0459ddee97c946b
[ "Apache-2.0" ]
1
2019-07-16T11:59:54.000Z
2019-07-16T11:59:54.000Z
logback/src/main/java/com/linecorp/armeria/common/logback/RequestContextExporterBuilder.java
tigerwk110/armeria
40d8367bc0640a932f86062381e35108844d7c63
[ "Apache-2.0" ]
null
null
null
logback/src/main/java/com/linecorp/armeria/common/logback/RequestContextExporterBuilder.java
tigerwk110/armeria
40d8367bc0640a932f86062381e35108844d7c63
[ "Apache-2.0" ]
1
2021-12-07T09:46:39.000Z
2021-12-07T09:46:39.000Z
38.038043
110
0.655236
6,500
/* * Copyright 2016 LINE Corporation * * LINE Corporation 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: * * 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 com.linecorp.armeria.common.logback; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static java.util.Objects.requireNonNull; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import com.linecorp.armeria.common.HttpHeaderNames; import com.linecorp.armeria.common.logback.RequestContextExporter.ExportEntry; import io.netty.util.AsciiString; import io.netty.util.AttributeKey; final class RequestContextExporterBuilder { private static final String PREFIX_ATTRS = "attrs."; private static final String PREFIX_HTTP_REQ_HEADERS = "req.http_headers."; private static final String PREFIX_HTTP_RES_HEADERS = "res.http_headers."; private final Set<BuiltInProperty> builtIns = EnumSet.noneOf(BuiltInProperty.class); private final Set<ExportEntry<AttributeKey<?>>> attrs = new HashSet<>(); private final Set<ExportEntry<AsciiString>> httpReqHeaders = new HashSet<>(); private final Set<ExportEntry<AsciiString>> httpResHeaders = new HashSet<>(); void addBuiltIn(BuiltInProperty property) { builtIns.add(requireNonNull(property, "property")); } boolean containsBuiltIn(BuiltInProperty property) { return builtIns.contains(requireNonNull(property, "property")); } Set<BuiltInProperty> getBuiltIns() { return Collections.unmodifiableSet(builtIns); } void addAttribute(String alias, AttributeKey<?> attrKey) { requireNonNull(alias, "alias"); requireNonNull(attrKey, "attrKey"); attrs.add(new ExportEntry<>(attrKey, PREFIX_ATTRS + alias, null)); } void addAttribute(String alias, AttributeKey<?> attrKey, Function<?, String> stringifier) { requireNonNull(alias, "alias"); requireNonNull(attrKey, "attrKey"); requireNonNull(stringifier, "stringifier"); attrs.add(new ExportEntry<>(attrKey, PREFIX_ATTRS + alias, stringifier)); } boolean containsAttribute(AttributeKey<?> key) { requireNonNull(key, "key"); return attrs.stream().anyMatch(e -> e.key.equals(key)); } Map<String, AttributeKey<?>> getAttributes() { return Collections.unmodifiableMap(attrs.stream().collect( Collectors.toMap(e -> e.mdcKey.substring(PREFIX_ATTRS.length()), e -> e.key))); } void addHttpRequestHeader(CharSequence name) { addHttpHeader(PREFIX_HTTP_REQ_HEADERS, httpReqHeaders, name); } void addHttpResponseHeader(CharSequence name) { addHttpHeader(PREFIX_HTTP_RES_HEADERS, httpResHeaders, name); } private static void addHttpHeader( String mdcKeyPrefix, Set<ExportEntry<AsciiString>> httpHeaders, CharSequence name) { final AsciiString key = toHeaderName(name); final String value = mdcKeyPrefix + key; httpHeaders.add(new ExportEntry<>(key, value, null)); } boolean containsHttpRequestHeader(CharSequence name) { return httpReqHeaders.stream().anyMatch(e -> e.key.contentEqualsIgnoreCase(name)); } boolean containsHttpResponseHeader(CharSequence name) { return httpResHeaders.stream().anyMatch(e -> e.key.contentEqualsIgnoreCase(name)); } private static AsciiString toHeaderName(CharSequence name) { return HttpHeaderNames.of(requireNonNull(name, "name").toString()); } Set<AsciiString> getHttpRequestHeaders() { return httpReqHeaders.stream().map(e -> e.key).collect(toImmutableSet()); } Set<AsciiString> getHttpResponseHeaders() { return httpResHeaders.stream().map(e -> e.key).collect(toImmutableSet()); } void export(String mdcKey) { requireNonNull(mdcKey, "mdcKey"); final List<BuiltInProperty> builtInPropertyList = BuiltInProperty.findByMdcKeyPattern(mdcKey); if (!builtInPropertyList.isEmpty()) { builtIns.addAll(builtInPropertyList); return; } if (mdcKey.contains(BuiltInProperty.WILDCARD_STR)) { return; } if (mdcKey.startsWith(PREFIX_ATTRS)) { final String[] components = mdcKey.split(":"); switch (components.length) { case 2: addAttribute(components[0].substring(PREFIX_ATTRS.length()), AttributeKey.valueOf(components[1])); break; case 3: final Function<?, String> stringifier = newStringifier(mdcKey, components[2]); addAttribute(components[0].substring(PREFIX_ATTRS.length()), AttributeKey.valueOf(components[1]), stringifier); break; default: throw new IllegalArgumentException( "invalid attribute export: " + mdcKey + " (expected: attrs.<alias>:<AttributeKey.name>[:<FQCN of Function<?, String>>])"); } return; } if (mdcKey.startsWith(PREFIX_HTTP_REQ_HEADERS)) { addHttpRequestHeader(mdcKey.substring(PREFIX_HTTP_REQ_HEADERS.length())); return; } if (mdcKey.startsWith(PREFIX_HTTP_RES_HEADERS)) { addHttpResponseHeader(mdcKey.substring(PREFIX_HTTP_RES_HEADERS.length())); return; } throw new IllegalArgumentException("unknown MDC key: " + mdcKey); } @SuppressWarnings("unchecked") private Function<?, String> newStringifier(String mdcKey, String className) { final Function<?, String> stringifier; try { stringifier = (Function<?, String>) Class.forName(className, true, getClass().getClassLoader()) .getDeclaredConstructor() .newInstance(); } catch (Exception e) { throw new IllegalArgumentException("failed to instantiate a stringifier function: " + mdcKey, e); } return stringifier; } RequestContextExporter build() { return new RequestContextExporter(builtIns, attrs, httpReqHeaders, httpResHeaders); } }
3e0f51498f2bda46d9f1736b428d3d525d460cb4
2,467
java
Java
app/src/main/java/com/google/engedu/wordstack/StackedLayout.java
kjcoder001/WordStack_starter
30a5546b3c427e22afc3360e27ba616c913c94dd
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/google/engedu/wordstack/StackedLayout.java
kjcoder001/WordStack_starter
30a5546b3c427e22afc3360e27ba616c913c94dd
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/google/engedu/wordstack/StackedLayout.java
kjcoder001/WordStack_starter
30a5546b3c427e22afc3360e27ba616c913c94dd
[ "Apache-2.0" ]
null
null
null
26.526882
122
0.61897
6,501
/* Copyright 2016 Google 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.google.engedu.wordstack; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import java.util.Stack; public class StackedLayout extends LinearLayout { private Stack<View> tiles = new Stack(); public StackedLayout(Context context) { super(context); } /** * My code below. * push implementation for stackedLayout (analogous to stacks push). * -->The words are pushed in reverse order from onStartGame(). * -->But the user should get the letters in the same order as that of scrambledWord. Hence the push method makes sure * that the order of letters is preserved by calling removeView() and addView(). * @param tile */ public void push(View tile) { if(!tiles.empty()) { removeView(tiles.peek()); } tiles.push(tile); addView(tile); } /** * My code below. * --> pop() is called from LetterTile.moveViewtoGroup() method. * --> It is used to implement the logic of frozen and unfrozen tiles. * @return */ public View pop() { View popped=null; // To avoid crashes.Takes care of test cases . if(!tiles.isEmpty()) popped=tiles.pop(); removeView(popped); if(!tiles.empty()) addView(tiles.peek()); return popped; } public View peek() { return tiles.peek(); } public boolean empty() { return tiles.empty(); } /** * My code below. * clear() is used to erase the current word and game and is called before initializing a new game. */ public void clear() { if(!tiles.isEmpty()) removeView(tiles.peek()); tiles.clear(); } }
3e0f515aa7d3861920d8b902a59d5f6f6c673308
12,848
java
Java
generator/src/test/java/com/graphicsfuzz/generator/tool/GenerateTest.java
porames25/graphicsfuzz
ab3c44b90c7a14acf8ea1df48bf799a4a1270789
[ "Apache-2.0" ]
1
2018-12-13T16:37:46.000Z
2018-12-13T16:37:46.000Z
generator/src/test/java/com/graphicsfuzz/generator/tool/GenerateTest.java
porames25/graphicsfuzz
ab3c44b90c7a14acf8ea1df48bf799a4a1270789
[ "Apache-2.0" ]
null
null
null
generator/src/test/java/com/graphicsfuzz/generator/tool/GenerateTest.java
porames25/graphicsfuzz
ab3c44b90c7a14acf8ea1df48bf799a4a1270789
[ "Apache-2.0" ]
null
null
null
34.44504
188
0.61496
6,502
/* * Copyright 2018 The GraphicsFuzz Project 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 com.graphicsfuzz.generator.tool; import com.graphicsfuzz.common.ast.TranslationUnit; import com.graphicsfuzz.common.ast.decl.VariablesDeclaration; import com.graphicsfuzz.common.glslversion.ShadingLanguageVersion; import com.graphicsfuzz.common.transformreduce.ShaderJob; import com.graphicsfuzz.common.util.ListConcat; import com.graphicsfuzz.common.util.ParseHelper; import com.graphicsfuzz.common.util.ParseTimeoutException; import com.graphicsfuzz.common.util.RandomWrapper; import com.graphicsfuzz.common.util.ShaderJobFileOperations; import com.graphicsfuzz.common.util.ShaderKind; import com.graphicsfuzz.generator.transformation.donation.DonateLiveCode; import com.graphicsfuzz.generator.util.GenerationParams; import com.graphicsfuzz.generator.util.TransformationProbabilities; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.sourceforge.argparse4j.inf.ArgumentParserException; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class GenerateTest { public static final String A_VERTEX_SHADER = "" + "layout(location=0) in highp vec4 a_position;" + "float foo(float b) {" + " for (int i = 0; i < 10; i++) {" + " b += float(i);" + " }" + " return b;" + "}" + "" + "void main()" + "{\n" + " float x = 0.0;" + " int a;" + " a = 100;" + " while (a > 0) {" + " a = a - 2;" + " x += foo(x);" + " }" + " vec2 iAmAVertexShader;" + "}"; public static final String EMPTY_JSON = "{\n" + "}"; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test public void testSynthetic() throws Exception { ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); // TODO: Use fileOps more. final String program = "layout(location=0) out highp vec4 _GLF_color;" + "uniform vec2 injectionSwitch;\n" + "\n" + "void main()\n" + "{\n" + " int r;\n" + " int g;\n" + " int b;\n" + " int a;\n" + " r = 100 * int(injectionSwitch.y);\n" + " g = int(injectionSwitch.x) * int(injectionSwitch.y);\n" + " b = 2 * int(injectionSwitch.x);\n" + " a = g - int(injectionSwitch.x);\n" + " for(\n" + " int i = 0;\n" + " i < 10;\n" + " i ++\n" + " )\n" + " {\n" + " r --;\n" + " g ++;\n" + " b ++;\n" + " a ++;\n" + " for(\n" + " int j = 1;\n" + " j < 10;\n" + " j ++\n" + " )\n" + " {\n" + " a ++;\n" + " b ++;\n" + " g ++;\n" + " r --;\n" + " }\n" + " }\n" + " float fr;\n" + " float fg;\n" + " float fb;\n" + " float fa;\n" + " fr = float(r / 100);\n" + " fg = float(g / 100);\n" + " fb = float(b / 100);\n" + " fa = float(a / 100);\n" + " _GLF_color = vec4(r, g, b, a);\n" + "}\n"; final String json = "{\n" + " \"injectionSwitch\": {\n" + " \"func\": \"glUniform2f\",\n" + " \"args\": [\n" + " 0.0,\n" + " 1.0\n" + " ]\n" + " }\n" + "}"; File shaderFile = temporaryFolder.newFile("shader.frag"); File jsonFile = temporaryFolder.newFile("shader.json"); FileUtils.writeStringToFile(shaderFile, program, StandardCharsets.UTF_8); FileUtils.writeStringToFile(jsonFile, json, StandardCharsets.UTF_8); File outputDir = temporaryFolder.getRoot(); File outputShaderJobFile = new File(outputDir, "output.json"); File donors = temporaryFolder.newFolder("donors"); Generate.mainHelper(new String[]{"--seed", "0", jsonFile.toString(), donors.toString(), "300 es", outputShaderJobFile.toString(), }); fileOps.areShadersValid(outputShaderJobFile, true); } @Test public void testStructDonation() throws Exception { final String usesStruct = "struct A { int x; }; void main() { { A a = A(1); a.x = 2; } }"; File donorsFolder = temporaryFolder.newFolder(); for (int i = 0; i < 10; i++) { File donor = new File( Paths.get(donorsFolder.getAbsolutePath(), "donor" + i + ".frag").toString()); BufferedWriter bw = new BufferedWriter(new FileWriter(donor)); bw.write(usesStruct); bw.close(); } String reference = "void main() { ; { ; ; ; }; ; { ; ; ; }; ; ; ; ; ; ; }"; TranslationUnit tu = ParseHelper.parse(reference); new DonateLiveCode(TransformationProbabilities.likelyDonateLiveCode()::donateLiveCodeAtStmt, donorsFolder, GenerationParams.normal(ShaderKind.FRAGMENT, true), false) .apply(tu, TransformationProbabilities.likelyDonateLiveCode(), ShadingLanguageVersion.ESSL_100, new RandomWrapper(0), GenerationParams.normal(ShaderKind.FRAGMENT, true)); } @Test public void testFragVertAndUniformsPassedThrough() throws Exception { ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); // TODO: Use fileOps more. final String dummyFragment = "void main()\n" + "{\n" + " float iAmAFragmentShader;" + "}\n"; final String dummyVertex = "void main()\n" + "{\n" + " float iAmAVertexShader;" + "}\n"; final String json = "{\n" + "}"; File fragmentShaderFile = temporaryFolder.newFile("shader.frag"); File vertexShaderFile = temporaryFolder.newFile("shader.vert"); File jsonFile = temporaryFolder.newFile("shader.json"); BufferedWriter bw = new BufferedWriter(new FileWriter(fragmentShaderFile)); bw.write(dummyFragment); bw.close(); bw = new BufferedWriter(new FileWriter(vertexShaderFile)); bw.write(dummyVertex); bw.close(); bw = new BufferedWriter(new FileWriter(jsonFile)); bw.write(json); bw.close(); File outputDir = temporaryFolder.getRoot(); File outputShaderJobFile = new File(outputDir, "output.json"); File donors = temporaryFolder.newFolder("donors"); Generate.mainHelper(new String[]{"--seed", "0", jsonFile.toString(), donors.toString(), "100", outputShaderJobFile.toString() }); fileOps.areShadersValid(outputShaderJobFile, true); assertTrue( fileOps .getShaderContents(outputShaderJobFile, ShaderKind.FRAGMENT) .contains("iAmAFragmentShader") ); assertTrue( fileOps .getShaderContents(outputShaderJobFile, ShaderKind.VERTEX) .contains("iAmAVertexShader") ); } @Test public void testValidityOfVertexShaderTransformations() throws Exception { testValidityOfVertexShaderTransformations(new ArrayList<>(), 0); } @Test public void testValidityOfVertexShaderJumpTransformations() throws Exception { testValidityOfVertexShaderTransformations(Arrays.asList("--enable_only", "jump"), 5); } private void testValidityOfVertexShaderTransformations(List<String> extraArgs, int repeatCount) throws IOException, InterruptedException, ParseTimeoutException, ArgumentParserException { ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); // TODO: Use fileOps more. File vertexShaderFile = temporaryFolder.newFile("shader.vert"); File jsonFile = temporaryFolder.newFile("shader.json"); FileUtils.writeStringToFile(vertexShaderFile, A_VERTEX_SHADER, StandardCharsets.UTF_8); FileUtils.writeStringToFile(jsonFile, EMPTY_JSON, StandardCharsets.UTF_8); final File outputDir = temporaryFolder.getRoot(); final File outputShaderJobFile = new File(outputDir, "output.json"); final File donors = temporaryFolder.newFolder("donors"); for (int seed = 0; seed < repeatCount; seed++) { final List<String> args = new ArrayList<>(); args.addAll( Arrays.asList( "--seed", Integer.toString(seed), jsonFile.toString(), donors.toString(), "300 es", outputShaderJobFile.toString() ) ); args.addAll(extraArgs); Generate.mainHelper(args.toArray(new String[0])); assertTrue( fileOps .getShaderContents(outputShaderJobFile, ShaderKind.VERTEX) .contains("iAmAVertexShader") ); fileOps.areShadersValid(outputShaderJobFile, true); } } @Test public void testInjectionSwitchAddedByDefault() throws Exception { final ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); final String program = "#version 100\n" + "void main() {" + " int x = 0;" + " for (int i = 0; i < 100; i++) {" + " x = x + i;" + " }" + "}"; final String uniforms = "{}"; final File json = temporaryFolder.newFile("shader.json"); final File frag = temporaryFolder.newFile("shader.frag"); FileUtils.writeStringToFile(frag, program, StandardCharsets.UTF_8); FileUtils.writeStringToFile(json, uniforms, StandardCharsets.UTF_8); final File donors = temporaryFolder.newFolder(); final File output = temporaryFolder.newFile("output.json"); Generate.mainHelper(new String[] { json.getAbsolutePath(), donors.getAbsolutePath(), "100", output.getAbsolutePath(), "--seed", "0" }); final ShaderJob shaderJob = fileOps.readShaderJobFile(output); assertTrue(shaderJob.getUniformsInfo().containsKey("injectionSwitch")); assertTrue(fileOps.areShadersValid(output, false)); assertTrue(shaderJob.getShaders().get(0).getTopLevelDeclarations() .stream() .filter(item -> item instanceof VariablesDeclaration) .map(item -> ((VariablesDeclaration) item).getDeclInfos()) .reduce(new ArrayList<>(), ListConcat::concatenate) .stream() .map(item -> item.getName()) .anyMatch(item -> item.equals("injectionSwitch"))); } @Test public void testNoInjectionSwitchIfDisabled() throws Exception { final ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); final String program = "#version 100\n" + "void main() {" + " int x = 0;" + " for (int i = 0; i < 100; i++) {" + " x = x + i;" + " }" + "}"; final String uniforms = "{}"; final File json = temporaryFolder.newFile("shader.json"); final File frag = temporaryFolder.newFile("shader.frag"); FileUtils.writeStringToFile(frag, program, StandardCharsets.UTF_8); FileUtils.writeStringToFile(json, uniforms, StandardCharsets.UTF_8); final File donors = temporaryFolder.newFolder(); final File output = temporaryFolder.newFile("output.json"); Generate.mainHelper(new String[] { json.getAbsolutePath(), donors.getAbsolutePath(), "100", output.getAbsolutePath(), "--no_injection_switch", "--seed", "0" }); final ShaderJob shaderJob = fileOps.readShaderJobFile(output); assertFalse(shaderJob.getUniformsInfo().containsKey("injectionSwitch")); assertTrue(fileOps.areShadersValid(output, false)); assertFalse(shaderJob.getShaders().get(0).getTopLevelDeclarations() .stream() .filter(item -> item instanceof VariablesDeclaration) .map(item -> ((VariablesDeclaration) item).getDeclInfos()) .reduce(new ArrayList<>(), ListConcat::concatenate) .stream() .map(item -> item.getName()) .anyMatch(item -> item.equals("injectionSwitch"))); } }
3e0f5242952e3de3955d9cc691aafd6a87b72d15
1,024
java
Java
workspace_BOS/billing-api/billing-service/web-service_09_28_16/src/main/java/com/api/billing/model/product/ProductInput.java
billingoss/product_202002
7f579b2c0f45d86ffbca208d0904408089968031
[ "Apache-2.0" ]
null
null
null
workspace_BOS/billing-api/billing-service/web-service_09_28_16/src/main/java/com/api/billing/model/product/ProductInput.java
billingoss/product_202002
7f579b2c0f45d86ffbca208d0904408089968031
[ "Apache-2.0" ]
null
null
null
workspace_BOS/billing-api/billing-service/web-service_09_28_16/src/main/java/com/api/billing/model/product/ProductInput.java
billingoss/product_202002
7f579b2c0f45d86ffbca208d0904408089968031
[ "Apache-2.0" ]
null
null
null
21.787234
52
0.756836
6,503
package com.api.billing.model.product; import com.api.model.Criteria; public class ProductInput extends Criteria { private String productId; private String productType; private String productName; /*ID mapping*/ private String username; private int providernumber; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getProvidernumber() { return providernumber; } public void setProvidernumber(int providernumber) { this.providernumber = providernumber; } /*ID mapping*/ public String getProductType() { return productType; } public String getProductName() { return productName; } public String getProductId(String productId) { return productId; } public void setProductType(String productType) { this.productType = productType; } public void setProductName(String productName) { this.productName = productName; } public void setProductId(String productId) { this.productId = productId; } }
3e0f524aa90562140b34482191ef9cfed46d3766
3,881
java
Java
rs3 files/876 Deob Less Renamed/source/com/jagex/Class325.java
emcry666/project-scape
827d213f129a9fd266cf42e7412402609191c484
[ "Apache-2.0" ]
null
null
null
rs3 files/876 Deob Less Renamed/source/com/jagex/Class325.java
emcry666/project-scape
827d213f129a9fd266cf42e7412402609191c484
[ "Apache-2.0" ]
null
null
null
rs3 files/876 Deob Less Renamed/source/com/jagex/Class325.java
emcry666/project-scape
827d213f129a9fd266cf42e7412402609191c484
[ "Apache-2.0" ]
null
null
null
43.122222
231
0.754445
6,504
/* Class325 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ package com.jagex; public class Class325 implements Interface33 { Class395 aClass395_3455; public void method208(boolean bool) { if (bool) Class31.aClass178_303.method3193(0, 0, Class170.anInt1833 * 2141365743, -495986435 * Class254.anInt2742, (aClass395_3455.anInt4057 * -668188707), 0); } public boolean method211() { return true; } public void method210(int i) { /* empty */ } public boolean method209(byte i) { return true; } Class325(Class395 class395) { aClass395_3455 = class395; } public void method213(boolean bool, short i) { if (bool) Class31.aClass178_303.method3193(0, 0, Class170.anInt1833 * 2141365743, -495986435 * Class254.anInt2742, (aClass395_3455.anInt4057 * -668188707), 0); } public void method212() { /* empty */ } static final void method5735(Class669 class669, byte i) { Class677 class677 = (class669.aBool8570 ? class669.aClass677_8566 : class669.aClass677_8574); Class250 class250 = class677.aClass250_8638; Class242 class242 = class677.aClass242_8637; Class614.method10060(class250, class242, class669, -1747863168); } static final void method5736(Class669 class669, byte i) { int i_0_ = (class669.anIntArray8557[(class669.anInt8558 -= 2138772399) * 1357652815]); Class250 class250 = Class188.method3592(i_0_, -646403547); Class242 class242 = Class31.aClass242Array302[i_0_ >> 16]; Class613.method10054(class250, class242, class669, -1448299598); } static final void method5737(Class669 class669, int i) { int i_1_ = (class669.anIntArray8557[(class669.anInt8558 -= 2138772399) * 1357652815]); Class239 class239 = ((Class239) Class287.aClass53_Sub1_3102.getDefinition(i_1_, (byte) -14)); class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = 1444609703 * class239.anInt2443; } static String method5738(int i, Class668 class668, Class625 class625, int i_2_) { if (i < 100000) return new StringBuilder().append(Class288.method5163(114388337 * class625.anInt8138, -183686774)).append(i).append(ItemDefinitions.aString171).toString(); if (i < 10000000) return new StringBuilder().append(Class288.method5163(class625.anInt8161 * -1459907571, -688943909)).append(i / 1000).append(Class39.aClass39_520.method1124(class668, (byte) -102)).append(ItemDefinitions.aString171).toString(); return new StringBuilder().append(Class288.method5163(class625.anInt8162 * 2086406891, -327165512)).append(i / 1000000).append(Class39.aClass39_518.method1124(class668, (byte) -107)).append(ItemDefinitions.aString171).toString(); } public static final void method5739(boolean bool, int i) { Class523_Sub22 class523_sub22 = Class523_Sub18.method16042(OutgoingPacket.CLOSE_INTERFACE_PACKET, client.aClass116_11058.aClass11_1413, 1370050649); client.aClass116_11058.method1974(class523_sub22, (byte) 98); for (Class523_Sub36 class523_sub36 = ((Class523_Sub36) client.aClass14_11187.method735(-380907255)); null != class523_sub36; class523_sub36 = ((Class523_Sub36) client.aClass14_11187.method749(60817144))) { if (!class523_sub36.method8660(-264166446)) { class523_sub36 = ((Class523_Sub36) client.aClass14_11187.method735(-380907255)); if (class523_sub36 == null) break; } if (class523_sub36.anInt10667 * -1502434839 == 0) Class579.method9657(class523_sub36, true, bool, -1982424981); } if (null != client.aClass250_11189) { Class523_Sub14.method15991(client.aClass250_11189, (byte) -127); client.aClass250_11189 = null; } } static final void method5740(Class669 class669, int i) { int i_3_ = (class669.anIntArray8557[(class669.anInt8558 -= 2138772399) * 1357652815]); class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = Class449.aClass523_Sub33_4946.aClass687_Sub21_10604.method13890(i_3_, 1912523630); } }
3e0f52aa9a2a381a9ef06dd8e42d0832c2a1d345
296
java
Java
src/test/java/com/theleapofcode/algosandds/recursion/TestTowerOfHanoi.java
theleapofcode/algorithms-data-structures-java
baccbb314b4116c5844c9133e8a6d28182c98aee
[ "MIT" ]
null
null
null
src/test/java/com/theleapofcode/algosandds/recursion/TestTowerOfHanoi.java
theleapofcode/algorithms-data-structures-java
baccbb314b4116c5844c9133e8a6d28182c98aee
[ "MIT" ]
null
null
null
src/test/java/com/theleapofcode/algosandds/recursion/TestTowerOfHanoi.java
theleapofcode/algorithms-data-structures-java
baccbb314b4116c5844c9133e8a6d28182c98aee
[ "MIT" ]
null
null
null
19.733333
68
0.679054
6,505
package com.theleapofcode.algosandds.recursion; import org.junit.Assert; import org.junit.Test; public class TestTowerOfHanoi { @Test public void testSolve() { String result = TowerOfHanoi.solve("A", "B", "C", 3); Assert.assertEquals("A->B A->C B->C A->B C->A C->B A->B", result); } }
3e0f53704748acadb09719491183357ce2f8314e
3,212
java
Java
src/mitiv/optim/OptimStatus.java
emmt/TiPi
dfcdf5b21eeaaf6b9d0372cb86f527ff47ba3dfd
[ "MIT" ]
8
2015-03-28T01:47:32.000Z
2019-06-22T11:56:31.000Z
src/mitiv/optim/OptimStatus.java
emmt/TiPi
dfcdf5b21eeaaf6b9d0372cb86f527ff47ba3dfd
[ "MIT" ]
1
2016-03-02T14:42:52.000Z
2016-10-20T20:59:01.000Z
src/mitiv/optim/OptimStatus.java
emmt/TiPi
dfcdf5b21eeaaf6b9d0372cb86f527ff47ba3dfd
[ "MIT" ]
3
2015-01-29T10:34:19.000Z
2019-06-24T15:10:57.000Z
39.777778
78
0.739913
6,506
/* * This file is part of TiPi (a Toolkit for Inverse Problems and Imaging) * developed by the MitiV project. * * Copyright (c) 2014 the MiTiV project, http://mitiv.univ-lyon1.fr/ * * 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 mitiv.optim; /** * Values returned by the reverse communication version of optimization * algorithms. * * @author Éric Thiébaut <ychag@example.com> */ public enum OptimStatus { SUCCESS("Success"), INVALID_ARGUMENT("Invalid argument"), INSUFFICIENT_MEMORY("Insufficient memory"), ILLEGAL_ADDRESS("Illegal address"), NOT_IMPLEMENTED("Not implemented"), CORRUPTED_WORKSPACE("Corrupted workspace"), BAD_SPACE("Bad variable space"), OUT_OF_BOUNDS_INDEX("Out of bounds index"), ALGORITHM_NOT_STARTED("Algorithm not started"), LNSRCH_NOT_STARTED("Line search not started"), NOT_A_DESCENT("Not a descent direction"), STEP_CHANGED("Step changed"), STEP_OUTSIDE_BRACKET("Step outside bracket"), STPMIN_GT_STPMAX("Lower step bound larger than upper bound"), STPMIN_LT_ZERO("Minimal step length less than zero"), STEP_LT_STPMIN("Step lesser than lower bound"), STEP_GT_STPMAX("Step greater than upper bound"), FTOL_TEST_SATISFIED("Convergence within variable tolerance"), GTOL_TEST_SATISFIED("Convergence within function tolerance"), XTOL_TEST_SATISFIED("Convergence within gradient tolerance"), STEP_EQ_STPMAX("Step blocked at upper bound"), STEP_EQ_STPMIN("Step blocked at lower bound"), ROUNDING_ERRORS_PREVENT_PROGRESS("Rounding errors prevent progress"), BAD_PRECONDITIONER("Preconditioner is not positive definite"), INFEASIBLE_BOUNDS("Box set is infeasible"), WOULD_BLOCK("Variables cannot be improved (would block)"), UNDEFINED_VALUE("Undefined value"), TOO_MANY_ITERATIONS("Too many iterations"), TOO_MANY_EVALUATIONS("Too many evaluations"); private final String description; OptimStatus(String description) { this.description = description; } /** * Query the description of the optimization task. */ @Override public String toString(){ return description; } }
3e0f54a7ed197e4f583f062e4b7a74886017456f
1,846
java
Java
src/main/java/com/zxc74171/thaumicpotatoes/items/ItemTaintedCorePerditio.java
limuness/ThaumicPotatoes2
523714447a91194a9294fefb7316c7d851211cce
[ "WTFPL" ]
4
2017-06-29T12:22:11.000Z
2021-05-30T05:09:11.000Z
src/main/java/com/zxc74171/thaumicpotatoes/items/ItemTaintedCorePerditio.java
limuness/ThaumicPotatoes2
523714447a91194a9294fefb7316c7d851211cce
[ "WTFPL" ]
3
2017-08-01T12:31:39.000Z
2018-02-11T05:24:27.000Z
src/main/java/com/zxc74171/thaumicpotatoes/items/ItemTaintedCorePerditio.java
limuness/ThaumicPotatoes2
523714447a91194a9294fefb7316c7d851211cce
[ "WTFPL" ]
2
2017-08-01T10:04:52.000Z
2017-08-02T08:23:09.000Z
35.5
155
0.763814
6,507
package com.zxc74171.thaumicpotatoes.items; import static com.zxc74171.thaumicpotatoes.ThaumicPotatoes2.proxy; import java.util.List; import javax.annotation.Nullable; import com.zxc74171.thaumicpotatoes.entities.EntityJagaimo; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class ItemTaintedCorePerditio extends Item { public ItemTaintedCorePerditio() { setMaxDamage(1); setMaxStackSize(1); } @Override public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if(!worldIn.isRemote) { player.getHeldItem(hand).damageItem(2, player); EntityJagaimo bosso = new EntityJagaimo(worldIn); bosso.setLocationAndAngles(pos.getX(), pos.getY()+1,pos.getZ(), MathHelper.wrapDegrees(worldIn.rand.nextFloat() * 360.0F), 0.0F); worldIn.spawnEntity(bosso); String message = String.format(proxy.translateToLocal("bosstext_jagaimo")); player.sendMessage(new TextComponentString(message)); } return EnumActionResult.PASS; } @SideOnly(Side.CLIENT) public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { tooltip.add(proxy.translateToLocal("tooltipTaintedCore")); } }
3e0f55e367723cfb4ff5d02472e616a82f152476
1,233
java
Java
src/com/jsyn/unitgen/UnitSink.java
oletizi/jsyn-debug
e1dacd3c21e01a56ae337027a5214aabf7207d6d
[ "ECL-2.0", "Apache-2.0" ]
200
2015-01-02T10:51:01.000Z
2022-03-17T09:24:30.000Z
src/com/jsyn/unitgen/UnitSink.java
oletizi/jsyn-debug
e1dacd3c21e01a56ae337027a5214aabf7207d6d
[ "ECL-2.0", "Apache-2.0" ]
64
2015-08-27T02:45:05.000Z
2022-01-30T19:14:35.000Z
src/com/jsyn/unitgen/UnitSink.java
oletizi/jsyn-debug
e1dacd3c21e01a56ae337027a5214aabf7207d6d
[ "ECL-2.0", "Apache-2.0" ]
68
2015-01-02T11:06:14.000Z
2022-03-08T20:30:57.000Z
28.022727
96
0.717762
6,508
/* * Copyright 2009 Phil Burk, Mobileer 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.jsyn.unitgen; import com.jsyn.ports.UnitInputPort; import com.softsynth.shared.time.TimeStamp; /** * Interface for unit generators that have an input. * * @author Phil Burk, (C) 2009 Mobileer Inc */ public interface UnitSink { public UnitInputPort getInput(); /** * Begin execution of this unit by the Synthesizer. The input will pull data from any output * port that is connected from it. */ public void start(); public void start(TimeStamp timeStamp); public void stop(); public void stop(TimeStamp timeStamp); public UnitGenerator getUnitGenerator(); }
3e0f56238b07e0797cb27ea31cd266026d6b516b
3,031
java
Java
src/main/java/mods/railcraft/client/util/sounds/RCSoundHandler.java
Bil481Railcraft/Railcraft
c503bfccc5ee38a3a7d14f4be1143c469b3f04de
[ "FTL" ]
3
2018-11-03T12:39:14.000Z
2018-12-04T15:29:51.000Z
src/main/java/mods/railcraft/client/util/sounds/RCSoundHandler.java
Bil481Railcraft/Railcraft
c503bfccc5ee38a3a7d14f4be1143c469b3f04de
[ "FTL" ]
5
2018-11-15T17:52:30.000Z
2020-03-19T08:10:17.000Z
src/main/java/mods/railcraft/client/util/sounds/RCSoundHandler.java
Bil481Railcraft/Railcraft
c503bfccc5ee38a3a7d14f4be1143c469b3f04de
[ "FTL" ]
1
2020-01-09T13:41:07.000Z
2020-01-09T13:41:07.000Z
43.927536
147
0.629495
6,509
/******************************************************************************* Copyright (c) CovertJaguar, 2011-2016 http://railcraft.info This code is the property of CovertJaguar and may only be used with explicit written permission unless otherwise specified on the license page at http://railcraft.info/wiki/info:license. ******************************************************************************/ package mods.railcraft.client.util.sounds; import mods.railcraft.common.core.Railcraft; import mods.railcraft.common.util.sounds.SoundHelper; import mods.railcraft.common.util.sounds.SoundRegistry; import net.minecraft.block.SoundType; import net.minecraft.client.audio.ISound; import net.minecraft.client.audio.PositionedSound; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.client.event.sound.PlaySoundEvent; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * @author CovertJaguar <http://www.railcraft.info> */ public final class RCSoundHandler { public static final RCSoundHandler INSTANCE = new RCSoundHandler(); private RCSoundHandler() { } //TODO: test, catch PlaySoundAtEntityEvent? @SubscribeEvent public void onPlaySound(PlaySoundEvent event) { ISound soundEvent = event.getSound(); ResourceLocation soundResource = soundEvent.getSoundLocation(); if (SoundHelper.matchesSoundResource(soundResource, "null")) { event.setResultSound(null); } else if (SoundHelper.matchesSoundResource(soundResource, "override")) { World world = Railcraft.getProxy().getClientWorld(); if (world != null) { float x = soundEvent.getXPosF(); float y = soundEvent.getYPosF(); float z = soundEvent.getZPosF(); BlockPos pos = new BlockPos(x, y, z); String soundPath = soundEvent.getSoundLocation().getPath(); SoundType blockSound = SoundRegistry.getBlockSound(world, pos); if (blockSound == null) { if (soundPath.contains("place")) { event.getManager().playDelayedSound(event.getSound(), 3); //Play sound later to adjust for the block not being there yet. } else if (soundPath.contains("step")) { blockSound = SoundRegistry.getBlockSound(world, pos.down()); } } if (blockSound != null) { SoundEvent newSound = SoundHelper.matchSoundEvent(soundResource, blockSound); // ObfuscationReflectionHelper.setPrivateValue(PositionedSound.class, (PositionedSound) soundEvent, newSound.getSoundName(), 3); } else { event.setResultSound(null); } } } } }
3e0f5799b1f8c3ed6442a54b1c5967f49e205592
647
java
Java
src/main/java/org/fidoalliance/fdo/epid/verification/exceptions/InvalidEpidGroupIdException.java
trbehera/epid-verification-service
c9356d4491ab838d3f86db4826ce0945184c1322
[ "Apache-2.0" ]
1
2022-03-25T05:42:52.000Z
2022-03-25T05:42:52.000Z
src/main/java/org/fidoalliance/fdo/epid/verification/exceptions/InvalidEpidGroupIdException.java
trbehera/epid-verification-service
c9356d4491ab838d3f86db4826ce0945184c1322
[ "Apache-2.0" ]
1
2021-06-16T12:16:03.000Z
2021-08-16T04:14:40.000Z
src/main/java/org/fidoalliance/fdo/epid/verification/exceptions/InvalidEpidGroupIdException.java
trbehera/epid-verification-service
c9356d4491ab838d3f86db4826ce0945184c1322
[ "Apache-2.0" ]
7
2021-04-30T07:55:16.000Z
2021-12-24T19:55:32.000Z
30.809524
99
0.741886
6,510
// Copyright 2021 Intel Corporation // SPDX-License-Identifier: Apache 2.0 package org.fidoalliance.fdo.epid.verification.exceptions; import org.fidoalliance.fdo.epid.verification.enums.EpidVersion; public class InvalidEpidGroupIdException extends Exception { /** * Exception for handling requests in which the specified GroupId is invalid. * @param epidVersion EPID version * @param groupId EPID Group ID */ public InvalidEpidGroupIdException(EpidVersion epidVersion, String groupId) { super( String.format( "Requested (%s) group (%s) does not exist", epidVersion.toLowerCaseString(), groupId)); } }
3e0f582e4322b8f39b933ad534b0259aa6b77d82
16,135
java
Java
src/main/java/com/vcarecity/utils/Logger.java
ewsq/Jimg
75198b3cc2df31e445a280244e589629f281d840
[ "MIT" ]
3
2020-01-17T15:23:46.000Z
2021-05-01T19:32:51.000Z
src/main/java/com/vcarecity/utils/Logger.java
ewsq/Jimg
75198b3cc2df31e445a280244e589629f281d840
[ "MIT" ]
8
2020-03-30T09:00:55.000Z
2022-02-16T02:01:58.000Z
src/main/java/com/vcarecity/utils/Logger.java
ewsq/Jimg
75198b3cc2df31e445a280244e589629f281d840
[ "MIT" ]
1
2020-03-30T08:55:37.000Z
2020-03-30T08:55:37.000Z
32.99591
88
0.547815
6,511
package com.vcarecity.utils; import java.io.*; import java.util.Properties; import java.text.SimpleDateFormat; public class Logger { private static Logger logger; private static String logPath; private static String eventPath; private static String website; private FileWriter fwlogger =null; private StackTraceElement elements[]; private static String ClassMethodName=""; private static String level="info"; protected Logger() { level="debug"; InputStream is = null; Properties properties = new Properties(); String filePath = "config/logger.properties"; try { is = new FileInputStream(filePath); properties.load(is); logPath = properties.getProperty("logPath", "./logs/"); website = properties.getProperty("website", ""); } catch (IOException ex) { System.err.println("不能读取属性文件.请确保logger.properties在resources指定的路径中"); }finally{ try { if(is!=null){ is.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static Logger getLogger() { try { if (logger == null) { logger = new Logger(); } } catch (Exception e) { System.out.println("创建日志文件失败:" + e.toString()); e.printStackTrace(); } return logger; } //获得日志文件目录的上一级目录 public String getLogParentPath() { int ss = logPath.length(); String strPath = logPath.substring(0, ss - 1); ss = strPath.lastIndexOf('\\'); String retPath = strPath.substring(0, ss + 1); return retPath; } public void setLogPath(String path) { if (path == null) { logPath = ""; } else { logPath = path; } } public synchronized void writeLog(String msg) { StringBuffer fileName = new StringBuffer(); if (logPath != null) { fileName.append(logPath); } else { System.out.println("logpath is null!"); } elements = new Throwable().getStackTrace(); ClassMethodName=elements[1].getClassName() + "." + elements[1].getMethodName(); if("".equalsIgnoreCase(website)){ fileName.append("Log_"); }else{ fileName.append("Log_" + website + "_" +ClassMethodName+"_"); } java.sql.Timestamp nowDate = new java.sql.Timestamp(System.currentTimeMillis()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd"); String aa = sdf.format(nowDate); fileName.append(aa); fileName.append(".txt"); try { fwlogger = new FileWriter(fileName.toString(), true); StringBuffer sbMsg = new StringBuffer(); sbMsg.append(getLongTimeString() + ":\r\n"); sbMsg.append(msg); sbMsg.append("\r\n"); fwlogger.write(sbMsg.toString()); writeConsle(sbMsg.toString()); } catch (Exception e) { System.out.println("writer log error:" + e.toString()); }finally{ try { if(fwlogger!=null){ fwlogger.close(); } } catch (IOException e) { e.printStackTrace(); } } } public synchronized void writeErrorLog(String msg) { StringBuffer fileName = new StringBuffer(); if (logPath != null) { fileName.append(logPath); } else { System.out.println("logpath is null!"); } elements = new Throwable().getStackTrace(); ClassMethodName=elements[1].getClassName() + "." + elements[1].getMethodName(); if("".equalsIgnoreCase(website)){ fileName.append("ErrorLog_"); }else{ fileName.append("ErrorLog_" + website + "_" +ClassMethodName+"_"); } java.sql.Timestamp nowDate = new java.sql.Timestamp(System.currentTimeMillis()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd"); String aa = sdf.format(nowDate); fileName.append(aa); fileName.append(".txt"); try { fwlogger = new FileWriter(fileName.toString(), true); StringBuffer sbMsg = new StringBuffer(); sbMsg.append(getLongTimeString() + ":\r\n"); sbMsg.append("Error:"+msg); sbMsg.append("\r\n"); fwlogger.write(sbMsg.toString()); writeConsle(sbMsg.toString()); } catch (Exception e) { System.out.println("writer log error:" + e.toString()); }finally{ try { if(fwlogger!=null){ fwlogger.close(); } } catch (IOException e) { e.printStackTrace(); } } } public synchronized void writeDebugLog(String msg) { StringBuffer fileName = new StringBuffer(); if (logPath != null) { fileName.append(logPath); } else { System.out.println("logpath is null!"); } elements = new Throwable().getStackTrace(); ClassMethodName=elements[1].getClassName() + "." + elements[1].getMethodName(); if("".equalsIgnoreCase(website)){ fileName.append("DebugLog_"); }else{ fileName.append("DebugLog_" + website + "_" +ClassMethodName+"_"); } java.sql.Timestamp nowDate = new java.sql.Timestamp(System.currentTimeMillis()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd"); String aa = sdf.format(nowDate); fileName.append(aa); fileName.append(".txt"); try { fwlogger = new FileWriter(fileName.toString(), true); StringBuffer sbMsg = new StringBuffer(); sbMsg.append(getLongTimeString() + ":\r\n"); sbMsg.append("Debug:"+msg); sbMsg.append("\r\n"); fwlogger.write(sbMsg.toString()); writeConsle(sbMsg.toString()); } catch (Exception e) { System.out.println("writer log error:" + e.toString()); }finally{ try { if(fwlogger!=null){ fwlogger.close(); } } catch (IOException e) { e.printStackTrace(); } } } public synchronized void writeDebugInfo(String msg) { StringBuffer fileName = new StringBuffer(); if (logPath != null) { fileName.append(logPath); } else { System.out.println("logpath is null!"); } elements = new Throwable().getStackTrace(); ClassMethodName=elements[1].getClassName() + "." + elements[1].getMethodName(); if("".equalsIgnoreCase(website)){ fileName.append("DebugInfo_"); }else{ fileName.append("DebugInfo_" + website + "_" +ClassMethodName+"_"); } java.sql.Timestamp nowDate = new java.sql.Timestamp(System.currentTimeMillis()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd"); String aa = sdf.format(nowDate); fileName.append(aa); fileName.append(".txt"); try { fwlogger = new FileWriter(fileName.toString(), true); StringBuffer sbMsg = new StringBuffer(); sbMsg.append(getLongTimeString() + ":\r\n"); sbMsg.append("Debug:"+msg); sbMsg.append("\r\n"); fwlogger.write(sbMsg.toString()); writeConsle(sbMsg.toString()); } catch (Exception e) { System.out.println("writer log error:" + e.toString()); }finally{ try { if(fwlogger!=null){ fwlogger.close(); } } catch (IOException e) { e.printStackTrace(); } } } public synchronized void writeConsle(String msg) { if (level.equalsIgnoreCase("debug")) { System.out.println(msg); } else { } } //////////////////系统日志 public String getEventParentPath() { int ss = eventPath.length(); String strPath = eventPath.substring(0, ss - 1); ss = strPath.lastIndexOf('\\'); String retPath = strPath.substring(0, ss + 1); return retPath; } public void setEventPath(String path) { if (path == null) { eventPath = ""; } else { eventPath = path; } } public synchronized void writeEvent(String msg) { StringBuffer fileName = new StringBuffer(); if (eventPath != null) { fileName.append(eventPath); } else { System.out.println("Eventpath is null "); } elements = new Throwable().getStackTrace(); ClassMethodName=elements[1].getClassName() + "." + elements[1].getMethodName(); if("".equalsIgnoreCase(website)){ fileName.append("System_Event_"); }else{ fileName.append("System_Event_" + website + "_" +ClassMethodName+"_"); } java.sql.Timestamp nowDate = new java.sql.Timestamp(System.currentTimeMillis()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd"); String aa = sdf.format(nowDate); fileName.append(aa); fileName.append(".txt"); try { fwlogger = new FileWriter(fileName.toString(), true); StringBuffer sbMsg = new StringBuffer(); sbMsg.append(getLongTimeString() + ":\r\n"); sbMsg.append(msg); sbMsg.append("\r\n"); fwlogger.write(sbMsg.toString()); writeConsle(msg); } catch (Exception e) { e.printStackTrace(); }finally{ try { if(fwlogger!=null){ fwlogger.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * writeDebugEvent * 写专有日志标记,主要用于数据刷新较快的情况下处理专门的日志便于查看 * @param eventFlag 日志事件标签,给一个易于标识和查询的标识,关键易于查找 * @param msg 要写入的消息内容 */ public synchronized void writeDebugEvent(String eventFlag,String msg) { StringBuffer fileName = new StringBuffer(); if (eventPath != null) { fileName.append(eventPath); } else { System.out.println("Eventpath is null "); } elements = new Throwable().getStackTrace(); ClassMethodName=elements[1].getClassName() + "." + elements[1].getMethodName(); if("".equalsIgnoreCase(website)){ fileName.append(eventFlag+"_"); }else{ fileName.append(eventFlag+"_" + website + "_" +ClassMethodName+"_"); } java.sql.Timestamp nowDate = new java.sql.Timestamp(System.currentTimeMillis()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd"); String aa = sdf.format(nowDate); fileName.append(aa); fileName.append(".txt"); try { fwlogger = new FileWriter(fileName.toString(), true); StringBuffer sbMsg = new StringBuffer(); sbMsg.append(getLongTimeString() + ":\r\n"); sbMsg.append(msg); sbMsg.append("\r\n"); fwlogger.write(sbMsg.toString()); writeConsle(sbMsg.toString()); } catch (Exception e) { e.printStackTrace(); }finally{ try { if(fwlogger!=null){ fwlogger.close(); } } catch (IOException e) { e.printStackTrace(); } } } public synchronized void writeExceptionInfo(Exception ex) { StringBuffer fileName = new StringBuffer(); StringBuffer sb = new StringBuffer(); if (logPath != null) { fileName.append(logPath); } else { System.out.println("logpath is null!"); } elements = ex.getStackTrace(); ClassMethodName=elements[1].getClassName() + "." + elements[1].getMethodName(); for(int i = 0; i < elements.length; i++) { StackTraceElement element = elements[i]; sb.append(element.toString() + "\n"); } if("".equalsIgnoreCase(website)){ fileName.append("DebugInfo_"); }else{ fileName.append("DebugInfo_" + website + "_" +ClassMethodName+"_"); } java.sql.Timestamp nowDate = new java.sql.Timestamp(System.currentTimeMillis()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd"); String aa = sdf.format(nowDate); fileName.append(aa); fileName.append(".txt"); try { fwlogger = new FileWriter(fileName.toString(), true); StringBuffer sbMsg = new StringBuffer(); sbMsg.append(getLongTimeString() + ":\r\n"); sbMsg.append("Exception:"+sb.toString()); sbMsg.append("\r\n"); fwlogger.write(sbMsg.toString()); writeConsle(sbMsg.toString()); } catch (Exception e) { System.out.println("writer Exception error:" + e.toString()); }finally{ try { if(fwlogger!=null){ fwlogger.close(); } } catch (IOException e) { e.printStackTrace(); } } } public synchronized void writeThrowableInfo(Throwable ex) { StringBuffer fileName = new StringBuffer(); StringBuffer sb = new StringBuffer(); if (logPath != null) { fileName.append(logPath); } else { System.out.println("logpath is null!"); } elements = ex.getStackTrace(); ClassMethodName=elements[1].getClassName() + "." + elements[1].getMethodName(); for(int i = 0; i < elements.length; i++) { StackTraceElement element = elements[i]; sb.append(element.toString() + "\n"); } if("".equalsIgnoreCase(website)){ fileName.append("DebugInfo_"); }else{ fileName.append("DebugInfo_" + website + "_" +ClassMethodName+"_"); } java.sql.Timestamp nowDate = new java.sql.Timestamp(System.currentTimeMillis()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd"); String aa = sdf.format(nowDate); fileName.append(aa); fileName.append(".txt"); try { fwlogger = new FileWriter(fileName.toString(), true); StringBuffer sbMsg = new StringBuffer(); sbMsg.append(getLongTimeString() + ":\r\n"); sbMsg.append("Exception:"+sb.toString()); sbMsg.append("\r\n"); fwlogger.write(sbMsg.toString()); writeConsle(sbMsg.toString()); } catch (Exception e) { System.out.println("writer Exception error:" + e.toString()); }finally{ try { if(fwlogger!=null){ fwlogger.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static String getEncodeString(String s) { String retStr = ""; try { if (s != null) { retStr = new String(s.getBytes("ISO-8859-1"), "GBK"); } } catch (Exception ex) { System.out.println(s + " getEncodeString error:" + ex.toString()); } return retStr; } //生成长时间字符串,形如:2005-01-01 01:01:01 public static String getLongTimeString() { java.util.Date myDate = new java.util.Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //long myTime = (myDate.getTime() / 1000) - 60 * 60 * 24 * 365; //myDate.setTime(myTime * 1000); String mDate = formatter.format(myDate); return mDate; } public static void main(String[] args) { Logger log=Logger.getLogger(); log.writeLog("111111111111111"); } }
3e0f590c3c30d2489ed0d8b1077a6b7a6d4f3971
6,399
java
Java
core/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/As2ComponentBuilderFactory.java
LittleEntity/camel
da0d257a983859c25add75047498aa2aa319d7e2
[ "Apache-2.0" ]
4,262
2015-01-01T15:28:37.000Z
2022-03-31T04:46:41.000Z
core/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/As2ComponentBuilderFactory.java
LittleEntity/camel
da0d257a983859c25add75047498aa2aa319d7e2
[ "Apache-2.0" ]
3,408
2015-01-03T02:11:17.000Z
2022-03-31T20:07:56.000Z
core/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/As2ComponentBuilderFactory.java
LittleEntity/camel
da0d257a983859c25add75047498aa2aa319d7e2
[ "Apache-2.0" ]
5,505
2015-01-02T14:58:12.000Z
2022-03-30T19:23:41.000Z
40.757962
148
0.642913
6,512
/* * 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.camel.builder.component.dsl; import javax.annotation.Generated; import org.apache.camel.Component; import org.apache.camel.builder.component.AbstractComponentBuilder; import org.apache.camel.builder.component.ComponentBuilder; import org.apache.camel.component.as2.AS2Component; /** * Transfer data securely and reliably using the AS2 protocol (RFC4130). * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.ComponentDslMojo") public interface As2ComponentBuilderFactory { /** * AS2 (camel-as2) * Transfer data securely and reliably using the AS2 protocol (RFC4130). * * Category: file * Since: 2.22 * Maven coordinates: org.apache.camel:camel-as2 * * @return the dsl builder */ static As2ComponentBuilder as2() { return new As2ComponentBuilderImpl(); } /** * Builder for the AS2 component. */ interface As2ComponentBuilder extends ComponentBuilder<AS2Component> { /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default As2ComponentBuilder bridgeErrorHandler( boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default As2ComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default As2ComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * Component configuration. * * The option is a: * &lt;code&gt;org.apache.camel.component.as2.AS2Configuration&lt;/code&gt; type. * * Group: advanced * * @param configuration the value to set * @return the dsl builder */ default As2ComponentBuilder configuration( org.apache.camel.component.as2.AS2Configuration configuration) { doSetProperty("configuration", configuration); return this; } } class As2ComponentBuilderImpl extends AbstractComponentBuilder<AS2Component> implements As2ComponentBuilder { @Override protected AS2Component buildConcreteComponent() { return new AS2Component(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "bridgeErrorHandler": ((AS2Component) component).setBridgeErrorHandler((boolean) value); return true; case "lazyStartProducer": ((AS2Component) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((AS2Component) component).setAutowiredEnabled((boolean) value); return true; case "configuration": ((AS2Component) component).setConfiguration((org.apache.camel.component.as2.AS2Configuration) value); return true; default: return false; } } } }
3e0f5918e109d52e3e24308fd1f1928abe86e48c
498
java
Java
blelibrary/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleScanCallback.java
QiangzhenZhu/andoridble
bb13aa6b58fd760cca59f1c489d526300a021af9
[ "Apache-2.0" ]
4
2019-04-24T04:17:07.000Z
2020-01-10T03:37:29.000Z
blelibrary/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleScanCallback.java
bzw073/Android-BLE
af3c2a181da6587b73e88349104699a55ce25041
[ "Apache-2.0" ]
null
null
null
blelibrary/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleScanCallback.java
bzw073/Android-BLE
af3c2a181da6587b73e88349104699a55ce25041
[ "Apache-2.0" ]
1
2018-07-31T07:12:19.000Z
2018-07-31T07:12:19.000Z
19.153846
73
0.596386
6,513
package cn.com.heaton.blelibrary.ble.callback; /** * Created by LiuLei on 2017/10/23. */ public abstract class BleScanCallback<T> { /** * Start the scan */ public void onStart(){}; /** * Stop scanning */ public void onStop(){}; /** * Scan to device * @param device ble device object * @param rssi rssi * @param scanRecord Bluetooth radio package */ public abstract void onLeScan(T device, int rssi, byte[] scanRecord); }
3e0f5a7dbbfcc9e9322f8777fe2e998aeb379e62
2,473
java
Java
Java/Exercicios - Paradigma Estruturado/Exercicios - Estrutura Condicional/Exercicio23.java
RicardoMart922/estudos_Java
53b47d07419ebd21ae782a32416ed18189cde362
[ "MIT" ]
null
null
null
Java/Exercicios - Paradigma Estruturado/Exercicios - Estrutura Condicional/Exercicio23.java
RicardoMart922/estudos_Java
53b47d07419ebd21ae782a32416ed18189cde362
[ "MIT" ]
null
null
null
Java/Exercicios - Paradigma Estruturado/Exercicios - Estrutura Condicional/Exercicio23.java
RicardoMart922/estudos_Java
53b47d07419ebd21ae782a32416ed18189cde362
[ "MIT" ]
null
null
null
31.705128
91
0.553579
6,514
/* 23 - Faça um programa que receba: ■ o código do produto comprado; e ■ a quantidade comprada do produto. Calcule e mostre: ■ o preço unitário do produto comprado, seguindo a Tabela I; ■ o preço total da nota; ■ o valor do desconto, seguindo a Tabela II e aplicado sobre o preço total da nota; e ■ o preço final da nota depois do desconto. TABELA I CÓDIGO PREÇO 1 a 10 R$ 10,00 11 a 20 R$ 15,00 21 a 30 R$ 20,00 31 a 40 R$ 30,00 TABELA II PREÇO TOTAL DA NOTA % DE DESCONTO Até R$ 250,00 5% Entre R$ 250,00 e R$ 500,00 10% Acima de R$ 500,00 15% */ package exercicio.estrutura.condional; import java.util.Scanner; public class Exercicio23 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int codigoProduto = 0, quantidadeProduto = 0; double precoUnitario = 0.00, precoTotal = 0.00, precoFinal = 0.00, desconto = 0.00; System.out.printf("Código do produto: "); codigoProduto = in.nextInt(); System.out.printf("Quantidade comprada do produto: "); quantidadeProduto = in.nextInt(); if (codigoProduto >= 1 && codigoProduto <= 10) { precoUnitario = 10.00; } else if (codigoProduto >= 11 && codigoProduto <= 20) { precoUnitario = 15.00; } else if (codigoProduto >= 21 && codigoProduto <= 30) { precoUnitario = 20.00; } else if (codigoProduto >= 31 && codigoProduto <= 40) { precoUnitario = 30.00; } else { System.out.printf("Código do produto inválido!\n"); } System.out.printf("Preço unitário do produto: R$%.2f\n", precoUnitario); precoTotal = precoUnitario * quantidadeProduto; System.out.printf("Preço total da nota: R$%.2f\n", precoTotal); if (precoTotal <= 250.00) { desconto = precoTotal * 0.05; } else if (precoTotal > 250.00 && precoTotal <= 500.00) { desconto = precoTotal * 0.1; } else { desconto = precoTotal * 0.15; } System.out.printf("O valor do desconto: R$%.2f\n", desconto); precoFinal = precoTotal - desconto; System.out.printf("Preço final da nota: R$%.2f\n", precoFinal); in.close(); } }
3e0f5aaad9f61b48d83430f09d912c1168a2b4f9
203
java
Java
src/main/java/spencercjh/problems/ReorderedPowerOf2.java
spencercjh/leetcode-playground
6417947791c3be15397ac04c05eb151bfdebb562
[ "Apache-2.0" ]
null
null
null
src/main/java/spencercjh/problems/ReorderedPowerOf2.java
spencercjh/leetcode-playground
6417947791c3be15397ac04c05eb151bfdebb562
[ "Apache-2.0" ]
27
2020-12-09T14:57:24.000Z
2022-03-30T21:13:32.000Z
src/main/java/spencercjh/problems/ReorderedPowerOf2.java
spencercjh/leetcode-playground
6417947791c3be15397ac04c05eb151bfdebb562
[ "Apache-2.0" ]
null
null
null
15.615385
57
0.689655
6,515
package spencercjh.problems; /** * https://leetcode-cn.com/problems/reordered-power-of-2/ * * @author spencercjh */ class ReorderedPowerOf2 { public boolean reorderedPowerOf2(int n) { } }
3e0f5b053c663338900b759ad9fd7f353a64d24b
1,184
java
Java
promotion-service-project/promotion-service-app/src/main/java/cn/iocoder/mall/promotionservice/convert/activity/PromotionActivityConvert.java
xifeng10/onemall
dfd25c151669a41996204016b7bc658c15811e1c
[ "MulanPSL-1.0" ]
1
2020-12-20T08:19:09.000Z
2020-12-20T08:19:09.000Z
promotion-service-project/promotion-service-app/src/main/java/cn/iocoder/mall/promotionservice/convert/activity/PromotionActivityConvert.java
zhangxule/onemall
dfd25c151669a41996204016b7bc658c15811e1c
[ "MulanPSL-1.0" ]
null
null
null
promotion-service-project/promotion-service-app/src/main/java/cn/iocoder/mall/promotionservice/convert/activity/PromotionActivityConvert.java
zhangxule/onemall
dfd25c151669a41996204016b7bc658c15811e1c
[ "MulanPSL-1.0" ]
null
null
null
32.888889
92
0.799831
6,516
package cn.iocoder.mall.promotionservice.convert.activity; import cn.iocoder.mall.promotion.api.rpc.activity.dto.PromotionActivityRespDTO; import cn.iocoder.mall.promotionservice.dal.mysql.dataobject.activity.PromotionActivityDO; import cn.iocoder.mall.promotionservice.service.activity.bo.PromotionActivityBO; import org.mapstruct.Mapper; import org.mapstruct.Mappings; import org.mapstruct.factory.Mappers; import java.util.List; @Mapper public interface PromotionActivityConvert { PromotionActivityConvert INSTANCE = Mappers.getMapper(PromotionActivityConvert.class); @Mappings({}) PromotionActivityBO convertToBO(PromotionActivityDO activity); @Mappings({}) List<PromotionActivityBO> convertToBO(List<PromotionActivityDO> activityList); @Mappings({}) List<PromotionActivityDO> convertToDO(List<PromotionActivityBO> activityList); @Mappings({}) List<PromotionActivityRespDTO> convertToRespDTO(List<PromotionActivityDO> activityList); // @Mappings({}) // PromotionActivityDO convert(PromotionActivityAddDTO activityAddDTO); // // @Mappings({}) // PromotionActivityDO convert(PromotionActivityUpdateDTO activityUpdateDTO); }
3e0f5b8649906cd9de149201926dac34cb3bf5c6
2,216
java
Java
counter-alarm-clock/app/src/main/java/gparap/apps/alarm_clock/AlarmReceiver.java
gparap/android-java
09650d2f42aec28531720450daf87fd585b353b2
[ "Apache-2.0" ]
5
2021-07-25T17:32:51.000Z
2021-11-04T09:28:12.000Z
counter-alarm-clock/app/src/main/java/gparap/apps/alarm_clock/AlarmReceiver.java
gparap/android
09650d2f42aec28531720450daf87fd585b353b2
[ "Apache-2.0" ]
null
null
null
counter-alarm-clock/app/src/main/java/gparap/apps/alarm_clock/AlarmReceiver.java
gparap/android
09650d2f42aec28531720450daf87fd585b353b2
[ "Apache-2.0" ]
null
null
null
41.037037
127
0.727888
6,517
/* * Copyright 2021 gparap * * 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 gparap.apps.alarm_clock; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import androidx.core.app.NotificationCompat; public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String channelId = "channel id"; NotificationChannel notificationChannel = null; //create a notification channel (needed for Android 8.0 or higher) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { notificationChannel = new NotificationChannel(channelId, "channel name", NotificationManager.IMPORTANCE_DEFAULT); notificationChannel.setDescription("channel description"); } //create the notification Notification notification = new NotificationCompat.Builder(context, channelId) .setContentTitle("Alarm") .setContentText("Alarm is ON") .setSmallIcon(R.mipmap.ic_launcher) .setPriority(NotificationCompat.PRIORITY_DEFAULT).build(); //post the notification NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { notificationManager.createNotificationChannel(notificationChannel); } notificationManager.notify(0, notification); } }
3e0f5b88ab85f46300fe8f80d9e073b6d682b3bd
1,384
java
Java
src/TP2/src/main/Vue1.java
marmat8951/MVC
752c3a25d6133ce21a4ef38989a5a7ee810ea91e
[ "MIT" ]
null
null
null
src/TP2/src/main/Vue1.java
marmat8951/MVC
752c3a25d6133ce21a4ef38989a5a7ee810ea91e
[ "MIT" ]
null
null
null
src/TP2/src/main/Vue1.java
marmat8951/MVC
752c3a25d6133ce21a4ef38989a5a7ee810ea91e
[ "MIT" ]
null
null
null
23.066667
67
0.714595
6,518
package TP2.src.main; import java.util.Observable; import java.util.Observer; import javafx.event.ActionEvent; import javafx.geometry.Orientation; import javafx.scene.Scene; import javafx.scene.control.Slider; import javafx.stage.Stage; public class Vue1 implements Observer { private Stage newFenetre=new Stage(); private Slider s=new Slider(Model.MIN_VALUE, Model.MAX_VALUE, 0); public void lunch(Model m){ m.addObserver(this); s.setOrientation(Orientation.VERTICAL); newFenetre.setX(100); newFenetre.setY(0); s.setValue(m.getCelcus()); s.setShowTickLabels(true); s.setShowTickMarks(true); s.setMajorTickUnit(10); s.setBlockIncrement(0.5); s.setMinorTickCount(9); newFenetre.setMinHeight(400); Scene sceneFenetre=new Scene(s); newFenetre.setScene(sceneFenetre); newFenetre.setTitle("Slider Celsius"); newFenetre.setOnCloseRequest(e->{ m.deleteObserver(this); }); s.setOnMousePressed(e->{ m.setCelcus(s.getValue()); }); s.setOnMouseClicked(e->{ m.setCelcus(s.getValue()); }); s.addEventHandler(ActionEvent.ACTION, e->{ m.setCelcus(s.getValue()); }); s.setOnMouseDragged(e->{ m.setCelcus(s.getValue()); }); s.setOnKeyPressed(e->{ m.setCelcus(s.getValue()); }); newFenetre.show(); } @Override public void update(Observable o, Object arg) { Model m=(Model)o; this.s.setValue(m.getCelcus()); } }
3e0f5c0839a95fad65a3afb92e474ac1ce2ca914
27,420
java
Java
Releases/January2014/src/src/org/nypl/SelectionWebView.java
dougreside/MOVER
6db815c44b39a6bb7a871c297c4fbf93ea582201
[ "MIT" ]
1
2016-12-07T23:35:23.000Z
2016-12-07T23:35:23.000Z
Releases/January2014/src/src/org/nypl/SelectionWebView.java
dougreside/MOVER
6db815c44b39a6bb7a871c297c4fbf93ea582201
[ "MIT" ]
null
null
null
Releases/January2014/src/src/org/nypl/SelectionWebView.java
dougreside/MOVER
6db815c44b39a6bb7a871c297c4fbf93ea582201
[ "MIT" ]
null
null
null
28.065507
290
0.697228
6,519
package org.nypl; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.json.JSONException; import org.json.JSONObject; import org.nypl.adapter.ViewPagerAdapter; import org.nypl.database.PlayNoteDAO; import org.nypl.drag.DragController; import org.nypl.drag.DragLayer; import org.nypl.drag.DragListener; import org.nypl.drag.DragSource; import org.nypl.drag.MyAbsoluteLayout; import org.nypl.popup.ActionItem; import org.nypl.popup.QuickAction; import org.nypl.popup.QuickAction.OnDismissListener; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.graphics.Rect; import android.graphics.Region; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.view.inputmethod.InputMethodManager; import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; public class SelectionWebView extends WebView implements TextSelectionJavascriptInterfaceListener, OnTouchListener, OnLongClickListener, OnDismissListener, DragListener { private static final String TAG = "SelectionWebView"; private ProgressDialog pd; private String mNoteId; private String textString; public File xml_file_path; protected Context ctx; private QuickAction mContextMenu; private DragLayer mSelectionDragLayer; private File FilePath = Environment.getExternalStorageDirectory(); public static String CONTENT_LOCATION ; /** The drag controller for selection. */ private DragController mDragController; /** The start selection handle. */ private ImageView mStartSelectionHandle; /** the end selection handle. */ private ImageView mEndSelectionHandle; /** The selection bounds. */ private Rect mSelectionBounds = null; /** The previously selected region. */ protected Region lastSelectedRegion = null; /** The selected range. */ protected String selectedRange = ""; /** The selected text. */ protected String selectedText = ""; /** Javascript interface for catching text selection. */ protected TextSelectionJavascriptInterface textSelectionJSInterface = null; /** Selection mode flag. */ protected boolean inSelectionMode = false; /** Flag to stop from showing context menu twice. */ protected boolean contextMenuVisible = false; /** The current content width. */ protected int contentWidth = 0; /** Identifier for the selection start handle. */ private final int SELECTION_START_HANDLE = 0; /** Identifier for the selection end handle. */ private final int SELECTION_END_HANDLE = 1; /** Last touched selection handle. */ private int mLastTouchedSelectionHandle = -1; private String mRange = ""; private String path = Environment.getExternalStorageDirectory().toString(); public SelectionWebView(Context context) { super(context); SelectionWebView.this.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT"); this.ctx = context; this.setup(context); } public SelectionWebView(Context context, AttributeSet attrs) { super(context, attrs); SelectionWebView.this.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT"); this.ctx = context; this.setup(context); } public SelectionWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); SelectionWebView.this.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT"); this.ctx = context; this.setup(context); } //***************************************************** //* //* Touch Listeners //* //***************************************************** private boolean mScrolling = false; private float mScrollDiffY = 0; private float mLastTouchY = 0; private float mScrollDiffX = 0; private float mLastTouchX = 0; @Override public boolean onTouch(View v, MotionEvent event) { float xPoint = getDensityIndependentValue(event.getX(), ctx) / getDensityIndependentValue(this.getScale(), ctx); float yPoint = getDensityIndependentValue(event.getY(), ctx) / getDensityIndependentValue(this.getScale(), ctx); // TODO: Need to update this to use this.getScale() as a factor. if(event.getAction() == MotionEvent.ACTION_DOWN){ String startTouchUrl = String.format("javascript:android.selection.startTouch(%f, %f);", xPoint, yPoint); mLastTouchX = xPoint; mLastTouchY = yPoint; this.loadUrl(startTouchUrl); } else if(event.getAction() == MotionEvent.ACTION_UP){ // Check for scrolling flag if(!mScrolling){ this.endSelectionMode(); } mScrollDiffX = 0; mScrollDiffY = 0; mScrolling = false; } else if(event.getAction() == MotionEvent.ACTION_MOVE){ mScrollDiffX += (xPoint - mLastTouchX); mScrollDiffY += (yPoint - mLastTouchY); mLastTouchX = xPoint; mLastTouchY = yPoint; // Only account for legitimate movement. if(Math.abs(mScrollDiffX) > 10 || Math.abs(mScrollDiffY) > 10){ mScrolling = true; } } // If this is in selection mode, then nothing else should handle this touch return false; } @Override public boolean onLongClick(View v){ // Tell the javascript to handle this if not in selection mode //if(!this.isInSelectionMode()){ this.loadUrl("javascript:android.selection.longTouch();"); mScrolling = true; //} // Don't let the webview handle it return true; } //***************************************************** //* //* Setup //* //***************************************************** /** * Setups up the web view. * @param context */ protected void setup(Context context){ // On Touch Listener this.setOnLongClickListener(this); this.setOnTouchListener(this); // Webview setup this.getSettings().setJavaScriptEnabled(true); this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); this.getSettings().setPluginsEnabled(true); // Javascript interfaces this.textSelectionJSInterface = new TextSelectionJavascriptInterface(context, this); this.addJavascriptInterface(this.textSelectionJSInterface, this.textSelectionJSInterface.getInterfaceName()); // Create the selection handles createSelectionLayer(context); // Set to the empty region Region region = new Region(); region.setEmpty(); this.lastSelectedRegion = region; } //***************************************************** //* //* Selection Layer Handling //* //***************************************************** /** * Creates the selection layer. * * @param context */ protected void createSelectionLayer(Context context){ LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.mSelectionDragLayer = (DragLayer) inflater.inflate(R.layout.selection_drag_layer, null); // Make sure it's filling parent this.mDragController = new DragController(context); this.mDragController.setDragListener(this); this.mDragController.addDropTarget(mSelectionDragLayer); this.mSelectionDragLayer.setDragController(mDragController); this.mStartSelectionHandle = (ImageView) this.mSelectionDragLayer.findViewById(R.id.startHandle); this.mStartSelectionHandle.setTag(new Integer(SELECTION_START_HANDLE)); this.mEndSelectionHandle = (ImageView) this.mSelectionDragLayer.findViewById(R.id.endHandle); this.mEndSelectionHandle.setTag(new Integer(SELECTION_END_HANDLE)); OnTouchListener handleTouchListener = new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { boolean handledHere = false; final int action = event.getAction(); // Down event starts drag for handle. if (action == MotionEvent.ACTION_DOWN) { handledHere = startDrag (v); mLastTouchedSelectionHandle = (Integer) v.getTag(); } return handledHere; } }; this.mStartSelectionHandle.setOnTouchListener(handleTouchListener); this.mEndSelectionHandle.setOnTouchListener(handleTouchListener); } /** * Starts selection mode on the UI thread */ private Handler startSelectionModeHandler = new Handler(){ public void handleMessage(Message m){ if(mSelectionBounds == null) return; addView(mSelectionDragLayer); drawSelectionHandles(); int contentHeight = (int) Math.ceil(getDensityDependentValue(getContentHeight(), ctx)); // Update Layout Params ViewGroup.LayoutParams layerParams = mSelectionDragLayer.getLayoutParams(); layerParams.height = contentHeight; layerParams.width = contentWidth; mSelectionDragLayer.setLayoutParams(layerParams); } }; /** * Starts selection mode. * * @param selectionBounds */ public void startSelectionMode(){ this.startSelectionModeHandler.sendEmptyMessage(0); } // Ends selection mode on the UI thread private Handler endSelectionModeHandler = new Handler(){ public void handleMessage(Message m){ removeView(mSelectionDragLayer); if(getParent() != null && mContextMenu != null && contextMenuVisible){ // This will throw an error if the webview is being redrawn. // No error handling needed, just need to stop the crash. try{ mContextMenu.dismiss(); } catch(Exception e){ } } mSelectionBounds = null; mLastTouchedSelectionHandle = -1; loadUrl("javascript: android.selection.clearSelection();"); } }; /** * Ends selection mode. */ public void endSelectionMode(){ this.endSelectionModeHandler.sendEmptyMessage(0); } /** * Calls the handler for drawing the selection handles. */ private void drawSelectionHandles(){ this.drawSelectionHandlesHandler.sendEmptyMessage(0); } /** * Handler for drawing the selection handles on the UI thread. */ private Handler drawSelectionHandlesHandler = new Handler(){ public void handleMessage(Message m){ MyAbsoluteLayout.LayoutParams startParams = (org.nypl.drag.MyAbsoluteLayout.LayoutParams) mStartSelectionHandle.getLayoutParams(); startParams.x = (int) (mSelectionBounds.left - mStartSelectionHandle.getDrawable().getIntrinsicWidth()); startParams.y = (int) (mSelectionBounds.top - mStartSelectionHandle.getDrawable().getIntrinsicHeight()); // Stay on screen. startParams.x = (startParams.x < 0) ? 0 : startParams.x; startParams.y = (startParams.y < 0) ? 0 : startParams.y; mStartSelectionHandle.setLayoutParams(startParams); MyAbsoluteLayout.LayoutParams endParams = (org.nypl.drag.MyAbsoluteLayout.LayoutParams) mEndSelectionHandle.getLayoutParams(); endParams.x = (int) mSelectionBounds.right; endParams.y = (int) mSelectionBounds.bottom; // Stay on screen endParams.x = (endParams.x < 0) ? 0 : endParams.x; endParams.y = (endParams.y < 0) ? 0 : endParams.y; mEndSelectionHandle.setLayoutParams(endParams); } }; private String mText; private Dialog mPlayNoteDialog; private EditText mNoteText; private Button mSaveBtn; private Button mCancelBtn; public static String URLID; public static String HTMLFileLocation = null; /** * Checks to see if this view is in selection mode. * @return */ public boolean isInSelectionMode(){ return this.mSelectionDragLayer.getParent() != null; } //***************************************************** //* //* DragListener Methods //* //***************************************************** /** * Start dragging a view. * */ private boolean startDrag (View v) { // Let the DragController initiate a drag-drop sequence. // I use the dragInfo to pass along the object being dragged. // I'm not sure how the Launcher designers do this. Object dragInfo = v; mDragController.startDrag (v, mSelectionDragLayer, dragInfo, DragController.DRAG_ACTION_MOVE); return true; } @Override public void onDragStart(DragSource source, Object info, int dragAction) { // TODO Auto-generated method stub } @Override public void onDragEnd() { // TODO Auto-generated method stub MyAbsoluteLayout.LayoutParams startHandleParams = (MyAbsoluteLayout.LayoutParams) this.mStartSelectionHandle.getLayoutParams(); MyAbsoluteLayout.LayoutParams endHandleParams = (MyAbsoluteLayout.LayoutParams) this.mEndSelectionHandle.getLayoutParams(); float scale = getDensityIndependentValue(this.getScale(), ctx); float startX = startHandleParams.x - this.getScrollX(); float startY = startHandleParams.y - this.getScrollY(); float endX = endHandleParams.x - this.getScrollX(); float endY = endHandleParams.y - this.getScrollY(); startX = getDensityIndependentValue(startX, ctx) / scale; startY = getDensityIndependentValue(startY, ctx) / scale; endX = getDensityIndependentValue(endX, ctx) / scale; endY = getDensityIndependentValue(endY, ctx) / scale; if(mLastTouchedSelectionHandle == SELECTION_START_HANDLE && startX > 0 && startY > 0){ String saveStartString = String.format("javascript: android.selection.setStartPos(%f, %f);", startX, startY); this.loadUrl(saveStartString); } if(mLastTouchedSelectionHandle == SELECTION_END_HANDLE && endX > 0 && endY > 0){ String saveEndString = String.format("javascript: android.selection.setEndPos(%f, %f);", endX, endY); this.loadUrl(saveEndString); } } //***************************************************** //* //* Context Menu Creation //* //***************************************************** /** * Shows the context menu using the given region as an anchor point. * @param region */ private void showContextMenu(Rect displayRect){ // Don't show this twice if(this.contextMenuVisible){ return; } // Don't use empty rect //if(displayRect.isEmpty()){ if(displayRect.right <= displayRect.left){ return; } ActionItem buttonThree = new ActionItem(); buttonThree.setTitle("Add Note"); buttonThree.setActionId(3); // buttonThree.setIcon(getResources().getDrawable(R.drawable.menu_eraser)); // The action menu mContextMenu = new QuickAction(this.getContext()); mContextMenu.setOnDismissListener(this); // Add buttons /// mContextMenu.addActionItem(buttonOne); //mContextMenu.addActionItem(buttonTwo); mContextMenu.addActionItem(buttonThree); //setup the action item click listener mContextMenu.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() { @Override public void onItemClick(QuickAction source, int pos, int actionId) { // TODO Auto-generated method stub if (actionId == 1) { // Do Button 1 stuff Log.i(TAG, "Hit Button 1"); ((Activity)ctx).runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub //SelectionWebView.this.setWebViewClient(new MyWebview()); SelectionWebView.this.getSettings().setJavaScriptEnabled(true); ViewPagerAdapter.getAudio(); // SelectionWebView.this.getSettings().setJavaScriptEnabled(true); // SelectionWebView.this.loadUrl("javascript:highlightsTextAudio();"); ///SelectionWebView.this.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT"); // SelectionWebView.this.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');"); } }); } /*else if (actionId == 2) { // Do Button 2 stuff Log.i(TAG, "Hit Button 2"); } */ else if (actionId == 3) { // Do Button 3 stuff Log.i(TAG, "Hit Button 3"); ((Activity)ctx).runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub //SelectionWebView.this.setWebViewClient(new MyWebview()); SelectionWebView.this.getSettings().setJavaScriptEnabled(true); saveNoteDetail(); } }); } contextMenuVisible = false; } }); this.contextMenuVisible = true; mContextMenu.show(this, displayRect); } public void SetAudio(String Id,String HTMLName){ if(Id.contains("external")) { System.out.println("ID:::::::::::::::::::::::::::::::::::::::::::::::"+Id); Uri partialUri = Uri.parse("content://media"+Id); Cursor cursor = ctx.getContentResolver().query(partialUri, new String[] { android.provider.MediaStore.Audio.AudioColumns.DATA }, null, null, null);//("content://media/external/audio/media/4743.mp3", new String[] { android.provider.MediaStore.Audio.AudioColumns.DATA }, null, null, null); cursor.moveToFirst(); URLID = cursor.getString(0); cursor.close(); }else{ URLID = Id; } HTMLFileLocation=HTMLName; SelectionWebView.this.getSettings().setJavaScriptEnabled(true); SelectionWebView.this.loadUrl("javascript:highlightsTextAudio();"); //SelectionWebView.this.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT"); SelectionWebView.this.loadUrl("javascript:window.HTMLOUT.showHTML2('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');"); ///SelectionWebView.this.loadUrl(); } public class MyJavaScriptInterface { String html6; @SuppressWarnings("unused") public void getIdAudio(String html5) { html6=html5; mNoteId = html5.replace("audioImage:", ""); } @SuppressWarnings("unused") public void showHTML2(String html) { if(HTMLFileLocation!=null){ HTMLFileLocation=HTMLFileLocation; html=html.replace(android.os.Environment.getExternalStorageDirectory()+File.separator +PlaysDetailActivity.CONTENT_LOCATION+File.separator +"nypl_audio-", URLID);////.replace(html6, mNoteId); html=html.replace("nypl_audio-", URLID); }else{ HTMLFileLocation=PlaysDetailActivity.HTMLFileName; } File cacheDir; ///cacheDir=new File(android.os.Environment.getExternalStorageDirectory(), "contents"); cacheDir=new File(android.os.Environment.getExternalStorageDirectory(), PlaysDetailActivity.CONTENT_LOCATION+File.separator); ///"Android/data/"+this.getPackageName() xml_file_path = new File(cacheDir,HTMLFileLocation); FileOutputStream fos; byte[] data = new String(html).getBytes(); try { System.out.println("data:::::::"+data); fos = new FileOutputStream(xml_file_path); System.out.println("fos:::::::"+fos); fos.write(data); fos.flush(); fos.close(); //String filePath = "file://"+path+xml_file_path; //SelectionWebView.this.loadUrl(filePath); } catch (FileNotFoundException e) { // handle exception } catch (IOException e) { // handle exception } System.out.println("SelectionWebView 690"); //String filePath = "file://"+path+"/HTMLContent/"+HTMLFileLocation String filePath = "file:///"+FilePath.getAbsolutePath() + File.separator+ PlaysDetailActivity.CONTENT_LOCATION + File.separator +HTMLFileLocation; SelectionWebView.this.loadUrl(filePath); /*System.out.println("xml_file_path:::::::"+xml_file_path); new AlertDialog.Builder(ctx) .setTitle("HTML") .setMessage(html) .setPositiveButton(android.R.string.ok, null) .setCancelable(false) .create() .show(); */ } @SuppressWarnings("unused") public void showHTML(String html) { HTMLFileLocation=PlaysDetailActivity.HTMLFileName; File cacheDir; cacheDir=new File(android.os.Environment.getExternalStorageDirectory(), PlaysDetailActivity.CONTENT_LOCATION+File.separator); xml_file_path = new File(cacheDir,HTMLFileLocation); FileOutputStream fos; byte[] data = new String(html).getBytes(); try { System.out.println("data:::::::"+data); fos = new FileOutputStream(xml_file_path); System.out.println("fos:::::::"+fos); fos.write(data); fos.flush(); fos.close(); //String filePath = "file://"+path+xml_file_path; //SelectionWebView.this.loadUrl(filePath); } catch (FileNotFoundException e) { // handle exception } catch (IOException e) { // handle exception } } @SuppressWarnings("unused") public void getId(String html5) { mNoteId = html5.replace("highlight:", ""); PlayNoteDAO.saveNotes(ctx,mNoteId,SelectionWebView.this.mText,PlaysDetailActivity.PlayID,PlaysDetailActivity.VersionID,PlaysDetailActivity.VersionName,textString.trim()); } } public void saveNoteDetail(){ mPlayNoteDialog=new Dialog(ctx,R.style.FullHeightDialog); mPlayNoteDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); mPlayNoteDialog.setContentView(R.layout.popup_notes); mNoteText=(EditText) mPlayNoteDialog.findViewById(R.id.popup_note_txt); mSaveBtn= (Button) mPlayNoteDialog.findViewById(R.id.btn_save); mCancelBtn= (Button) mPlayNoteDialog.findViewById(R.id.btn_cancel); mSaveBtn.setOnClickListener(new OnClickListener() { private ImageView mPlayNote; @Override public void onClick(View v) { textString = mNoteText.getText().toString(); if (textString != null && textString.trim().length() ==0) { Toast.makeText(ctx, "Please enter note text", Toast.LENGTH_LONG).show(); } else { pd = ProgressDialog.show(ctx, "Loading", "please wait..."); SelectionWebView.this.loadUrl("javascript:highlightsText();"); SelectionWebView.this.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');"); mPlayNoteDialog.cancel(); InputMethodManager inputMethodManager=(InputMethodManager)ctx.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null){ mPlayNoteDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); } SelectionWebView.this.pd.dismiss(); Toast.makeText(ctx, "Note saved successfully.", Toast.LENGTH_LONG).show(); } } }); mCancelBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mPlayNoteDialog.cancel(); // SelectionWebView.this.loadUrl("javascript:deletetagValue("+mNoteId+");"); } }); mPlayNoteDialog.show(); InputMethodManager inputMethodManager=(InputMethodManager)ctx.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null){ mPlayNoteDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } //***************************************************** //* //* OnDismiss Listener //* //***************************************************** /** * Clears the selection when the context menu is dismissed. */ public void onDismiss(){ //clearSelection(); this.contextMenuVisible = false; } //***************************************************** //* //* Text Selection Javascript Interface Listener //* //***************************************************** /** * Shows/updates the context menu based on the range */ public void tsjiJSError(String error){ Log.e(TAG, "JSError: " + error); } /** * The user has started dragging the selection handles. */ public void tsjiStartSelectionMode(){ this.startSelectionMode(); } /** * The user has stopped dragging the selection handles. */ public void tsjiEndSelectionMode(){ this.endSelectionMode(); } /** * The selection has changed * @param range * @param text * @param handleBounds * @param menuBounds * @param showHighlight * @param showUnHighlight */ public void tsjiSelectionChanged(String range, String text, String handleBounds, String menuBounds){ try { System.out.println("range is "+range); System.out.println("text is::::::::::::::: "+text); mRange=range; mText=text; JSONObject selectionBoundsObject = new JSONObject(handleBounds); float scale = getDensityIndependentValue(this.getScale(), ctx); Rect handleRect = new Rect(); handleRect.left = (int) (getDensityDependentValue(selectionBoundsObject.getInt("left"), getContext()) * scale); handleRect.top = (int) (getDensityDependentValue(selectionBoundsObject.getInt("top"), getContext()) * scale); handleRect.right = (int) (getDensityDependentValue(selectionBoundsObject.getInt("right"), getContext()) * scale); handleRect.bottom = (int) (getDensityDependentValue(selectionBoundsObject.getInt("bottom"), getContext()) * scale); this.mSelectionBounds = handleRect; this.selectedRange = range; this.selectedText = text; JSONObject menuBoundsObject = new JSONObject(menuBounds); Rect displayRect = new Rect(); displayRect.left = (int) (getDensityDependentValue(menuBoundsObject.getInt("left"), getContext()) * scale); displayRect.top = (int) (getDensityDependentValue(menuBoundsObject.getInt("top") - 25, getContext()) * scale); displayRect.right = (int) (getDensityDependentValue(menuBoundsObject.getInt("right"), getContext()) * scale); displayRect.bottom = (int) (getDensityDependentValue(menuBoundsObject.getInt("bottom") + 25, getContext()) * scale); if(!this.isInSelectionMode()){ this.startSelectionMode(); } // This will send the menu rect this.showContextMenu(displayRect); drawSelectionHandles(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Receives the content width for the page. */ public void tsjiSetContentWidth(float contentWidth){ this.contentWidth = (int) this.getDensityDependentValue(contentWidth, ctx); } //***************************************************** //* //* Density Conversion //* //***************************************************** /** * Returns the density dependent value of the given float * @param val * @param ctx * @return */ public float getDensityDependentValue(float val, Context ctx){ // Get display from context Display display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // Calculate min bound based on metrics DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); return val * (metrics.densityDpi / 160f); //return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, val, metrics); } /** * Returns the density independent value of the given float * @param val * @param ctx * @return */ public float getDensityIndependentValue(float val, Context ctx){ // Get display from context Display display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // Calculate min bound based on metrics DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); return val / (metrics.densityDpi / 160f); //return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, val, metrics); } }
3e0f5c3e634d4b3c9ddf0e30b339554b2e6b8548
488
java
Java
app/src/androidTest/java/com/smartlab/drivetrain/license/ApplicationTest.java
tempest1/ChinaDriveTrainingMobileAndroid
bc7796cbc472470a1c1e4a4c3332822b1b1bdf8e
[ "Apache-2.0" ]
null
null
null
app/src/androidTest/java/com/smartlab/drivetrain/license/ApplicationTest.java
tempest1/ChinaDriveTrainingMobileAndroid
bc7796cbc472470a1c1e4a4c3332822b1b1bdf8e
[ "Apache-2.0" ]
null
null
null
app/src/androidTest/java/com/smartlab/drivetrain/license/ApplicationTest.java
tempest1/ChinaDriveTrainingMobileAndroid
bc7796cbc472470a1c1e4a4c3332822b1b1bdf8e
[ "Apache-2.0" ]
null
null
null
25.684211
93
0.690574
6,520
package com.smartlab.drivetrain.license; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } public void test () throws Exception{ final int i = 1; final int j = 1; assertEquals(i,j); } }
3e0f5cd206bb0f050cae83bd53e4cc2c2fdf7694
2,859
java
Java
hivemq-getting-started-public-broker/src/main/java/com/hivemq/HiveMqPublicExample.java
hivemq/hivemq-examples
52585bf9c392a259a8e2487be89abbf2ab8d4708
[ "Apache-2.0" ]
4
2020-03-17T13:25:49.000Z
2022-01-30T04:36:15.000Z
hivemq-getting-started-public-broker/src/main/java/com/hivemq/HiveMqPublicExample.java
hivemq/hivemq-examples
52585bf9c392a259a8e2487be89abbf2ab8d4708
[ "Apache-2.0" ]
null
null
null
hivemq-getting-started-public-broker/src/main/java/com/hivemq/HiveMqPublicExample.java
hivemq/hivemq-examples
52585bf9c392a259a8e2487be89abbf2ab8d4708
[ "Apache-2.0" ]
2
2021-08-18T09:51:21.000Z
2022-01-02T06:50:48.000Z
36.653846
124
0.614201
6,521
package com.hivemq; import com.hivemq.client.mqtt.mqtt5.Mqtt5Client; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; public class HiveMqPublicExample { public static void main(String[] args) throws InterruptedException, UnknownHostException, SocketException { InetAddress localHost = InetAddress.getLocalHost(); NetworkInterface ni = NetworkInterface.getByInetAddress(localHost); byte[] hardwareAddress = ni.getHardwareAddress(); // use this to get your MAC address, use it as a unique identifier // 1. create the client final Mqtt5Client client = Mqtt5Client.builder() .identifier("sensor-" + hardwareAddress) // use a unique identifier .serverHost("broker.hivemq.com") // use the public HiveMQ broker .automaticReconnectWithDefaultConfig() // the client automatically reconnects .build(); // 2. connect the client client.toBlocking().connectWith() .willPublish() .topic("home/will") .payload("sensor gone".getBytes()) .applyWillPublish() .send(); // 3. subscribe and consume messages client.toAsync().subscribeWith() .topicFilter("home/#") .callback(publish -> { System.out.println("Received message on topic " + publish.getTopic() + ": " + new String(publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); }) .send(); // 4. simulate periodic publishing of sensor data while (true) { client.toBlocking().publishWith() .topic("home/brightness") .payload(getBrightness()) .send(); TimeUnit.MILLISECONDS.sleep(500); client.toBlocking().publishWith() .topic("home/temperature") .payload(getTemperature()) .send(); TimeUnit.MILLISECONDS.sleep(500); } } private static byte[] getBrightness() { // simulate a brightness sensor with values between 1000lux and 10000lux final int brightness = ThreadLocalRandom.current().nextInt(1_000, 10_000); return (brightness + "lux").getBytes(StandardCharsets.UTF_8); } private static byte[] getTemperature() { // simulate a temperature sensor with values between 20°C and 30°C final int temperature = ThreadLocalRandom.current().nextInt(20, 30); return (temperature + "°C").getBytes(StandardCharsets.UTF_8); } }
3e0f5cf1cf741f48fa7184c42093af27c58108e1
1,047
java
Java
src/main/java/com/ontotext/trree/plugin/autocomplete/AbstractEntitiesIterator.java
Ontotext-AD/graphdb-autocomplete-plugin
4ea4da340610d6f5858b3b7e858872be266dd857
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ontotext/trree/plugin/autocomplete/AbstractEntitiesIterator.java
Ontotext-AD/graphdb-autocomplete-plugin
4ea4da340610d6f5858b3b7e858872be266dd857
[ "Apache-2.0" ]
1
2019-12-06T12:01:29.000Z
2019-12-06T12:01:29.000Z
src/main/java/com/ontotext/trree/plugin/autocomplete/AbstractEntitiesIterator.java
Ontotext-AD/graphdb-autocomplete-plugin
4ea4da340610d6f5858b3b7e858872be266dd857
[ "Apache-2.0" ]
1
2019-09-24T10:22:12.000Z
2019-09-24T10:22:12.000Z
24.928571
83
0.728749
6,522
package com.ontotext.trree.plugin.autocomplete; import org.apache.lucene.search.suggest.InputIterator; import org.apache.lucene.util.BytesRef; import org.eclipse.rdf4j.model.IRI; import java.util.Set; /** * Created by Pavel Mihaylov on 13/08/2020. */ public abstract class AbstractEntitiesIterator implements InputIterator { protected long currentIteratorIndex = 0L; protected IRI currentURI; protected String currentLocalName; protected final AutocompleteIndex autocompleteIndex; AbstractEntitiesIterator(AutocompleteIndex autocompleteIndex) { this.autocompleteIndex = autocompleteIndex; } @Override public long weight() { return autocompleteIndex.getWeight(currentIteratorIndex, currentLocalName); } @Override public boolean hasPayloads() { return true; } @Override public Set<BytesRef> contexts() { return autocompleteIndex.getURINamespaceAsContext(currentURI); } @Override public boolean hasContexts() { return true; } }
3e0f5d3918b2da02dac0a32196b933e5d4a5798f
1,002
java
Java
eclipse-workspace/KOPO_javaBase/src/ch02/P03_re.java
blueduckgraymouse/KOPO_SoftwareCoding
4a84f4cc84045fda05a6d6b5d03311856a3826f1
[ "MIT" ]
null
null
null
eclipse-workspace/KOPO_javaBase/src/ch02/P03_re.java
blueduckgraymouse/KOPO_SoftwareCoding
4a84f4cc84045fda05a6d6b5d03311856a3826f1
[ "MIT" ]
null
null
null
eclipse-workspace/KOPO_javaBase/src/ch02/P03_re.java
blueduckgraymouse/KOPO_SoftwareCoding
4a84f4cc84045fda05a6d6b5d03311856a3826f1
[ "MIT" ]
null
null
null
20.875
76
0.557884
6,523
package ch02; import java.util.Scanner; /** * Calculating Change Program * Calculate Gap And Change * * @author KOPO */ public class P03_re { public static void main(String[] args) { int[] n = {0,0}; // input int[] bill = {50000, 10000, 5000, 1000, 500, 100, 50, 10}; // bill type int[] changes = {0 ,0, 0, 0, 0, 0, 0, 0}; // bill counted int cur_change = 0; // temp change in calculation Scanner sc = new Scanner(System.in); // input number System.out.print("Input number1 : "); n[0] = sc.nextInt(); System.out.print("Input number2 : "); n[1] = sc.nextInt(); // calculate change cur_change = n[0] - n[1]; System.out.println("\nsub\t - " + cur_change + "\n"); for(int i=0; i<bill.length ; i++) { changes[i] = cur_change / bill[i]; cur_change = cur_change % bill[i]; } // print change for(int i=0; i<changes.length ; i++) { System.out.println(bill[i] + "\t - " + changes[i]); } } }
3e0f60adcb9019e032b67612d4d3513c477c6407
394
java
Java
src/main/java/br/com/rpolnx/spring_cloud_stream_rabbitmq_poc/broker/Source.java
rpolnx/spring-cloud-stream-rabbitmq-poc
56b89e95b669eca6ed4de8f1e3e757daeefbd5f0
[ "MIT" ]
null
null
null
src/main/java/br/com/rpolnx/spring_cloud_stream_rabbitmq_poc/broker/Source.java
rpolnx/spring-cloud-stream-rabbitmq-poc
56b89e95b669eca6ed4de8f1e3e757daeefbd5f0
[ "MIT" ]
null
null
null
src/main/java/br/com/rpolnx/spring_cloud_stream_rabbitmq_poc/broker/Source.java
rpolnx/spring-cloud-stream-rabbitmq-poc
56b89e95b669eca6ed4de8f1e3e757daeefbd5f0
[ "MIT" ]
null
null
null
23.176471
62
0.784264
6,524
package br.com.rpolnx.spring_cloud_stream_rabbitmq_poc.broker; import org.springframework.cloud.stream.annotation.Output; import org.springframework.messaging.MessageChannel; public interface Source { String OUTPUT1 = "custom-channel-1"; String OUTPUT2 = "custom-channel-2"; @Output(Source.OUTPUT1) MessageChannel output1(); @Output(Source.OUTPUT2) MessageChannel output2(); }
3e0f60d7cb93ba95f8f6e33979ecc0d7f4d37e5e
570
java
Java
src/main/java/cc/sfclub/util/common/Http.java
iceBear67/Util
58504a71c0829cd9a07a94e9ace0a18a545e2693
[ "Apache-2.0" ]
null
null
null
src/main/java/cc/sfclub/util/common/Http.java
iceBear67/Util
58504a71c0829cd9a07a94e9ace0a18a545e2693
[ "Apache-2.0" ]
null
null
null
src/main/java/cc/sfclub/util/common/Http.java
iceBear67/Util
58504a71c0829cd9a07a94e9ace0a18a545e2693
[ "Apache-2.0" ]
null
null
null
24.782609
92
0.635088
6,525
package cc.sfclub.util.common; import lombok.SneakyThrows; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; public class Http { @SneakyThrows public static String get(String _url) { URL url = new URL(_url); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s; StringBuilder sb = new StringBuilder(); while ((s = reader.readLine()) != null) { sb.append(s); } reader.close(); return sb.toString(); } }
3e0f60f58b77ac8b7304c3090eed7bcb820244ea
3,087
java
Java
platform-pojo-bl/src/main/java/ua/com/fielden/platform/entity/factory/DefaultCompanionObjectFinderImpl.java
fieldenms/
4efd3b2475877d434a57cbba638b711df95748e7
[ "MIT" ]
16
2017-03-22T05:42:26.000Z
2022-01-17T22:38:38.000Z
platform-pojo-bl/src/main/java/ua/com/fielden/platform/entity/factory/DefaultCompanionObjectFinderImpl.java
fieldenms/
4efd3b2475877d434a57cbba638b711df95748e7
[ "MIT" ]
647
2017-03-21T07:47:44.000Z
2022-03-31T13:03:47.000Z
platform-pojo-bl/src/main/java/ua/com/fielden/platform/entity/factory/DefaultCompanionObjectFinderImpl.java
fieldenms/
4efd3b2475877d434a57cbba638b711df95748e7
[ "MIT" ]
8
2017-03-21T08:26:56.000Z
2020-06-27T01:55:09.000Z
37.646341
159
0.673469
6,526
package ua.com.fielden.platform.entity.factory; import static java.lang.String.format; import org.apache.log4j.Logger; import com.google.inject.Inject; import com.google.inject.Injector; import ua.com.fielden.platform.companion.ICanReadUninstrumented; import ua.com.fielden.platform.companion.IEntityReader; import ua.com.fielden.platform.dao.IEntityDao; import ua.com.fielden.platform.dao.exceptions.EntityCompanionException; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.annotation.CompanionObject; /** * Default implementation for {@link ICompanionObjectFinder}, which utilises injector for creating controller instances. * * @author TG Team * */ public class DefaultCompanionObjectFinderImpl implements ICompanionObjectFinder { private static final Logger LOGGER = Logger.getLogger(DefaultCompanionObjectFinderImpl.class); private final Injector injector; @Inject public DefaultCompanionObjectFinderImpl(final Injector injector) { this.injector = injector; } @Override public <T extends IEntityDao<E>, E extends AbstractEntity<?>> T find(final Class<E> type) { return find(type, false); } @Override public <T extends IEntityReader<E>, E extends AbstractEntity<?>> T findAsReader(final Class<E> type, final boolean uninstrumented) { return find(type, uninstrumented); } @Override public <T extends IEntityDao<E>, E extends AbstractEntity<?>> T find(final Class<E> type, final boolean uninstrumented) { if (type.isAnnotationPresent(CompanionObject.class)) { try { final Class<T> coType = (Class<T>) type.getAnnotation(CompanionObject.class).value(); final T co = injector.getInstance(coType); return decideUninstrumentation(uninstrumented, coType, co); } catch (final EntityCompanionException e) { throw e; } catch (final Exception e) { LOGGER.warn(format("Could not locate companion for type [%s].", type.getName()), e); // if controller could not be instantiated for whatever reason it can be considered non-existent // thus, returning null return null; } } return null; } /** * A helper method to decide whether the instantiated companion should read instrumented or uninstrumented entities. * * @param uninstrumented * @param coType * @param co * @return */ private <T extends IEntityDao<E>, E extends AbstractEntity<?>> T decideUninstrumentation(final boolean uninstrumented, final Class<T> coType, final T co) { if (uninstrumented) { if (co instanceof ICanReadUninstrumented) { ((ICanReadUninstrumented) co).readUninstrumented(); } else { throw new EntityCompanionException(format("Cannot produce uninstrumented companion of type [%s].", coType.getName())); } } return co; } }
3e0f62b8daffaec64a3a906e78cf904cc61f2924
2,671
java
Java
Mage.Sets/src/mage/cards/k/KrakenOfTheStraits.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage.Sets/src/mage/cards/k/KrakenOfTheStraits.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage.Sets/src/mage/cards/k/KrakenOfTheStraits.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
32.975309
128
0.751404
6,527
package mage.cards.k; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.dynamicvalue.DynamicValue; import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount; import mage.abilities.effects.RestrictionEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import mage.constants.Zone; import mage.filter.common.FilterControlledPermanent; import mage.game.Game; import mage.game.permanent.Permanent; import java.util.UUID; /** * @author LevelX2 */ public final class KrakenOfTheStraits extends CardImpl { public KrakenOfTheStraits(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{5}{U}{U}"); this.subtype.add(SubType.KRAKEN); this.power = new MageInt(6); this.toughness = new MageInt(6); // Creatures with power less than the number of Islands you control can't block Kraken of the Straits. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new CantBeBlockedByCreaturesWithLessPowerEffect())); } private KrakenOfTheStraits(final KrakenOfTheStraits card) { super(card); } @Override public KrakenOfTheStraits copy() { return new KrakenOfTheStraits(this); } } class CantBeBlockedByCreaturesWithLessPowerEffect extends RestrictionEffect { private static final FilterControlledPermanent filter = new FilterControlledPermanent("Islands"); static { filter.add(SubType.ISLAND.getPredicate()); } private final DynamicValue dynamicValue = new PermanentsOnBattlefieldCount(filter); public CantBeBlockedByCreaturesWithLessPowerEffect() { super(Duration.WhileOnBattlefield); staticText = "Creatures with power less than the number of Islands you control can't block {this}"; } public CantBeBlockedByCreaturesWithLessPowerEffect(final CantBeBlockedByCreaturesWithLessPowerEffect effect) { super(effect); } @Override public boolean applies(Permanent permanent, Ability source, Game game) { return permanent.getId().equals(source.getSourceId()); } @Override public boolean canBeBlocked(Permanent attacker, Permanent blocker, Ability source, Game game, boolean canUseChooseDialogs) { return blocker.getPower().getValue() >= dynamicValue.calculate(game, source, this); } @Override public CantBeBlockedByCreaturesWithLessPowerEffect copy() { return new CantBeBlockedByCreaturesWithLessPowerEffect(this); } }
3e0f62ccc4d6341a875fa9cb67570c539ec4351a
1,236
java
Java
src/main/java/pl/decerto/hyperon/demo/dictionary/dict/impl/MultiValueDictionary.java
hyperon-io/dictionary-engine
07e301cc1db7fc64068b2da1a3eaeba1b55de9da
[ "Apache-2.0" ]
null
null
null
src/main/java/pl/decerto/hyperon/demo/dictionary/dict/impl/MultiValueDictionary.java
hyperon-io/dictionary-engine
07e301cc1db7fc64068b2da1a3eaeba1b55de9da
[ "Apache-2.0" ]
null
null
null
src/main/java/pl/decerto/hyperon/demo/dictionary/dict/impl/MultiValueDictionary.java
hyperon-io/dictionary-engine
07e301cc1db7fc64068b2da1a3eaeba1b55de9da
[ "Apache-2.0" ]
null
null
null
26.869565
93
0.798544
6,528
package pl.decerto.hyperon.demo.dictionary.dict.impl; import static pl.decerto.hyperon.demo.dictionary.dict.impl.MultiValueKeyNormalizer.normalize; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; import pl.decerto.hyperon.demo.dictionary.dict.Dictionary; import pl.decerto.hyperon.demo.dictionary.dict.DictionaryEntry; /** * Class of multi-column dictionary */ @RequiredArgsConstructor @ToString @EqualsAndHashCode @Getter @Builder class MultiValueDictionary implements Dictionary { private final Set<String> levels; private final Map<String, MultiValueDictionaryEntry> entries; @Override public Optional<DictionaryEntry> getEntry(String key) { return Optional.ofNullable(entries.get(normalize(key))); } @Override public Optional<DictionaryEntry> getLevelEntry(String key, String level) { return Optional.ofNullable(entries.get(normalize(key))) .flatMap(entry -> entry.getSubEntry(level)); } @Override public List<DictionaryEntry> getEntries() { return new ArrayList<>(entries.values()); } }