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
3e115fb11c5a3d3f6201180b91b4b32f60931b3b
170
java
Java
OpenEdXMobile/src/main/java/sa/gov/moe/etraining/model/api/AuthErrorResponse.java
ilearninteractive/mobileAPP
d661b8aecb871e21378f317665dfdd97217b633d
[ "Apache-2.0" ]
1
2019-06-07T01:06:03.000Z
2019-06-07T01:06:03.000Z
OpenEdXMobile/src/main/java/sa/gov/moe/etraining/model/api/AuthErrorResponse.java
ilearninteractive/mobileAPP
d661b8aecb871e21378f317665dfdd97217b633d
[ "Apache-2.0" ]
1
2018-11-07T09:17:55.000Z
2018-11-07T09:17:55.000Z
OpenEdXMobile/src/main/java/sa/gov/moe/etraining/model/api/AuthErrorResponse.java
ilearninteractive/mobileAPP
d661b8aecb871e21378f317665dfdd97217b633d
[ "Apache-2.0" ]
1
2018-08-15T08:51:17.000Z
2018-08-15T08:51:17.000Z
21.25
66
0.729412
7,333
package sa.gov.moe.etraining.model.api; public class AuthErrorResponse { // {"detail": "Authentication credentials were not provided."} public String detail; }
3e115fe2b60645a4b7cbe38d8f4ac0e31989c748
18,457
java
Java
zm-mailbox/store/src/java/com/zimbra/qa/unittest/TestRemoteImapMultiServer.java
hernad/zimbra9
cf61ffa40d9600ab255ef4516ca25029fff6603b
[ "Apache-2.0" ]
null
null
null
zm-mailbox/store/src/java/com/zimbra/qa/unittest/TestRemoteImapMultiServer.java
hernad/zimbra9
cf61ffa40d9600ab255ef4516ca25029fff6603b
[ "Apache-2.0" ]
null
null
null
zm-mailbox/store/src/java/com/zimbra/qa/unittest/TestRemoteImapMultiServer.java
hernad/zimbra9
cf61ffa40d9600ab255ef4516ca25029fff6603b
[ "Apache-2.0" ]
null
null
null
43.840855
217
0.692529
7,334
package com.zimbra.qa.unittest; import static com.zimbra.common.util.TaskUtil.newDaemonThreadFactory; import static java.util.concurrent.Executors.newCachedThreadPool; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.sql.Date; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.mail.MessagingException; import javax.security.auth.login.LoginException; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import com.google.common.collect.Maps; import com.zimbra.client.ZFolder; import com.zimbra.client.ZMailbox; import com.zimbra.client.ZMessage; import com.zimbra.common.account.ProvisioningConstants; import com.zimbra.common.localconfig.LC; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.AdminConstants; import com.zimbra.common.util.Log; import com.zimbra.cs.account.Account; import com.zimbra.cs.account.AuthTokenException; import com.zimbra.cs.account.Provisioning; import com.zimbra.cs.account.Server; import com.zimbra.cs.account.soap.SoapProvisioning; import com.zimbra.cs.imap.ImapProxy.ZimbraClientAuthenticator; import com.zimbra.cs.mailbox.Mailbox; import com.zimbra.cs.mailclient.CommandFailedException; import com.zimbra.cs.mailclient.auth.AuthenticatorFactory; import com.zimbra.cs.mailclient.imap.AppendResult; import com.zimbra.cs.mailclient.imap.Body; import com.zimbra.cs.mailclient.imap.BodyStructure; import com.zimbra.cs.mailclient.imap.Envelope; import com.zimbra.cs.mailclient.imap.Flags; import com.zimbra.cs.mailclient.imap.IDInfo; import com.zimbra.cs.mailclient.imap.ImapConfig; import com.zimbra.cs.mailclient.imap.ImapConnection; import com.zimbra.cs.mailclient.imap.ListData; import com.zimbra.cs.mailclient.imap.Literal; import com.zimbra.cs.mailclient.imap.MailboxInfo; import com.zimbra.cs.mailclient.imap.MessageData; import com.zimbra.cs.security.sasl.ZimbraAuthenticator; import com.zimbra.cs.service.AuthProvider; import com.zimbra.cs.service.AuthProviderException; import com.zimbra.cs.util.BuildInfo; import junit.framework.Assert; public class TestRemoteImapMultiServer { private static final String USER = "TestRemoteImap-user"; private static final String PASS = "test123"; private String[] imapServersForLocalhost = null; private static boolean mHomeDisplayMailFoldersOnly; private static boolean mIMAPDisplayMailFoldersOnly; private Server homeServer = null; private Server imapServer = null; private Account acc = null; private ImapConnection connection; private static final Provisioning prov = Provisioning.getInstance(); private static final SoapProvisioning sp = new SoapProvisioning(); private static List<Server> servers; private static AuthenticatorFactory ZIMBRA_AUTH_FACTORY = new AuthenticatorFactory(); @BeforeClass public static void beforeClass() throws Exception { servers = prov.getAllServers(Provisioning.SERVICE_MAILBOX); ZIMBRA_AUTH_FACTORY.register(ZimbraAuthenticator.MECHANISM, ZimbraClientAuthenticator.class); sp.soapSetURI(LC.zimbra_admin_service_scheme.value() + servers.get(0).getServiceHostname() + ":" + servers.get(0).getAdminPort() + AdminConstants.ADMIN_SERVICE_URI); sp.soapZimbraAdminAuthenticate(); } @Before public void setUp() throws ServiceException, IOException { TestUtil.assumeTrue(String.format("Number of servers=%d needs to be > 1", servers.size()), servers.size() > 1); cleanup(); homeServer = servers.get(0); imapServer = servers.get(1); mHomeDisplayMailFoldersOnly = homeServer.isImapDisplayMailFoldersOnly(); mIMAPDisplayMailFoldersOnly = imapServer.isImapDisplayMailFoldersOnly(); homeServer.setImapDisplayMailFoldersOnly(false); imapServer.setImapDisplayMailFoldersOnly(false); Map<String, Object> attrs = Maps.newHashMap(); attrs.put(Provisioning.A_zimbraMailHost, homeServer.getServiceHostname()); attrs.put(Provisioning.A_zimbraFeatureIMEnabled, ProvisioningConstants.TRUE); acc = TestUtil.createAccount(USER, attrs); Provisioning.getInstance().setPassword(acc, PASS); //preserve original setting, so we can set it back on tearDown imapServersForLocalhost = homeServer.getReverseProxyUpstreamImapServers(); //homeServer will be the mailbox server and imapServer will be the remote IMAP homeServer.setReverseProxyUpstreamImapServers(new String[]{imapServer.getServiceHostname()}); sp.flushCache("all", null, true); } private void cleanup() throws ServiceException { if(TestUtil.accountExists(USER)) { TestUtil.deleteAccount(USER); } } @After public void tearDown() throws ServiceException { cleanup(); if(homeServer != null) { homeServer.setReverseProxyUpstreamImapServers(imapServersForLocalhost); homeServer.setImapDisplayMailFoldersOnly(mHomeDisplayMailFoldersOnly); } if(imapServer != null) { imapServer.setImapDisplayMailFoldersOnly(mIMAPDisplayMailFoldersOnly); } sp.flushCache("all", null, true); } private ImapConnection connect(Server server) throws IOException { ImapConfig config = new ImapConfig(server.getServiceHostname()); config.setPort(server.getImapBindPort()); config.setAuthenticationId(USER); config.getLogger().setLevel(Log.Level.trace); ImapConnection connection = new ImapConnection(config); connection.connect(); return connection; } private ImapConnection connectAsProxy(Server server) throws IOException { ImapConfig config = new ImapConfig(server.getServiceHostname()); config.setPort(server.getImapBindPort()); config.setAuthenticationId(USER); config.setAuthenticatorFactory(ZIMBRA_AUTH_FACTORY); config.setMechanism(ZimbraAuthenticator.MECHANISM); config.getLogger().setLevel(Log.Level.trace); ImapConnection connection = new ImapConnection(config); connection.connect(); return connection; } @Test public void testAUTHENTICATEToIMAPHost() throws IOException { connection = connect(imapServer); connection.login(PASS); assertTrue("IMAP connection is not authenticated", connection.isAuthenticated()); } @Test public void testAUTHENTICATEToHomeHost() throws IOException { connection = connect(homeServer); try { connection.login(PASS); } catch (CommandFailedException e) { assertNotNull(e); assertTrue("Should toget 'LOGIN failed' error from home server", e.getMessage().indexOf("LOGIN failed") > -1); } assertFalse("IMAP connection should not be authenticated", connection.isAuthenticated()); } @Test public void testAuthenticateAsProxyToIMAPHost() throws IOException, LoginException, AuthProviderException, AuthTokenException { connection = connectAsProxy(imapServer); IDInfo id = new IDInfo(); id.put(IDInfo.NAME, "ZCS"); id.put(IDInfo.VERSION, BuildInfo.VERSION); connection.id(id); connection.authenticate(AuthProvider.getAuthToken(acc).getEncoded()); assertTrue("IMAP connection is not authenticated", connection.isAuthenticated()); } @Test public void testAuthenticateAsProxyToHomeHost() throws IOException, LoginException, AuthProviderException, AuthTokenException { connection = connectAsProxy(homeServer); IDInfo id = new IDInfo(); id.put(IDInfo.NAME, "ZCS"); id.put(IDInfo.VERSION, BuildInfo.VERSION); connection.id(id); connection.authenticate(AuthProvider.getAuthToken(acc).getEncoded()); assertTrue("IMAP connection is not authenticated", connection.isAuthenticated()); } @Test public void testFolderList() throws IOException { connection = connect(imapServer); connection.login(PASS); Assert.assertTrue("IMAP connection is not authenticated", connection.isAuthenticated()); List<ListData> listResult = connection.list("", "*"); assertNotNull(listResult); Assert.assertTrue("Should have at least 5 subscriptions ", listResult.size() >= 5); SharedImapTests.verifyFolderList(listResult); } @Test public void testMailOnlyFolderList() throws IOException, ServiceException { imapServer.setImapDisplayMailFoldersOnly(true); connection = connect(imapServer); connection.login(PASS); Assert.assertTrue("IMAP connection is not authenticated", connection.isAuthenticated()); List<ListData> listResult = connection.list("", "*"); assertNotNull(listResult); Assert.assertTrue("Should have at least 5 subscriptions ", listResult.size() >= 5); SharedImapTests.verifyFolderList(listResult, true); } @Test public void testListInbox() throws Exception { connection = connect(imapServer); connection.login(PASS); Assert.assertTrue("IMAP connection is not authenticated", connection.isAuthenticated()); List<ListData> listResult = connection.list("", "INBOX"); assertNotNull(listResult); assertEquals("List result should have this number of entries", 1, listResult.size()); } @Ignore("requires SELECT to work") public void testAppend() throws Exception { connection = connect(imapServer); connection.login(PASS); Assert.assertTrue("IMAP connection is not authenticated", connection.isAuthenticated()); assertTrue(connection.hasCapability("UIDPLUS")); Flags flags = Flags.fromSpec("afs"); Date date = new Date(System.currentTimeMillis()); Literal msg = SharedImapTests.message(100000); try { AppendResult res = connection.append("INBOX", flags, date, msg); assertNotNull(res); byte[] b = fetchBody(res.getUid()); assertArrayEquals("content mismatch", msg.getBytes(), b); } finally { msg.dispose(); } } @Test public void testSubscribe() throws IOException, ServiceException { String folderName = "TestRemoteImap-testSubscribe"; TestUtil.createFolder(TestUtil.getZMailbox(USER), folderName); connection = connect(imapServer); connection.login(PASS); Assert.assertTrue("IMAP connection is not authenticated", connection.isAuthenticated()); List<ListData> listResult = connection.lsub("", "*"); assertNotNull(listResult); Assert.assertEquals("Should have 0 subscriptions at this point", 0, listResult.size()); try { connection.subscribe(folderName); } catch (Exception e) { Assert.fail(e.getMessage()); } listResult = connection.lsub("", "*"); assertNotNull(listResult); Assert.assertEquals(1, listResult.size()); Assert.assertTrue("Should be subscribed to " + folderName + ". Instead got " + listResult.get(0).getMailbox(), folderName.equalsIgnoreCase(listResult.get(0).getMailbox())); } @Test public void testSubscribeNested() throws IOException, ServiceException { String folderName = "TestRemoteImap-testSubscribe"; ZFolder folder = TestUtil.createFolder(TestUtil.getZMailbox(USER), Integer.toString(Mailbox.ID_FOLDER_INBOX), folderName); connection = connect(imapServer); connection.login(PASS); Assert.assertTrue("IMAP connection is not authenticated", connection.isAuthenticated()); List<ListData> listResult = connection.lsub("", "*"); assertNotNull(listResult); Assert.assertEquals("Should have 0 subscriptions before subscribing", 0, listResult.size()); try { connection.subscribe(folder.getPath()); } catch (Exception e) { Assert.fail(e.getMessage()); } listResult = connection.lsub("", "*"); assertNotNull(listResult); Assert.assertEquals("Should have found 1 subscription after subscribing", 1, listResult.size()); Assert.assertTrue("Should be subscribed to " + folder.getPath().substring(1) +". Instead got " + listResult.get(0).getMailbox(), folder.getPath().substring(1).equalsIgnoreCase(listResult.get(0).getMailbox())); } @Test public void testUnSubscribe() throws IOException, ServiceException { String folderName = "TestRemoteImap-testSubscribe"; TestUtil.createFolder(TestUtil.getZMailbox(USER), folderName); connection = connect(imapServer); connection.login(PASS); Assert.assertTrue("IMAP connection is not authenticated", connection.isAuthenticated()); List<ListData> listResult = connection.lsub("", "*"); assertNotNull(listResult); Assert.assertEquals("Should have 0 subscriptions before subscribing", 0, listResult.size()); try { connection.subscribe(folderName); } catch (Exception e) { Assert.fail(e.getMessage()); } listResult = connection.lsub("", "*"); assertNotNull(listResult); Assert.assertEquals(1, listResult.size()); Assert.assertTrue("Should be subscribed to " + folderName + ". Instead got " + listResult.get(0).getMailbox(), folderName.equalsIgnoreCase(listResult.get(0).getMailbox())); try { connection.unsubscribe(folderName); } catch (Exception e) { Assert.fail(e.getMessage()); } listResult = connection.lsub("", "*"); assertNotNull(listResult); Assert.assertEquals("Should have 0 subscriptions after unsubscribing", 0, listResult.size()); } @Test public void testCreate() throws Exception { String folderName = "TestRemoteImap-testCreate"; connection = connect(imapServer); connection.login(PASS); Assert.assertFalse(connection.exists(folderName)); connection.create(folderName); Assert.assertTrue(connection.exists(folderName)); } private byte[] fetchBody(long uid) throws IOException { MessageData md = connection.uidFetch(uid, "(BODY.PEEK[])"); assertNotNull("message not found", md); assertEquals(uid, md.getUid()); Body[] bs = md.getBodySections(); assertNotNull(bs); assertEquals(1, bs.length); return bs[0].getImapData().getBytes(); } @Test public void testLOGOUTNotLoggedIn() throws IOException { connection = connect(imapServer); connection.logout(); assertFalse("IMAP connection should not be authenticated after sending LOGOUT", connection.isAuthenticated()); } @Test public void testLOGOUTHomeServer() throws IOException { connection = connect(homeServer); connection.logout(); assertFalse("IMAP connection should not be authenticated after sending LOGOUT", connection.isAuthenticated()); } @Test public void testLOGOUT() throws IOException { connection = connect(imapServer); connection.login(PASS); Assert.assertTrue("IMAP should be authenticated after logging in", connection.isAuthenticated()); connection.logout(); assertFalse("IMAP connection should not be authenticated after sending LOGOUT", connection.isAuthenticated()); } @Test public void testListFolderContents() throws IOException, ServiceException, MessagingException { String folderName = "TestRemoteImap-testOpenFolder"; String subject = "TestRemoteImap-testMessage"; ZMailbox zmbox = TestUtil.getZMailbox(USER); ZFolder folder = TestUtil.createFolder(zmbox, folderName); String msgId = TestUtil.addMessage(zmbox, subject, folder.getId(), null); ZMessage msg = zmbox.getMessageById(msgId); connection = connect(imapServer); connection.login(PASS); MailboxInfo info = connection.select(folderName); Map<Long, MessageData> mdMap = connection.fetch("1:*", "(ENVELOPE INTERNALDATE BODY BODY[TEXT])"); assertEquals(1, mdMap.size()); MessageData md = mdMap.values().iterator().next(); assertNotNull(md); Envelope env = md.getEnvelope(); assertNotNull(env); assertEquals(msg.getSubject(), env.getSubject()); assertEquals(msg.getDate(), md.getInternalDate().getTime()); BodyStructure bs = md.getBodyStructure(); assertNotNull(bs); assertEquals("TEXT", bs.getType()); assertEquals("PLAIN", bs.getSubtype()); assertNotNull(md.getBodySections()); assertEquals(1, md.getBodySections().length); Body body = md.getBodySections()[0]; assertNotNull(body); Literal imapData = (Literal) body.getData(); assertEquals(MessageBuilder.DEFAULT_MESSAGE_BODY, imapData.toString()); } @Test public void testMultipleSelect() throws Exception { String folderName = "TestRemoteImap-testSelectFolder"; ZMailbox zmbox = TestUtil.getZMailbox(USER); TestUtil.createFolder(zmbox, folderName); connection = connect(imapServer); connection.login(PASS); ExecutorService executor = newCachedThreadPool(newDaemonThreadFactory("TestRemoteImap")); for (int i=0; i<3; i++) { Future<MailboxInfo> future = executor.submit(new Callable<MailboxInfo>() { @Override public MailboxInfo call() throws Exception { return connection.select(folderName); } }); try { MailboxInfo info = future.get(5, TimeUnit.SECONDS); assertNotNull(info); } catch (TimeoutException e) { Assert.fail("failed getting a response from SELECT command within 5 seconds"); } } } }
3e11617889bc4c1a3287beb863e63036ea648b72
384
java
Java
gulimall-product/src/main/java/com/baoge/gulimall/product/dao/SpuInfoDescDao.java
Wanbaoping/gulimall
bd3e6f9c364114cca6733439f5a6bb5f4e419121
[ "Apache-2.0" ]
null
null
null
gulimall-product/src/main/java/com/baoge/gulimall/product/dao/SpuInfoDescDao.java
Wanbaoping/gulimall
bd3e6f9c364114cca6733439f5a6bb5f4e419121
[ "Apache-2.0" ]
null
null
null
gulimall-product/src/main/java/com/baoge/gulimall/product/dao/SpuInfoDescDao.java
Wanbaoping/gulimall
bd3e6f9c364114cca6733439f5a6bb5f4e419121
[ "Apache-2.0" ]
null
null
null
21.277778
71
0.770235
7,335
package com.baoge.gulimall.product.dao; import com.baoge.gulimall.product.entity.SpuInfoDescEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * spu信息介绍 * * @author baoge * @email efpyi@example.com * @date 2021-02-01 19:41:21 */ @Mapper public interface SpuInfoDescDao extends BaseMapper<SpuInfoDescEntity> { }
3e1161943c816987c37da6ab44f96951327f447a
1,019
java
Java
src/main/java/gwt/material/design/incubator/client/daterange/constants/DateRangeElementSelector.java
vokke/gwt-material-addins
4014982b0f8b8d1115239e284965a564760d2804
[ "Apache-2.0" ]
37
2015-11-19T15:53:12.000Z
2021-04-03T22:38:18.000Z
src/main/java/gwt/material/design/incubator/client/daterange/constants/DateRangeElementSelector.java
vokke/gwt-material-addins
4014982b0f8b8d1115239e284965a564760d2804
[ "Apache-2.0" ]
360
2015-12-01T15:20:51.000Z
2021-12-23T14:08:34.000Z
src/main/java/gwt/material/design/incubator/client/daterange/constants/DateRangeElementSelector.java
vokke/gwt-material-addins
4014982b0f8b8d1115239e284965a564760d2804
[ "Apache-2.0" ]
57
2015-11-30T17:25:28.000Z
2022-01-29T18:09:10.000Z
32.870968
75
0.720314
7,336
/* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2018 GwtMaterialDesign * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package gwt.material.design.incubator.client.daterange.constants; public interface DateRangeElementSelector { String MONTH_SELECT = ".monthselect"; String YEAR_SELECT = ".yearselect"; String HOUR_SELECT = ".hourselect"; String MINUTE_SELECT = ".minuteselect"; String AM_PM_SELECT = ".ampmselect"; String SECONDS_SELECT = ".secondselect"; }
3e1162aaae6fe4595f4e4b1380f314c15c5941a3
95
java
Java
app/src/main/java/fr/acinq/eclair/wallet/presenter/PaymentSuccess.java
ShifnaS/eclair-wallet-dev-master
45ceb836e78970938a93eaee3591975d3f70cbdd
[ "Apache-2.0" ]
null
null
null
app/src/main/java/fr/acinq/eclair/wallet/presenter/PaymentSuccess.java
ShifnaS/eclair-wallet-dev-master
45ceb836e78970938a93eaee3591975d3f70cbdd
[ "Apache-2.0" ]
null
null
null
app/src/main/java/fr/acinq/eclair/wallet/presenter/PaymentSuccess.java
ShifnaS/eclair-wallet-dev-master
45ceb836e78970938a93eaee3591975d3f70cbdd
[ "Apache-2.0" ]
null
null
null
13.571429
41
0.736842
7,337
package fr.acinq.eclair.wallet.presenter; public interface PaymentSuccess { void ok(); }
3e1162ece9971858bbaaf1a337af12bc1da3b1ba
389
java
Java
ggp-base/src/org/ggp/base/test/AllTests.java
hobson/ggpy
4e6e6e876c3a4294cd711647051da2d9c1836b60
[ "MIT" ]
1
2015-01-26T19:07:45.000Z
2015-01-26T19:07:45.000Z
ggp-base/src/org/ggp/base/test/AllTests.java
hobson/ggpy
4e6e6e876c3a4294cd711647051da2d9c1836b60
[ "MIT" ]
null
null
null
ggp-base/src/org/ggp/base/test/AllTests.java
hobson/ggpy
4e6e6e876c3a4294cd711647051da2d9c1836b60
[ "MIT" ]
null
null
null
22.882353
35
0.709512
7,338
package org.ggp.base.test import org.junit.runner.RunWith import org.junit.runners.Suite @RunWith(Suite.class) @Suite.SuiteClasses( GameParsingTests.class, GdlCleanerTests.class, NoTabsInRulesheetsTest.class, ProverStateMachineTests.class, SimpleSentenceFormTest.class, StaticValidationTests.class }) class AllTests(object):
3e1162f3eb2586cf813ccc9dd2ef55674b7d42a1
3,877
java
Java
src/main/java/com/client/glowclient/commands/TPCommand.java
Intel-i80486-DX4/GlowClient-Fixed
0292ecc19ec604aea04a3440121b15a905dbcd43
[ "Unlicense" ]
6
2022-02-10T20:54:58.000Z
2022-03-14T11:27:55.000Z
src/main/java/com/client/glowclient/commands/TPCommand.java
christallinqq/glowclient
6247c4c5c185864739cf352820844197475bd639
[ "MIT" ]
2
2022-02-10T20:55:37.000Z
2022-02-26T10:51:29.000Z
GlowClient/src/main/java/com/client/glowclient/commands/TPCommand.java
14ms/Minecraft-Disclosed-Source-Modifications
d3729ab0fb20c36da1732b2070d1cb5d1409ffbc
[ "Unlicense" ]
1
2022-02-11T07:36:47.000Z
2022-02-11T07:36:47.000Z
46.154762
207
0.700542
7,339
//Deobfuscated with https://github.com/PetoPetko/Minecraft-Deobfuscator3000 using mappings "1.12 stable mappings"! /* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.entity.Entity * net.minecraft.entity.EntityLivingBase * net.minecraft.entity.player.EntityPlayerMP * net.minecraft.network.Packet * net.minecraft.network.play.client.CPacketPlayer$Position * net.minecraft.network.play.server.SPacketPlayerPosLook$EnumFlags * net.minecraft.util.math.MathHelper */ package com.client.glowclient.commands; import com.client.glowclient.utils.Utils; import com.client.glowclient.utils.base.command.Command; import com.client.glowclient.utils.classes.conversion.StringConversionUtils; import com.client.glowclient.utils.client.Globals; import com.client.glowclient.utils.mc.console.Console; import java.util.EnumSet; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.Packet; import net.minecraft.network.play.client.CPacketPlayer; import net.minecraft.network.play.server.SPacketPlayerPosLook; import net.minecraft.util.math.MathHelper; public class TPCommand extends Command { public TPCommand() { super("tp"); } @Override public void execute(String cmd, String[] args) { if (args.length < 4) { Console.write("\u00a7cNot enough data given"); } String x = args[1]; String y = args[2]; String z = args[3]; if (Globals.MC.player != null && StringConversionUtils.isStringDouble(x) && StringConversionUtils.isStringDouble(y) && StringConversionUtils.isStringDouble(z)) { TPCommand.doTeleport((Entity)Globals.MC.player, Double.parseDouble(x), Double.parseDouble(y), Double.parseDouble(z), Globals.MC.player.rotationYaw, Globals.MC.player.rotationPitch); if (Globals.MC.player.getRidingEntity() != null) { TPCommand.doTeleport(Globals.MC.player.getRidingEntity(), Double.parseDouble(x), Double.parseDouble(y), Double.parseDouble(z), Globals.MC.player.rotationYaw, Globals.MC.player.rotationPitch); } Utils.getNetworkManager().sendPacket((Packet)new CPacketPlayer.Position((double)Integer.parseInt(x), (double)Integer.parseInt(y), (double)Integer.parseInt(z), true)); } Console.write("\u00a7bTeleported to: " + x + ", " + y + ", " + z); } private static void doTeleport(Entity teleportingEntity, double argX, double argY, double argZ, float argYaw, float argPitch) { if (teleportingEntity instanceof EntityPlayerMP) { EnumSet<SPacketPlayerPosLook.EnumFlags> set = EnumSet.noneOf(SPacketPlayerPosLook.EnumFlags.class); float f = argYaw; f = MathHelper.wrapDegrees((float)f); float f1 = argPitch; f1 = MathHelper.wrapDegrees((float)f1); teleportingEntity.dismountRidingEntity(); ((EntityPlayerMP)teleportingEntity).connection.setPlayerLocation(argX, argY, argZ, f, f1, set); teleportingEntity.setRotationYawHead(f); } else { float f2 = MathHelper.wrapDegrees((float)argYaw); float f3 = MathHelper.wrapDegrees((float)argPitch); f3 = MathHelper.clamp((float)f3, (float)-90.0f, (float)90.0f); teleportingEntity.setLocationAndAngles(argX, argY, argZ, f2, f3); teleportingEntity.setRotationYawHead(f2); } if (!(teleportingEntity instanceof EntityLivingBase) || !((EntityLivingBase)teleportingEntity).isElytraFlying()) { teleportingEntity.motionY = 0.0; teleportingEntity.onGround = true; } } @Override public String getSuggestion(String cmd, String[] args) { return Command.prefix.getString() + "tp"; } }
3e116313318e08fa4bbd6eaa0b510d08efb034bb
682
java
Java
org/apache/xalan/templates/VarNameCollector.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
1
2022-02-24T01:32:41.000Z
2022-02-24T01:32:41.000Z
org/apache/xalan/templates/VarNameCollector.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
null
null
null
org/apache/xalan/templates/VarNameCollector.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
null
null
null
23.517241
73
0.721408
7,340
package org.apache.xalan.templates; import java.util.Vector; import org.apache.xml.utils.QName; import org.apache.xpath.ExpressionOwner; import org.apache.xpath.XPathVisitor; import org.apache.xpath.operations.Variable; public class VarNameCollector extends XPathVisitor { Vector m_refs = new Vector(); public void reset() { this.m_refs.removeAllElements(); } public int getVarCount() { return this.m_refs.size(); } boolean doesOccur(QName refName) { return this.m_refs.contains(refName); } public boolean visitVariableRef(ExpressionOwner owner, Variable var) { this.m_refs.addElement(var.getQName()); return true; } }
3e11643b25437c66820fb3669eac0bd9a62fcb72
3,752
java
Java
module1/BaitAlarms/src/com/helper/HttpsURLReader.java
SangramChavan/BaitAlarm
7f6894842baaf0d07161e086ba4da6625ee6a99b
[ "MIT" ]
null
null
null
module1/BaitAlarms/src/com/helper/HttpsURLReader.java
SangramChavan/BaitAlarm
7f6894842baaf0d07161e086ba4da6625ee6a99b
[ "MIT" ]
null
null
null
module1/BaitAlarms/src/com/helper/HttpsURLReader.java
SangramChavan/BaitAlarm
7f6894842baaf0d07161e086ba4da6625ee6a99b
[ "MIT" ]
null
null
null
29.543307
117
0.691631
7,341
package com.helper; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.net.URLConnection; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.KeyManagementException; import java.security.cert.X509Certificate; public class HttpsURLReader { public static void main(String[] args) throws Exception { StringBuffer sv= readHttpsURL("https://retail.onlinesbi.com/personal/css/style.css"); System.out.println(sv); } public static StringBuffer readHttpsURL(String url1) { StringBuffer sb = new StringBuffer(); try { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection .setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); URL url = new URL(url1); URLConnection con = url.openConnection(); con.setRequestProperty("Cookie", "foo=bar"); con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"); Reader reader = new InputStreamReader(con.getInputStream()); while (true) { int ch = reader.read(); if (ch == -1) { break; } // System.out.print((char)ch); sb.append((char) ch); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return sb; } public static InputStream readHttpsURLStream(String url1) { try { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection .setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); URL url = new URL(url1); URLConnection con = url.openConnection(); return con.getInputStream(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
3e1164449a2715fb9c8bd9d435d599e8dc5e92b6
820
java
Java
Homeworks/zi1819/src/main/java/hr/fer/zemris/java/listeneri/AppListener.java
dbrcina/OPJJ-FER-2018-19
7e98f6d63b844543e0ef131247de37b63e913cc0
[ "MIT" ]
1
2021-02-22T21:16:43.000Z
2021-02-22T21:16:43.000Z
Homeworks/zi1819/src/main/java/hr/fer/zemris/java/listeneri/AppListener.java
dbrcina/OPJJ-FER-2018-19
7e98f6d63b844543e0ef131247de37b63e913cc0
[ "MIT" ]
null
null
null
Homeworks/zi1819/src/main/java/hr/fer/zemris/java/listeneri/AppListener.java
dbrcina/OPJJ-FER-2018-19
7e98f6d63b844543e0ef131247de37b63e913cc0
[ "MIT" ]
null
null
null
26.451613
74
0.75
7,342
package hr.fer.zemris.java.listeneri; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import hr.fer.zemris.java.hw17.jvdraw.JVDraw; /** * Application Lifecycle Listener implementation class AppListener * */ @WebListener public class AppListener implements ServletContextListener { /** * @see ServletContextListener#contextDestroyed(ServletContextEvent) */ public void contextDestroyed(ServletContextEvent sce) { sce.getServletContext().removeAttribute("jvDraw"); } /** * @see ServletContextListener#contextInitialized(ServletContextEvent) */ public void contextInitialized(ServletContextEvent sce) { sce.getServletContext().setAttribute("jvDraw", new JVDraw()); } }
3e1164b4cbedd370f873c028049f57ca936b6d74
661
java
Java
Aula12ARepeticao1/src/aula12arepeticao1/Aula12ARepeticao1.java
DeyvisonMoraes05/Java-Basico
482fc94384cb7f0edaa4c738b0a98fdf5122c092
[ "MIT" ]
null
null
null
Aula12ARepeticao1/src/aula12arepeticao1/Aula12ARepeticao1.java
DeyvisonMoraes05/Java-Basico
482fc94384cb7f0edaa4c738b0a98fdf5122c092
[ "MIT" ]
null
null
null
Aula12ARepeticao1/src/aula12arepeticao1/Aula12ARepeticao1.java
DeyvisonMoraes05/Java-Basico
482fc94384cb7f0edaa4c738b0a98fdf5122c092
[ "MIT" ]
null
null
null
22.793103
79
0.594554
7,343
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package aula12arepeticao1; /** * * @author Deyvison Moraes */ public class Aula12ARepeticao1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here // ESTRUTURA DE REPETIÇÃO COM TESTE LÓGICO NO FINAL ("do" "while") int cc = 0; do { System.out.println("Cambalhota" + cc); cc++; } while (cc < 5); } }
3e1164eb4e06ced1f753767ea176da5314081b22
1,697
java
Java
open-metadata-implementation/integration-services/api-integrator/api-integrator-api/src/main/java/org/odpi/openmetadata/integrationservices/api/api/APIIntegratorAPI.java
MightyNerdEric/egeria
b195e2bacff4c88f6d7020b0f202cac8332a6b43
[ "CC-BY-4.0" ]
526
2018-06-21T12:15:13.000Z
2022-03-30T19:17:17.000Z
open-metadata-implementation/integration-services/api-integrator/api-integrator-api/src/main/java/org/odpi/openmetadata/integrationservices/api/api/APIIntegratorAPI.java
MightyNerdEric/egeria
b195e2bacff4c88f6d7020b0f202cac8332a6b43
[ "CC-BY-4.0" ]
4,157
2018-06-07T08:46:46.000Z
2022-03-31T13:29:01.000Z
open-metadata-implementation/integration-services/api-integrator/api-integrator-api/src/main/java/org/odpi/openmetadata/integrationservices/api/api/APIIntegratorAPI.java
aproeve/egeria
9c709f5aed7ece528c811a8d9d3ae60fdd1af25c
[ "CC-BY-4.0" ]
265
2018-06-05T13:34:36.000Z
2022-03-25T18:15:36.000Z
49.911765
115
0.704773
7,344
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.integrationservices.api.api; import org.odpi.openmetadata.frameworks.connectors.ffdc.InvalidParameterException; import org.odpi.openmetadata.frameworks.connectors.ffdc.PropertyServerException; import org.odpi.openmetadata.frameworks.connectors.ffdc.UserNotAuthorizedException; import org.odpi.openmetadata.frameworks.connectors.properties.beans.ConnectorType; /** * APIIntegratorAPI is the interface to validate that a connector is suitable to run in the API Integrator OMIS. * It validates that it implements the correct interfaces and returns the connector type for the connector. */ public interface APIIntegratorAPI { /** * Validate the connector and return its connector type. * * @param userId calling user * @param connectorProviderClassName name of a specific connector or null for all connectors * * @return connector type for this connector * * @throws InvalidParameterException the connector provider class name is not a valid connector fo this service * @throws UserNotAuthorizedException user not authorized to issue this request * @throws PropertyServerException there was a problem detected by the integration service */ ConnectorType validateConnector(String userId, String connectorProviderClassName) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException; }
3e1165108c4b9892f12c041151191d9dbb78697e
2,480
java
Java
impl/src/main/java/org/jboss/cdi/tck/tests/se/customCDIProvider/CustomCDIProvider.java
manovotn/cdi-tck
a14899cc9345792808c8905d01219beb2b5cc505
[ "Apache-2.0" ]
3
2019-09-13T12:11:32.000Z
2022-02-05T16:09:05.000Z
impl/src/main/java/org/jboss/cdi/tck/tests/se/customCDIProvider/CustomCDIProvider.java
manovotn/cdi-tck
a14899cc9345792808c8905d01219beb2b5cc505
[ "Apache-2.0" ]
107
2019-11-13T13:07:39.000Z
2022-03-31T11:15:35.000Z
impl/src/main/java/org/jboss/cdi/tck/tests/se/customCDIProvider/CustomCDIProvider.java
manovotn/cdi-tck
a14899cc9345792808c8905d01219beb2b5cc505
[ "Apache-2.0" ]
14
2020-02-26T15:49:34.000Z
2022-03-24T15:20:07.000Z
26.666667
89
0.654435
7,345
/* * JBoss, Home of Professional Open Source * Copyright 2015, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.cdi.tck.tests.se.customCDIProvider; import jakarta.enterprise.inject.Instance; import jakarta.enterprise.inject.Vetoed; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.CDI; import jakarta.enterprise.inject.spi.CDIProvider; import jakarta.enterprise.util.TypeLiteral; import java.lang.annotation.Annotation; import java.util.Iterator; /** * @author Martin Kouba * @author Matej Novotny * */ @Vetoed public class CustomCDIProvider implements CDIProvider { public static boolean initializedCalled = false; @Override public CDI<Object> getCDI() { initializedCalled = true; return new CustomCdi(); } public class CustomCdi extends CDI<Object> { @Override public BeanManager getBeanManager() { return null; } @Override public Instance<Object> select(Annotation... qualifiers) { return null; } @Override public <U> Instance<U> select(Class<U> subtype, Annotation... qualifiers) { return null; } @Override public <U> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers) { return null; } @Override public boolean isUnsatisfied() { return false; } @Override public boolean isAmbiguous() { return false; } @Override public void destroy(Object instance) { } @Override public Object get() { return null; } @Override public Iterator<Object> iterator() { return null; } } }
3e11669ff03dbdf5aa015a38e3a86652048d6d04
4,698
java
Java
httpcore5/src/main/java/org/apache/hc/core5/http/message/BasicHeaderIterator.java
cwildman/httpcomponents-core
2b3c7c388fdb8b74ca296920c78365ce52ec4925
[ "Apache-2.0" ]
205
2017-05-21T11:33:40.000Z
2022-03-31T02:31:37.000Z
httpcore5/src/main/java/org/apache/hc/core5/http/message/BasicHeaderIterator.java
cwildman/httpcomponents-core
2b3c7c388fdb8b74ca296920c78365ce52ec4925
[ "Apache-2.0" ]
186
2017-05-24T19:41:36.000Z
2022-03-21T21:42:59.000Z
httpcore5/src/main/java/org/apache/hc/core5/http/message/BasicHeaderIterator.java
cwildman/httpcomponents-core
2b3c7c388fdb8b74ca296920c78365ce52ec4925
[ "Apache-2.0" ]
308
2017-05-12T18:12:36.000Z
2022-03-16T11:27:16.000Z
31.32
86
0.620903
7,346
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.hc.core5.http.message; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.util.Args; /** * {@link java.util.Iterator} of {@link org.apache.hc.core5.http.Header}s. * * @since 4.0 */ public class BasicHeaderIterator implements Iterator<Header> { /** * An array of headers to iterate over. * Not all elements of this array are necessarily part of the iteration. * This array will never be modified by the iterator. * Derived implementations are expected to adhere to this restriction. */ private final Header[] allHeaders; /** * The position of the next header in {@link #allHeaders allHeaders}. * Negative if the iteration is over. */ private int currentIndex; /** * The header name to filter by. * {@code null} to iterate over all headers in the array. */ private final String headerName; /** * Creates a new header iterator. * * @param headers an array of headers over which to iterate * @param name the name of the headers over which to iterate, or * {@code null} for any */ public BasicHeaderIterator(final Header[] headers, final String name) { super(); this.allHeaders = Args.notNull(headers, "Header array"); this.headerName = name; this.currentIndex = findNext(-1); } /** * Determines the index of the next header. * * @param pos one less than the index to consider first, * -1 to search for the first header * * @return the index of the next header that matches the filter name, * or negative if there are no more headers */ private int findNext(final int pos) { int from = pos; if (from < -1) { return -1; } final int to = this.allHeaders.length-1; boolean found = false; while (!found && (from < to)) { from++; found = filterHeader(from); } return found ? from : -1; } /** * Checks whether a header is part of the iteration. * * @param index the index of the header to check * * @return {@code true} if the header should be part of the * iteration, {@code false} to skip */ private boolean filterHeader(final int index) { return (this.headerName == null) || this.headerName.equalsIgnoreCase(this.allHeaders[index].getName()); } @Override public boolean hasNext() { return this.currentIndex >= 0; } /** * Obtains the next header from this iteration. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ @Override public Header next() throws NoSuchElementException { final int current = this.currentIndex; if (current < 0) { throw new NoSuchElementException("Iteration already finished."); } this.currentIndex = findNext(current); return this.allHeaders[current]; } /** * Removing headers is not supported. * * @throws UnsupportedOperationException always */ @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("Removing headers is not supported."); } }
3e1167115b77e60fc7b40ba10e3c73d7999b8e00
1,738
java
Java
src/org/intellij/erlang/rebar/runner/RebarRunConfigurationEditorForm.java
cy6erGn0m/intellij-erlang
38c5b6a57929a3aa63c4e36c7440eb6a10093b89
[ "Apache-2.0" ]
1
2015-04-18T12:05:05.000Z
2015-04-18T12:05:05.000Z
src/org/intellij/erlang/rebar/runner/RebarRunConfigurationEditorForm.java
cy6erGn0m/intellij-erlang
38c5b6a57929a3aa63c4e36c7440eb6a10093b89
[ "Apache-2.0" ]
null
null
null
src/org/intellij/erlang/rebar/runner/RebarRunConfigurationEditorForm.java
cy6erGn0m/intellij-erlang
38c5b6a57929a3aa63c4e36c7440eb6a10093b89
[ "Apache-2.0" ]
null
null
null
32.792453
120
0.788838
7,347
/* * Copyright 2012-2013 Sergey Ignatov * * 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.intellij.erlang.rebar.runner; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SettingsEditor; import org.jetbrains.annotations.NotNull; import javax.swing.*; final class RebarRunConfigurationEditorForm extends SettingsEditor<RebarRunConfigurationBase> { private JPanel myComponent; private JTextField myCommandText; private JCheckBox mySkipDependencies; @Override protected void resetEditorFrom(@NotNull RebarRunConfigurationBase rebarRunConfiguration) { myCommandText.setText(rebarRunConfiguration.getCommand()); mySkipDependencies.setSelected(rebarRunConfiguration.isSkipDependencies()); } @Override protected void applyEditorTo(@NotNull RebarRunConfigurationBase rebarRunConfiguration) throws ConfigurationException { rebarRunConfiguration.setCommand(myCommandText.getText()); rebarRunConfiguration.setSkipDependencies(mySkipDependencies.isSelected()); } @NotNull @Override protected JComponent createEditor() { return myComponent; } @Override protected void disposeEditor() { myComponent.setVisible(false); } }
3e116737f023ad0abc8814d7682afe4e0fab1105
1,086
java
Java
header/rest/src/main/java/cn/ikangxu/header/rest/RestApplication.java
IKangXu/ikx-demo
3b35390f2e74d6c37febdf96037121451696d22e
[ "MIT" ]
null
null
null
header/rest/src/main/java/cn/ikangxu/header/rest/RestApplication.java
IKangXu/ikx-demo
3b35390f2e74d6c37febdf96037121451696d22e
[ "MIT" ]
null
null
null
header/rest/src/main/java/cn/ikangxu/header/rest/RestApplication.java
IKangXu/ikx-demo
3b35390f2e74d6c37febdf96037121451696d22e
[ "MIT" ]
null
null
null
28.578947
72
0.779006
7,348
/* * Engine3D Technologies Co., Ltd. Copyright 2019, All rights reserved */ package cn.ikangxu.header.rest; import cn.ikangxu.boot.header.annotation.EnableHeader; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; /** * @author kangxu [xukang@engine3d.com] * @version v1.0 * @className RestApplication * @description * @date 2019/11/6 13:30 */ @EnableHeader({"testHeader"}) @EnableAutoConfiguration @EnableDiscoveryClient @SpringCloudApplication public class RestApplication { public static void main(String[] args) { SpringApplication.run(RestApplication.class, args); } @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } }
3e116756eb2d97dbf0fadf5667b05e125b62ce1b
1,719
java
Java
src/main/java/com/jrp/pma/controllers/HomeController.java
wuh0007/springProjectManagementTool
f4e7029c8c21ace6815eb686718a7bcbdc21cf60
[ "MIT" ]
null
null
null
src/main/java/com/jrp/pma/controllers/HomeController.java
wuh0007/springProjectManagementTool
f4e7029c8c21ace6815eb686718a7bcbdc21cf60
[ "MIT" ]
null
null
null
src/main/java/com/jrp/pma/controllers/HomeController.java
wuh0007/springProjectManagementTool
f4e7029c8c21ace6815eb686718a7bcbdc21cf60
[ "MIT" ]
null
null
null
29.135593
80
0.779523
7,349
package com.jrp.pma.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.jrp.pma.dto.ChartData; import com.jrp.pma.dto.EmployeeProject; import com.jrp.pma.entities.Project; import com.jrp.pma.services.EmployeeService; import com.jrp.pma.services.ProjectService; @Controller public class HomeController { @Value("${version}") private String ver; @Autowired ProjectService proService; @Autowired EmployeeService empService; @GetMapping("/") public String displayHome(Model model) throws JsonProcessingException { model.addAttribute("versionNumber", ver); // we are querying the database for projects List<Project> projects = proService.getAll(); model.addAttribute("projectsList", projects); List<ChartData> projectData = proService.getProjectStatus(); // Lets convert projectData object into a json structure for use in javascript ObjectMapper objectMapper = new ObjectMapper(); String jsonString = objectMapper.writeValueAsString(projectData); // [["NOTSTARTED", 1], ["INPROGRESS", 2], ["COMPLETED", 1]] model.addAttribute("projectStatusCnt", jsonString); // we are querying the database for employees List<EmployeeProject> employeesProjectCnt = empService.employeeProjects(); model.addAttribute("employeesListProjectsCnt", employeesProjectCnt); return "main/home"; } }
3e1167f713bd60ee4389d2519c0a6e32ce2e931c
3,864
java
Java
plugins/local-store/src/main/java/fr/layer4/dek/property/LocalPropertyManager.java
Treydone/dek
c2e8b880ba8d4d0a415739eb5bce46daecc66b89
[ "MIT" ]
1
2018-11-06T16:18:11.000Z
2018-11-06T16:18:11.000Z
plugins/local-store/src/main/java/fr/layer4/dek/property/LocalPropertyManager.java
Treydone/dek
c2e8b880ba8d4d0a415739eb5bce46daecc66b89
[ "MIT" ]
139
2018-11-26T17:45:24.000Z
2021-08-02T17:16:26.000Z
plugins/local-store/src/main/java/fr/layer4/dek/property/LocalPropertyManager.java
Treydone/hhsl
c2e8b880ba8d4d0a415739eb5bce46daecc66b89
[ "MIT" ]
1
2018-12-20T12:35:44.000Z
2018-12-20T12:35:44.000Z
39.835052
151
0.709886
7,350
package fr.layer4.dek.property; /*- * #%L * DEK * %% * Copyright (C) 2018 Layer4 * %% * 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. * #L% */ import fr.layer4.dek.events.StoreReadyEvent; import fr.layer4.dek.store.LocalSecuredStore; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.tuple.Pair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; @Getter @Component @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class LocalPropertyManager implements PropertyManager, ApplicationListener<StoreReadyEvent> { private final LocalSecuredStore localSecuredStore; public static void updateDdl(JdbcTemplate jdbcTemplate) { jdbcTemplate.batchUpdate( "CREATE TABLE IF NOT EXISTS env(id INT AUTO_INCREMENT PRIMARY KEY, key VARCHAR(255), value VARCHAR(255))"); } public static void updateData(JdbcTemplate jdbcTemplate) { jdbcTemplate.batchUpdate( "MERGE INTO env KEY (`key`) VALUES " + "(default, 'http.socket.timeout', '30000')," + "(default, 'http.connect.timeout', '30000')," + "(default, 'proxy.enabled', 'false')" ); } @Override public void onApplicationEvent(StoreReadyEvent storeReadyEvent) { updateDdl(this.localSecuredStore.getJdbcTemplate()); updateData(this.localSecuredStore.getJdbcTemplate()); } @Override public Map<String, String> getProperty() { List<Map<String, Object>> maps = this.localSecuredStore.getJdbcTemplate().queryForList("SELECT `key`, `value` FROM env"); return maps.stream().map(e -> Pair.of((String) e.get("KEY"), (String) e.get("VALUE"))).collect(Collectors.toMap(Pair::getKey, Pair::getRight)); } @Override public Optional<String> getProperty(String key) { try { return Optional.of(this.localSecuredStore.getJdbcTemplate().queryForObject("SELECT `value` FROM env WHERE `key` = ?", String.class, key)); } catch (EmptyResultDataAccessException e) { return Optional.empty(); } } @Override public void setProperty(String key, String value) { this.localSecuredStore.getJdbcTemplate().update("MERGE INTO env KEY (`key`) VALUES (default, ?, ?);", key, value); } @Override public void deleteProperty(String key) { this.localSecuredStore.getJdbcTemplate().update("DELETE env WHERE `key` = ?", key); } }
3e1168eecf6c89245bbf97a7b18b36a313ad971c
1,308
java
Java
src/attic/attic-java/com/metaos/market/OpenPosition.java
K0414/metaos
be36c88d3c22fd2f0968edd1fba03c2f2353e4e8
[ "MIT" ]
3
2017-04-10T16:23:32.000Z
2020-07-04T07:59:25.000Z
src/attic/attic-java/com/metaos/market/OpenPosition.java
K0414/metaos
be36c88d3c22fd2f0968edd1fba03c2f2353e4e8
[ "MIT" ]
null
null
null
src/attic/attic-java/com/metaos/market/OpenPosition.java
K0414/metaos
be36c88d3c22fd2f0968edd1fba03c2f2353e4e8
[ "MIT" ]
6
2017-10-25T10:12:27.000Z
2020-07-04T07:59:27.000Z
27.829787
80
0.664373
7,351
/* * Copyright 2011 - 2012 * All rights reserved. License and terms according to LICENSE.txt file. * The LICENSE.txt file and this header must be included or referenced * in each piece of code derived from this project. */ package com.metaos.market; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import java.util.logging.Logger; /** * Open Position data. */ public abstract class OpenPosition { public final Calendar when; public final double price; public final double cost; public final double netPrice; public final boolean isLong; protected OpenPosition(final Calendar when, final double price, final double cost, final double netPrice, boolean isLong) { this.when = when; this.price = price; this.cost = cost; this.netPrice = netPrice; this.isLong = isLong; } public static class Long extends OpenPosition { public Long(final Calendar when,final double price,final double cost) { super(when, price, cost, price+cost, true); } } public static class Short extends OpenPosition { public Short(final Calendar when,final double price,final double cost) { super(when, price, cost, price-cost, false); } } }
3e116a1e76f185ec0db4bef0bbb00f3aa5277c3c
3,528
java
Java
mekon/src/uk/ac/manchester/cs/mekon/model/ISlotValuesVisitor.java
colin-puleston/mekon
4470424f63fe60031f16f72610921d710ac985a5
[ "MIT" ]
null
null
null
mekon/src/uk/ac/manchester/cs/mekon/model/ISlotValuesVisitor.java
colin-puleston/mekon
4470424f63fe60031f16f72610921d710ac985a5
[ "MIT" ]
null
null
null
mekon/src/uk/ac/manchester/cs/mekon/model/ISlotValuesVisitor.java
colin-puleston/mekon
4470424f63fe60031f16f72610921d710ac985a5
[ "MIT" ]
null
null
null
30.678261
81
0.719671
7,352
/* * The MIT License (MIT) * * Copyright (c) 2014 University of Manchester * * 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 uk.ac.manchester.cs.mekon.model; import java.util.*; /** * Visitor for visiting the sets of current-values for specific * {@link ISlot} objects. * * @author Colin Puleston */ public abstract class ISlotValuesVisitor extends FVisitor<ISlot> { private class ValueTypeVisitor extends CValueVisitor { private ISlot slot; protected void visit(CFrame valueType) { ISlotValuesVisitor.this.visit(valueType, castValues(valueType)); } protected void visit(CNumber valueType) { ISlotValuesVisitor.this.visit(valueType, castValues(valueType)); } protected void visit(CString valueType) { ISlotValuesVisitor.this.visit(valueType, castValues(valueType)); } protected void visit(MFrame valueType) { ISlotValuesVisitor.this.visit(valueType, castValues(valueType)); } ValueTypeVisitor(ISlot slot) { this.slot = slot; visit(slot.getValueType()); } private <V extends IValue>List<V> castValues(CValue<V> valueType) { return valueType.castValues(slot.getValues().asList()); } } /** * Method whose implementation defines actions to be performed on * visiting values of relevant type. * * @param valueType Type of values being visited * @param values Values being visited */ protected abstract void visit(CFrame valueType, List<IFrame> values); /** * Method whose implementation defines actions to be performed on * visiting values of relevant type. * * @param valueType Type of values being visited * @param values Values being visited */ protected abstract void visit(CNumber valueType, List<INumber> values); /** * Method whose implementation defines actions to be performed on * visiting values of relevant type. * * @param valueType Type of values being visited * @param values Values being visited */ protected abstract void visit(CString valueType, List<IString> values); /** * Method whose implementation defines actions to be performed on * visiting values of relevant type. * * @param valueType Type of values being visited * @param values Values being visited */ protected abstract void visit(MFrame valueType, List<CFrame> values); void performVisit(ISlot acceptor) throws Exception { new ValueTypeVisitor(acceptor); } }
3e116a995bf0308b88310712796514a63475538a
4,223
java
Java
tracer-starter-shop/tracer-shop-usr/tracer-shop-usr-rest/src/main/java/com/ow/tracer/shop/usr/rest/UsrAddressController.java
hanhanxiaorong/Task
246b667867d5d95e0efba9ca41ca4d8ef368b520
[ "MIT" ]
null
null
null
tracer-starter-shop/tracer-shop-usr/tracer-shop-usr-rest/src/main/java/com/ow/tracer/shop/usr/rest/UsrAddressController.java
hanhanxiaorong/Task
246b667867d5d95e0efba9ca41ca4d8ef368b520
[ "MIT" ]
null
null
null
tracer-starter-shop/tracer-shop-usr/tracer-shop-usr-rest/src/main/java/com/ow/tracer/shop/usr/rest/UsrAddressController.java
hanhanxiaorong/Task
246b667867d5d95e0efba9ca41ca4d8ef368b520
[ "MIT" ]
null
null
null
32.992188
109
0.653564
7,353
package com.ow.tracer.shop.usr.rest; import com.ow.tracer.shop.usr.dto.UsrAddress; import com.ow.tracer.shop.usr.service.IUsrAddressService; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ow.tracer.common.base.BaseController; import com.ow.tracer.common.base.BaseEnums; import com.ow.tracer.common.base.Result; import com.ow.tracer.common.util.Results; import com.ow.tracer.common.vo.UserVO; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Date; import java.util.List; /** * 类描述: [控制器] * 创建人: [江雪立] * 创建时间: [2019-01-14 22:16:05] * 版本: [v1.0] */ @SuppressWarnings("ALL") @RestController @RequestMapping("/usrAddress") public class UsrAddressController extends BaseController { @Autowired private IUsrAddressService usrAddressService; private Logger logger = LoggerFactory.getLogger(UsrAddressController.class); /** * 分页 PAGE * @param current 当前页数 * @return 分页数据 */ @ApiOperation(value="获取分页数据",notes = "获取分页数据") @GetMapping(value="/pageList") public Result pageList(Integer current){ Page page = new Page(); page.setCurrent(current); page.setSize(20); IPage<UsrAddress> usrAddressIPage = usrAddressService.listAll(page,null); return Results.successWithData(usrAddressIPage , BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc()); } /** * 全部list * @return List实体集合 */ @GetMapping(value="/allList") public Result allList(){ List<UsrAddress> usrAddressList = usrAddressService.list(new QueryWrapper<>()); return Results.successWithData(usrAddressList, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc()); } /** * 通过ID查询 * @param id ID * @return Dept */ @GetMapping("/{id}") public Result get(@PathVariable String id) { UsrAddress usrAddress = new UsrAddress (); usrAddress=usrAddressService.getById(id); return Results.successWithData(usrAddress, BaseEnums.SUCCESS.desc()); } /** * 根据ID删除 * @param id 编号 * @return success/false */ @DeleteMapping("/{id}") public Result del(@PathVariable String id) { boolean boo = usrAddressService.removeById(id); return Results.successWithData(boo, BaseEnums.SUCCESS.desc()); } /** * 添加{data.describe} * * @param usrAddress {data.describe} * @return success/false */ @PostMapping("/add") public Result add(@RequestBody UsrAddress usrAddress ) { usrAddress.setUserId("156156165156");//测试写死了一个,回头删掉 if(usrAddress.getType()==1) { UsrAddress usrAddress1 = usrAddressService.selectTypeByUserId(usrAddress.getUserId()); if (usrAddress1 != null) { usrAddress1.setType(0); usrAddressService.updateById(usrAddress1); } } boolean boo = usrAddressService.save(usrAddress); return Results.successWithData(boo, BaseEnums.SUCCESS.desc()); } /** * 更新 * @param usrAddress {data.describe} UserVO user操作用户 * @return success/false */ @PutMapping("/edit") public Result edit(@RequestBody UsrAddress usrAddress ,UserVO userVO){ usrAddress .setUpdateDate(new Date()); usrAddress .setUpdateBy(userVO.getId()); usrAddress .setUpdater(userVO.getUserName()); if(usrAddress.getType()==1){ //查询他有没有默认收获地址 UsrAddress usrAddress1=usrAddressService.selectTypeByUserId(usrAddress.getUserId()); if(usrAddress1!=null){ usrAddress1.setType(0); usrAddressService.updateById(usrAddress1); } } boolean boo = usrAddressService.updateById( usrAddress); return Results.successWithData(boo,BaseEnums.SUCCESS.desc()); } }
3e116aa2b98fcf52db958e3329cf3fb1f088f3a8
1,581
java
Java
src/main/java/com/onaple/brawlator/data/beans/loot/ItemizerPoolLoot.java
OnapleRPG/Brawlator
e5d8d441d332e3357103659d4c146c0a47c3cd02
[ "Apache-2.0" ]
1
2019-05-14T13:13:38.000Z
2019-05-14T13:13:38.000Z
src/main/java/com/onaple/brawlator/data/beans/loot/ItemizerPoolLoot.java
OnapleRPG/Brawlator
e5d8d441d332e3357103659d4c146c0a47c3cd02
[ "Apache-2.0" ]
11
2018-07-22T19:43:11.000Z
2020-09-11T17:42:19.000Z
src/main/java/com/onaple/brawlator/data/beans/loot/ItemizerPoolLoot.java
OnapleRPG/Brawlator
e5d8d441d332e3357103659d4c146c0a47c3cd02
[ "Apache-2.0" ]
null
null
null
29.277778
109
0.652119
7,354
package com.onaple.brawlator.data.beans.loot; import com.onaple.brawlator.Brawlator; import com.onaple.itemizer.service.IItemService; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataQuery; import org.spongepowered.api.data.Queries; import org.spongepowered.api.item.inventory.ItemStack; import java.util.Optional; public class ItemizerPoolLoot extends PonderedLoot { private String poolId; public ItemizerPoolLoot(double weigth, String poolId) { super(weigth); this.poolId = poolId; } @Override public ItemStack fetch() { Optional<IItemService> optionalIItemService = Sponge.getServiceManager().provide(IItemService.class); if (optionalIItemService.isPresent()) { IItemService iItemService = optionalIItemService.get(); return iItemService.fetch(poolId).orElse(ItemStack.empty()); } else { Brawlator.getLogger().error("Itemizer plugin not found"); } return ItemStack.empty(); } @Override public int getContentVersion() { return 0; } @Override public DataContainer toContainer() { return DataContainer.createNew() .set(DataQuery.of("PoolId"), this.poolId) .set(Queries.CONTENT_VERSION, getContentVersion()); } @Override public String toString() { return "ItemizerPoolLoot{" + "poolId='" + poolId + '\'' + ", weigth=" + weigth + '}'; } }
3e116c63b5a5dd7cfbd57e586d6706e0dbcbbc0f
932
java
Java
Examples/src/main/java/ru/alttiri/examples/youtube/husivm/multithreading/MyCountDownLatch.java
AlternatiOne/StepikSimple
81b1b42f60da2d8d6daf47c25ea2529c338de0b2
[ "MIT" ]
null
null
null
Examples/src/main/java/ru/alttiri/examples/youtube/husivm/multithreading/MyCountDownLatch.java
AlternatiOne/StepikSimple
81b1b42f60da2d8d6daf47c25ea2529c338de0b2
[ "MIT" ]
3
2017-09-03T02:52:45.000Z
2017-11-19T20:39:16.000Z
Examples/src/main/java/ru/alttiri/examples/youtube/husivm/multithreading/MyCountDownLatch.java
AlternatiOne/HomeWork
81b1b42f60da2d8d6daf47c25ea2529c338de0b2
[ "MIT" ]
2
2019-07-10T14:51:44.000Z
2019-11-19T09:49:53.000Z
23.897436
72
0.639485
7,355
package ru.alttiri.examples.youtube.husivm.multithreading; import java.util.concurrent.CountDownLatch; /** * https://youtu.be/6dx3Ma4JeZE */ public class MyCountDownLatch { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(3); new Work(countDownLatch); new Work(countDownLatch); new Work(countDownLatch); countDownLatch.await(); System.out.println("all job done"); } } class Work extends Thread { CountDownLatch countDownLatch; public Work(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; start(); } @Override public void run() { try { sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("done work"); countDownLatch.countDown(); } }
3e116deff0fd64d2c31f832b108455c7d886b175
1,193
java
Java
account-service/src/main/java/com/test/bank/accountservice/dto/MessageResponseDTO.java
jaflolo/bank-exercise
a4af3b333417d1e9e0312cbb34d9e90fc0300d26
[ "Apache-1.1" ]
null
null
null
account-service/src/main/java/com/test/bank/accountservice/dto/MessageResponseDTO.java
jaflolo/bank-exercise
a4af3b333417d1e9e0312cbb34d9e90fc0300d26
[ "Apache-1.1" ]
null
null
null
account-service/src/main/java/com/test/bank/accountservice/dto/MessageResponseDTO.java
jaflolo/bank-exercise
a4af3b333417d1e9e0312cbb34d9e90fc0300d26
[ "Apache-1.1" ]
null
null
null
31.394737
75
0.775356
7,356
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.test.bank.accountservice.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor @ApiModel(description = "Common object to send messages to consumers") public class MessageResponseDTO implements Serializable { private static final long serialVersionUID = 1141467997923213196L; @ApiModelProperty(notes = "Detailed message") private String message; }
3e116e1c2fbe95fa92252597c630b2b26228b68a
1,469
java
Java
metaq-commons/src/main/java/com/taobao/metamorphosis/utils/IdGenerator.java
gszhuang/metaq_study
ccc2d8bc98731077d6f0e5bdbb7798df505aa11e
[ "Apache-2.0" ]
21
2017-02-27T15:59:04.000Z
2021-12-22T01:01:36.000Z
metaq-commons/src/main/java/com/taobao/metamorphosis/utils/IdGenerator.java
stateIs0/metaq
ccc2d8bc98731077d6f0e5bdbb7798df505aa11e
[ "Apache-2.0" ]
null
null
null
metaq-commons/src/main/java/com/taobao/metamorphosis/utils/IdGenerator.java
stateIs0/metaq
ccc2d8bc98731077d6f0e5bdbb7798df505aa11e
[ "Apache-2.0" ]
19
2017-03-20T08:02:14.000Z
2021-03-22T07:45:37.000Z
23.693548
98
0.561607
7,357
package com.taobao.metamorphosis.utils; import java.util.concurrent.atomic.AtomicLong; import com.taobao.metamorphosis.network.RemotingUtils; /** * Generator for Globally unique Strings. * * @author boyan */ public class IdGenerator { private String seed; private final AtomicLong sequence = new AtomicLong(1); private int length; /** * Construct an IdGenerator */ public IdGenerator() { try { this.seed = RemotingUtils.getLocalAddress() + "-" + System.currentTimeMillis() + "-"; this.length = this.seed.length() + ("" + Long.MAX_VALUE).length(); } catch (final Exception e) { throw new RuntimeException(e); } } /** * Generate a unqiue id * * @return a unique id */ public synchronized String generateId() { final StringBuilder sb = new StringBuilder(this.length); sb.append(this.seed); sb.append(this.sequence.getAndIncrement()); return sb.toString(); } /** * Generate a unique ID - that is friendly for a URL or file system * * @return a unique id */ public String generateSanitizedId() { String result = this.generateId(); result = result.replace(':', '-'); result = result.replace('_', '-'); result = result.replace('.', '-'); return result; } }
3e116f25f18ded23a00268818030879e22cd4a85
4,698
java
Java
src/nl/pdekker/nts_ms_1_0_3_0/Date_pair.java
p-dekker/BoeienApp
fd5f6ec95d51838f8d902dea02a8be62b41494c0
[ "MIT" ]
null
null
null
src/nl/pdekker/nts_ms_1_0_3_0/Date_pair.java
p-dekker/BoeienApp
fd5f6ec95d51838f8d902dea02a8be62b41494c0
[ "MIT" ]
null
null
null
src/nl/pdekker/nts_ms_1_0_3_0/Date_pair.java
p-dekker/BoeienApp
fd5f6ec95d51838f8d902dea02a8be62b41494c0
[ "MIT" ]
null
null
null
29.923567
110
0.605364
7,358
/** * Date_pair.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package nl.pdekker.nts_ms_1_0_3_0; public class Date_pair implements java.io.Serializable { private java.util.Date date_start; private java.util.Date date_end; public Date_pair() { } public Date_pair( java.util.Date date_start, java.util.Date date_end) { this.date_start = date_start; this.date_end = date_end; } /** * Gets the date_start value for this Date_pair. * * @return date_start */ public java.util.Date getDate_start() { return date_start; } /** * Sets the date_start value for this Date_pair. * * @param date_start */ public void setDate_start(java.util.Date date_start) { this.date_start = date_start; } /** * Gets the date_end value for this Date_pair. * * @return date_end */ public java.util.Date getDate_end() { return date_end; } /** * Sets the date_end value for this Date_pair. * * @param date_end */ public void setDate_end(java.util.Date date_end) { this.date_end = date_end; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof Date_pair)) return false; Date_pair other = (Date_pair) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.date_start==null && other.getDate_start()==null) || (this.date_start!=null && this.date_start.equals(other.getDate_start()))) && ((this.date_end==null && other.getDate_end()==null) || (this.date_end!=null && this.date_end.equals(other.getDate_end()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getDate_start() != null) { _hashCode += getDate_start().hashCode(); } if (getDate_end() != null) { _hashCode += getDate_end().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(Date_pair.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://www.ris.eu/nts.ms/1.0.3.0", "date_pair")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("date_start"); elemField.setXmlName(new javax.xml.namespace.QName("http://www.ris.eu/nts.ms/1.0.3.0", "date_start")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "date")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("date_end"); elemField.setXmlName(new javax.xml.namespace.QName("http://www.ris.eu/nts.ms/1.0.3.0", "date_end")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "date")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
3e116f62367171e4a452f15a740af39451e0a8e1
17,979
java
Java
src/test/java/org/kiwiproject/curator/leader/ManagedLeaderLatchTest.java
kiwiproject/dropwizard-leader-latch
dcfd00f494ecd6ccf6ca9161d9dd32c20da1f4d2
[ "MIT" ]
null
null
null
src/test/java/org/kiwiproject/curator/leader/ManagedLeaderLatchTest.java
kiwiproject/dropwizard-leader-latch
dcfd00f494ecd6ccf6ca9161d9dd32c20da1f4d2
[ "MIT" ]
94
2020-09-25T19:07:57.000Z
2022-03-11T02:11:58.000Z
src/test/java/org/kiwiproject/curator/leader/ManagedLeaderLatchTest.java
kiwiproject/dropwizard-leader-latch
dcfd00f494ecd6ccf6ca9161d9dd32c20da1f4d2
[ "MIT" ]
null
null
null
38.171975
110
0.690806
7,359
package org.kiwiproject.curator.leader; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.awaitility.Awaitility.await; import static org.awaitility.Durations.FIVE_SECONDS; import static org.kiwiproject.curator.leader.util.CuratorTestHelpers.closeIfStarted; import static org.kiwiproject.curator.leader.util.CuratorTestHelpers.deleteRecursivelyIfExists; import static org.kiwiproject.curator.leader.util.CuratorTestHelpers.startAndAwait; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import lombok.extern.slf4j.Slf4j; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.framework.recipes.leader.LeaderLatch; import org.apache.curator.framework.recipes.leader.LeaderLatchListener; import org.apache.curator.framework.recipes.leader.Participant; import org.apache.curator.retry.RetryOneTime; import org.assertj.core.api.SoftAssertions; import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.kiwiproject.curator.leader.exception.ManagedLeaderLatchException; import org.kiwiproject.test.curator.CuratorTestingServerExtension; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; @DisplayName("ManagedLeaderLatch") @ExtendWith(SoftAssertionsExtension.class) @Slf4j class ManagedLeaderLatchTest { @RegisterExtension static final CuratorTestingServerExtension ZK_TEST_SERVER = new CuratorTestingServerExtension(); private CuratorFramework client; private ManagedLeaderLatch leaderLatch1; private LeaderLatchListener leaderListener1; private ManagedLeaderLatch leaderLatch2; private LeaderLatchListener leaderListener2; @BeforeEach void setUp() throws Exception { client = ZK_TEST_SERVER.getClient(); leaderListener1 = mock(LeaderLatchListener.class); leaderLatch1 = new ManagedLeaderLatch(client, "id-12345", "test-service", leaderListener1); leaderListener2 = mock(LeaderLatchListener.class); leaderLatch2 = new ManagedLeaderLatch(client, "id-67890", "test-service", leaderListener2); if (exists(leaderLatch1.getLatchPath())) { deleteRecursivelyIfExists(client, leaderLatch1.getLatchPath()); } } @AfterEach void tearDown() { closeIfStarted(leaderLatch1); closeIfStarted(leaderLatch2); } @ParameterizedTest @CsvSource({ "test-service, 42.0.0, host1, 8080, test-service/42.0.0/host1:8080", "test-service, 42.0.0, host1, 9090, test-service/42.0.0/host1:9090", "test-service, 84.0.0, host4, 8080, test-service/84.0.0/host4:8080", "other-service, 21.0.42, host9, 9100, other-service/21.0.42/host9:9100", }) void shouldCreateLeaderLatchId(String serviceName, String serviceVersion, String hostname, int port, String expectedId) { var serviceDescriptor = ServiceDescriptor.builder() .name(serviceName) .version(serviceVersion) .hostname(hostname) .port(port) .build(); assertThat(ManagedLeaderLatch.leaderLatchId(serviceDescriptor)).isEqualTo(expectedId); } @ParameterizedTest @CsvSource({ "a-service, /kiwi/leader-latch/a-service/leader-latch", "other-service, /kiwi/leader-latch/other-service/leader-latch", "one-more-service, /kiwi/leader-latch/one-more-service/leader-latch", }) void shouldCreateLeaderLatchPath(String serviceName, String expectedPath) { assertThat(ManagedLeaderLatch.leaderLatchPath(serviceName)).isEqualTo(expectedPath); } @Test void shouldConstructNewLatch(SoftAssertions softly) { var latch = new ManagedLeaderLatch(client, "id-12345", "test-service", leaderListener1); softly.assertThat(latch.getId()).isEqualTo("id-12345"); softly.assertThat(latch.getLatchPath()).isEqualTo("/kiwi/leader-latch/test-service/leader-latch"); softly.assertThat(latch.getLatchState()).isEqualTo(LeaderLatch.State.LATENT); } @Test void shouldConstructNewLeaderLatch_UsingServiceDescriptor(SoftAssertions softly) { var service = ServiceDescriptor.builder() .name("test-service") .version("42.0.24") .hostname("host-12345") .port(8901) .build(); var latch = new ManagedLeaderLatch(client, service, leaderListener1); softly.assertThat(latch.getId()).isEqualTo("test-service/42.0.24/host-12345:8901"); softly.assertThat(latch.getLatchPath()).isEqualTo("/kiwi/leader-latch/test-service/leader-latch"); softly.assertThat(latch.getLatchState()).isEqualTo(LeaderLatch.State.LATENT); } @Test void shouldCreateNewLatchNode_WhenDoesNotExist() throws Exception { assertThat(exists(leaderLatch1.getLatchPath())).isFalse(); startAndAwait(leaderLatch1); assertThat(exists(leaderLatch1.getLatchPath())).isTrue(); assertThat(leaderLatch1.getParticipants()).hasSize(1); } @Test void shouldIgnore_WhenStartCalledMoreThanOnce() throws Exception { assertThat(exists(leaderLatch1.getLatchPath())).isFalse(); startAndAwait(leaderLatch1); leaderLatch1.start(); leaderLatch1.start(); assertThat(exists(leaderLatch1.getLatchPath())).isTrue(); assertThat(leaderLatch1.getParticipants()).hasSize(1); } private boolean exists(String path) throws Exception { return client.checkExists().forPath(path) != null; } @Test void shouldChangeState() throws Exception { assertThat(leaderLatch1.getLatchState()).isEqualTo(LeaderLatch.State.LATENT); startAndAwait(leaderLatch1); assertThat(leaderLatch1.getLatchState()).isEqualTo(LeaderLatch.State.STARTED); closeIfStarted(leaderLatch1); assertThat(leaderLatch1.getLatchState()).isEqualTo(LeaderLatch.State.CLOSED); } @Test void shouldReportLeadership_WhenMultipleLatchParticipants() throws Exception { startAndAwait(leaderLatch1, leaderLatch2); var nodes = client.getChildren().forPath(leaderLatch1.getLatchPath()); assertThat(nodes).hasSize(2); assertThat(atLeastOneHasLeadership()).isTrue(); assertThat(bothAreLeaders()).isFalse(); } private boolean atLeastOneHasLeadership() { return leaderLatch1.hasLeadership() || leaderLatch2.hasLeadership(); } private boolean bothAreLeaders() { return leaderLatch1.hasLeadership() && leaderLatch2.hasLeadership(); } @Test void shouldThrowException_WhenHasLeadershipCalled_WhenCuratorIsNotStarted() { var retryPolicy = new RetryOneTime(500); var curatorClient = CuratorFrameworkFactory.newClient(ZK_TEST_SERVER.getConnectString(), retryPolicy); var latch = new ManagedLeaderLatch(curatorClient, "testLatchId", "test-service"); LOG.trace("Created latch {}", latch); assertThatThrownBy(latch::hasLeadership) .isExactlyInstanceOf(ManagedLeaderLatchException.class) .hasMessage("Curator must be started before calling this method. Curator state: " + CuratorFrameworkState.LATENT.name()); } @Test void shouldThrowException_WhenHasLeadershipCalled_WhenLeaderLatchIsNotStarted() { var retryPolicy = new RetryOneTime(500); var curatorClient = CuratorFrameworkFactory.newClient(ZK_TEST_SERVER.getConnectString(), retryPolicy); var latch = new ManagedLeaderLatch(curatorClient, "testLatchId", "test-service"); LOG.trace("Created latch {}", latch); try (curatorClient) { curatorClient.start(); assertThatThrownBy(latch::hasLeadership) .isExactlyInstanceOf(ManagedLeaderLatchException.class) .hasMessage("LeaderLatch must be started before calling this method. Latch state: " + LeaderLatch.State.LATENT.name()); } } @Test void shouldThrowException_WhenHasLeadershipCalled_WhenLeaderLatchHasNoParticipantsYet() throws Exception { var retryPolicy = new RetryOneTime(500); var curatorClient = CuratorFrameworkFactory.newClient(ZK_TEST_SERVER.getConnectString(), retryPolicy); var latch = new ManagedLeaderLatch(curatorClient, "testLatchId", "test-vip-address") { @Override public Collection<Participant> getParticipants() { return Collections.emptyList(); } }; LOG.trace("Created latch {} that always returns empty participants", latch); try (curatorClient) { curatorClient.start(); latch.start(); assertThatThrownBy(latch::hasLeadership) .isExactlyInstanceOf(ManagedLeaderLatchException.class) .hasMessage("LeaderLatch must have participants before calling this method."); } finally { latch.stop(); } } @Test void shouldChangeLeadership() throws Exception { startAndAwait(leaderLatch1); assertThat(leaderLatch1.hasLeadership()).isTrue(); startAndAwait(leaderLatch2); assertThat(leaderLatch2.hasLeadership()).isFalse(); closeIfStarted(leaderLatch1); assertThat(leaderLatch2.hasLeadership()).isTrue(); } @Test void shouldNotify_LeaderChangeNotifications_InOrder() throws Exception { startAndAwait(leaderLatch1); startAndAwait(leaderLatch2); closeIfStarted(leaderLatch1); closeIfStarted(leaderLatch2); var inOrder = inOrder(leaderListener1, leaderListener2); inOrder.verify(leaderListener1).isLeader(); inOrder.verify(leaderListener1).notLeader(); inOrder.verify(leaderListener2).isLeader(); inOrder.verify(leaderListener2).notLeader(); } @Test void shouldNotifyAllListeners_WhenThereAreMultipleListeners() throws Exception { var leaderLatchListener1a = mock(LeaderLatchListener.class); var leaderLatchListener1b = mock(LeaderLatchListener.class); var latchWithListeners = new ManagedLeaderLatch( client, "id-12345", "test-service", leaderLatchListener1a, leaderLatchListener1b); startAndAwait(latchWithListeners); closeIfStarted(latchWithListeners); var inOrder1 = inOrder(leaderLatchListener1a); inOrder1.verify(leaderLatchListener1a).isLeader(); inOrder1.verify(leaderLatchListener1a).notLeader(); var inOrder2 = inOrder(leaderLatchListener1b); inOrder2.verify(leaderLatchListener1b).isLeader(); inOrder2.verify(leaderLatchListener1b).notLeader(); } @Test void shouldStartAndStop_WhenNoListeners() throws Exception { var leaderLatch = new ManagedLeaderLatch(client, "id-4242", "test-service"); startAndAwait(leaderLatch); try { assertThat(leaderLatch.getLatchState()).isEqualTo(LeaderLatch.State.STARTED); } finally { closeIfStarted(leaderLatch); } assertThat(leaderLatch.getLatchState()).isEqualTo(LeaderLatch.State.CLOSED); } @Test void shouldGetParticipants() throws Exception { startAndAwait(leaderLatch1); assertThat(leaderLatch1.getParticipants()) .containsExactly(new Participant(leaderLatch1.getId(), true)); startAndAwait(leaderLatch2); var expectedParticipants = List.of( new Participant(leaderLatch1.getId(), true), new Participant(leaderLatch2.getId(), false) ); assertThat(leaderLatch1.getParticipants()) .hasSize(2) .containsAll(expectedParticipants); assertThat(leaderLatch2.getParticipants()) .hasSize(2) .containsAll(expectedParticipants); } @Test void shouldGetLeader() throws Exception { startAndAwait(leaderLatch1); assertThat(leaderLatch1.getLeader()).isEqualTo(new Participant(leaderLatch1.getId(), true)); startAndAwait(leaderLatch2); assertThat(leaderLatch1.getLeader()) .describedAs("Both latch instances should have same leader") .isEqualTo(leaderLatch2.getLeader()); assertThat(leaderLatch1.getLeader()) .describedAs("leaderLatch1 is still leader") .isEqualTo(new Participant(leaderLatch1.getId(), true)); closeIfStarted(leaderLatch1); assertThat(leaderLatch2.getLeader()) .describedAs("leaderLatch2 should now be leader") .isEqualTo(new Participant(leaderLatch2.getId(), true)); } @Test void shouldCallActionSynchronously_WhenIsLeader() throws Exception { startAndAwait(leaderLatch1); var called = new AtomicBoolean(); leaderLatch1.whenLeader(() -> called.set(true)); assertThat(called).isTrue(); } @Test void shouldNotCallActionSynchronously_WhenIsNotLeader() throws Exception { startAndAwait(leaderLatch1); startAndAwait(leaderLatch2); assertThat(leaderLatch1.hasLeadership()).isTrue(); var called = new AtomicBoolean(); leaderLatch2.whenLeader(() -> called.set(true)); assertThat(called).isFalse(); } @Test void shouldCallActionAsynchronously_WhenIsLeader() throws Exception { startAndAwait(leaderLatch1); assertThat(leaderLatch1.hasLeadership()).isTrue(); var called = new AtomicBoolean(); Optional<CompletableFuture<Void>> result = leaderLatch1.whenLeaderAsync(() -> called.set(true)); assertThat(result).isPresent(); CompletableFuture<Void> future = result.orElseThrow(); await().atMost(FIVE_SECONDS).until(future::isDone); assertThat(called).isTrue(); } @Test void shouldNotCallActionAsynchronously_WhenIsNotLeader() throws Exception { startAndAwait(leaderLatch1); startAndAwait(leaderLatch2); assertThat(leaderLatch1.hasLeadership()).isTrue(); var called = new AtomicBoolean(); Optional<CompletableFuture<Void>> result = leaderLatch2.whenLeaderAsync(() -> called.set(true)); assertThat(result).isEmpty(); assertThat(called).isFalse(); } @Test void shouldCallSupplierSynchronously_WhenIsLeader() throws Exception { startAndAwait(leaderLatch1); Supplier<Integer> supplier = () -> 42; Optional<Integer> result = leaderLatch1.whenLeader(supplier); assertThat(result).contains(42); } @Test void shouldNotCallSupplierSynchronously_WhenIsNotLeader() throws Exception { startAndAwait(leaderLatch1); startAndAwait(leaderLatch2); assertThat(leaderLatch1.hasLeadership()).isTrue(); Optional<Integer> result = leaderLatch2.whenLeader(() -> 42); assertThat(result).isEmpty(); } @Test void shouldCallSupplierAsynchronously_WhenIsLeader() throws Exception { startAndAwait(leaderLatch1); Supplier<Integer> supplier = () -> 42; Optional<CompletableFuture<Integer>> result = leaderLatch1.whenLeaderAsync(supplier); assertThat(result).isPresent(); CompletableFuture<Integer> future = result.orElseThrow(); await().atMost(FIVE_SECONDS).until(future::isDone); assertThat(future.get()).isEqualTo(42); } @Test void shouldNotCallSupplierAsynchronously_WhenIsNotLeader() throws Exception { startAndAwait(leaderLatch1); startAndAwait(leaderLatch2); assertThat(leaderLatch1.hasLeadership()).isTrue(); Optional<CompletableFuture<Integer>> result = leaderLatch2.whenLeaderAsync(() -> 42); assertThat(result).isEmpty(); } @Test void shouldCallSupplierAsynchronously_WithCustomExecutor_WhenIsLeader() throws Exception { startAndAwait(leaderLatch1); Supplier<Integer> supplier = () -> 42; var executor = Executors.newSingleThreadExecutor(); Optional<CompletableFuture<Integer>> result = leaderLatch1.whenLeaderAsync(supplier, executor); assertThat(result).isNotEmpty(); CompletableFuture<Integer> future = result.orElseThrow(); await().atMost(FIVE_SECONDS).until(future::isDone); assertThat(future.get()).isEqualTo(42); } @Test void shouldNotCallSupplierAsynchronously_WithCustomExecutor_WhenIsNotLeader() throws Exception { startAndAwait(leaderLatch1); startAndAwait(leaderLatch2); assertThat(leaderLatch1.hasLeadership()).isTrue(); var nullExecutor = nullExecutorWhichShouldNeverBeUsed(); Optional<CompletableFuture<Integer>> result = leaderLatch2.whenLeaderAsync(() -> 42, nullExecutor); assertThat(result).isEmpty(); } private Executor nullExecutorWhichShouldNeverBeUsed() { return null; } }
3e116fc1287234ffbd40be0b1e8de5ba8b8f1e85
85
java
Java
Assignment3/src/academy/pocu/comp2500/assignment3/TankMode.java
quasar0204/POCU_OOP
765adebe2ef0ec68c934153376d46011fd8a15bd
[ "MIT" ]
null
null
null
Assignment3/src/academy/pocu/comp2500/assignment3/TankMode.java
quasar0204/POCU_OOP
765adebe2ef0ec68c934153376d46011fd8a15bd
[ "MIT" ]
null
null
null
Assignment3/src/academy/pocu/comp2500/assignment3/TankMode.java
quasar0204/POCU_OOP
765adebe2ef0ec68c934153376d46011fd8a15bd
[ "MIT" ]
null
null
null
14.166667
42
0.752941
7,360
package academy.pocu.comp2500.assignment3; public enum TankMode { TANK, SIEGE }
3e11704bae3f8bb9fa6021e02e157a4516699a7f
861
java
Java
ransom/Ransom.java
wingtonbrito/problems-and-more-problems
f8d8fc198fafb4a5510c9f11ec106124059d3376
[ "CC-BY-4.0" ]
333
2015-01-02T04:26:16.000Z
2022-03-28T22:15:05.000Z
ransom/Ransom.java
wingtonbrito/problems-and-more-problems
f8d8fc198fafb4a5510c9f11ec106124059d3376
[ "CC-BY-4.0" ]
7
2015-03-09T03:13:02.000Z
2019-09-13T10:14:52.000Z
ransom/Ransom.java
wingtonbrito/problems-and-more-problems
f8d8fc198fafb4a5510c9f11ec106124059d3376
[ "CC-BY-4.0" ]
167
2015-02-23T09:31:12.000Z
2022-03-10T07:28:29.000Z
27.774194
69
0.470383
7,361
import java.util.HashMap; import java.util.Map; public class Ransom { public static boolean canRansom(String magazine, String ransom) { if (magazine.length() < ransom.length()) { return false; } Map<String, Integer> magMap = new HashMap<>(); for (String word : magazine.split(" ")) { if (magMap.containsKey(word)) { magMap.put(word, magMap.get(word) + 1); } else { magMap.put(word, 1); } } for (String word : ransom.split(" ")) { if (!magMap.containsKey(word)) { return false; } if (magMap.get(word) == 1) { magMap.remove(word); } else { magMap.put(word, magMap.get(word) - 1); } } return true; } }
3e1171822a03836a1d82b2c4d299489634bb16ad
850
java
Java
library/src/main/java/com/animX/animationlib/library/animx_fading_out/FadingOutDown.java
chiragjasani/AnimX_Animation
1f356781ee6b8b3f56b93c8acb31a79a304f6c8a
[ "MIT" ]
null
null
null
library/src/main/java/com/animX/animationlib/library/animx_fading_out/FadingOutDown.java
chiragjasani/AnimX_Animation
1f356781ee6b8b3f56b93c8acb31a79a304f6c8a
[ "MIT" ]
null
null
null
library/src/main/java/com/animX/animationlib/library/animx_fading_out/FadingOutDown.java
chiragjasani/AnimX_Animation
1f356781ee6b8b3f56b93c8acb31a79a304f6c8a
[ "MIT" ]
null
null
null
32.692308
93
0.711765
7,362
package com.animX.animationlib.library.animx_fading_out; import android.view.View; import com.nineoldandroids.animation.ObjectAnimator; import com.animX.animationlib.library.Animx_BaseViewAnimator; public class FadingOutDown extends Animx_BaseViewAnimator { @Override public void prepare(View target) { final float horizontalCenter = mHorizontalCenter; final float verticalCenter = mVerticalCenter; int distance = (int) mSlideLength; getAnimatorAgent().playTogether( ObjectAnimator.ofFloat(target,"alpha",1,0), ObjectAnimator.ofFloat(target,"translationY",0,distance), ObjectAnimator.ofFloat(target, "pivotX", horizontalCenter, horizontalCenter), ObjectAnimator.ofFloat(target, "pivotY", verticalCenter, verticalCenter) ); } }
3e1171db0d6dd9f5a80049d3d7e8d5f69194ee24
162,981
java
Java
app/src/main/java/com/arnoldvaz27/remarques/activities/CreateNoteActivity.java
arnoldvaz27/Remarques
814477078c455b2651b786e42a3eda0a7762c40a
[ "MIT" ]
null
null
null
app/src/main/java/com/arnoldvaz27/remarques/activities/CreateNoteActivity.java
arnoldvaz27/Remarques
814477078c455b2651b786e42a3eda0a7762c40a
[ "MIT" ]
null
null
null
app/src/main/java/com/arnoldvaz27/remarques/activities/CreateNoteActivity.java
arnoldvaz27/Remarques
814477078c455b2651b786e42a3eda0a7762c40a
[ "MIT" ]
null
null
null
45.897212
284
0.540621
7,363
package com.arnoldvaz27.remarques.activities; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.appcompat.view.menu.MenuBuilder; import androidx.appcompat.view.menu.MenuPopupHelper; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.GradientDrawable; import android.media.MediaRecorder; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.SystemClock; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.speech.RecognizerIntent; import android.speech.tts.TextToSpeech; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.text.util.Linkify; import android.util.Patterns; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.CheckBox; import android.widget.Chronometer; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.arnoldvaz27.remarques.DeviceFiles.DeviceFilesDisplay; import com.arnoldvaz27.remarques.FileDisplayed; import com.arnoldvaz27.remarques.FileAdapter; import com.arnoldvaz27.remarques.R; import com.arnoldvaz27.remarques.database.NotesDatabase; import com.arnoldvaz27.remarques.entities.Note; import com.arnoldvaz27.remarques.onFileSelectListener; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.Image; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Font; import com.itextpdf.text.pdf.BarcodeQRCode; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfWriter; import com.xeoh.android.texthighlighter.TextHighlighter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Objects; import top.defaults.colorpicker.ColorPickerPopup; import static com.arnoldvaz27.remarques.FileDisplayed.fileEnd; import static com.arnoldvaz27.remarques.activities.MainActivity.createNoteFolder; @SuppressLint({"SetTextI18n", "RestrictedApi"}) @SuppressWarnings({"deprecation"}) public class CreateNoteActivity extends AppCompatActivity implements onFileSelectListener { public static EditText inputNoteTitle, inputNoteSubTitle, inputNoteText, inputSearch; private TextView textDateTime, textDateTime2, labels, TextFileName; private ImageView imageSave, imageMoreOption; private View viewSubTitleIndicator; private HorizontalScrollView richTextLayout; private LinearLayout layoutWebURL, moreLayout, searchLayout, checkLinear; private ScrollView Parent; private TextView textWebURL; private BottomSheetDialog bottomSheetDialog, addingClip, addingFileType, addingRecorder; private String selectedNoteColor; private ImageView imageNote, imageDown, imageUp, imageSpeak, imageLock, imageUnLock, imageCopy, imagePaste, imageFiles, imageShare, imageColorLens, imageSearchClose, imageSearch, cancelSearch, imageSearchPic, imageScan, imageGoSearch, imageDefault, imageDefaultBackground, MoreImage, MoreUrl, imageSettings, imageClip; private ImageView NumberText, BulletText, circleText, squareText, starText, alphabetText, alphabetSmallText, rightText, wrongText, checkBoxText; private String selectedImagePath, selectedImagePath2, toShare, custom; private static final int REQUEST_CODE_STORAGE_PERMISSION = 1; private static final int REQUEST_CODE_SELECT_IMAGE = 2; private static final int CAMERA_REQUEST = 1888; private View sheetView; private String show = "No"; private AlertDialog dialogAddURL, dialogLabelURL; private AlertDialog dialogDeleteNote, dialogSettingsNote, dialogResetNote, UrlOption, ImageOption; private final int REQ_CODE_TITLE = 100; private final int REQ_CODE_SUB_TITLE = 101; private final int REQ_CODE_NOTE = 102; public static File pdfFiles; private Typeface typeface1, typeface2, typeface3, typeface4, typeface5, typeface6; private Note alreadyAvailableNote, note; private String FileName, fontSettings, richText; final private int REQUEST_CODE_ASK_PERMISSIONS = 111; private File pdfFile; private TextToSpeech TTS; private int mDefaultColor, mDefaultTextColor, numberList = 1; private char c = 'A', d = 'a'; private InputStream inputStream; private Bitmap bitmap; private Uri selectImageUri; public static String folderName, fileFormat; File sdCard; public static String viewHolder; private RecyclerView recyclerView; private int i; boolean isRecording; String fileName; MediaRecorder recorder; private ImageView fileMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_note); First(); viewHolder = "CreateNote"; displayPdf(); } private void createFolder() throws Exception { File docsFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName); boolean success = true; if (!docsFolder.exists()) { success = docsFolder.mkdirs(); } if (success) { pdfFile = new File(docsFolder.getAbsolutePath(), "ReadMe.pdf"); OutputStream outputStream = new FileOutputStream(pdfFile); Document document = new Document(); PdfWriter.getInstance(document, outputStream); document.open(); Font f = new Font(Font.FontFamily.TIMES_ROMAN, 18f, Font.BOLD, BaseColor.RED); document.add(new Paragraph("Don't Delete this folder", f)); document.close(); } else { showToastRed("Error"); } } private void First() { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); ImageView imageBack = findViewById(R.id.imageBack); imageBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); inputNoteTitle = findViewById(R.id.inputNoteTitle); inputNoteSubTitle = findViewById(R.id.inputNoteSubTitle); inputNoteText = findViewById(R.id.inputNote); labels = findViewById(R.id.labels); textDateTime = findViewById(R.id.textDateTime); textDateTime2 = findViewById(R.id.textDateTimeLive); imageMoreOption = findViewById(R.id.imageMoreMenu); viewSubTitleIndicator = findViewById(R.id.viewSubtitleIndicator); imageNote = findViewById(R.id.imageNote); textWebURL = findViewById(R.id.textWebURL); layoutWebURL = findViewById(R.id.layoutWebURL); imageDown = findViewById(R.id.imageDownLayout); imageUp = findViewById(R.id.imageUpLayout); moreLayout = findViewById(R.id.layoutMore); imageSpeak = findViewById(R.id.imageSpeak); imageLock = findViewById(R.id.imageLock); imageUnLock = findViewById(R.id.imageUnLock); imageCopy = findViewById(R.id.imageCopy); imagePaste = findViewById(R.id.imagePaste); imageFiles = findViewById(R.id.imageFiles); imageShare = findViewById(R.id.imageShare); // imageNewNote = findViewById(R.id.imageNewNote); imageColorLens = findViewById(R.id.imageColorLens); imageSearchClose = findViewById(R.id.imageSearchClose); imageSearch = findViewById(R.id.imageSearch); imageScan = findViewById(R.id.imageQRCodeScan); imageSettings = findViewById(R.id.imageSettings); searchLayout = findViewById(R.id.LayoutSearch); Parent = findViewById(R.id.Parent); cancelSearch = findViewById(R.id.SearchCancel); inputSearch = findViewById(R.id.inputSearch); imageSearchPic = findViewById(R.id.search); imageGoSearch = findViewById(R.id.searchGo); imageDefault = findViewById(R.id.imageDefault); imageDefaultBackground = findViewById(R.id.imageDefaultBackground); richTextLayout = findViewById(R.id.richText); MoreImage = findViewById(R.id.imageMoreImage); MoreUrl = findViewById(R.id.imageMoreWebURL); // checkLinear = findViewById(R.id.linearLayout); recyclerView = findViewById(R.id.recycler_view); NumberText = findViewById(R.id.numberedText); BulletText = findViewById(R.id.bulletText); circleText = findViewById(R.id.circleText); squareText = findViewById(R.id.squareText); starText = findViewById(R.id.starText); rightText = findViewById(R.id.rightText); wrongText = findViewById(R.id.wrongText); alphabetText = findViewById(R.id.alphaText); alphabetSmallText = findViewById(R.id.alphaSmallText); checkBoxText = findViewById(R.id.checkboxText); // moreIcons = findViewById(R.id.more_icons); imageClip = findViewById(R.id.imageClip); mDefaultColor = 0; mDefaultTextColor = 0; fileMenu = findViewById(R.id.fileMenuMore); TextFileName = findViewById(R.id.textFileName); sdCard = Environment.getExternalStorageDirectory(); SharedPreferences getShared3 = getSharedPreferences("settings", MODE_PRIVATE); richText = getShared3.getString("rich text", null); if (richText.equals("1")) { richTextLayout.setVisibility(View.GONE); } else if (richText.equals("2")) { richTextLayout.setVisibility(View.VISIBLE); } SharedPreferences getShared4 = getSharedPreferences("settings", MODE_PRIVATE); String linkText = getShared4.getString("link text", null); if (linkText.equals("2")) { Linkify.addLinks(inputNoteText, Linkify.PHONE_NUMBERS | Linkify.WEB_URLS); } SharedPreferences getShared2 = getSharedPreferences("settings", MODE_PRIVATE); fontSettings = getShared2.getString("font number", null); typeface1 = Typeface.createFromAsset(getAssets(), "font/regular.ttf"); typeface2 = Typeface.createFromAsset(getAssets(), "font/robotoregular.ttf"); typeface3 = Typeface.createFromAsset(getAssets(), "font/lobsterregular.ttf"); typeface4 = Typeface.createFromAsset(getAssets(), "font/dancingfont.ttf"); typeface5 = Typeface.createFromAsset(getAssets(), "font/indieflowerregular.ttf"); typeface6 = Typeface.createFromAsset(getAssets(), "font/pacificoregular.ttf"); switch (fontSettings) { case "1": inputNoteTitle.setTypeface(typeface1); textDateTime.setTypeface(typeface1); textDateTime2.setTypeface(typeface1); textWebURL.setTypeface(typeface1); inputNoteSubTitle.setTypeface(typeface1); inputNoteText.setTypeface(typeface1); break; case "2": inputNoteTitle.setTypeface(typeface2); textDateTime.setTypeface(typeface2); textDateTime2.setTypeface(typeface2); textWebURL.setTypeface(typeface2); inputNoteSubTitle.setTypeface(typeface2); inputNoteText.setTypeface(typeface2); break; case "3": inputNoteTitle.setTypeface(typeface3); textDateTime.setTypeface(typeface3); textDateTime2.setTypeface(typeface3); textWebURL.setTypeface(typeface3); inputNoteSubTitle.setTypeface(typeface3); inputNoteText.setTypeface(typeface3); break; case "4": inputNoteTitle.setTypeface(typeface4); textDateTime.setTypeface(typeface4); textDateTime2.setTypeface(typeface4); textWebURL.setTypeface(typeface4); inputNoteSubTitle.setTypeface(typeface4); inputNoteText.setTypeface(typeface4); break; case "5": inputNoteTitle.setTypeface(typeface5); textDateTime.setTypeface(typeface5); textDateTime2.setTypeface(typeface5); textWebURL.setTypeface(typeface5); inputNoteSubTitle.setTypeface(typeface5); inputNoteText.setTypeface(typeface5); break; case "6": inputNoteTitle.setTypeface(typeface6); textDateTime.setTypeface(typeface6); textDateTime2.setTypeface(typeface6); textWebURL.setTypeface(typeface6); inputNoteSubTitle.setTypeface(typeface6); inputNoteText.setTypeface(typeface6); break; } // inputNoteText.setGravity(Gravity.RIGHT); TTS = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status != TextToSpeech.ERROR) { TTS.setLanguage(Locale.UK); } } }); textDateTime.setText("Created on: " + new SimpleDateFormat("EEEE , dd MM yyyy HH:mm a", Locale.getDefault()).format(new Date()) ); textDateTime2.setText("Editing Started on: " + new SimpleDateFormat("EEEE , dd MM yyyy HH:mm a", Locale.getDefault()).format(new Date()) ); imageSave = findViewById(R.id.imageSave); imageSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveNote(); } }); selectedNoteColor = "#333333"; selectedImagePath = ""; setSubTitleIndicatorColor(); if (getIntent().getBooleanExtra("isViewOrUpdate", false)) { alreadyAvailableNote = (Note) getIntent().getSerializableExtra("note"); setViewOrUpdateNote(); } else { i = 1; createNoteFolder = createNoteFolder.replaceAll(":", ""); createNoteFolder = createNoteFolder.replaceAll(" ", ""); folderName = createNoteFolder; int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) { showMessage((dialog, which) -> requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS)); return; } requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } } else { try { createFolder(); } catch (Exception e) { e.printStackTrace(); } } File docsFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName + File.separator + "ReadMe.pdf"); docsFolder.delete(); } MoreUrl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* textWebURL.setText(null); layoutWebURL.setVisibility(View.GONE);*/ UrlOptions(); } }); MoreImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ImageOptions(); } }); imageDown.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageDown.setVisibility(View.GONE); imageUp.setVisibility(View.VISIBLE); moreLayout.setVisibility(View.VISIBLE); } }); imageUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageUp.setVisibility(View.GONE); imageDown.setVisibility(View.VISIBLE); moreLayout.setVisibility(View.GONE); } }); imageSpeak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* imageSpeak.setVisibility(View.GONE); imageSpeakOff.setVisibility(View.VISIBLE);*/ if (inputNoteTitle.getText().toString().isEmpty() && inputNoteSubTitle.getText().toString().isEmpty() && inputNoteText.getText().toString().isEmpty()) { String toSpeak = "There is no Data to read"; TTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (inputNoteSubTitle.getText().toString().isEmpty()) { String toSpeak = inputNoteTitle.getText().toString() + inputNoteText.getText().toString(); TTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else { String toSpeak = inputNoteTitle.getText().toString() + inputNoteSubTitle.getText().toString() + inputNoteText.getText().toString(); TTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } } }); /* imageSpeakOff.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TTS.stop(); imageSpeakOff.setVisibility(View.GONE); imageSpeak.setVisibility(View.VISIBLE); } });*/ imageCopy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (inputNoteTitle.getText().toString().isEmpty() && inputNoteSubTitle.getText().toString().isEmpty() && inputNoteText.getText().toString().isEmpty()) { String toSpeak = "There is no Data to copy"; TTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (inputNoteSubTitle.getText().toString().isEmpty()) { String toCopy = "Title \n\n" + inputNoteTitle.getText().toString() + "\n\nNote \n\n" + inputNoteText.getText().toString(); ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Note Text", toCopy); clipboard.setPrimaryClip(clip); } else { String toCopy = "Title \n\n" + inputNoteTitle.getText().toString() + "\n\nSubTitle \n\n" + inputNoteSubTitle.getText().toString() + "\n\nNote \n\n" + inputNoteText.getText().toString(); ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Note Text", toCopy); clipboard.setPrimaryClip(clip); } } }); imagePaste.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData abc = clipboard.getPrimaryClip(); ClipData.Item item = abc.getItemAt(0); String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { String text = item.getText().toString(); inputNoteText.setText(text); } else { inputNoteText.setText(string + "\n\n "); String text = item.getText().toString(); inputNoteText.setText(text); } inputNoteText.setSelection(inputNoteText.getText().length()); } }); imageFiles.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), DeviceFilesDisplay.class)); } }); inputNoteText.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (TextUtils.isEmpty(inputNoteText.getText().toString())) { showToastRed("There is no text to copy"); } else { String toCopy = inputNoteText.getText().toString(); ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Note Text", toCopy); clipboard.setPrimaryClip(clip); showToast("Copied to clipboard"); } return true; } }); inputNoteTitle.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (TextUtils.isEmpty(inputNoteTitle.getText().toString())) { showToastRed("There is no text to copy"); } else { String toCopy = inputNoteTitle.getText().toString(); ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Title", toCopy); clipboard.setPrimaryClip(clip); showToast("Copied to clipboard"); } return true; } }); inputNoteSubTitle.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (TextUtils.isEmpty(inputNoteSubTitle.getText().toString())) { showToastRed("There is no text to copy"); } else { String toCopy = inputNoteSubTitle.getText().toString(); ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Sub Title", toCopy); clipboard.setPrimaryClip(clip); showToast("Copied to clipboard"); } return true; } }); imageScan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), ScannerView.class)); } }); inputSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.toString().length() > 0) { cancelSearch.setVisibility(View.VISIBLE); imageSearchPic.setVisibility(View.GONE); imageGoSearch.setVisibility(View.VISIBLE); } else { cancelSearch.setVisibility(View.GONE); imageSearchPic.setVisibility(View.VISIBLE); imageGoSearch.setVisibility(View.GONE); } } }); imageSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NoteSettings(); } }); cancelSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { inputSearch.setText(""); } }); imageShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (inputNoteTitle.getText().toString().isEmpty() && inputNoteSubTitle.getText().toString().isEmpty() && inputNoteText.getText().toString().isEmpty()) { String toSpeak = "There is no Data to share"; TTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (inputNoteSubTitle.getText().toString().isEmpty()) { toShare = "Title \n\n" + inputNoteTitle.getText().toString() + "\n\nNote \n\n" + inputNoteText.getText().toString(); } else { toShare = "Title \n\n" + inputNoteTitle.getText().toString() + "\n\nSubTitle \n\n" + inputNoteSubTitle.getText().toString() + "\n\nNote \n\n" + inputNoteText.getText().toString(); } ShareBottomLayout(); } }); imageMoreOption.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottomUp(); } }); imageClip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AddingClip(); } }); /* imageNewNote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivityForResult( new Intent(CreateNoteActivity.this, CreateNoteActivity.class), REQUEST_CODE_ADD_NOTE ); } });*/ imageGoSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new TextHighlighter() .setBackgroundColor(Color.parseColor("#FFFF00")) .setForegroundColor(Color.GREEN) .addTarget(inputNoteText) .highlight(inputSearch.getText().toString(), TextHighlighter.BASE_MATCHER); } }); imageDefault.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showResetDialog(); } }); imageDefaultBackground.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Parent.setBackgroundColor(ContextCompat.getColor(CreateNoteActivity.this, R.color.colorPrimary)); mDefaultColor = Integer.parseInt(String.valueOf(getResources().getColor(R.color.colorPrimary))); mDefaultTextColor = Integer.parseInt(String.valueOf(getResources().getColor(R.color.colorWhite))); inputNoteTitle.setTextColor(Integer.parseInt(String.valueOf(getResources().getColor(R.color.colorWhite)))); inputNoteSubTitle.setTextColor(Integer.parseInt(String.valueOf(getResources().getColor(R.color.colorWhite)))); inputNoteText.setTextColor(Integer.parseInt(String.valueOf(getResources().getColor(R.color.colorWhite)))); textDateTime.setTextColor(Integer.parseInt(String.valueOf(getResources().getColor(R.color.colorWhite)))); textDateTime2.setTextColor(Integer.parseInt(String.valueOf(getResources().getColor(R.color.colorWhite)))); labels.setTextColor(Integer.parseInt(String.valueOf(getResources().getColor(R.color.colorWhite)))); TextFileName.setTextColor(Integer.parseInt(String.valueOf(getResources().getColor(R.color.colorWhite)))); } }); imageNote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageBottomUp(); } }); imageColorLens.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { PopupMenu popup = new PopupMenu(getApplicationContext(), imageColorLens); //Inflating the Popup using xml file popup.getMenuInflater().inflate(R.menu.notes_color, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.txtColor) { new ColorPickerPopup.Builder(CreateNoteActivity.this).initialColor( getResources().getColor(R.color.colorPrimary)) // set initial color // of the color // picker dialog .enableBrightness( true) // enable color brightness // slider or not .enableAlpha( true) // enable color alpha // changer on slider or // not .okTitle( "Choose") // this is top right // Choose button .cancelTitle( "Cancel") // this is top left // Cancel button which // closes the .showIndicator( true) // this is the small box // which shows the chosen // color by user at the // bottom of the cancel // button .showValue( false) // this is the value which // shows the selected // color hex code // the above all values can be made // false to disable them on the // color picker dialog. .build() .show( v, new ColorPickerPopup.ColorPickerObserver() { @Override public void onColorPicked(int color) { // set the color // which is returned // by the color // picker mDefaultTextColor = color; // now as soon as // the dialog closes // set the preview // box to returned // color inputNoteTitle.setTextColor(mDefaultTextColor); inputNoteSubTitle.setTextColor(mDefaultTextColor); inputNoteText.setTextColor(mDefaultTextColor); textDateTime.setTextColor(mDefaultTextColor); textDateTime2.setTextColor(mDefaultTextColor); labels.setTextColor(mDefaultTextColor); TextFileName.setTextColor(mDefaultTextColor); } }); } if (item.getItemId() == R.id.bgColor) { new ColorPickerPopup.Builder(CreateNoteActivity.this).initialColor( getResources().getColor(R.color.colorPrimary)) // set initial color // of the color // picker dialog .enableBrightness( true) // enable color brightness // slider or not .enableAlpha( true) // enable color alpha // changer on slider or // not .okTitle( "Choose") // this is top right // Choose button .cancelTitle( "Cancel") // this is top left // Cancel button which // closes the .showIndicator( true) // this is the small box // which shows the chosen // color by user at the // bottom of the cancel // button .showValue( false) // this is the value which // shows the selected // color hex code // the above all values can be made // false to disable them on the // color picker dialog. .build() .show( v, new ColorPickerPopup.ColorPickerObserver() { @Override public void onColorPicked(int color) { // set the color // which is returned // by the color // picker mDefaultColor = color; // now as soon as // the dialog closes // set the preview // box to returned // color Parent.setBackgroundColor(mDefaultColor); } }); } return true; } }); popup.show(); } }); imageSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageSearch.setVisibility(View.GONE); imageSearchClose.setVisibility(View.VISIBLE); searchLayout.setVisibility(View.VISIBLE); } }); imageSearchClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageSearch.setVisibility(View.VISIBLE); imageSearchClose.setVisibility(View.GONE); searchLayout.setVisibility(View.GONE); new TextHighlighter() .resetBackgroundColor() .resetForegroundColor() .addTarget(inputNoteText) .highlight(inputSearch.getText().toString(), TextHighlighter.BASE_MATCHER); } }); fileMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(getApplicationContext(), fileMenu); //Inflating the Popup using xml file popup.getMenuInflater().inflate(R.menu.createnotefileoption, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.file) { custom = "file"; displayCustomPdf(); } if (item.getItemId() == R.id.video) { custom = "video"; displayCustomPdf(); } if (item.getItemId() == R.id.audio) { custom = "audio"; displayCustomPdf(); } if (item.getItemId() == R.id.music) { custom = "music"; displayCustomPdf(); } if (item.getItemId() == R.id.pictures) { custom = "pictures"; displayCustomPdf(); } return true; } }); popup.show(); } }); findViewById(R.id.refreshFile).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { displayPdf(); } }); findViewById(R.id.NoteRight).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { inputNoteText.setGravity(Gravity.END); } }); findViewById(R.id.NoteLeft).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { inputNoteText.setGravity(Gravity.START); } }); findViewById(R.id.NoteMiddle).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { inputNoteText.setGravity(Gravity.CENTER_HORIZONTAL); } }); findViewById(R.id.imageQRCode).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(inputNoteTitle.getText().toString()) || TextUtils.isEmpty(inputNoteText.getText().toString())) { showToastRed("Qr Can not be created empty"); } else { try { createQRCode(); } catch (Exception exception) { exception.printStackTrace(); } } } }); BulletText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("⬤ "); } else { inputNoteText.setText(string + "\n\n⬤ "); } inputNoteText.setSelection(inputNoteText.getText().length()); inputNoteText.requestFocus(); } }); circleText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("〇 "); } else { inputNoteText.setText(string + "\n\n〇 "); } inputNoteText.setSelection(inputNoteText.getText().length()); inputNoteText.requestFocus(); } }); starText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("★ "); } else { inputNoteText.setText(string + "\n\n★ "); } inputNoteText.setSelection(inputNoteText.getText().length()); inputNoteText.requestFocus(); } }); rightText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("✔ "); } else { inputNoteText.setText(string + "\n\n✔ "); } inputNoteText.setSelection(inputNoteText.getText().length()); inputNoteText.requestFocus(); } }); wrongText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("X "); } else { inputNoteText.setText(string + "\n\nX "); } inputNoteText.setSelection(inputNoteText.getText().length()); inputNoteText.requestFocus(); } }); squareText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("▢ "); } else { inputNoteText.setText(string + "\n\n▢ "); } inputNoteText.setSelection(inputNoteText.getText().length()); inputNoteText.requestFocus(); } }); alphabetText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText(c + ") "); } else { inputNoteText.setText(string + "\n\n" + c + ") "); } inputNoteText.setSelection(inputNoteText.getText().length()); c = (char) (c + 1); if (c > 'Z') { c = 'A'; } inputNoteText.requestFocus(); } }); alphabetSmallText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText(d + ") "); } else { inputNoteText.setText(string + "\n\n" + d + ") "); } inputNoteText.setSelection(inputNoteText.getText().length()); d = (char) (d + 1); if (d > 'z') { d = 'a'; } inputNoteText.requestFocus(); } }); NumberText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText(numberList + ") "); } else { inputNoteText.setText(string + "\n\n" + numberList + ") "); } inputNoteText.setSelection(inputNoteText.getText().length()); numberList = numberList + 1; inputNoteText.requestFocus(); } }); checkBoxText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("☑️ "); } else { inputNoteText.setText(string + "\n\n☑️ "); } inputNoteText.setSelection(inputNoteText.getText().length()); inputNoteText.requestFocus(); } }); /* checkBoxText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox ch = new CheckBox(getApplicationContext()); ch.setText("☑️"); checkLinear.addView(ch); } });*/ /* moreIcons.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IconBottomLayout(); } });*/ imageLock.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageLock.setVisibility(View.GONE); imageUnLock.setVisibility(View.VISIBLE); } }); imageUnLock.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageLock.setVisibility(View.VISIBLE); imageUnLock.setVisibility(View.GONE); } }); sheetView = LayoutInflater.from(CreateNoteActivity.this).inflate(R.layout.layout_miscellaneous, (ViewGroup) findViewById(R.id.layoutMiscellaneous)); if (alreadyAvailableNote != null && alreadyAvailableNote.getBackgroundColor() != null && !alreadyAvailableNote.getBackgroundColor().trim().isEmpty()) { Parent.setBackgroundColor(Integer.parseInt(alreadyAvailableNote.getBackgroundColor())); mDefaultColor = Integer.parseInt(alreadyAvailableNote.getBackgroundColor()); } if (alreadyAvailableNote != null && alreadyAvailableNote.getTextColor() != null && !alreadyAvailableNote.getTextColor().trim().isEmpty()) { mDefaultTextColor = Integer.parseInt(alreadyAvailableNote.getTextColor()); inputNoteTitle.setTextColor(Integer.parseInt(alreadyAvailableNote.getTextColor())); inputNoteSubTitle.setTextColor(Integer.parseInt(alreadyAvailableNote.getTextColor())); inputNoteText.setTextColor(Integer.parseInt(alreadyAvailableNote.getTextColor())); textDateTime.setTextColor(Integer.parseInt(alreadyAvailableNote.getTextColor())); textDateTime2.setTextColor(Integer.parseInt(alreadyAvailableNote.getTextColor())); labels.setTextColor(Integer.parseInt(alreadyAvailableNote.getTextColor())); TextFileName.setTextColor(Integer.parseInt(alreadyAvailableNote.getTextColor())); } if (alreadyAvailableNote != null && alreadyAvailableNote.getColor() != null && !alreadyAvailableNote.getColor().trim().isEmpty()) { ChangingDBBackground(); } if (getIntent().getBooleanExtra("isFromQuickActions", false)) { String type = getIntent().getStringExtra("quickActionType"); if (type != null) { switch (type) { case "image": selectedImagePath = getIntent().getStringExtra("imagePath"); imageNote.setImageBitmap(BitmapFactory.decodeFile(selectedImagePath)); imageNote.setVisibility(View.VISIBLE); findViewById(R.id.imageMoreImage).setVisibility(View.VISIBLE); break; case "URL": textWebURL.setText(getIntent().getStringExtra("URL")); layoutWebURL.setVisibility(View.VISIBLE); break; case "Text": inputNoteText.setText(getIntent().getStringExtra("Text")); break; } } } final ImageView imageSpeech = findViewById(R.id.imageSpeech); imageSpeech.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(getApplicationContext(), imageSpeech); //Inflating the Popup using xml file popup.getMenuInflater().inflate(R.menu.voice_note, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.title) { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Need to speak"); try { startActivityForResult(intent, REQ_CODE_TITLE); } catch (ActivityNotFoundException a) { showToastRed("Sorry your device not supported"); } } if (item.getItemId() == R.id.sub) { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Need to speak"); try { startActivityForResult(intent, REQ_CODE_SUB_TITLE); } catch (ActivityNotFoundException a) { showToastRed("Sorry your device not supported"); } } if (item.getItemId() == R.id.note) { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Need to speak"); try { startActivityForResult(intent, REQ_CODE_NOTE); } catch (ActivityNotFoundException a) { showToastRed("Sorry your device not supported"); } } return true; } }); popup.show(); } }); // Linkify.addLinks(inputNoteText, Linkify.PHONE_NUMBERS | Linkify.WEB_URLS); /*Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); if (Intent.ACTION_SEND.equals(action) && type != null) { if (type.startsWith("image/")) { handleSendImage(intent); // Handle single image being sent } else if (type.startsWith("text/")) { handleSendText(intent); } }*/ } private void AddingClip() { viewHolder = "CreateNote"; addingClip = new BottomSheetDialog(CreateNoteActivity.this, R.style.BottomSheetTheme); sheetView = LayoutInflater.from(CreateNoteActivity.this).inflate(R.layout.addingbottomlayout, (ViewGroup) findViewById(R.id.layoutAdding)); sheetView.findViewById(R.id.layoutAddImage).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addingClip.dismiss(); if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager .PERMISSION_GRANTED) { ActivityCompat.requestPermissions(CreateNoteActivity.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE_PERMISSION ); } else { selectImage(); } } }); sheetView.findViewById(R.id.layoutAddImage2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addingClip.dismiss(); Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_REQUEST); } }); sheetView.findViewById(R.id.layoutAddUrl).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addingClip.dismiss(); showAddURLDialog(); } }); sheetView.findViewById(R.id.layoutAddLabel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addingClip.dismiss(); showAddLabelDialog(); } }); sheetView.findViewById(R.id.layoutAddTimeStamp).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addingClip.dismiss(); @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z"); String currentDateandTime = sdf.format(new Date()); String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText(currentDateandTime); } else { inputNoteText.setText(string + "\n\n" + currentDateandTime); } inputNoteText.setSelection(inputNoteText.getText().length()); inputNoteText.requestFocus(); } }); sheetView.findViewById(R.id.layoutSelectFile).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* PopupMenu popup = new PopupMenu(getApplicationContext(), sheetView.findViewById(R.id.layoutSelectFile)); //Inflating the Popup using xml file popup.getMenuInflater().inflate(R.menu.storage_choosing, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.internal) { addingClip.dismiss(); fileFormat = "File"; fileEnd = "pdf"; Intent intent = new Intent(CreateNoteActivity.this, FileDisplayed.class); startActivity(intent); *//* fileEnd = "pdf"; Intent intent = new Intent(CreateNoteActivity.this,FileDisplayed.class); startActivity(intent);*//* } if (item.getItemId() == R.id.external) { Toast.makeText(CreateNoteActivity.this, "Feature in progress", Toast.LENGTH_SHORT).show(); } return true; } }); popup.show();*/ fileFormat = "File"; fileEnd = "pdf"; startActivity(new Intent(getApplicationContext(), FileDisplayed.class)); } }); sheetView.findViewById(R.id.layoutSelectAudio).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*PopupMenu popup = new PopupMenu(getApplicationContext(), sheetView.findViewById(R.id.layoutSelectAudio)); //Inflating the Popup using xml file popup.getMenuInflater().inflate(R.menu.storage_choosing, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.internal) { fileFormat = "Audio"; fileEnd = "amr"; Intent intent = new Intent(CreateNoteActivity.this, FileDisplayed.class); startActivity(intent); } if (item.getItemId() == R.id.bgColor) { Toast.makeText(CreateNoteActivity.this, "Feature in progress", Toast.LENGTH_SHORT).show(); } return true; } }); popup.show();*/ fileFormat = "Audio"; fileEnd = "amr"; startActivity(new Intent(getApplicationContext(), FileDisplayed.class)); } }); sheetView.findViewById(R.id.layoutSelectVideo).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*PopupMenu popup = new PopupMenu(getApplicationContext(), sheetView.findViewById(R.id.layoutSelectVideo)); //Inflating the Popup using xml file popup.getMenuInflater().inflate(R.menu.storage_choosing, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.internal) { fileFormat = "Video"; fileEnd = "mp4"; Intent intent = new Intent(CreateNoteActivity.this, FileDisplayed.class); startActivity(intent); } if (item.getItemId() == R.id.bgColor) { Toast.makeText(CreateNoteActivity.this, "Feature in progress", Toast.LENGTH_SHORT).show(); } return true; } }); popup.show();*/ fileFormat = "Video"; fileEnd = "mp4"; startActivity(new Intent(getApplicationContext(), FileDisplayed.class)); } }); sheetView.findViewById(R.id.layoutSelectMusic).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*PopupMenu popup = new PopupMenu(getApplicationContext(), sheetView.findViewById(R.id.layoutSelectMusic)); //Inflating the Popup using xml file popup.getMenuInflater().inflate(R.menu.storage_choosing, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.internal) { fileFormat = "Music"; fileEnd = "mp3"; Intent intent = new Intent(CreateNoteActivity.this, FileDisplayed.class); startActivity(intent); } if (item.getItemId() == R.id.bgColor) { Toast.makeText(CreateNoteActivity.this, "Feature in progress", Toast.LENGTH_SHORT).show(); } return true; } }); popup.show();*/ fileFormat = "Music"; fileEnd = "mp3"; startActivity(new Intent(getApplicationContext(), FileDisplayed.class)); } }); sheetView.findViewById(R.id.layoutRecord).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addingClip.dismiss(); RecordingBottom(); } }); addingClip.setContentView(sheetView); addingClip.show(); } private void RecordingBottom() { addingRecorder = new BottomSheetDialog(CreateNoteActivity.this, R.style.BottomSheetTheme); sheetView = LayoutInflater.from(CreateNoteActivity.this).inflate(R.layout.recordingbottom, (ViewGroup) findViewById(R.id.layoutRecording)); ImageButton btnRec; TextView txtRecStatus; Chronometer timeRec; ImageView cancel; File path = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName); btnRec = sheetView.findViewById(R.id.btnRec); txtRecStatus = sheetView.findViewById(R.id.txtRecStatus); timeRec = sheetView.findViewById(R.id.timeRec); cancel = sheetView.findViewById(R.id.cancelRecorder); isRecording = false; SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()); String date = format.format(new Date()); fileName = path + "/recording_" + date + ".amr"; btnRec.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isRecording) { try { startRecording(); timeRec.setBase(SystemClock.elapsedRealtime()); timeRec.start(); txtRecStatus.setText("Recording..."); btnRec.setImageResource(R.drawable.ic_stop); isRecording = true; } catch (Exception e) { e.printStackTrace(); showToastRed("Couldn't Record"); } } else { stopRecording(); timeRec.setBase(SystemClock.elapsedRealtime()); timeRec.stop(); txtRecStatus.setText(""); btnRec.setImageResource(R.drawable.ic_record); isRecording = false; } } }); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addingRecorder.dismiss(); displayPdf(); AddingClip(); } }); addingRecorder.setContentView(sheetView); addingRecorder.show(); } public void startRecording() { recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); recorder.setOutputFile(fileName); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try { recorder.prepare(); } catch (IOException e) { e.printStackTrace(); } recorder.start(); } public void stopRecording() { displayPdf(); recorder.stop(); recorder.release(); recorder = null; } private void imageBottomUp() { bottomSheetDialog = new BottomSheetDialog(CreateNoteActivity.this, R.style.BottomSheetTheme); sheetView = LayoutInflater.from(CreateNoteActivity.this).inflate(R.layout.imagefull, (ViewGroup) findViewById(R.id.layoutImage)); final ImageView imageView = sheetView.findViewById(R.id.fullImage); final ImageView imageView2 = sheetView.findViewById(R.id.fullImage2); final ImageView imageView3 = sheetView.findViewById(R.id.left); final ImageView imageView4 = sheetView.findViewById(R.id.right); if (alreadyAvailableNote.getImagePath() != null && !alreadyAvailableNote.getImagePath().trim().isEmpty() && selectImageUri != null) { imageView.setVisibility(View.GONE); imageView2.setVisibility(View.GONE); imageView2.setImageBitmap(BitmapFactory.decodeFile(alreadyAvailableNote.getImagePath())); try { inputStream = getContentResolver().openInputStream(selectImageUri); bitmap = BitmapFactory.decodeStream(inputStream); imageView.setImageBitmap(bitmap); selectedImagePath2 = getPathFromUri(selectImageUri); } catch (Exception exception) { showToastRed("Error occurred, Please try again"); } selectedImagePath2 = alreadyAvailableNote.getImagePath(); imageView2.setVisibility(View.VISIBLE); imageView4.setVisibility(View.VISIBLE); imageView4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView4.setVisibility(View.INVISIBLE); imageView2.setVisibility(View.GONE); imageView.setVisibility(View.VISIBLE); imageView3.setVisibility(View.VISIBLE); } }); imageView3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.setVisibility(View.GONE); imageView3.setVisibility(View.INVISIBLE); imageView4.setVisibility(View.VISIBLE); imageView2.setVisibility(View.VISIBLE); } }); } else { if (alreadyAvailableNote.getImagePath() != null && !alreadyAvailableNote.getImagePath().trim().isEmpty()) { imageView2.setImageBitmap(BitmapFactory.decodeFile(alreadyAvailableNote.getImagePath())); selectedImagePath2 = alreadyAvailableNote.getImagePath(); } if (selectImageUri != null) { try { inputStream = getContentResolver().openInputStream(selectImageUri); bitmap = BitmapFactory.decodeStream(inputStream); imageView.setImageBitmap(bitmap); selectedImagePath2 = getPathFromUri(selectImageUri); } catch (Exception exception) { showToastRed("Error occurred, Please try again"); } } } bottomSheetDialog.setContentView(sheetView); bottomSheetDialog.show(); } private void ImageOptions() { if (ImageOption == null) { AlertDialog.Builder builder = new AlertDialog.Builder(CreateNoteActivity.this); View view = LayoutInflater.from(this).inflate( R.layout.imagemenu, (ViewGroup) findViewById(R.id.layoutImageMenuContainer) ); builder.setView(view); ImageOption = builder.create(); if (ImageOption.getWindow() != null) { ImageOption.getWindow().setBackgroundDrawable(new ColorDrawable(0)); } LinearLayout linearLayout, linearLayout1, linearLayout2, linearLayout3, linearLayout4; linearLayout = view.findViewById(R.id.Expand); linearLayout1 = view.findViewById(R.id.Download); linearLayout2 = view.findViewById(R.id.Delete); linearLayout3 = view.findViewById(R.id.imageHistory); linearLayout4 = view.findViewById(R.id.Share); ImageView imageView = view.findViewById(R.id.ImageSettingsCancel); linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* Drawable drawable=imageNote.getDrawable(); Bitmap bitmap= ((BitmapDrawable)drawable).getBitmap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] b = baos.toByteArray(); Intent intent=new Intent(CreateNoteActivity.this,FullImageView.class); intent.putExtra("picture", b); startActivity(intent); ImageOption.cancel();*/ imageBottomUp(); ImageOption.cancel(); } }); linearLayout1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String randCode = new SimpleDateFormat("dd MM yyyy HH:mm:ss a", Locale.getDefault()).format(new Date()); randCode = randCode.replaceAll(":", ""); randCode = randCode.replaceAll(" ", ""); BitmapDrawable bitmapDrawable = (BitmapDrawable) imageNote.getDrawable(); Bitmap bitmap = bitmapDrawable.getBitmap(); FileOutputStream outputStream = null; File file = Environment.getExternalStorageDirectory(); File dir = new File(file.getAbsolutePath() + File.separator + "Remarques" + File.separator + "Gallery"); boolean success = true; if (!dir.exists()) { success = dir.mkdirs(); } if (success) { String fileName = String.format(randCode + ".png", System.currentTimeMillis()); File outFile = new File(dir, fileName); try { outputStream = new FileOutputStream(outFile); } catch (FileNotFoundException e) { e.printStackTrace(); } bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); try { assert outputStream != null; outputStream.flush(); } catch (Exception e) { e.printStackTrace(); } try { outputStream.close(); } catch (Exception e) { e.printStackTrace(); } showToast("Image saved in gallery"); } else { showToastRed("Error"); } ImageOption.cancel(); } }); linearLayout3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveInFavorite(); ImageOption.cancel(); } }); linearLayout2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageNote.setImageDrawable(null); imageNote.setVisibility(View.GONE); MoreImage.setVisibility(View.GONE); ImageOption.cancel(); } }); linearLayout4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String fileName; String randCode = new SimpleDateFormat("dd MM yyyy HH:mm:ss a", Locale.getDefault()).format(new Date()); randCode = randCode.replaceAll(":", ""); randCode = randCode.replaceAll(" ", ""); BitmapDrawable bitmapDrawable = (BitmapDrawable) imageNote.getDrawable(); Bitmap bitmap = bitmapDrawable.getBitmap(); FileOutputStream outputStream = null; File file = Environment.getExternalStorageDirectory(); File dir = new File(file.getAbsolutePath() + File.separator + "Remarques" + File.separator + "Shared Images"); boolean success = true; if (!dir.exists()) { success = dir.mkdirs(); } if (success) { fileName = String.format(randCode + ".png", System.currentTimeMillis()); File outFile = new File(dir, fileName); try { outputStream = new FileOutputStream(outFile); } catch (FileNotFoundException e) { e.printStackTrace(); } bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); try { assert outputStream != null; outputStream.flush(); } catch (Exception e) { e.printStackTrace(); } try { outputStream.close(); } catch (Exception e) { e.printStackTrace(); } File dir2 = new File(file.getAbsolutePath() + File.separator + "Remarques" + File.separator + "Shared Images" + File.separator + fileName); Sharing(dir2); } else { showToastRed("Error"); } } }); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ImageOption.dismiss(); } }); } ImageOption.show(); } private void saveInFavorite() { /*Random r = new Random(System.currentTimeMillis()); int randomCode = ((1 + r.nextInt(2)) * 10000000 + r.nextInt(10000000)); String randCode = Integer.toString(randomCode);*/ String randCode = new SimpleDateFormat("dd MM yyyy HH:mm:ss a", Locale.getDefault()).format(new Date()); randCode = randCode.replaceAll(":", ""); randCode = randCode.replaceAll(" ", ""); BitmapDrawable bitmapDrawable = (BitmapDrawable) imageNote.getDrawable(); Bitmap bitmap = bitmapDrawable.getBitmap(); FileOutputStream outputStream = null; File file = Environment.getExternalStorageDirectory(); File dir = new File(file.getAbsolutePath() + File.separator + "Remarques" + File.separator + "Favorite Pictures"); boolean success = true; if (!dir.exists()) { success = dir.mkdirs(); } if (success) { String fileName = String.format(randCode + ".png", System.currentTimeMillis()); File outFile = new File(dir, fileName); try { outputStream = new FileOutputStream(outFile); } catch (FileNotFoundException e) { e.printStackTrace(); } bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); try { assert outputStream != null; outputStream.flush(); } catch (Exception e) { e.printStackTrace(); } try { outputStream.close(); } catch (Exception e) { e.printStackTrace(); } showToastRed("Image saved in favorite"); } else { showToast("Error"); } } private void UrlOptions() { if (UrlOption == null) { AlertDialog.Builder builder = new AlertDialog.Builder(CreateNoteActivity.this); View view = LayoutInflater.from(this).inflate( R.layout.urlmenu, (ViewGroup) findViewById(R.id.layoutUrlMenuContainer) ); builder.setView(view); UrlOption = builder.create(); if (UrlOption.getWindow() != null) { UrlOption.getWindow().setBackgroundDrawable(new ColorDrawable(0)); } LinearLayout linearLayout, linearLayout1, linearLayout2, linearLayout3, linearLayout4, linearLayout5, linearLayout6; linearLayout = view.findViewById(R.id.SearchGoogle); linearLayout1 = view.findViewById(R.id.SearchDuckDuck); // linearLayout2 = view.findViewById(R.id.Web); linearLayout3 = view.findViewById(R.id.SavePDF); linearLayout4 = view.findViewById(R.id.QRCode); linearLayout5 = view.findViewById(R.id.Share); linearLayout6 = view.findViewById(R.id.Delete); ImageView imageView; imageView = view.findViewById(R.id.ImageSettingsCancel); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UrlOption.dismiss(); } }); linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { String toCopy = textWebURL.getText().toString(); ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Google Chrome Url", toCopy); clipboard.setPrimaryClip(clip); showToast("Paste the URL in the search box"); PackageManager pm = getPackageManager(); Intent intent2 = pm.getLaunchIntentForPackage("com.android.chrome"); startActivity(intent2); } catch (Exception e) { showToastRed("Google Chrome does not exists"); } } }); linearLayout1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { String toCopy = textWebURL.getText().toString(); ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Duck Duck Go Url", toCopy); clipboard.setPrimaryClip(clip); showToast("Paste the URL in the search box"); PackageManager pm = getPackageManager(); Intent intent2 = pm.getLaunchIntentForPackage("com.duckduckgo.mobile.android"); startActivity(intent2); } catch (Exception e) { showToastRed("Duck Duck Go does not exists"); } } }); linearLayout3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE); if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) { showMessage(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } }); return; } requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } } else { showToast("PDF copy has been saved to this device successfully"); File docsFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + "PDF Files"); boolean success = true; if (!docsFolder.exists()) { success = docsFolder.mkdirs(); } if (success) { String randCode = new SimpleDateFormat("dd MM yyyy HH:mm:ss a", Locale.getDefault()).format(new Date()); randCode = randCode.replaceAll(":", ""); randCode = randCode.replaceAll(" ", ""); pdfFile = new File(docsFolder.getAbsolutePath(), randCode + ".pdf"); OutputStream outputStream = new FileOutputStream(pdfFile); Document document = new Document(); PdfWriter.getInstance(document, outputStream); document.open(); Font f = new Font(Font.FontFamily.TIMES_ROMAN, 18f, Font.BOLD, BaseColor.BLUE); document.add(new Paragraph(textWebURL.getText().toString(), f)); document.close(); } else { showToastRed("Error"); } } } catch (Exception e) { e.printStackTrace(); } } }); linearLayout4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { File docsFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + "QR Codes"); boolean success = true; if (!docsFolder.exists()) { success = docsFolder.mkdirs(); } if (success) { String randCode = new SimpleDateFormat("dd MM yyyy HH:mm:ss a", Locale.getDefault()).format(new Date()); randCode = randCode.replaceAll(":", ""); randCode = randCode.replaceAll(" ", ""); pdfFile = new File(docsFolder.getAbsolutePath(), randCode + ".pdf"); OutputStream outputStream = new FileOutputStream(pdfFile); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfContentByte cb = writer.getDirectContent(); BarcodeQRCode barcodeQRCode = new BarcodeQRCode(textWebURL.getText().toString(), 1000, 1000, null); Image codeQrImage = barcodeQRCode.getImage(); codeQrImage.scaleAbsolute(350, 350); document.add(codeQrImage); document.newPage(); document.close(); } else { showToastRed("Error"); } } catch (Exception e) { e.printStackTrace(); } } }); linearLayout5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(android.content.Intent.ACTION_SEND); String shareBody = textWebURL.getText().toString(); intent.setType("text/plain"); intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); startActivity(Intent.createChooser(intent, "Share")); } }); linearLayout6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textWebURL.setText(null); layoutWebURL.setVisibility(View.GONE); UrlOption.cancel(); } }); } UrlOption.show(); } private void NoteSettings() { if (dialogSettingsNote == null) { AlertDialog.Builder builder = new AlertDialog.Builder(CreateNoteActivity.this); View view = LayoutInflater.from(this).inflate( R.layout.note_settings_layout, (ViewGroup) findViewById(R.id.layoutSettingsNoteContainer) ); builder.setView(view); dialogSettingsNote = builder.create(); if (dialogSettingsNote.getWindow() != null) { dialogSettingsNote.getWindow().setBackgroundDrawable(new ColorDrawable(0)); } final CheckBox textBox, textBox1; String richText, linkText; textBox = view.findViewById(R.id.richTextBox); textBox1 = view.findViewById(R.id.linkTextBox); SharedPreferences getShared3 = getSharedPreferences("settings", MODE_PRIVATE); richText = getShared3.getString("rich text", null); if (richText.equals("1")) { textBox.setChecked(false); } else if (richText.equals("2")) { textBox.setChecked(true); } SharedPreferences getShared4 = getSharedPreferences("settings", MODE_PRIVATE); linkText = getShared4.getString("link text", null); if (linkText.equals("1")) { textBox1.setChecked(false); } else if (linkText.equals("2")) { textBox1.setChecked(true); } textBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final SharedPreferences shard2 = getSharedPreferences("settings", MODE_PRIVATE); final SharedPreferences.Editor editor2 = shard2.edit(); if (textBox.isChecked()) { editor2.putString("rich text", "2"); } else { editor2.putString("rich text", "1"); } editor2.apply(); dialogSettingsNote.cancel(); First(); } }); textBox1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final SharedPreferences shard2 = getSharedPreferences("settings", MODE_PRIVATE); final SharedPreferences.Editor editor2 = shard2.edit(); if (textBox1.isChecked()) { editor2.putString("link text", "2"); } else { editor2.putString("link text", "1"); } editor2.apply(); dialogSettingsNote.cancel(); First(); } }); view.findViewById(R.id.ImageSettingsCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialogSettingsNote.dismiss(); } }); } dialogSettingsNote.show(); } /*private void IconBottomLayout() { bottomSheetDialog = new BottomSheetDialog(CreateNoteActivity.this, R.style.BottomSheetTheme); sheetView = LayoutInflater.from(CreateNoteActivity.this).inflate(R.layout.icon_layout, (ViewGroup) findViewById(R.id.layoutIcons)); final SwitchCompat switchCompat, switchCompat1; switchCompat = sheetView.findViewById(R.id.switchCompat); switchCompat1 = sheetView.findViewById(R.id.switchCompat1); final TextView textView = sheetView.findViewById(R.id.textShown); final TextView textView1 = sheetView.findViewById(R.id.textShown1); final LinearLayout linearLayout, linearLayout1, linearLayout2, linearLayout3; linearLayout = sheetView.findViewById(R.id.layoutOutline1); linearLayout2 = sheetView.findViewById(R.id.layoutOutline2); linearLayout1 = sheetView.findViewById(R.id.layoutFilled1); linearLayout3 = sheetView.findViewById(R.id.layoutFilled2); final LinearLayout linearLayoutSymbol; linearLayoutSymbol = sheetView.findViewById(R.id.layoutSymbol1); final ImageView imageView, imageView1, imageView2, imageView3, imageView4, imageView5; imageView = sheetView.findViewById(R.id.symbol1); imageView1 = sheetView.findViewById(R.id.symbol2); imageView2 = sheetView.findViewById(R.id.symbol3); imageView3 = sheetView.findViewById(R.id.symbol4); imageView4 = sheetView.findViewById(R.id.symbol5); imageView5 = sheetView.findViewById(R.id.symbol6); switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (switchCompat.isChecked()) { linearLayout.setVisibility(View.GONE); linearLayout2.setVisibility(View.GONE); textView.setText("Filled"); linearLayout1.setVisibility(View.VISIBLE); linearLayout3.setVisibility(View.VISIBLE); } else { linearLayout1.setVisibility(View.GONE); linearLayout3.setVisibility(View.GONE); textView.setText("Outlined"); linearLayout.setVisibility(View.VISIBLE); linearLayout2.setVisibility(View.VISIBLE); } } }); bottomSheetDialog.dismiss(); switchCompat1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (switchCompat1.isChecked()) { linearLayoutSymbol.setVisibility(View.VISIBLE); textView1.setText("Hide Symbols"); } else { linearLayoutSymbol.setVisibility(View.GONE); textView1.setText("Show Symbols"); } } }); bottomSheetDialog.dismiss(); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("₹ "); } else { inputNoteText.setText(string + "\n\n₹ "); } inputNoteText.setSelection(inputNoteText.getText().length()); bottomSheetDialog.dismiss(); } }); imageView1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("Rs "); } else { inputNoteText.setText(string + "\n\nRs "); } inputNoteText.setSelection(inputNoteText.getText().length()); bottomSheetDialog.dismiss(); } }); imageView2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("◆ "); } else { inputNoteText.setText(string + "\n\n◆ "); } inputNoteText.setSelection(inputNoteText.getText().length()); bottomSheetDialog.dismiss(); } }); imageView3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("❖ "); } else { inputNoteText.setText(string + "\n\n❖ "); } inputNoteText.setSelection(inputNoteText.getText().length()); bottomSheetDialog.dismiss(); } }); imageView4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("♠️ "); } else { inputNoteText.setText(string + "\n\n♠️ "); } inputNoteText.setSelection(inputNoteText.getText().length()); bottomSheetDialog.dismiss(); } }); imageView5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("➤ "); } else { inputNoteText.setText(string + "\n\n➤ "); } inputNoteText.setSelection(inputNoteText.getText().length()); bottomSheetDialog.dismiss(); } }); imageView4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = inputNoteText.getText().toString(); if (TextUtils.isEmpty(string)) { inputNoteText.setText("♠ "); } else { inputNoteText.setText(string + "\n\n♠ "); } inputNoteText.setSelection(inputNoteText.getText().length()); bottomSheetDialog.dismiss(); } }); bottomSheetDialog.setContentView(sheetView); bottomSheetDialog.show(); }*/ private void Sharing(File file) { Uri uri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", file); Intent pdfIntent = new Intent(Intent.ACTION_SEND); pdfIntent.setDataAndType(uri, "image/*"); pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); pdfIntent.putExtra(Intent.EXTRA_STREAM, uri); try { startActivity(Intent.createChooser(pdfIntent, "Share Sound File")); } catch (ActivityNotFoundException e) { Toast.makeText(getApplicationContext(), "No Applications found to open this format file. You can download relevant application to view this file format", Toast.LENGTH_LONG).show(); } } private void ChangingDBBackground() { switch (alreadyAvailableNote.getColor()) { case "#FDBE3B": selectedNoteColor = "#FDBE3B"; setSubTitleIndicatorColor(); break; case "#FF4842": selectedNoteColor = "#FF4842"; setSubTitleIndicatorColor(); break; case "#3a52fc": selectedNoteColor = "#3a52fc"; setSubTitleIndicatorColor(); break; case "#000000": selectedNoteColor = "#000000"; setSubTitleIndicatorColor(); break; case "#EE82EE": selectedNoteColor = "#EE82EE"; setSubTitleIndicatorColor(); break; case "#800080": selectedNoteColor = "#800080"; setSubTitleIndicatorColor(); break; case "#000080": selectedNoteColor = "#000080"; setSubTitleIndicatorColor(); break; case "#0d98ba": selectedNoteColor = "#0d98ba"; setSubTitleIndicatorColor(); break; case "#7cfc00": selectedNoteColor = "#7cfc00"; setSubTitleIndicatorColor(); break; case "#006400": selectedNoteColor = "#006400"; setSubTitleIndicatorColor(); break; case "#fb7268": selectedNoteColor = "#fb7268"; setSubTitleIndicatorColor(); break; } } private void ShareBottomLayout() { bottomSheetDialog = new BottomSheetDialog(CreateNoteActivity.this, R.style.BottomSheetTheme); sheetView = LayoutInflater.from(CreateNoteActivity.this).inflate(R.layout.layout_share, (ViewGroup) findViewById(R.id.layoutMiscellaneous)); sheetView.findViewById(R.id.WhatsApp).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PackageManager pm = CreateNoteActivity.this.getPackageManager(); try { Intent waIntent = new Intent(Intent.ACTION_SEND); waIntent.setType("text/plain"); String text = toShare; PackageInfo info = pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA); waIntent.setPackage("com.whatsapp"); waIntent.putExtra(Intent.EXTRA_TEXT, text); startActivity(Intent.createChooser(waIntent, "Share with")); } catch (PackageManager.NameNotFoundException e) { showToastRed("WhatsApp not Installed"); } bottomSheetDialog.dismiss(); } }); bottomSheetDialog.setContentView(sheetView); bottomSheetDialog.show(); } private void bottomUp() { bottomSheetDialog = new BottomSheetDialog(CreateNoteActivity.this, R.style.BottomSheetTheme); sheetView = LayoutInflater.from(CreateNoteActivity.this).inflate(R.layout.layout_miscellaneous, (ViewGroup) findViewById(R.id.layoutMiscellaneous)); final ImageView imageColor1, imageColor2, imageColor3, imageColor4, imageColor5, imageColor6, imageColor7, imageColor8, imageColor9, imageColor10, imageColor11, imageColor12; final LinearLayout linearLayout, linearLayout1, linearLayout2, linearLayout3, linearLayout4, linearLayout5; imageColor1 = sheetView.findViewById(R.id.imageColor1); imageColor2 = sheetView.findViewById(R.id.imageColor2); imageColor3 = sheetView.findViewById(R.id.imageColor3); imageColor4 = sheetView.findViewById(R.id.imageColor4); imageColor5 = sheetView.findViewById(R.id.imageColor5); imageColor6 = sheetView.findViewById(R.id.imageColor6); imageColor7 = sheetView.findViewById(R.id.imageColor7); imageColor8 = sheetView.findViewById(R.id.imageColor8); imageColor9 = sheetView.findViewById(R.id.imageColor9); imageColor10 = sheetView.findViewById(R.id.imageColor10); imageColor11 = sheetView.findViewById(R.id.imageColor11); imageColor12 = sheetView.findViewById(R.id.imageColor12); linearLayout = sheetView.findViewById(R.id.layoutPin); // linearLayout1 = sheetView.findViewById(R.id.layoutUnPin); linearLayout2 = sheetView.findViewById(R.id.layoutStar); // linearLayout3 = sheetView.findViewById(R.id.layoutUnStar); linearLayout4 = sheetView.findViewById(R.id.layoutArchive); // linearLayout5 = sheetView.findViewById(R.id.layoutUnArchive); sheetView.findViewById(R.id.viewColor1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#333333"; imageColor1.setImageResource(R.drawable.done); imageColor2.setImageResource(0); imageColor3.setImageResource(0); imageColor4.setImageResource(0); imageColor5.setImageResource(0); imageColor6.setImageResource(0); imageColor7.setImageResource(0); imageColor8.setImageResource(0); imageColor9.setImageResource(0); imageColor10.setImageResource(0); imageColor11.setImageResource(0); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#FDBE3B"; imageColor1.setImageResource(0); imageColor2.setImageResource(R.drawable.done); imageColor3.setImageResource(0); imageColor4.setImageResource(0); imageColor5.setImageResource(0); imageColor6.setImageResource(0); imageColor7.setImageResource(0); imageColor8.setImageResource(0); imageColor9.setImageResource(0); imageColor10.setImageResource(0); imageColor11.setImageResource(0); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#FF4842"; imageColor1.setImageResource(0); imageColor2.setImageResource(0); imageColor3.setImageResource(R.drawable.done); imageColor4.setImageResource(0); imageColor5.setImageResource(0); imageColor6.setImageResource(0); imageColor7.setImageResource(0); imageColor8.setImageResource(0); imageColor9.setImageResource(0); imageColor10.setImageResource(0); imageColor11.setImageResource(0); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor4).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#3a52fc"; imageColor1.setImageResource(0); imageColor2.setImageResource(0); imageColor3.setImageResource(0); imageColor4.setImageResource(R.drawable.done); imageColor5.setImageResource(0); imageColor6.setImageResource(0); imageColor7.setImageResource(0); imageColor8.setImageResource(0); imageColor9.setImageResource(0); imageColor10.setImageResource(0); imageColor11.setImageResource(0); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor5).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#000000"; imageColor1.setImageResource(0); imageColor2.setImageResource(0); imageColor3.setImageResource(0); imageColor4.setImageResource(0); imageColor5.setImageResource(R.drawable.done); imageColor6.setImageResource(0); imageColor7.setImageResource(0); imageColor8.setImageResource(0); imageColor9.setImageResource(0); imageColor10.setImageResource(0); imageColor11.setImageResource(0); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor6).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#EE82EE"; imageColor1.setImageResource(0); imageColor2.setImageResource(0); imageColor3.setImageResource(0); imageColor4.setImageResource(0); imageColor5.setImageResource(0); imageColor6.setImageResource(R.drawable.done); imageColor7.setImageResource(0); imageColor8.setImageResource(0); imageColor9.setImageResource(0); imageColor10.setImageResource(0); imageColor11.setImageResource(0); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor7).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#800080"; imageColor1.setImageResource(0); imageColor2.setImageResource(0); imageColor3.setImageResource(0); imageColor4.setImageResource(0); imageColor5.setImageResource(0); imageColor6.setImageResource(0); imageColor7.setImageResource(R.drawable.done); imageColor8.setImageResource(0); imageColor9.setImageResource(0); imageColor10.setImageResource(0); imageColor11.setImageResource(0); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor8).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#000080"; imageColor1.setImageResource(0); imageColor2.setImageResource(0); imageColor3.setImageResource(0); imageColor4.setImageResource(0); imageColor5.setImageResource(0); imageColor6.setImageResource(0); imageColor7.setImageResource(0); imageColor8.setImageResource(R.drawable.done); imageColor9.setImageResource(0); imageColor10.setImageResource(0); imageColor11.setImageResource(0); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor9).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#0d98ba"; imageColor1.setImageResource(0); imageColor2.setImageResource(0); imageColor3.setImageResource(0); imageColor4.setImageResource(0); imageColor5.setImageResource(0); imageColor6.setImageResource(0); imageColor7.setImageResource(0); imageColor8.setImageResource(0); imageColor9.setImageResource(R.drawable.done); imageColor10.setImageResource(0); imageColor11.setImageResource(0); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor10).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#7cfc00"; imageColor1.setImageResource(0); imageColor2.setImageResource(0); imageColor3.setImageResource(0); imageColor4.setImageResource(0); imageColor5.setImageResource(0); imageColor6.setImageResource(0); imageColor7.setImageResource(0); imageColor8.setImageResource(0); imageColor9.setImageResource(0); imageColor10.setImageResource(R.drawable.done); imageColor11.setImageResource(0); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor11).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#006400"; imageColor1.setImageResource(0); imageColor2.setImageResource(0); imageColor3.setImageResource(0); imageColor4.setImageResource(0); imageColor5.setImageResource(0); imageColor6.setImageResource(0); imageColor7.setImageResource(0); imageColor8.setImageResource(0); imageColor9.setImageResource(0); imageColor10.setImageResource(0); imageColor11.setImageResource(R.drawable.done); imageColor12.setImageResource(0); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); sheetView.findViewById(R.id.viewColor12).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedNoteColor = "#fb7268"; imageColor1.setImageResource(0); imageColor2.setImageResource(0); imageColor3.setImageResource(0); imageColor4.setImageResource(0); imageColor5.setImageResource(0); imageColor6.setImageResource(0); imageColor7.setImageResource(0); imageColor8.setImageResource(0); imageColor9.setImageResource(0); imageColor10.setImageResource(0); imageColor11.setImageResource(0); imageColor12.setImageResource(R.drawable.done); setSubTitleIndicatorColor(); bottomSheetDialog.dismiss(); } }); if (alreadyAvailableNote != null && alreadyAvailableNote.getColor() != null && !alreadyAvailableNote.getColor().trim().isEmpty()) { switch (alreadyAvailableNote.getColor()) { case "#FDBE3B": sheetView.findViewById(R.id.viewColor2).performClick(); break; case "#FF4842": sheetView.findViewById(R.id.viewColor3).performClick(); break; case "#3a52fc": sheetView.findViewById(R.id.viewColor4).performClick(); break; case "#000000": sheetView.findViewById(R.id.viewColor5).performClick(); break; case "#EE82EE": sheetView.findViewById(R.id.viewColor6).performClick(); break; case "#800080": sheetView.findViewById(R.id.viewColor7).performClick(); break; case "#000080": sheetView.findViewById(R.id.viewColor8).performClick(); break; case "#0d98ba": sheetView.findViewById(R.id.viewColor9).performClick(); break; case "#7cfc00": sheetView.findViewById(R.id.viewColor10).performClick(); break; case "#006400": sheetView.findViewById(R.id.viewColor11).performClick(); break; case "#fb7268": sheetView.findViewById(R.id.viewColor12).performClick(); break; } } /* sheetView.findViewById(R.id.layoutAddImage).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottomSheetDialog.dismiss(); if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager .PERMISSION_GRANTED) { ActivityCompat.requestPermissions(CreateNoteActivity.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE_PERMISSION ); } else { selectImage(); } } }); sheetView.findViewById(R.id.layoutAddImage2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottomSheetDialog.dismiss(); Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_REQUEST); } }); sheetView.findViewById(R.id.layoutAddUrl).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottomSheetDialog.dismiss(); showAddURLDialog(); } });*/ if (!inputNoteText.getText().toString().isEmpty() && !inputNoteTitle.getText().toString().isEmpty()) { sheetView.findViewById(R.id.SavingLayout).setVisibility(View.VISIBLE); sheetView.findViewById(R.id.layoutSavePdf).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { createPDF(); } catch (Exception exception) { exception.printStackTrace(); } } }); sheetView.findViewById(R.id.layoutSaveTxt).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { createPDF2(); } catch (Exception exception) { exception.printStackTrace(); } } }); } /* if(!inputNoteText.getText().toString().isEmpty() && !inputNoteTitle.getText().toString().isEmpty()) { sheetView.findViewById(R.id.layoutSaveWord).setVisibility(View.VISIBLE); sheetView.findViewById(R.id.layoutSaveWord).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { createPDF1(); } catch (Exception exception) { exception.printStackTrace(); } } }); }*/ if (!inputNoteText.getText().toString().isEmpty() && !inputNoteTitle.getText().toString().isEmpty()) { sheetView.findViewById(R.id.layoutPin).setVisibility(View.VISIBLE); sheetView.findViewById(R.id.layoutPin).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(CreateNoteActivity.this, "Feature in Progress", Toast.LENGTH_SHORT).show(); } }); } if (!inputNoteText.getText().toString().isEmpty() && !inputNoteTitle.getText().toString().isEmpty()) { sheetView.findViewById(R.id.layoutStar).setVisibility(View.VISIBLE); sheetView.findViewById(R.id.layoutStar).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(CreateNoteActivity.this, "Feature in Progress", Toast.LENGTH_SHORT).show(); } }); } if (!inputNoteText.getText().toString().isEmpty() && !inputNoteTitle.getText().toString().isEmpty()) { sheetView.findViewById(R.id.layoutArchive).setVisibility(View.VISIBLE); sheetView.findViewById(R.id.layoutArchive).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(CreateNoteActivity.this, "Feature in Progress", Toast.LENGTH_SHORT).show(); } }); } if (alreadyAvailableNote != null) { sheetView.findViewById(R.id.layoutDeleteNote).setVisibility(View.VISIBLE); sheetView.findViewById(R.id.layoutDeleteNote).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDeleteDialog(); } }); } linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); bottomSheetDialog.setContentView(sheetView); bottomSheetDialog.show(); } private void createQRCode() throws Exception { File docsFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + "QR Codes"); boolean success = true; if (!docsFolder.exists()) { success = docsFolder.mkdirs(); } if (success) { String randCode = new SimpleDateFormat("dd MM yyyy HH:mm:ss a", Locale.getDefault()).format(new Date()); randCode = randCode.replaceAll(":", ""); randCode = randCode.replaceAll(" ", ""); pdfFile = new File(docsFolder.getAbsolutePath(), randCode + ".pdf"); OutputStream outputStream = new FileOutputStream(pdfFile); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfContentByte cb = writer.getDirectContent(); BarcodeQRCode barcodeQRCode = new BarcodeQRCode("Title: \n" + inputNoteTitle + "\nNote :\n\n" + inputNoteText, 1000, 1000, null); Image codeQrImage = barcodeQRCode.getImage(); codeQrImage.scaleAbsolute(350, 350); document.add(codeQrImage); document.newPage(); document.close(); showToast("Qr Code created successfully"); } else { showToastRed("Error"); } } private void createPDF2() throws Exception { int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) { showMessage(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } }); return; } requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } } else { showToast("TEXT copy has been saved to this device successfully"); File docsFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + "Text Files"); boolean success = true; if (!docsFolder.exists()) { success = docsFolder.mkdirs(); } if (success) { String randCode = new SimpleDateFormat("dd MM yyyy HH:mm:ss a", Locale.getDefault()).format(new Date()); randCode = randCode.replaceAll(":", ""); randCode = randCode.replaceAll(" ", ""); pdfFile = new File(docsFolder.getAbsolutePath(), randCode + ".txt"); OutputStream outputStream = new FileOutputStream(pdfFile); Document document = new Document(); PdfWriter.getInstance(document, outputStream); document.open(); Font f = new Font(Font.FontFamily.TIMES_ROMAN, 18f, Font.BOLD, BaseColor.RED); document.add(new Paragraph("Title", f)); Font f1 = new Font(Font.FontFamily.TIMES_ROMAN, 15f, Font.NORMAL, BaseColor.BLACK); document.add(new Paragraph("\n\n" + inputNoteTitle.getText().toString(), f1)); Font f2 = new Font(Font.FontFamily.TIMES_ROMAN, 18f, Font.BOLD, BaseColor.RED); document.add(new Paragraph("\n\n" + "Note", f2)); Font f3 = new Font(Font.FontFamily.TIMES_ROMAN, 15f, Font.BOLD, BaseColor.BLACK); document.add(new Paragraph("\n\n" + inputNoteText.getText().toString(), f3)); document.close(); } else { showToastRed("Error"); } } } private void showResetDialog() { if (dialogResetNote == null) { AlertDialog.Builder builder = new AlertDialog.Builder(CreateNoteActivity.this); View view = LayoutInflater.from(this).inflate( R.layout.layout_reset, (ViewGroup) findViewById(R.id.layoutDeleteNoteContainer) ); builder.setView(view); dialogResetNote = builder.create(); if (dialogResetNote.getWindow() != null) { dialogResetNote.getWindow().setBackgroundDrawable(new ColorDrawable(0)); } view.findViewById(R.id.textDeleteNote).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (getIntent().getBooleanExtra("isViewOrUpdate", false)) { setViewOrUpdateNote(); } else { inputNoteTitle.setText(""); inputNoteSubTitle.setText(""); inputNoteText.setText(""); layoutWebURL.setVisibility(View.GONE); textWebURL.setText(""); imageNote.setVisibility(View.GONE); MoreImage.setVisibility(View.GONE); imageNote.setImageBitmap(null); } dialogResetNote.cancel(); } }); view.findViewById(R.id.textCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialogResetNote.dismiss(); } }); } dialogResetNote.show(); } private void showDeleteDialog() { if (dialogDeleteNote == null) { AlertDialog.Builder builder = new AlertDialog.Builder(CreateNoteActivity.this); View view = LayoutInflater.from(this).inflate( R.layout.layout_delete_note, (ViewGroup) findViewById(R.id.layoutDeleteNoteContainer) ); builder.setView(view); dialogDeleteNote = builder.create(); if (dialogDeleteNote.getWindow() != null) { dialogDeleteNote.getWindow().setBackgroundDrawable(new ColorDrawable(0)); } view.findViewById(R.id.textDeleteNote).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deleteRecursive(new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName)); @SuppressLint("StaticFieldLeak") class DeleteNoteTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { NotesDatabase.getNotesDatabase(getApplicationContext()).noteDao() .deleteNote(alreadyAvailableNote); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); Intent intent = new Intent(); intent.putExtra("isNoteDeleted", true); setResult(RESULT_OK, intent); finish(); } } new DeleteNoteTask().execute(); } }); view.findViewById(R.id.textCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialogDeleteNote.dismiss(); } }); } dialogDeleteNote.show(); } private void saveNote() { /*if(inputNoteTitle.getText().toString().trim().isEmpty()) { Toast.makeText(this, "Note title can't be empty!", Toast.LENGTH_SHORT).show(); } else if(inputNoteSubTitle.getText().toString().trim().isEmpty() && inputNoteText.getText().toString().trim().isEmpty()) { Toast.makeText(this, "Note can't be empty", Toast.LENGTH_SHORT).show(); } else { }*/ i = 0; final Note note = new Note(); note.setTitle(inputNoteTitle.getText().toString()); note.setSubtitle(inputNoteSubTitle.getText().toString()); note.setNoteText(inputNoteText.getText().toString()); note.setDateTime(textDateTime.getText().toString()); note.setFolder(folderName); note.setBackgroundColor(String.valueOf(mDefaultColor)); note.setTextColor(String.valueOf(mDefaultTextColor)); note.setColor(selectedNoteColor); note.setNoteLabel(labels.getText().toString()); if (imageNote.getVisibility() == View.VISIBLE) { note.setImagePath(selectedImagePath); } if (layoutWebURL.getVisibility() == View.VISIBLE) { note.setWebLink(textWebURL.getText().toString()); } if (imageUnLock.getVisibility() == View.VISIBLE) { note.setPasswordState("Yes"); } else { note.setPasswordState("No"); } if (alreadyAvailableNote != null) { note.setId(alreadyAvailableNote.getId()); } @SuppressLint("StaticFieldLeak") class SaveNoteTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { NotesDatabase.getNotesDatabase(getApplicationContext()).noteDao().insertNote(note); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); Intent intent = new Intent(CreateNoteActivity.this, MainActivity.class); setResult(RESULT_OK, intent); startActivity(intent); } } new SaveNoteTask().execute(); } private void setSubTitleIndicatorColor() { GradientDrawable gradientDrawable = (GradientDrawable) viewSubTitleIndicator.getBackground(); gradientDrawable.setColor(Color.parseColor(selectedNoteColor)); } @SuppressLint("QueryPermissionsNeeded") private void selectImage() { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); if (intent.resolveActivity(getPackageManager()) != null) { startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_STORAGE_PERMISSION && grantResults.length > 0) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { selectImage(); } else { showToastRed("Permission Denied"); } } if (requestCode == REQUEST_CODE_ASK_PERMISSIONS) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { try { createPDF(); } catch (Exception e) { e.printStackTrace(); } } else { showToastRed("Write_External Permission Denied"); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_SELECT_IMAGE && resultCode == RESULT_OK) { if (data != null) { selectImageUri = data.getData(); if (selectImageUri != null) { try { inputStream = getContentResolver().openInputStream(selectImageUri); bitmap = BitmapFactory.decodeStream(inputStream); imageNote.setImageBitmap(bitmap); imageNote.setVisibility(View.VISIBLE); findViewById(R.id.imageMoreImage).setVisibility(View.VISIBLE); selectedImagePath = getPathFromUri(selectImageUri); } catch (Exception exception) { showToastRed("Error occurred, Please try again"); } } } } else if (requestCode == REQ_CODE_TITLE && resultCode == RESULT_OK && null != data) { ArrayList<String> result = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); String i = result.get(0); if (i.equals("Next") || i.equals("next")) { inputNoteTitle.append("\n"); } else { inputNoteTitle.append(result.get(0)); } // inputSearch.append(result.toString().replaceAll("\\[", "").replaceAll("]", "")); } else if (requestCode == REQ_CODE_SUB_TITLE && resultCode == RESULT_OK && null != data) { ArrayList<String> result = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); String i = result.get(0); if (i.equals("Next") || i.equals("next")) { inputNoteSubTitle.append("\n"); } else { inputNoteSubTitle.append(result.get(0)); } // inputSearch.append(result.toString().replaceAll("\\[", "").replaceAll("]", "")); } else if (requestCode == REQ_CODE_NOTE && resultCode == RESULT_OK && null != data) { ArrayList<String> result = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); String i = result.get(0); if (i.equals("Next") || i.equals("next")) { inputNoteText.append("\n"); } else { inputNoteText.append(result.get(0)); } // inputSearch.append(result.toString().replaceAll("\\[", "").replaceAll("]", "")); } else if (requestCode == CAMERA_REQUEST && null != data) { selectImageUri = data.getData(); Bitmap photo = (Bitmap) data.getExtras().get("data"); imageNote.setVisibility(View.VISIBLE); findViewById(R.id.imageMoreImage).setVisibility(View.VISIBLE); imageNote.setImageBitmap(photo); selectedImagePath = getPathFromUri(selectImageUri); } else if (requestCode == 12 && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri uri = data.getData(); String uriString = uri.toString(); File myFile = new File(uriString); String path = myFile.getAbsolutePath(); String displayName = null; TextView textView; textView = findViewById(R.id.text); if (uriString.startsWith("content://")) { Cursor cursor = null; try { cursor = getApplicationContext().getContentResolver().query(uri, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); textView.setText(displayName); } } finally { cursor.close(); } } else if (uriString.startsWith("file://")) { displayName = myFile.getName(); textView.setText(displayName); } } } private String getPathFromUri(Uri contentUri) { String filePath; Cursor cursor = getContentResolver().query(contentUri, null, null, null, null); if (cursor == null) { filePath = contentUri.getPath(); } else { cursor.moveToFirst(); int index = cursor.getColumnIndex("_data"); filePath = cursor.getString(index); cursor.close(); } return filePath; } private void showAddURLDialog() { if (dialogAddURL == null) { AlertDialog.Builder builder = new AlertDialog.Builder(CreateNoteActivity.this); View view = LayoutInflater.from(this).inflate( R.layout.layout_add_url, (ViewGroup) findViewById(R.id.layoutAddUrlContainer) ); builder.setView(view); dialogAddURL = builder.create(); if (dialogAddURL.getWindow() != null) { dialogAddURL.getWindow().setBackgroundDrawable(new ColorDrawable(0)); } final EditText inputURL = view.findViewById(R.id.inputURL); inputURL.requestFocus(); view.findViewById(R.id.textAdd).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (inputURL.getText().toString().trim().isEmpty()) { showToastRed("Enter URL"); } else if (!Patterns.WEB_URL.matcher(inputURL.getText().toString()).matches()) { showToastRed("Enter Valid URL"); } else { layoutWebURL.setVisibility(View.VISIBLE); MoreUrl.setVisibility(View.VISIBLE); textWebURL.setText(inputURL.getText().toString()); dialogAddURL.dismiss(); } } }); view.findViewById(R.id.textCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialogAddURL.dismiss(); } }); } dialogAddURL.show(); } private void showAddLabelDialog() { if (dialogLabelURL == null) { AlertDialog.Builder builder = new AlertDialog.Builder(CreateNoteActivity.this); View view = LayoutInflater.from(this).inflate( R.layout.layout_add_label, (ViewGroup) findViewById(R.id.layoutAddUrlContainer) ); builder.setView(view); dialogLabelURL = builder.create(); if (dialogLabelURL.getWindow() != null) { dialogLabelURL.getWindow().setBackgroundDrawable(new ColorDrawable(0)); } final EditText inputLabel = view.findViewById(R.id.inputLabel); inputLabel.requestFocus(); view.findViewById(R.id.textAdd).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (inputLabel.getText().toString().trim().isEmpty()) { showToastRed("Enter Label"); } else { if (labels.getText().toString().equals("No Label")) { labels.setText(inputLabel.getText().toString()); } else { String string = labels.getText().toString(); labels.setText(string + " , " + inputLabel.getText().toString()); } dialogLabelURL.dismiss(); inputLabel.setText(""); } } }); view.findViewById(R.id.textCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialogLabelURL.dismiss(); } }); } dialogLabelURL.show(); } private void setViewOrUpdateNote() { if (alreadyAvailableNote.getPasswordState().equals("Yes")) { imageLock.setVisibility(View.GONE); imageUnLock.setVisibility(View.VISIBLE); if (dialogResetNote == null) { AlertDialog.Builder builder = new AlertDialog.Builder(CreateNoteActivity.this); View view = LayoutInflater.from(this).inflate( R.layout.enter_note_password, (ViewGroup) findViewById(R.id.layoutPasswordNoteContainer) ); builder.setView(view); dialogResetNote = builder.create(); if (dialogResetNote.getWindow() != null) { dialogResetNote.getWindow().setBackgroundDrawable(new ColorDrawable(0)); } EditText editText = view.findViewById(R.id.textPassword); editText.setSelection(editText.getText().length()); editText.requestFocus(); editText.getShowSoftInputOnFocus(); view.findViewById(R.id.textSubmitNote).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (editText.getText().toString().equals("123456")) { inputNoteTitle.setText(alreadyAvailableNote.getTitle()); inputNoteSubTitle.setText(alreadyAvailableNote.getSubtitle()); inputNoteText.setText(alreadyAvailableNote.getNoteText()); textDateTime.setText(alreadyAvailableNote.getDateTime()); labels.setText(alreadyAvailableNote.getNoteLabel()); folderName = alreadyAvailableNote.getFolder(); // Parent.setBackgroundColor(Integer.parseInt(alreadyAvailableNote.getBackgroundColor())); File path = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName); if (!path.exists()) { try { createFolder(); } catch (Exception e) { e.printStackTrace(); } } File docsFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName + File.separator + "ReadMe.pdf"); docsFolder.delete(); if (alreadyAvailableNote.getImagePath() != null && !alreadyAvailableNote.getImagePath().trim().isEmpty()) { imageNote.setImageBitmap(BitmapFactory.decodeFile(alreadyAvailableNote.getImagePath())); imageNote.setVisibility(View.VISIBLE); findViewById(R.id.imageMoreImage).setVisibility(View.VISIBLE); selectedImagePath = alreadyAvailableNote.getImagePath(); } else { imageNote.setVisibility(View.GONE); MoreImage.setVisibility(View.GONE); imageNote.setImageBitmap(null); } if (alreadyAvailableNote.getWebLink() != null && !alreadyAvailableNote.getWebLink().trim().isEmpty()) { textWebURL.setText(alreadyAvailableNote.getWebLink()); layoutWebURL.setVisibility(View.VISIBLE); } else { layoutWebURL.setVisibility(View.GONE); MoreUrl.setVisibility(View.GONE); textWebURL.setText(""); } dialogResetNote.dismiss(); } else { showToastRed("Please enter correct password"); } } }); view.findViewById(R.id.textReset).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } dialogResetNote.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialogResetNote.show(); } else { imageLock.setVisibility(View.VISIBLE); imageUnLock.setVisibility(View.GONE); inputNoteTitle.setText(alreadyAvailableNote.getTitle()); inputNoteSubTitle.setText(alreadyAvailableNote.getSubtitle()); inputNoteText.setText(alreadyAvailableNote.getNoteText()); textDateTime.setText(alreadyAvailableNote.getDateTime()); labels.setText(alreadyAvailableNote.getNoteLabel()); folderName = alreadyAvailableNote.getFolder(); File path = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName); if (!path.exists()) { try { createFolder(); } catch (Exception e) { e.printStackTrace(); } } File docsFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName + File.separator + "ReadMe.pdf"); docsFolder.delete(); // Parent.setBackgroundColor(Integer.parseInt(alreadyAvailableNote.getBackgroundColor())); if (alreadyAvailableNote.getImagePath() != null && !alreadyAvailableNote.getImagePath().trim().isEmpty()) { imageNote.setImageBitmap(BitmapFactory.decodeFile(alreadyAvailableNote.getImagePath())); imageNote.setVisibility(View.VISIBLE); findViewById(R.id.imageMoreImage).setVisibility(View.VISIBLE); selectedImagePath = alreadyAvailableNote.getImagePath(); } else { imageNote.setVisibility(View.GONE); MoreImage.setVisibility(View.GONE); imageNote.setImageBitmap(null); } if (alreadyAvailableNote.getWebLink() != null && !alreadyAvailableNote.getWebLink().trim().isEmpty()) { textWebURL.setText(alreadyAvailableNote.getWebLink()); layoutWebURL.setVisibility(View.VISIBLE); } else { layoutWebURL.setVisibility(View.GONE); MoreUrl.setVisibility(View.GONE); textWebURL.setText(""); } } // if (alreadyAvailableNote.getFolder() != null && !alreadyAvailableNote.getFolder().trim().isEmpty()) { // recyclerView.setVisibility(View.VISIBLE); // } else { // recyclerView.setVisibility(View.GONE); // } } private void createPDF() throws Exception { int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) { showMessage(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } }); return; } requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } } else { showToast("PDF copy has been saved to this device successfully"); File docsFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + "PDF Files"); boolean success = true; if (!docsFolder.exists()) { success = docsFolder.mkdirs(); } if (success) { String randCode = new SimpleDateFormat("dd MM yyyy HH:mm:ss a", Locale.getDefault()).format(new Date()); randCode = randCode.replaceAll(":", ""); randCode = randCode.replaceAll(" ", ""); pdfFile = new File(docsFolder.getAbsolutePath(), randCode + ".pdf"); OutputStream outputStream = new FileOutputStream(pdfFile); Document document = new Document(); PdfWriter.getInstance(document, outputStream); document.open(); Font f = new Font(Font.FontFamily.TIMES_ROMAN, 18f, Font.BOLD, BaseColor.RED); document.add(new Paragraph("Title", f)); Font f1 = new Font(Font.FontFamily.TIMES_ROMAN, 15f, Font.NORMAL, BaseColor.BLACK); document.add(new Paragraph("\n\n" + inputNoteTitle.getText().toString(), f1)); Font f2 = new Font(Font.FontFamily.TIMES_ROMAN, 18f, Font.BOLD, BaseColor.RED); document.add(new Paragraph("\n\n" + "Note", f2)); Font f3 = new Font(Font.FontFamily.TIMES_ROMAN, 15f, Font.BOLD, BaseColor.BLACK); document.add(new Paragraph("\n\n" + inputNoteText.getText().toString(), f3)); document.close(); } else { showToastRed("Error"); } } } private void showMessage(DialogInterface.OnClickListener onClickListener) { new AlertDialog.Builder(this) .setMessage("You need to allow to Storage") .setNegativeButton("Cancel", null) .setPositiveButton("OK", onClickListener) .create() .show(); } @SuppressLint("RestrictedApi") public void buttonBold(View view) { PopupMenu popup = new PopupMenu(getApplicationContext(), view); popup.getMenuInflater().inflate(R.menu.text_alignment, popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem menu_item) { switch (menu_item.getItemId()) { case R.id.Center: Toast.makeText(CreateNoteActivity.this, "Center", Toast.LENGTH_SHORT).show(); break; case R.id.Right: break; } return true; } }); MenuPopupHelper menuHelper = new MenuPopupHelper(getApplicationContext(), (MenuBuilder) popup.getMenu(), view); menuHelper.setForceShowIcon(true); menuHelper.setGravity(Gravity.END); menuHelper.show(); } public void onPause() { if (TTS != null) { TTS.stop(); TTS.shutdown(); } super.onPause(); } @Override public void onBackPressed() { if (i == 1) { deleteRecursive(new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName)); Intent i = new Intent(CreateNoteActivity.this, MainActivity.class); startActivity(i); } else { Intent i = new Intent(CreateNoteActivity.this, MainActivity.class); startActivity(i); } } private void displayPdf() { RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(CreateNoteActivity.this, RecyclerView.VERTICAL, false)); List<File> pdfList = new ArrayList<>(findPdf(new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName))); FileAdapter fileAdapter = new FileAdapter(this, pdfList, this); recyclerView.setAdapter(fileAdapter); } public ArrayList<File> findPdf(File file) { ArrayList<File> arrayList = new ArrayList<>(); if (file.exists()) { File[] files = file.listFiles(); if (files != null) { for (File singleFile : files) { if (singleFile.isDirectory() || singleFile.isHidden()) { arrayList.addAll(findPdf(singleFile)); } else { if (singleFile.getName().contains(".")) { arrayList.add(singleFile); } } } } } return arrayList; } private void displayCustomPdf() { RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(CreateNoteActivity.this, RecyclerView.VERTICAL, false)); List<File> pdfList = new ArrayList<>(findCustomPdf(new File(Environment.getExternalStorageDirectory() + File.separator + "Remarques" + File.separator + ".Important File" + File.separator + ".R " + folderName))); FileAdapter fileAdapter = new FileAdapter(this, pdfList, this); recyclerView.setAdapter(fileAdapter); } public ArrayList<File> findCustomPdf(File file) { ArrayList<File> arrayList = new ArrayList<>(); if (file.exists()) { File[] files = file.listFiles(); if (files != null) { for (File singleFile : files) { if (singleFile.isDirectory() || singleFile.isHidden()) { arrayList.addAll(findCustomPdf(singleFile)); } else { switch (custom) { case "file": if (singleFile.getName().endsWith(".pdf") || singleFile.getName().endsWith(".docx") || singleFile.getName().endsWith(".pptx") || singleFile.getName().endsWith(".xlsx") || singleFile.getName().endsWith(".zip") || singleFile.getName().endsWith(".txt")) { arrayList.add(singleFile); } else { showToastRed("No Files"); } break; case "video": if (singleFile.getName().endsWith(".mp4")) { arrayList.add(singleFile); } else { showToastRed("No Videos"); } break; case "audio": if (singleFile.getName().endsWith(".amr")) { arrayList.add(singleFile); } else { showToastRed("No Audios"); } break; case "music": if (singleFile.getName().endsWith(".mp3")) { arrayList.add(singleFile); } else { showToastRed("No Musics"); } break; case "pictures": if (singleFile.getName().endsWith(".jpg") || singleFile.getName().endsWith(".jpeg") || singleFile.getName().endsWith(".png")) { arrayList.add(singleFile); } else { showToastRed("No Pictures"); } break; } } } } else { showToastRed("Nothing to display"); } } else { showToastRed("Files not available"); } return arrayList; } @Override public void onFileSelected(File file) { Uri uri = FileProvider.getUriForFile(this, CreateNoteActivity.this.getApplicationContext().getPackageName() + ".provider", file); Intent pdfIntent = new Intent(Intent.ACTION_VIEW); if (file.getName().endsWith(".pdf")) { pdfIntent.setDataAndType(uri, "application/pdf"); } else if (file.getName().endsWith(".mp4") || file.getName().endsWith(".amr") || file.getName().endsWith(".mp3")) { pdfIntent.setDataAndType(uri, "audio/x-wav"); } pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); try { startActivity(pdfIntent); } catch (ActivityNotFoundException e) { showToastRed("No Applications found to open this format file. You can download relevant application to view this file format"); } } public void deleteRecursive(File file) { if (file.isDirectory()) for (File child : Objects.requireNonNull(file.listFiles())) { child.delete(); deleteRecursive(child); } file.delete(); } @Override protected void onResume() { super.onResume(); viewHolder = "CreateNote"; displayPdf(); } void showToast(String message) { Toast toast = new Toast(CreateNoteActivity.this); @SuppressLint("InflateParams") View view = LayoutInflater.from(CreateNoteActivity.this) .inflate(R.layout.toast_green, null); TextView tvMessage = view.findViewById(R.id.tvMessage); tvMessage.setText(message); toast.setView(view); toast.show(); } void showToastRed(String message) { Toast toast = new Toast(CreateNoteActivity.this); @SuppressLint("InflateParams") View view = LayoutInflater.from(CreateNoteActivity.this) .inflate(R.layout.toast_layout, null); TextView tvMessage = view.findViewById(R.id.Message); tvMessage.setText(message); toast.setView(view); toast.show(); } }
3e117214dcab6391832a1cfc12b30b9ee6728ea7
1,954
java
Java
src/main/java/org/takes/misc/EnglishLowerCase.java
alxn/takes
341fb1b89833de6838cc2f535ffff81aa48f8351
[ "MIT" ]
1
2018-03-20T00:48:24.000Z
2018-03-20T00:48:24.000Z
src/main/java/org/takes/misc/EnglishLowerCase.java
alxn/takes
341fb1b89833de6838cc2f535ffff81aa48f8351
[ "MIT" ]
null
null
null
src/main/java/org/takes/misc/EnglishLowerCase.java
alxn/takes
341fb1b89833de6838cc2f535ffff81aa48f8351
[ "MIT" ]
null
null
null
29.651515
80
0.69443
7,364
/** * The MIT License (MIT) * * Copyright (c) 2014-2018 Yegor Bugayenko * * 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 NON-INFRINGEMENT. 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 org.takes.misc; import java.util.Locale; /** * English lower case string representation. * @author Dali Freire (anpch@example.com) * @version $Id: 3e117214dcab6391832a1cfc12b30b9ee6728ea7 $ * @since 0.33 */ public final class EnglishLowerCase { /** * String value. */ private final String value; /** * Ctor. * @param text Text value */ public EnglishLowerCase(final CharSequence text) { this(text.toString()); } /** * Ctor. * @param string String value */ public EnglishLowerCase(final String string) { this.value = string; } /** * Returns string value. * @return String value */ public String string() { return this.value.toLowerCase(Locale.ENGLISH); } }
3e1172f44b2372dc23adc36beb523ced63155045
1,732
java
Java
src/main/java/com/gti/solicita/config/WebSecurityConfig.java
gti-muriae/so-licita
10207e6d94d5aa383d22ae2a29c1aec643a06681
[ "MIT" ]
null
null
null
src/main/java/com/gti/solicita/config/WebSecurityConfig.java
gti-muriae/so-licita
10207e6d94d5aa383d22ae2a29c1aec643a06681
[ "MIT" ]
null
null
null
src/main/java/com/gti/solicita/config/WebSecurityConfig.java
gti-muriae/so-licita
10207e6d94d5aa383d22ae2a29c1aec643a06681
[ "MIT" ]
null
null
null
43.3
109
0.825058
7,365
package com.gti.solicita.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private final BCryptPasswordEncoder passwordEncoder; private final UserDetailsService userDetailsService; public WebSecurityConfig(BCryptPasswordEncoder passwordEncoder, UserDetailsService userDetailsService) { this.passwordEncoder = passwordEncoder; this.userDetailsService = userDetailsService; } @Override protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); } @Override public void configure(WebSecurity webSecurity) throws Exception { webSecurity.ignoring().antMatchers("/actuator/**"); } @Override @Bean protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } }
3e1174059d1441f0dc3cd7a3be50dc4cc534b1bd
20,714
java
Java
jsettlers.logic/src/main/java/jsettlers/ai/army/ConfigurableGeneral.java
numsim1415/settlers-remake
33a066473001a727944872c1c16a7bdd50d2137e
[ "MIT" ]
46
2020-05-12T22:36:19.000Z
2022-03-08T21:52:24.000Z
jsettlers.logic/src/main/java/jsettlers/ai/army/ConfigurableGeneral.java
numsim1415/settlers-remake
33a066473001a727944872c1c16a7bdd50d2137e
[ "MIT" ]
32
2020-08-29T18:57:50.000Z
2022-03-28T12:04:31.000Z
jsettlers.logic/src/main/java/jsettlers/ai/army/ConfigurableGeneral.java
numsim1415/settlers-remake
33a066473001a727944872c1c16a7bdd50d2137e
[ "MIT" ]
14
2020-03-13T13:47:42.000Z
2022-03-30T07:06:38.000Z
46.236607
200
0.789804
7,366
/******************************************************************************* * Copyright (c) 2016 - 2018 * * 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 jsettlers.ai.army; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import jsettlers.ai.highlevel.AiStatistics; import jsettlers.common.action.SetMaterialProductionAction.EMaterialProductionType; import jsettlers.common.ai.EPlayerType; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.material.EMaterialType; import jsettlers.common.movable.EMovableType; import jsettlers.common.movable.ESoldierType; import jsettlers.common.player.IPlayer; import jsettlers.common.position.ShortPoint2D; import jsettlers.input.tasks.ChangeTowerSoldiersGuiTask; import jsettlers.common.action.EMoveToType; import jsettlers.input.tasks.MoveToGuiTask; import jsettlers.input.tasks.SetMaterialProductionGuiTask; import jsettlers.input.tasks.UpgradeSoldiersGuiTask; import jsettlers.logic.buildings.military.occupying.OccupyingBuilding; import jsettlers.logic.constants.MatchConstants; import jsettlers.logic.map.grid.movable.MovableGrid; import jsettlers.logic.movable.MovableManager; import jsettlers.logic.movable.interfaces.ILogicMovable; import jsettlers.logic.player.Player; import jsettlers.network.client.interfaces.ITaskScheduler; import static java8.util.stream.StreamSupport.stream; /** * This general is named winner because his attacks and defence should be very hard for human enemies. This should be realized by creating locally superiority. (You can kill 200 BOWMEN with just 100 * BOWMEN if you fight 100 vs 20 in loops. This general should lay the focus on some SWORDSMEN to occupy own towers, 20 spearmen to defeat rushes and the rest only BOWMEN because in mass this is the * strongest military unit. It upgrades BOWMEN first because this is the main unit and the 20 defeating spearmen defeats with lv1 as well. This general should store bows until level3 is reached to get * as many level3 BOWMEN as posibble. TODO: store bows until level3 is reached TODO: group SOLDIERS in direction of enemy groups to defeat them TODO: group SOLDIERS in direction of enemy groups to * attack them * * @author codingberlin */ public class ConfigurableGeneral implements ArmyGeneral { private static float[] ATTACKER_COUNT_FACTOR_BY_PLAYER_TYPE = { 1.1F, 1F, 0.9F, 0.8F, 0F }; private static final byte MIN_ATTACKER_COUNT = 20; private static final byte MIN_SWORDSMEN_COUNT = 10; private static final byte MIN_PIKEMEN_COUNT = 20; private static final int BOWMEN_COUNT_OF_KILLING_INFANTRY = 300; private static final EBuildingType[] MIN_BUILDING_REQUIREMENTS_FOR_ATTACK = { EBuildingType.COALMINE, EBuildingType.IRONMINE, EBuildingType.IRONMELT, EBuildingType.WEAPONSMITH, EBuildingType.BARRACK }; private static final ESoldierType[] SOLDIER_UPGRADE_ORDER = new ESoldierType[] { ESoldierType.BOWMAN, ESoldierType.PIKEMAN, ESoldierType.SWORDSMAN }; private static final float SOLDIERS_MIN_HEALTH = 0.6f; private static final float HEALING_DISTANCE_WEIGHT = -1; private static final float HEALING_USAGE_WEIGHT = -10; private static final float MAX_WOUNDED_RATIO_FOR_ATTACK = 0.5f; private final AiStatistics aiStatistics; private final Player player; private final ITaskScheduler taskScheduler; private final MovableGrid movableGrid; private final float attackerCountFactor; private final float healPropFactor; private final Set<Integer> woundedSoldiers = new HashSet<>(); private final Map<ILogicMovable, ShortPoint2D> assignedPatients = new HashMap<>(); private final Map<ShortPoint2D, Integer> usedHospitalCapacity = new HashMap<>(); private final int hospitalWorkRadius; /** * * @param healPropFactor * The fraction of wounded soldiers that get send to the hospital */ public ConfigurableGeneral(AiStatistics aiStatistics, Player player, MovableGrid movableGrid, ITaskScheduler taskScheduler, EPlayerType playerType, float healPropFactor) { this.aiStatistics = aiStatistics; this.player = player; this.taskScheduler = taskScheduler; this.movableGrid = movableGrid; this.attackerCountFactor = ATTACKER_COUNT_FACTOR_BY_PLAYER_TYPE[playerType.ordinal()]; this.healPropFactor = healPropFactor; // setup woundedSoldiers doHealTroops(false); hospitalWorkRadius = EBuildingType.HOSPITAL.getVariant(player.getCivilisation()).getWorkRadius(); } @Override public void commandTroops(Set<Integer> soldiersWithOrders) { soldiersWithOrders.addAll(woundedSoldiers); ensureAllTowersFullyMounted(); SoldierPositions soldierPositions = calculateSituation(player.playerId); if (aiStatistics.getEnemiesInTownOf(player.playerId).size() > 0) { defend(soldierPositions, soldiersWithOrders); } else if (existsAliveEnemy()) { IPlayer weakestEnemy = getWeakestEnemy(); SoldierPositions enemySoldierPositions = calculateSituation(weakestEnemy.getPlayerId()); boolean infantryWouldDie = wouldInfantryDie(enemySoldierPositions); if (woundedSoldiers.size()/(float)soldierPositions.getSoldiersCount() <= MAX_WOUNDED_RATIO_FOR_ATTACK && attackIsPossible(soldierPositions, enemySoldierPositions, infantryWouldDie)) { attack(soldierPositions, infantryWouldDie, soldiersWithOrders); } } } private void ensureAllTowersFullyMounted() { stream(aiStatistics.getBuildingPositionsOfTypesForPlayer(EBuildingType.MILITARY_BUILDINGS, player.playerId)) .map(aiStatistics::getBuildingAt) .filter(building -> building instanceof OccupyingBuilding) .map(building -> (OccupyingBuilding) building) .filter(building -> !building.isSetToBeFullyOccupied()) .forEach(building -> taskScheduler.scheduleTask(new ChangeTowerSoldiersGuiTask(player.playerId, building.getPosition(), ChangeTowerSoldiersGuiTask.EChangeTowerSoldierTaskType.FULL, null))); } private boolean attackIsPossible(SoldierPositions soldierPositions, SoldierPositions enemySoldierPositions, boolean infantryWouldDie) { for (EBuildingType requiredType : MIN_BUILDING_REQUIREMENTS_FOR_ATTACK) { if (aiStatistics.getNumberOfBuildingTypeForPlayer(requiredType, player.playerId) < 1) { return false; } } float combatStrength = player.getCombatStrengthInformation().getCombatStrength(false); float effectiveAttackerCount; if (infantryWouldDie) { effectiveAttackerCount = soldierPositions.bowmenPositions.size() * combatStrength; } else { effectiveAttackerCount = soldierPositions.getSoldiersCount() * combatStrength; } return effectiveAttackerCount >= MIN_ATTACKER_COUNT && effectiveAttackerCount * attackerCountFactor > enemySoldierPositions.getSoldiersCount(); } private boolean wouldInfantryDie(SoldierPositions enemySoldierPositions) { return enemySoldierPositions.bowmenPositions.size() > BOWMEN_COUNT_OF_KILLING_INFANTRY; } private boolean existsAliveEnemy() { return !aiStatistics.getAliveEnemiesOf(player).isEmpty(); } @Override public void levyUnits() { upgradeSoldiers(); int missingSwordsmenCount = Math.max(0, MIN_SWORDSMEN_COUNT - aiStatistics.getCountOfMovablesOfPlayer(player, EMovableType.SWORDSMEN)); int missingPikemenCount = Math.max(0, MIN_PIKEMEN_COUNT - aiStatistics.getCountOfMovablesOfPlayer(player, EMovableType.PIKEMEN)); int bowmenCount = aiStatistics.getCountOfMovablesOfPlayer(player, EMovableType.BOWMEN); if (missingSwordsmenCount > 0) { setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.SWORD, missingSwordsmenCount); setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.SPEAR, 0); setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.BOW, 0); setRatioOfMaterial(player.playerId, EMaterialType.SWORD, 0F); setRatioOfMaterial(player.playerId, EMaterialType.SPEAR, 1F); setRatioOfMaterial(player.playerId, EMaterialType.BOW, 0F); } else if (missingPikemenCount > 0) { setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.SWORD, 0); setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.SPEAR, missingPikemenCount); setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.BOW, 0); setRatioOfMaterial(player.playerId, EMaterialType.SWORD, 0F); setRatioOfMaterial(player.playerId, EMaterialType.SPEAR, 0.3F); setRatioOfMaterial(player.playerId, EMaterialType.BOW, 1F); } else if (bowmenCount * player.getCombatStrengthInformation().getCombatStrength(false) < BOWMEN_COUNT_OF_KILLING_INFANTRY) { setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.SWORD, 0); setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.SPEAR, 0); setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.BOW, 0); setRatioOfMaterial(player.playerId, EMaterialType.SWORD, 0F); setRatioOfMaterial(player.playerId, EMaterialType.SPEAR, 0.3F); setRatioOfMaterial(player.playerId, EMaterialType.BOW, 1F); } else { setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.SWORD, 0); setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.SPEAR, 0); setNumberOfFutureProducedMaterial(player.playerId, EMaterialType.BOW, 0); setRatioOfMaterial(player.playerId, EMaterialType.SWORD, 0F); setRatioOfMaterial(player.playerId, EMaterialType.SPEAR, 0F); setRatioOfMaterial(player.playerId, EMaterialType.BOW, 1F); } } private void setNumberOfFutureProducedMaterial(byte playerId, EMaterialType materialType, int numberToProduce) { if (aiStatistics.getMaterialProduction(playerId).getAbsoluteProductionRequest(materialType) != numberToProduce) { taskScheduler.scheduleTask(new SetMaterialProductionGuiTask(playerId, aiStatistics.getPositionOfPartition(playerId), materialType, EMaterialProductionType.SET_PRODUCTION, numberToProduce)); } } private void setRatioOfMaterial(byte playerId, EMaterialType materialType, float ratio) { if (aiStatistics.getMaterialProduction(playerId).getUserConfiguredRelativeRequestValue(materialType) != ratio) { taskScheduler.scheduleTask(new SetMaterialProductionGuiTask(playerId, aiStatistics.getPositionOfPartition(playerId), materialType, EMaterialProductionType.SET_RATIO, ratio)); } } private void upgradeSoldiers() { for (ESoldierType type : SOLDIER_UPGRADE_ORDER) { if (player.getMannaInformation().isUpgradePossible(type)) { taskScheduler.scheduleTask(new UpgradeSoldiersGuiTask(player.playerId, type)); } } } @Override public void healTroops() { doHealTroops(true); } private void doHealTroops(boolean commit) { woundedSoldiers.clear(); if(healPropFactor == 0) return; // this list is at most a couple of seconds old Set<ShortPoint2D> hospitals = aiStatistics.getActiveHospitalsForPlayer(player.playerId); if(hospitals.isEmpty()) return; Iterator<Map.Entry<ILogicMovable, ShortPoint2D>> woundedIter = assignedPatients.entrySet().iterator(); // remove dead and healed movables from the patients list // regenerate the usedHospitalCapacity // unassigned patients that are going to destroyed hospitals usedHospitalCapacity.clear(); hospitals.forEach(pt -> usedHospitalCapacity.put(pt, 0)); while(woundedIter.hasNext()) { Map.Entry<ILogicMovable, ShortPoint2D> next = woundedIter.next(); ShortPoint2D hospital = next.getValue(); if(!hospitals.contains(hospital)) { woundedIter.remove(); continue; } ILogicMovable movable = next.getKey(); if(!isWounded(movable) || !movable.isAlive()) { woundedIter.remove(); continue; } increaseHospitalUse(hospital); } // assign newly wounded soldiers to hospitals Map<ShortPoint2D, List<Integer>> newOrders = new HashMap<>(); hospitals.forEach(hospital -> newOrders.put(hospital, new ArrayList<>())); MovableManager.getAllMovables().stream() .filter(this::isWounded) .filter(mov -> mov.getPlayer().equals(player)) .filter(mov -> EMovableType.PLAYER_CONTROLLED_HUMAN_MOVABLE_TYPES .contains(mov.getMovableType())) // only wounded movables that we actually can heal should be considered .forEach(mov -> { ShortPoint2D assignedHospital = assignedPatients.get(mov); // not all wounded soldiers should be send if(assignedHospital != null || randomHealChance()) { if (assignedHospital == null) { assignedHospital = getBestHospital(mov, hospitals); increaseHospitalUse(assignedHospital); assignedPatients.put(mov, assignedHospital); } woundedSoldiers.add(mov.getID()); if(mov.getPosition().getOnGridDistTo(assignedHospital) >= hospitalWorkRadius) { newOrders.get(assignedHospital).add(mov.getID()); } } }); if(commit) { newOrders.entrySet().forEach(newOrder -> { sendTroopsToById(newOrder.getValue(), newOrder.getKey(), null, EMoveToType.FORCED); }); } } private boolean randomHealChance() { if(healPropFactor == 1) return true; return MatchConstants.aiRandom().nextFloat() >= 1-healPropFactor; } private boolean isWounded(ILogicMovable mov) { return mov.getHealth() <= SOLDIERS_MIN_HEALTH * mov.getMovableType().getHealth(); } private void increaseHospitalUse(ShortPoint2D hospital) { usedHospitalCapacity.compute(hospital, (pos, oldValue) -> oldValue+1); } private ShortPoint2D getBestHospital(ILogicMovable movable, Set<ShortPoint2D> hospitals) { float maxScore = Float.NEGATIVE_INFINITY; ShortPoint2D bestHospital = null; for (ShortPoint2D hospital : hospitals) { float localScore = getHospitalScore(hospital, movable.getPosition()); if (localScore > maxScore) { maxScore = localScore; bestHospital = hospital; } } return bestHospital; } private float getHospitalScore(ShortPoint2D hospital, ShortPoint2D from) { int distance = hospital.getOnGridDistTo(from); int usage = usedHospitalCapacity.get(hospital); float score = 0; score += distance * HEALING_DISTANCE_WEIGHT; score += usage * HEALING_USAGE_WEIGHT; return score; } private void defend(SoldierPositions soldierPositions, Set<Integer> soldiersWithOrders) { List<ShortPoint2D> allMyTroops = new Vector<>(); allMyTroops.addAll(soldierPositions.bowmenPositions); allMyTroops.addAll(soldierPositions.pikemenPositions); allMyTroops.addAll(soldierPositions.swordsmenPositions); sendTroopsTo(allMyTroops, aiStatistics.getEnemiesInTownOf(player.playerId).iterator().next(), soldiersWithOrders, EMoveToType.DEFAULT); } private void attack(SoldierPositions soldierPositions, boolean infantryWouldDie, Set<Integer> soldiersWithOrders) { IPlayer weakestEnemy = getWeakestEnemy(); ShortPoint2D targetDoor = getTargetEnemyDoorToAttack(weakestEnemy); if(targetDoor == null) return; if (infantryWouldDie) { sendTroopsTo(soldierPositions.bowmenPositions, targetDoor, soldiersWithOrders, EMoveToType.DEFAULT); } else { List<ShortPoint2D> soldiers = new ArrayList<>(soldierPositions.bowmenPositions.size() + soldierPositions.pikemenPositions.size() + soldierPositions.swordsmenPositions.size()); soldiers.addAll(soldierPositions.bowmenPositions); soldiers.addAll(soldierPositions.pikemenPositions); soldiers.addAll(soldierPositions.swordsmenPositions); sendTroopsTo(soldiers, targetDoor, soldiersWithOrders, EMoveToType.DEFAULT); } } private IPlayer getWeakestEnemy() { IPlayer weakestEnemyPlayer = null; int minAmountOfEnemyId = Integer.MAX_VALUE; for (IPlayer enemyPlayer : aiStatistics.getAliveEnemiesOf(player)) { int amountOfEnemyTroops = aiStatistics.getCountOfMovablesOfPlayer(enemyPlayer, EMovableType.SOLDIERS); if (amountOfEnemyTroops < minAmountOfEnemyId) { minAmountOfEnemyId = amountOfEnemyTroops; weakestEnemyPlayer = enemyPlayer; } } return weakestEnemyPlayer; } private void sendTroopsTo(List<ShortPoint2D> attackerPositions, ShortPoint2D target, Set<Integer> soldiersWithOrders, EMoveToType moveToType) { List<Integer> attackerIds = new Vector<>(attackerPositions.size()); for (ShortPoint2D attackerPosition : attackerPositions) { ILogicMovable movable = movableGrid.getMovableAt(attackerPosition.x, attackerPosition.y); if(movable == null) { System.err.printf("AI ERROR: Attacker at %d:%d does not exist!\n", attackerPosition.x, attackerPosition.y); continue; } attackerIds.add(movable.getID()); } sendTroopsToById(attackerIds, target, soldiersWithOrders, moveToType); } private void sendTroopsToById(List<Integer> attackerIds, ShortPoint2D target, Set<Integer> soldiersWithOrders, EMoveToType moveToType) { if(soldiersWithOrders != null) { attackerIds.removeAll(soldiersWithOrders); soldiersWithOrders.addAll(attackerIds); } taskScheduler.scheduleTask(new MoveToGuiTask(player.playerId, target, attackerIds, moveToType)); } private ShortPoint2D getTargetEnemyDoorToAttack(IPlayer enemyToAttack) { List<ShortPoint2D> myMilitaryBuildings = aiStatistics.getBuildingPositionsOfTypesForPlayer(EBuildingType.MILITARY_BUILDINGS, player.playerId); ShortPoint2D myBaseAveragePoint = AiStatistics.calculateAveragePointFromList(myMilitaryBuildings); List<ShortPoint2D> enemyMilitaryBuildings = aiStatistics.getBuildingPositionsOfTypesForPlayer(EBuildingType.MILITARY_BUILDINGS, enemyToAttack.getPlayerId()); Iterator<ShortPoint2D> iter = enemyMilitaryBuildings.iterator(); // ignore unfinished buildings while(iter.hasNext()) { if(!aiStatistics.getBuildingAt(iter.next()).isConstructionFinished()) iter.remove(); } ShortPoint2D nearestEnemyBuildingPosition = AiStatistics.detectNearestPointFromList(myBaseAveragePoint, enemyMilitaryBuildings); if(nearestEnemyBuildingPosition == null) return null; return aiStatistics.getBuildingAt(nearestEnemyBuildingPosition).getDoor(); } private SoldierPositions calculateSituation(byte playerId) { SoldierPositions soldierPositions = new SoldierPositions(); soldierPositions.swordsmenPositions.addAll(aiStatistics.getPositionsOfMovablesWithTypeForPlayer(playerId, EMovableType.SWORDSMAN_L1)); soldierPositions.swordsmenPositions.addAll(aiStatistics.getPositionsOfMovablesWithTypeForPlayer(playerId, EMovableType.SWORDSMAN_L2)); soldierPositions.swordsmenPositions.addAll(aiStatistics.getPositionsOfMovablesWithTypeForPlayer(playerId, EMovableType.SWORDSMAN_L3)); soldierPositions.bowmenPositions.addAll(aiStatistics.getPositionsOfMovablesWithTypeForPlayer(playerId, EMovableType.BOWMAN_L1)); soldierPositions.bowmenPositions.addAll(aiStatistics.getPositionsOfMovablesWithTypeForPlayer(playerId, EMovableType.BOWMAN_L2)); soldierPositions.bowmenPositions.addAll(aiStatistics.getPositionsOfMovablesWithTypeForPlayer(playerId, EMovableType.BOWMAN_L3)); soldierPositions.pikemenPositions.addAll(aiStatistics.getPositionsOfMovablesWithTypeForPlayer(playerId, EMovableType.PIKEMAN_L1)); soldierPositions.pikemenPositions.addAll(aiStatistics.getPositionsOfMovablesWithTypeForPlayer(playerId, EMovableType.PIKEMAN_L2)); soldierPositions.pikemenPositions.addAll(aiStatistics.getPositionsOfMovablesWithTypeForPlayer(playerId, EMovableType.PIKEMAN_L3)); return soldierPositions; } private static class SoldierPositions { private final List<ShortPoint2D> swordsmenPositions = new Vector<>(); private final List<ShortPoint2D> bowmenPositions = new Vector<>(); private final List<ShortPoint2D> pikemenPositions = new Vector<>(); int getSoldiersCount() { return swordsmenPositions.size() + bowmenPositions.size() + pikemenPositions.size(); } } @Override public String toString() { return this.getClass().getName(); } }
3e11740d00c1a81d7c78cdbb954d420f753a6ecc
3,011
java
Java
algoritmos-ed2/huffmancecilia/HuffmanCecilia.java
ceciliassis/graduate_ufu
7d3d51f6b9679b023e703f0d5b98fb6081f02017
[ "MIT" ]
null
null
null
algoritmos-ed2/huffmancecilia/HuffmanCecilia.java
ceciliassis/graduate_ufu
7d3d51f6b9679b023e703f0d5b98fb6081f02017
[ "MIT" ]
null
null
null
algoritmos-ed2/huffmancecilia/HuffmanCecilia.java
ceciliassis/graduate_ufu
7d3d51f6b9679b023e703f0d5b98fb6081f02017
[ "MIT" ]
null
null
null
27.126126
111
0.479907
7,367
package huffmancecilia; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * * @author Cecília Assis */ public class HuffmanCecilia { static ArrayList <NoTab> tabel = new ArrayList<>(); public static void main(String[] args) { ArrayList <No> lista = new ArrayList<>(); //huffmancecilia lista.add(new No('e',2, null, null)); lista.add(new No('s',2, null, null)); lista.add(new No(' ',2, null, null)); lista.add(new No('b',3, null, null)); lista.add(new No('o',3, null, null)); lista.add(new No('m',3, null, null)); codifica(lista); criaTabela(lista); decodifica("111 00 01 110 100 101 101 100 110 111 00 01 111 00 01"); } private static void ordenaPorNumero(ArrayList<No> lista) { Collections.sort(lista, new Comparator<No>() { @Override public int compare(No o1, No o2) { return o1.getPesoLetra().compareTo(o2.getPesoLetra()); } }); } //VERIFICAR ESSA PARTE, ORDENAR NA MAO PARA VER private static void codifica(ArrayList<No> lista){ No esq ; No dir ; while (lista.size()>1){ ordenaPorNumero(lista); // VERIFICAR, com o slide dela esq = lista.get(0); dir = lista.get(1); No novo = new No('#',esq.getPesoLetra()+dir.getPesoLetra()); //não da pra passar um caracter vazio novo.setEsquerdo(esq); novo.setDireito(dir); lista.add(novo); lista.remove(esq); lista.remove(dir); } } private static void criaTabela(ArrayList<No> lista){ for (No letra : lista) percorreArvore(letra, new String()); } private static void percorreArvore(No aux, String s){ if(aux.getDireito()==null && aux.getEsquerdo()==null){ System.out.println("Letra: " + aux.getLetra()); System.out.println("Código: " + s); tabel.add(new NoTab(aux.getLetra(),s)); } else{ percorreArvore(aux.getEsquerdo(),s+"0"); System.out.println(); percorreArvore(aux.getDireito(), s+"1"); } } private static void decodifica(String word){ System.out.println("\n----- Decodificando ---- \n"); String[] aux1 = word.split(" "); for (String token: aux1){ for (NoTab aux : tabel){ if (aux.getCode().equals(token)) System.out.print(aux.getLetra()); } } System.out.println("\n"); } }
3e1174c9bbe7904235acf7f71eb3820535b7a949
1,614
java
Java
MCA/.extra/DS using java/custom/LinkedList.java
muhammadmuzzammil1998/CollegeStuff
618cec9ebfbfd29a2d1e5a182b90cfb36b38a906
[ "MIT" ]
3
2018-03-13T12:34:51.000Z
2018-10-02T18:54:22.000Z
MCA/.extra/DS using java/custom/LinkedList.java
muhammadmuzzammil1998/CollegeStuff
618cec9ebfbfd29a2d1e5a182b90cfb36b38a906
[ "MIT" ]
null
null
null
MCA/.extra/DS using java/custom/LinkedList.java
muhammadmuzzammil1998/CollegeStuff
618cec9ebfbfd29a2d1e5a182b90cfb36b38a906
[ "MIT" ]
null
null
null
17.170213
44
0.576828
7,368
package custom; public class LinkedList { class Node { int data; Node next; Node(int n) { data = n; next = null; } } Node head; public void insert(int data) { if (head == null) { head = new Node(data); return; } Node current = head; while (current.next != null) current = current.next; current.next = new Node(data); } public void delete(int data) { if (head == null) return; if (head.data == data) { head = head.next; return; } Node current = head; while (current.next != null) { if (current.next.data == data) { current.next = current.next.next; return; } current = current.next; } } public void sort() { Node current = head; while (current.next != null) { Node ncurrent = current.next; while (ncurrent != null) { if (ncurrent.data < current.data) { int temp = current.data; current.data = ncurrent.data; ncurrent.data = temp; } ncurrent = ncurrent.next; } current = current.next; } } public int search(int data) { Node current = head; int index = 0; boolean found = false; while (current != null) { index++; if (current.data == data) { found = true; break; } current = current.next; } return found ? index : -1; } @Override public String toString() { String out = ""; Node current = head; while (current != null) { out += current.data + " -> "; current = current.next; } out += "NULL"; return out; } public void populate(int lim) { for (int i = 0; i < lim; i++) { this.insert((int) (Math.random() * 100)); } } }
3e11751b5afb288ea9e5eac354dadb7da12a0af1
1,746
java
Java
feed-aggregator/src/main/java/de/falconit/microservices/feeds/service/FeedInitializer.java
Philipp-Borchert-ISH/microservices
abda9fbf7c872fae0d12d4b99c136a384705faf0
[ "Apache-2.0" ]
null
null
null
feed-aggregator/src/main/java/de/falconit/microservices/feeds/service/FeedInitializer.java
Philipp-Borchert-ISH/microservices
abda9fbf7c872fae0d12d4b99c136a384705faf0
[ "Apache-2.0" ]
null
null
null
feed-aggregator/src/main/java/de/falconit/microservices/feeds/service/FeedInitializer.java
Philipp-Borchert-ISH/microservices
abda9fbf7c872fae0d12d4b99c136a384705faf0
[ "Apache-2.0" ]
null
null
null
23.594595
68
0.592211
7,369
package de.falconit.microservices.feeds.service; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.Schedule; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.inject.Inject; import org.jboss.logging.Logger; import org.wildfly.swarm.spi.api.config.Resolver; import org.wildfly.swarm.spi.runtime.annotations.ConfigurationValue; @Startup @Singleton public class FeedInitializer { @Inject @ConfigurationValue("feeds") private Resolver<String> feedResolver; @Inject private Logger log; @Inject private FeedService feedService; @SuppressWarnings({ "rawtypes", "unchecked" }) @PostConstruct public void loadFeeds() { if (!feedResolver.hasValue()) { log.warn("no feeds found"); } Resolver<List> as = feedResolver.as(List.class); List<String> feeds = as.getValue(); for (String feedURL : feeds) { if (feedService.getFeedByURL(feedURL) != null) { log.infov("Feed exists: {0}", feedURL); continue; } URL feed; try { feed = new URL(feedURL); } catch (MalformedURLException e) { log.error("issue with feed url", e); continue; } log.infov("Adding new feed by URL: {0}", feedURL); feedService.addFeedByURL(feed); } } @Schedule(minute = "*/5", second="0", hour="*", dayOfMonth="*") public void refreshFeeds() { log.info("refreshing feeds"); feedService.updateAllFeeds(); } }
3e1175358d6d9d20b17f07e3e7dac67ffc7d86bc
4,746
java
Java
src/main/java/frc/robot/commands/DriverAssist.java
frc-862/Gemini2019
488f0e9ef2f1d5357add2c947400ea6f2b49aea9
[ "MIT" ]
2
2019-03-15T23:42:26.000Z
2019-04-22T23:43:41.000Z
src/main/java/frc/robot/commands/DriverAssist.java
frc-862/Gemini2019
488f0e9ef2f1d5357add2c947400ea6f2b49aea9
[ "MIT" ]
18
2019-01-12T13:34:59.000Z
2019-02-12T01:03:03.000Z
src/main/java/frc/robot/commands/DriverAssist.java
frc-862/Gemini2019
488f0e9ef2f1d5357add2c947400ea6f2b49aea9
[ "MIT" ]
1
2019-10-28T22:36:08.000Z
2019-10-28T22:36:08.000Z
32.067568
86
0.563843
7,370
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import frc.lightning.commands.StatefulCommand; import frc.lightning.logging.CommandLogger; import frc.robot.Constants; import frc.robot.Robot; public class DriverAssist extends StatefulCommand { // private CommandLogger logger = new CommandLogger("DriverAssist"); enum States { VISION_AQUIRE, VISION_DRIVE, VISION_CLOSING, LINE_FOLLOW, DONE } private double gain; double kpp = .188; double kP = Constants.velocityMultiplier * kpp; double kD = .0; double minTurnPower = 1; double onTargetEpsilon = 0.1; // scaled 0..1 double turnP = .475; //linefollow double turningVelocity = .5;//4 double straightVelocity = 4 ;//1 double turnI = 0.001; double turnD = .5; double prevError = 0; double errorAcc = 0; private double turn; private double velocity; public DriverAssist() { super(States.VISION_AQUIRE); requires(Robot.drivetrain); } @Override protected void initialize() { setState(States.VISION_AQUIRE); } public void visionAquire() { if (Robot.core.timeOnLine() > 0.254) { setState(States.LINE_FOLLOW); } else if (Robot.simpleVision.simpleTargetFound()) { setState(States.VISION_DRIVE); } } public void visionDrive() { if (Robot.core.timeOnLine() > 0.254) { setState(States.LINE_FOLLOW); } else if (Robot.simpleVision.getObjectCount() == 1) { setState(States.VISION_CLOSING); } else if (Robot.simpleVision.getObjectCount() == 2) { kP = Constants.velocityMultiplier * kpp; double velocity = 4* Constants.velocityMultiplier; gain = 0; double error = Robot.simpleVision.getError(); if (Math.abs(error) > onTargetEpsilon) { gain = error * kP; if (Math.abs(gain) < minTurnPower) { gain = minTurnPower * Math.signum(gain); } gain += Robot.simpleVision.getErrorD() * kD; } SmartDashboard.putNumber("Simple Vision Gain ", gain); Robot.drivetrain.setVelocity(velocity - gain, velocity + gain); } } public void visionClosing() { if (Robot.core.timeOnLine() > 0.254) { setState(States.LINE_FOLLOW); } else if (Robot.simpleVision.getObjectCount() == 2) { setState(States.VISION_DRIVE); } else { Robot.drivetrain.setVelocity(velocity - gain, velocity + gain); } } private void updateCalculations() { final double error = Robot.core.lineSensor(); turnP = SmartDashboard.getNumber("Turn Power", turnP); straightVelocity = SmartDashboard.getNumber("Straight Vel", straightVelocity); turningVelocity = SmartDashboard.getNumber("Turning Vel", turningVelocity); turnI = SmartDashboard.getNumber("turnI", turnI); turnD = SmartDashboard.getNumber("turnD", turnD); if (Double.isNaN(error) || Math.abs(error) <= 1) { errorAcc = 0; } else { errorAcc += error; } turn = (error * turnP) + (errorAcc * turnI)-(prevError-error)*turnD; velocity = (Math.abs(error) <= 1) ? straightVelocity : turningVelocity; prevError = error; } public void lineFollow() { updateCalculations(); Robot.drivetrain.setVelocity(velocity + turn, velocity - turn); //if (!Robot.core.isMoving() && Math.abs(prevError)> 1.5) { // if (Math.abs(prevError)> 1.5) { // state = State.followBackward; // backupError = prevError; // } else { // Robot.drivetrain.setVelocity(0, 0); // } // } } // Make this return true when this Command no longer needs to run execute() @Override protected boolean isFinished() { return getState() == States.DONE; } @Override protected void end() { Robot.drivetrain.stop(); } }
3e117557cf4b659ac42dc4b2dc8964fa7128e80d
699
java
Java
Pizza/PizzaTestDrive.java
justinAurand/DesignPatterns
1fc0a0071b2c78b31684e3958a9d57ea01557816
[ "MIT" ]
null
null
null
Pizza/PizzaTestDrive.java
justinAurand/DesignPatterns
1fc0a0071b2c78b31684e3958a9d57ea01557816
[ "MIT" ]
null
null
null
Pizza/PizzaTestDrive.java
justinAurand/DesignPatterns
1fc0a0071b2c78b31684e3958a9d57ea01557816
[ "MIT" ]
null
null
null
36.789474
73
0.652361
7,371
public class PizzaTestDrive { public static void main(String[] args) { PizzaStore nyStore = new NyPizzaStore(); PizzaStore chicagoStore = new ChicagoPizzaStore(); Pizza pizza = nyStore.orderPizza(Pizzas.Veggie); System.out.println("Ethan received...\n" + pizza.toString()); pizza = chicagoStore.orderPizza(Pizzas.Veggie); System.out.println("Joel received...\n" + pizza.toString()); pizza = nyStore.orderPizza(Pizzas.Clam); System.out.println("Sebastian received...\n" + pizza.toString()); pizza = chicagoStore.orderPizza(Pizzas.Pepperoni); System.out.println("Jeffy received...\n" + pizza.toString()); } }
3e11757187de7afdb4feffe5cb40456a3e8f175e
1,375
java
Java
entity-view/testsuite/src/test/java/com/blazebit/persistence/view/collections/basic/model/BasicDocumentCollectionsView.java
cybernetics/blaze-persistence
2e4270829aaddda5fa2ca2a4a15d89dd549bf8cf
[ "Apache-2.0" ]
1
2019-04-22T08:48:39.000Z
2019-04-22T08:48:39.000Z
entity-view/testsuite/src/test/java/com/blazebit/persistence/view/collections/basic/model/BasicDocumentCollectionsView.java
cybernetics/blaze-persistence
2e4270829aaddda5fa2ca2a4a15d89dd549bf8cf
[ "Apache-2.0" ]
null
null
null
entity-view/testsuite/src/test/java/com/blazebit/persistence/view/collections/basic/model/BasicDocumentCollectionsView.java
cybernetics/blaze-persistence
2e4270829aaddda5fa2ca2a4a15d89dd549bf8cf
[ "Apache-2.0" ]
null
null
null
31.25
79
0.764364
7,372
/* * Copyright 2014 Blazebit. * * 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.blazebit.persistence.view.collections.basic.model; import com.blazebit.persistence.view.EntityView; import com.blazebit.persistence.view.Mapping; import com.blazebit.persistence.view.collections.entity.DocumentForCollections; import com.blazebit.persistence.view.collections.entity.PersonForCollections; import java.util.List; import java.util.Map; import java.util.Set; /** * * @author Christian Beikov * @since 1.0 */ @EntityView(DocumentForCollections.class) public interface BasicDocumentCollectionsView { public String getName(); @Mapping("contacts") public Map<Integer, PersonForCollections> getContacts(); @Mapping("partners") public Set<PersonForCollections> getPartners(); public List<PersonForCollections> getPersonList(); }
3e1175b65d6388ff11903c1320ecf6c7f6e97e5d
2,418
java
Java
sdk/src/main/java/com/vk/api/sdk/queries/ads/AdsDeleteTargetGroupQuery.java
KokorinIlya/vk-java-sdk
8d21f9b32b46db09defa9b9dd2647cd18a5116e7
[ "MIT" ]
1
2021-06-13T03:57:42.000Z
2021-06-13T03:57:42.000Z
sdk/src/main/java/com/vk/api/sdk/queries/ads/AdsDeleteTargetGroupQuery.java
vadimgurov/vk-java-sdk
bd4da82881dc5101cc82629cf64b08019d18ac06
[ "MIT" ]
null
null
null
sdk/src/main/java/com/vk/api/sdk/queries/ads/AdsDeleteTargetGroupQuery.java
vadimgurov/vk-java-sdk
bd4da82881dc5101cc82629cf64b08019d18ac06
[ "MIT" ]
1
2018-10-01T09:43:32.000Z
2018-10-01T09:43:32.000Z
34.056338
109
0.688586
7,373
package com.vk.api.sdk.queries.ads; import com.vk.api.sdk.client.AbstractQueryBuilder; import com.vk.api.sdk.client.VkApiClient; import com.vk.api.sdk.client.actors.UserActor; import com.vk.api.sdk.objects.base.responses.OkResponse; import java.util.Arrays; import java.util.List; /** * Query for Ads.deleteTargetGroup method */ public class AdsDeleteTargetGroupQuery extends AbstractQueryBuilder<AdsDeleteTargetGroupQuery, OkResponse> { /** * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters * * @param client VK API client * @param actor actor with access token * @param accountId value of "account id" parameter. * @param targetGroupId value of "target group id" parameter. */ public AdsDeleteTargetGroupQuery(VkApiClient client, UserActor actor, int accountId, int targetGroupId) { super(client, "ads.deleteTargetGroup", OkResponse.class); accessToken(actor.getAccessToken()); accountId(accountId); targetGroupId(targetGroupId); } /** * Advertising account ID. * * @param value value of "account id" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ protected AdsDeleteTargetGroupQuery accountId(int value) { return unsafeParam("account_id", value); } /** * "Only for advertising agencies." * ID of the client with the advertising account where the group will be created. * * @param value value of "client id" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ public AdsDeleteTargetGroupQuery clientId(Integer value) { return unsafeParam("client_id", value); } /** * Group ID. * * @param value value of "target group id" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ protected AdsDeleteTargetGroupQuery targetGroupId(int value) { return unsafeParam("target_group_id", value); } @Override protected AdsDeleteTargetGroupQuery getThis() { return this; } @Override protected List<String> essentialKeys() { return Arrays.asList("target_group_id", "account_id", "access_token"); } }
3e1175f49d319df9b16ebdce7aa921102eea17b2
3,787
java
Java
checklistbank-nub/src/test/java/org/gbif/nub/lookup/fuzzy/NubIndexTest.java
ahahn-gbif/checklistbank
9bd65a831d9d6ed7b4e1f93e3b7e0ff8f51c7d4f
[ "Apache-2.0" ]
16
2015-02-07T17:03:05.000Z
2022-02-19T01:47:33.000Z
checklistbank-nub/src/test/java/org/gbif/nub/lookup/fuzzy/NubIndexTest.java
ahahn-gbif/checklistbank
9bd65a831d9d6ed7b4e1f93e3b7e0ff8f51c7d4f
[ "Apache-2.0" ]
215
2016-04-29T09:44:09.000Z
2022-03-21T09:01:22.000Z
checklistbank-nub/src/test/java/org/gbif/nub/lookup/fuzzy/NubIndexTest.java
ahahn-gbif/checklistbank
9bd65a831d9d6ed7b4e1f93e3b7e0ff8f51c7d4f
[ "Apache-2.0" ]
12
2016-08-02T00:43:09.000Z
2021-09-08T20:47:22.000Z
34.117117
106
0.702667
7,374
package org.gbif.nub.lookup.fuzzy; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.io.Resources; import org.apache.commons.lang3.StringUtils; import org.gbif.api.model.checklistbank.NameUsageMatch; import org.gbif.api.service.checklistbank.NameParser; import org.gbif.api.util.VocabularyUtils; import org.gbif.api.vocabulary.Rank; import org.gbif.api.vocabulary.TaxonomicStatus; import org.gbif.nameparser.NameParserGbifV1; import org.gbif.utils.file.csv.CSVReader; import org.gbif.utils.file.csv.CSVReaderFactory; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; import static org.junit.Assert.*; public class NubIndexTest { private static NubIndex index; @BeforeClass public static void buildMatcher() throws IOException { HigherTaxaComparator syn = new HigherTaxaComparator(); syn.loadClasspathDicts("dicts"); index = NubIndex.newMemoryIndex(readTestNames()); } public static List<NameUsageMatch> readTestNames() throws IOException { List<NameUsageMatch> usages = Lists.newArrayList(); NameParser parser = new NameParserGbifV1(); try (InputStream testFile = Resources.getResource("testNames.txt").openStream()) { CSVReader reader = CSVReaderFactory.build(testFile, "UTF8", "\t", null, 0); while (reader.hasNext()) { String[] row = reader.next(); NameUsageMatch n = new NameUsageMatch(); n.setUsageKey(Integer.valueOf(row[0])); n.setAcceptedUsageKey(toInt(row[1])); n.setScientificName(row[2]); n.setCanonicalName(parser.parseToCanonical(n.getScientificName(), null)); n.setFamily(row[3]); n.setOrder(row[4]); n.setClazz(row[5]); n.setPhylum(row[6]); n.setKingdom(row[7]); n.setStatus(n.getAcceptedUsageKey() != null ? TaxonomicStatus.SYNONYM : TaxonomicStatus.ACCEPTED); n.setRank(VocabularyUtils.lookupEnum(row[8], Rank.class)); usages.add(n); } Preconditions.checkArgument(usages.size() == 10, "Wrong number of test names"); } return usages; } private static Integer toInt(String x) { return StringUtils.isBlank(x) ? null : Integer.valueOf(x); } @Test public void testMatchByName() throws Exception { final Integer abiesAlbaKey = 7; NameUsageMatch m = index.matchByUsageId(abiesAlbaKey); assertEquals(abiesAlbaKey, m.getUsageKey()); assertEquals("Abies alba Mill.", m.getScientificName()); assertEquals(Rank.SPECIES, m.getRank()); assertFalse(m.isSynonym()); assertNull(m.getAcceptedUsageKey()); m = index.matchByName("Abies alba", true, 2).get(0); assertEquals(abiesAlbaKey, m.getUsageKey()); m = index.matchByName("abies alba", true, 2).get(0); assertEquals(abiesAlbaKey, m.getUsageKey()); m = index.matchByName("Abbies alba", true, 2).get(0); assertEquals(abiesAlbaKey, m.getUsageKey()); m = index.matchByName("abyes alba", true, 2).get(0); assertEquals(abiesAlbaKey, m.getUsageKey()); m = index.matchByName(" apies alba", true, 2).get(0); assertEquals(abiesAlbaKey, m.getUsageKey()); // sciname soundalike filter enables this m = index.matchByName("Abies alllbbbbaaa", true, 2).get(0); assertEquals(abiesAlbaKey, m.getUsageKey()); m = index.matchByName("Aebies allba", true, 2).get(0); assertEquals(abiesAlbaKey, m.getUsageKey()); // fuzzy searches use a minPrefix=1 assertTrue(index.matchByName("Obies alba", true, 2).isEmpty()); assertTrue(index.matchByName("Abies elba", false, 2).isEmpty()); // synonym matching m = index.matchByName("Picea abies", false, 2).get(0); assertTrue(m.isSynonym()); } }
3e117657164d93b6c18a244c1494c5bf97240655
384
java
Java
app/src/main/java/com/xdw/ThirdActivity.java
huihui-Android/testAPP
d5cc4e92e2c7377bf00d3e32c5da18118e45f4c4
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/xdw/ThirdActivity.java
huihui-Android/testAPP
d5cc4e92e2c7377bf00d3e32c5da18118e45f4c4
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/xdw/ThirdActivity.java
huihui-Android/testAPP
d5cc4e92e2c7377bf00d3e32c5da18118e45f4c4
[ "Apache-2.0" ]
null
null
null
22.588235
56
0.744792
7,375
package com.xdw; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class SecondActivity extends Activity { private TextView tvUser; private TextView tvPwd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); } }
3e11767804087f9f4bc7b17f8eaaa205f8a62c73
326
java
Java
src/main/java/org/jretty/kafka/xclient/consumer/ConsumerFactory.java
jretty-org/kafka-xclient
4ead262b7f3accc7cf3ad005ab5e9dd1cc9528d5
[ "Apache-2.0" ]
2
2017-02-16T04:21:56.000Z
2018-09-05T12:08:32.000Z
src/main/java/org/jretty/kafka/xclient/consumer/ConsumerFactory.java
jretty-org/kafka-xclient
4ead262b7f3accc7cf3ad005ab5e9dd1cc9528d5
[ "Apache-2.0" ]
null
null
null
src/main/java/org/jretty/kafka/xclient/consumer/ConsumerFactory.java
jretty-org/kafka-xclient
4ead262b7f3accc7cf3ad005ab5e9dd1cc9528d5
[ "Apache-2.0" ]
3
2018-07-11T01:51:52.000Z
2019-09-11T10:57:57.000Z
18.111111
50
0.711656
7,376
package org.jretty.kafka.xclient.consumer; import java.util.Map; import org.apache.kafka.clients.consumer.Consumer; public interface ConsumerFactory<K, V> { public Map<String, Object> getConfigs(); public String getBrokerUrl(); Consumer<K, V> createConsumer(); public boolean isAutoCommit(); }
3e11773859a0509e42ce23f3d77048e11a19ca19
3,859
java
Java
x4o-driver/src/main/java/org/x4o/xml/io/sax/ext/AbstractContentWriterLexical.java
ralic/gnu_x4o
0c811208ecebe659d0acfcf5e1dc875c704ce75b
[ "BSD-2-Clause" ]
null
null
null
x4o-driver/src/main/java/org/x4o/xml/io/sax/ext/AbstractContentWriterLexical.java
ralic/gnu_x4o
0c811208ecebe659d0acfcf5e1dc875c704ce75b
[ "BSD-2-Clause" ]
null
null
null
x4o-driver/src/main/java/org/x4o/xml/io/sax/ext/AbstractContentWriterLexical.java
ralic/gnu_x4o
0c811208ecebe659d0acfcf5e1dc875c704ce75b
[ "BSD-2-Clause" ]
null
null
null
31.120968
116
0.735424
7,377
/* * Copyright (c) 2004-2014, Willem Cazander * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.x4o.xml.io.sax.ext; import java.io.Writer; import org.x4o.xml.io.XMLConstants; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; /** * ContentWriterXml writes SAX content handler events to XML. * * @author Willem Cazander * @version 1.0 May 3, 2013 */ public abstract class AbstractContentWriterLexical extends AbstractContentWriterHandler implements LexicalHandler { protected boolean printCDATA = false; /** * Creates XmlWriter which prints to the Writer interface. * @param out The writer to print the xml to. */ public AbstractContentWriterLexical(Writer out) { super(out); } /** * @see org.xml.sax.ext.LexicalHandler#startCDATA() */ public void startCDATA() throws SAXException { autoCloseStartElement(); charactersRaw(XMLConstants.CDATA_START); printCDATA = true; } /** * @see org.xml.sax.ext.LexicalHandler#endCDATA() */ public void endCDATA() throws SAXException { charactersRaw(XMLConstants.CDATA_END); printCDATA = false; } /** * @see org.xml.sax.ext.LexicalHandler#startDTD(java.lang.String, java.lang.String, java.lang.String) */ public void startDTD(String name, String publicId, String systemId) throws SAXException { charactersRaw(XMLConstants.XML_DOCTYPE); charactersRaw(" "); charactersRaw(name); if (publicId!=null) { charactersRaw(" "); charactersRaw(publicId); } if (systemId!=null) { charactersRaw(" \""); charactersRaw(systemId); charactersRaw("\""); } charactersRaw(XMLConstants.TAG_CLOSE); } /** * @see org.xml.sax.ext.LexicalHandler#endDTD() */ public void endDTD() throws SAXException { writeFlush(); } /** * @see org.xml.sax.ext.LexicalHandler#startEntity(java.lang.String) */ public void startEntity(String arg0) throws SAXException { } /** * @see org.xml.sax.ext.LexicalHandler#endEntity(java.lang.String) */ public void endEntity(String arg0) throws SAXException { } /** * @see org.x4o.xml.io.sax.ext.AbstractContentWriterHandler#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { characters(new String(ch, start, length)); } /** * @see org.x4o.xml.io.sax.ext.AbstractContentWriterHandler#characters(java.lang.String) */ @Override public void characters(String text) throws SAXException { if (printCDATA) { charactersRaw(XMLConstants.escapeCharactersCdata(text,"","")); } else { super.characters(text); } } }
3e11792b511b70410826edfa91dd04234aa4e2e8
2,783
java
Java
smart-http-server/src/main/java/org/smartboot/http/HttpRequest.java
tcrct/smart-http
fb6fa763fdce43dd5a1ffd26fec22d374edd9881
[ "Apache-2.0" ]
null
null
null
smart-http-server/src/main/java/org/smartboot/http/HttpRequest.java
tcrct/smart-http
fb6fa763fdce43dd5a1ffd26fec22d374edd9881
[ "Apache-2.0" ]
null
null
null
smart-http-server/src/main/java/org/smartboot/http/HttpRequest.java
tcrct/smart-http
fb6fa763fdce43dd5a1ffd26fec22d374edd9881
[ "Apache-2.0" ]
null
null
null
25.126126
80
0.629975
7,378
/******************************************************************************* * Copyright (c) 2017-2020, org.smartboot. All rights reserved. * project name: smart-http * file name: HttpRequest.java * Date: 2020-01-01 * Author: sandao (hzdkv@example.com) ******************************************************************************/ package org.smartboot.http; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.util.Collection; import java.util.Enumeration; import java.util.Locale; import java.util.Map; /** * Http消息请求接口 * * @author 三刀 * @version V1.0 , 2018/8/7 */ public interface HttpRequest { String HTTP_1_0_STRING = "HTTP/1.0"; String HTTP_1_1_STRING = "HTTP/1.1"; /** * 获取指定名称的Http Header值 * * @param headName * @return */ String getHeader(String headName); public Collection<String> getHeaders(String name); Collection<String> getHeaderNames(); InputStream getInputStream() throws IOException; String getRequestURI(); String getProtocol(); /** * Returns the name of the HTTP method with which this * request was made, for example, GET, POST, or PUT. * Same as the value of the CGI variable REQUEST_METHOD. * * @return a <code>String</code> * specifying the name * of the method with which * this request was made */ String getMethod(); String getScheme(); String getRequestURL(); String getQueryString(); String getContentType(); int getContentLength(); String getParameter(String name); String[] getParameterValues(String name); Map<String, String[]> getParameters(); /** * Returns the Internet Protocol (IP) address of the client * or last proxy that sent the request. * For HTTP servlets, same as the value of the * CGI variable <code>REMOTE_ADDR</code>. * * @return a <code>String</code> containing the * IP address of the client that sent the request */ String getRemoteAddr(); InetSocketAddress getRemoteAddress(); InetSocketAddress getLocalAddress(); /** * Returns the fully qualified name of the client * or the last proxy that sent the request. * If the engine cannot or chooses not to resolve the hostname * (to improve performance), this method returns the dotted-string form of * the IP address. For HTTP servlets, same as the value of the CGI variable * <code>REMOTE_HOST</code>. * * @return a <code>String</code> containing the fully * qualified name of the client */ String getRemoteHost(); public Locale getLocale(); public Enumeration<Locale> getLocales(); String getCharacterEncoding(); }
3e1179f472ff705877873d89a7b23d5c1b55dff3
422
java
Java
src/main/java/edu/uwo/health/entity/FaceLoginParams.java
yweng47/HealthU_backend
c945d0d2aeb0c64543f9e83ab04e54c42da9f368
[ "MIT" ]
null
null
null
src/main/java/edu/uwo/health/entity/FaceLoginParams.java
yweng47/HealthU_backend
c945d0d2aeb0c64543f9e83ab04e54c42da9f368
[ "MIT" ]
null
null
null
src/main/java/edu/uwo/health/entity/FaceLoginParams.java
yweng47/HealthU_backend
c945d0d2aeb0c64543f9e83ab04e54c42da9f368
[ "MIT" ]
null
null
null
19.181818
54
0.677725
7,379
package edu.uwo.health.entity; import java.io.Serializable; public class FaceLoginParams implements Serializable { private String username; public FaceLoginParams() {} public FaceLoginParams(String username) { this.username = username; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
3e117ca3e7f329361913dd8d0d279abe133d4d1c
40,297
java
Java
platform/util/src/com/intellij/util/ui/JBUI.java
pavel-ryzhov/intellij-community
8f62306112e5e5f56e5af87b4104ead2aa831e22
[ "Apache-2.0" ]
null
null
null
platform/util/src/com/intellij/util/ui/JBUI.java
pavel-ryzhov/intellij-community
8f62306112e5e5f56e5af87b4104ead2aa831e22
[ "Apache-2.0" ]
null
null
null
platform/util/src/com/intellij/util/ui/JBUI.java
pavel-ryzhov/intellij-community
8f62306112e5e5f56e5af87b4104ead2aa831e22
[ "Apache-2.0" ]
1
2019-07-18T16:50:52.000Z
2019-07-18T16:50:52.000Z
31.630298
131
0.668437
7,380
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.util.ui; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.ScalableIcon; import com.intellij.openapi.util.SystemInfo; import com.intellij.ui.border.CustomLineBorder; import com.intellij.util.SystemProperties; import com.intellij.util.ui.components.BorderLayoutPanel; import gnu.trove.TDoubleObjectHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.plaf.UIResource; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.ImageObserver; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import static com.intellij.util.ui.JBUI.ScaleType.*; /** * @author Konstantin Bulenkov * @author tav */ public class JBUI { private static final Logger LOG = Logger.getInstance("#com.intellij.util.ui.JBUI"); public static final String USER_SCALE_FACTOR_PROPERTY = "JBUI.userScaleFactor"; private static final PropertyChangeSupport PCS = new PropertyChangeSupport(new JBUI()); private static final float DISCRETE_SCALE_RESOLUTION = 0.25f; /** * The IDE supports two different HiDPI modes: * * 1) IDE-managed HiDPI mode. * * Supported for backward compatibility until complete transition to the JRE-managed HiDPI mode happens. * In this mode there's a single coordinate space and the whole UI is scaled by the IDE guided by the * user scale factor ({@link #USR_SCALE}). * * 2) JRE-managed HiDPI mode. * * In this mode the JRE scales graphics prior to drawing it on the device. So, there're two coordinate * spaces: the user space and the device space. The system scale factor ({@link #SYS_SCALE}) defines the * transform b/w the spaces. The UI size metrics (windows, controls, fonts height) are in the user * coordinate space. Though, the raster images should be aware of the device scale in order to meet * HiDPI. (For instance, JRE on a Mac Retina monitor device works in the JRE-managed HiDPI mode, * transforming graphics to the double-scaled device coordinate space) * * The IDE operates the scale factors of the following types: * * 1) The user scale factor: {@link #USR_SCALE} * 2) The system (monitor device) scale factor: {@link #SYS_SCALE} * 3) The object (UI instance specific) scale factor: {@link #OBJ_SCALE} * 4) The pixel scale factor: {@link #PIX_SCALE} * * @see UIUtil#isJreHiDPIEnabled() * @see UIUtil#isJreHiDPI() * @see UIUtil#isJreHiDPI(GraphicsConfiguration) * @see UIUtil#isJreHiDPI(Graphics2D) * @see JBUI#isUsrHiDPI() * @see JBUI#isPixHiDPI(GraphicsConfiguration) * @see JBUI#isPixHiDPI(Graphics2D) * @see UIUtil#drawImage(Graphics, Image, int, int, int, int, ImageObserver) * @see UIUtil#createImage(Graphics, int, int, int) * @see UIUtil#createImage(GraphicsConfiguration, int, int, int) * @see UIUtil#createImage(int, int, int) * @see ScaleContext */ public enum ScaleType { /** * The user scale factor is set and managed by the IDE. Currently it's derived from the UI font size, * specified in the IDE Settings. * * The user scale value depends on which HiDPI mode is enabled. In the IDE-managed HiDPI mode the * user scale "includes" the default system scale and simply equals it with the default UI font size. * In the JRE-managed HiDPI mode the user scale is independent of the system scale and equals 1.0 * with the default UI font size. In case the default UI font size changes, the user scale changes * proportionally in both the HiDPI modes. * * In the IDE-managed HiDPI mode the user scale completely defines the UI scale. In the JRE-managed * HiDPI mode the user scale can be considered a supplementary scale taking effect in cases like * the IDE Presentation Mode and when the default UI scale is changed by the user. * * @see #setUserScaleFactor(float) * @see #scale(float) * @see #scale(int) */ USR_SCALE, /** * The system scale factor is defined by the device DPI and/or the system settings. For instance, * Mac Retina monitor device has the system scale 2.0 by default. As there can be multiple devices * (multi-monitor configuration) there can be multiple system scale factors, appropriately. However, * there's always a single default system scale factor corresponding to the default device. And it's * the only system scale available in the IDE-managed HiDPI mode. * * In the JRE-managed HiDPI mode, the system scale defines the scale of the transform b/w the user * and the device coordinate spaces performed by the JRE. * * @see #sysScale() * @see #sysScale(GraphicsConfiguration) * @see #sysScale(Graphics2D) * @see #sysScale(Component) */ SYS_SCALE, /** * An extra scale factor of a particular UI object, which doesn't affect any other UI object, as opposed * to the user scale and the system scale factors. Doesn't depend on the HiDPI mode and is 1.0 by default. */ OBJ_SCALE, /** * The pixel scale factor "combines" all the other scale factors (user, system and object) and defines the * effective scale of a particular UI object. * * For instance, on Mac Retina monitor (JRE-managed HiDPI) in the Presentation mode (which, say, * doubles the UI scale) the pixel scale would equal 4.0 (provided the object scale is 1.0). The value * is the product of the user scale 2.0 and the system scale 2.0. In the IDE-managed HiDPI mode, * the pixel scale is the product of the user scale and the object scale. * * @see #pixScale() * @see #pixScale(GraphicsConfiguration) * @see #pixScale(Graphics2D) * @see #pixScale(Component) * @see #pixScale(GraphicsConfiguration, float) * @see #pixScale(float) */ PIX_SCALE; public Scale of(double value) { return Scale.create(value, this); } } /** * A scale factor of a particular type. */ public static class Scale { private final double value; private final ScaleType type; // The cache radically reduces potentially thousands of equal Scale instances. private static final ThreadLocal<EnumMap<ScaleType, TDoubleObjectHashMap<Scale>>> cache = new ThreadLocal<EnumMap<ScaleType, TDoubleObjectHashMap<Scale>>>() { @Override protected EnumMap<ScaleType, TDoubleObjectHashMap<Scale>> initialValue() { return new EnumMap<ScaleType, TDoubleObjectHashMap<Scale>>(ScaleType.class); } }; public static Scale create(double value, ScaleType type) { EnumMap<ScaleType, TDoubleObjectHashMap<Scale>> emap = cache.get(); TDoubleObjectHashMap<Scale> map = emap.get(type); if (map == null) { emap.put(type, map = new TDoubleObjectHashMap<Scale>()); } Scale scale = map.get(value); if (scale != null) return scale; map.put(value, scale = new Scale(value, type)); return scale; } private Scale(double value, ScaleType type) { this.value = value; this.type = type; } public double value() { return value; } public ScaleType type() { return type; } public Scale newOrThis(double value) { if (this.value == value) return this; return type.of(value); } @Override public String toString() { return "[" + type.name() + " " + value + "]"; } } /** * The system scale factor, corresponding to the default monitor device. */ private static final Float SYSTEM_SCALE_FACTOR = sysScale(); /** * The user space scale factor. */ private static float userScaleFactor; static { setUserScaleFactor(UIUtil.isJreHiDPIEnabled() ? 1f : SYSTEM_SCALE_FACTOR); LOG.info("System scale factor: " + SYSTEM_SCALE_FACTOR + " (" + (UIUtil.isJreHiDPIEnabled() ? "JRE-managed" : "IDE-managed") + " HiDPI)"); } /** * Adds property change listener. Supported properties: * {@link #USER_SCALE_FACTOR_PROPERTY} */ public static void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { PCS.addPropertyChangeListener(propertyName, listener); } /** * Removes property change listener */ public static void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { PCS.removePropertyChangeListener(propertyName, listener); } /** * Returns the system scale factor, corresponding to the default monitor device. */ public static float sysScale() { if (SYSTEM_SCALE_FACTOR != null) { return SYSTEM_SCALE_FACTOR; } if (UIUtil.isJreHiDPIEnabled()) { GraphicsDevice gd = null; try { gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); } catch (HeadlessException ignore) {} if (gd != null && gd.getDefaultConfiguration() != null) { return sysScale(gd.getDefaultConfiguration()); } return 1.0f; } if (SystemProperties.has("hidpi") && !SystemProperties.is("hidpi")) { return 1.0f; } UIUtil.initSystemFontData(); Pair<String, Integer> fdata = UIUtil.getSystemFontData(); int size = fdata == null ? Fonts.label().getSize() : fdata.getSecond(); return getFontScale(size); } /** * Returns the system scale factor, corresponding to the graphics configuration. * In the IDE-managed HiDPI mode defaults to {@link #sysScale()} */ public static float sysScale(@Nullable GraphicsConfiguration gc) { if (UIUtil.isJreHiDPIEnabled() && gc != null) { if (gc.getDevice().getType() == GraphicsDevice.TYPE_RASTER_SCREEN) { if (SystemInfo.isMac && UIUtil.isJreHiDPI_earlierVersion()) { return UIUtil.DetectRetinaKit.isOracleMacRetinaDevice(gc.getDevice()) ? 2f : 1f; } return (float)gc.getDefaultTransform().getScaleX(); } } return sysScale(); } /** * Returns the system scale factor, corresponding to the graphics. * For BufferedImage's graphics, the scale is taken from the graphics itself. * In the IDE-managed HiDPI mode defaults to {@link #sysScale()} */ public static float sysScale(@Nullable Graphics2D g) { if (UIUtil.isJreHiDPIEnabled() && g != null) { GraphicsConfiguration gc = g.getDeviceConfiguration(); if (gc == null || gc.getDevice().getType() == GraphicsDevice.TYPE_IMAGE_BUFFER || gc.getDevice().getType() == GraphicsDevice.TYPE_PRINTER) { // in this case gc doesn't provide a valid scale return (float)g.getTransform().getScaleX(); } return sysScale(gc); } return sysScale(); } /** * Returns the system scale factor, corresponding to the device the component is tied to. * In the IDE-managed HiDPI mode defaults to {@link #sysScale()} */ public static float sysScale(@Nullable Component comp) { if (comp != null) { return sysScale(comp.getGraphicsConfiguration()); } return sysScale(); } public static double sysScale(@Nullable ScaleContext ctx) { if (ctx != null) { return ctx.getScale(SYS_SCALE); } return sysScale(); } /** * Returns the pixel scale factor, corresponding to the default monitor device. */ public static float pixScale() { return UIUtil.isJreHiDPIEnabled() ? sysScale() * scale(1f) : scale(1f); } /** * Returns "f" scaled by pixScale(). */ public static float pixScale(float f) { return pixScale() * f; } /** * Returns "f" scaled by pixScale(gc). */ public static float pixScale(@Nullable GraphicsConfiguration gc, float f) { return pixScale(gc) * f; } /** * Returns the pixel scale factor, corresponding to the provided configuration. * In the IDE-managed HiDPI mode defaults to {@link #pixScale()} */ public static float pixScale(@Nullable GraphicsConfiguration gc) { return UIUtil.isJreHiDPIEnabled() ? sysScale(gc) * scale(1f) : scale(1f); } /** * Returns the pixel scale factor, corresponding to the provided graphics. * In the IDE-managed HiDPI mode defaults to {@link #pixScale()} */ public static float pixScale(@Nullable Graphics2D g) { return UIUtil.isJreHiDPIEnabled() ? sysScale(g) * scale(1f) : scale(1f); } /** * Returns the pixel scale factor, corresponding to the device the provided component is tied to. * In the IDE-managed HiDPI mode defaults to {@link #pixScale()} */ public static float pixScale(@Nullable Component comp) { return pixScale(comp != null ? comp.getGraphicsConfiguration() : null); } public static <T extends BaseScaleContext> double pixScale(@Nullable T ctx) { if (ctx != null) { double usrScale = ctx.getScale(USR_SCALE); return UIUtil.isJreHiDPIEnabled() ? ctx.getScale(SYS_SCALE) * usrScale : usrScale; } return pixScale(); } private static void setUserScaleFactorProperty(float scale) { PCS.firePropertyChange(USER_SCALE_FACTOR_PROPERTY, userScaleFactor, userScaleFactor = scale); LOG.info("User scale factor: " + userScaleFactor); } /** * Sets the user scale factor. * The method is used by the IDE, it's not recommended to call the method directly from the client code. * For debugging purposes, the following registry keys can be used: * ide.ui.scale.override=[boolean] * ide.ui.scale=[float] */ public static void setUserScaleFactor(float scale) { if (SystemProperties.has("hidpi") && !SystemProperties.is("hidpi")) { setUserScaleFactorProperty(1.0f); return; } scale = discreteScale(scale); // Downgrading user scale below 1.0 may be uncomfortable (tiny icons), // whereas some users prefer font size slightly below normal which is ok. if (scale < 1 && sysScale() >= 1) scale = 1; // Ignore the correction when UIUtil.DEF_SYSTEM_FONT_SIZE is overridden, see UIUtil.initSystemFontData. if (SystemInfo.isLinux && scale == 1.25f && UIUtil.DEF_SYSTEM_FONT_SIZE == 12) { //Default UI font size for Unity and Gnome is 15. Scaling factor 1.25f works badly on Linux scale = 1f; } if (userScaleFactor == scale) { return; } setUserScaleFactorProperty(scale); } static float discreteScale(float scale) { return Math.round(scale / DISCRETE_SCALE_RESOLUTION) * DISCRETE_SCALE_RESOLUTION; } /** * @return 'f' scaled by the user scale factor */ public static float scale(float f) { return f * userScaleFactor; } /** * @return 'i' scaled by the user scale factor */ public static int scale(int i) { return Math.round(userScaleFactor * i); } public static int scaleFontSize(float fontSize) { if (userScaleFactor == 1.25f) return (int)(fontSize * 1.34f); if (userScaleFactor == 1.75f) return (int)(fontSize * 1.67f); return (int)scale(fontSize); } /** * @return the scale factor of {@code fontSize} relative to the standard font size (currently 12pt) */ public static float getFontScale(float fontSize) { return fontSize / UIUtil.DEF_SYSTEM_FONT_SIZE; } public static JBDimension size(int width, int height) { return new JBDimension(width, height); } public static JBDimension size(int widthAndHeight) { return new JBDimension(widthAndHeight, widthAndHeight); } public static JBDimension size(Dimension size) { if (size instanceof JBDimension) { JBDimension newSize = ((JBDimension)size).newSize(); return size instanceof UIResource ? newSize.asUIResource() : newSize; } return new JBDimension(size.width, size.height); } public static JBInsets insets(int top, int left, int bottom, int right) { return new JBInsets(top, left, bottom, right); } public static JBInsets insets(int all) { return insets(all, all, all, all); } public static JBInsets insets(int topBottom, int leftRight) { return insets(topBottom, leftRight, topBottom, leftRight); } public static JBInsets emptyInsets() { return new JBInsets(0, 0, 0, 0); } public static JBInsets insetsTop(int t) { return insets(t, 0, 0, 0); } public static JBInsets insetsLeft(int l) { return insets(0, l, 0, 0); } public static JBInsets insetsBottom(int b) { return insets(0, 0, b, 0); } public static JBInsets insetsRight(int r) { return insets(0, 0, 0, r); } /** * @deprecated use JBUI.scale(EmptyIcon.create(size)) instead */ public static EmptyIcon emptyIcon(int size) { return scale(EmptyIcon.create(size)); } @NotNull public static <T extends JBIcon> T scale(@NotNull T icon) { return (T)icon.withIconPreScaled(false); } @NotNull public static JBDimension emptySize() { return new JBDimension(0, 0); } @NotNull public static JBInsets insets(@NotNull Insets insets) { return JBInsets.create(insets); } /** * @deprecated use {@link #isUsrHiDPI()} instead */ @Deprecated public static boolean isHiDPI() { return isUsrHiDPI(); } /** * Returns whether the {@link ScaleType#USR_SCALE} scale factor assumes HiDPI-awareness. * An equivalent of {@code isHiDPI(scale(1f))} */ public static boolean isUsrHiDPI() { return isHiDPI(scale(1f)); } /** * Returns whether the {@link ScaleType#PIX_SCALE} scale factor assumes HiDPI-awareness in the provided graphics config. * An equivalent of {@code isHiDPI(pixScale(gc))} */ public static boolean isPixHiDPI(@Nullable GraphicsConfiguration gc) { return isHiDPI(pixScale(gc)); } /** * Returns whether the {@link ScaleType#PIX_SCALE} scale factor assumes HiDPI-awareness in the provided graphics. * An equivalent of {@code isHiDPI(pixScale(g))} */ public static boolean isPixHiDPI(@Nullable Graphics2D g) { return isHiDPI(pixScale(g)); } /** * Returns whether the {@link ScaleType#PIX_SCALE} scale factor assumes HiDPI-awareness in the provided component's device. * An equivalent of {@code isHiDPI(pixScale(comp))} */ public static boolean isPixHiDPI(@Nullable Component comp) { return isHiDPI(pixScale(comp)); } /** * Returns whether the provided scale assumes HiDPI-awareness. */ public static boolean isHiDPI(double scale) { return scale > 1f; } /** * Aligns the x or/and y translate of the graphics to the integer coordinate grid if the graphics has fractional scale transform, * otherwise does nothing. This is used to avoid the rounding problem, see JRE-502. * * @param g the graphics to align * @param alignX should the x-translate be aligned * @param alignY should the y-translate be aligned * @return the original graphics transform when aligned, otherwise null */ public static AffineTransform alignToIntGrid(@NotNull Graphics2D g, boolean alignX, boolean alignY) { try { AffineTransform tx = g.getTransform(); if (isFractionalScale(tx)) { double scaleX = tx.getScaleX(); double scaleY = tx.getScaleY(); AffineTransform alignedTx = new AffineTransform(); double trX = alignX ? (int)Math.ceil(tx.getTranslateX() - 0.5) : tx.getTranslateX(); double trY = alignY ? (int)Math.ceil(tx.getTranslateY() - 0.5) : tx.getTranslateY(); alignedTx.translate(trX, trY); alignedTx.scale(scaleX, scaleY); assert tx.getShearX() == 0 && tx.getShearY() == 0; // the shear is ignored g.setTransform(alignedTx); return tx; } } catch (Exception e) { LOG.trace(e); } return null; } /** * Returns true if the transform matrix contains fractional scale element. */ public static boolean isFractionalScale(AffineTransform tx) { double scaleX = tx.getScaleX(); double scaleY = tx.getScaleY(); return scaleX != (int)scaleX || scaleY != (int)scaleY; } public static class Fonts { @NotNull public static JBFont label() { return JBFont.create(UIManager.getFont("Label.font"), false); } @NotNull public static JBFont label(float size) { return label().deriveFont(scale(size)); } @NotNull public static JBFont smallFont() { return label().deriveFont(UIUtil.getFontSize(UIUtil.FontSize.SMALL)); } @NotNull public static JBFont miniFont() { return label().deriveFont(UIUtil.getFontSize(UIUtil.FontSize.MINI)); } @NotNull public static JBFont create(String fontFamily, int size) { return JBFont.create(new Font(fontFamily, Font.PLAIN, size)); } } @SuppressWarnings("UseDPIAwareBorders") public static class Borders { public static JBEmptyBorder empty(int top, int left, int bottom, int right) { return new JBEmptyBorder(top, left, bottom, right); } public static JBEmptyBorder empty(int topAndBottom, int leftAndRight) { return empty(topAndBottom, leftAndRight, topAndBottom, leftAndRight); } public static JBEmptyBorder emptyTop(int offset) { return empty(offset, 0, 0, 0); } public static JBEmptyBorder emptyLeft(int offset) { return empty(0, offset, 0, 0); } public static JBEmptyBorder emptyBottom(int offset) { return empty(0, 0, offset, 0); } public static JBEmptyBorder emptyRight(int offset) { return empty(0, 0, 0, offset); } public static JBEmptyBorder empty() { return empty(0, 0, 0, 0); } public static Border empty(int offsets) { return empty(offsets, offsets, offsets, offsets); } public static Border customLine(Color color, int top, int left, int bottom, int right) { return new CustomLineBorder(color, insets(top, left, bottom, right)); } public static Border customLine(Color color, int thickness) { return customLine(color, thickness, thickness, thickness, thickness); } public static Border customLine(Color color) { return customLine(color, 1); } public static Border merge(@Nullable Border source, @NotNull Border extra, boolean extraIsOutside) { if (source == null) return extra; return new CompoundBorder(extraIsOutside ? extra : source, extraIsOutside? source : extra); } } public static class Panels { public static BorderLayoutPanel simplePanel() { return new BorderLayoutPanel(); } public static BorderLayoutPanel simplePanel(Component comp) { return simplePanel().addToCenter(comp); } public static BorderLayoutPanel simplePanel(int hgap, int vgap) { return new BorderLayoutPanel(hgap, vgap); } } /** * A wrapper over a user scale supplier, representing a state of a UI element * in which its initial size is either pre-scaled (according to {@link #currentScale()}) * or not (given in a standard resolution, e.g. 16x16 for an icon). */ public abstract static class Scaler { protected double initialScale = currentScale(); private double alignedScale() { return currentScale() / initialScale; } protected boolean isPreScaled() { return initialScale != 1d; } protected void setPreScaled(boolean preScaled) { initialScale = preScaled ? currentScale() : 1d; } /** * @param value the value (e.g. a size of the associated UI object) to scale * @return the scaled result, taking into account the pre-scaled state and {@link #currentScale()} */ public double scaleVal(double value) { return value * alignedScale(); } /** * Supplies the Scaler with the current user scale. This can be the current global user scale or * the context scale ({@link BaseScaleContext#usrScale}) or something else. */ protected abstract double currentScale(); /** * Synchronizes the state with the provided scaler. * * @return whether the state has been updated */ public boolean update(@NotNull Scaler scaler) { boolean updated = initialScale != scaler.initialScale; initialScale = scaler.initialScale; return updated; } } /** * Represents a snapshot of the scale factors (see {@link ScaleType}), except the system scale. * The context can be associated with a UI object (see {@link ScaleContextAware}) to define its HiDPI behaviour. * Unlike {@link ScaleContext}, BaseScaleContext is system scale independent and is thus used for vector-based painting. * * @see ScaleContextAware * @see ScaleContext * @author tav */ public static class BaseScaleContext { protected Scale usrScale = USR_SCALE.of(scale(1f)); protected Scale objScale = OBJ_SCALE.of(1d); protected Scale pixScale = PIX_SCALE.of(usrScale.value); private List<UpdateListener> listeners; private BaseScaleContext() { } /** * Creates a context with the provided scale factors (system scale is ignored) */ public static BaseScaleContext create(@NotNull Scale... scales) { BaseScaleContext ctx = create(); for (Scale s : scales) ctx.update(s); return ctx; } /** * Creates a default context with the current user scale */ public static BaseScaleContext create() { return new BaseScaleContext(); } protected double derivePixScale() { return usrScale.value * objScale.value; } /** * @return the context scale factor of the provided type (1d for system scale) */ public double getScale(ScaleType type) { switch (type) { case USR_SCALE: return usrScale.value; case SYS_SCALE: return 1d; case OBJ_SCALE: return objScale.value; case PIX_SCALE: return pixScale.value; } return 1f; // unreachable } protected boolean onUpdated(boolean updated) { if (updated) { update(pixScale, derivePixScale()); notifyUpdateListeners(); } return updated; } /** * Updates the user scale with the current global user scale if necessary. * * @return whether any of the scale factors has been updated */ public boolean update() { return onUpdated(update(usrScale, scale(1f))); } /** * Updates the provided scale if necessary (system scale is ignored) * * @param scale the new scale * @return whether the scale factor has been updated */ public boolean update(@NotNull Scale scale) { boolean updated = false; switch (scale.type) { case USR_SCALE: updated = update(usrScale, scale.value); break; case SYS_SCALE: break; case OBJ_SCALE: updated = update(objScale, scale.value); break; case PIX_SCALE: break; } return onUpdated(updated); } /** * Updates the context with the state of the provided one. * * @param ctx the new context * @return whether any of the scale factors has been updated */ public boolean update(@Nullable BaseScaleContext ctx) { if (ctx == null) return update(); return onUpdated(updateAll(ctx)); } protected <T extends BaseScaleContext> boolean updateAll(@NotNull T ctx) { boolean updated = update(usrScale, ctx.usrScale.value); return update(objScale, ctx.objScale.value) || updated; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof BaseScaleContext)) return false; BaseScaleContext that = (BaseScaleContext)obj; return that.usrScale.value == usrScale.value && that.objScale.value == objScale.value; } /** * Clears the links. */ public void dispose() { listeners = null; } /** * A context update listener. Used to listen to possible external context updates. */ public interface UpdateListener { void contextUpdated(); } public void addUpdateListener(UpdateListener l) { if (listeners == null) listeners = new ArrayList<UpdateListener>(1); listeners.add(l); } public void removeUpdateListener(UpdateListener l) { if (listeners != null) listeners.remove(l); } protected void notifyUpdateListeners() { if (listeners == null) return; for (UpdateListener l : listeners) { l.contextUpdated(); } } protected boolean update(@NotNull Scale scale, double value) { Scale newScale = scale.newOrThis(value); if (newScale == scale) return false; switch (scale.type) { case USR_SCALE: usrScale = newScale; break; case OBJ_SCALE: objScale = newScale; break; case PIX_SCALE: pixScale = newScale; break; } return true; } } /** * Extends {@link BaseScaleContext} with the system scale, and is thus used for raster-based painting. * The context is created via a context provider. If the provider is {@link Component}, the context's * system scale can be updated via a call to {@link #update()}, reflecting the current component's * system scale (which may change as the component moves b/w devices). * * @see ScaleContextAware * @author tav */ public static class ScaleContext extends BaseScaleContext { protected Scale sysScale = SYS_SCALE.of(sysScale()); @Nullable private WeakReference<Component> compRef; private ScaleContext() { update(pixScale, derivePixScale()); } private ScaleContext(Scale scale) { switch (scale.type) { case USR_SCALE: update(usrScale, scale.value); break; case SYS_SCALE: update(sysScale, scale.value); break; case OBJ_SCALE: update(objScale, scale.value); break; case PIX_SCALE: break; } update(pixScale, derivePixScale()); } /** * Creates a context based on the comp's system scale and sticks to it via the {@link #update()} method. */ public static ScaleContext create(@NotNull Component comp) { final ScaleContext ctx = new ScaleContext(SYS_SCALE.of(sysScale(comp))); ctx.compRef = new WeakReference<Component>(comp); return ctx; } /** * Creates a context based on the gc's system scale */ public static ScaleContext create(GraphicsConfiguration gc) { return new ScaleContext(SYS_SCALE.of(sysScale(gc))); } /** * Creates a context based on the g's system scale */ public static ScaleContext create(Graphics2D g) { return new ScaleContext(SYS_SCALE.of(sysScale(g))); } /** * Creates a context with the provided scale */ public static ScaleContext create(@NotNull Scale scale) { return new ScaleContext(scale); } /** * Creates a context with the provided scale factors */ public static ScaleContext create(@NotNull Scale... scales) { ScaleContext ctx = create(); for (Scale s : scales) ctx.update(s); return ctx; } /** * Creates a default context with the default screen scale and the current user scale */ public static ScaleContext create() { return new ScaleContext(); } @Override protected double derivePixScale() { return UIUtil.isJreHiDPIEnabled() ? sysScale.value * super.derivePixScale() : super.derivePixScale(); } /** * {@inheritDoc} */ @Override public double getScale(ScaleType type) { if (type == SYS_SCALE) return sysScale.value; return super.getScale(type); } /** * {@inheritDoc} * Also updates the system scale (if the context was created from Component) if necessary. */ @Override public boolean update() { boolean updated = update(usrScale, scale(1f)); if (compRef != null) { Component comp = compRef.get(); if (comp != null) updated = update(sysScale, sysScale(comp)) || updated; } return onUpdated(updated); } /** * {@inheritDoc} * Also includes the system scale. */ @Override public boolean update(@NotNull Scale scale) { if (scale.type == SYS_SCALE) return onUpdated(update(sysScale, scale.value)); return super.update(scale); } @Override protected <T extends BaseScaleContext> boolean updateAll(@NotNull T ctx) { boolean updated = super.updateAll(ctx); if (!(ctx instanceof ScaleContext)) return updated; ScaleContext context = (ScaleContext)ctx; if (compRef != null) compRef.clear(); compRef = context.compRef; return update(sysScale, context.sysScale.value) || updated; } @Override protected boolean update(@NotNull Scale scale, double value) { if (scale.type == SYS_SCALE) { Scale newScale = scale.newOrThis(value); if (newScale == scale) return false; sysScale = newScale; return true; } return super.update(scale, value); } @Override public boolean equals(Object obj) { if (super.equals(obj) && obj instanceof ScaleContext) { ScaleContext that = (ScaleContext)obj; return that.sysScale.value == sysScale.value; } return false; } @Override public void dispose() { super.dispose(); if (compRef != null) { compRef.clear(); } } } /** * Provides ScaleContext awareness of a UI object. * * @see ScaleContextSupport * @author tav */ public interface ScaleContextAware<T extends BaseScaleContext> { /** * @return the scale context */ @NotNull T getScaleContext(); /** * Updates the current context with the state of the provided context. * If {@code ctx} is null, then updates the current context via {@link ScaleContext#update()} * and returns the result. * * @param ctx the new scale context * @return whether any of the scale factors has been updated */ boolean updateScaleContext(@Nullable T ctx); /** * @return the scale of the provided type from the context */ double getScale(ScaleType type); /** * Updates the provided scale in the context * * @return whether the provided scale has been changed */ boolean updateScale(Scale scale); } public static class ScaleContextSupport<T extends BaseScaleContext> implements ScaleContextAware<T> { @NotNull private final T myScaleContext; public ScaleContextSupport(@NotNull T ctx) { myScaleContext = ctx; } @NotNull @Override public T getScaleContext() { return myScaleContext; } @Override public boolean updateScaleContext(@Nullable T ctx) { return myScaleContext.update(ctx); } @Override public double getScale(ScaleType type) { return getScaleContext().getScale(type); } @Override public boolean updateScale(Scale scale) { return getScaleContext().update(scale); } } /** * A {@link BaseScaleContext} aware Icon, assuming vector-based painting, system scale independent. * * @author tav */ public abstract static class JBIcon extends ScaleContextSupport<BaseScaleContext> implements Icon { private final Scaler myScaler = new Scaler() { @Override protected double currentScale() { if (autoUpdateScaleContext) getScaleContext().update(); return getScale(USR_SCALE); } }; private boolean autoUpdateScaleContext = true; protected JBIcon() { super(BaseScaleContext.create()); } protected JBIcon(JBIcon icon) { this(); updateScaleContext(icon.getScaleContext()); myScaler.update(icon.myScaler); autoUpdateScaleContext = icon.autoUpdateScaleContext; } protected boolean isIconPreScaled() { return myScaler.isPreScaled(); } protected void setIconPreScaled(boolean preScaled) { myScaler.setPreScaled(preScaled); } @NotNull public JBIcon withIconPreScaled(boolean preScaled) { setIconPreScaled(preScaled); return this; } /** * See {@link Scaler#scaleVal(double)} */ protected double scaleVal(double value) { return myScaler.scaleVal(value); } /** * Sets whether the scale context should be auto-updated by the {@link Scaler}. * This ensures that {@link #scaleVal(double)} always uses up-to-date scale. * This is useful when the icon doesn't need to recalculate its internal sizes * on the scale context update and so it doesn't need the result of the update * and/or it doesn't listen for updates. Otherwise, the value should be set to * false and the scale context should be updated manually. * <p> * By default the value is true. */ protected void setAutoUpdateScaleContext(boolean autoUpdate) { autoUpdateScaleContext = autoUpdate; } @Override public String toString() { return getClass().getName() + " " + getIconWidth() + "x" + getIconHeight(); } } /** * A {@link JBIcon} implementing {@link ScalableIcon} * * @author tav */ public abstract static class ScalableJBIcon extends JBIcon implements ScalableIcon { protected ScalableJBIcon() {} protected ScalableJBIcon(ScalableJBIcon icon) { super(icon); } @Override public float getScale() { return (float)getScale(OBJ_SCALE); // todo: float -> double } @Override public Icon scale(float scale) { updateScale(OBJ_SCALE.of(scale)); return this; } /** * An equivalent of scaleVal(value, PIX_SCALE) */ @Override protected double scaleVal(double value) { return scaleVal(value, PIX_SCALE); } /** * Updates the context and scales the provided value according to the provided type */ protected double scaleVal(double value, ScaleType type) { switch (type) { case USR_SCALE: return super.scaleVal(value); case SYS_SCALE: return value * getScale(SYS_SCALE); case OBJ_SCALE: return value * getScale(OBJ_SCALE); case PIX_SCALE: return super.scaleVal(value * getScale(OBJ_SCALE)); } return value; // unreachable } } /** * A {@link ScalableJBIcon} providing an immutable caching implementation of the {@link ScalableIcon#scale(float)} method. * * @author tav * @author Aleksey Pivovarov */ public abstract static class CachingScalableJBIcon<T extends CachingScalableJBIcon> extends ScalableJBIcon { private CachingScalableJBIcon myScaledIconCache; protected CachingScalableJBIcon() {} protected CachingScalableJBIcon(CachingScalableJBIcon icon) { super(icon); } /** * @return a new scaled copy of this icon, or the cached instance of the provided scale */ @Override public Icon scale(float scale) { if (scale == getScale()) return this; if (myScaledIconCache == null || myScaledIconCache.getScale() != scale) { myScaledIconCache = copy(); myScaledIconCache.updateScale(OBJ_SCALE.of(scale)); } return myScaledIconCache; } /** * @return a copy of this icon instance */ @NotNull protected abstract T copy(); } /** * A {@link ScaleContext} aware Icon, assuming raster-based painting, system scale dependant. * * @author tav */ public abstract static class RasterJBIcon extends ScaleContextSupport<ScaleContext> implements Icon { public RasterJBIcon() { super(ScaleContext.create()); } } }
3e117ce18733400db482934c0b893daaebef73d9
655
java
Java
Corpus/aspectj/510.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
1
2022-01-15T02:47:45.000Z
2022-01-15T02:47:45.000Z
Corpus/aspectj/510.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
null
null
null
Corpus/aspectj/510.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
null
null
null
32.75
81
0.574046
7,381
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial implementation *******************************************************************************/ package org.aspectj.lang.reflect; import org.aspectj.lang.Signature; public interface UnlockSignature extends Signature { }
3e117d22cfbd364ce2383b2494e62e70e7da2793
9,024
java
Java
components/camel-aws/src/main/java/org/apache/camel/component/aws/sqs/SqsEndpoint.java
cerker/camel
f5b73ce48ba8e5bf58495ad2dff0896d83bffa61
[ "Apache-2.0" ]
null
null
null
components/camel-aws/src/main/java/org/apache/camel/component/aws/sqs/SqsEndpoint.java
cerker/camel
f5b73ce48ba8e5bf58495ad2dff0896d83bffa61
[ "Apache-2.0" ]
null
null
null
components/camel-aws/src/main/java/org/apache/camel/component/aws/sqs/SqsEndpoint.java
cerker/camel
f5b73ce48ba8e5bf58495ad2dff0896d83bffa61
[ "Apache-2.0" ]
null
null
null
41.777778
168
0.69559
7,382
/** * 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.component.aws.sqs; import java.util.HashMap; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.CreateQueueRequest; import com.amazonaws.services.sqs.model.CreateQueueResult; import com.amazonaws.services.sqs.model.ListQueuesResult; import com.amazonaws.services.sqs.model.QueueAttributeName; import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; import org.apache.camel.Consumer; import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultExchange; import org.apache.camel.impl.ScheduledPollEndpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Defines the <a href="http://camel.apache.org/aws.html">AWS SQS Endpoint</a>. * */ public class SqsEndpoint extends ScheduledPollEndpoint { private static final transient Logger LOG = LoggerFactory.getLogger(SqsEndpoint.class); private AmazonSQSClient client; private String queueUrl; private SqsConfiguration configuration; private int maxMessagesPerPoll; public SqsEndpoint(String uri, SqsComponent component, SqsConfiguration configuration) { super(uri, component); this.configuration = configuration; } public Producer createProducer() throws Exception { return new SqsProducer(this); } public Consumer createConsumer(Processor processor) throws Exception { SqsConsumer sqsConsumer = new SqsConsumer(this, processor); configureConsumer(sqsConsumer); sqsConsumer.setMaxMessagesPerPoll(maxMessagesPerPoll); return sqsConsumer; } public boolean isSingleton() { return true; } @Override protected void doStart() throws Exception { client = getConfiguration().getAmazonSQSClient() != null ? getConfiguration().getAmazonSQSClient() : getClient(); // check whether the queue already exists ListQueuesResult listQueuesResult = client.listQueues(); for (String url : listQueuesResult.getQueueUrls()) { if (url.endsWith("/" + configuration.getQueueName())) { queueUrl = url; LOG.trace("Queue available at '{}'.", queueUrl); break; } } if (queueUrl == null) { createQueue(client); } else { updateQueueAttributes(client); } } private void createQueue(AmazonSQSClient client) { LOG.trace("Queue '{}' doesn't exist. Will create it...", configuration.getQueueName()); // creates a new queue, or returns the URL of an existing one CreateQueueRequest request = new CreateQueueRequest(configuration.getQueueName()); if (getConfiguration().getDefaultVisibilityTimeout() != null) { request.getAttributes().put(QueueAttributeName.VisibilityTimeout.name(), String.valueOf(getConfiguration().getDefaultVisibilityTimeout())); } if (getConfiguration().getMaximumMessageSize() != null) { request.getAttributes().put(QueueAttributeName.MaximumMessageSize.name(), String.valueOf(getConfiguration().getMaximumMessageSize())); } if (getConfiguration().getMessageRetentionPeriod() != null) { request.getAttributes().put(QueueAttributeName.MessageRetentionPeriod.name(), String.valueOf(getConfiguration().getMessageRetentionPeriod())); } if (getConfiguration().getPolicy() != null) { request.getAttributes().put(QueueAttributeName.Policy.name(), String.valueOf(getConfiguration().getPolicy())); } if (getConfiguration().getReceiveMessageWaitTimeSeconds() != null) { request.getAttributes().put(QueueAttributeName.ReceiveMessageWaitTimeSeconds.name(), String.valueOf(getConfiguration().getReceiveMessageWaitTimeSeconds())); } LOG.trace("Creating queue [{}] with request [{}]...", configuration.getQueueName(), request); CreateQueueResult queueResult = client.createQueue(request); queueUrl = queueResult.getQueueUrl(); LOG.trace("Queue created and available at: {}", queueUrl); } private void updateQueueAttributes(AmazonSQSClient client) { SetQueueAttributesRequest request = new SetQueueAttributesRequest(); request.setQueueUrl(queueUrl); if (getConfiguration().getDefaultVisibilityTimeout() != null) { request.getAttributes().put(QueueAttributeName.VisibilityTimeout.name(), String.valueOf(getConfiguration().getDefaultVisibilityTimeout())); } if (getConfiguration().getMaximumMessageSize() != null) { request.getAttributes().put(QueueAttributeName.MaximumMessageSize.name(), String.valueOf(getConfiguration().getMaximumMessageSize())); } if (getConfiguration().getMessageRetentionPeriod() != null) { request.getAttributes().put(QueueAttributeName.MessageRetentionPeriod.name(), String.valueOf(getConfiguration().getMessageRetentionPeriod())); } if (getConfiguration().getPolicy() != null) { request.getAttributes().put(QueueAttributeName.Policy.name(), String.valueOf(getConfiguration().getPolicy())); } if (getConfiguration().getReceiveMessageWaitTimeSeconds() != null) { request.getAttributes().put(QueueAttributeName.ReceiveMessageWaitTimeSeconds.name(), String.valueOf(getConfiguration().getReceiveMessageWaitTimeSeconds())); } if (!request.getAttributes().isEmpty()) { LOG.trace("Updating queue '{}' with the provided queue attributes...", configuration.getQueueName()); client.setQueueAttributes(request); LOG.trace("Queue '{}' updated and available at {}'", configuration.getQueueName(), queueUrl); } } @Override protected void doStop() throws Exception { client = null; } public Exchange createExchange(com.amazonaws.services.sqs.model.Message msg) { return createExchange(getExchangePattern(), msg); } private Exchange createExchange(ExchangePattern pattern, com.amazonaws.services.sqs.model.Message msg) { Exchange exchange = new DefaultExchange(this, pattern); Message message = exchange.getIn(); message.setBody(msg.getBody()); message.setHeaders(new HashMap<String, Object>(msg.getAttributes())); message.setHeader(SqsConstants.MESSAGE_ID, msg.getMessageId()); message.setHeader(SqsConstants.MD5_OF_BODY, msg.getMD5OfBody()); message.setHeader(SqsConstants.RECEIPT_HANDLE, msg.getReceiptHandle()); message.setHeader(SqsConstants.ATTRIBUTES, msg.getAttributes()); return exchange; } public SqsConfiguration getConfiguration() { return configuration; } public void setConfiguration(SqsConfiguration configuration) { this.configuration = configuration; } public AmazonSQSClient getClient() { if (client == null) { client = createClient(); } return client; } public void setClient(AmazonSQSClient client) { this.client = client; } /** * Provide the possibility to override this method for an mock implementation * @return AmazonSQSClient */ AmazonSQSClient createClient() { AWSCredentials credentials = new BasicAWSCredentials(configuration.getAccessKey(), configuration.getSecretKey()); AmazonSQSClient client = new AmazonSQSClient(credentials); if (configuration.getAmazonSQSEndpoint() != null) { client.setEndpoint(configuration.getAmazonSQSEndpoint()); } return client; } protected String getQueueUrl() { return queueUrl; } public int getMaxMessagesPerPoll() { return maxMessagesPerPoll; } public void setMaxMessagesPerPoll(int maxMessagesPerPoll) { this.maxMessagesPerPoll = maxMessagesPerPoll; } }
3e117d587bf61135999b564068e71abc88b71b3f
810
java
Java
service/src/main/java/uk/gov/hmcts/reform/fpl/service/orders/docmosis/C23EPODocmosisParameters.java
damongreen123/fpl-ccd-configuration
722138312853574b35285e24fdc15dc30b3cb73e
[ "MIT" ]
6
2019-08-16T12:58:12.000Z
2021-09-27T09:04:36.000Z
service/src/main/java/uk/gov/hmcts/reform/fpl/service/orders/docmosis/C23EPODocmosisParameters.java
damongreen123/fpl-ccd-configuration
722138312853574b35285e24fdc15dc30b3cb73e
[ "MIT" ]
2,084
2018-10-02T16:15:34.000Z
2022-03-31T18:04:14.000Z
service/src/main/java/uk/gov/hmcts/reform/fpl/service/orders/docmosis/C23EPODocmosisParameters.java
damongreen123/fpl-ccd-configuration
722138312853574b35285e24fdc15dc30b3cb73e
[ "MIT" ]
7
2018-11-29T18:05:37.000Z
2022-01-25T13:57:25.000Z
27
66
0.796296
7,383
package uk.gov.hmcts.reform.fpl.service.orders.docmosis; import lombok.EqualsAndHashCode; import lombok.ToString; import lombok.Value; import lombok.experimental.SuperBuilder; import uk.gov.hmcts.reform.fpl.enums.EPOType; import uk.gov.hmcts.reform.fpl.enums.GeneratedOrderType; @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) @Value @SuperBuilder(toBuilder = true) public class C23EPODocmosisParameters extends DocmosisParameters { GeneratedOrderType orderType; String orderDetails; String furtherDirections; String localAuthorityName; EPOType epoType; String includePhrase; String childrenDescription; String epoStartDateTime; String epoEndDateTime; String removalAddress; String exclusionRequirement; boolean powerOfArrestFileAttached; }
3e117df1dea58501a26a20e45c1cd72234fe0644
297
java
Java
biz.aQute.bndlib.tests/src/test/uses/param/UsesParam.java
mcculls/bnd
f553787d0e339948b01085545e291f63d0e9175c
[ "Apache-2.0" ]
1
2022-03-23T14:00:11.000Z
2022-03-23T14:00:11.000Z
biz.aQute.bndlib.tests/src/test/uses/param/UsesParam.java
mcculls/bnd
f553787d0e339948b01085545e291f63d0e9175c
[ "Apache-2.0" ]
1
2018-07-31T09:47:46.000Z
2020-10-10T18:55:13.000Z
biz.aQute.bndlib.tests/src/test/uses/param/UsesParam.java
mcculls/bnd
f553787d0e339948b01085545e291f63d0e9175c
[ "Apache-2.0" ]
1
2021-01-26T10:41:39.000Z
2021-01-26T10:41:39.000Z
16.5
45
0.747475
7,384
package test.uses.param; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; public class UsesParam { public static void foo(Callback config) { Subject subject = new Subject(); } @SuppressWarnings("unused") private static void bar(Subject subject) { } }
3e117e5c94e18e068e91949e1950c5247063624b
1,292
java
Java
smallrye-reactive-messaging-camel/src/main/java/io/smallrye/reactive/messaging/camel/OutgoingExchangeMetadata.java
jogueber/smallrye-reactive-messaging
4af403aed8d0bd19781af2b7429de8af0d7024e5
[ "Apache-2.0" ]
145
2018-11-05T13:38:46.000Z
2022-03-30T19:01:57.000Z
smallrye-reactive-messaging-camel/src/main/java/io/smallrye/reactive/messaging/camel/OutgoingExchangeMetadata.java
jogueber/smallrye-reactive-messaging
4af403aed8d0bd19781af2b7429de8af0d7024e5
[ "Apache-2.0" ]
885
2018-11-13T09:00:34.000Z
2022-03-31T16:57:44.000Z
smallrye-reactive-messaging-camel/src/main/java/io/smallrye/reactive/messaging/camel/OutgoingExchangeMetadata.java
jogueber/smallrye-reactive-messaging
4af403aed8d0bd19781af2b7429de8af0d7024e5
[ "Apache-2.0" ]
132
2018-12-17T08:30:18.000Z
2022-03-30T08:01:52.000Z
24.846154
81
0.686533
7,385
package io.smallrye.reactive.messaging.camel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.camel.ExchangePattern; public class OutgoingExchangeMetadata { private Map<String, Object> properties = new ConcurrentHashMap<>(); private Map<String, Object> headers = new ConcurrentHashMap<>(); private ExchangePattern pattern; public OutgoingExchangeMetadata putProperty(String name, Object value) { properties.put(name, value); return this; } public OutgoingExchangeMetadata removeProperty(String name) { properties.remove(name); return this; } public Map<String, Object> getProperties() { return properties; } public OutgoingExchangeMetadata putHeader(String name, Object value) { headers.put(name, value); return this; } public OutgoingExchangeMetadata removeHeader(String name) { headers.remove(name); return this; } public Map<String, Object> getHeaders() { return headers; } public OutgoingExchangeMetadata setExchangePattern(ExchangePattern pattern) { this.pattern = pattern; return this; } public ExchangePattern getExchangePattern() { return pattern; } }
3e117e84a37023a37013c95a5becddecc78f48bf
7,042
java
Java
src/main/java/org/jhove2/module/format/tiff/profile/TiffITBLP1Profile.java
opf-labs/jhove2
cae9ab898bcc82b9623539f161bc4d749b365a48
[ "BSD-2-Clause" ]
11
2015-02-03T19:52:39.000Z
2020-03-24T11:25:29.000Z
src/main/java/org/jhove2/module/format/tiff/profile/TiffITBLP1Profile.java
opf-labs/jhove2
cae9ab898bcc82b9623539f161bc4d749b365a48
[ "BSD-2-Clause" ]
1
2015-05-12T12:03:52.000Z
2015-05-12T12:24:08.000Z
src/main/java/org/jhove2/module/format/tiff/profile/TiffITBLP1Profile.java
opf-labs/jhove2
cae9ab898bcc82b9623539f161bc4d749b365a48
[ "BSD-2-Clause" ]
1
2015-04-30T11:02:02.000Z
2015-04-30T11:02:02.000Z
41.181287
118
0.629509
7,386
/** * JHOVE2 - Next-generation architecture for format-aware characterization * * Copyright (c) 2009 by The Regents of the University of California, Ithaka * Harbors, Inc., and The Board of Trustees of the Leland Stanford Junior * University. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of the University of California/California Digital * Library, Ithaka Harbors/Portico, or Stanford University, nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.jhove2.module.format.tiff.profile; import org.jhove2.core.JHOVE2; import org.jhove2.core.JHOVE2Exception; import org.jhove2.core.Message; import org.jhove2.core.Message.Context; import org.jhove2.core.Message.Severity; import org.jhove2.core.format.Format; import org.jhove2.module.format.tiff.TiffIFD; import org.jhove2.persist.FormatProfileAccessor; import com.sleepycat.persist.model.Persistent; /** * @author MStrong * */ @Persistent public class TiffITBLP1Profile extends TiffItProfile { /** Profile version identifier. */ public static final String VERSION = "2.0.0"; /** Profile release date. */ public static final String RELEASE = "2010-09-10"; /** Profile rights statement. */ public static final String RIGHTS = "Copyright 2010 by The Regents of the University of California. " + "Available under the terms of the BSD license."; /** Profile validation coverage. */ public static final Coverage COVERAGE = Coverage.Inclusive; /** * * @param format * @param formatProfileAccessor */ public TiffITBLP1Profile(Format format, FormatProfileAccessor formatProfileAccessor) { super(format, formatProfileAccessor); } @SuppressWarnings("unused") private TiffITBLP1Profile(){ this(null,null); } /* * (non-Javadoc) * * @see * org.jhove2.module.format.tiff.profile.TiffProfile#validateThisProfile() */ @Override public void validateThisProfile(JHOVE2 jhove2, TiffIFD ifd) throws JHOVE2Exception { /* Check required tags. */ super.validateThisProfile(jhove2, ifd); /* Check required values. */ int[] bps = ifd.getBitsPerSample(); if (bps == null || (bps[0] != 1)) { this.isValid = Validity.False; Object[] args = new Object[] { 1 }; this.invalidBPSValueMessage = new Message( Severity.WARNING, Context.OBJECT, "org.jhove2.module.format.tiff.profile.TIFFITProfile.InvalidBPSValueMessage", args, jhove2.getConfigInfo()); } if (!isCompressionValid(ifd, 32898)) { this.isValid = Validity.False; Object[] args = new Object[] { 32898 }; this.invalidCompressionValueMessage = new Message( Severity.WARNING, Context.OBJECT, "org.jhove2.module.format.tiff.profile.TIFFITProfile.InvalidCompressionValueMessage", args, jhove2.getConfigInfo()); } if (!isPhotometricInterpretationValid(ifd, new int[] { 0, 1 })) { this.isValid = Validity.False; this.invalidPhotometricInterpretationValueMessage = new Message( Severity.WARNING, Context.OBJECT, "org.jhove2.module.format.tiff.profile.TIFFProfile.InvalidPhotometricInterpretationValueMessage", jhove2.getConfigInfo()); } if (!isSamplesPerPixelValid(ifd, 1)) { this.isValid = Validity.False; Object[] args = new Object[] { 1 }; this.invalidSPPValueMessage = new Message( Severity.WARNING, Context.OBJECT, "org.jhove2.module.format.tiff.profile.TIFFITProfile.InvalidSPPValueMessage", args, jhove2.getConfigInfo()); } int[] validValues; /* ImageColorIndicator=1, but only if ImageColorValue is defined */ if ((ifd.getEntries().get(TiffIFD.IMAGECOLORVALUE)) != null) validValues = new int[] { 1 }; else { /* ImageColorIndicator=0,1,2 */ validValues = new int[] { 0, 1, 2 }; } if (!isImageColorIndicatorValid(ifd, validValues)) { this.isValid = Validity.False; this.invalidImageColorIndicatorMessage = new Message( Severity.WARNING, Context.OBJECT, "org.jhove2.module.format.tiff.profile.TIFFITProfile.InvalidImageColorIndicatorMessage", jhove2.getConfigInfo()); } /* * BackgroundColorIndicator=0,1, or 2; BackgroundColorIndicator=1, but * only if BackgroundColorValue is defined. */ if ((ifd.getEntries().get(TiffIFD.BACKGROUNDCOLORVALUE)) != null) { validValues = new int[] { 1 }; } else { validValues = new int[] { 0, 1, 2 }; } if (!isBackgroundColorIndicatorValid(ifd, validValues)) { this.isValid = Validity.False; this.invalidBackgroundColorIndicatorMessage = new Message( Severity.WARNING, Context.OBJECT, "org.jhove2.module.format.tiff.profile.TIFFITProfile.InvalidBackgroundColorIndicatorMessage", jhove2.getConfigInfo()); } } }
3e117e9c8e47274f3e7627ab7b540a391765cff0
1,190
java
Java
javalin-service/src/test/java/org/example/web/IntegrationTest.java
avaje-metrics/examples
cdcc2e7ca77ac357a85e68a9f9d82ffd3e5a7c45
[ "Apache-2.0" ]
null
null
null
javalin-service/src/test/java/org/example/web/IntegrationTest.java
avaje-metrics/examples
cdcc2e7ca77ac357a85e68a9f9d82ffd3e5a7c45
[ "Apache-2.0" ]
null
null
null
javalin-service/src/test/java/org/example/web/IntegrationTest.java
avaje-metrics/examples
cdcc2e7ca77ac357a85e68a9f9d82ffd3e5a7c45
[ "Apache-2.0" ]
null
null
null
25.319149
95
0.67479
7,387
package org.example.web; import io.javalin.Javalin; import kong.unirest.GenericType; import kong.unirest.HttpResponse; import kong.unirest.Unirest; import org.example.web.api.Foo; import org.example.web.api.ListResponse; import org.junit.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class IntegrationTest { @Test public void GET_home() { Javalin app = Application.start(9891); try { final HttpResponse<String> res0 = Unirest.get("http://localhost:9891") .header("Content-Type", "application/json") .asString(); assertThat(res0.getStatus()).isEqualTo(200); assertThat(res0.getBody()).isEqualTo("ok"); final HttpResponse<ListResponse<Foo>> res1 = Unirest.get("http://localhost:9891/api/foo") .header("Content-Type", "application/json") .asObject(new GenericType<ListResponse<Foo>>() { }); assertThat(res1.getStatus()).isEqualTo(200); final ListResponse<Foo> body = res1.getBody(); final List<Foo> list = body.getList(); assertThat(list).isNotNull(); assertThat(list).hasSize(2); } finally { app.stop(); } } }
3e117f0690557bfd88f121a84b767ca8a670e25f
1,684
java
Java
java/core/Java7NewFeaturesCookbook/src/main/java/org/nandao/cap06/p01ManagingSimpleFiles/Test.java
fernando-romulo-silva/myStudies
33097bb4f5441a64f3647d8eceec4550c84822dc
[ "Apache-2.0" ]
1
2020-12-02T19:03:30.000Z
2020-12-02T19:03:30.000Z
java/core/Java7NewFeaturesCookbook/src/main/java/org/nandao/cap06/p01ManagingSimpleFiles/Test.java
fernando-romulo-silva/myStudies
33097bb4f5441a64f3647d8eceec4550c84822dc
[ "Apache-2.0" ]
4
2021-08-02T23:29:06.000Z
2021-09-28T22:43:34.000Z
java/core/Java7NewFeaturesCookbook/src/main/java/org/nandao/cap06/p01ManagingSimpleFiles/Test.java
fernando-romulo-silva/myStudies
33097bb4f5441a64f3647d8eceec4550c84822dc
[ "Apache-2.0" ]
null
null
null
35.083333
113
0.688242
7,388
package org.nandao.cap06.p01ManagingSimpleFiles; import java.io.File; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; // Some files are small and contain simple data. This is usually true for text files. When it is // feasible to read or write the entire contents of the file at one time, there are a few Files // class methods that will work quite well. // // In this recipe, we will examine techniques for processing simple files. Initially, we will // examine how to read the contents of these types of files. public class Test { public static void main(String[] args) throws Exception { test0(); } public static void test0() throws Exception { final ClassLoader classLoader = Test.class.getClassLoader(); final Path pathSource = Paths.get(new File(classLoader.getResource("Home").getFile()).getAbsolutePath()); final Path path = Paths.get(pathSource + "/Docs/users.txt"); final byte[] contents = Files.readAllBytes(path); for (final byte b : contents) { System.out.print((char) b); } final Path newPath = Paths.get(pathSource + "/Docs/newUsers.txt"); final byte[] newContent = "Christopher".getBytes(); Files.write(newPath, contents, StandardOpenOption.CREATE); Files.write(newPath, newContent, StandardOpenOption.APPEND); final List<String> newContents = Files.readAllLines(newPath, Charset.defaultCharset()); for (final String b : newContents) { System.out.println(b); } } }
3e117f6754d5fa72b2fe5d9cc9329714578b9c1b
3,229
java
Java
src/main/java/com/webcheckers/ui/PostGameRoute.java
samuelkeir98/WebCheckers
dcccd29d67925d71274e5a7b891ce7adbd510404
[ "MIT" ]
null
null
null
src/main/java/com/webcheckers/ui/PostGameRoute.java
samuelkeir98/WebCheckers
dcccd29d67925d71274e5a7b891ce7adbd510404
[ "MIT" ]
null
null
null
src/main/java/com/webcheckers/ui/PostGameRoute.java
samuelkeir98/WebCheckers
dcccd29d67925d71274e5a7b891ce7adbd510404
[ "MIT" ]
1
2019-03-10T17:52:39.000Z
2019-03-10T17:52:39.000Z
36.693182
103
0.67668
7,389
package com.webcheckers.ui; import com.webcheckers.appl.GameLobby; import com.webcheckers.appl.PlayerLobby; import com.webcheckers.model.Color; import com.webcheckers.model.Game; import com.webcheckers.model.Player; import spark.*; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * UI Controller for POST /game * * @author Andy Gin */ public class PostGameRoute implements Route { public static final String CURRENT_PLAYER_ATTR = "currentPlayer"; public static final String VIEW_MODE_ATTR = "viewMode"; public static final String RED_PLAYER_ATTR = "redPlayer"; public static final String WHITE_PLAYER_ATTR = "whitePlayer"; public static final String ACTIVE_COLOR_ATTR = "activeColor"; public static final String BOARD_ATTR = "board"; public static final String TEMPLATE_NAME = "game.ftl"; public static final String OPPONENT_SPECTATING = "Player spectating a game!"; public static final String OPPONENT_BUSY = "Player already in game!"; private final TemplateEngine templateEngine; private final GameLobby gameLobby; private final PlayerLobby playerLobby; /** * Create the spark component for the * {@code POST /game} HTTP request. * @param templateEngine ftl engine * @param gameLobby keeps track of games */ public PostGameRoute(TemplateEngine templateEngine, GameLobby gameLobby, PlayerLobby playerLobby) { this.gameLobby = gameLobby; this.playerLobby = playerLobby; Objects.requireNonNull(templateEngine, "templateEngine must not be null"); this.templateEngine = templateEngine; } /** * Renders game page if opponent not in game * @param request HTTP request object * @param response HTTP response object * @return rendered game page */ @Override public Object handle(Request request, Response response) { final String opponent = request.queryParams("name"); final Map<String, Object> vm = new HashMap<>(); vm.put("title", "Game"); Player player1 = request.session().attribute(PostSigninRoute.PLAYER_KEY); Player player2 = playerLobby.getPlayer(opponent); if(!gameLobby.inGame(player2) && !gameLobby.isSpectating(player2)) { Game game = new Game(player1, player2); gameLobby.enterGame(player2, game); gameLobby.enterGame(player1, game); ViewMode view = ViewMode.PLAY; vm.put(CURRENT_PLAYER_ATTR, player1); vm.put(VIEW_MODE_ATTR, view); vm.put(RED_PLAYER_ATTR, player1); vm.put(WHITE_PLAYER_ATTR, player2); vm.put(ACTIVE_COLOR_ATTR, game.getCurPlayer() == player1 ? Color.RED : Color.WHITE); vm.put(BOARD_ATTR, new BoardView(game.getBoard(),Color.RED)); return templateEngine.render(new ModelAndView(vm, TEMPLATE_NAME)); } else { if(gameLobby.inGame(player2)) request.session().attribute("message", OPPONENT_BUSY); else request.session().attribute("message", OPPONENT_SPECTATING); response.redirect(WebServer.HOME_URL); return null; } } }
3e117fa2ed085eac74bc78b14f532c9a4b916ea5
1,542
java
Java
src/main/java/Controller/IAiMovable.java
Epirius/Chess_OOP
6e82bfe518abbb2a5fa44eb2368dc64f27ea6b41
[ "MIT" ]
null
null
null
src/main/java/Controller/IAiMovable.java
Epirius/Chess_OOP
6e82bfe518abbb2a5fa44eb2368dc64f27ea6b41
[ "MIT" ]
null
null
null
src/main/java/Controller/IAiMovable.java
Epirius/Chess_OOP
6e82bfe518abbb2a5fa44eb2368dc64f27ea6b41
[ "MIT" ]
null
null
null
20.837838
102
0.597276
7,390
package Controller; import Model.Move; import Model.Pieces.Piece; import Model.Team; import Model.Type; import java.util.List; /** * @author Felix Kaasa */ public interface IAiMovable { /** * get piece at square * @param id of the square that you want the piece from * @return a Piece from the given square */ Piece getPiece(int id); /** * @return returns a list of all current pieces on the board */ List<Piece> getAllPieces(); /** * a method to send moves to. * @param move move to be made. */ void doMove(Move move); /** * method to undo the last move. */ void undoMove(); /** * finds all legal move for the current player. * @return List<Move> */ List<Move> getLegalMoves(); /** * gets the current score of the game, positive if white is winning, negative if black is winning. * @return score of the current game */ int getScore(); /** * gets the move id of the last turn * @return int number of turns that have been made since the start. */ int getCurrentTurn(); /** * method to upgrade a pawn when it gets to the last row * @param type QUEEN, ROOK, BISHOP or KNIGHT */ void upgradePawn(Type type); /** * gets the team of the current player * @return Team.WHITE or Team.BLACK. */ Team getTeam(); /** * a method to get the last move from the moveHistoryList * @return Move */ Move getLastMove(); }
3e117fca60eedd9017cff96b037be0d014de9552
1,343
java
Java
TcBrowse/browse/src/main/java/com/tamic/jswebview/browse/JsWeb/CustomWebViewClient.java
Tamicer/JsWebView
00a4ab753360422b89453abbdb5e002eb3835a3e
[ "Apache-2.0" ]
166
2016-12-02T08:22:40.000Z
2021-12-27T04:12:44.000Z
TcBrowse/browse/src/main/java/com/tamic/jswebview/browse/JsWeb/CustomWebViewClient.java
NeglectedByBoss/JsWebView
00a4ab753360422b89453abbdb5e002eb3835a3e
[ "Apache-2.0" ]
4
2017-02-07T05:57:50.000Z
2018-10-29T02:45:27.000Z
TcBrowse/browse/src/main/java/com/tamic/jswebview/browse/JsWeb/CustomWebViewClient.java
Tamicer/JsWebView
00a4ab753360422b89453abbdb5e002eb3835a3e
[ "Apache-2.0" ]
48
2016-12-02T08:22:41.000Z
2021-05-24T11:15:53.000Z
22.383333
72
0.657483
7,391
package com.tamic.jswebview.browse.JsWeb; import android.support.annotation.NonNull; import android.webkit.WebView; import com.tamic.jswebview.browse.BridgeWebView; import com.tamic.jswebview.browse.BridgeWebViewClient; import java.util.Map; /** * Class description * * @author YEZHENNAN220 * @date 2016-07-08 13:54 */ public abstract class CustomWebViewClient extends BridgeWebViewClient { public CustomWebViewClient(BridgeWebView webView) { super(webView); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (onPageHeaders(url) != null) { view.loadUrl(url, onPageHeaders(url)); } return super.shouldOverrideUrlLoading(view, url); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { view.loadUrl(onPageError(failingUrl)); } /** * return errorUrl * @param url * @return */ public abstract String onPageError(String url); /** * HttpHeaders * return * @return */ @NonNull public abstract Map<String, String> onPageHeaders(String url); }
3e11804fb812ea3b2e9d898e0412f589855ed2b4
1,326
java
Java
src/main/java/net/es/nsi/pce/visualization/Display.java
BandwidthOnDemand/nsi-pce
2b3807259b1bdb59806e3683df80b8ab6eee046d
[ "BSD-3-Clause-LBNL" ]
1
2015-03-10T19:47:57.000Z
2015-03-10T19:47:57.000Z
src/main/java/net/es/nsi/pce/visualization/Display.java
BandwidthOnDemand/nsi-pce
2b3807259b1bdb59806e3683df80b8ab6eee046d
[ "BSD-3-Clause-LBNL" ]
10
2015-05-29T16:38:39.000Z
2021-12-13T14:01:57.000Z
src/main/java/net/es/nsi/pce/visualization/Display.java
BandwidthOnDemand/nsi-pce
2b3807259b1bdb59806e3683df80b8ab6eee046d
[ "BSD-3-Clause-LBNL" ]
1
2015-12-08T20:16:00.000Z
2015-12-08T20:16:00.000Z
27.625
88
0.629713
7,392
package net.es.nsi.pce.visualization; import java.awt.Color; /** * * @author hacksaw */ public class Display { public static final int maxX = 1200; public static final int maxY = 1000; public static final float centerX = maxX / 2; public static final float centerY = maxY / 2; public static final Color backgroundColor = Color.WHITE; static public int getX(float longitude) { return Math.round(centerX + ((longitude * centerX) / 180.0f)); } static public int getY(float latitude) { return Math.round(centerY + ((latitude * centerY) / 180.0f)); } /** * Get the coordinates associated with the specified network. * * @param longitude * @param latitude * @return Coordinates of network. */ public static CartesianCoordinates getCoordinates(float longitude, float latitude) { return new CartesianCoordinates(getX(longitude), getY(latitude)); } public static CartesianCoordinates getRandomCoordinates() { return getCoordinates( (float) getRandomInRange(-180, 180), (float) getRandomInRange(-180, 180) ); } public static double getRandomInRange(double from, double to) { return Math.random() * (to - from) + from; } }
3e11807a381beeb993fccd3ab105dfea42f061a9
3,193
java
Java
data-service/src/contract-tests/java/uk/gov/gchq/palisade/contract/data/rest/HealthActuatorContractTest.java
gchq/Palisade-services
105c35f7fe42216858cb1011c749e6f5db76b86f
[ "Apache-2.0", "CC-BY-4.0" ]
3
2020-07-13T09:43:55.000Z
2021-01-07T12:44:52.000Z
data-service/src/contract-tests/java/uk/gov/gchq/palisade/contract/data/rest/HealthActuatorContractTest.java
gchq/Palisade-services
105c35f7fe42216858cb1011c749e6f5db76b86f
[ "Apache-2.0", "CC-BY-4.0" ]
66
2019-10-03T14:47:59.000Z
2022-01-24T03:36:02.000Z
data-service/src/contract-tests/java/uk/gov/gchq/palisade/contract/data/rest/HealthActuatorContractTest.java
gchq/Palisade-services
105c35f7fe42216858cb1011c749e6f5db76b86f
[ "Apache-2.0", "CC-BY-4.0" ]
4
2020-05-07T20:39:11.000Z
2021-05-19T04:55:21.000Z
40.935897
119
0.724084
7,393
/* * Copyright 2018-2021 Crown Copyright * * 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.gov.gchq.palisade.contract.data.rest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import uk.gov.gchq.palisade.service.data.DataApplication; import uk.gov.gchq.palisade.service.data.web.AkkaHttpServer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; /** * SpringBoot Starter Actuator is a service loaded-up by adding the spring-boot-starter-actuator as a dependency to the * project and configured in the application.yaml file. It is a service which provides information on the application * and is being used to monitor the "health" of the palisade service. If there is an indication that this service has * fallen over, this information can be used to restore the service. */ @SpringBootTest( classes = {DataApplication.class}, webEnvironment = WebEnvironment.MOCK, properties = {"management.health.kafka.enabled=false", "server.port=0"} ) @ActiveProfiles("akka-test") class HealthActuatorContractTest { private TestRestTemplate restTemplate; @Autowired private AkkaHttpServer akkaHttpServer; @BeforeEach void setUp() { var localAddress = akkaHttpServer.getServerBinding().join().localAddress(); var rootUri = "http://localhost:" + localAddress.getPort(); restTemplate = new TestRestTemplate(new RestTemplateBuilder().rootUri(rootUri)); } @Test void testContextLoads() { assertThat(restTemplate).isNotNull(); } @Test void testServiceIsHealthy() { ResponseEntity<String> responseEntity = restTemplate.getForEntity("/actuator/health", String.class); assertAll("Assert the Health Actuator", () -> assertThat(responseEntity.getStatusCode()) .as("Check the status code of the response") .isEqualTo(HttpStatus.OK), () -> assertThat(responseEntity.getBody()) .as("Check the body of the response") .contains("\"status\":\"UP\"") ); } }
3e1180ea108383c79c463cc7e563aa04f24cb80f
3,889
java
Java
components/components-marketo/components-marketo-definition/src/main/java/org/talend/components/marketo/helpers/MarketoColumnMappingsTable.java
wwang-talend/components
273af8f4ec300684c65b8afef23b96107680f8d9
[ "Apache-2.0" ]
53
2016-03-06T10:52:48.000Z
2020-12-09T15:11:21.000Z
components/components-marketo/components-marketo-definition/src/main/java/org/talend/components/marketo/helpers/MarketoColumnMappingsTable.java
wwang-talend/components
273af8f4ec300684c65b8afef23b96107680f8d9
[ "Apache-2.0" ]
1,727
2016-01-28T09:05:53.000Z
2022-03-29T05:59:55.000Z
components/components-marketo/components-marketo-definition/src/main/java/org/talend/components/marketo/helpers/MarketoColumnMappingsTable.java
wwang-talend/components
273af8f4ec300684c65b8afef23b96107680f8d9
[ "Apache-2.0" ]
112
2016-01-28T03:27:24.000Z
2021-10-13T02:58:54.000Z
33.817391
105
0.608897
7,394
// ============================================================================ // // Copyright (C) 2006-2019 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.components.marketo.helpers; import static org.talend.daikon.properties.property.PropertyFactory.newProperty; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.TypeLiteral; import org.talend.components.common.BasedOnSchemaTable; import org.talend.daikon.avro.SchemaConstants; import org.talend.daikon.properties.presentation.Form; import org.talend.daikon.properties.property.Property; public class MarketoColumnMappingsTable extends BasedOnSchemaTable { private static final TypeLiteral<List<String>> LIST_STRING_TYPE = new TypeLiteral<List<String>>() { }; public Property<List<String>> marketoColumnName = newProperty(LIST_STRING_TYPE, "marketoColumnName"); private static final long serialVersionUID = 3473102423403696522L; public MarketoColumnMappingsTable(String name) { super(name); } @Override public void setupProperties() { super.setupProperties(); } @Override public void setupLayout() { super.setupLayout(); Form mainForm = getForm(Form.MAIN); mainForm.addColumn(marketoColumnName); } public Map<String, String> getNameMappingsForMarketo() { Map<String, String> result = new HashMap<>(); List<String> value = columnName.getValue(); if (value == null || value.isEmpty()) { return result; } for (int i = 0; i < value.size(); i++) { String schemaCol = value.get(i); String marketoCol = marketoColumnName.getValue().get(i); if (marketoCol == null || marketoCol.isEmpty()) { marketoCol = schemaCol; } result.put(schemaCol, marketoCol); } return result; } public Map<String, String> getInputedNameMappingsForMarketo() { Map<String, String> result = new HashMap<>(); List<String> value = columnName.getValue(); if (value == null || value.isEmpty()) { return result; } for (int i = 0; i < value.size(); i++) { String schemaCol = value.get(i); String marketoCol = marketoColumnName.getValue().get(i); result.put(schemaCol, marketoCol); } return result; } public List<String> getMarketoColumns(Schema schema) { List<String> result = new ArrayList<>(); Map<String, String> mappings = getInputedNameMappingsForMarketo(); String marketoCol = null; String schemaCol = null; for (Field f : schema.getFields()) { marketoCol = mappings.get(f.name()); if (StringUtils.isEmpty(marketoCol)) { schemaCol = f.getProp(SchemaConstants.TALEND_COLUMN_DB_COLUMN_NAME); if (!StringUtils.isEmpty(schemaCol)) { marketoCol = schemaCol; } else { marketoCol = f.name(); } } result.add(marketoCol); } return result; } public int size() { if (marketoColumnName.getValue() == null) { return 0; } return marketoColumnName.getValue().size(); } }
3e11822167c15545ee4070887174af5d9508beb2
2,792
java
Java
src/main/java/com/dalgen/mybatis/model/dbtable/Table.java
wjn161/mybatis-dalgen
514aa50bf0c9f898fa26c239a95a1ee69d4356c5
[ "Apache-2.0" ]
19
2018-05-18T12:43:06.000Z
2021-07-16T04:08:36.000Z
src/main/java/com/dalgen/mybatis/model/dbtable/Table.java
lioutall/mybatis-dalgen
df05e0ce1ed022ea1b69015e4ab0724a7b5c5468
[ "Apache-2.0" ]
1
2019-01-18T14:39:30.000Z
2019-01-19T11:55:35.000Z
src/main/java/com/dalgen/mybatis/model/dbtable/Table.java
lioutall/mybatis-dalgen
df05e0ce1ed022ea1b69015e4ab0724a7b5c5468
[ "Apache-2.0" ]
13
2018-05-09T02:01:04.000Z
2020-10-26T09:48:17.000Z
18.012903
59
0.534742
7,395
package com.dalgen.mybatis.model.dbtable; import com.google.common.collect.Lists; import java.util.List; /** * 表信息 Created by bangis.wangdf on 15/12/4. Desc */ public class Table { /** * The Sql name. */ private String sqlName; /** * The Java name. */ private String javaName; /** * The Remark. */ private String remark; /** * The Column list. */ private List<Column> columnList = Lists.newArrayList(); /** * The Primary keys. */ private PrimaryKeys primaryKeys; /** * The Physical name. */ private String physicalName; /** * Gets primary keys. * * @return the primary keys */ public PrimaryKeys getPrimaryKeys() { return primaryKeys; } /** * Sets primary keys. * * @param primaryKeys the primary keys */ public void setPrimaryKeys(PrimaryKeys primaryKeys) { this.primaryKeys = primaryKeys; } /** * Gets sql name. * * @return the sql name */ public String getSqlName() { return sqlName; } /** * Sets sql name. * * @param sqlName the sql name */ public void setSqlName(String sqlName) { this.sqlName = sqlName; } /** * Gets java name. * * @return the java name */ public String getJavaName() { return javaName; } /** * Sets java name. * * @param javaName the java name */ public void setJavaName(String javaName) { this.javaName = javaName; } /** * Gets remark. * * @return the remark */ public String getRemark() { return remark; } /** * Sets remark. * * @param remark the remark */ public void setRemark(String remark) { this.remark = remark; } /** * Gets column list. * * @return the column list */ public List<Column> getColumnList() { return Lists.newArrayList(columnList); } /** * Add column. * * @param column the column */ public void addColumn(Column column) { this.columnList.add(column); } /** * Sets column list. * * @param columnList the column list */ public void setColumnList(List<Column> columnList) { this.columnList = columnList; } /** * Gets physical name. * * @return the physical name */ public String getPhysicalName() { return physicalName; } /** * Sets physical name. * * @param physicalName the physical name */ public void setPhysicalName(String physicalName) { this.physicalName = physicalName; } }
3e11825d210b92fbecea7808956263d8c1f1667f
2,108
java
Java
vlogpp2/src/apfe/vlogpp2/CellDefine.java
gburdell/apfe
7c6aff9121206bb60be6128fc76d4d49d4d2cfb1
[ "MIT" ]
null
null
null
vlogpp2/src/apfe/vlogpp2/CellDefine.java
gburdell/apfe
7c6aff9121206bb60be6128fc76d4d49d4d2cfb1
[ "MIT" ]
null
null
null
vlogpp2/src/apfe/vlogpp2/CellDefine.java
gburdell/apfe
7c6aff9121206bb60be6128fc76d4d49d4d2cfb1
[ "MIT" ]
null
null
null
32.430769
80
0.68833
7,396
/* * The MIT License * * Copyright 2014 gburdell. * * 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 apfe.vlogpp2; import apfe.runtime.Acceptor; import apfe.runtime.Marker; import apfe.runtime.CharSeq; import apfe.runtime.PrioritizedChoice; /** * * @author gburdell */ public class CellDefine extends Acceptor { @Override protected boolean accepti() { //CellDefine <- "`celldefine" / "`endcelldefine" final Marker start = getStartMark(); PrioritizedChoice p1 = new PrioritizedChoice(new CharSeq("`celldefine"), new CharSeq("`endcelldefine")); boolean match = (null != (p1 = match(p1))); if (match) { m_isBegin = (0 == p1.whichAccepted()); m_text = super.toString(); //Helper.getTheOne().replace(start); } return match; } private boolean m_isBegin; private String m_text; @Override public String toString() { return m_text; } @Override public Acceptor create() { return new CellDefine(); } }
3e11832dffd18607c2e8f24579b92d3ada980f00
9,973
java
Java
src/org/citydb/gui/menubar/InfoDialog.java
Fuxuandi-Michelle/importer-exporter-BuildingADE
27f1581fafcff4f2418ca35184fb0ad8d579906e
[ "Apache-2.0" ]
null
null
null
src/org/citydb/gui/menubar/InfoDialog.java
Fuxuandi-Michelle/importer-exporter-BuildingADE
27f1581fafcff4f2418ca35184fb0ad8d579906e
[ "Apache-2.0" ]
null
null
null
src/org/citydb/gui/menubar/InfoDialog.java
Fuxuandi-Michelle/importer-exporter-BuildingADE
27f1581fafcff4f2418ca35184fb0ad8d579906e
[ "Apache-2.0" ]
1
2019-04-16T04:29:15.000Z
2019-04-16T04:29:15.000Z
43.850877
170
0.704141
7,397
/* * 3D City Database - The Open Source CityGML Database * http://www.3dcitydb.org/ * * Copyright 2013 - 2016 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.gis.bgu.tum.de/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * virtualcitySYSTEMS GmbH, Berlin <http://www.virtualcitysystems.de/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * 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.citydb.gui.menubar; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.MessageFormat; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.text.html.HTMLDocument; import org.citydb.config.Config; import org.citydb.config.language.Language; import org.citydb.config.project.global.LanguageType; import org.citydb.gui.factory.PopupMenuDecorator; import org.citydb.util.gui.GuiUtil; @SuppressWarnings("serial") public class InfoDialog extends JDialog { private final Config config; public InfoDialog(Config config, JFrame frame) { super(frame, Language.I18N.getString("menu.help.info.label"), true); this.config = config; initGUI(); } private void initGUI() { setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); JButton button = new JButton(Language.I18N.getString("common.button.ok")); setLayout(new GridBagLayout()); { JPanel header = new JPanel(); header.setBackground(new Color(255, 255, 255)); add(header, GuiUtil.setConstraints(0,0,1.0,0.0,GridBagConstraints.BOTH,0,0,0,0)); header.setLayout(new GridBagLayout()); { String name = this.getClass().getPackage().getImplementationTitle(); String version = this.getClass().getPackage().getImplementationVersion(); JLabel titel = new JLabel(); titel.setText("<html><body><b>" + name + "</b><br>" + "Version " + version + "</body></html>"); GridBagConstraints c = GuiUtil.setConstraints(0,0,1.0,1.0,GridBagConstraints.HORIZONTAL,10,5,0,20); c.anchor = GridBagConstraints.NORTHEAST; header.add(titel, c); JLabel img = new JLabel(new ImageIcon(getToolkit().getImage(this.getClass().getResource("/resources/img/common/logo.png")))); header.add(img, GuiUtil.setConstraints(1,0,0.0,1.0,GridBagConstraints.NONE,5,0,5,10)); } JSeparator sep = new JSeparator(JSeparator.HORIZONTAL); sep.setMinimumSize(sep.getPreferredSize()); add(sep, GuiUtil.setConstraints(0,1,0.0,0.0,GridBagConstraints.BOTH,0,0,0,0)); JTabbedPane tabs = new JTabbedPane(); add(tabs, GuiUtil.setConstraints(0,2,1.0,1.0,GridBagConstraints.BOTH,5,5,5,5)); tabs.add(getGeneralTab(), Language.I18N.getString("menu.help.info.tab.general")); tabs.add(getPartnerTab(), Language.I18N.getString("menu.help.info.tab.partner")); button.setMargin(new Insets(button.getMargin().top, 25, button.getMargin().bottom, 25)); add(button, GuiUtil.setConstraints(0,3,0.0,0.0,GridBagConstraints.NONE,5,5,5,5)); } setMinimumSize(new Dimension(400, 450)); setResizable(true); pack(); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { dispose(); } }); } }); } private JPanel getGeneralTab() { JPanel general = new JPanel(); general.setLayout(new GridBagLayout()); { Border border = BorderFactory.createEtchedBorder(); Border margin = BorderFactory.createEmptyBorder(2, 2, 2, 2); JLabel authorsHeader = new JLabel(Language.I18N.getString("menu.help.info.authors")); general.add(authorsHeader, GuiUtil.setConstraints(0,0,1.0,0.0,GridBagConstraints.HORIZONTAL,15,5,0,5)); JTextArea authors = new JTextArea(); authors.setBorder(new CompoundBorder(border, margin)); authors.setEditable(false); authors.setBackground(new Color(255, 255, 255)); authors.setFont(authorsHeader.getFont()); authors.setText("Claus Nagel <anpch@example.com>\n" + "Richard Redweik <hzdkv@example.com>\n" + "Felix Kunde <ychag@example.com>\n" + "Zhihang Yao <dycjh@example.com>\n" + "György Hudra <upchh@example.com>\n" + "Thomas H. Kolbe <lyhxr@example.com>"); general.add(authors, GuiUtil.setConstraints(0,1,1.0,1.0,GridBagConstraints.BOTH,2,5,5,5)); String tum_label_text = config.getProject().getGlobal().getLanguage() == LanguageType.EN ? "Chair of Geoinformatics,\nTechnical University of Munich, Germany" : "Lehrstuhl für Geoinformatik,\nTechnische Universität München, Deutschland"; JLabel copyHeader = new JLabel("Copyright"); general.add(copyHeader, GuiUtil.setConstraints(0,2,1.0,0.0,GridBagConstraints.HORIZONTAL,15,5,0,5)); JTextArea copy = new JTextArea(); copy.setBorder(new CompoundBorder(border, margin)); copy.setEditable(false); copy.setBackground(new Color(255, 255, 255)); copy.setFont(authorsHeader.getFont()); copy.setText("(C) 2013 - 2016\n" + tum_label_text + "\n" + "https://www.gis.bgu.tum.de/\n\n" + "This program is free software and licensed under the\n" + "Apache License, Version 2.0. For a copy of the Apache License see\n<http://www.apache.org/licenses/LICENSE-2.0>."); general.add(copy, GuiUtil.setConstraints(0,3,1.0,1.0,GridBagConstraints.BOTH,2,5,5,5)); PopupMenuDecorator.getInstance().decorate(authors, copy); } return general; } private JPanel getPartnerTab() { JPanel partner = new JPanel(); partner.setLayout(new GridBagLayout()); { String text = Language.I18N.getString("menu.help.info.partner"); Object[] args = new Object[]{ this.getClass().getPackage().getImplementationTitle() }; String result = MessageFormat.format(text, args); JLabel supportText = new JLabel(result); partner.add(supportText, GuiUtil.setConstraints(0,0,1.0,0.0,GridBagConstraints.HORIZONTAL,15,5,0,5)); JPanel logos = new JPanel(); partner.add(logos, GuiUtil.setConstraints(0,1,1.0,1.0,GridBagConstraints.BOTH,5,5,5,5)); logos.setBackground(Color.WHITE); logos.setBorder(BorderFactory.createEtchedBorder()); logos.setLayout(new GridBagLayout()); { Font font = UIManager.getFont("Label.font"); String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize() + "pt; }"; String tum_label_text = config.getProject().getGlobal().getLanguage() == LanguageType.EN ? "Chair of Geoinformatics,<br/>nTechnical University of Munich" : "Lehrstuhl für Geoinformatik,<br/>Technische Universität München"; JLabel tum_logo = new JLabel(new ImageIcon(getToolkit().getImage(this.getClass().getResource("/resources/img/partner/tum_logo.png")))); logos.add(tum_logo, GuiUtil.setConstraints(0,0,0,0,GridBagConstraints.NONE,10,0,10,0)); JEditorPane tum_label = new JEditorPane("text/html", "<html><b>" + tum_label_text + "</b><br/>https://www.gis.bgu.tum.de/</html>"); ((HTMLDocument)tum_label.getDocument()).getStyleSheet().addRule(bodyRule); tum_label.setEditable(false); logos.add(tum_label, GuiUtil.setConstraints(1,0,1,0,GridBagConstraints.HORIZONTAL,5,15,5,5)); JLabel vcs_logo = new JLabel(new ImageIcon(getToolkit().getImage(this.getClass().getResource("/resources/img/partner/vcs_logo.png")))); logos.add(vcs_logo, GuiUtil.setConstraints(0,1,0,0,GridBagConstraints.NONE,5,5,10,0)); JEditorPane vcs_label = new JEditorPane("text/html", "<html><b>virtualcitySYSTEMS GmbH, Berlin</b><br/>http://www.virtualcitysystems.de/</html>"); ((HTMLDocument)vcs_label.getDocument()).getStyleSheet().addRule(bodyRule); vcs_label.setEditable(false); logos.add(vcs_label, GuiUtil.setConstraints(1,1,1,0,GridBagConstraints.HORIZONTAL,5,15,5,5)); JLabel moss_logo = new JLabel(new ImageIcon(getToolkit().getImage(this.getClass().getResource("/resources/img/partner/moss_logo.png")))); logos.add(moss_logo, GuiUtil.setConstraints(0,2,0,0,GridBagConstraints.NONE,5,5,5,0)); JEditorPane moss_label = new JEditorPane("text/html", "<html><b>M.O.S.S. Computer Grafik Systeme GmbH,<br/>Taufkirchen, Germany</b><br/>http://www.moss.de/</html>"); ((HTMLDocument)moss_label.getDocument()).getStyleSheet().addRule(bodyRule); moss_label.setEditable(false); logos.add(moss_label, GuiUtil.setConstraints(1,2,1,0,GridBagConstraints.HORIZONTAL,5,15,5,5)); logos.add(new JLabel(), GuiUtil.setConstraints(0,3,1.0,1.0,GridBagConstraints.BOTH,5,5,0,5)); PopupMenuDecorator.getInstance().decorate(tum_label, vcs_label, moss_label); } } return partner; } }
3e1184b9553605f88883c1531e8e5cea33ebfdf2
3,585
java
Java
bookkeeper-server/src/test/java/org/apache/bookkeeper/client/UpdateMapTest.java
cesto93/bookkeeper
dc1f8065d89f8de790a649e5055753dbe505c8fa
[ "Apache-2.0" ]
null
null
null
bookkeeper-server/src/test/java/org/apache/bookkeeper/client/UpdateMapTest.java
cesto93/bookkeeper
dc1f8065d89f8de790a649e5055753dbe505c8fa
[ "Apache-2.0" ]
null
null
null
bookkeeper-server/src/test/java/org/apache/bookkeeper/client/UpdateMapTest.java
cesto93/bookkeeper
dc1f8065d89f8de790a649e5055753dbe505c8fa
[ "Apache-2.0" ]
null
null
null
33.194444
122
0.58159
7,398
package org.apache.bookkeeper.client; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; import java.util.*; import org.apache.bookkeeper.client.WeightedRandomSelection.WeightedObject; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class UpdateMapTest { int maxProbabilityMultiplier; Map<Object, WeightedObject> map; Map<Object, Double> res; public UpdateMapTest(int maxProbabilityMultiplier, Map<Object, WeightedObject> map, Map<Object, Double> res) { this.maxProbabilityMultiplier = maxProbabilityMultiplier; this.map = map; this.res = res; } private static WeightedObject getWeightedObject(long weight) { WeightedObject mock = mock(WeightedObject.class); when(mock.getWeight()).thenReturn(weight); return mock; } @Parameterized.Parameters public static Collection param() { Map<Object, WeightedObject> map1 = new HashMap<>(); Map<Object, WeightedObject> map2 = new HashMap<>(); Map<Object, WeightedObject> map3 = new HashMap<>(); Map<Object, WeightedObject> map4 = new HashMap<>(); Map<Object, WeightedObject> map5 = new HashMap<>(); Map<Object, Double> res1 = new HashMap<>(); Map<Object, Double> res2 = new HashMap<>(); Map<Object, Double> res3 = new HashMap<>(); Map<Object, Double> res4 = new HashMap<>(); Map<Object, Double> res5 = new HashMap<>(); res1.put(null, 0.0); map2.put("1", getWeightedObject(0)); map2.put("2", getWeightedObject(0)); res2.put("1", 0.0); res2.put("2", 0.5); map3.put("1", getWeightedObject(2)); map3.put("2", getWeightedObject(2)); map3.put("3", getWeightedObject(2)); res3.put("1", 0.0); res3.put("2", 0.3333333333333333); res3.put("3", 0.6666666666666666); map4.put("1", getWeightedObject(1)); map4.put("2", getWeightedObject(2)); map4.put("3", getWeightedObject(3)); res4.put("1", 0.0 ); res4.put("2", 1.0 / 6.0); res4.put("3", 1.0 / 6.0 + 2.0 / 6.0); //added after coverage goal map5.put("1", getWeightedObject(4)); map5.put("2", getWeightedObject(3)); map5.put("3", getWeightedObject(2)); map5.put("4", getWeightedObject(1)); res5.put("1", 0.0 ); res5.put("2", 0.25); res5.put("3", 0.5); res5.put("4", 0.7); return Arrays.asList(new Object[][] { {-1, map1, res1}, {-1, map2, res2}, {-1, map3, res3}, {-1, map4, res4}, {0, map1, res1}, {0, map2, res2}, {0, map3, res3}, {0, map4, res4}, {1, map1, res1}, {1, map2, res2}, {1, map3, res3}, {1, map4, res4}, {1, map5, res5} }); } @Test public void testUpdateMap() { WeightedRandomSelectionImpl<Object> randomSelection = new WeightedRandomSelectionImpl<>(maxProbabilityMultiplier); randomSelection.updateMap(map); System.out.println(randomSelection.cummulativeMap.keySet()); for (Object key : map.keySet()) { assertTrue(randomSelection.cummulativeMap.containsValue(key)); assertEquals(key, randomSelection.cummulativeMap.get(res.get(key))); } } }
3e1184ef7173d3a82d92229116c653417d9ed7a4
3,173
java
Java
server/src/main/java/umm3601/rides/RideRequestHandler.java
UMM-CSci-3601-S19/iteration-1-iteration-1-jrmk
5b55d087cb46e9abb2079784eb51a7c746dcb965
[ "MIT" ]
null
null
null
server/src/main/java/umm3601/rides/RideRequestHandler.java
UMM-CSci-3601-S19/iteration-1-iteration-1-jrmk
5b55d087cb46e9abb2079784eb51a7c746dcb965
[ "MIT" ]
19
2019-03-05T19:41:24.000Z
2019-03-16T03:51:13.000Z
server/src/main/java/umm3601/rides/RideRequestHandler.java
UMM-CSci-3601-S19/iteration-1-iteration-1-jrmk
5b55d087cb46e9abb2079784eb51a7c746dcb965
[ "MIT" ]
null
null
null
33.4
128
0.680429
7,399
package umm3601.rides; import org.bson.Document; import spark.Request; import spark.Response; import umm3601.user.UserController; public class RideRequestHandler { private final RideController rideController; public RideRequestHandler(RideController rideController) { this.rideController = rideController; } /** * Method called from Server when the 'api/users/:id' endpoint is received. * Get a JSON response with a list of all the users in the database. * * @param req the HTTP request * @param res the HTTP response * @return one user in JSON formatted string and if it fails it will return text with a different HTTP status code */ public String getRideJSON(Request req, Response res) { res.type("application/json"); String id = req.params("id"); String ride; try { ride = rideController.getRide(id); } catch (IllegalArgumentException e) { // This is thrown if the ID doesn't have the appropriate // form for a Mongo Object ID. // https://docs.mongodb.com/manual/reference/method/ObjectId/ res.status(400); res.body("The requested ride id " + id + " wasn't a legal Mongo Object ID.\n" + "See 'https://docs.mongodb.com/manual/reference/method/ObjectId/' for more info."); return ""; } if (ride != null) { return ride; } else { res.status(404); res.body("The requested ride with id " + id + " was not found"); return ""; } } /** * Method called from Server when the 'api/users' endpoint is received. * This handles the request received and the response * that will be sent back. * * @param req the HTTP request * @param res the HTTP response * @return an array of users in JSON formatted String */ public String getRides(Request req, Response res) { res.type("application/json"); return rideController.getRides(req.queryMap().toMap()); } /** * Method called from Server when the 'api/users/new' endpoint is received. * Gets specified user info from request and calls addNewUser helper method * to append that info to a document * * @param req the HTTP request * @param res the HTTP response * @return a boolean as whether the user was added successfully or not */ public String addNewRide(Request req, Response res) { res.type("application/json"); Document newRide = Document.parse(req.body()); String vehicle = newRide.getString("vehicle"); int mileage = newRide.getInteger("mileage"); String condition = newRide.getString("condition"); String start_location = newRide.getString("start_location"); String destination = newRide.getString("destination"); String tags = newRide.getString("tags"); String driver = "Roen"; Boolean riders = false; Boolean hasDriver = true; System.err.println("Adding new ride [vehicle=" + vehicle + ", mileage=" + mileage + " condition=" + condition + " start_location=" + start_location + " destination=" + destination +']'); return rideController.addNewRide(vehicle, mileage, condition, start_location, destination, tags, driver, riders, hasDriver); } }
3e11858dd0000d097feb43c8e1ee488ad3d89f32
503
java
Java
scorpio-framework/src/main/java/top/jshanet/scorpio/framework/repository/ScorpioRepository.java
jshanet/scorpio
476f99c1b561460b7326fd7c6023baa381e5e939
[ "MIT" ]
1
2020-08-24T15:13:05.000Z
2020-08-24T15:13:05.000Z
scorpio-framework/src/main/java/top/jshanet/scorpio/framework/repository/ScorpioRepository.java
jshanet/scorpio
476f99c1b561460b7326fd7c6023baa381e5e939
[ "MIT" ]
null
null
null
scorpio-framework/src/main/java/top/jshanet/scorpio/framework/repository/ScorpioRepository.java
jshanet/scorpio
476f99c1b561460b7326fd7c6023baa381e5e939
[ "MIT" ]
null
null
null
31.4375
72
0.823062
7,400
package top.jshanet.scorpio.framework.repository; import top.jshanet.scorpio.framework.entity.ScorpioEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.NoRepositoryBean; /** * @author seanjiang * @since 2019/12/25 */ @NoRepositoryBean public interface ScorpioRepository<T extends ScorpioEntity> extends JpaRepository<T, Long>, JpaSpecificationExecutor<T> { }
3e11869dad3bc73ef61efd1174725ecb6d8916cf
1,039
java
Java
src/main/java/cn/jeeweb/core/common/entity/tree/TreeNode.java
tanfangit/pc-web
933cb5133088a8a5c5f253cc3762f08603791c4c
[ "MIT" ]
12
2018-08-07T05:49:42.000Z
2021-04-07T13:00:03.000Z
src/main/java/cn/jeeweb/core/common/entity/tree/TreeNode.java
tanfangit/pc-web
933cb5133088a8a5c5f253cc3762f08603791c4c
[ "MIT" ]
5
2019-11-13T06:38:52.000Z
2021-09-20T20:38:54.000Z
src/main/java/cn/jeeweb/core/common/entity/tree/TreeNode.java
tanfangit/pc-web
933cb5133088a8a5c5f253cc3762f08603791c4c
[ "MIT" ]
8
2018-08-08T07:29:52.000Z
2021-09-23T07:14:14.000Z
16.234375
73
0.677575
7,401
package cn.jeeweb.core.common.entity.tree; public interface TreeNode<ID> { public ID getId();// 主键 public void setId(ID name);// 设置主键 /** * 是否是根节点 * * @return */ public boolean isRoot(); public String getName();// 节点名称 public void setName(String name);// 设置节点名称 public Long getLevel();// 节点的级别,默认最高级为0 public Boolean isLeaf();// 是否为叶节点,为true时表示该节点下面没有子节点了 /** * 获取 parentIds 之间的分隔符 * * @return */ public String getSeparator(); /** * 把自己构造出新的父节点路径 * * @return */ public String makeSelfAsNewParentIds(); /** * 父路径 * * @return */ public ID getParentId(); public void setParentId(ID parentId); /** * 所有父路径 如1,2,3, * * @return */ public String getParentIds(); public void setParentIds(String parentIds); public Boolean getExpanded();// 是否默认展开状态 public void setExpanded(Boolean expanded);// 是否默认展开状态 public void setLoaded(Boolean loaded);// 是否已经加载过子节点(为false时点击节点会自动加载子节点) public Boolean getLoaded();// 是否已经加载过子节点(为false时点击节点会自动加载子节点) public String[] makeTags(); }
3e1186b66e19ffdccf6a5ad35c9ba55677d6c90b
3,933
java
Java
ui/web/main/src/java/com/echothree/ui/web/main/action/advertising/offeritemprice/HistoryAction.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-09-01T08:39:01.000Z
2020-09-01T08:39:01.000Z
ui/web/main/src/java/com/echothree/ui/web/main/action/advertising/offeritemprice/HistoryAction.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
null
null
null
ui/web/main/src/java/com/echothree/ui/web/main/action/advertising/offeritemprice/HistoryAction.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-05-31T08:34:46.000Z
2020-05-31T08:34:46.000Z
50.423077
136
0.742944
7,402
// -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, LLC // // 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.echothree.ui.web.main.action.advertising.offeritemprice; import com.echothree.control.user.offer.common.OfferUtil; import com.echothree.control.user.offer.common.form.GetOfferItemPriceForm; import com.echothree.control.user.offer.common.result.GetOfferItemPriceResult; import com.echothree.ui.web.main.framework.AttributeConstants; import com.echothree.ui.web.main.framework.ForwardConstants; import com.echothree.ui.web.main.framework.MainBaseAction; import com.echothree.ui.web.main.framework.ParameterConstants; import com.echothree.util.common.command.CommandResult; import com.echothree.util.common.command.ExecutionResult; import com.echothree.view.client.web.struts.sprout.annotation.SproutAction; import com.echothree.view.client.web.struts.sprout.annotation.SproutForward; import com.echothree.view.client.web.struts.sprout.annotation.SproutProperty; import com.echothree.view.client.web.struts.sslext.config.SecureActionMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; @SproutAction( path = "/Advertising/OfferItemPrice/History", mappingClass = SecureActionMapping.class, properties = { @SproutProperty(property = "secure", value = "true") }, forwards = { @SproutForward(name = "Display", path = "/advertising/offeritemprice/history.jsp") } ) public class HistoryAction extends MainBaseAction<ActionForm> { @Override public ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String forwardKey = null; GetOfferItemPriceForm commandForm = OfferUtil.getHome().getGetOfferItemPriceForm(); commandForm.setOfferName(request.getParameter(ParameterConstants.OFFER_NAME)); commandForm.setItemName(request.getParameter(ParameterConstants.ITEM_NAME)); commandForm.setInventoryConditionName(request.getParameter(ParameterConstants.INVENTORY_CONDITION_NAME)); commandForm.setUnitOfMeasureTypeName(request.getParameter(ParameterConstants.UNIT_OF_MEASURE_TYPE_NAME)); commandForm.setCurrencyIsoName(request.getParameter(ParameterConstants.CURRENCY_ISO_NAME)); commandForm.setIncludeHistory(Boolean.TRUE.toString()); CommandResult commandResult = OfferUtil.getHome().getOfferItemPrice(getUserVisitPK(request), commandForm); if(!commandResult.hasErrors()) { ExecutionResult executionResult = commandResult.getExecutionResult(); GetOfferItemPriceResult result = (GetOfferItemPriceResult)executionResult.getResult(); request.setAttribute(AttributeConstants.OFFER_ITEM_PRICE, result.getOfferItemPrice()); request.setAttribute(AttributeConstants.OFFER_ITEM_PRICE_HISTORY, result.getHistory()); forwardKey = ForwardConstants.DISPLAY; } return mapping.findForward(forwardKey == null ? ForwardConstants.ERROR_404 : forwardKey); } }
3e11886d9ad6a561f4a3048259ca2976a6c109e7
620
java
Java
jforgame-server/src/main/java/jforgame/server/game/database/config/bean/ConfigSkill.java
apaz4/jforgame-master
3ac0d1a9a0dafc0bcdb583e2d42a49b311d5fe67
[ "Apache-2.0" ]
784
2017-09-10T06:26:04.000Z
2022-03-31T09:55:51.000Z
jforgame-server/src/main/java/jforgame/server/game/database/config/bean/ConfigSkill.java
apaz4/jforgame-master
3ac0d1a9a0dafc0bcdb583e2d42a49b311d5fe67
[ "Apache-2.0" ]
19
2017-10-18T15:02:06.000Z
2022-01-06T08:59:58.000Z
jforgame-server/src/main/java/jforgame/server/game/database/config/bean/ConfigSkill.java
apaz4/jforgame-master
3ac0d1a9a0dafc0bcdb583e2d42a49b311d5fe67
[ "Apache-2.0" ]
262
2017-09-12T06:07:45.000Z
2022-03-28T10:43:44.000Z
12.653061
50
0.682258
7,403
package jforgame.server.game.database.config.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity() public class ConfigSkill { @Id @Column private int id; @Column private String name; /** * 技能效果说明 */ @Column private String effect; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEffect() { return effect; } public void setEffect(String effect) { this.effect = effect; } }
3e11890d969d340ded4b9b2b50bcf919f646b5bf
347
java
Java
src/test/java/ca/netopia/projects/shortbin/ShortbinApplicationTests.java
cypherkey/shortbin
1e1e0c1a6377d6050a6d43d30bf0bf753ac300d4
[ "MIT" ]
null
null
null
src/test/java/ca/netopia/projects/shortbin/ShortbinApplicationTests.java
cypherkey/shortbin
1e1e0c1a6377d6050a6d43d30bf0bf753ac300d4
[ "MIT" ]
null
null
null
src/test/java/ca/netopia/projects/shortbin/ShortbinApplicationTests.java
cypherkey/shortbin
1e1e0c1a6377d6050a6d43d30bf0bf753ac300d4
[ "MIT" ]
null
null
null
20.411765
60
0.81268
7,404
package ca.netopia.projects.shortbin; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ShortbinApplicationTests { @Test public void contextLoads() { } }
3e118919305a04ca12b7485e7d30a0c6e5900321
20,230
java
Java
org.metafacture.fix/src/main/java/org/metafacture/metamorph/FixBuilder.java
metafacture/metafacture-fix
92f27fbebdee440382a9154b4dabe07a30e76964
[ "Apache-2.0" ]
8
2019-05-10T12:04:21.000Z
2022-01-21T11:36:27.000Z
org.metafacture.fix/src/main/java/org/metafacture/metamorph/FixBuilder.java
metafacture/metafacture-fix
92f27fbebdee440382a9154b4dabe07a30e76964
[ "Apache-2.0" ]
160
2019-08-27T11:21:22.000Z
2022-03-31T11:52:34.000Z
org.metafacture.fix/src/main/java/org/metafacture/metamorph/FixBuilder.java
metafacture/metafacture-fix
92f27fbebdee440382a9154b4dabe07a30e76964
[ "Apache-2.0" ]
3
2020-01-22T13:12:12.000Z
2020-10-28T14:23:46.000Z
38.460076
127
0.627336
7,405
/* * Copyright 2013, 2020 Deutsche Nationalbibliothek and others * * Licensed under the Apache License, Version 2.0 the "License"; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.metafacture.metamorph; import org.metafacture.commons.StringUtil; import org.metafacture.fix.fix.Do; import org.metafacture.fix.fix.Expression; import org.metafacture.fix.fix.Fix; import org.metafacture.fix.fix.If; import org.metafacture.fix.fix.MethodCall; import org.metafacture.fix.fix.Options; import org.metafacture.metamorph.api.Collect; import org.metafacture.metamorph.api.ConditionAware; import org.metafacture.metamorph.api.FlushListener; import org.metafacture.metamorph.api.Function; import org.metafacture.metamorph.api.InterceptorFactory; import org.metafacture.metamorph.api.NamedValuePipe; import org.metafacture.metamorph.functions.Constant; import org.metafacture.metamorph.functions.NotEquals; import org.metafacture.metamorph.functions.Replace; import com.google.common.collect.Multimap; import org.eclipse.emf.common.util.EList; import org.eclipse.xtext.xbase.lib.Pair; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * Builds a {@link Metafix} from a Fix DSL description * * @author Markus Michael Geipel (MorphBuilder) * @author Christoph Böhme (MorphBuilder) * @author Fabian Steeg (FixBuilder) * */ public class FixBuilder { // checkstyle-disable-line ClassDataAbstractionCoupling|ClassFanOutComplexity static final String ARRAY_MARKER = "[]"; private static final String FLUSH_WITH = "flushWith"; private static final String RECORD = "record"; private final Deque<StackFrame> stack = new LinkedList<>(); private final InterceptorFactory interceptorFactory; private final Metafix metafix; private CollectFactory collectFactory; private FunctionFactory functionFactory; public FixBuilder(final Metafix metafix, final InterceptorFactory interceptorFactory) { this.metafix = metafix; this.interceptorFactory = interceptorFactory; stack.push(new StackFrame(metafix)); collectFactory = new CollectFactory(); functionFactory = new FunctionFactory(); // morph: not-equals, replace, fix: not_equals, replace_all functionFactory.registerClass("not_equals", NotEquals.class); functionFactory.registerClass("replace_all", Replace.class); } Metafix getMetafix() { return metafix; } public void walk(final Fix fix) { processSubexpressions(fix.getElements(), null); } private void processBind(final Expression expression, final EList<String> params) { final String firstParam = resolvedAttribute(params, 1); final Do theDo = (Do) expression; Collect collect = null; // Special bind cases, no generic no-args collectors switch (expression.getName()) { case "entity": collect = createEntity(firstParam); break; case "array": collect = createEntity(firstParam + ARRAY_MARKER); break; case "map": final NamedValuePipe enterDataMap = enterDataMap(params, false); processSubexpressions(theDo.getElements(), firstParam); exitData(); if (enterDataMap instanceof Entity) { exitCollectorAndFlushWith(firstParam); } return; default: break; } // try generic no-args collectors, registered in collectFactory if (collect == null) { if (!collectFactory.containsKey(expression.getName())) { throw new IllegalArgumentException("Collector " + expression.getName() + " not found"); } final Map<String, String> attributes = resolvedAttributeMap(params, theDo.getOptions()); // flushWith should not be passed to the headPipe object via a // setter (see newInstance): attributes.remove(FLUSH_WITH); collect = collectFactory.newInstance(expression.getName(), attributes); } if (collect != null) { stack.push(new StackFrame(collect)); processSubexpressions(theDo.getElements(), firstParam); // must be set after recursive calls to flush descendants before parent final String flushWith = resolvedAttribute(resolvedAttributeMap(params, theDo.getOptions()), FLUSH_WITH); exitCollectorAndFlushWith(flushWith); } } protected final String resolveVars(final String string) { return string == null ? null : StringUtil.format(string, Metafix.VAR_START, Metafix.VAR_END, false, metafix.getVars()); } protected final Map<String, String> resolvedAttributeMap(final List<String> params, final Options options) { final Map<String, String> attributes = new HashMap<String, String>(); if (options == null) { return attributes; } final EList<String> keys = options.getKeys(); final EList<String> values = options.getValues(); for (int i = 0; i < keys.size() && i < values.size(); i = i + 1) { attributes.put(resolveVars(keys.get(i)), resolveVars(values.get(i))); } return attributes; } private Collect createEntity(final String name) { final Entity entity = new Entity(() -> metafix.getStreamReceiver()); entity.setName(name); return entity; } protected void exitCollectorAndFlushWith(final String flushWith) { final StackFrame currentCollect = stack.pop(); final NamedValuePipe tailPipe = currentCollect.getPipe(); final NamedValuePipe interceptor = interceptorFactory.createNamedValueInterceptor(); final NamedValuePipe delegate; if (interceptor == null || tailPipe instanceof Entity) { // The result of entity collectors cannot be intercepted // because they only use the receive/emit interface for // signalling while the actual data is transferred using // a custom mechanism. In order for this to work the Entity // class checks whether source and receiver are an // instances of Entity. If an interceptor is inserted between // entity elements this mechanism will break. delegate = tailPipe; } else { delegate = interceptor; delegate.addNamedValueSource(tailPipe); } final StackFrame parent = stack.peek(); if (parent.isInEntity()) { ((Entity) parent.getPipe()).setNameSource(delegate); } else if (parent.isInCondition()) { ((ConditionAware) parent.getPipe()).setConditionSource(delegate); } else { parent.getPipe().addNamedValueSource(delegate); } final Collect collector = (Collect) tailPipe; if (null != flushWith) { collector.setWaitForFlush(true); registerFlush(flushWith, collector); } } private void registerFlush(final String flushWith, final FlushListener flushListener) { final String[] keysSplit = Pattern.compile("|", Pattern.LITERAL).split(flushWith); for (final String key : keysSplit) { final FlushListener interceptor = interceptorFactory.createFlushInterceptor(flushListener); final FlushListener delegate; if (interceptor == null) { delegate = flushListener; } else { delegate = interceptor; } if (key.equals(RECORD)) { metafix.registerRecordEndFlush(delegate); } else { metafix.registerNamedValueReceiver(key, new Flush(delegate)); } } } private void processSubexpressions(final List<Expression> expressions, final String superSource) { for (final Expression sub : expressions) { final EList<String> p = sub.getParams(); String source = resolvedAttribute(p, 1); if (source == null && superSource != null) { source = superSource; } if (sub instanceof Do) { processBind(sub, p); } else if (sub instanceof If) { processConditional(sub, p); } else { processFunction(sub, p, source); } } } private void processConditional(final Expression expression, final EList<String> p) { final boolean isTopLevelIf = stack.peek().pipe instanceof Metafix; // If we're at the top level, we wrap the If into a collector: if (isTopLevelIf) { final Collect collect = collectFactory.newInstance("choose"); stack.push(new StackFrame(collect)); } enterIf(); final If theIf = (If) expression; enterDataMap(p, false); final Map<String, String> attributes = resolvedAttributeMap(p, null); attributes.put("string", resolvedAttribute(p, 2)); // for contains & equals morph functions // TODO: support morph functions: regexp -> match, morph quantors as prefixes: none_, all_, any_ runMetamorphFunction(expression.getName(), attributes); exitData(); // The Metamorph IF acts like a guard, executing not nested statements, but following statements: exitIf(); processSubexpressions(theIf.getElements(), resolvedAttribute(p, 1)); // As a draft for a record mode, we might do something like this instead: if (metafix.isRecordMode() && testConditional(theIf.getName(), p)) { processSubexpressions(theIf.getElements(), resolvedAttribute(p, 1)); } // If we're at the top level, we close the wrapping collector: if (isTopLevelIf) { exitCollectorAndFlushWith(RECORD); } } private boolean testConditional(final String conditional, final EList<String> p) { System.out.printf("<IF>: %s p: %s\n", conditional, p); boolean result = false; final String field = resolvedAttribute(p, 1); final String value = resolvedAttribute(p, 2); final Multimap<String, String> map = metafix.getCurrentRecord(); System.out.printf("<%s>: field: %s value: %s in: %s\n", conditional, field, value, map); switch (conditional) { case "any_match": result = map.containsKey(field) && map.get(field).stream().anyMatch(v -> v.matches(value)); break; case "all_match": result = map.containsKey(field) && map.get(field).stream().allMatch(v -> v.matches(value)); break; default: } return result; } private void processFunction(final Expression expression, final List<String> params, final String source) { final FixFunction functionToRun = findFixFunction(expression); if (functionToRun != null) { System.out.printf("Running Fix function %s, params %s, source %s\n", expression.getName(), params, source); functionToRun.apply(this, expression, params, source); } else { final Options options = ((MethodCall) expression).getOptions(); final Map<String, String> attributes = resolvedAttributeMap(params, options); runMetamorphFunction(expression.getName(), attributes); } } private FixFunction findFixFunction(final Expression expression) { for (final FixFunction exp : FixFunction.values()) { if (exp.name().equalsIgnoreCase(expression.getName())) { return exp; } } return null; } private void runMetamorphFunction(final String name, final Map<String, String> attributes) { if (functionFactory.containsKey(name)) { final String flushWith = attributes.remove(FLUSH_WITH); final Function function = functionFactory.newInstance(name, attributes); if (null != flushWith) { registerFlush(flushWith, function); } function.setMaps(metafix); final StackFrame head = stack.peek(); final NamedValuePipe interceptor = interceptorFactory.createNamedValueInterceptor(); final NamedValuePipe delegate; if (interceptor == null) { delegate = function; } else { delegate = interceptor; function.addNamedValueSource(delegate); } delegate.addNamedValueSource(head.getPipe()); head.setPipe(function); } else { throw new IllegalArgumentException(name + " not found"); } } void exitData() { final NamedValuePipe dataPipe = stack.pop().getPipe(); final NamedValuePipe interceptor = interceptorFactory.createNamedValueInterceptor(); final NamedValuePipe delegate; if (interceptor == null) { delegate = dataPipe; } else { delegate = interceptor; delegate.addNamedValueSource(dataPipe); } final StackFrame parent = stack.peek(); if (parent.isInEntity()) { ((Entity) parent.getPipe()).setNameSource(delegate); } else if (parent.isInCondition()) { ((ConditionAware) parent.getPipe()).setConditionSource(delegate); } else { parent.getPipe().addNamedValueSource(delegate); } } NamedValuePipe enterDataMap(final List<String> params, final boolean standalone) { Entity entity = null; final Data data = new Data(); String dataName = resolvedAttribute(params, 2); final String resolvedAttribute = resolvedAttribute(params, 2); if (resolvedAttribute != null && resolvedAttribute.contains(".")) { final String[] keyElements = resolvedAttribute.split("\\."); final Pair<Entity, Entity> firstAndLast = createEntities(keyElements); firstAndLast.getValue().addNamedValueSource(data); entity = firstAndLast.getKey(); stack.push(new StackFrame(entity)); dataName = keyElements[keyElements.length - 1]; } data.setName(dataName); final String source = resolvedAttribute(params, 1); metafix.registerNamedValueReceiver(source, getDelegate(data)); final StackFrame frame = new StackFrame(data); if (!standalone) { frame.setInEntity(true); } stack.push(frame); return entity != null ? entity : data; } void enterDataAdd(final List<String> params) { final String resolvedAttribute = resolvedAttribute(params, 1); if (resolvedAttribute.contains(".")) { addNestedField(params, resolvedAttribute); } else { final Data newDate = new Data(); newDate.setName(resolvedAttribute); final Constant constant = new Constant(); constant.setValue(resolvedAttribute(params, 2)); newDate.addNamedValueSource(constant); metafix.registerNamedValueReceiver("_id", constant); stack.push(new StackFrame(newDate)); } } void enterDataFunction(final String fieldName, final NamedValuePipe function, final boolean standalone) { if (standalone) { final Data data = new Data(); data.setName("@" + fieldName); metafix.registerNamedValueReceiver(fieldName, getDelegate(data, function)); stack.push(new StackFrame(data)); return; } final StackFrame head = stack.peek(); final NamedValuePipe interceptor = interceptorFactory.createNamedValueInterceptor(); final NamedValuePipe delegate; if (interceptor == null) { delegate = function; } else { delegate = interceptor; function.addNamedValueSource(delegate); } delegate.addNamedValueSource(head.getPipe()); head.setPipe(function); } void enterIf() { assert stack.peek().getPipe() instanceof ConditionAware : "statement `if` is not allowed in the current element"; stack.peek().setInCondition(true); } void exitIf() { stack.peek().setInCondition(false); } private void addNestedField(final List<String> params, final String resolvedAttribute) { final String[] keyElements = resolvedAttribute.split("\\."); final Pair<Entity, Entity> firstAndLast = createEntities(keyElements); final Constant constant = new Constant(); constant.setValue(resolvedAttribute(params, 2)); final Data newData = new Data(); newData.setName(keyElements[keyElements.length - 1]); newData.addNamedValueSource(constant); firstAndLast.getValue().addNamedValueSource(newData); metafix.registerNamedValueReceiver("_id", constant); stack.push(new StackFrame(firstAndLast.getKey())); } private Pair<Entity, Entity> createEntities(final String[] keyElements) { Entity firstEntity = null; Entity lastEntity = null; for (int i = 0; i < keyElements.length - 1; i = i + 1) { final Entity currentEntity = new Entity(() -> metafix.getStreamReceiver()); currentEntity.setName(keyElements[i]); if (firstEntity == null) { firstEntity = currentEntity; } if (lastEntity != null) { lastEntity.addNamedValueSource(currentEntity); } lastEntity = currentEntity; } return new Pair<>(firstEntity, lastEntity); } private NamedValuePipe getDelegate(final NamedValuePipe dataForDelegate) { return getDelegate(dataForDelegate, interceptorFactory.createNamedValueInterceptor()); } private NamedValuePipe getDelegate(final NamedValuePipe dataForDelegate, final NamedValuePipe interceptor) { final NamedValuePipe delegate; if (interceptor == null) { delegate = dataForDelegate; } else { delegate = interceptor; dataForDelegate.addNamedValueSource(delegate); } return delegate; } private String resolvedAttribute(final List<String> params, final int i) { return params.size() < i ? null : resolveVars(params.get(i - 1)); } private String resolvedAttribute(final Map<String, String> attributes, final String string) { return resolveVars(attributes.get(string)); } private static class StackFrame { private NamedValuePipe pipe; private boolean inEntity; private boolean inCondition; private StackFrame(final NamedValuePipe pipe) { this.pipe = pipe; } public void setInCondition(final boolean inCondition) { this.inCondition = inCondition; } public boolean isInCondition() { return inCondition; } public NamedValuePipe getPipe() { return pipe; } public void setPipe(final NamedValuePipe pipe) { this.pipe = pipe; } public void setInEntity(final boolean inEntity) { this.inEntity = inEntity; } public boolean isInEntity() { return inEntity; } } }
3e118976ed0989d75276a5d6bf1af7840cc29431
6,644
java
Java
src/test/java/com/lmax/disruptor/SingleProducerSequencerTest.java
jlusdy/disruptor
c2a23324b4353726fc5515ee6459bc70b67fc2f1
[ "Apache-2.0" ]
2
2016-04-01T02:24:25.000Z
2016-12-26T05:44:12.000Z
src/test/java/com/lmax/disruptor/SingleProducerSequencerTest.java
jlusdy/disruptor
c2a23324b4353726fc5515ee6459bc70b67fc2f1
[ "Apache-2.0" ]
null
null
null
src/test/java/com/lmax/disruptor/SingleProducerSequencerTest.java
jlusdy/disruptor
c2a23324b4353726fc5515ee6459bc70b67fc2f1
[ "Apache-2.0" ]
null
null
null
30.759259
115
0.663606
7,406
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Test; import com.lmax.disruptor.support.DaemonThreadFactory; public final class SingleProducerSequencerTest { private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(new DaemonThreadFactory()); private static final int BUFFER_SIZE = 4; private final Sequencer sequencer = new SingleProducerSequencer(BUFFER_SIZE, new SleepingWaitStrategy()); private final Sequence gatingSequence = new Sequence(SingleProducerSequencer.INITIAL_CURSOR_VALUE); public SingleProducerSequencerTest() { sequencer.setGatingSequences(gatingSequence); } @Test public void shouldStartWithInitialValue() { assertEquals(SingleProducerSequencer.INITIAL_CURSOR_VALUE, sequencer.getCursor()); } @Test public void shouldGetPublishFirstSequence() { final long sequence = sequencer.next(); assertEquals(SingleProducerSequencer.INITIAL_CURSOR_VALUE, sequencer.getCursor()); assertEquals(sequence, 0L); sequencer.publish(sequence); assertEquals(sequence, sequencer.getCursor()); } @Test public void shouldIndicateAvailableCapacity() { assertTrue(sequencer.hasAvailableCapacity(1)); } @Test public void voidShouldIndicateNoAvailableCapacity() { fillBuffer(); assertFalse(sequencer.hasAvailableCapacity(1)); } @Test public void shouldForceClaimSequence() { final long claimSequence = 3L; final long sequence = sequencer.claim(claimSequence); assertEquals(SingleProducerSequencer.INITIAL_CURSOR_VALUE, sequencer.getCursor()); assertEquals(sequence, claimSequence); sequencer.forcePublish(sequence); assertEquals(claimSequence, sequencer.getCursor()); } @Test public void shouldWaitOnSequence() throws AlertException, InterruptedException { final SequenceBarrier barrier = sequencer.newBarrier(); final long sequence = sequencer.next(); sequencer.publish(sequence); assertEquals(sequence, barrier.waitFor(sequence)); } @Test public void shouldWaitOnSequenceShowingBatchingEffect() throws AlertException, InterruptedException { final SequenceBarrier barrier = sequencer.newBarrier(); sequencer.publish(sequencer.next()); sequencer.publish(sequencer.next()); final long sequence = sequencer.next(); sequencer.publish(sequence); assertEquals(sequence, barrier.waitFor(SingleProducerSequencer.INITIAL_CURSOR_VALUE + 1L)); } @Test public void shouldSignalWaitingProcessorWhenSequenceIsPublished() throws InterruptedException { final SequenceBarrier barrier = sequencer.newBarrier(); final CountDownLatch waitingLatch = new CountDownLatch(1); final CountDownLatch doneLatch = new CountDownLatch(1); final long expectedSequence = SingleProducerSequencer.INITIAL_CURSOR_VALUE + 1L; EXECUTOR.submit(new Runnable() { @Override public void run() { try { waitingLatch.countDown(); assertEquals(expectedSequence, barrier.waitFor(expectedSequence)); } catch (Exception e) { // will not happen } gatingSequence.set(expectedSequence); doneLatch.countDown(); } }); waitingLatch.await(); assertEquals(gatingSequence.get(), SingleProducerSequencer.INITIAL_CURSOR_VALUE); sequencer.publish(sequencer.next()); doneLatch.await(); assertEquals(gatingSequence.get(), expectedSequence); } @Test public void shouldHoldUpPublisherWhenBufferIsFull() throws InterruptedException { fillBuffer(); final CountDownLatch waitingLatch = new CountDownLatch(1); final CountDownLatch doneLatch = new CountDownLatch(1); final long expectedFullSequence = SingleProducerSequencer.INITIAL_CURSOR_VALUE + sequencer.getBufferSize(); assertEquals(sequencer.getCursor(), expectedFullSequence); EXECUTOR.submit(new Runnable() { @Override public void run() { waitingLatch.countDown(); sequencer.publish(sequencer.next()); doneLatch.countDown(); } }); waitingLatch.await(); assertEquals(sequencer.getCursor(), expectedFullSequence); gatingSequence.set(SingleProducerSequencer.INITIAL_CURSOR_VALUE + 1L); doneLatch.await(); assertEquals(sequencer.getCursor(), expectedFullSequence + 1L); } @Test(expected = InsufficientCapacityException.class) public void shouldThrowInsufficientCapacityExceptionWhenSequencerIsFull() throws Exception { for (int i = 0; i < 4; i++) { long sequence = sequencer.next(); sequencer.publish(sequence); } sequencer.tryNext(); } @Test public void shouldCalculateRemainingCapacity() throws Exception { assertThat(sequencer.remainingCapacity(), is(4L)); sequencer.publish(sequencer.next()); assertThat(sequencer.remainingCapacity(), is(3L)); sequencer.publish(sequencer.next()); assertThat(sequencer.remainingCapacity(), is(2L)); sequencer.publish(sequencer.next()); assertThat(sequencer.remainingCapacity(), is(1L)); } private void fillBuffer() { for (int i = 0; i < BUFFER_SIZE; i++) { final long sequence = sequencer.next(); sequencer.publish(sequence); } } }
3e118a4e2e4d0ed3633c47a88a9c75f522711604
2,926
java
Java
sdk/src/main/java/net/tenie/Sqlucky/sdk/po/DbSchemaPo.java
tenie/SQLucky
be7d263183430e2af14953b9ca54f7b71df5f309
[ "Apache-2.0" ]
17
2020-11-16T09:14:23.000Z
2022-03-25T05:46:33.000Z
sdk/src/main/java/net/tenie/Sqlucky/sdk/po/DbSchemaPo.java
tenie/SQLucky
be7d263183430e2af14953b9ca54f7b71df5f309
[ "Apache-2.0" ]
1
2022-02-28T10:36:46.000Z
2022-02-28T10:36:46.000Z
sdk/src/main/java/net/tenie/Sqlucky/sdk/po/DbSchemaPo.java
tenie/SQLucky
be7d263183430e2af14953b9ca54f7b71df5f309
[ "Apache-2.0" ]
1
2021-02-07T08:03:47.000Z
2021-02-07T08:03:47.000Z
20.461538
73
0.713944
7,407
package net.tenie.Sqlucky.sdk.po; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author tenie * */ public class DbSchemaPo { private String schemaName; private List<TablePo> tabs; private Map<String, TablePo> mTabs = new HashMap<>(); private List<TablePo> views; private Map<String, TablePo> mViews = new HashMap<>(); private List<FuncProcTriggerPo> functions; private Map<String, FuncProcTriggerPo> mFunctions = new HashMap<>(); private List<FuncProcTriggerPo> procedures; private Map<String, FuncProcTriggerPo> mProcedures = new HashMap<>(); private List<FuncProcTriggerPo> triggers; private Map<String, FuncProcTriggerPo> mTriggers = new HashMap<>(); public DbSchemaPo() { } public DbSchemaPo(String schemaName, List<TablePo> tabs) { super(); this.schemaName = schemaName; this.tabs = tabs; if (tabs != null && tabs.size() > 0) { for (int i = 0; i < tabs.size(); i++) { TablePo tpo = tabs.get(i); mTabs.put(tpo.getTableName(), tpo); } } } public TablePo getTable(String name) { return mTabs.get(name); } public TablePo getView(String name) { return mViews.get(name); } public Map<String, TablePo> getmTabs() { return mTabs; } public void setmTabs(Map<String, TablePo> mTabs) { this.mTabs = mTabs; } public Map<String, TablePo> getmViews() { return mViews; } public void setmViews(Map<String, TablePo> mViews) { this.mViews = mViews; } public Map<String, FuncProcTriggerPo> getmFunctions() { return mFunctions; } public void setmFunctions(Map<String, FuncProcTriggerPo> mFunctions) { this.mFunctions = mFunctions; } public Map<String, FuncProcTriggerPo> getmProcedures() { return mProcedures; } public void setmProcedures(Map<String, FuncProcTriggerPo> mProcedures) { this.mProcedures = mProcedures; } public Map<String, FuncProcTriggerPo> getmTriggers() { return mTriggers; } public void setmTriggers(Map<String, FuncProcTriggerPo> mTriggers) { this.mTriggers = mTriggers; } public String getSchemaName() { return schemaName; } public void setSchemaName(String schemaName) { this.schemaName = schemaName; } public List<TablePo> getTabs() { return tabs; } public void setTabs(List<TablePo> tabs) { this.tabs = tabs; } public List<TablePo> getViews() { return views; } public void setViews(List<TablePo> views) { this.views = views; } public List<FuncProcTriggerPo> getFunctions() { return functions; } public void setFunctions(List<FuncProcTriggerPo> functions) { this.functions = functions; } public List<FuncProcTriggerPo> getProcedures() { return procedures; } public void setProcedures(List<FuncProcTriggerPo> procedures) { this.procedures = procedures; } public List<FuncProcTriggerPo> getTriggers() { return triggers; } public void setTriggers(List<FuncProcTriggerPo> triggers) { this.triggers = triggers; } }
3e118a75947dda86e35f2226ebc1bfe865a07535
964
java
Java
powerauth-data-adapter-model/src/main/java/io/getlime/security/powerauth/lib/dataadapter/model/enumeration/SmsDeliveryResult.java
wultra/powerauth-webflow
83623321f8987d79e2ee48487ec8290137f9d3b5
[ "Apache-2.0" ]
5
2019-04-19T08:51:15.000Z
2022-03-19T10:01:29.000Z
powerauth-data-adapter-model/src/main/java/io/getlime/security/powerauth/lib/dataadapter/model/enumeration/SmsDeliveryResult.java
wultra/powerauth-webflow
83623321f8987d79e2ee48487ec8290137f9d3b5
[ "Apache-2.0" ]
346
2018-07-19T12:40:22.000Z
2022-02-22T18:20:13.000Z
powerauth-data-adapter-model/src/main/java/io/getlime/security/powerauth/lib/dataadapter/model/enumeration/SmsDeliveryResult.java
wultra/powerauth-webflow
83623321f8987d79e2ee48487ec8290137f9d3b5
[ "Apache-2.0" ]
6
2019-01-27T12:02:57.000Z
2022-01-05T18:43:59.000Z
26.944444
75
0.712371
7,408
/* * Copyright 2019 Wultra s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getlime.security.powerauth.lib.dataadapter.model.enumeration; /** * Result of SMS authorization code delivery. * * @author Roman Strobl, kenaa@example.com */ public enum SmsDeliveryResult { /** * Authorization SMS was successfully delivered. */ SUCCEEDED, /** * Authorization SMS could not be delivered. */ FAILED }
3e118aade02d167cda25789a05d6a6428402136c
1,976
java
Java
paxtools-core/src/main/java/org/biopax/paxtools/controller/TransitivePropertyAccessor.java
metincansiper/Paxtools
2f93afa94426bf8b5afc2e0e61cd4b269a83288d
[ "MIT" ]
20
2015-07-22T15:48:51.000Z
2021-12-15T10:49:24.000Z
paxtools-core/src/main/java/org/biopax/paxtools/controller/TransitivePropertyAccessor.java
metincansiper/Paxtools
2f93afa94426bf8b5afc2e0e61cd4b269a83288d
[ "MIT" ]
48
2015-08-04T13:58:19.000Z
2021-12-15T19:43:14.000Z
paxtools-core/src/main/java/org/biopax/paxtools/controller/TransitivePropertyAccessor.java
metincansiper/Paxtools
2f93afa94426bf8b5afc2e0e61cd4b269a83288d
[ "MIT" ]
10
2015-10-02T05:19:38.000Z
2021-12-15T11:55:55.000Z
31.870968
127
0.753036
7,409
package org.biopax.paxtools.controller; import org.biopax.paxtools.model.BioPAXElement; import org.biopax.paxtools.util.IllegalBioPAXArgumentException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.Set; /** * This class is a transitive decorator for PropertyAccessors. BioPAX has transitive properties, * such as: memberEntityReference, memberEntityFeature, memberPhysicalEntity, component. * These all represent nested containment relationships. * * When decorating a suitable property accessor this accessor will traverse the whole nesting hierarchy and bring all * children( or if inverse parents). For example when used on a {@link org.biopax.paxtools.model.level3.Complex#getComponent()} * it will not only return the immediate components but also the components of the components. */ public class TransitivePropertyAccessor<R extends BioPAXElement, D extends R> extends DecoratingPropertyAccessor<D, R> { private final static Logger log = LoggerFactory.getLogger(TransitivePropertyAccessor.class); private TransitivePropertyAccessor(PropertyAccessor<D, R> accessor) { super(accessor); } @Override public Set<? extends R> getValueFromBean(D bean) throws IllegalBioPAXArgumentException { Set<R> values = new HashSet<R>(); transitiveGet(bean, values); return values; } private void transitiveGet(D bean, Set<R> values) { Set<? extends R> valuesFromBean = impl.getValueFromBean(bean); for (R value : valuesFromBean) { if(values.add(value)) { //if(impl.getDomain().isInstance(value)) - unnecessary as the impl does that check transitiveGet((D) value, values); } else { //report loop log.debug("Escaped an inf. loop (" + impl+ ") at " + value.getUri()); } } } public static < R extends BioPAXElement, D extends R> TransitivePropertyAccessor<R, D> create( PropertyAccessor<D, R> pa) { return new TransitivePropertyAccessor<R,D>(pa); } }
3e118caa8b235613ab6fb51daafcaab735bc3698
4,381
java
Java
src/main/java/dev/tricht/lunaris/listeners/ClipboardListenerStack.java
mtricht/venarius
904a7647ffc088050ef92e5b8e33672c65ed6811
[ "MIT" ]
96
2020-01-08T03:21:02.000Z
2021-09-05T23:29:28.000Z
src/main/java/dev/tricht/lunaris/listeners/ClipboardListenerStack.java
mtricht/venarius
904a7647ffc088050ef92e5b8e33672c65ed6811
[ "MIT" ]
66
2020-01-09T22:37:10.000Z
2021-04-17T14:48:40.000Z
src/main/java/dev/tricht/lunaris/listeners/ClipboardListenerStack.java
mtricht/poe-assistant
904a7647ffc088050ef92e5b8e33672c65ed6811
[ "MIT" ]
9
2020-01-10T18:48:52.000Z
2022-02-07T23:32:08.000Z
32.451852
110
0.587537
7,410
package dev.tricht.lunaris.listeners; import dev.tricht.lunaris.item.ItemGrabber; import dev.tricht.lunaris.util.Platform; import lombok.extern.slf4j.Slf4j; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.KeyEvent; import java.io.IOException; import java.util.ArrayList; @Slf4j public class ClipboardListenerStack implements GameListener, ClipboardOwner { private final ItemGrabber itemGrabber; private final Robot robot; private static boolean isOwner = false; private static ClipboardCallback callback; public ClipboardListenerStack(ItemGrabber itemGrabber, Robot robot) { this.itemGrabber = itemGrabber; this.robot = robot; registerClipboardListener(); } private ArrayList<GameListener> keyListeners = new ArrayList<>(); public void addListener(GameListener listener) { keyListeners.add(listener); } @Override public void onEvent(GameEvent event) { for (GameListener listenerEntry : keyListeners) { if (listenerEntry.supports(event)) { if (!isOwner) { flushClipboard(); } callback = new ClipboardCallback() { private boolean fired = false; @Override public void onContentChange(String clipboard) { if (clipboard.isEmpty() || fired) { return; } event.setItem(itemGrabber.grab(clipboard)); listenerEntry.onEvent(event); fired = true; } }; log.debug("Registered clipboard listener for " + listenerEntry.getClass().getName()); pressControlC(event); return; } } } @Override public boolean supports(GameEvent event) { for (GameListener listenerEntry : keyListeners) { if (listenerEntry.supports(event)) { return true; } } return false; } private void registerClipboardListener() { Toolkit.getDefaultToolkit().getSystemClipboard().addFlavorListener(flavorEvent -> { if (!Platform.INSTANCE.isPoeActive()) { return; } String clipboardText = getClipboardText(); log.debug("Got clipboard text:" + clipboardText); if (clipboardText != null && callback != null) { callback.onContentChange(clipboardText); } }); } private void flushClipboard() { try { Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(""), this); isOwner = true; log.debug("Regained ownership"); } catch (IllegalStateException e) { log.error("Clipboard error, trying again", e); // TODO: Wait a bit? Have max retries? flushClipboard(); } } private String getClipboardText() { try { return (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor); } catch (IllegalStateException | IOException | UnsupportedFlavorException e) { if (e instanceof UnsupportedFlavorException) { return ""; } log.error("Clipboard error, trying again", e); // TODO: Wait a bit? Have max retries? return getClipboardText(); } } private void pressControlC(GameEvent event) { HotKeyHandler.setPaused(true); boolean wasControlAlreadyPressed = (event.getOriginalEvent().getModifiers() & 34) != 0; if (!wasControlAlreadyPressed) { robot.keyPress(KeyEvent.VK_CONTROL); } robot.keyPress(KeyEvent.VK_C); log.debug("Pressed ctrl+c"); if (!wasControlAlreadyPressed) { robot.keyRelease(KeyEvent.VK_CONTROL); } robot.keyRelease(KeyEvent.VK_C); HotKeyHandler.setPaused(false); } @Override public void lostOwnership(Clipboard clipboard, Transferable contents) { isOwner = false; log.debug("Lost ownership"); } private interface ClipboardCallback { void onContentChange(String clipboard); } }
3e118d1b596457cb6e4c8e0f3cd08ba7cc0d4298
10,805
java
Java
client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ClientConnectionPoolingTest.java
yrodiere/infinispan
bf58f28b4654849dceece725ecb695abf4e26be7
[ "Apache-2.0" ]
null
null
null
client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ClientConnectionPoolingTest.java
yrodiere/infinispan
bf58f28b4654849dceece725ecb695abf4e26be7
[ "Apache-2.0" ]
null
null
null
client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ClientConnectionPoolingTest.java
yrodiere/infinispan
bf58f28b4654849dceece725ecb695abf4e26be7
[ "Apache-2.0" ]
null
null
null
40.040741
143
0.70382
7,411
package org.infinispan.client.hotrod; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.net.InetSocketAddress; import java.util.concurrent.ExecutionException; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.pool.impl.GenericKeyedObjectPool; import org.infinispan.Cache; import org.infinispan.client.hotrod.configuration.ExhaustedAction; import org.infinispan.client.hotrod.impl.transport.tcp.TcpTransportFactory; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.InternalRemoteCacheManager; import org.infinispan.commands.VisitableCommand; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.base.CommandInterceptor; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * @author lyhxr@example.com * @since 4.1 */ @Test(testName = "client.hotrod.ClientConnectionPoolingTest", groups="functional") public class ClientConnectionPoolingTest extends MultipleCacheManagersTest { private static final Log log = LogFactory.getLog(ClientConnectionPoolingTest.class); Cache<String, String> c1; Cache<String, String> c2; private HotRodServer hotRodServer1; private HotRodServer hotRodServer2; RemoteCache<String, String> remoteCache; private RemoteCacheManager remoteCacheManager; private GenericKeyedObjectPool<?, ?> connectionPool; private InetSocketAddress hrServ1Addr; private InetSocketAddress hrServ2Addr; private WorkerThread workerThread1; private WorkerThread workerThread2; private WorkerThread workerThread3; private WorkerThread workerThread4; private WorkerThread workerThread5; private WorkerThread workerThread6; @Override protected void createCacheManagers() throws Throwable { // The caches are not configured to form a cluster // so the client will have to use round-robin for balancing. // This means requests will alternate between server 1 and server 2. c1 = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()).getCache(); c2 = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()).getCache(); registerCacheManager(c1.getCacheManager(), c2.getCacheManager()); hotRodServer1 = HotRodClientTestingUtil.startHotRodServer(c1.getCacheManager()); hotRodServer2 = HotRodClientTestingUtil.startHotRodServer(c2.getCacheManager()); String servers = HotRodClientTestingUtil.getServersString(hotRodServer1, hotRodServer2); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder .connectionPool() .maxActive(2) .maxTotal(8) .maxIdle(6) .exhaustedAction(ExhaustedAction.WAIT) .testOnBorrow(false) .testOnReturn(false) .timeBetweenEvictionRuns(-2) .minEvictableIdleTime(7) .testWhileIdle(true) .minIdle(-5) .lifo(true) .addServers(servers); remoteCacheManager = new InternalRemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(); TcpTransportFactory tcpConnectionFactory = (TcpTransportFactory) ((InternalRemoteCacheManager) remoteCacheManager).getTransportFactory(); connectionPool = tcpConnectionFactory.getConnectionPool(); workerThread1 = new WorkerThread(remoteCache); workerThread2 = new WorkerThread(remoteCache); workerThread3 = new WorkerThread(remoteCache); workerThread4 = new WorkerThread(remoteCache); workerThread5 = new WorkerThread(remoteCache); workerThread6 = new WorkerThread(remoteCache); hrServ1Addr = InetSocketAddress.createUnresolved("localhost", hotRodServer1.getPort()); hrServ2Addr = InetSocketAddress.createUnresolved("localhost", hotRodServer2.getPort()); } @AfterMethod public void tearDown() throws ExecutionException, InterruptedException { killServers(hotRodServer1, hotRodServer2); workerThread1.stop(); workerThread2.stop(); workerThread3.stop(); workerThread4.stop(); workerThread5.stop(); workerThread6.stop(); workerThread1.awaitTermination(); workerThread2.awaitTermination(); workerThread3.awaitTermination(); workerThread4.awaitTermination(); workerThread5.awaitTermination(); workerThread6.awaitTermination(); killRemoteCacheManager(remoteCacheManager); } @Test public void testPropsCorrectlySet() { assertEquals(2, connectionPool.getMaxActive()); assertEquals(8, connectionPool.getMaxTotal()); assertEquals(6, connectionPool.getMaxIdle()); assertEquals(1, connectionPool.getWhenExhaustedAction()); assertFalse(connectionPool.getTestOnBorrow()); assertFalse(connectionPool.getTestOnReturn()); assertEquals(-2, connectionPool.getTimeBetweenEvictionRunsMillis()); assertEquals(7, connectionPool.getMinEvictableIdleTimeMillis()); assertTrue(connectionPool.getTestWhileIdle()); assertEquals(-5, connectionPool.getMinIdle()); assertTrue(connectionPool.getLifo()); } public void testMaxActiveReached() throws Exception { workerThread1.put("k1", "v1"); workerThread1.put("k2", "v2"); // verify that each cache got a request assertEquals(1, c1.size()); assertEquals(1, c2.size()); assertEquals("v1", remoteCache.get("k1")); assertEquals(1, c1.size()); assertEquals("v2", remoteCache.get("k2")); assertEquals(1, c2.size()); // there should be no active connections to any server assertEquals(0, connectionPool.getNumActive(hrServ1Addr)); assertEquals(0, connectionPool.getNumActive(hrServ2Addr)); assertEquals(1, connectionPool.getNumIdle(hrServ1Addr)); assertEquals(1, connectionPool.getNumIdle(hrServ2Addr)); // install an interceptor that will block all requests on the server until the allow() call DelayTransportInterceptor dt1 = new DelayTransportInterceptor(true); DelayTransportInterceptor dt2 = new DelayTransportInterceptor(true); c1.getAdvancedCache().addInterceptor(dt1, 0); c2.getAdvancedCache().addInterceptor(dt2, 0); log.info("Cache operations blocked"); try { // start one operation on each server, using the existing connections workerThread1.putAsync("k3", "v3"); workerThread2.putAsync("k4", "v4"); log.info("Async calls for k3 and k4 is done."); eventually(() -> 1 == connectionPool.getNumActive(hrServ1Addr) && 1 == connectionPool.getNumActive(hrServ2Addr) && 0 == connectionPool.getNumIdle(hrServ1Addr) && 0 == connectionPool.getNumIdle(hrServ2Addr)); // another operation for each server, creating new connections workerThread3.putAsync("k5", "v5"); workerThread4.putAsync("k6", "v6"); eventually(() -> 2 == connectionPool.getNumActive(hrServ1Addr) && 2 == connectionPool.getNumActive(hrServ2Addr) && 0 == connectionPool.getNumIdle(hrServ1Addr) && 0 == connectionPool.getNumIdle(hrServ2Addr)); // we've reached the connection pool limit, the new operations will block // until a connection is released workerThread5.putAsync("k7", "v7"); workerThread6.putAsync("k8", "v8"); Thread.sleep(2000); //sleep a bit longer to make sure the async threads do their job assertEquals(2, connectionPool.getNumActive(hrServ1Addr)); assertEquals(2, connectionPool.getNumActive(hrServ2Addr)); assertEquals(0, connectionPool.getNumIdle(hrServ1Addr)); assertEquals(0, connectionPool.getNumIdle(hrServ2Addr)); } catch (Exception e) { log.error(e); } finally { //now allow dt1.allow(); dt2.allow(); } // give the servers some time to process the operations eventually(() -> connectionPool.getNumActive() == 0, 1000); assertExistKeyValue("k3", "v3"); assertExistKeyValue("k4", "v4"); assertExistKeyValue("k5", "v5"); assertExistKeyValue("k6", "v6"); assertExistKeyValue("k7", "v7"); assertExistKeyValue("k8", "v8"); // all the connections have been released to the pool, but haven't been closed assertEquals(0, connectionPool.getNumActive(hrServ1Addr)); assertEquals(0, connectionPool.getNumActive(hrServ2Addr)); assertEquals(2, connectionPool.getNumIdle(hrServ1Addr)); assertEquals(2, connectionPool.getNumIdle(hrServ2Addr)); } private void assertExistKeyValue(String key, String value) throws InterruptedException { boolean exists = false; for (int i = 0; i < 10; i++) { exists = value.equals(remoteCache.get(key)) || value.equals(remoteCache.get(key)); if (exists) break; Thread.sleep(1000); } assertEquals("key value not found: (" + key + ", " + value + ")", true, exists); } public static class DelayTransportInterceptor extends CommandInterceptor { private final ReentrantLock lock = new ReentrantLock(); public DelayTransportInterceptor(boolean lock) { if (lock) block(); } @Override protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable { log.trace("Acquiring lock. " + lockInfo()); lock.lock(); try { return super.handleDefault(ctx, command); } finally { log.trace("Done operation, releasing lock" + lockInfo()); lock.unlock(); } } private String lockInfo() { return " Is locked? " + lock.isLocked() + ". Lock held by me? " + lock.isHeldByCurrentThread(); } public void block() { log.trace("block. " + lockInfo()); lock.lock(); } public void allow() { log.trace("allow." + lockInfo()); lock.unlock(); } } }
3e118dadbf05932555dd36786526b654dc91821c
4,481
java
Java
Skizzle/net/minecraft/client/gui/GuiSlider.java
14ms/Minecraft-Disclosed-Source-Modifications
d3729ab0fb20c36da1732b2070d1cb5d1409ffbc
[ "Unlicense" ]
3
2022-02-28T17:34:51.000Z
2022-03-06T21:55:16.000Z
Skizzle/net/minecraft/client/gui/GuiSlider.java
14ms/Minecraft-Disclosed-Source-Modifications
d3729ab0fb20c36da1732b2070d1cb5d1409ffbc
[ "Unlicense" ]
2
2022-02-25T20:10:14.000Z
2022-03-03T14:25:03.000Z
Skizzle/net/minecraft/client/gui/GuiSlider.java
14ms/Minecraft-Disclosed-Source-Modifications
d3729ab0fb20c36da1732b2070d1cb5d1409ffbc
[ "Unlicense" ]
null
null
null
39.654867
255
0.651417
7,412
/* * Decompiled with CFR 0.150. */ package net.minecraft.client.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiPageButtonList; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.resources.I18n; public class GuiSlider extends GuiButton { private float field_175227_p = 1.0f; public boolean field_175228_o; private String field_175226_q; private final float field_175225_r; private final float field_175224_s; private final GuiPageButtonList.GuiResponder field_175223_t; private FormatHelper field_175222_u; private static final String __OBFID = "CL_00001954"; public GuiSlider(GuiPageButtonList.GuiResponder p_i45541_1_, int p_i45541_2_, int p_i45541_3_, int p_i45541_4_, String p_i45541_5_, float p_i45541_6_, float p_i45541_7_, float p_i45541_8_, FormatHelper p_i45541_9_) { super(p_i45541_2_, p_i45541_3_, p_i45541_4_, 150, 20, ""); this.field_175226_q = p_i45541_5_; this.field_175225_r = p_i45541_6_; this.field_175224_s = p_i45541_7_; this.field_175227_p = (p_i45541_8_ - p_i45541_6_) / (p_i45541_7_ - p_i45541_6_); this.field_175222_u = p_i45541_9_; this.field_175223_t = p_i45541_1_; this.displayString = this.func_175221_e(); } public float func_175220_c() { return this.field_175225_r + (this.field_175224_s - this.field_175225_r) * this.field_175227_p; } public void func_175218_a(float p_175218_1_, boolean p_175218_2_) { this.field_175227_p = (p_175218_1_ - this.field_175225_r) / (this.field_175224_s - this.field_175225_r); this.displayString = this.func_175221_e(); if (p_175218_2_) { this.field_175223_t.func_175320_a(this.id, this.func_175220_c()); } } public float func_175217_d() { return this.field_175227_p; } private String func_175221_e() { return this.field_175222_u == null ? String.valueOf(I18n.format(this.field_175226_q, new Object[0])) + ": " + this.func_175220_c() : this.field_175222_u.func_175318_a(this.id, I18n.format(this.field_175226_q, new Object[0]), this.func_175220_c()); } @Override protected int getHoverState(boolean mouseOver) { return 0; } @Override protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { if (this.visible) { if (this.field_175228_o) { this.field_175227_p = (float)(mouseX - (this.xPosition + 4)) / (float)(this.width - 8); if (this.field_175227_p < 0.0f) { this.field_175227_p = 0.0f; } if (this.field_175227_p > 1.0f) { this.field_175227_p = 1.0f; } this.displayString = this.func_175221_e(); this.field_175223_t.func_175320_a(this.id, this.func_175220_c()); } GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); this.drawTexturedModalRect(this.xPosition + (int)(this.field_175227_p * (float)(this.width - 8)), this.yPosition, 0, 66, 4, 20); this.drawTexturedModalRect(this.xPosition + (int)(this.field_175227_p * (float)(this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); } } public void func_175219_a(float p_175219_1_) { this.field_175227_p = p_175219_1_; this.displayString = this.func_175221_e(); this.field_175223_t.func_175320_a(this.id, this.func_175220_c()); } @Override public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { if (super.mousePressed(mc, mouseX, mouseY)) { this.field_175227_p = (float)(mouseX - (this.xPosition + 4)) / (float)(this.width - 8); if (this.field_175227_p < 0.0f) { this.field_175227_p = 0.0f; } if (this.field_175227_p > 1.0f) { this.field_175227_p = 1.0f; } this.displayString = this.func_175221_e(); this.field_175223_t.func_175320_a(this.id, this.func_175220_c()); this.field_175228_o = true; return true; } return false; } @Override public void mouseReleased(int mouseX, int mouseY) { this.field_175228_o = false; } public static interface FormatHelper { public String func_175318_a(int var1, String var2, float var3); } }
3e118ed38f37f446dc8fbe4e880d4835685f5013
5,922
java
Java
nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/test/java/org/nd4j/jita/concurrency/CudaAffinityManagerTest.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
2
2018-11-26T15:30:37.000Z
2018-11-26T15:30:39.000Z
nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/test/java/org/nd4j/jita/concurrency/CudaAffinityManagerTest.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
16
2018-12-03T11:37:19.000Z
2018-12-03T19:47:25.000Z
nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/test/java/org/nd4j/jita/concurrency/CudaAffinityManagerTest.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
2
2021-03-01T07:46:24.000Z
2021-09-26T17:08:40.000Z
31.844086
105
0.572176
7,413
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.jita.concurrency; import org.apache.commons.lang3.ArrayUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.nd4j.linalg.factory.Nd4j; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.*; /** * @author dycjh@example.com */ @Ignore public class CudaAffinityManagerTest { @Before public void setUp() throws Exception { } @Test public void getDeviceForCurrentThread() throws Exception { CudaAffinityManager manager = new CudaAffinityManager(); Integer deviceId = manager.getDeviceForCurrentThread(); assertEquals(0, deviceId.intValue()); manager.attachThreadToDevice(Thread.currentThread().getId(), 1); assertEquals(1, manager.getDeviceForCurrentThread().intValue()); manager.attachThreadToDevice(Thread.currentThread().getId(), 0); assertEquals(0, manager.getDeviceForCurrentThread().intValue()); } @Test public void getDeviceForAnotherThread() throws Exception { CudaAffinityManager manager = new CudaAffinityManager(); Integer deviceId = manager.getDeviceForCurrentThread(); assertEquals(0, deviceId.intValue()); manager.attachThreadToDevice(1731L, 0); assertEquals(0, manager.getDeviceForThread(1731L).intValue()); } @Test public void getDeviceForAnotherThread2() throws Exception { CudaAffinityManager manager = new CudaAffinityManager(); Integer deviceId = manager.getDeviceForCurrentThread(); assertEquals(0, deviceId.intValue()); System.out.println("Current threadId: " + Thread.currentThread().getId()); Thread thread = new Thread(); long threadIdPrior = thread.getId(); System.out.println("Next threadId: " + thread.getId()); assertNotEquals(Thread.currentThread().getId(), thread.getId()); thread.start(); System.out.println("Current threadId: " + thread.getId()); assertEquals(threadIdPrior, thread.getId()); } /** * This is special test for multi-threaded environment * @throws Exception */ @Test public void getDeviceForAnotherThread3() throws Exception { final int limit = 10; final CudaAffinityManager manager = new CudaAffinityManager(); final Thread threads[] = new Thread[limit]; final AtomicBoolean[] results = new AtomicBoolean[limit]; for (int cnt = 0; cnt < limit; cnt++) { final int c = cnt; results[cnt] = new AtomicBoolean(false); threads[cnt] = new Thread(new Runnable() { @Override public void run() { assertEquals(0, manager.getDeviceForCurrentThread().intValue()); results[c].set(true); } }); manager.attachThreadToDevice(threads[cnt], 0); threads[cnt].start(); } for (int cnt = 0; cnt < limit; cnt++) { threads[cnt].join(); assertTrue("Failed for thread ["+ cnt+"]", results[cnt].get()); } } /** * This is special test for multi-threaded multi-gpu environment * @throws Exception */ @Test public void getDeviceForAnotherThread4() throws Exception { final int limit = 10; final CudaAffinityManager manager = new CudaAffinityManager(); final Thread threads[] = new Thread[limit]; final AtomicBoolean[] results = new AtomicBoolean[limit]; final int cards[] = new int[limit]; for (int cnt = 0; cnt < limit; cnt++) { final int c = cnt; results[cnt] = new AtomicBoolean(false); threads[cnt] = new Thread(new Runnable() { @Override public void run() { // this is pseudo-master thread final int deviceId = manager.getDeviceForCurrentThread(); Thread thread = new Thread(new Runnable() { @Override public void run() { int cdev = manager.getDeviceForCurrentThread(); assertEquals(deviceId, cdev); results[c].set(true); cards[c] = cdev; } }); manager.attachThreadToDevice(thread, deviceId); thread.start(); try { thread.join(); } catch (Exception e) { ; } } }); threads[cnt].start(); } for (int cnt = 0; cnt < limit; cnt++) { threads[cnt].join(); assertTrue("Failed for thread ["+ cnt+"]", results[cnt].get()); } int numDevices = Nd4j.getAffinityManager().getNumberOfDevices(); for (int c = 0; c < numDevices; c++) { assertTrue("Failed to find device ["+ c +"] in used devices", ArrayUtils.contains(cards, c)); } } }
3e118ed4fd3ec0683435306470ba032112374129
947
java
Java
src/main/java/info/ata4/bsplib/struct/DVertex.java
sneak-it/bspsrc
c55498518db85c54c54386df459cc8f830e11300
[ "Apache-2.0" ]
428
2015-01-08T22:09:24.000Z
2022-03-28T17:12:00.000Z
src/main/java/info/ata4/bsplib/struct/DVertex.java
sneak-it/bspsrc
c55498518db85c54c54386df459cc8f830e11300
[ "Apache-2.0" ]
117
2015-01-15T18:51:16.000Z
2022-03-31T19:04:23.000Z
src/main/java/info/ata4/bsplib/struct/DVertex.java
sneak-it/bspsrc
c55498518db85c54c54386df459cc8f830e11300
[ "Apache-2.0" ]
103
2015-01-18T22:53:49.000Z
2022-03-11T01:38:51.000Z
23.097561
69
0.647307
7,414
/* ** 2011 September 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.bsplib.struct; import info.ata4.bsplib.vector.Vector3f; import info.ata4.io.DataReader; import info.ata4.io.DataWriter; import java.io.IOException; /** * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class DVertex implements DStruct { public Vector3f point; @Override public int getSize() { return 12; } @Override public void read(DataReader in) throws IOException { point = Vector3f.read(in); } @Override public void write(DataWriter out) throws IOException { Vector3f.write(out, point); } }
3e118fe9455a25d1710e232e39ef3b4b40d7eaa6
1,637
java
Java
jmix-cuba/cuba/src/main/java/com/haulmont/cuba/gui/components/compatibility/PickerFieldFieldListenerWrapper.java
pierresj/jmix
df2da30df1e0bb7a10ffba3a98e16e9dc4d31318
[ "Apache-2.0" ]
30
2019-02-26T07:42:11.000Z
2022-03-31T16:46:03.000Z
jmix-cuba/cuba/src/main/java/com/haulmont/cuba/gui/components/compatibility/PickerFieldFieldListenerWrapper.java
pierresj/jmix
df2da30df1e0bb7a10ffba3a98e16e9dc4d31318
[ "Apache-2.0" ]
909
2019-02-26T08:29:19.000Z
2022-03-31T16:56:18.000Z
jmix-cuba/cuba/src/main/java/com/haulmont/cuba/gui/components/compatibility/PickerFieldFieldListenerWrapper.java
pierresj/jmix
df2da30df1e0bb7a10ffba3a98e16e9dc4d31318
[ "Apache-2.0" ]
15
2019-05-08T19:17:03.000Z
2022-03-31T06:24:22.000Z
30.314815
83
0.720831
7,415
/* * Copyright 2020 Haulmont. * * 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.haulmont.cuba.gui.components.compatibility; import com.haulmont.cuba.gui.components.PickerField; import io.jmix.core.Entity; import java.util.function.Consumer; @Deprecated public class PickerFieldFieldListenerWrapper<E extends Entity> implements Consumer<PickerField.FieldValueChangeEvent<E>> { protected final PickerField.FieldListener listener; public PickerFieldFieldListenerWrapper(PickerField.FieldListener listener) { this.listener = listener; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PickerFieldFieldListenerWrapper that = (PickerFieldFieldListenerWrapper) o; return listener.equals(that.listener); } @Override public int hashCode() { return listener.hashCode(); } @Override public void accept(PickerField.FieldValueChangeEvent<E> event) { listener.actionPerformed(event.getText(), event.getPrevValue()); } }
3e119108c850d230717b7d85a9395325b064f295
4,910
java
Java
fastersparql-operators/src/main/java/com/github/alexishuf/fastersparql/operators/impl/SimpleFilter.java
alexishuf/fastersparql
16272fe9c58c907b3027511a692b57a362122f20
[ "Apache-2.0" ]
null
null
null
fastersparql-operators/src/main/java/com/github/alexishuf/fastersparql/operators/impl/SimpleFilter.java
alexishuf/fastersparql
16272fe9c58c907b3027511a692b57a362122f20
[ "Apache-2.0" ]
null
null
null
fastersparql-operators/src/main/java/com/github/alexishuf/fastersparql/operators/impl/SimpleFilter.java
alexishuf/fastersparql
16272fe9c58c907b3027511a692b57a362122f20
[ "Apache-2.0" ]
null
null
null
43.451327
101
0.700611
7,416
package com.github.alexishuf.fastersparql.operators.impl; import com.github.alexishuf.fastersparql.client.model.Results; import com.github.alexishuf.fastersparql.client.model.row.RowOperations; import com.github.alexishuf.fastersparql.client.util.reactive.AbstractProcessor; import com.github.alexishuf.fastersparql.client.util.reactive.FSPublisher; import com.github.alexishuf.fastersparql.operators.BidCosts; import com.github.alexishuf.fastersparql.operators.FasterSparqlOpProperties; import com.github.alexishuf.fastersparql.operators.Filter; import com.github.alexishuf.fastersparql.operators.expressions.ExprEvaluator; import com.github.alexishuf.fastersparql.operators.expressions.ExprEvaluatorCompiler; import com.github.alexishuf.fastersparql.operators.expressions.ExprEvaluatorCompilerRegistry; import com.github.alexishuf.fastersparql.operators.expressions.RDFValues; import com.github.alexishuf.fastersparql.operators.metrics.PlanMetrics; import com.github.alexishuf.fastersparql.operators.plan.FilterPlan; import com.github.alexishuf.fastersparql.operators.providers.FilterProvider; import lombok.Value; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.github.alexishuf.fastersparql.operators.FasterSparqlOps.hasGlobalMetricsListeners; import static com.github.alexishuf.fastersparql.operators.FasterSparqlOps.sendMetrics; @Value @Accessors(fluent = true) public class SimpleFilter implements Filter { RowOperations rowOperations; ExprEvaluatorCompiler compiler; @Slf4j public static class Provider implements FilterProvider { private @MonotonicNonNull List<ExprEvaluatorCompiler> compilerCache = null; private ExprEvaluatorCompiler findCompiler() { if (compilerCache == null) { String name = FasterSparqlOpProperties.preferredExprCompiler(); ExprEvaluatorCompiler compiler = ExprEvaluatorCompilerRegistry.get().preferred(name); compilerCache = Collections.singletonList(compiler); } return compilerCache.get(0); } @Override public @NonNegative int bid(long flags) { if (findCompiler() == null) { log.warn("No ExprEvaluatorCompiler in ExprEvaluatorCompilerRegistry.get(), " + "will bid UNSUPPORTED"); return BidCosts.UNSUPPORTED; } return BidCosts.BUILTIN_COST; } @Override public Filter create(long flags, RowOperations rowOperations) { ExprEvaluatorCompiler compiler = findCompiler(); if (compiler == null) throw new UnsupportedOperationException("No ExprEvaluatorCompiler is available"); return new SimpleFilter(rowOperations, compiler); } } @Override public <R> Class<R> rowClass() { //noinspection unchecked return (Class<R>) rowOperations.rowClass(); } @Override public <R> Results<R> checkedRun(FilterPlan<R> plan) { Results<R> left = plan.input().execute(); Collection<? extends CharSequence> filters = plan.filters(); if (filters == null || filters.isEmpty()) return left; Class<? super R> rowClass = left.rowClass(); List<ExprEvaluator<R>> evaluators = new ArrayList<>(); for (CharSequence expr : filters) { evaluators.add(compiler.compile(rowClass, rowOperations, left.vars(), expr)); } val pub = new FilterPublisher<>(left.publisher(), evaluators, plan); return new Results<>(left.vars(), rowClass, pub); } private static class FilterPublisher<R> extends AbstractProcessor<R, R> { private final FilterPlan<R> plan; private final List<ExprEvaluator<R>> predicates; public FilterPublisher(FSPublisher<? extends R> upstream, List<ExprEvaluator<R>> predicates, FilterPlan<R> plan) { super(upstream); this.predicates = predicates; this.plan = plan; } @Override protected void handleOnNext(R row) { for (ExprEvaluator<R> predicate : predicates) { if (!RDFValues.coerceToBool(predicate.evaluate(row))) return; // discard row } emit(row); } @Override protected void onTerminate(@Nullable Throwable error, boolean cancelled) { if (hasGlobalMetricsListeners()) sendMetrics(plan, new PlanMetrics(plan.name(), rows, start, error, cancelled)); } } }
3e1192cbba360bd4011a84fcf3a4771a96d3c62c
78
java
Java
src/main/java/com/xabe/mapstruct/dto/CarTypeDTO.java
xabe/java-test
6b358e3c8fb3eab79f28d00d2ac42d2eca515b95
[ "MIT" ]
null
null
null
src/main/java/com/xabe/mapstruct/dto/CarTypeDTO.java
xabe/java-test
6b358e3c8fb3eab79f28d00d2ac42d2eca515b95
[ "MIT" ]
3
2021-12-14T21:15:59.000Z
2021-12-18T18:18:44.000Z
src/main/java/com/xabe/mapstruct/dto/CarTypeDTO.java
xabe/java-test
6b358e3c8fb3eab79f28d00d2ac42d2eca515b95
[ "MIT" ]
null
null
null
11.142857
31
0.730769
7,417
package com.xabe.mapstruct.dto; public enum CarTypeDTO { CREDIT, DEBIT }
3e1192df72f84ee420d173aa99b6dac0ce5daaf0
1,391
java
Java
src/main/java/com/mshams/cs/algorithms/dp/PartitionProblem.java
mehrshadshams/algorithms
e5bfe270c468ecefb467559b65aa88a844f15cad
[ "MIT" ]
null
null
null
src/main/java/com/mshams/cs/algorithms/dp/PartitionProblem.java
mehrshadshams/algorithms
e5bfe270c468ecefb467559b65aa88a844f15cad
[ "MIT" ]
null
null
null
src/main/java/com/mshams/cs/algorithms/dp/PartitionProblem.java
mehrshadshams/algorithms
e5bfe270c468ecefb467559b65aa88a844f15cad
[ "MIT" ]
null
null
null
22.079365
72
0.428469
7,418
package com.mshams.cs.algorithms.dp; /** * Skienna * Ch. 8.5 */ public class PartitionProblem { public static void main(String[] args) { PartitionProblem p = new PartitionProblem(); p.partition(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 3); } public void partition(int[] s, int k) { int n = s.length; int[][] m = new int[n + 1][k + 1]; int[][] d = new int[n + 1][k + 1]; int[] p = new int[n + 1]; for (int i = 1; i <= n; i++) { p[i] = p[i - 1] + s[i - 1]; } for (int i = 1; i <= n; i++) m[i][1] = p[i]; for (int j = 1; j < k; j++) m[1][j] = s[0]; for (int i = 2; i <= n; i++) { for (int j = 2; j <= k; j++) { m[i][j] = Integer.MAX_VALUE; for (int x = 1; x <= (i - 1); x++) { int cost = Math.max(m[x][j - 1], p[i] - p[x]); if (m[i][j] > cost) { m[i][j] = cost; d[i][j] = x; } } } } reconstructPartitions(s, d, n, k); } private void reconstructPartitions(int[] s, int[][] d, int n, int k) { if (k == 1) { print(s, 1, n); } else { reconstructPartitions(s, d, d[n][k], k - 1); print(s, d[n][k] + 1, n); } } private void print(int[] s, int start, int end) { for (int i = start; i <= end; i++) { System.out.print(" " + s[i - 1] + " "); } System.out.println(); } }
3e1192fe19c9019bf75918a19daf13424c0c3c96
4,871
java
Java
tencentcloud-sdk-java-tcr/src/main/java/com/tencentcloudapi/tcr/v20190924/models/TriggerInvokePara.java
Chronos-Ye/tencentcloud-sdk-java
07e1d5d59359f81c894070be98262f0a1fbe2ebd
[ "Apache-2.0" ]
3
2020-07-28T07:46:56.000Z
2021-05-24T12:09:48.000Z
tencentcloud-sdk-java-tcr/src/main/java/com/tencentcloudapi/tcr/v20190924/models/TriggerInvokePara.java
Chronos-Ye/tencentcloud-sdk-java
07e1d5d59359f81c894070be98262f0a1fbe2ebd
[ "Apache-2.0" ]
null
null
null
tencentcloud-sdk-java-tcr/src/main/java/com/tencentcloudapi/tcr/v20190924/models/TriggerInvokePara.java
Chronos-Ye/tencentcloud-sdk-java
07e1d5d59359f81c894070be98262f0a1fbe2ebd
[ "Apache-2.0" ]
1
2021-03-23T03:19:20.000Z
2021-03-23T03:19:20.000Z
23.531401
83
0.659618
7,419
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.tcr.v20190924.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class TriggerInvokePara extends AbstractModel{ /** * AppId 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("AppId") @Expose private String AppId; /** * TKE集群ID 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("ClusterId") @Expose private String ClusterId; /** * TKE集群命名空间 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("Namespace") @Expose private String Namespace; /** * TKE集群工作负载名称 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("ServiceName") @Expose private String ServiceName; /** * TKE集群工作负载中容器名称 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("ContainerName") @Expose private String ContainerName; /** * TKE集群地域数字ID 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("ClusterRegion") @Expose private Long ClusterRegion; /** * Get AppId 注意:此字段可能返回 null,表示取不到有效值。 * @return AppId AppId 注意:此字段可能返回 null,表示取不到有效值。 */ public String getAppId() { return this.AppId; } /** * Set AppId 注意:此字段可能返回 null,表示取不到有效值。 * @param AppId AppId 注意:此字段可能返回 null,表示取不到有效值。 */ public void setAppId(String AppId) { this.AppId = AppId; } /** * Get TKE集群ID 注意:此字段可能返回 null,表示取不到有效值。 * @return ClusterId TKE集群ID 注意:此字段可能返回 null,表示取不到有效值。 */ public String getClusterId() { return this.ClusterId; } /** * Set TKE集群ID 注意:此字段可能返回 null,表示取不到有效值。 * @param ClusterId TKE集群ID 注意:此字段可能返回 null,表示取不到有效值。 */ public void setClusterId(String ClusterId) { this.ClusterId = ClusterId; } /** * Get TKE集群命名空间 注意:此字段可能返回 null,表示取不到有效值。 * @return Namespace TKE集群命名空间 注意:此字段可能返回 null,表示取不到有效值。 */ public String getNamespace() { return this.Namespace; } /** * Set TKE集群命名空间 注意:此字段可能返回 null,表示取不到有效值。 * @param Namespace TKE集群命名空间 注意:此字段可能返回 null,表示取不到有效值。 */ public void setNamespace(String Namespace) { this.Namespace = Namespace; } /** * Get TKE集群工作负载名称 注意:此字段可能返回 null,表示取不到有效值。 * @return ServiceName TKE集群工作负载名称 注意:此字段可能返回 null,表示取不到有效值。 */ public String getServiceName() { return this.ServiceName; } /** * Set TKE集群工作负载名称 注意:此字段可能返回 null,表示取不到有效值。 * @param ServiceName TKE集群工作负载名称 注意:此字段可能返回 null,表示取不到有效值。 */ public void setServiceName(String ServiceName) { this.ServiceName = ServiceName; } /** * Get TKE集群工作负载中容器名称 注意:此字段可能返回 null,表示取不到有效值。 * @return ContainerName TKE集群工作负载中容器名称 注意:此字段可能返回 null,表示取不到有效值。 */ public String getContainerName() { return this.ContainerName; } /** * Set TKE集群工作负载中容器名称 注意:此字段可能返回 null,表示取不到有效值。 * @param ContainerName TKE集群工作负载中容器名称 注意:此字段可能返回 null,表示取不到有效值。 */ public void setContainerName(String ContainerName) { this.ContainerName = ContainerName; } /** * Get TKE集群地域数字ID 注意:此字段可能返回 null,表示取不到有效值。 * @return ClusterRegion TKE集群地域数字ID 注意:此字段可能返回 null,表示取不到有效值。 */ public Long getClusterRegion() { return this.ClusterRegion; } /** * Set TKE集群地域数字ID 注意:此字段可能返回 null,表示取不到有效值。 * @param ClusterRegion TKE集群地域数字ID 注意:此字段可能返回 null,表示取不到有效值。 */ public void setClusterRegion(Long ClusterRegion) { this.ClusterRegion = ClusterRegion; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "AppId", this.AppId); this.setParamSimple(map, prefix + "ClusterId", this.ClusterId); this.setParamSimple(map, prefix + "Namespace", this.Namespace); this.setParamSimple(map, prefix + "ServiceName", this.ServiceName); this.setParamSimple(map, prefix + "ContainerName", this.ContainerName); this.setParamSimple(map, prefix + "ClusterRegion", this.ClusterRegion); } }
3e11930bc1479e3817517825370d7249ecc3e9c6
224
java
Java
flexi-elephant-loop/src/main/java/com/flexi/elephant/loop/LifeCycle.java
Lien6o/flexi-elephant
e0a936d55f554529969f231607d905e5407b6f4d
[ "Apache-2.0" ]
null
null
null
flexi-elephant-loop/src/main/java/com/flexi/elephant/loop/LifeCycle.java
Lien6o/flexi-elephant
e0a936d55f554529969f231607d905e5407b6f4d
[ "Apache-2.0" ]
null
null
null
flexi-elephant-loop/src/main/java/com/flexi/elephant/loop/LifeCycle.java
Lien6o/flexi-elephant
e0a936d55f554529969f231607d905e5407b6f4d
[ "Apache-2.0" ]
null
null
null
11.789474
36
0.549107
7,420
package com.flexi.elephant.loop; /** * @author Lien6o */ public interface LifeCycle { /** * init */ void init() throws Exception; /** * destroy */ void destroy() throws Exception; }
3e1193a0a9be0089c11a641eb05213547a2bf21e
16,348
java
Java
app/src/main/java/com/ls/drupalcon/model/managers/SharedScheduleManager.java
Anagraph/vg2017-connfa-android
0d9ee5248c5a21c0152cba5bdee34bfb48384e97
[ "Apache-2.0" ]
134
2016-01-14T16:05:32.000Z
2021-10-16T10:20:10.000Z
app/src/main/java/com/ls/drupalcon/model/managers/SharedScheduleManager.java
Anagraph/vg2017-connfa-android
0d9ee5248c5a21c0152cba5bdee34bfb48384e97
[ "Apache-2.0" ]
37
2016-04-14T09:56:00.000Z
2021-12-07T15:28:39.000Z
app/src/main/java/com/ls/drupalcon/model/managers/SharedScheduleManager.java
Anagraph/vg2017-connfa-android
0d9ee5248c5a21c0152cba5bdee34bfb48384e97
[ "Apache-2.0" ]
110
2015-12-08T14:14:42.000Z
2020-10-05T07:37:18.000Z
34.489451
200
0.642586
7,421
package com.ls.drupalcon.model.managers; import android.net.Uri; import android.os.AsyncTask; import android.widget.Toast; import com.ls.drupal.DrupalClient; import com.ls.drupalcon.R; import com.ls.drupalcon.app.App; import com.ls.drupalcon.model.Listener; import com.ls.drupalcon.model.Model; import com.ls.drupalcon.model.PreferencesManager; import com.ls.drupalcon.model.dao.EventDao; import com.ls.drupalcon.model.dao.SharedEventsDao; import com.ls.drupalcon.model.dao.SharedScheduleDao; import com.ls.drupalcon.model.data.Event; import com.ls.drupalcon.model.data.SharedEvents; import com.ls.drupalcon.model.data.PostResponse; import com.ls.drupalcon.model.data.Schedule; import com.ls.drupalcon.model.data.SharedSchedule; import com.ls.http.base.BaseRequest; import com.ls.http.base.RequestConfig; import com.ls.http.base.ResponseData; import com.ls.utils.L; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SharedScheduleManager { public static final long MY_DEFAULT_SCHEDULE_CODE = -1; private boolean isInitialized; private SharedScheduleDao sharedScheduleDao; private SharedEventsDao sharedEventsDao; private EventDao mEventDao; private List<SharedEvents> sharedEvents = new ArrayList<>(); private List<SharedSchedule> schedules = new ArrayList<>(); private List<Long> favoriteEventsIds = new ArrayList<>(); private CurrentScheduleManager currentScheduleManager; public SharedScheduleManager() { this.sharedScheduleDao = new SharedScheduleDao(); this.sharedEventsDao = new SharedEventsDao(); this.mEventDao = new EventDao(App.getContext()); this.currentScheduleManager = new CurrentScheduleManager(); } //must called in background public void initialize() { if (!isInitialized) { isInitialized = true; SharedSchedule currentSchedule = currentScheduleManager.getCurrentSchedule(); List<SharedSchedule> allSchedules = sharedScheduleDao.getAllSafe(); sharedEvents = sharedEventsDao.getAllSafe(); if (!allSchedules.contains(currentSchedule)) { schedules.add(currentSchedule); sharedScheduleDao.saveOrUpdateSafe(currentSchedule); } schedules.addAll(allSchedules); favoriteEventsIds.addAll(getFavoriteEventsSafe()); } } public List<SharedSchedule> getSchedules() { return schedules; } public List<String> getAllSchedulesNameList() { List<String> result = new ArrayList<>(); for (SharedSchedule item : schedules) { result.add(item.getScheduleName()); } return result; } public void setCurrentSchedule(int scheduleOrder) { currentScheduleManager.setCurrentSchedule(scheduleOrder); } private SharedSchedule getCurrentSchedule() { return currentScheduleManager.getCurrentSchedule(); } public long getCurrentScheduleId() { return currentScheduleManager.getCurrentScheduleId(); } public String getCurrentFriendScheduleName() { return getCurrentSchedule().getScheduleName(); } public int getItemPosition() { return currentScheduleManager.getItemPosition(); } public List<Long> getFavoriteEventDays() { return mEventDao.selectDistrictFavoriteDateSafe(); } private List<Long> getFavoriteEventsSafe() { return mEventDao.selectFavoriteEventsSafe(); } public void setFavoriteEvent(final long eventId, final boolean isFavorite) { if (isFavorite) { favoriteEventsIds.add(eventId); } else { favoriteEventsIds.remove(eventId); } new Thread(new Runnable() { @Override public void run() { mEventDao.setFavoriteSafe(eventId, isFavorite); } }).start(); } private void saveNewSharedSchedule(long scheduleCode, String name) { SharedSchedule schedule = generateSchedule(scheduleCode, name); currentScheduleManager.setCurrentSchedule(schedule); schedules.add(schedule); new Thread(new Runnable() { @Override public void run() { } }).start(); this.sharedScheduleDao.saveDataSafe(schedule); } public void renameSchedule(String newScheduleName) { SharedSchedule schedule = schedules.get(currentScheduleManager.getItemPosition()); schedule.setScheduleName(newScheduleName); currentScheduleManager.setCurrentSchedule(schedule); AsyncTask.execute(new Runnable() { @Override public void run() { sharedScheduleDao.saveOrUpdateSafe(currentScheduleManager.getCurrentSchedule()); } }); } public void deleteSharedScheduleFromCache() { currentScheduleManager.deleteSharedScheduleFromCache(); } public void restoreSchedule() { currentScheduleManager.restoreSchedule(); } public void deleteSharedSchedule() { currentScheduleManager.deleteSharedSchedule(); } public List<SharedEvents> getAllFriendsFavorite() { return sharedEvents; } public ArrayList<Long> getFriendsFavoriteEventIds() { ArrayList<Long> favoriteEventIds = new ArrayList<>(); for (SharedEvents favorite : getAllFriendsFavorite()) { if (favorite.getId() == (Model.instance().getSharedScheduleManager().getCurrentScheduleId())) favoriteEventIds.add(favorite.getEventId()); } return favoriteEventIds; } public List<Long> getMyFavoriteEventIds() { return favoriteEventsIds; } public List<Event> getAllFriendsFavoriteEvent() { EventDao eventDao = Model.instance().getEventManager().getEventDao(); return eventDao.selectEventsByIdsSafe(getFriendsFavoriteEventIds()); } public void saveSharedEvents(final ArrayList<SharedEvents> items) { new Thread(new Runnable() { @Override public void run() { sharedEventsDao.deleteAllSafe(); sharedEventsDao.saveDataSafe(items); } }).start(); sharedEvents.clear(); sharedEvents.addAll(items); } private void saveFavoriteEventsSafe(final ArrayList<SharedEvents> items) { sharedEvents.addAll(items); new Thread(new Runnable() { @Override public void run() { sharedEventsDao.saveDataSafe(items); } }).start(); } public SharedEventsDao getSharedEventsDao() { return sharedEventsDao; } public SharedScheduleDao getSharedScheduleDao() { return sharedScheduleDao; } private List<SharedSchedule> getSharedSchedulesById(long eventId) { return sharedScheduleDao.getScheduleNameId(eventId); } public ArrayList<String> getSharedSchedulesNamesById(long eventId) { List<SharedSchedule> list = getSharedSchedulesById(eventId); ArrayList<String> namesList = new ArrayList<>(); for (SharedSchedule schedule : list) { namesList.add(schedule.getScheduleName()); } return namesList; } public boolean checkIfFriendIsGoing(long eventId) { for (SharedEvents events : sharedEvents) { if (events.getEventId() == eventId) { return true; } } return false; } public void postAllSchedules() { new Thread(new Runnable() { @Override public void run() { PreferencesManager instance = PreferencesManager.getInstance(); if (instance.getMyScheduleCode() == MY_DEFAULT_SCHEDULE_CODE) { postSchedules(); } else { updateSchedules(); } } }).start(); } private Map<String, List<Long>> getObjectToPost(List<Long> ids) { Map<String, List<Long>> objectToPost = new HashMap<>(); objectToPost.put("data", ids); L.e("Object to post = " + objectToPost.toString()); return objectToPost; } public String getPath() { List<SharedSchedule> schedules = Model.instance().getSharedScheduleManager().getSchedules(); Uri.Builder builder = new Uri.Builder(); builder.appendPath("getSchedules"); for (SharedSchedule schedule : schedules) { Long id = schedule.getId(); if (id != MY_DEFAULT_SCHEDULE_CODE) { builder.appendQueryParameter("codes[]=", schedule.getId().toString()); } } L.e("Get URL = " + builder.build().toString()); return builder.build().toString(); } public Long getMyScheduleCode() { return Model.instance().getPreferencesManager().getMyScheduleCode(); } private SharedSchedule generateSchedule(long scheduleCode, String name) { return new SharedSchedule(scheduleCode, name); } public boolean checkIfNameIsExist(String name) { for (SharedSchedule item : schedules) { if (item.getScheduleName().equals(name)) { ToastManager.messageSync(App.getContext(), App.getContext().getString(R.string.this_schedule_name_already_exist)); // Toast.makeText(App.getContext(), R.string.this_schedule_name_already_exist, Toast.LENGTH_LONG).show(); return true; } } return false; } public boolean checkIfCodeIsExist(long code) { for (SharedSchedule item : schedules) { if (item.getId() == code) { currentScheduleManager.setCurrentSchedule(item); Toast.makeText(App.getContext(), R.string.this_schedule_already_exist, Toast.LENGTH_LONG).show(); return true; } } return false; } private void initializeError() { if (!isInitialized) { throw new Error("SharedScheduleManager should be initialized asynchronously"); } } private void updateSchedules() { RequestConfig requestConfig = new RequestConfig(); requestConfig.setResponseFormat(BaseRequest.ResponseFormat.JSON); requestConfig.setRequestFormat(BaseRequest.RequestFormat.JSON); requestConfig.setResponseClassSpecifier(PostResponse.class); final PreferencesManager instance = PreferencesManager.getInstance(); BaseRequest request = new BaseRequest(BaseRequest.RequestMethod.PUT, App.getContext().getString(R.string.api_value_base_url) + "updateSchedule/" + instance.getMyScheduleCode(), requestConfig); request.setObjectToPost(getObjectToPost(favoriteEventsIds)); DrupalClient client = Model.instance().getClient(); client.performRequest(request, false); } private void postSchedules() { RequestConfig requestConfig = new RequestConfig(); requestConfig.setResponseFormat(BaseRequest.ResponseFormat.JSON); requestConfig.setRequestFormat(BaseRequest.RequestFormat.JSON); requestConfig.setResponseClassSpecifier(PostResponse.class); BaseRequest request = new BaseRequest(BaseRequest.RequestMethod.POST, App.getContext().getString(R.string.api_value_base_url) + "createSchedule", requestConfig); request.setObjectToPost(getObjectToPost(favoriteEventsIds)); DrupalClient client = Model.instance().getClient(); client.performRequest(request, "post", new DrupalClient.OnResponseListener() { @Override public void onResponseReceived(ResponseData data, Object tag) { PostResponse response = (PostResponse) data.getData(); L.e("Schedule Code = " + response.getCode() + " Tag = " + tag); Long code = response.getCode(); PreferencesManager.getInstance().saveMyScheduleCode(code); } @Override public void onError(ResponseData data, Object tag) { L.e("Update Error = " + data); } @Override public void onCancel(Object tag) { L.e("Update Cancel = " + tag); } }, false); } public void fetchSharedEventsByCode(final long scheduleCode, final String name, final Listener<ResponseData, ResponseData> listener) { RequestConfig requestConfig = new RequestConfig(); requestConfig.setResponseFormat(BaseRequest.ResponseFormat.JSON); requestConfig.setRequestFormat(BaseRequest.RequestFormat.JSON); requestConfig.setResponseClassSpecifier(Schedule.class); BaseRequest request = new BaseRequest(BaseRequest.RequestMethod.GET, App.getContext().getString(R.string.api_value_base_url) + "getSchedule/" + scheduleCode, requestConfig); DrupalClient client = Model.instance().getClient(); client.performRequest(request, "Fetch Shared Events By Code", new DrupalClient.OnResponseListener() { @Override public void onResponseReceived(ResponseData data, Object tag) { Schedule schedule = (Schedule) data.getData(); ArrayList<SharedEvents> sharedSchedules = new ArrayList<>(); for (Long eventId : schedule.getEvents()) { sharedSchedules.add(new SharedEvents(eventId, schedule.getCode())); } Model.instance().getSharedScheduleManager().saveNewSharedSchedule(scheduleCode, name); Model.instance().getSharedScheduleManager().saveFavoriteEventsSafe(sharedSchedules); listener.onSucceeded(data); } @Override public void onError(ResponseData data, Object tag) { listener.onFailed(data); } @Override public void onCancel(Object tag) { } }, false); } private class CurrentScheduleManager { private SharedSchedule currentSchedule; private List<SharedSchedule> schedulesTemp; private SharedSchedule scheduleTemp; public CurrentScheduleManager() { this.currentSchedule = new SharedSchedule(MY_DEFAULT_SCHEDULE_CODE, App.getContext().getString(R.string.my_schedule)); } public void setCurrentSchedule(int scheduleOrder) { this.currentSchedule = schedules.get(scheduleOrder); } public void setCurrentSchedule(SharedSchedule currentSchedule) { this.currentSchedule = currentSchedule; } private SharedSchedule getCurrentSchedule() { return currentSchedule; } public long getCurrentScheduleId() { return currentSchedule.getId(); } public String getCurrentFriendScheduleName() { return getCurrentSchedule().getScheduleName(); } public int getItemPosition() { return schedules.indexOf(currentSchedule); } public void deleteSharedScheduleFromCache() { schedulesTemp = new ArrayList<>(schedules); scheduleTemp = currentSchedule; schedules.remove(currentSchedule); currentSchedule = schedules.get(0); } public void restoreSchedule() { schedules = schedulesTemp; currentSchedule = scheduleTemp; } public void deleteSharedSchedule() { removeSharedEvents(); new Thread(new Runnable() { @Override public void run() { sharedScheduleDao.deleteDataSafe(scheduleTemp.getId()); sharedEventsDao.deleteDataSafe(scheduleTemp.getId()); } }).start(); } private void removeSharedEvents() { List<SharedEvents> removeList = new ArrayList<>(); for (SharedEvents events : sharedEvents) { if (events.getId() == scheduleTemp.getId()){ removeList.add(events); } } sharedEvents.removeAll(removeList); L.e("removeSharedEvents = " + sharedEvents.toString()); } } }
3e119430826799db1e07eafae61941a467355930
182
java
Java
app/src/main/java/com/ylzyh/plugin/medicineRemind/widget/pickerView/listener/OnDismissListener.java
JAYAndroid/medicineRemind
c42741ec4c5e2c963b44c653fc58d40c86bb1e55
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ylzyh/plugin/medicineRemind/widget/pickerView/listener/OnDismissListener.java
JAYAndroid/medicineRemind
c42741ec4c5e2c963b44c653fc58d40c86bb1e55
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ylzyh/plugin/medicineRemind/widget/pickerView/listener/OnDismissListener.java
JAYAndroid/medicineRemind
c42741ec4c5e2c963b44c653fc58d40c86bb1e55
[ "Apache-2.0" ]
null
null
null
20.222222
67
0.741758
7,422
package com.ylzyh.plugin.medicineRemind.widget.pickerView.listener; /** * Created by Sai on 15/8/9. */ public interface OnDismissListener { public void onDismiss(Object o); }
3e11943b343cce0164253a22174b7c53e43aeaf7
1,642
java
Java
silent-genes-io/src/main/java/org/monarchinitiative/sgenes/io/json/deserialize/GeneDeserializer.java
monarch-initiative/SilentGenes
5143cb62370b82b2fd38b4b5e35eb7e0f0faac97
[ "BSD-3-Clause" ]
null
null
null
silent-genes-io/src/main/java/org/monarchinitiative/sgenes/io/json/deserialize/GeneDeserializer.java
monarch-initiative/SilentGenes
5143cb62370b82b2fd38b4b5e35eb7e0f0faac97
[ "BSD-3-Clause" ]
null
null
null
silent-genes-io/src/main/java/org/monarchinitiative/sgenes/io/json/deserialize/GeneDeserializer.java
monarch-initiative/SilentGenes
5143cb62370b82b2fd38b4b5e35eb7e0f0faac97
[ "BSD-3-Clause" ]
null
null
null
34.93617
110
0.74665
7,423
package org.monarchinitiative.sgenes.io.json.deserialize; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import org.monarchinitiative.svart.GenomicRegion; import org.monarchinitiative.sgenes.model.Gene; import org.monarchinitiative.sgenes.model.GeneIdentifier; import org.monarchinitiative.sgenes.model.Transcript; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class GeneDeserializer extends StdDeserializer<Gene> { private static final long serialVersionUID = 1L; public GeneDeserializer() { this(Gene.class); } protected GeneDeserializer(Class<?> vc) { super(vc); } @Override public Gene deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException { ObjectCodec codec = jp.getCodec(); JsonNode node = codec.readTree(jp); GeneIdentifier id = codec.treeToValue(node.get("id"), GeneIdentifier.class); GenomicRegion location = codec.treeToValue(node.get("loc"), GenomicRegion.class); Iterator<JsonNode> transcriptIterator = node.get("transcripts").elements(); List<Transcript> transcripts = new LinkedList<>(); while (transcriptIterator.hasNext()) { transcripts.add(codec.treeToValue(transcriptIterator.next(), Transcript.class)); } return Gene.of(id, location, transcripts); } }
3e11951349ac914c26890508f04098ebc01d2bab
1,037
java
Java
src/main/java/org/topicquests/backside/kafka/connector/AbstractBaseConnector.java
topicquests/tqks-kafka-support
2653e866780497959a8c4e1eaafd5680ada88516
[ "Apache-2.0" ]
null
null
null
src/main/java/org/topicquests/backside/kafka/connector/AbstractBaseConnector.java
topicquests/tqks-kafka-support
2653e866780497959a8c4e1eaafd5680ada88516
[ "Apache-2.0" ]
null
null
null
src/main/java/org/topicquests/backside/kafka/connector/AbstractBaseConnector.java
topicquests/tqks-kafka-support
2653e866780497959a8c4e1eaafd5680ada88516
[ "Apache-2.0" ]
null
null
null
25.292683
77
0.733848
7,424
/* * Copyright 2017, 2018 TopicQuests * * 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.topicquests.backside.kafka.connector; import org.topicquests.support.api.IEnvironment; /** * @author jackpark * */ public abstract class AbstractBaseConnector { protected IEnvironment environment; /** * */ public AbstractBaseConnector(IEnvironment env) { environment = env; } public abstract void close(); /** * Allow extension to do its own initializations */ public abstract void initialize(); }
3e119636e10a7e3f90f4d140ed0ef3228251d9d3
983
java
Java
consumer-pat/consumer-pat-main/src/main/java/br/com/alelo/consumer/consumerpat/data/model/Card.java
dalyleide/Microservices-Portifolio
c958aa440e9839d7e5487bf486919ab0f2497b91
[ "MIT" ]
null
null
null
consumer-pat/consumer-pat-main/src/main/java/br/com/alelo/consumer/consumerpat/data/model/Card.java
dalyleide/Microservices-Portifolio
c958aa440e9839d7e5487bf486919ab0f2497b91
[ "MIT" ]
null
null
null
consumer-pat/consumer-pat-main/src/main/java/br/com/alelo/consumer/consumerpat/data/model/Card.java
dalyleide/Microservices-Portifolio
c958aa440e9839d7e5487bf486919ab0f2497b91
[ "MIT" ]
null
null
null
23.404762
89
0.71414
7,425
package br.com.alelo.consumer.consumerpat.data.model; import br.com.alelo.consumer.consumerpat.util.TypeCardsEnum; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; import java.math.BigDecimal; @NoArgsConstructor @AllArgsConstructor @Data @Entity @Table(name = "CARDS") public class Card implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer id; @Column(name = "CARD_NUMBER", nullable = false, length = 16) Long number; @Column(name = "BALANCE", nullable = false) BigDecimal balance; @Column(name = "TYPE_CARD", nullable = false) TypeCardsEnum type; @ManyToOne Consumer consumer; public Card(Consumer consumer, TypeCardsEnum type, BigDecimal balance, Long number) { this.balance = balance; this.consumer = consumer; this.number = number; this.type = type; } }
3e1196e27d7cf8f43d5ba6addc565bb79e119317
7,278
java
Java
learn.online.impl/src/main/java/learn/online/impl/servicemapper/impl/Forumpostserviceimp.java
yufengqi/parent
21473a70310a6bd7fda56825bc18cda1f3a8dbfd
[ "Apache-2.0" ]
null
null
null
learn.online.impl/src/main/java/learn/online/impl/servicemapper/impl/Forumpostserviceimp.java
yufengqi/parent
21473a70310a6bd7fda56825bc18cda1f3a8dbfd
[ "Apache-2.0" ]
null
null
null
learn.online.impl/src/main/java/learn/online/impl/servicemapper/impl/Forumpostserviceimp.java
yufengqi/parent
21473a70310a6bd7fda56825bc18cda1f3a8dbfd
[ "Apache-2.0" ]
null
null
null
26.955556
97
0.714619
7,426
package learn.online.impl.servicemapper.impl; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import learn.online.api.service.servicemapper.Forumpostservice; import learn.online.common.util.PageBean; import learn.online.common.vo.Foruminfo; import learn.online.common.vo.Forumpost; import learn.online.common.vo.Forumrelation; import learn.online.common.vo.Forumreview; import learn.online.common.vo.Registertable; import learn.online.impl.dao.impl.ControlforumpostImp; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; public class Forumpostserviceimp implements Forumpostservice { private ControlforumpostImp fpi; // private ControlForumralationImp fpi; public void setFpi(ControlforumpostImp fpi) { this.fpi = fpi; } HttpServletRequest request = ServletActionContext.getRequest(); public Map<String, Object> getSessionnow() { Map<String, Object> session = ActionContext.getContext().getSession(); return session; } //���� public List<Forumpost> Allforumposts() { // TODO Auto-generated method stub List<Forumpost> list = fpi.queryAll(); return list; } public PageBean<Forumpost> AllClasses(String sql,String coutsql,int pageSize,int page) { // TODO Auto-generated method stub int allRow = this.fpi.getAllRowCount(coutsql); //总记录数 int totalPage = PageBean.countTatalPage(pageSize, allRow); //总页数 final int offset = PageBean.countOffset(pageSize, page); //当前页开始记录 final int length = pageSize; // 每页记录数 final int currentPage = PageBean.countCurrentPage(page); // 当前页 List list = this.fpi.queryAll(sql,offset, length);//把分页信息保存到Bean当中 PageBean<Forumpost> pageBean = new PageBean<Forumpost>(); pageBean.setPageSize(pageSize); pageBean.setCurrentPage(currentPage); pageBean.setAllRow(allRow); pageBean.setTotalPage(totalPage); pageBean.setList(list); //pageBean.init(); System.out.print(pageBean.getList()); return pageBean; } public PageBean<Forumreview> AllClassesreview(String sql,String coutsql,int pageSize,int page) { // TODO Auto-generated method stub int allRow = this.fpi.getAllRowCount(coutsql); //总记录数 int totalPage = PageBean.countTatalPage(pageSize, allRow); //总页数 final int offset = PageBean.countOffset(pageSize, page); //当前页开始记录 final int length = pageSize; // 每页记录数 final int currentPage = PageBean.countCurrentPage(page); // 当前页 List list = this.fpi.queryAll(sql,offset, length);//把分页信息保存到Bean当中 PageBean<Forumreview> pageBean = new PageBean<Forumreview>(); pageBean.setPageSize(pageSize); pageBean.setCurrentPage(currentPage); pageBean.setAllRow(allRow); pageBean.setTotalPage(totalPage); pageBean.setList(list); //pageBean.init(); System.out.print(pageBean.getList()); return pageBean; } public boolean insertforumpostserver(Forumpost an){ Foruminfo fi = (Foruminfo)getSessionnow().get("Foruminfo"); Registertable rt = (Registertable)getSessionnow().get("register"); an.setForuminfo(fi); an.setRight(0); an.setPosttime(new Date()); an.setPostman(rt.getYhm()); fpi.insert(an); return true; } public boolean delectforumpostserver(Forumpost an) { // TODO Auto-generated method stub an = fpi.selectById(an.getFpid()); boolean flag = fpi.delete(an); if(flag == true) return true; return false; } public boolean updateforumpostserver(Forumpost an) { // TODO Auto-generated method stub boolean flag = fpi.update(an); if(flag == true) return true; return false; } public Forumpost selectupdateforumpostserver(int i) { // TODO Auto-generated method stub Forumpost an = fpi.selectById(i); return an; } public boolean passforumpostserver(Forumpost ci) { // TODO Auto-generated method stub ci.setRight(1); boolean flag = fpi.update(ci); if(flag == true) return true; return false; } public List<Forumpost> passAllforumposts() { // TODO Auto-generated method stub List<Forumpost> list = null; int manage = Integer.parseInt(request.getParameter("manage")); if(manage == 0) { list = fpi.queryAllpassTeacher(); } else if(manage == 1) { list = fpi.queryAllpassStudent(); } else if(manage == 2) { list = fpi.queryAllpass(); } return list; } //���� public boolean insertforumreviewserver(Forumreview ci) { // TODO Auto-generated method stub Forumpost fp = (Forumpost)getSessionnow().get("Forumpost"); Registertable rt = (Registertable)getSessionnow().get("register"); ci.setForumpost(fp); ci.setForumrman(rt.getYhm());//��Ҫ�׳��쳣�� ci.setForumrtime(new Date()); boolean flag = fpi.insertForumReview(ci); if(flag) { return true; } return false; } public List<Forumreview> Allforumreviewes() { // TODO Auto-generated method stub List<Forumreview> list = fpi.queryAllreview(); return list; } //��̳��ϵ public boolean insertralationserver(Forumrelation an){ Foruminfo fi = (Foruminfo)getSessionnow().get("Foruminfo"); Registertable registertable = (Registertable)getSessionnow().get("register"); if(registertable.getIdentity() == 0) { an.setRegistertableByJid(registertable); an.setTforumidentity(1); } else { an.setRegistertableBySid(registertable); an.setSforumidentity(1); } an.setForuminfo(fi); fpi.insert(an); return true; } public boolean delectralationserver(Forumrelation an) { // TODO Auto-generated method stub boolean flag = false; Registertable registertable = (Registertable)getSessionnow().get("register"); String id = request.getParameter("cid"); int cid = Integer.parseInt(id); Forumrelation cr = fpi.selectByRid(cid); if(registertable.getIdentity() == 1) { an.setTforumidentity(1); an.setRegistertableByJid(null); an.setSforumidentity(0); an.setForuminfo(cr.getForuminfo()); an.setId(cr.getId()); an.setRegistertableByJid(cr.getRegistertableByJid()); an.setTforumidentity(cr.getTforumidentity()); flag = fpi.update(an); } else { an = cr; flag = fpi.delete(an); } if(flag == true) return true; return false; } public boolean updateralationserver(Forumrelation an) { // TODO Auto-generated method stub boolean flag; String id = request.getParameter("fid"); int fid = Integer.parseInt(id); Registertable registertable = (Registertable)getSessionnow().get("register"); Forumrelation cr = fpi.selectByRid(fid); an.setRegistertableBySid(registertable); an.setSforumidentity(1); an.setForuminfo(cr.getForuminfo()); an.setId(cr.getId()); an.setRegistertableByJid(cr.getRegistertableByJid()); an.setTforumidentity(cr.getTforumidentity()); if(cr.getRegistertableBySid()!=null) { fpi.insert(an); flag = true; } else { flag = fpi.update(an); } if(flag == true) return true; return false; } public Forumrelation selectupdateralationserver(Forumrelation frt) { // TODO Auto-generated method stub Forumrelation an = fpi.selectById(frt); return an; } public boolean delectforumreviewserver(Forumreview ci) { // TODO Auto-generated method stub boolean flag = fpi.delete(ci); if(flag) { return true; } return false; } }
3e1197db5f7819e8984a45c8d2ced98caa3d7934
5,690
java
Java
src/main/java/com/tencentcloudapi/mdl/v20200326/models/DestinationInfo.java
TencentCloud/tencentcloud-sdk-java-intl-en
1c50ecf932a175ee06fa8b9568c2f20faf566d96
[ "Apache-2.0" ]
3
2020-04-07T03:13:05.000Z
2021-06-21T10:19:37.000Z
src/main/java/com/tencentcloudapi/mdl/v20200326/models/DestinationInfo.java
TencentCloud/tencentcloud-sdk-java-intl-en
1c50ecf932a175ee06fa8b9568c2f20faf566d96
[ "Apache-2.0" ]
3
2021-04-26T11:46:42.000Z
2022-01-19T01:07:07.000Z
src/main/java/com/tencentcloudapi/mdl/v20200326/models/DestinationInfo.java
TencentCloud/tencentcloud-sdk-java-intl-en
1c50ecf932a175ee06fa8b9568c2f20faf566d96
[ "Apache-2.0" ]
2
2020-04-07T03:13:11.000Z
2021-04-26T11:35:25.000Z
34.071856
89
0.669947
7,427
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.mdl.v20200326.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DestinationInfo extends AbstractModel{ /** * Relay destination address. Length limit: [1,512]. */ @SerializedName("OutputUrl") @Expose private String OutputUrl; /** * Authentication key. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. */ @SerializedName("AuthKey") @Expose private String AuthKey; /** * Authentication username. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. */ @SerializedName("Username") @Expose private String Username; /** * Authentication password. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. */ @SerializedName("Password") @Expose private String Password; /** * Get Relay destination address. Length limit: [1,512]. * @return OutputUrl Relay destination address. Length limit: [1,512]. */ public String getOutputUrl() { return this.OutputUrl; } /** * Set Relay destination address. Length limit: [1,512]. * @param OutputUrl Relay destination address. Length limit: [1,512]. */ public void setOutputUrl(String OutputUrl) { this.OutputUrl = OutputUrl; } /** * Get Authentication key. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. * @return AuthKey Authentication key. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. */ public String getAuthKey() { return this.AuthKey; } /** * Set Authentication key. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. * @param AuthKey Authentication key. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. */ public void setAuthKey(String AuthKey) { this.AuthKey = AuthKey; } /** * Get Authentication username. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. * @return Username Authentication username. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. */ public String getUsername() { return this.Username; } /** * Set Authentication username. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. * @param Username Authentication username. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. */ public void setUsername(String Username) { this.Username = Username; } /** * Get Authentication password. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. * @return Password Authentication password. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. */ public String getPassword() { return this.Password; } /** * Set Authentication password. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. * @param Password Authentication password. Length limit: [1,128]. Note: this field may return null, indicating that no valid values can be obtained. */ public void setPassword(String Password) { this.Password = Password; } public DestinationInfo() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DestinationInfo(DestinationInfo source) { if (source.OutputUrl != null) { this.OutputUrl = new String(source.OutputUrl); } if (source.AuthKey != null) { this.AuthKey = new String(source.AuthKey); } if (source.Username != null) { this.Username = new String(source.Username); } if (source.Password != null) { this.Password = new String(source.Password); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "OutputUrl", this.OutputUrl); this.setParamSimple(map, prefix + "AuthKey", this.AuthKey); this.setParamSimple(map, prefix + "Username", this.Username); this.setParamSimple(map, prefix + "Password", this.Password); } }
3e1199134f8eaba1c1a31f164e10db1c89ec4b57
1,657
java
Java
aura-util/src/main/java/org/auraframework/util/json/JsonHandlerProvider.java
augustyakaravat/aura
98d7ba491172c7ea44cbbf74be5eb858040c9c46
[ "Apache-2.0" ]
587
2015-01-01T00:42:17.000Z
2022-01-23T00:14:13.000Z
aura-util/src/main/java/org/auraframework/util/json/JsonHandlerProvider.java
DebalinaDey/AuraDevelopDeb
7a208333165e2621f168e7476f66d3c81c27dc06
[ "Apache-2.0" ]
156
2015-02-06T17:56:21.000Z
2019-02-27T05:19:11.000Z
aura-util/src/main/java/org/auraframework/util/json/JsonHandlerProvider.java
DebalinaDey/AuraDevelopDeb
7a208333165e2621f168e7476f66d3c81c27dc06
[ "Apache-2.0" ]
340
2015-01-13T14:13:38.000Z
2022-03-21T04:05:29.000Z
35.255319
80
0.695836
7,428
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.util.json; public interface JsonHandlerProvider { /** * This will be called for every entry in a map. If you want to provide a * special handler for that key, return its handler. If you return null, the * default handler implementation will be used. * * @param key The key in the parent object for which the handler is being * requested. */ JsonHandlerProvider getObjectEntryHandlerProvider(String key); /** * This will be called once each time an array is read. The returned handler * provider will be used to get a handler for each object or array within * the array. If you return null, the default handler implementation will be * used. */ JsonHandlerProvider getArrayEntryHandlerProvider(); /** * Return a handler to be used for reading an object. */ JsonObjectHandler getObjectHandler(); /** * Return a handler to be used for reading an array. */ JsonArrayHandler getArrayHandler(); }
3e1199e29847371fb251f101e494c7665c5e971d
475
java
Java
app/src/main/java/com/git/vladkudryshov/testparsejson/parser/gson/UserGsonList.java
VladKudryshov/TestParseJson
dd7cdd6fcd8dd3a4cc1071d402fd00010cbd129d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/git/vladkudryshov/testparsejson/parser/gson/UserGsonList.java
VladKudryshov/TestParseJson
dd7cdd6fcd8dd3a4cc1071d402fd00010cbd129d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/git/vladkudryshov/testparsejson/parser/gson/UserGsonList.java
VladKudryshov/TestParseJson
dd7cdd6fcd8dd3a4cc1071d402fd00010cbd129d
[ "Apache-2.0" ]
null
null
null
22.619048
60
0.743158
7,429
package com.git.vladkudryshov.testparsejson.parser.gson; import com.git.vladkudryshov.testparsejson.parser.IUser; import com.git.vladkudryshov.testparsejson.parser.IUserList; import java.util.List; class UserGsonList implements IUserList { private final List<IUser> mUserGsonList; UserGsonList(final List<IUser> pUsersLists) { mUserGsonList = pUsersLists; } @Override public List<IUser> getUserList() { return mUserGsonList; } }
3e119a0d7e033d39bccaa92ca0213ea4a19378f0
2,371
java
Java
src/main/java/net/crazysnailboy/mods/villagerinventory/client/config/ModGuiConfigEntries.java
crazysnailboy/VillagerInventory
fc9bada912a549ec4b5f0beb3d3973d01c0ff9a4
[ "MIT" ]
5
2017-01-28T13:31:30.000Z
2019-12-14T16:20:55.000Z
src/main/java/net/crazysnailboy/mods/villagerinventory/client/config/ModGuiConfigEntries.java
crazysnailboy/VillagerInventory
fc9bada912a549ec4b5f0beb3d3973d01c0ff9a4
[ "MIT" ]
4
2017-01-28T15:57:57.000Z
2018-12-07T05:16:01.000Z
src/main/java/net/crazysnailboy/mods/villagerinventory/client/config/ModGuiConfigEntries.java
crazysnailboy/VillagerInventory
fc9bada912a549ec4b5f0beb3d3973d01c0ff9a4
[ "MIT" ]
6
2017-01-28T13:31:51.000Z
2022-03-01T00:57:31.000Z
23.71
122
0.735133
7,430
package net.crazysnailboy.mods.villagerinventory.client.config; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.GuiConfigEntries; import net.minecraftforge.fml.client.config.GuiConfigEntries.ButtonEntry; import net.minecraftforge.fml.client.config.GuiUtils; import net.minecraftforge.fml.client.config.IConfigElement; public class ModGuiConfigEntries { public static class BooleanEntry extends ButtonEntry { protected final boolean beforeValue; protected boolean currentValue; public BooleanEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement) { super(owningScreen, owningEntryList, configElement); this.beforeValue = Boolean.valueOf(configElement.get().toString()); this.currentValue = this.beforeValue; this.btnValue.enabled = this.enabled(); this.updateValueButtonText(); } @Override public void updateValueButtonText() { this.btnValue.displayString = I18n.format(String.valueOf(this.currentValue)); this.btnValue.packedFGColour = this.currentValue ? GuiUtils.getColorCode('2', true) : GuiUtils.getColorCode('4', true); } @Override public void valueButtonPressed(int slotIndex) { if (this.enabled()) this.currentValue = !this.currentValue; } @Override public boolean isDefault() { return this.currentValue == Boolean.valueOf(this.configElement.getDefault().toString()); } @Override public void setToDefault() { if (this.enabled()) { this.currentValue = Boolean.valueOf(this.configElement.getDefault().toString()); this.updateValueButtonText(); } } @Override public boolean isChanged() { return this.currentValue != this.beforeValue; } @Override public void undoChanges() { if (this.enabled()) { this.currentValue = this.beforeValue; this.updateValueButtonText(); } } @Override public boolean saveConfigElement() { if (this.enabled() && this.isChanged()) { this.configElement.set(this.currentValue); return this.configElement.requiresMcRestart(); } return false; } @Override public Boolean getCurrentValue() { return this.currentValue; } @Override public Boolean[] getCurrentValues() { return new Boolean[] { this.getCurrentValue() }; } } }
3e119b56f37c59517f63a346744a9cf5703c547d
3,956
java
Java
src/main/groovy/org/arl/fjage/shell/GroovyBoot.java
AnneThKu/fjage
20c9bf89247f2c6e5d8f9ef60e83e35057a66a51
[ "BSD-3-Clause" ]
12
2017-10-27T05:51:34.000Z
2021-12-08T15:56:51.000Z
src/main/groovy/org/arl/fjage/shell/GroovyBoot.java
AnneThKu/fjage
20c9bf89247f2c6e5d8f9ef60e83e35057a66a51
[ "BSD-3-Clause" ]
153
2015-01-19T12:20:00.000Z
2022-03-17T02:37:52.000Z
src/main/groovy/org/arl/fjage/shell/GroovyBoot.java
AnneThKu/fjage
20c9bf89247f2c6e5d8f9ef60e83e35057a66a51
[ "BSD-3-Clause" ]
10
2016-01-11T11:02:35.000Z
2021-07-02T11:00:29.000Z
36.293578
144
0.610465
7,431
/****************************************************************************** Copyright (c) 2018, Mandar Chitre This file is part of fjage which is released under Simplified BSD License. See file LICENSE.txt or go to http://www.opensource.org/licenses/BSD-3-Clause for full license details. ******************************************************************************/ package org.arl.fjage.shell; import org.arl.fjage.GroovyExtensions; import org.arl.fjage.Platform; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; /** * fjage bootloader. * <p> * Usage: * <code> * java [-Djava.util.logging.config.file=logging.properties] org.arl.fjage.shell.GroovyBoot [-debug:package-name] [[-arg:arg]... script-file]... * </code> * * @author Mandar Chitre */ public class GroovyBoot { private static final String loggingProperties = "logging.properties"; /** * Application entry point. */ public static void main(String[] args) { Logger log = null; List<Logger> loggers = new ArrayList<Logger>(); try { // setup Groovy extensions GroovyExtensions.enable(); // load logging configuration from fjage defaults, if not specified if (System.getProperty("java.util.logging.config.file") == null && System.getProperty("java.util.logging.config.class") == null) { InputStream logprop = GroovyBoot.class.getResourceAsStream(loggingProperties); if (logprop == null) throw new FileNotFoundException("res://org/arl/fjage/shell/"+loggingProperties+" not found"); LogManager.getLogManager().readConfiguration(logprop); } log = Logger.getLogger(GroovyBoot.class.getName()); // load build details log.info("fjage Build: "+Platform.getBuildVersion()); // parse command line and execute scripts GroovyScriptEngine engine = new GroovyScriptEngine(); List<String> arglist = new ArrayList<String>(); for (String a: args) { if (a.equals("-debug")) { log.info("Setting root logger level to ALL"); Logger logger = Logger.getLogger(""); logger.setLevel(Level.ALL); loggers.add(logger); // keep reference to avoid the level setting being garbage collected } else if (a.startsWith("-debug:")) { String lname = a.substring(7); log.info("Setting logger "+lname+" level to ALL"); Logger logger = Logger.getLogger(lname); logger.setLevel(Level.ALL); loggers.add(logger); // keep reference to avoid the level setting being garbage collected } else if (a.startsWith("-arg:")) { arglist.add(a.substring(5)); } else { if (!a.endsWith(".groovy") && !a.startsWith("cls://")) a += ".groovy"; log.info("Running "+a); if (a.startsWith("res:/")) { // execute script from resource file InputStream inp = GroovyBoot.class.getResourceAsStream(a.substring(5)); if (inp == null) throw new FileNotFoundException(a+" not found"); engine.exec(new InputStreamReader(inp), a, arglist); if (arglist.size() > 0) arglist = new ArrayList<String>(); } else if (a.startsWith("cls://")) { // execute pre-compiled script from class file Class<?> cls = Class.forName(a.substring(6)); engine.exec(cls, arglist); } else { // execute script from file engine.exec(new File(a), arglist); if (arglist.size() > 0) arglist = new ArrayList<String>(); } } } engine.shutdown(); } catch (Throwable ex) { if (log == null) ex.printStackTrace(System.err); else log.severe(ex.toString()); } } }
3e119c6cfd66f5eeb26f1feab05f12f5117333fc
617
java
Java
src/main/java/com/hirath/explik/source/SourceBuilder.java
a-be/explik
3f915cb59bab8f4e9fdb1b7039e96d678c329a2f
[ "Apache-2.0" ]
null
null
null
src/main/java/com/hirath/explik/source/SourceBuilder.java
a-be/explik
3f915cb59bab8f4e9fdb1b7039e96d678c329a2f
[ "Apache-2.0" ]
null
null
null
src/main/java/com/hirath/explik/source/SourceBuilder.java
a-be/explik
3f915cb59bab8f4e9fdb1b7039e96d678c329a2f
[ "Apache-2.0" ]
null
null
null
24.68
74
0.645057
7,432
package com.hirath.explik.source; public class SourceBuilder<B,A> { private Condition<B,A> condition; private boolean publish; public SourceBuilder(Condition<B,A> condition) { this.condition = condition; this.publish = true; } public static <B,A> SourceBuilder<B,A> when(Condition<B,A> condition){ return new SourceBuilder<>(condition); } public SourceBuilder<B,A> disablePublish(){ this.publish = false; return this; } public Source<B,A> then(Producer<B,A> producer){ return new Source<>(condition, producer, publish); } }