hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
6b7ded835f24c0858432898f2d2d0dfc58eb49e1
3,045
package persistence; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import trainer.DefaultObjectFactory; import trainer.Exercise; import trainer.ExerciseGroup; import trainer.PerformanceRate; /** * Tests {@link persistence.ExerciseCRUD}, {@link persistence.ExerciseGroupCRUD}, and * {@link persistence.SessionPersist}. * * @author Lasse Osterhagen * */ public class CRUDTest { private static DbBase db = DbAccess.getInstance(); private static ArrayList<Integer> createdExerciseGroupIds = new ArrayList<>(); private static ArrayList<Integer> createdExerciseIds = new ArrayList<>(); @BeforeClass public static void setUp() { db.connect(CreateInitialTestTables.PATH2TESTDB); } private ExerciseGroup createNewExerciseGroup() { ExerciseGroup eGNew = DefaultObjectFactory.getExerciseGroup(); ExerciseGroupCRUD.createExerciseGroup(eGNew); createdExerciseGroupIds.add(eGNew.getId()); return eGNew; } private Exercise createNewExercise() { Exercise eNew = DefaultObjectFactory.getExercise(); eNew.setExerciseGroup(createNewExerciseGroup()); ExerciseCRUD.createExercise(eNew); createdExerciseIds.add(eNew.getId()); return eNew; } @Test public void testNewExerciseGroup() { ExerciseGroup eGNew = createNewExerciseGroup(); ExerciseGroup eGLoad = ExerciseGroupCRUD.loadExerciseGroup(eGNew.getId()); assertEquals(eGNew.getName(), eGLoad.getName()); assertEquals(eGNew.isEditable(), eGLoad.isEditable()); } @Test public void testNewExercise() { Exercise eNew = createNewExercise(); Integer ideNew = eNew.getId(); assertNotNull(ideNew); Exercise eLoad = ExerciseCRUD.loadExercise(ideNew); assertEquals(eNew.getName(), eLoad.getName()); assertEquals(eNew.getExerciseGroup().getName(), eLoad.getExerciseGroup().getName()); assertEquals(eNew.getLineCreatorType(), eLoad.getLineCreatorType()); assertEquals(eNew.getParam(), eLoad.getParam()); assertEquals(eNew.getLimitType(), eLoad.getLimitType()); assertEquals(eNew.getLimitUnits(), eLoad.getLimitUnits()); } @Test public void testSession() throws InterruptedException { Exercise e = createNewExercise(); PerformanceRate pr1 = new PerformanceRate(10, 2); PerformanceRate pr2 = new PerformanceRate(8, 5); final long requiredTime = 360_002; SessionPersist sp = new SessionPersist(); sp.saveSession2DB(e.getId(), pr1, requiredTime); Thread.sleep(1); // to guarantee different timeStamps sp.saveSession2DB(e.getId(), pr2, requiredTime); ArrayList<Session> sessions = sp.getSessions(e.getId()); assertEquals(sessions.size(), 2); assertEquals(sessions.get(0).getPerformanceRate(), pr2); // ORDER BY timeStamp DESC assertEquals(sessions.get(1).getPerformanceRate(), pr1); } @AfterClass public static void tearDown() { for(int id : createdExerciseIds) ExerciseCRUD.deleteExercise(id); for(int id : createdExerciseGroupIds) ExerciseGroupCRUD.deleteExerciseGroup(id); db.disconnect(); } }
31.071429
86
0.759278
f136a467fcbcc517d11e1f6320e4ccd669faf5b6
1,404
package org.shaolin.uimaster.page.ajax.json; public interface IRequestData extends java.io.Serializable { public final static String ENTITY_NAME = "org.shaolin.uimaster.page.ajax.json.RequestData"; /** * get uiid * * @return uiid */ public java.lang.String getUiid(); public java.lang.String getEntityName(); /** * get entityUiid * * @return entityUiid */ public java.lang.String getEntityUiid(); /** * get data * * @return data */ public java.util.Map getData(); /** * get frameId * * @return frameId */ public String getFrameId(); /** * get bAName * * @return bAName */ public String getBAName(); // setter methods block /** * set uiid */ public void setUiid(java.lang.String uiid); /** * set entityUiid */ public void setEntityUiid(java.lang.String entityUiid); /** * set entityName */ public void setEntityName(java.lang.String entityName); /** * set data */ public void setData(java.util.Map data); /** * set frameId */ public void setFrameId(String frameId); /** * set bAName */ public void setBAName(String bAName); }
17.333333
95
0.52208
f47a89c7ec05190d7561ae2a889d5d755b21379e
5,621
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.ejb.plugins.cmp.jdbc; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.SQLException; /** * The representation (mapping) in the Java<sup><font size=-2>TM</font></sup> * programming language of an SQL <code>BLOB</code> value to an array of bytes. * A ByteArrayBlob contains an internal buffer that contains bytes that may be * read from the stream. The <code>Blob</code> interface provides methods for * getting the length of an SQL <code>BLOB</code> (Binary Large Object) value, * for materializing a <code>BLOB</code> value on the client, and for * determining the position of a pattern of bytes within a <code>BLOB</code> * value. The ByteArrayBlob has static factory methods for construting an * <code>BLOB</code> using either an existing serializable object, or an array * of bytes. This is a nice way to store serialized objects in a relational * field of type SQL <code>BLOB</code>. * * @author <a href="mailto:amccullo@sourceforge.new">Andrew McCulloch</a> * @version $Revision: 63479 $ */ public final class ByteArrayBlob implements Blob { /** * The internal buffer for the bytes of the Blob. */ private byte[] mBytes; public ByteArrayBlob(byte[] bytes) { if (bytes == null) { bytes = new byte[0]; } mBytes = bytes; } public InputStream getBinaryStream() throws SQLException { return new ByteArrayInputStream(mBytes); } public byte[] getBytes(long pos, int length) throws SQLException { // Defensive code, parameter checks. if (length < 0 || length > mBytes.length || pos > mBytes.length) { return new byte[0]; } if (pos <= 0) { pos = 1; // One since the copy starts at pos. } byte[] buffer = new byte[length]; System.arraycopy(mBytes, (int)pos - 1, buffer, 0, length); return buffer; } public long length() throws SQLException { return mBytes.length; } public long position(Blob pattern, long start) throws SQLException { return position(pattern.getBytes(0, (int)pattern.length()), start); } public long position(byte pattern[], long start) throws SQLException { // Small optimization, no need to look beyond this. int max = mBytes.length - pattern.length; if (start < 0) { start = 0; // Cannot start negative, so put it at the beginning. } else if (start >= mBytes.length) { return -1; // Out of bounds, start was past the end of the buffer. } if (pattern.length == 0) { return -1; // Indicate that the pattern was not found. } byte first = pattern[0]; int i = (int)start; while (true) { // Look for the first character. while (i <= max && mBytes[i] != first) { i++; } if (i > max) { return -1; // Went to far, reject the pattern. } // Found the first character, now look for remainder of v2. int j = i + 1; int end = j + pattern.length - 1; int k = 1; boolean cont = true; // While the bytes remain equal and the end of v1 is not reached // continue the either rejecting this match, or accepting it. while (cont && j < end) { if (mBytes[j++] != pattern[k++]) { i++; cont = false; } } // If cont == false then the pattern was found. if (cont) { return i; } } } public OutputStream setBinaryStream(long pos) throws SQLException { throw new UnsupportedOperationException("ByteArrayBlob is immutable"); } public int setBytes(long pos, byte[] bytes) throws SQLException { throw new UnsupportedOperationException("ByteArrayBlob is immutable"); } public int setBytes(long pos, byte[] bytes, int offset, int length) throws SQLException { throw new UnsupportedOperationException("ByteArrayBlob is immutable"); } public void truncate(long length) throws SQLException { throw new UnsupportedOperationException("ByteArrayBlob is immutable"); } public void free() throws SQLException { mBytes = null; } public InputStream getBinaryStream(long pos, long length) throws SQLException { return new ByteArrayInputStream(mBytes, (int)pos, (int)length); } }
30.22043
90
0.638854
ff064e181865aba588ab7beefc33f2b847fc7802
577
package mic.poulet.goodsmash.pepites.model; import java.math.BigInteger; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import lombok.Data; import lombok.EqualsAndHashCode; @Entity @Data @EqualsAndHashCode public class Timecode { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank private String songId; @NotNull private BigInteger timecode; }
19.896552
52
0.819757
8bd581ca02874531238e9486a9ec9a62edb1ff06
620
package de.saschadoemer.iso11873.enums.units; /** * The internal force unit. * <p> * 00 Metric (newtons, ...) * 01 Imperial/US (pounds force, ...) * 10 Reserved * 11 No action */ public enum ForceUnit { METRIC(false, false), IMPERIAL_US(false, true), RESERVED(true, false), NO_ACTION(true, true); private final boolean bit_1; private final boolean bit_2; ForceUnit(boolean bit_1, boolean bit_2) { this.bit_1 = bit_1; this.bit_2 = bit_2; } public boolean isBit_1() { return bit_1; } public boolean isBit_2() { return bit_2; } }
18.235294
45
0.609677
4640dc2f0d08a3a6d1b97e98417afd8cbfb8ac89
846
package capitulo7; import capitulo2.Usuario; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class Capitulo7_2 { /* Tornando moderadores os usuários com mais 100 pontos */ public static void main(String[] args) { Usuario user1 = new Usuario("Paulo Silveira", 150); Usuario user2 = new Usuario("Rodrigo Turini", 120); Usuario user3 = new Usuario("Guilherme Silveira", 90); List<Usuario> usuarios = Arrays.asList(user1, user2, user3); usuarios.stream().filter(u -> u.getPontos() > 100).forEach(Usuario::tornarModerador); //Stream<Usuario> moderadores = usuarios.stream().filter(u -> u.isModerador()); Stream<Usuario> moderadores = usuarios.stream().filter(Usuario::isModerador); moderadores.forEach(System.out::println); } }
31.333333
93
0.683215
904081a150cdb6d4172b96385b222a4218b24bb3
1,039
/* * Copyright 2018-2019 Sysco Middleware * * 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 no.sysco.middleware.kafka.interceptor.zipkin; /** * Keys to be tagged on spans created by interceptors. See * {@link TracingConsumerInterceptor} and {@link TracingProducerInterceptor} */ class KafkaInterceptorTagKey { static final String KAFKA_TOPIC = "kafka.topic"; static final String KAFKA_KEY = "kafka.key"; static final String KAFKA_CLIENT_ID = "kafka.client.id"; static final String KAFKA_GROUP_ID = "kafka.group.id"; }
37.107143
100
0.759384
667b6d9f7615f6579248498cf5a79d6f3e28ada9
1,374
package com.github.marwin1991.keep_changelog.markdown.entry; import com.github.marwin1991.keep_changelog.yaml.model.ChangelogEntry; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringSubstitutor; import java.util.HashMap; import java.util.Map; class MarkdownChangelogEntryIssues extends MarkdownChangelogEntryAbstract { private static final String issueFormat = "#${issue}"; public MarkdownChangelogEntryIssues(ChangelogEntry entry) { super(entry); } public String getIssues() { if (entry.getIssues() == null || entry.getIssues().size() == 0) { return StringUtils.EMPTY; } if (entry.getIssues().size() == 1) { Map<String, String> valuesMap = new HashMap<>(); valuesMap.put("issue", entry.getIssues().get(0)); StringSubstitutor sub = new StringSubstitutor(valuesMap); return sub.replace(issueFormat); } StringBuilder issues = new StringBuilder(StringUtils.EMPTY); for (String issue : entry.getIssues()) { Map<String, String> valuesMap = new HashMap<>(); valuesMap.put("issue", issue); StringSubstitutor sub = new StringSubstitutor(valuesMap); issues.append(sub.replace(issueFormat)).append(" "); } return issues.toString().trim(); } }
33.512195
75
0.656477
e15aa873a93c4e10f52a56c4de7c558810cd0932
5,799
package com.unity.cxsolution.Enter; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.os.PersistableBundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; public class CustomActivity extends AppCompatActivity { /** * 当前Activity对象 */ @SuppressLint("StaticFieldLeak") public static Activity CurrentActivity; /** * @param methodName 函数名称 * @param params 参数列表 * @param paramTypes 参数类型列表 */ private static void TriggerBefore(String methodName, Object[] params, Class[] paramTypes) { EnterTool.TriggerBefore(EnterTool.ClassType_Activity, methodName, params, paramTypes); } /** * @param methodName 函数名称 * @param params 参数列表 * @param paramTypes 参数类型列表 */ private static void TriggerAfter(String methodName, Object[] params, Class[] paramTypes) { EnterTool.TriggerAfter(EnterTool.ClassType_Activity, methodName, params, paramTypes); } @Override protected void onCreate(Bundle bundle) { CurrentActivity = this; TriggerBefore("onCreate", new Object[]{bundle}, new Class[]{Bundle.class}); super.onCreate(bundle); TriggerAfter("onCreate", new Object[]{bundle}, new Class[]{Bundle.class}); } @Override protected void onNewIntent(Intent intent) { TriggerBefore("onNewIntent", new Object[]{intent}, new Class[]{Intent.class}); super.onNewIntent(intent); TriggerAfter("onNewIntent", new Object[]{intent}, new Class[]{Intent.class}); } @Override protected void onStart() { TriggerBefore("onStart", null, null); super.onStart(); TriggerAfter("onStart", null, null); } @Override protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { TriggerBefore("onRestoreInstanceState", new Object[]{savedInstanceState}, new Class[]{Bundle.class}); super.onRestoreInstanceState(savedInstanceState); TriggerAfter("onRestoreInstanceState", new Object[]{savedInstanceState}, new Class[]{Bundle.class}); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onRestoreInstanceState(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) { TriggerBefore("onRestoreInstanceState", new Object[]{savedInstanceState, persistentState}, new Class[]{Bundle.class, PersistableBundle.class}); super.onRestoreInstanceState(savedInstanceState, persistentState); TriggerAfter("onRestoreInstanceState", new Object[]{savedInstanceState, persistentState}, new Class[]{Bundle.class, PersistableBundle.class}); } @Override protected void onResume() { TriggerBefore("onResume", null, null); super.onResume(); TriggerAfter("onResume", null, null); } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { TriggerBefore("onSaveInstanceState", new Object[]{outState}, new Class[]{Bundle.class}); super.onSaveInstanceState(outState); TriggerAfter("onSaveInstanceState", new Object[]{outState}, new Class[]{Bundle.class}); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) { TriggerBefore("onSaveInstanceState", new Object[]{outState, outPersistentState}, new Class[]{Bundle.class, PersistableBundle.class}); super.onSaveInstanceState(outState, outPersistentState); TriggerAfter("onSaveInstanceState", new Object[]{outState, outPersistentState}, new Class[]{Bundle.class, PersistableBundle.class}); } @Override protected void onPause() { TriggerBefore("onPause", null, null); super.onPause(); TriggerAfter("onPause", null, null); } @Override protected void onStop() { TriggerBefore("onStop", null, null); super.onStop(); TriggerAfter("onStop", null, null); } @Override protected void onRestart() { TriggerBefore("onRestart", null, null); super.onRestart(); TriggerAfter("onRestart", null, null); } @Override protected void onDestroy() { TriggerBefore("onDestroy", null, null); super.onDestroy(); TriggerAfter("onDestroy", null, null); CurrentActivity = null; } @Override public void onLowMemory() { TriggerBefore("onLowMemory", null, null); super.onLowMemory(); TriggerAfter("onLowMemory", null, null); } @Override public void onTrimMemory(int level) { TriggerBefore("onTrimMemory", new Object[]{level}, new Class[]{int.class}); super.onTrimMemory(level); TriggerAfter("onTrimMemory", new Object[]{level}, new Class[]{int.class}); } @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { TriggerBefore("Configuration", new Object[]{newConfig}, new Class[]{Configuration.class}); super.onConfigurationChanged(newConfig); TriggerAfter("Configuration", new Object[]{newConfig}, new Class[]{Configuration.class}); } @Override public void onWindowFocusChanged(boolean hasFocus) { TriggerBefore("onWindowFocusChanged", new Object[]{hasFocus}, new Class[]{boolean.class}); super.onWindowFocusChanged(hasFocus); TriggerAfter("onWindowFocusChanged", new Object[]{hasFocus}, new Class[]{boolean.class}); } }
30.68254
151
0.684946
fa7a31473b1fac02d1f96fd4e9c0ab7408da6ed9
8,395
/* * Copyright (C) 2012 TopCoder Inc., All Rights Reserved. */ package gov.medicaid.screening.services; import gov.medicaid.entities.MedicaidCertifiedProviderSearchCriteria; import gov.medicaid.entities.ResultLogEntry; import gov.medicaid.entities.SourceStats; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.Properties; import javax.naming.InitialContext; import org.apache.http.HttpStatus; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; /** * Functional tests for <code>StatsTrackerService</code>. * * @author j3_guile * @version 1.0 */ @RunWith(BlockJUnit4ClassRunner.class) public class StatsTrackerServiceTest extends SOAPInvocationTestCase { /** * The service to be tested as a remote EJB. */ private StatsTrackerService service; /** * Default empty constructor. */ public StatsTrackerServiceTest() { } /** * Setup test class. * * @throws Exception to JUnit */ @Before public void setUp() throws Exception { Properties props = new Properties(); props.setProperty("java.naming.provider.url", getProperty("java.naming.provider.url")); props.setProperty("java.naming.factory.url.pkgs", getProperty("java.naming.factory.url.pkgs")); props.setProperty("java.naming.factory.initial", getProperty("java.naming.factory.initial")); InitialContext ctx = new InitialContext(props); service = (StatsTrackerService) ctx.lookup(getProperty("StatsTrackerServiceJNDI")); Class.forName("oracle.jdbc.driver.OracleDriver"); clearStatsAndLogs(); } /** * Clears the tables used by this test. * * @throws Exception to JUnit */ private void clearStatsAndLogs() throws Exception { Connection conn = null; Statement stmt = null; try { conn = DriverManager.getConnection(getProperty("jdbc.url"), getProperty("jdbc.user"), getProperty("jdbc.pass")); stmt = conn.createStatement(); stmt.execute("DELETE FROM SOURCE_STATS"); stmt.execute("DELETE FROM MEDICAID_CERT_PROV_CRIT"); stmt.execute("DELETE FROM RESULT_LOG_ENTRY"); stmt.execute("DELETE FROM SEARCH_CRITERIA"); conn.commit(); } catch (SQLException e) { e.printStackTrace(); } finally { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } } /** * Destroy properties. * * @throws Exception to JUnit */ @After public void tearDown() throws Exception { clearStatsAndLogs(); service = null; } /** * Tests managing statistics via the remote service layer. * * @throws Exception to JUnit */ @Test public void testManageStats() throws Exception { SourceStats stats = service.getReliabilityStatistics("test"); assertNull("stats should be null if not found", stats); // create service.updateSourceStats("test", HttpStatus.SC_OK); stats = service.getReliabilityStatistics("test"); assertNotNull("stats should be created", stats); // reset stats.setReliability(0); stats.setPageChangedRequests(0); stats.setPageNotFoundRequests(0); stats.setServerErrorRequests(0); stats.setSuccessRequests(0); service.setReliabilityStatistics(stats); SourceStats updated = service.getReliabilityStatistics("test"); assertEquals("stats should be updated", 0.0, updated.getReliability()); assertEquals("stats should be updated", 0, updated.getPageChangedRequests()); assertEquals("stats should be updated", 0, updated.getPageNotFoundRequests()); assertEquals("stats should be updated", 0, updated.getServerErrorRequests()); assertEquals("stats should be updated", 0, updated.getSuccessRequests()); // add response service.updateSourceStats("test", HttpStatus.SC_OK); updated = service.getReliabilityStatistics("test"); assertEquals("stats should be updated", 1.0, updated.getReliability()); assertEquals("stats should be updated", 0, updated.getPageChangedRequests()); assertEquals("stats should be updated", 0, updated.getPageNotFoundRequests()); assertEquals("stats should be updated", 0, updated.getServerErrorRequests()); assertEquals("stats should be updated", 1, updated.getSuccessRequests()); // add response service.updateSourceStats("test", HttpStatus.SC_INTERNAL_SERVER_ERROR); updated = service.getReliabilityStatistics("test"); assertEquals("stats should be updated", 0.5, updated.getReliability()); assertEquals("stats should be updated", 0, updated.getPageChangedRequests()); assertEquals("stats should be updated", 0, updated.getPageNotFoundRequests()); assertEquals("stats should be updated", 1, updated.getServerErrorRequests()); assertEquals("stats should be updated", 1, updated.getSuccessRequests()); // add response service.updateSourceStats("test", HttpStatus.SC_MOVED_TEMPORARILY); service.updateSourceStats("test", HttpStatus.SC_MOVED_PERMANENTLY); updated = service.getReliabilityStatistics("test"); assertEquals("stats should be updated", 0.25, updated.getReliability()); assertEquals("stats should be updated", 2, updated.getPageChangedRequests()); assertEquals("stats should be updated", 0, updated.getPageNotFoundRequests()); assertEquals("stats should be updated", 1, updated.getServerErrorRequests()); assertEquals("stats should be updated", 1, updated.getSuccessRequests()); // add response service.updateSourceStats("test", HttpStatus.SC_NOT_FOUND); updated = service.getReliabilityStatistics("test"); assertEquals("stats should be updated", 0.20, updated.getReliability()); assertEquals("stats should be updated", 2, updated.getPageChangedRequests()); assertEquals("stats should be updated", 1, updated.getPageNotFoundRequests()); assertEquals("stats should be updated", 1, updated.getServerErrorRequests()); assertEquals("stats should be updated", 1, updated.getSuccessRequests()); List<SourceStats> allReliabilityStatistics = service.getAllReliabilityStatistics(); assertFalse("There should be at least one", allReliabilityStatistics.isEmpty()); boolean found = false; for (SourceStats sourceStats : allReliabilityStatistics) { if (sourceStats.getName().equals("test")) { found = true; break; } } assertTrue("The test data should be included", found); } /** * Tests managing log entries via the service layer. * * @throws Exception to JUnit */ @Test public void testManageLogEntries() throws Exception { List<ResultLogEntry> all = service.getLoggedEntries(0, 0); assertTrue("No entries expected", all.isEmpty()); // create ResultLogEntry entry = new ResultLogEntry(); entry.setCriteria(new MedicaidCertifiedProviderSearchCriteria()); service.saveLoggedEntry(entry); all = service.getLoggedEntries(0, 0); assertEquals("1 entry expected", 1, all.size()); assertEquals("same type expected", entry.getCriteria().getClass(), all.get(0).getCriteria().getClass()); // create another service.saveLoggedEntry(entry); all = service.getLoggedEntries(0, 0); assertEquals("2 entries expected", 2, all.size()); // test pagination service.saveLoggedEntry(entry); service.saveLoggedEntry(entry); all = service.getLoggedEntries(1, 1); assertEquals("1 entry expected", 1, all.size()); all = service.getLoggedEntries(1, 2); assertEquals("2 entries expected", 2, all.size()); all = service.getLoggedEntries(2, 1); assertEquals("1 entry expected", 1, all.size()); } }
37.477679
112
0.660512
05bad3f13306effc0191d70b7690ddd5be49360e
1,992
package com.twu.items; import com.twu.menuoptions.CheckoutHistory; import java.util.ArrayList; public class LibrarySection<Section extends Item> { private ArrayList<Section> availableItems; private ArrayList<Section> issuedItems; private CheckoutHistory<Section> checkoutHistory; public LibrarySection(ArrayList<Section> availableItems, ArrayList<Section> issuedItems, CheckoutHistory<Section> checkoutHistory) { this.availableItems = availableItems; this.issuedItems = issuedItems; this.checkoutHistory = checkoutHistory; } @Override public String toString() { String itemList = new String(); for (Section item : availableItems) itemList += item.toString() + "\n"; return itemList; } public String checkout(String searchItemName, String successfull, String unsuccessfull, String userId) { ArrayList<Section> searchResult = search(searchItemName, availableItems); for (Section item : searchResult) { availableItems.remove(item); issuedItems.add(item); checkoutHistory.add(userId, item); return successfull; } return unsuccessfull; } public String returnItem(String searchItemName, String successfull, String unsuccessfull, String userId) { ArrayList<Section> searchResult = search(searchItemName, issuedItems); for (Section item : searchResult) { if (!checkoutHistory.remove(userId, item)) { availableItems.add(item); issuedItems.remove(item); return successfull; } } return unsuccessfull; } private ArrayList<Section> search(String bookName, ArrayList<Section> listOfBooks) { ArrayList<Section> result = new ArrayList<>(); for (Section item : listOfBooks) { if (item.match(bookName)) result.add(item); } return result; } }
34.344828
136
0.651606
5c4125d272e2367472414e05f235887cba5ea5db
1,119
package Core; public class Main { public static void main(String[] args){ //TODO: find roots other than square roots // implement log base anything // style everything if possible // a^2b is a^(2b) instead of (a^2)b //{History, Mode, GraphSettings} history stuff FullEval eval = new FullEval(); print(eval.evaluate("x+56/2")); // EquationSolver eqSolver = new EquationSolver(); // long start = System.currentTimeMillis(); // eqSolver.solve("x^3-x=-3"); // long end = System.currentTimeMillis(); // print((end-start) + "ms"); /* GraphSolver solver = new GraphSolver(); long start = System.currentTimeMillis(); Double[][] results = solver.solveDouble("x^2+y^2=5"); //x^2+y^2=9" long end = System.currentTimeMillis(); print((end-start) + "ms"); print("------------------------------"); for(Double[] coords : results){ print(coords[0]); print(coords[1]); }*/ } static void print(Object p){ System.out.println(p); } }
30.243243
74
0.544236
eff015cafea052760cabfcee6e91e5f538c4b628
3,590
package cn.xz.sample; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; /** * Created by xuanzhui on 2017/3/13. * * Every implementation of the Java platform is required to support the following standard symmetric Cipher transformations with the keysizes in parentheses: * AES/CBC/NoPadding (128) * AES/CBC/PKCS5Padding (128) * AES/ECB/NoPadding (128) * AES/ECB/PKCS5Padding (128) * DES/CBC/NoPadding (56) * DES/CBC/PKCS5Padding (56) * DES/ECB/NoPadding (56) * DES/ECB/PKCS5Padding (56) * DESede/CBC/NoPadding (168) * DESede/CBC/PKCS5Padding (168) * DESede/ECB/NoPadding (168) * DESede/ECB/PKCS5Padding (168) * * normally prefer AES/CBC/PKCS5Padding * AES padding should be using PKCS#7 although here saying PKCS5Padding * key and vector should change each time before encryption in production environment. * * https://security.stackexchange.com/questions/26179/security-comparsion-of-3des-and-aes */ public class AESCipher { public byte[] encryptCBCMode(String key, String vector, String plainText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { IvParameterSpec iv = new IvParameterSpec(vector.getBytes(StandardCharsets.UTF_8)); SecretKey keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); return cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); } public byte[] decryptCBCMode(String key, String vector, byte[] cipherBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { IvParameterSpec iv = new IvParameterSpec(vector.getBytes(StandardCharsets.UTF_8)); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, keySpec, iv); return cipher.doFinal(cipherBytes); } public byte[] encryptECBMode(String key, String plainText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { SecretKey keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); return cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); } public byte[] decryptECBMode(String key, byte[] cipherBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, keySpec); return cipher.doFinal(cipherBytes); } }
43.780488
157
0.752089
2be473830a38ae18dab12c4e8da7e95149cee170
1,247
/** * @package Showcase-Acceptance-Testing-Quarkus * * @file Todo class * @copyright 2021 Christoph Kappel <christoph@unexist.dev> * @version $Id$ * * This program can be distributed under the terms of the Apache License v2.0. * See the file LICENSE for details. **/ package dev.unexist.showcase.todo.domain.todo; public class Todo extends TodoBase { private int id; /** * Constructor **/ public Todo() { } /** * Constructor * * @param base Base entry **/ public Todo(final TodoBase base) { this.update(base); } /** * Update values from base * * @param base Todo base class **/ public void update(final TodoBase base) { this.setTitle(base.getTitle()); this.setDescription(base.getDescription()); this.setDone(base.getDone()); if (null != base.getDueDate()) { this.setDueDate(base.getDueDate()); } } /** * Get id of entry * * @return Id of the entry **/ public int getId() { return id; } /** * Set id of entry * * @param id Id of the entry **/ public void setId(int id) { this.id = id; } }
17.814286
78
0.548516
bd548b90e9cd525c02e584b0efb1945ab2640264
711
package rest.reflection.entity; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.annotate.JsonSerialize; public interface IManifest { @JsonProperty("order_id") public String getManifestId(); @JsonProperty("order_id") public void setManifestId(String pLocationId); @JsonProperty("order_reference") public String getOrderReference(); @JsonProperty("order_reference") public void setOrderReference(String pOrderReference); @JsonProperty("contract_id") @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public String getContractId(); @JsonProperty("contract_id") public void setContractId(String pLocationId); }
25.392857
62
0.759494
fccb6d83e6175f0903fef6ea29f3640254feda2b
8,085
/* * Copyright 2010-2021 Australian Signals Directorate * * 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 au.gov.asd.tac.constellation.graph.visual.plugins.select; import au.gov.asd.tac.constellation.graph.Graph; import au.gov.asd.tac.constellation.graph.GraphElementType; import au.gov.asd.tac.constellation.graph.StoreGraph; import au.gov.asd.tac.constellation.graph.attribute.BooleanAttributeDescription; import au.gov.asd.tac.constellation.graph.attribute.FloatAttributeDescription; import au.gov.asd.tac.constellation.graph.attribute.IntegerAttributeDescription; import au.gov.asd.tac.constellation.graph.attribute.StringAttributeDescription; import au.gov.asd.tac.constellation.graph.schema.visual.concept.VisualConcept; import au.gov.asd.tac.constellation.graph.visual.VisualGraphPluginRegistry; import au.gov.asd.tac.constellation.plugins.PluginException; import au.gov.asd.tac.constellation.plugins.PluginExecution; import static org.testng.Assert.fail; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Singleton Test. * * @author altair */ public class SelectSingletonsNGTest { private int attr1; private int attr2; private int attr3; private int attr4; private int attr5; private int attr6; private StoreGraph graph; private int vxId4; private int vxId5; public SelectSingletonsNGTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @BeforeMethod public void setUpMethod() throws Exception { int xAttr, yAttr, zAttr; int selectedAttr; graph = new StoreGraph(); attr1 = graph.addAttribute(GraphElementType.VERTEX, StringAttributeDescription.ATTRIBUTE_NAME, "field1", null, null, null); attr2 = graph.addAttribute(GraphElementType.VERTEX, StringAttributeDescription.ATTRIBUTE_NAME, "field2", null, null, null); attr3 = graph.addAttribute(GraphElementType.VERTEX, StringAttributeDescription.ATTRIBUTE_NAME, "field3", null, null, null); attr4 = graph.addAttribute(GraphElementType.VERTEX, IntegerAttributeDescription.ATTRIBUTE_NAME, "field4", null, null, null); attr5 = graph.addAttribute(GraphElementType.VERTEX, IntegerAttributeDescription.ATTRIBUTE_NAME, "field5", null, null, null); attr6 = graph.addAttribute(GraphElementType.TRANSACTION, StringAttributeDescription.ATTRIBUTE_NAME, "field6", null, null, null); xAttr = graph.addAttribute(GraphElementType.VERTEX, FloatAttributeDescription.ATTRIBUTE_NAME, "x", "x", 0.0, null); if (xAttr == Graph.NOT_FOUND) { fail(); } yAttr = graph.addAttribute(GraphElementType.VERTEX, FloatAttributeDescription.ATTRIBUTE_NAME, "y", "y", 0.0, null); if (yAttr == Graph.NOT_FOUND) { fail(); } zAttr = graph.addAttribute(GraphElementType.VERTEX, FloatAttributeDescription.ATTRIBUTE_NAME, "z", "z", 0.0, null); if (zAttr == Graph.NOT_FOUND) { fail(); } selectedAttr = graph.addAttribute(GraphElementType.TRANSACTION, BooleanAttributeDescription.ATTRIBUTE_NAME, "selected", "selected", false, null); if (selectedAttr == Graph.NOT_FOUND) { fail(); } selectedAttr = graph.addAttribute(GraphElementType.VERTEX, BooleanAttributeDescription.ATTRIBUTE_NAME, "selected", "selected", false, null); if (selectedAttr == Graph.NOT_FOUND) { fail(); } } @AfterMethod public void tearDownMethod() throws Exception { } private void generateDistinctTransactions() throws InterruptedException { int vxId1 = graph.addVertex(); int vxId2 = graph.addVertex(); int vxId3 = graph.addVertex(); vxId4 = graph.addVertex(); vxId5 = graph.addVertex(); graph.setStringValue(attr1, vxId1, "a1"); graph.setStringValue(attr2, vxId1, "b1"); graph.setStringValue(attr3, vxId1, "c1"); graph.setStringValue(attr4, vxId1, "10"); graph.setStringValue(attr5, vxId1, "100"); graph.setStringValue(attr1, vxId2, "a2"); graph.setStringValue(attr2, vxId2, "b1"); graph.setStringValue(attr3, vxId2, "c2"); graph.setStringValue(attr4, vxId2, "20"); graph.setStringValue(attr5, vxId2, "200"); graph.setStringValue(attr1, vxId3, "a3"); graph.setStringValue(attr2, vxId3, "b3"); graph.setStringValue(attr3, vxId3, "c3"); graph.setStringValue(attr4, vxId3, "30"); graph.setStringValue(attr5, vxId3, "100"); int txId1 = graph.addTransaction(vxId1, vxId2, true); int txId2 = graph.addTransaction(vxId2, vxId1, true); int txId3 = graph.addTransaction(vxId1, vxId2, false); int txId4 = graph.addTransaction(vxId2, vxId3, true); int txId5 = graph.addTransaction(vxId2, vxId3, true); graph.setStringValue(attr6, txId4, "a1"); graph.setStringValue(attr6, txId5, "a2"); } @Test public void singletonTest() throws InterruptedException, PluginException { generateDistinctTransactions(); int attrId = graph.getAttribute(GraphElementType.TRANSACTION, VisualConcept.TransactionAttribute.SELECTED.getName()); assertTrue("Selection column found", (attrId >= 0)); for (int i = 0; i < graph.getTransactionCount(); i++) { final int txId = graph.getTransaction(i); boolean flag = graph.getBooleanValue(attrId, txId); assertFalse(String.format("Transaction [%d] should be de-selected", txId), flag); } attrId = graph.getAttribute(GraphElementType.VERTEX, VisualConcept.VertexAttribute.SELECTED.getName()); assertTrue("Selection column found", (attrId >= 0)); for (int i = 0; i < graph.getVertexCount(); i++) { final int txId = graph.getVertex(i); boolean flag = graph.getBooleanValue(attrId, txId); assertFalse(String.format("Vertex [%d] should be de-selected", txId), flag); } PluginExecution.withPlugin(VisualGraphPluginRegistry.SELECT_SINGLETONS).executeNow(graph); attrId = graph.getAttribute(GraphElementType.TRANSACTION, VisualConcept.TransactionAttribute.SELECTED.getName()); assertTrue("Selection column found", (attrId >= 0)); for (int i = 0; i < graph.getTransactionCount(); i++) { final int txId = graph.getTransaction(i); boolean flag = graph.getBooleanValue(attrId, txId); assertFalse(String.format("Transaction [%d] should be de-selected", txId), flag); } attrId = graph.getAttribute(GraphElementType.VERTEX, VisualConcept.VertexAttribute.SELECTED.getName()); assertTrue("Selection column found", (attrId >= 0)); for (int i = 0; i < graph.getVertexCount(); i++) { final int txId = graph.getVertex(i); boolean flag = graph.getBooleanValue(attrId, txId); if ((txId == vxId4) || (txId == vxId5)) { assertTrue(String.format("Vertex [%d] should be selected", txId), flag); } else { assertFalse(String.format("Vertex [%d] should be de-selected", txId), flag); } } } }
42.329843
153
0.685467
7421555d96f7c33c68ce06469143b218dbf8d87f
992
/* * 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 Code; import java.io.Serializable; /** * This {@code ENUM} class holds all the constants used for roles in the game, * this is used by the server and client to identify and set roles in the game * @author Ben Gilad and Asaf Yeshayahus * @version %I% * @since 1.0 */ public enum Roles implements Serializable{ /** * Specifies that a user has the role of a CITIZEN */ CITIZEN, /** * Specifies that a user has the role of a KILLER */ KILLER, /** * Specifies that a user has the role of a HEALER */ HEALER, /** * Specifies that a user has the role of a SNITCH */ SNITCH, /** * Specifies that a user is DEAD */ DEAD, /** * Specifies that the user is in the voting phase */ VOTE; }
20.244898
79
0.621976
1b33f5d6346926d9d9de3515bddcfe993aeb3fca
254
package com.softicar.sqml.model.validation; import org.eclipse.xtext.diagnostics.Severity; public interface ISqmlValidationConfiguration { Severity getSeverity(ISqmlIssue issue); boolean isMandatoryIdColumn(); int getMaximumIdentifierLength(); }
19.538462
47
0.822835
11056cbbf4f1737e889f27d2bff52dc4d864695e
879
package cn.threefishes.cloudrepository.entity; public class FormatTemplate { private Integer formatId; private String formatName; private Integer formatSite; private Integer storeId; public Integer getFormatId() { return formatId; } public void setFormatId(Integer formatId) { this.formatId = formatId; } public String getFormatName() { return formatName; } public void setFormatName(String formatName) { this.formatName = formatName == null ? null : formatName.trim(); } public Integer getFormatSite() { return formatSite; } public void setFormatSite(Integer formatSite) { this.formatSite = formatSite; } public Integer getStoreId() { return storeId; } public void setStoreId(Integer storeId) { this.storeId = storeId; } }
20.44186
72
0.648464
ced524916ddd87f0b1d8caa5e5f20e5393552120
2,431
package com.ziroom.ziroomcustomer.ziroomstation.b; import com.ziroom.ziroomcustomer.e.q; public class d { public static String A = "rest/evaluate/getZraEvaluate.do"; public static String B = "client/upload/v1"; public static String C = "rest/evaluate/getEvaluateAndStarCount.do"; public static String D = "client/evaluate/v1"; public static String E = q.U + "rest/evaluate/getBeEvaluateRank.do"; public static String F = "client/uncheckin/list/v1"; public static String G = "client/project/info/v2"; public static String H = "client/pro/detailv1"; public static String I = "client/project/rules/v1"; public static String J = "client/usersInfo/v1"; public static String K = "client/order/bookOrderInfo/v1"; public static String L = "client/pro/calanderv1"; public static String M = "client/ordernew/orderMoneyv1"; public static String a = "client/basedata/v1"; public static String b = "client/check/refundWay/v1"; public static String c = "client/cms/HeaderImg/list/v1"; public static String d = "client/order/info/v1"; public static String e = "client/stock/v1"; public static String f = "client/project/info/v1"; public static String g = "client/order/list/v1"; public static String h = "client/project/list/v1"; public static String i = "client/tickets/v1"; public static String j = "client/order/submit/v1"; public static String k = "client/lock/v1"; public static String l = "client/order/pay/v1"; public static String m = "client/order/cancel/v1"; public static String n = "client/redeticket/v1"; public static String o = "client/order/refund/v1"; public static String p = "client/unevaluate/list/v1"; public static String q = "client/unpay/list/v1"; public static String r = "client/self/clear/v1"; public static String s = "client/self/lockingBed/v1"; public static String t = "client/self/pay/v1"; public static String u = "client/self/scheme/v1"; public static String v = "client/deposit/paySuccessText/v1"; public static String w = "client/labels/v1"; public static String x = "client/self/checked/detail/v1"; public static String y = "rest/evaluate/getEvaluateProblems.do"; public static String z = "rest/evaluate/putEvaluateContent.do"; } /* Location: /Users/gaoht/Downloads/zirom/classes4-dex2jar.jar!/com/ziroom/ziroomcustomer/ziroomstation/b/d.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
46.75
126
0.724805
e14efdea5d332c70ffc847c3e995ac466ed5d39d
1,549
package it.oblive.correctness.invoke.invokespecial; import it.oblive.helpers.AbstractTestCorrectnessTemplate; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import testclasses.invoke.invokespecial.InvokeSpecialObject; import testclasses.invoke.invokevirtual.InvokeVirtualObject; public class TestInvokeSpecialObject extends AbstractTestCorrectnessTemplate { private Class<?> className = testclasses.invoke.invokespecial.InvokeSpecialObject.class; private String[] methodTest = {"concatenate"}; private Class[][] methodParam = {new Class[]{String.class, char.class}}; private Object[][] methodArgs = {new Object[]{"hello world", '!'}}; @Test public void testSuperMethodIsCalled() { InvokeSpecialObject testme = new InvokeSpecialObject(); InvokeVirtualObject check = new InvokeVirtualObject(); //the normalAdd method of the testme class is wrong on purpose, the class should call the superclass one Assertions.assertEquals(check.concatenate("hello", 'w'), testme.concatenate("hello", 'w')); Assertions.assertNotEquals(check.normalcat("hello", 'w'), testme.normalcat("hello", 'w')); } @Override public Class<?> getTestClass() { return className; } @Override public String[] getTestMethodName() { return methodTest; } @Override public Class<?>[][] getTestMethodParams() { return methodParam; } @Override public Object[][] getTestMethodArgs() { return methodArgs; } }
33.673913
112
0.708199
acc5bf6042e89901554ec0660d5dae5a6a67eca1
6,578
/* * Copyright 2010-2015 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 org.jetbrains.kotlin.util.slicedMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import org.jetbrains.kotlin.utils.Printer; import java.util.Collection; import java.util.Iterator; import java.util.Map; public class TrackingSlicedMap extends SlicedMapImpl { private final Map<ReadOnlySlice<?, ?>, SliceWithStackTrace<?, ?>> sliceTranslationMap = Maps.newHashMap(); private final boolean trackWithStackTraces; public TrackingSlicedMap(boolean trackWithStackTraces) { super(Maps.<SlicedMapKey<?, ?>, Object>newLinkedHashMap()); this.trackWithStackTraces = trackWithStackTraces; } private <K, V> SliceWithStackTrace<K, V> wrapSlice(ReadOnlySlice<K, V> slice) { SliceWithStackTrace<?, ?> translated = sliceTranslationMap.get(slice); if (translated == null) { translated = new SliceWithStackTrace<K, V>(slice); sliceTranslationMap.put(slice, translated); } //noinspection unchecked return (SliceWithStackTrace) translated; } @Override public <K, V> V get(ReadOnlySlice<K, V> slice, K key) { return super.get(wrapSlice(slice), key).value; } @Override public <K, V> Collection<K> getKeys(WritableSlice<K, V> slice) { return super.getKeys(wrapSlice(slice)); } @NotNull @Override public Iterator<Map.Entry<SlicedMapKey<?, ?>, ?>> iterator() { Map<SlicedMapKey<?, ?>, Object> map = Maps.newHashMap(); Iterator<Map.Entry<SlicedMapKey<?, ?>, ?>> iterator = super.iterator(); //noinspection WhileLoopReplaceableByForEach while (iterator.hasNext()) { Map.Entry<SlicedMapKey<?, ?>, ?> entry = iterator.next(); map.put(entry.getKey(), ((TrackableValue<?>) entry.getValue()).value); } //noinspection unchecked return (Iterator) map.entrySet().iterator(); } @Override public <K, V> void put(WritableSlice<K, V> slice, K key, V value) { super.put(wrapSlice(slice), key, new TrackableValue<V>(value, trackWithStackTraces)); } @Override public <K, V> V remove(RemovableSlice<K, V> slice, K key) { return super.remove(wrapSlice(slice), key).value; } @Override public void clear() { super.clear(); } @Override @NotNull @TestOnly public <K, V> ImmutableMap<K, V> getSliceContents(@NotNull ReadOnlySlice<K, V> slice) { return super.getSliceContents(slice); } private static class TrackableValue<V> { private final static StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0]; private final V value; private final StackTraceElement[] stackTrace; private final String threadName; private TrackableValue(V value, boolean storeStack) { this.value = value; this.stackTrace = storeStack ? Thread.currentThread().getStackTrace() : EMPTY_STACK_TRACE; this.threadName = Thread.currentThread().getName(); } private Appendable printStackTrace(Appendable appendable) { Printer s = new Printer(appendable); s.println(value); s.println("Thread: " + threadName); s.println("Written at "); StackTraceElement[] trace = stackTrace; for (StackTraceElement aTrace : trace) { s.println("\tat " + aTrace); } s.println("---------"); return appendable; } @Override public String toString() { return printStackTrace(new StringBuilder()).toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrackableValue other = (TrackableValue) o; if (value != null ? !value.equals(other.value) : other.value != null) return false; return true; } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } } public class SliceWithStackTrace<K, V> implements RemovableSlice<K, TrackableValue<V>> { private final ReadOnlySlice<K, V> delegate; private SliceWithStackTrace(@NotNull ReadOnlySlice<K, V> delegate) { this.delegate = delegate; } // Methods of ReadOnlySlice @Override public SlicedMapKey<K, TrackableValue<V>> makeKey(K key) { //noinspection unchecked return (SlicedMapKey) delegate.makeKey(key); } @Override public TrackableValue<V> computeValue(SlicedMap map, K key, TrackableValue<V> value, boolean valueNotFound) { return new TrackableValue<V>(delegate.computeValue(map, key, value == null ? null : value.value, valueNotFound), trackWithStackTraces); } @Override public ReadOnlySlice<K, TrackableValue<V>> makeRawValueVersion() { return wrapSlice(delegate.makeRawValueVersion()); } // Methods of WritableSlice private WritableSlice<K, V> getWritableDelegate() { return (WritableSlice<K, V>) delegate; } @Override public boolean isCollective() { return getWritableDelegate().isCollective(); } @Override public RewritePolicy getRewritePolicy() { return getWritableDelegate().getRewritePolicy(); } @Override public void afterPut(MutableSlicedMap map, K key, TrackableValue<V> value) { getWritableDelegate().afterPut(map, key, value.value); } @Override public boolean check(K key, TrackableValue<V> value) { return getWritableDelegate().check(key, value.value); } } }
33.055276
147
0.631347
fd97c61b951432cf1017640d86e402cd71613600
698
import java.io.*; public class HeatMap { public static final String DATA_FILE = "data.csv"; HeatMap() { } /** * Parse dataset */ public void parse(File data) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(data)); String line; // read each line while ((line = reader.readLine()) != null) { // split line into tokens by whitespace regex, parse data String tokens[] = line.trim().split("\\s+"); } reader.close(); } public static void main(String[] args) { new HeatMap(); } } class Crash{ static void convertLatLong() { } }
16.619048
73
0.554441
f919035a790dc81ad375a4451bf81316558e9c12
2,055
package com.github.poetry.stop; import lombok.RequiredArgsConstructor; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.Set; /** * @author zhaoyuyu * @since 2019/11/27 */ @RequiredArgsConstructor public final class ClassicChineseStopWordSet implements StopWordSet { private static final double DEFAULT_COVERAGE_THRESHOLD = 70; private static final String RESOURCE_NAME = "chinese-word-stat.txt"; private final double coverageThreshold; public ClassicChineseStopWordSet() { this(DEFAULT_COVERAGE_THRESHOLD); } @Override public Set<String> get() { try (InputStream in = getClass().getClassLoader().getResourceAsStream(RESOURCE_NAME)) { assert in != null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { Set<String> result = new HashSet<>(); String line = reader.readLine(); while (line != null) { WordFreqStat stat = WordFreqStat.parseLine(line); if (stat.coverage > coverageThreshold) { result.add(stat.hanzi); } line = reader.readLine(); } return result; } } catch (IOException e) { throw new RuntimeException(e); } } @RequiredArgsConstructor @ToString private static final class WordFreqStat { private final int num; private final int codePoint; private final String hanzi; private final int freq; private final double coverage; static WordFreqStat parseLine(String line) { String[] a = StringUtils.splitPreserveAllTokens(line, '\t'); return new WordFreqStat( Integer.parseUnsignedInt(a[0]), Integer.parseUnsignedInt(a[1].substring(2), 16), a[3], Integer.parseInt(a[5]), Double.parseDouble(a[6])); } } }
27.4
91
0.682725
925888d67f4b9cdaea70b00bfe8d97710645a515
2,359
package main.java.pattern; import java.util.*; public class AlienDictionary { public static String findOrder(String[] words) { if(words == null || words.length ==0) return ""; StringBuilder sb = new StringBuilder(); Map<Character, List<Character>> graph = new HashMap<>(); Map<Character, Integer> inDegree = new HashMap<>(); //initialization for (String word: words){ for (char word1: word.toCharArray()) { inDegree.put(word1, 0); graph.put(word1, new ArrayList<>()); } } //compare the words build the graph for (int i=0; i< words.length-1; i++) { String word1 = words[i]; String word2 = words[i+1]; for (int j=0; j<Math.min(word1.length(), word2.length()); j++) { char parent = word1.charAt(j); char child = word2.charAt(j); if(parent != child) { graph.get(parent).add(child); inDegree.put(child, inDegree.get(child)+1); break; } } } Queue<Character> queue = new LinkedList<>(); for (Map.Entry<Character, Integer> entry: inDegree.entrySet()) { if (entry.getValue() == 0) { queue.add(entry.getKey()); } } while (!queue.isEmpty()) { char node = queue.poll(); sb.append(node); for (char children:graph.get(node)) { inDegree.put(children, inDegree.get(children)-1); if(inDegree.get(children) == 0) { queue.add(children); } } } if (sb.length() != inDegree.size()) return ""; return sb.toString(); } public static void main(String[] args) { String result = AlienDictionary.findOrder(new String[] { "ba", "bc", "ac", "cab" }); System.out.println("Character order: " + result); result = AlienDictionary.findOrder(new String[] { "cab", "aaa", "aab" }); System.out.println("Character order: " + result); result = AlienDictionary.findOrder(new String[] { "ywx", "wz", "xww", "xz", "zyy", "zwz" }); System.out.println("Character order: " + result); } }
31.039474
100
0.50106
d4d10e9d58313759ee90312ece9a7ea97d433df6
8,479
/** * this is based on jmetal.metaheuristics SPEA2.java * */ package mktgbi.moea; import java.io.IOException; import java.util.Comparator; import java.util.logging.Logger; import mktgbi.algorithm.util.RunMode; import mktgbi.dataio.Config; import mktgbi.moea.operator.ICrossover; import mktgbi.moea.operator.ISelector; import mktgbi.moea.operator.SolutionComparator; import mktgbi.moea.problem.Problem; /** * This class representing the SPEA2 algorithm */ public class Evolution { private static Logger sm_logger = Config.SM_LOGGER; private String m_objectivesFilename = null; private String m_variablesFilename = null; private String m_membersFilename = null; private String m_segmentSizeFilename = null; private String m_filenameAppendix = null; //Stores the problem to solve private Problem m_problem; private int m_minNumSegments = 0; private int m_maxNumSegments = 0; int m_setSize = 0; private SolutionSet[] m_solutionSet = null; private SolutionSet[] m_archive = null; private int m_evaluations = 0; private int m_populationSize, m_archiveSize, m_maxEvaluations; private ICrossover m_crossoverOperator = null; private ISelector m_selectionOperator = null; private int m_reportInterval = 0; private static int SM_REPORT_FREQUENCY = 10; private static int sm_numOfAdded = 0; private RunMode m_runMode = null; /** * Constructor. Create a new SPEA2 instance * * @param problem * Problem to solve */ public Evolution(Problem problem, RunMode runMode) { this.m_problem = problem; m_runMode = runMode; m_objectivesFilename = Config.OBJECTIVES_FILENAME; m_variablesFilename = Config.VARIABLES_FILENAME; m_membersFilename = Config.MEMBERS_FILENAME; m_segmentSizeFilename = Config.SEGMENT_SIZES_FILENAME; m_filenameAppendix = Config.FILENAME_APPENDIX; // Read the parameters m_populationSize = Config.getPopulationSize(); m_archiveSize = Config.getArchiveSize(); m_maxEvaluations = Config.getNumEvaluations(); // Mutation and Crossover for Real codification m_crossoverOperator = problem.getCrossoverOperator(); sm_logger.info("Crossover operator is: " + m_crossoverOperator.getClass().getSimpleName()); // Selection Operator m_selectionOperator = problem.getSelectorOperator(); sm_logger.info("Selection operator is: " + m_selectionOperator.getClass().getSimpleName()); // Initialize the variables m_minNumSegments = Config.getMinNumSegments(); m_maxNumSegments = Config.getMaxNumSegments(); m_setSize = m_maxNumSegments - m_minNumSegments + 1; m_solutionSet = new SolutionSet[m_setSize]; m_archive = new SolutionSet[m_setSize]; for (int setIndex = 0; setIndex < m_setSize; setIndex++) { m_solutionSet[setIndex] = new SolutionSet(m_populationSize); m_archive[setIndex] = new SolutionSet(m_archiveSize); } } /** * Runs of the Spea2 algorithm. * * @return a <code>SolutionSet</code> that is a set of non dominated * solutions as a result of the algorithm execution * @throws IOException * @throws JMException */ public SolutionSet[] execute() throws IOException { m_evaluations = 0; m_reportInterval = m_maxEvaluations / SM_REPORT_FREQUENCY; if (m_reportInterval == 0){ m_reportInterval = 1; } if (m_runMode == RunMode.READ_CHROMS || m_runMode == RunMode.READ_DETAIL) { for (int setIndex = 0; setIndex < m_setSize; setIndex++) { int segmentNumber = setIndex + m_minNumSegments; String filename = m_variablesFilename + "_" + String.valueOf(segmentNumber) + "_" + String.valueOf(0) + m_filenameAppendix; m_archive[setIndex] = m_problem.initFromFile(filename); evaluateSolutioinSet(m_archive); } sm_logger.info("Read inital archive: " + reportArchive()); } else { initilizeSolutionSet(); if (m_runMode == RunMode.DETAIL) { saveResults(); } } evolve(); return m_archive; } // execute private void initilizeSolutionSet() { sm_logger.info("Start solution set initialization"); // -> Create the initial solutionSet m_solutionSet = m_problem.initializeSolutions(); archiveSolutionSet(); sm_logger.info("Initial archive: " + reportArchive()); sm_numOfAdded = 0; } private void evolve() { sm_logger.info("Start evolving solution set."); int reportNumber = m_reportInterval; while (m_evaluations < m_maxEvaluations) { executeOperations(); archiveSolutionSet(); if (m_evaluations > reportNumber) { sm_logger.info("Generation number is " + m_evaluations + ". Number of added solutions: " + sm_numOfAdded + ". Archive status: " + reportArchive()); reportNumber += m_reportInterval; sm_numOfAdded = 0; if (m_runMode == RunMode.DETAIL || m_runMode == RunMode.READ_DETAIL) { saveResults(); } } } // while evaluations saveResults(); sm_logger.info("Evolution is done with number of evaluations: " + m_evaluations); } private String reportArchive() { StringBuilder retValue = new StringBuilder(); for (int setIndex = 0; setIndex < m_setSize; setIndex++) { int segmentNumber = setIndex + m_minNumSegments; retValue.append(" [Segment "); retValue.append(segmentNumber); retValue.append(" Size:"); retValue.append(m_archive[setIndex].size()); retValue.append( "] "); } return retValue.toString(); } private void archiveSolutionSet() { for (int setIndex = 0; setIndex < m_setSize; setIndex++) { SolutionSet solutionSet = m_solutionSet[setIndex]; SolutionSet archiveSet = m_archive[setIndex]; int oldSize = archiveSet.size(); SolutionSet union = SolutionSet.union(solutionSet, archiveSet); sm_numOfAdded += (union.size() - oldSize); Selection selection = new Selection(union); m_archive[setIndex] = selection.environmentalSelection(m_archiveSize); } } private void executeOperations() { SolutionSet[] offSpringSets = new SolutionSet[m_setSize]; for (int setIndex = 0; setIndex < m_setSize; setIndex++) { offSpringSets[setIndex] = new SolutionSet(); } int offSpringSize = 0; while (offSpringSize < m_populationSize && m_evaluations < m_maxEvaluations) { Solution[] parents = m_selectionOperator.execute(m_archive); Solution[] offsprings = m_crossoverOperator.execute(parents); for (int childIndex = 0; childIndex < offsprings.length; childIndex ++) { Solution offspring = offsprings[childIndex]; if (offspring != null) { int numSegments = offspring.getDecisionVariables().getNumSegments(); if ((numSegments >= m_minNumSegments) && (numSegments <= m_maxNumSegments)) { m_problem.evaluate(offspring); m_evaluations++; int setIndex = numSegments - m_minNumSegments; offSpringSets[setIndex].add(offspring); offSpringSize++; } } // else not a valid solution } } m_solutionSet = offSpringSets; } private void saveResults() { // sort the final solution set Comparator<Solution> comparator = new SolutionComparator(); for (int setIndex = 0; setIndex < m_setSize; setIndex++) { int segmentNumber = setIndex + m_minNumSegments; String objectivesFilename = m_objectivesFilename + "_" + String.valueOf(segmentNumber) + "_" + String.valueOf(m_evaluations) + m_filenameAppendix; String variablesFilename = m_variablesFilename + "_" + String.valueOf(segmentNumber) + "_" + String.valueOf(m_evaluations) + m_filenameAppendix; String membersFilename = m_membersFilename + "_" + String.valueOf(segmentNumber) + "_" + String.valueOf(m_evaluations) + m_filenameAppendix; String segmentSizeFilename = m_segmentSizeFilename + "_" + String.valueOf(segmentNumber) + "_" + String.valueOf(m_evaluations) + m_filenameAppendix; SolutionSet archive = m_archive[setIndex]; archive.sort(comparator); archive.printObjectivesToFile(objectivesFilename); archive.printVariablesToFile(variablesFilename); archive.printMembersToFile(membersFilename); archive.printSegmentSizesToFile(segmentSizeFilename); } } private void evaluateSolutioinSet(SolutionSet[] solutionSets) { int size = solutionSets.length; for (int setIndex = 0; setIndex < size; setIndex++) { SolutionSet solutionSet = solutionSets[setIndex]; int solutionSize = solutionSet.size(); for (int index = 0; index < solutionSize; index++) { Solution solution = solutionSet.get(index); m_problem.evaluate(solution); } } } }
31.756554
93
0.719896
2c275ec9f5f1ff961e65a445dc23a94f26b69cc1
570
package org.metahut.starfish.store.rdbms.repository; import org.metahut.starfish.store.rdbms.entity.RelationEntityProperty; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface RelationEntityPropertyRepository extends JpaRepository<RelationEntityProperty, Long>, JpaSpecificationExecutor<RelationEntityProperty> { List<RelationEntityProperty> removeByName(String name); }
31.666667
102
0.850877
430b59a3f8db12c3108b0f3a2e19143e61daef0f
442
package com.github.xxbeanxx.struts.actions.admin; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; /** * @author Greg Baker */ @SuppressWarnings("serial") public class IndexAction extends ActionSupport { public String fullAccess() throws Exception { return IndexAction.SUCCESS; } public String getNamespace() { return ServletActionContext.getActionMapping().getNamespace(); } }
20.090909
64
0.773756
01397c4319b0c1647782b32f9bdae49eb8d04bf9
1,956
package com.johnnghia.mvvmproject.views.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.johnnghia.mvvmproject.R; import com.johnnghia.mvvmproject.adapters.BlogsAdapter; import com.johnnghia.mvvmproject.databinding.BlogFragmentBinding; import com.johnnghia.mvvmproject.viewmodels.BlogUserViewModel; public class HomeFragment extends Fragment { private BlogFragmentBinding binding; private BlogUserViewModel blogUserViewModel; private RecyclerView recyclerView; private BlogsAdapter blogsAdapter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { blogUserViewModel = new BlogUserViewModel(); binding = DataBindingUtil.inflate(inflater, R.layout.blog_fragment, container, false); binding.setBlogs(blogUserViewModel); binding.setLifecycleOwner(this); blogsAdapter = new BlogsAdapter(blogUserViewModel.userbBlogs.getValue().list); binding.blogFragmentRv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); binding.blogFragmentRv.setAdapter(blogsAdapter); binding.blogFragmentRv.addItemDecoration(new DividerItemDecoration(binding.blogFragmentRv.getContext(), DividerItemDecoration.VERTICAL)); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } }
37.615385
145
0.797035
c11c27128954f777543f192318bd892c669c5f94
206
package problems; public class Q136_SingleNumber { public int singleNumber(int[] nums) { int num = 0; for (int i : nums) { num ^= i; } return num; } }
14.714286
41
0.495146
51ca949814aa31e82c92207fc902ef35ccafe6af
16,757
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql package|; end_package begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Iterator import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Queue import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|ConcurrentLinkedQueue import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|FileSinkOperator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|NodeUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|NodeUtils operator|. name|Function import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|Operator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|StatsTask import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|Task import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|TaskRunner import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|mr operator|. name|MapRedTask import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|HiveException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|MapWork import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|ReduceWork import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|session operator|. name|SessionState import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_comment comment|/** * Handles the queue of tasks that should be executed by the driver. */ end_comment begin_class specifier|public class|class name|TaskQueue block|{ specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|Driver operator|. name|class operator|. name|getName argument_list|() argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|SessionState operator|. name|LogHelper name|CONSOLE init|= operator|new name|SessionState operator|. name|LogHelper argument_list|( name|LOG argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|int name|SLEEP_TIME init|= literal|2000 decl_stmt|; specifier|private specifier|final name|Queue argument_list|< name|Task argument_list|< name|? argument_list|> argument_list|> name|runnable init|= operator|new name|ConcurrentLinkedQueue argument_list|< name|Task argument_list|< name|? argument_list|> argument_list|> argument_list|() decl_stmt|; empty_stmt|; specifier|private specifier|final name|List argument_list|< name|TaskRunner argument_list|> name|running init|= operator|new name|ArrayList argument_list|< name|TaskRunner argument_list|> argument_list|() decl_stmt|; specifier|private specifier|final name|Map argument_list|< name|String argument_list|, name|StatsTask argument_list|> name|statsTasks init|= operator|new name|HashMap argument_list|<> argument_list|( literal|1 argument_list|) decl_stmt|; specifier|private specifier|final name|Context name|ctx decl_stmt|; comment|// how many jobs have been started specifier|private name|int name|curJobNo decl_stmt|; specifier|private name|boolean name|shutdown decl_stmt|; specifier|public name|TaskQueue parameter_list|() block|{ name|this argument_list|( literal|null argument_list|) expr_stmt|; block|} specifier|public name|TaskQueue parameter_list|( name|Context name|ctx parameter_list|) block|{ name|this operator|. name|ctx operator|= name|ctx expr_stmt|; block|} specifier|public specifier|synchronized name|boolean name|isShutdown parameter_list|() block|{ return|return name|shutdown return|; block|} specifier|public specifier|synchronized name|boolean name|isRunning parameter_list|() block|{ return|return operator|! name|shutdown operator|&& operator|( operator|! name|running operator|. name|isEmpty argument_list|() operator||| operator|! name|runnable operator|. name|isEmpty argument_list|() operator|) return|; block|} specifier|public specifier|synchronized name|void name|remove parameter_list|( name|Task argument_list|< name|? argument_list|> name|task parameter_list|) block|{ name|runnable operator|. name|remove argument_list|( name|task argument_list|) expr_stmt|; block|} specifier|public specifier|synchronized name|void name|launching parameter_list|( name|TaskRunner name|runner parameter_list|) throws|throws name|HiveException block|{ name|checkShutdown argument_list|() expr_stmt|; name|running operator|. name|add argument_list|( name|runner argument_list|) expr_stmt|; block|} specifier|public specifier|synchronized name|Task argument_list|< name|? argument_list|> name|getRunnable parameter_list|( name|int name|maxthreads parameter_list|) throws|throws name|HiveException block|{ name|checkShutdown argument_list|() expr_stmt|; if|if condition|( name|runnable operator|. name|peek argument_list|() operator|!= literal|null operator|&& name|running operator|. name|size argument_list|() operator|< name|maxthreads condition|) block|{ return|return name|runnable operator|. name|remove argument_list|() return|; block|} return|return literal|null return|; block|} specifier|public specifier|synchronized name|void name|releaseRunnable parameter_list|() block|{ comment|//release the waiting poller. name|notify argument_list|() expr_stmt|; block|} comment|/** * Polls running tasks to see if a task has ended. * * @return The result object for any completed/failed task */ specifier|public specifier|synchronized name|TaskRunner name|pollFinished parameter_list|() throws|throws name|InterruptedException block|{ while|while condition|( operator|! name|shutdown condition|) block|{ name|Iterator argument_list|< name|TaskRunner argument_list|> name|it init|= name|running operator|. name|iterator argument_list|() decl_stmt|; while|while condition|( name|it operator|. name|hasNext argument_list|() condition|) block|{ name|TaskRunner name|runner init|= name|it operator|. name|next argument_list|() decl_stmt|; if|if condition|( name|runner operator|!= literal|null operator|&& operator|! name|runner operator|. name|isRunning argument_list|() condition|) block|{ name|it operator|. name|remove argument_list|() expr_stmt|; return|return name|runner return|; block|} block|} name|wait argument_list|( name|SLEEP_TIME argument_list|) expr_stmt|; block|} return|return literal|null return|; block|} specifier|private name|void name|checkShutdown parameter_list|() throws|throws name|HiveException block|{ if|if condition|( name|shutdown condition|) block|{ throw|throw operator|new name|HiveException argument_list|( literal|"FAILED: Operation cancelled" argument_list|) throw|; block|} block|} comment|/** * Cleans up remaining tasks in case of failure. */ specifier|public specifier|synchronized name|void name|shutdown parameter_list|() block|{ name|LOG operator|. name|debug argument_list|( literal|"Shutting down query " operator|+ name|ctx operator|. name|getCmd argument_list|() argument_list|) expr_stmt|; name|shutdown operator|= literal|true expr_stmt|; for|for control|( name|TaskRunner name|runner range|: name|running control|) block|{ if|if condition|( name|runner operator|. name|isRunning argument_list|() condition|) block|{ name|Task argument_list|< name|? argument_list|> name|task init|= name|runner operator|. name|getTask argument_list|() decl_stmt|; name|LOG operator|. name|warn argument_list|( literal|"Shutting down task : " operator|+ name|task argument_list|) expr_stmt|; try|try block|{ name|task operator|. name|shutdown argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|CONSOLE operator|. name|printError argument_list|( literal|"Exception on shutting down task " operator|+ name|task operator|. name|getId argument_list|() operator|+ literal|": " operator|+ name|e argument_list|) expr_stmt|; block|} name|Thread name|thread init|= name|runner operator|. name|getRunner argument_list|() decl_stmt|; if|if condition|( name|thread operator|!= literal|null condition|) block|{ name|thread operator|. name|interrupt argument_list|() expr_stmt|; block|} block|} block|} name|running operator|. name|clear argument_list|() expr_stmt|; block|} comment|/** * Checks if a task can be launched. * * @param tsk * the task to be checked * @return true if the task is launchable, false otherwise */ specifier|public specifier|static name|boolean name|isLaunchable parameter_list|( name|Task argument_list|< name|? argument_list|> name|tsk parameter_list|) block|{ comment|// A launchable task is one that hasn't been queued, hasn't been comment|// initialized, and is runnable. return|return name|tsk operator|. name|isNotInitialized argument_list|() operator|&& name|tsk operator|. name|isRunnable argument_list|() return|; block|} specifier|public specifier|synchronized name|boolean name|addToRunnable parameter_list|( name|Task argument_list|< name|? argument_list|> name|tsk parameter_list|) throws|throws name|HiveException block|{ if|if condition|( name|runnable operator|. name|contains argument_list|( name|tsk argument_list|) condition|) block|{ return|return literal|false return|; block|} name|checkShutdown argument_list|() expr_stmt|; name|runnable operator|. name|add argument_list|( name|tsk argument_list|) expr_stmt|; name|tsk operator|. name|setQueued argument_list|() expr_stmt|; return|return literal|true return|; block|} specifier|public name|int name|getCurJobNo parameter_list|() block|{ return|return name|curJobNo return|; block|} specifier|public name|void name|incCurJobNo parameter_list|( name|int name|amount parameter_list|) block|{ name|this operator|. name|curJobNo operator|= name|this operator|. name|curJobNo operator|+ name|amount expr_stmt|; block|} specifier|public name|void name|prepare parameter_list|( name|QueryPlan name|plan parameter_list|) block|{ comment|// extract stats keys from StatsTask name|List argument_list|< name|Task argument_list|< name|? argument_list|> argument_list|> name|rootTasks init|= name|plan operator|. name|getRootTasks argument_list|() decl_stmt|; name|NodeUtils operator|. name|iterateTask argument_list|( name|rootTasks argument_list|, name|StatsTask operator|. name|class argument_list|, operator|new name|Function argument_list|< name|StatsTask argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|apply parameter_list|( name|StatsTask name|statsTask parameter_list|) block|{ if|if condition|( name|statsTask operator|. name|getWork argument_list|() operator|. name|isAggregating argument_list|() condition|) block|{ name|statsTasks operator|. name|put argument_list|( name|statsTask operator|. name|getWork argument_list|() operator|. name|getAggKey argument_list|() argument_list|, name|statsTask argument_list|) expr_stmt|; block|} block|} block|} argument_list|) expr_stmt|; block|} specifier|public name|void name|finished parameter_list|( name|TaskRunner name|runner parameter_list|) block|{ if|if condition|( name|statsTasks operator|. name|isEmpty argument_list|() operator||| operator|! operator|( name|runner operator|. name|getTask argument_list|() operator|instanceof name|MapRedTask operator|) condition|) block|{ return|return; block|} name|MapRedTask name|mapredTask init|= operator|( name|MapRedTask operator|) name|runner operator|. name|getTask argument_list|() decl_stmt|; name|MapWork name|mapWork init|= name|mapredTask operator|. name|getWork argument_list|() operator|. name|getMapWork argument_list|() decl_stmt|; name|ReduceWork name|reduceWork init|= name|mapredTask operator|. name|getWork argument_list|() operator|. name|getReduceWork argument_list|() decl_stmt|; name|List argument_list|< name|Operator argument_list|> name|operators init|= operator|new name|ArrayList argument_list|< name|Operator argument_list|> argument_list|( name|mapWork operator|. name|getAliasToWork argument_list|() operator|. name|values argument_list|() argument_list|) decl_stmt|; if|if condition|( name|reduceWork operator|!= literal|null condition|) block|{ name|operators operator|. name|add argument_list|( name|reduceWork operator|. name|getReducer argument_list|() argument_list|) expr_stmt|; block|} specifier|final name|List argument_list|< name|String argument_list|> name|statKeys init|= operator|new name|ArrayList argument_list|< name|String argument_list|> argument_list|( literal|1 argument_list|) decl_stmt|; name|NodeUtils operator|. name|iterate argument_list|( name|operators argument_list|, name|FileSinkOperator operator|. name|class argument_list|, operator|new name|Function argument_list|< name|FileSinkOperator argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|apply parameter_list|( name|FileSinkOperator name|fsOp parameter_list|) block|{ if|if condition|( name|fsOp operator|. name|getConf argument_list|() operator|. name|isGatherStats argument_list|() condition|) block|{ name|statKeys operator|. name|add argument_list|( name|fsOp operator|. name|getConf argument_list|() operator|. name|getStatsAggPrefix argument_list|() argument_list|) expr_stmt|; block|} block|} block|} argument_list|) expr_stmt|; for|for control|( name|String name|statKey range|: name|statKeys control|) block|{ if|if condition|( name|statsTasks operator|. name|containsKey argument_list|( name|statKey argument_list|) condition|) block|{ name|statsTasks operator|. name|get argument_list|( name|statKey argument_list|) operator|. name|getWork argument_list|() operator|. name|setSourceTask argument_list|( name|mapredTask argument_list|) expr_stmt|; block|} else|else block|{ name|LOG operator|. name|debug argument_list|( literal|"There is no correspoing statTask for: " operator|+ name|statKey argument_list|) expr_stmt|; block|} block|} block|} block|} end_class end_unit
13.601461
813
0.791132
2ac57ac16c8f6ecad15f49953a9968331b020a95
1,828
public class Board { public int getScore(String[] input) { int row = input.length; int col = input[0].split(" ").length; String[][] grid = new String[row][col]; boolean[][] visited = new boolean[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { grid[i][j] = input[i].split(" ")[j]; } } int res = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (!visited[i][j]) { int[] cur = new int[2]; //area, points dfs(cur, grid, i, j, row, col, visited); res += cur[0] * cur[1]; } } } return res; } public void dfs(int[] cur, String[][] grid, int i, int j, int row, int col, boolean[][] visited) { char type = grid[i][j].charAt(0); cur[0]++; cur[1] += (int) (grid[i][j].charAt(1) - '0'); visited[i][j] = true; int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; for (int[] dir : dirs) { int x = i + dir[0]; int y = j + dir[1]; if (x < 0 || x >= row || y < 0 || y >= col) { continue; } if (visited[x][y]) { continue; } if (grid[x][y].charAt(0) != type) { continue; } dfs(cur, grid, x, y, row, col, visited); } } public static void main(String[] args) { String[] input = {"S0 W1 W1 W0 L2", "W0 W0 T0 T0 T0", "W0 W1 T0 M2 M1", "S0 L0 S1 S0 S0", "M0 R2 R0 S1 T0"}; Board b = new Board(); System.out.println(b.getScore(input)); } }
29.483871
102
0.378009
b1baacfdb07e2527ac7f0f7ba3400a697005fdda
1,023
package com.tinkerpop.furnace.wrappers.derived; import com.tinkerpop.blueprints.Vertex; import java.util.Iterator; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class DerivedVertexIterable implements Iterable<Vertex> { private final Iterable<Vertex> vertices; private final DerivedGraph derivedGraph; public DerivedVertexIterable(final Iterable<Vertex> vertices, final DerivedGraph derivedGraph) { this.vertices = vertices; this.derivedGraph = derivedGraph; } public Iterator<Vertex> iterator() { return new Iterator<Vertex>() { private final Iterator<Vertex> itty = vertices.iterator(); public void remove() { throw new UnsupportedOperationException(); } public Vertex next() { return new DerivedVertex(itty.next(), derivedGraph); } public boolean hasNext() { return this.itty.hasNext(); } }; } }
26.230769
100
0.630499
6d076b68da9895b4431e49ae26eb6a02caab1122
432
package com.rubus.event_hub; public class user_college_profile { public String name,college, email,department,phone; public user_college_profile(){ } public user_college_profile(String name, String college, String email,String department,String phone) { this.name = name; this.college=college; this.email = email; this.department=department; this.phone = phone; } }
21.6
107
0.678241
360f6e85ba695ef608184e25a5798fde86c8e77f
153
package co.edu.javeriana.configuracion.conf.bean.configuracion; public class BPMConf extends OSBConf { public BPMConf() { super(); } }
17
63
0.686275
c8f0163aac5ec586a0eca97dd6b312693077a468
2,135
package mindustry.ui.dialogs; import arc.*; import arc.graphics.*; import arc.graphics.g2d.*; import arc.input.*; import arc.scene.event.*; import arc.scene.ui.layout.*; import mindustry.gen.*; import static mindustry.Vars.renderer; public class MinimapDialog extends FloatingDialog{ public MinimapDialog(){ super("$minimap"); setFillParent(true); shown(this::setup); addCloseButton(); shouldPause = true; titleTable.remove(); onResize(this::setup); } void setup(){ cont.clear(); cont.table(Tex.pane,t -> { t.addRect((x, y, width, height) -> { if(renderer.minimap.getRegion() == null) return; Draw.color(Color.white); Draw.alpha(parentAlpha); Draw.rect(renderer.minimap.getRegion(), x + width / 2f, y + height / 2f, width, height); if(renderer.minimap.getTexture() != null){ renderer.minimap.drawEntities(x, y, width, height); } }).grow(); }).size(Math.min(Core.graphics.getWidth() / 1.1f, Core.graphics.getHeight() / 1.3f) / Scl.scl(1f)).padTop(-20f); cont.addListener(new InputListener(){ @Override public boolean scrolled(InputEvent event, float x, float y, float amountx, float amounty){ renderer.minimap.zoomBy(amounty); return true; } }); cont.addListener(new ElementGestureListener(){ float lzoom = -1f; @Override public void touchUp(InputEvent event, float x, float y, int pointer, KeyCode button){ lzoom = renderer.minimap.getZoom(); } @Override public void zoom(InputEvent event, float initialDistance, float distance){ if(lzoom < 0){ lzoom = renderer.minimap.getZoom(); } renderer.minimap.setZoom(initialDistance / distance * lzoom); } }); Core.app.post(() -> Core.scene.setScrollFocus(cont)); } }
30.070423
120
0.554098
37765145bdc4fc5aa29fe01f094489864f9ed2d0
501
package fr.itris.glips.svgeditor.actions.frame; public class MeasValue { private int id; private String name; private int psrId; 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 int getPsrId() { return psrId; } public void setPsrId(int psrId) { this.psrId = psrId; } @Override public String toString() { return this.name; } }
12.525
47
0.662675
f30786b0b01a2791c9b4fe9cea784236c61777fd
892
package org.jsoftware.utils.retriable; import org.junit.Assert; import org.junit.Test; public class RetriableDelayFunctionTest { @Test public void testLinear() throws Exception { RetriableDelayFunction function = RetriableDelayFunction.linearFunction(10); for(int i=0; i<10; i++) { Assert.assertEquals(10*i, function.retryWait(i)); } } @Test public void testConst() throws Exception { RetriableDelayFunction function = RetriableDelayFunction.constFunction(10); for(int i=0; i<10; i++) { Assert.assertEquals(10, function.retryWait(i)); } } @Test public void testNoDely() throws Exception { RetriableDelayFunction function = RetriableDelayFunction.noDealyFunction(); for(int i=0; i<10; i++) { Assert.assertEquals(0, function.retryWait(i)); } } }
28.774194
84
0.64574
140ec4ea31b8841cafa7e3d414064e3a0b5b1d44
8,580
package com.didi.carmate.dreambox.core; import android.app.Application; import android.content.Context; import androidx.annotation.WorkerThread; import androidx.lifecycle.Lifecycle; import com.didi.carmate.dreambox.core.action.DBActionAlias; import com.didi.carmate.dreambox.core.action.DBActions; import com.didi.carmate.dreambox.core.action.DBChangeMeta; import com.didi.carmate.dreambox.core.action.DBClosePage; import com.didi.carmate.dreambox.core.action.DBDialog; import com.didi.carmate.dreambox.core.action.DBInvoke; import com.didi.carmate.dreambox.core.action.DBLog; import com.didi.carmate.dreambox.core.action.DBNav; import com.didi.carmate.dreambox.core.action.DBNet; import com.didi.carmate.dreambox.core.action.DBStorage; import com.didi.carmate.dreambox.core.action.DBToast; import com.didi.carmate.dreambox.core.action.DBTrace; import com.didi.carmate.dreambox.core.action.DBTraceAttr; import com.didi.carmate.dreambox.core.base.DBCallbacks; import com.didi.carmate.dreambox.core.base.DBContext; import com.didi.carmate.dreambox.core.base.DBNodeParser; import com.didi.carmate.dreambox.core.base.DBNodeRegistry; import com.didi.carmate.dreambox.core.base.DBPack; import com.didi.carmate.dreambox.core.base.DBTemplate; import com.didi.carmate.dreambox.core.base.INodeCreator; import com.didi.carmate.dreambox.core.bridge.DBSendEvent; import com.didi.carmate.dreambox.core.bridge.DBSendEventMsg; import com.didi.carmate.dreambox.core.data.DBGlobalPool; import com.didi.carmate.dreambox.core.data.DBMeta; import com.didi.carmate.dreambox.core.render.DBButton; import com.didi.carmate.dreambox.core.render.DBCell; import com.didi.carmate.dreambox.core.render.DBChildren; import com.didi.carmate.dreambox.core.render.DBFlow; import com.didi.carmate.dreambox.core.render.DBImage; import com.didi.carmate.dreambox.core.render.DBLView; import com.didi.carmate.dreambox.core.render.DBList; import com.didi.carmate.dreambox.core.render.DBListFooter; import com.didi.carmate.dreambox.core.render.DBListHeader; import com.didi.carmate.dreambox.core.render.DBListVh; import com.didi.carmate.dreambox.core.render.DBLoading; import com.didi.carmate.dreambox.core.render.DBProgress; import com.didi.carmate.dreambox.core.render.DBRender; import com.didi.carmate.dreambox.core.render.DBText; import com.didi.carmate.dreambox.core.render.DBView; import com.didi.carmate.dreambox.core.render.view.IDBCoreView; import com.didi.carmate.dreambox.core.utils.DBUtils; import com.google.gson.Gson; import com.google.gson.JsonObject; /** * author: chenjing * date: 2020/5/6 */ public class DBEngine { private static volatile DBEngine sInstance; private Application mApplication; private DBNodeParser mDBLoader; private DBEngine() { } public static DBEngine getInstance() { if (sInstance == null) { synchronized (DBEngine.class) { if (sInstance == null) { sInstance = new DBEngine(); } } } return sInstance; } public void init(Application application) { mApplication = application; mDBLoader = new DBNodeParser(); initInternal(); } public Application getApplication() { return mApplication; } @WorkerThread public synchronized JsonObject extWrapper(String extJsonObject) { JsonObject extJson = null; if (!DBUtils.isEmpty(extJsonObject)) { extJson = new Gson().fromJson(extJsonObject, JsonObject.class); } return extJson; } @WorkerThread public synchronized DBTemplate parser(String accessKey, String templateId, String dblTemplate) { DBContext dbContext = new DBContext(mApplication, accessKey, templateId); return mDBLoader.parser(dbContext, dblTemplate); } public IDBCoreView render(DBTemplate template, JsonObject extJsonObject, Context currentContext, Lifecycle lifecycle) { if (null != template) { template.setExtJsonObject(extJsonObject); template.setCurrentContext(currentContext); // 节点树解析 template.parserAttribute(); template.parserNode(); template.finishParserNode(); // 绑定生命周期 template.bindLifecycle(lifecycle); return template.getDBCoreView(); } return null; } // public boolean putProperties(String accessKey, DBTemplate template, Map properties) { // return true; // } // // public boolean putProperty(String accessKey, DBTemplate template, String key, Object value) { // return true; // } // // public boolean putGlobalProperties(String accessKey, Map properties) { // return true; // } public void putGlobalProperty(String accessKey, String key, String value) { DBGlobalPool.get(accessKey).addData(key, value); } public void putGlobalProperty(String accessKey, String key, int value) { DBGlobalPool.get(accessKey).addData(key, value); } public void putGlobalProperty(String accessKey, String key, boolean value) { DBGlobalPool.get(accessKey).addData(key, value); } public void registerDBNode(String nodeTag, INodeCreator nodeCreator) { DBNodeRegistry.registerNode(nodeTag, nodeCreator); } private void initInternal() { registerRenderNode(); registerActionNode(); registerOtherNode(); } private void registerRenderNode() { DBNodeRegistry.registerNode(DBLView.getNodeTag(), new DBLView.NodeCreator()); DBNodeRegistry.registerNode(DBRender.getNodeTag(), new DBRender.NodeCreator()); DBNodeRegistry.registerNode(DBView.getNodeTag(), new DBView.NodeCreator()); DBNodeRegistry.registerNode(DBText.getNodeTag(), new DBText.NodeCreator()); DBNodeRegistry.registerNode(DBImage.getNodeTag(), new DBImage.NodeCreator()); DBNodeRegistry.registerNode(DBButton.getNodeTag(), new DBButton.NodeCreator()); DBNodeRegistry.registerNode(DBLoading.getNodeTag(), new DBLoading.NodeCreator()); DBNodeRegistry.registerNode(DBProgress.getNodeTag(), new DBProgress.NodeCreator()); DBNodeRegistry.registerNode(DBList.getNodeTag(), new DBList.NodeCreator()); DBNodeRegistry.registerNode(DBListVh.getNodeTag(), new DBListVh.NodeCreator()); DBNodeRegistry.registerNode(DBListHeader.getNodeTag(), new DBListHeader.NodeCreator()); DBNodeRegistry.registerNode(DBListFooter.getNodeTag(), new DBListFooter.NodeCreator()); DBNodeRegistry.registerNode(DBFlow.getNodeTag(), new DBFlow.NodeCreator()); DBNodeRegistry.registerNode(DBChildren.getNodeTag(), new DBChildren.NodeCreator()); DBNodeRegistry.registerNode(DBPack.getNodeTag(), new DBPack.NodeCreator()); DBNodeRegistry.registerNode(DBCell.getNodeTag(), new DBCell.NodeCreator()); } private void registerActionNode() { DBNodeRegistry.registerNode(DBClosePage.getNodeTag(), new DBClosePage.NodeCreator()); DBNodeRegistry.registerNode(DBLog.getNodeTag(), new DBLog.NodeCreator()); DBNodeRegistry.registerNode(DBTrace.getNodeTag(), new DBTrace.NodeCreator()); DBNodeRegistry.registerNode(DBTraceAttr.getNodeTag(), new DBTraceAttr.NodeCreator()); DBNodeRegistry.registerNode(DBActionAlias.getNodeTag(), new DBActionAlias.NodeCreator()); DBNodeRegistry.registerNode(DBStorage.getNodeTag(), new DBStorage.NodeCreator()); DBNodeRegistry.registerNode(DBChangeMeta.getNodeTag(), new DBChangeMeta.NodeCreator()); DBNodeRegistry.registerNode(DBDialog.getNodeTag(), new DBDialog.NodeCreator()); DBNodeRegistry.registerNode(DBNav.getNodeTag(), new DBNav.NodeCreator()); DBNodeRegistry.registerNode(DBNet.getNodeTag(), new DBNet.NodeCreator()); DBNodeRegistry.registerNode(DBToast.getNodeTag(), new DBToast.NodeCreator()); DBNodeRegistry.registerNode(DBInvoke.getNodeTag(), new DBInvoke.NodeCreator()); DBNodeRegistry.registerNode(DBActions.getNodeTag(), new DBActions.NodeCreator()); } private void registerOtherNode() { // bridge DBNodeRegistry.registerNode(DBSendEvent.getNodeTag(), new DBSendEvent.NodeCreator()); DBNodeRegistry.registerNode(DBSendEventMsg.getVNodeTag(), new DBSendEventMsg.VNodeCreator()); // meta DBNodeRegistry.registerNode(DBMeta.getNodeTag(), new DBMeta.NodeCreator()); // callback DBNodeRegistry.registerNode(DBCallbacks.getNodeTag(), new DBCallbacks.NodeCreator()); } }
43.77551
123
0.732284
d50c5dc36721c633a6d1a9b5903f5eee9340e8e1
8,783
package qiniu.predem.android.probe; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.squareup.okhttp.ResponseBody; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import okio.BufferedSource; import qiniu.predem.android.bean.LogBean; import qiniu.predem.android.bean.RespBean; import qiniu.predem.android.config.Configuration; import qiniu.predem.android.http.ProbeBufferedSource; import qiniu.predem.android.util.LogUtils; import qiniu.predem.android.util.MatcherUtil; /** * Created by Misty on 17/6/19. */ @Aspect public final class OkHttp2Probe { protected static final HashMap<ResponseBody, Response> RespBodyToRespMap = new HashMap<>(); protected static final HashMap<String, Long> dnsTimeMap = new HashMap<>(); protected static final HashMap<String, String> DomainToIpMap = new HashMap<>(); protected static final List<RespBean> startTimeStamp = new ArrayList<>(); private static final String TAG = "OkHttp2Probe"; @Around("call(* com.squareup.okhttp.Dns+.lookup(..))") public Object onOkHttpDnsLookup(ProceedingJoinPoint joinPoint) throws Throwable { if (!Configuration.httpMonitorEnable || !Configuration.dnsEnable) { return joinPoint.proceed(); } try { if (joinPoint.getArgs().length != 1) { return joinPoint.proceed(); } String hostName = (String) joinPoint.getArgs()[0]; // exclude url if (GlobalConfig.isExcludeHost(hostName)) { return joinPoint.proceed(); } long stime = System.currentTimeMillis(); Object result; try { result = joinPoint.proceed(); } catch (UnknownHostException e) { LogUtils.e(TAG, "-----networkError " + e.toString()); return joinPoint.proceed(); } long dnsTime = System.currentTimeMillis() - stime; synchronized (dnsTimeMap) { if (!dnsTimeMap.containsKey(hostName)) { dnsTimeMap.put(hostName, dnsTime); } } if (result instanceof List && ((List) result).get(0) instanceof InetAddress) { DomainToIpMap.put(((List<InetAddress>) result).get(0).getHostName(), ((List<InetAddress>) result).get(0).getHostAddress()); } return result; } catch (Throwable e) { LogUtils.e(TAG, "-----networkError " + e.toString()); return joinPoint.proceed(); } } @Around("call(* java.net.InetSocketAddress+.createUnresolved(..))") public Object onSocketAddressResolve(ProceedingJoinPoint joinPoint) throws Throwable { if (!Configuration.httpMonitorEnable || !Configuration.dnsEnable) { return joinPoint.proceed(); } try { if (joinPoint.getArgs().length != 2) { return joinPoint.proceed(); } String domain = (String) joinPoint.getArgs()[0]; // exclude url if (GlobalConfig.isExcludeHost(domain)) { return joinPoint.proceed(); } // match ip Matcher matcher = MatcherUtil.IP_Pattern.matcher(domain); if (matcher.find()) { return joinPoint.proceed(); } else { long stime = System.currentTimeMillis(); Object result = joinPoint.proceed(); synchronized (dnsTimeMap) { dnsTimeMap.put(domain, System.currentTimeMillis() - stime); } return result; } } catch (Throwable e) { LogUtils.e(TAG, "-----networkError " + e.toString()); return joinPoint.proceed(); } } @Around("call(* com.squareup.okhttp.Response.Builder+.build(..))") public Object onOkHttpRespBuild(ProceedingJoinPoint joinPoint) throws Throwable { if (!Configuration.httpMonitorEnable) { return joinPoint.proceed(); } Object result = joinPoint.proceed(); if (result instanceof Response) { Response resp = (Response) result; RespBodyToRespMap.put(resp.body(), resp); } return result; } @Around("call(* com.squareup.okhttp.OkHttpClient+.newCall(..))") public Object onOkHttpNew(ProceedingJoinPoint joinPoint) throws Throwable { if (!Configuration.httpMonitorEnable || joinPoint.getArgs().length != 1) { return joinPoint.proceed(); } Object[] args = joinPoint.getArgs(); Request request = (Request) args[0]; //url URL url = request.url(); if (GlobalConfig.isExcludeHost(url.getHost())) { return joinPoint.proceed(); } RespBean bean = new RespBean(); bean.setUrl(url.toString()); bean.setStartTimestamp(System.currentTimeMillis()); startTimeStamp.add(bean); return joinPoint.proceed(); } @Around("call(* com.squareup.okhttp.ResponseBody+.source(..))") public Object onOkHttpRespBodySource(ProceedingJoinPoint joinPoint) throws Throwable { if (!Configuration.httpMonitorEnable) { return joinPoint.proceed(); } Object result = joinPoint.proceed(); if (result instanceof BufferedSource && joinPoint.getTarget() instanceof ResponseBody) { ResponseBody respBody = (ResponseBody) joinPoint.getTarget(); if (RespBodyToRespMap.containsKey(respBody)) { URL url = RespBodyToRespMap.get(respBody).request().url(); String hostName = url.getHost(); LogUtils.d(TAG, "-----okhttp url " + url.toString()); // exclude host if (GlobalConfig.isExcludeHost(hostName)) { return result; } Response resp = RespBodyToRespMap.get(respBody); RespBodyToRespMap.remove(respBody); String location = resp.header("Location"); LogUtils.d(TAG, "-----location " + location); if (location != null) { for (int i = 0; i < startTimeStamp.size(); i++) { RespBean bean = startTimeStamp.get(i); if (bean.getUrl().equals(url.toString())) { bean.setUrl(location); startTimeStamp.set(i, bean); break; } } } if (resp != null) { synchronized (dnsTimeMap) { LogBean urlTraceRecord = LogBean.obtain(); urlTraceRecord.setDomain(hostName); urlTraceRecord.setPath(url.getPath()); urlTraceRecord.setMethod(resp.request().method()); urlTraceRecord.setStatusCode(resp.code()); urlTraceRecord.setResponseTimestamp(System.currentTimeMillis()); for (int i = 0; i < startTimeStamp.size(); i++) { RespBean bean = startTimeStamp.get(i); if (bean.getUrl().equals(url.toString())) { urlTraceRecord.setStartTimestamp(bean.getStartTimestamp()); // startTimeStamp.remove(i); break; } } if (dnsTimeMap.containsKey(hostName)) { if (DomainToIpMap.containsKey(hostName)) { urlTraceRecord.setHostIP(DomainToIpMap.get(hostName)); } urlTraceRecord.setDnsTime(dnsTimeMap.get(hostName)); } else { urlTraceRecord.setHostIP("-"); urlTraceRecord.setDnsTime(0); } if (result instanceof ProbeBufferedSource) { return result; } else { return ProbeBufferedSource.obtain((BufferedSource) result, urlTraceRecord); } } } } } return result; } }
39.563063
103
0.547535
8797427c3609a3fde2ea2992e5d05268a182bf5e
18,768
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package ec.edu.espe.translate.view; import ec.edu.espe.translate.controller.FormsHandler; import javax.swing.JOptionPane; /** * * @author Juan Diego */ public class FrmRegister extends javax.swing.JFrame { /** * Creates new form FrmRegister */ public FrmRegister() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); cmbDay = new javax.swing.JComboBox<>(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); cmbMonth = new javax.swing.JComboBox<>(); jLabel8 = new javax.swing.JLabel(); txtYear = new javax.swing.JTextField(); btnRegister = new javax.swing.JButton(); btnReturn = new javax.swing.JButton(); txtName = new javax.swing.JTextField(); txtCellPhone = new javax.swing.JTextField(); txtEmail = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jPasswordField1 = new javax.swing.JPasswordField(); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane2.setViewportView(jTable2); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N jLabel1.setText("REGISTER TO TRANSLATE"); jLabel2.setText("Name:"); jLabel3.setText("Cell phone:"); jLabel4.setText("Email:"); jLabel5.setText("Birth Date"); cmbDay.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" })); jLabel6.setText("DAY:"); jLabel7.setText("MONTH:"); cmbMonth.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "January", "February", "March", "April", "may", "June", "July", "August", "September", "October", "November", "December" })); cmbMonth.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbMonthActionPerformed(evt); } }); jLabel8.setText("YEAR:"); btnRegister.setText("REGISTER"); btnRegister.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRegisterActionPerformed(evt); } }); btnReturn.setText("RETURN"); btnReturn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnReturnActionPerformed(evt); } }); jLabel9.setText("Password:"); jLabel10.setText("MONTH:"); jButton1.setBackground(new java.awt.Color(240, 240, 210)); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagen/google.jpg"))); // NOI18N jButton1.setText("jButton1"); jButton1.setMargin(new java.awt.Insets(2, 14, 2, -20)); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagen/facebook.jpg"))); // NOI18N jButton2.setText("jButton2"); jButton2.setAlignmentY(0.0F); jButton2.setMargin(new java.awt.Insets(2, 14, 2, -15)); jButton2.setMaximumSize(new java.awt.Dimension(450, 20)); jButton2.setMinimumSize(new java.awt.Dimension(400, 103)); jButton2.setPreferredSize(new java.awt.Dimension(461, 103)); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagen/Apple.jpg"))); // NOI18N jButton3.setText("jButton3"); jButton3.setMargin(new java.awt.Insets(2, 14, 2, -15)); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(161, 161, 161) .addComponent(jLabel5)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9)) .addGroup(layout.createSequentialGroup() .addGap(153, 153, 153) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btnRegister) .addComponent(btnReturn, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cmbDay, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(jLabel7))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(247, 247, 247)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(cmbMonth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4)) .addGap(45, 45, 45) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPasswordField1) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(txtName) .addComponent(txtCellPhone) .addComponent(txtEmail)))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(44, 44, 44) .addComponent(jLabel8) .addGap(18, 18, 18) .addComponent(txtYear, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 377, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(128, 128, 128)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txtCellPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(15, 15, 15) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(9, 9, 9) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cmbDay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cmbMonth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8) .addComponent(jLabel7) .addComponent(jLabel6) .addComponent(jLabel10)) .addGap(18, 18, 18) .addComponent(btnRegister) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 118, Short.MAX_VALUE) .addComponent(btnReturn) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegisterActionPerformed JOptionPane.showMessageDialog(this,"Successfuly registered"); FrmTranslateAppLogin frmTranslateAppLogin = new FrmTranslateAppLogin(); frmTranslateAppLogin.setVisible(true); this.setVisible(false); }//GEN-LAST:event_btnRegisterActionPerformed private void btnReturnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReturnActionPerformed FormsHandler.goToMainScreen(this); }//GEN-LAST:event_btnReturnActionPerformed private void cmbMonthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbMonthActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cmbMonthActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed FrmGoogle1 frmGoogle1 = new FrmGoogle1(); frmGoogle1.setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed FrmApple frmApple = new FrmApple(); frmApple.setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButton3ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed FrmFacebook frmFacebook = new FrmFacebook(); frmFacebook.setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FrmTranslateApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FrmTranslateApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FrmTranslateApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FrmTranslateApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrmRegister().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnRegister; private javax.swing.JButton btnReturn; private javax.swing.JComboBox<String> cmbDay; private javax.swing.JComboBox<String> cmbMonth; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPasswordField jPasswordField1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JTable jTable2; private javax.swing.JTextField txtCellPhone; private javax.swing.JTextField txtEmail; private javax.swing.JTextField txtName; private javax.swing.JTextField txtYear; // End of variables declaration//GEN-END:variables }
50.451613
267
0.636296
ae7fcca25fdfc418481f48975e8ed38a1056867c
735
package com.zhao.leetcode; //68 剑指offer public class LowestParentNode2 { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode x= root; while (true){ if (p.val<x.val&&q.val<x.val){ x=x.left; }else if (p.val>x.val&&q.val>x.val){ x=x.right; }else { break; } } return x; } }
25.344828
81
0.482993
697ec03389093a8742f17308d9a0713401a53031
697
package org.springframework.samples.ioc.annotation.annotation.based.required; import org.springframework.beans.factory.annotation.Required; import org.springframework.samples.model.PlainModelOne; /** * Happy day, happy life. * * @author andy * @version 1.0-SNAPSHOT * Created date: 2015-01-29 21:53 */ public class RequiredAnnotationBean { private PlainModelOne plainModelOne; @Required public void setPlainModelOne(PlainModelOne plainModelOne) { this.plainModelOne = plainModelOne; } @Override public String toString() { return "RequiredAnnotationBean{" + "plainModelOne=" + plainModelOne + '}'; } }
24.034483
77
0.682927
60c0da26be17b724c2db46b1cb7405fb0cab1713
1,281
package monkeylord.XServer.api; import java.lang.reflect.Method; import java.util.Map; import monkeylord.XServer.XServer; import monkeylord.XServer.XposedEntry; import monkeylord.XServer.handler.ObjectHandler; //处理反射调用 public class Invoke extends BaseOperation { @Override public String handle(String url, Map<String, String> parms, Map<String, String> headers, Map<String, String> files) { StringBuilder sb = new StringBuilder(); Object thisobj; Object[] params; thisobj = parms.get("thisobj").equals("null") ? null : ObjectHandler.objects.get(parms.get("thisobj")); try { Method[] methods = Class.forName(parms.get("class"), false, XposedEntry.classLoader).getDeclaredMethods(); Method m = methods[Integer.parseInt(parms.get("method"))]; params = new Object[m.getParameterTypes().length]; for (int i = 0; i < m.getParameterTypes().length; i++) { params[i] = XServer.parsers.get(parms.get("parser" + i)).parse(parms.get("param" + i)); } m.setAccessible(true); sb.append(m.invoke(thisobj, params)); } catch (Exception e) { sb.append(e.getLocalizedMessage()); } return sb.toString(); } }
35.583333
121
0.63466
6cf5c4f32d6312154d3e114f1872783362c88fdd
4,563
package me.saket.dank.ui.compose; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.ViewFlipper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.FragmentManager; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import me.saket.dank.R; import me.saket.dank.ui.DankDialogFragment; import me.saket.dank.ui.giphy.GiphyGif; import me.saket.dank.widgets.AnimatedProgressBar; public class InsertGifDialog extends DankDialogFragment { private static final String KEY_GIPHY_GIF = "giphyGif"; private static final String KEY_PAYLOAD = "payload"; @BindView(R.id.uploadimage_image) ImageView imageView; @BindView(R.id.uploadimage_file_size) TextView fileSizeView; @BindView(R.id.uploadimage_state_viewflipper) ViewFlipper stateViewFlipper; @BindView(R.id.uploadimage_upload_progress_bar) AnimatedProgressBar progressBar; @BindView(R.id.uploadimage_title) EditText titleField; @BindView(R.id.uploadimage_url) TextView urlView; @BindView(R.id.uploadimage_state_failed_tap_to_retry) TextView errorView; @BindView(R.id.uploadimage_insert) Button insertButton; public interface OnGifInsertListener { void onGifInsert(String title, GiphyGif gif, @Nullable Parcelable payload); } public static void showWithPayload(FragmentManager fragmentManager, GiphyGif imageUrl, @Nullable Parcelable payload) { String tag = InsertGifDialog.class.getSimpleName(); InsertGifDialog dialog = (InsertGifDialog) fragmentManager.findFragmentByTag(tag); if (dialog != null) { dialog.dismiss(); } dialog = new InsertGifDialog(); Bundle arguments = new Bundle(); arguments.putParcelable(KEY_GIPHY_GIF, imageUrl); if (payload != null) { arguments.putParcelable(KEY_PAYLOAD, payload); } dialog.setArguments(arguments); dialog.show(fragmentManager, tag); } public static void show(FragmentManager fragmentManager, GiphyGif imageUrl) { showWithPayload(fragmentManager, imageUrl, null); } @Override public void onAttach(Context context) { super.onAttach(context); if (!(getHost() instanceof OnGifInsertListener)) { throw new AssertionError(); } } @NonNull @Override @SuppressLint("InflateParams") public Dialog onCreateDialog(Bundle savedInstanceState) { super.onCreateDialog(savedInstanceState); View dialogLayout = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_upload_image, null); ButterKnife.bind(this, dialogLayout); //noinspection ConstantConditions GiphyGif giphyGif = getArguments().getParcelable(KEY_GIPHY_GIF); Parcelable payload = getArguments().getParcelable(KEY_PAYLOAD); //noinspection ConstantConditions displayPickedImage(giphyGif.previewUrl()); urlView.setText(giphyUrlWithoutScheme(giphyGif.url())); stateViewFlipper.setDisplayedChild(stateViewFlipper.indexOfChild(stateViewFlipper.findViewById(R.id.uploadimage_state_uploaded))); insertButton.setEnabled(true); insertButton.setOnClickListener(v -> { String title = titleField.getText().toString().trim(); ((OnGifInsertListener) requireHost()).onGifInsert(title, giphyGif, payload); dismiss(); }); AlertDialog dialog = new AlertDialog.Builder(requireContext()) .setView(dialogLayout) .create(); titleField.requestFocus(); //noinspection ConstantConditions dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); return dialog; } @OnClick(R.id.uploadimage_cancel) void onClickCancel() { dismiss(); } private void displayPickedImage(String imageUrl) { Glide.with(this) .load(imageUrl) .transition(DrawableTransitionOptions.withCrossFade()) .into(imageView); } private static String giphyUrlWithoutScheme(String giphyUrl) { String scheme = Uri.parse(giphyUrl).getScheme(); return giphyUrl.substring((scheme + "://").length(), giphyUrl.length()); } }
33.306569
134
0.766382
607c54c174adb403c6f7d2d1b18e1efdedde3443
1,936
package edu.rhhs.frc.commands; import edu.rhhs.frc.subsystems.PneumaticSubsystem; import edu.rhhs.frc.subsystems.ShooterPitchAngle; import edu.rhhs.frc.subsystems.ShooterWheelRPM; import edu.wpi.first.wpilibj.command.CommandGroup; /** * @author rhhs */ public class ShooterShoot3FrisbeesHalfCourtWaitRPM extends CommandGroup { public ShooterShoot3FrisbeesHalfCourtWaitRPM() { addSequential(new ShooterWheelSetRPM(ShooterWheelRPM.SHOOTER_WHEEL_RPM_REAR_PYRAMID)); addSequential(new ShooterSetShootPositionRelative(ShooterPitchAngle.SHOOT_HALF_COURT_RELATIVE_ANGLE)); addSequential(new ShooterKickerShootOne()); addSequential(new ShooterLoaderSwish()); addSequential(new ShooterWheelSetRPM(ShooterWheelRPM.SHOOTER_WHEEL_RPM_REAR_PYRAMID)); addSequential(new ShooterSetShootPositionRelative(ShooterPitchAngle.SHOOT_HALF_COURT_RELATIVE_ANGLE)); addSequential(new WaitTimer(ShooterWheelRPM.SHOOTER_WHEEL_DELAY_BETWEEN_SHOTS_SEC)); addSequential(new ShooterKickerShootOne()); // addParallel(new ChassisMove(8.0, 0.8)); addSequential(new ShooterLoaderSetPosition(PneumaticSubsystem.EXTEND)); addSequential(new ShooterIntakeTimedRollers(0.6, 0.1)); addSequential(new ShooterIntakeTimedRearRoller(1.0 , 0.5)); addSequential(new ShooterLoaderSetPosition(PneumaticSubsystem.RETRACT)); // addSequential(new WaitCommand(1.0)); // addSequential(new ShooterIntakeTimedRollers(0.9, 0.5)); addParallel(new ShooterIntakeTimedRollers(1.0, 1.0)); addSequential(new ShooterWheelSetRPM(ShooterWheelRPM.SHOOTER_WHEEL_RPM_REAR_PYRAMID)); addSequential(new ShooterSetShootPositionRelative(ShooterPitchAngle.SHOOT_HALF_COURT_RELATIVE_ANGLE)); addSequential(new WaitTimer(ShooterWheelRPM.SHOOTER_WHEEL_DELAY_BETWEEN_SHOTS_SEC)); addSequential(new ShooterKickerShootOne()); } }
49.641026
110
0.777376
2653e668c7e6efae5dcbb7e5b3d1907e8caf56e9
11,815
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.plugins.groovy; import com.intellij.codeInsight.actions.ReformatCodeProcessor; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.completion.impl.NegatingComparable; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.lookup.LookupElementWeigher; import com.intellij.icons.AllIcons; import com.intellij.lang.xml.XMLLanguage; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.LeafElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlText; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.impl.GenericDomValueReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.dom.MavenVersionComparable; import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil; import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager; import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.library.RepositoryLibraryDescription; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; /** * @author Vladislav.Soroka */ public class MavenGroovyPomCompletionContributor extends CompletionContributor { public static final Key<VirtualFile> ORIGINAL_POM_FILE = Key.create("ORIGINAL_POM_FILE"); @Override public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) { final PsiElement position = parameters.getPosition(); if (!(position instanceof LeafElement)) return; Project project = position.getProject(); VirtualFile virtualFile = parameters.getOriginalFile().getVirtualFile(); if(virtualFile == null) return; MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(virtualFile); if (mavenProject == null) return; List<String> methodCallInfo = MavenGroovyPomUtil.getGroovyMethodCalls(position); if (methodCallInfo.isEmpty()) return; StringBuilder buf = new StringBuilder(); for (String s : methodCallInfo) { buf.append('<').append(s).append('>'); } for (String s : ContainerUtil.reverse(methodCallInfo)) { buf.append('<').append(s).append("/>"); } PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(MavenConstants.POM_XML, XMLLanguage.INSTANCE, buf); psiFile.putUserData(ORIGINAL_POM_FILE, virtualFile); List<Object> variants = new ArrayList<>(); String lastMethodCall = ContainerUtil.getLastItem(methodCallInfo); Ref<Boolean> completeDependency = Ref.create(false); Ref<Boolean> completeVersion = Ref.create(false); psiFile.accept(new PsiRecursiveElementVisitor(true) { @Override public void visitElement(@NotNull PsiElement element) { super.visitElement(element); if (!completeDependency.get() && element.getParent() instanceof XmlTag && "dependency".equals(((XmlTag)element.getParent()).getName())) { if ("artifactId".equals(lastMethodCall) || "groupId".equals(lastMethodCall)) { completeDependency.set(true); } else if ("version".equals(lastMethodCall) || "dependency".equals(lastMethodCall)) { completeVersion.set(true); //completeDependency.set(true); } } if (!completeDependency.get() && !completeVersion.get()) { PsiReference[] references = getReferences(element); for (PsiReference each : references) { if (each instanceof GenericDomValueReference) { Collections.addAll(variants, each.getVariants()); } } } } }); for (Object variant : variants) { if (variant instanceof LookupElement) { result.addElement((LookupElement)variant); } else { result.addElement(LookupElementBuilder.create(variant)); } } if (completeDependency.get()) { MavenProjectIndicesManager indicesManager = MavenProjectIndicesManager.getInstance(project); for (String groupId : indicesManager.getGroupIds()) { for (String artifactId : indicesManager.getArtifactIds(groupId)) { LookupElement builder = LookupElementBuilder.create(groupId + ':' + artifactId) .withIcon(AllIcons.Nodes.PpLib).withInsertHandler(MavenDependencyInsertHandler.INSTANCE); result.addElement(builder); } } } if (completeVersion.get()) { consumeDependencyElement(position, closableBlock -> { String groupId = null; String artifactId = null; for (GrMethodCall methodCall : PsiTreeUtil.findChildrenOfType(closableBlock, GrMethodCall.class)) { GroovyPsiElement[] arguments = methodCall.getArgumentList().getAllArguments(); if (arguments.length != 1) continue; PsiReference reference = arguments[0].getReference(); if (reference == null) continue; String callExpression = methodCall.getInvokedExpression().getText(); String argumentValue = reference.getCanonicalText(); if ("groupId".equals(callExpression)) { groupId = argumentValue; } else if ("artifactId".equals(callExpression)) { artifactId = argumentValue; } } completeVersions(result, project, groupId, artifactId, ""); }, element -> { if (element.getParent() instanceof PsiLiteral) { Object value = ((PsiLiteral)element.getParent()).getValue(); if (value == null) return; String[] mavenCoordinates = value.toString().split(":"); if (mavenCoordinates.length < 3) return; String prefix = mavenCoordinates[0] + ':' + mavenCoordinates[1] + ':'; completeVersions(result, project, mavenCoordinates[0], mavenCoordinates[1], prefix); } }); } } private static void completeVersions(@NotNull CompletionResultSet completionResultSet, @NotNull Project project, @Nullable String groupId, @Nullable String artifactId, @NotNull String prefix) { if (StringUtil.isEmptyOrSpaces(artifactId)) return; CompletionResultSet newResultSet = completionResultSet.withRelevanceSorter(CompletionService.getCompletionService().emptySorter().weigh( new LookupElementWeigher("mavenVersionWeigher") { @Nullable @Override public Comparable weigh(@NotNull LookupElement element) { return new NegatingComparable(new MavenVersionComparable(StringUtil.trimStart(element.getLookupString(), prefix))); } })); MavenProjectIndicesManager indicesManager = MavenProjectIndicesManager.getInstance(project); Set<String> versions; if (StringUtil.isEmptyOrSpaces(groupId)) { versions = Collections.emptySet(); //if (!(coordinates instanceof MavenDomPlugin)) return; // //versions = indicesManager.getVersions(MavenArtifactUtil.DEFAULT_GROUPS[0], artifactId); //for (int i = 0; i < MavenArtifactUtil.DEFAULT_GROUPS.length; i++) { // versions = Sets.union(versions, indicesManager.getVersions(MavenArtifactUtil.DEFAULT_GROUPS[i], artifactId)); //} } else { versions = indicesManager.getVersions(groupId, artifactId); } for (String version : versions) { newResultSet.addElement(LookupElementBuilder.create(prefix + version)); } newResultSet.addElement(LookupElementBuilder.create(prefix + RepositoryLibraryDescription.ReleaseVersionId)); newResultSet.addElement(LookupElementBuilder.create(prefix + RepositoryLibraryDescription.LatestVersionId)); } @NotNull private static PsiReference[] getReferences(PsiElement psiElement) { return psiElement instanceof XmlText ? psiElement.getParent().getReferences() : psiElement.getReferences(); } private static void consumeDependencyElement(PsiElement psiElement, Consumer<GrClosableBlock> closureNotationConsumer, Consumer<PsiElement> stringNotationConsumer) { final GrClosableBlock owner = PsiTreeUtil.getParentOfType(psiElement, GrClosableBlock.class); if (owner != null && owner.getParent() instanceof GrMethodCallExpression) { String invokedExpressionText = ((GrMethodCallExpression)owner.getParent()).getInvokedExpression().getText(); if ("dependency".equals(invokedExpressionText)) { closureNotationConsumer.consume(owner); } if ("dependencies".equals(invokedExpressionText)) { GrMethodCall methodCall = PsiTreeUtil.getParentOfType(psiElement, GrMethodCall.class); if (methodCall != null && "dependency".equals(methodCall.getInvokedExpression().getText())) { stringNotationConsumer.consume(psiElement); } } } } private static class MavenDependencyInsertHandler implements InsertHandler<LookupElement> { private static final InsertHandler<LookupElement> INSTANCE = new MavenDependencyInsertHandler(); @Override public void handleInsert(@NotNull final InsertionContext context, @NotNull LookupElement item) { String s = item.getLookupString(); int idx = s.indexOf(':'); String groupId = s.substring(0, idx); String artifactId = s.substring(idx + 1); int startOffset = context.getStartOffset(); PsiFile psiFile = context.getFile(); PsiElement psiElement = psiFile.findElementAt(startOffset); consumeDependencyElement(psiElement, closableBlock -> { int textOffset = closableBlock.getTextOffset(); String value = "{groupId '" + groupId + "'\n" + "artifactId '" + artifactId + "'\n" + "version ''}"; context.getDocument().replaceString(textOffset, textOffset + closableBlock.getTextLength(), value); context.getEditor().getCaretModel().moveToOffset(textOffset + value.length() - 2); context.commitDocument(); new ReformatCodeProcessor(psiFile.getProject(), psiFile, closableBlock.getTextRange(), false).run(); MavenDependencyCompletionUtil.invokeCompletion(context, CompletionType.BASIC); }, element -> { int textOffset = element.getTextOffset(); String value = '\'' + groupId + ":" + artifactId + ":'"; context.getDocument().replaceString(textOffset, textOffset + element.getTextLength(), value); context.getEditor().getCaretModel().moveToOffset(textOffset + value.length() - 1); MavenDependencyCompletionUtil.invokeCompletion(context, CompletionType.BASIC); }); } } }
44.584906
140
0.702412
857b01874e39e3a39ef604216feb69a5c519a76a
1,503
/* * Copyright (C) 2013 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.code.axonguice.saga; import com.google.inject.Injector; import org.axonframework.saga.ResourceInjector; import org.axonframework.saga.Saga; import javax.inject.Inject; /** * Guice-based {@link ResourceInjector} implementation. * * @author Alexey Krylov * @see SagaModule#bindResourceInjector() * @since 14.02.13 */ public class GuiceResourceInjector implements ResourceInjector { /*===========================================[ INSTANCE VARIABLES ]===========*/ @Inject private Injector injector; /*===========================================[ INTERFACE METHODS ]============*/ @Override public void injectResources(Saga saga) { injector.injectMembers(saga); } }
31.978723
82
0.66334
65de5277e2fb6a8d1742fb045615cefad7f05b72
189
package uk.czcz.freespacefinder; import java.util.ArrayList; import java.util.List; public class HardcodedData { public static List<List<CarPark>> carParkList = new ArrayList<>(); }
18.9
70
0.756614
7f2ae7dcf86c492640e28bfb89cc0617d8e354a6
5,102
package gov.med.va.innovations.util; import gov.va.medora.mdws.emrsvc.EmrSvcSoap; import gov.va.medora.mdws.emrsvc.UserTO; import gov.va.medora.mdws.querysvc.QuerySvcSoap; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * Track stateful Mdws clients by session. Unfortunately, these cannot be stored in the session * as they're non-serializable. A session Destroyed listener will clean up these entries. * @author VHADMAROSENMA * */ public class MdwsClientFactory implements ApplicationContextAware { private static final Log LOG = LogFactory.getLog(MdwsClientFactory.class); private Map<String,MdwsClient> clients = Collections.synchronizedMap(new HashMap<String,MdwsClient>()); private String initialSite; private ApplicationContext applicationContext; public void setInitialSite(String initialSite) { this.initialSite = initialSite; } public String getInitialSite() { return initialSite; } /** * Retrieve managed session for a session * @param sessionId * @return */ public EmrSvcSoap getMdwsForClient() { String sessionId = getSessionId(); MdwsClient client = clients.get(sessionId); if (client == null) client = createNewClient(sessionId); return client.getEmrService(); } /** * Convenience method for retrieving a session, and logging on the session if not already logged on * * @param sessionId * @param access - Vista Access code * @param verify - Vista verify code * @return */ public EmrSvcSoap getMdwsForClient(String access, String verify) { EmrSvcSoap service = getMdwsForClient(); MdwsClient client = clients.get(getSessionId()); if (!client.isLoggedIn()) { client.setAccessCode(access); client.setVerifyCode(verify); UserTO user = service.login(access, verify, ""); if (user.getDUZ() != null) client.setLoggedIn(true); } return service; } /** * Retrieve managed session for a session * @param sessionId * @return */ public QuerySvcSoap getQueryForClient() { String sessionId = getSessionId(); MdwsClient client = clients.get(sessionId); if (client == null) client = createNewClient(sessionId); QuerySvcSoap query = client.getQueryService(); // Log in should have already happened client.queryLogin(); return query; } /** * Convenience method for retrieving a session, and logging on the session if not already logged on * * @param sessionId * @param access - Vista Access code * @param verify - Vista verify code * @return */ public QuerySvcSoap getQueryForClient(String access, String verify) { QuerySvcSoap service = getQueryForClient(); MdwsClient client = clients.get(getSessionId()); if (!client.isLoggedIn()) { client.setAccessCode(access); client.setVerifyCode(verify); gov.va.medora.mdws.querysvc.UserTO user = service.login(access, verify, ""); if (user.getDUZ() != null) client.setLoggedIn(true); } return service; } private String getSessionId() { String sessionId = SessionSecurityContextHolder.getSessionID(); if (null == sessionId) throw new RuntimeException("No session ID stored in SessionSecurityContextHolder!"); return sessionId; } public void cacheCredentials(String accessCode, String verifyCode) { String sessionId = SessionSecurityContextHolder.getSessionID(); MdwsClient client = clients.get(sessionId); client.setAccessCode(accessCode); client.setVerifyCode(verifyCode); if (LOG.isDebugEnabled()) LOG.debug("Checking MDWS Client for valid logon"); if (null != client.getEmrService().getWards() && null == client.getEmrService().getWards().getFault()) client.setLoggedIn(true); } public void remove() { clients.get(getSessionId()).disconnect(); clients.remove(getSessionId()); } private MdwsClient createNewClient(String sessionId) { if (LOG.isDebugEnabled()) LOG.debug("Creating new MDWS Client"); MdwsClient mdwsClient = (MdwsClient) applicationContext.getBean("mdwsClient"); clients.put(sessionId, mdwsClient); return mdwsClient; } public synchronized void destroy() { if (LOG.isDebugEnabled()) LOG.debug("Destroying all MDWS Clients"); String[] keys = clients.keySet().toArray(new String[0]); for (String key : keys) { MdwsClient client = clients.get(key); client.disconnect(); clients.remove(key); } } public void reconnect() { if (LOG.isDebugEnabled()) LOG.debug("Reconnecting MDWS Client"); MdwsClient client =clients.get(getSessionId()); client.disconnect(); client.connect(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
31.109756
105
0.715014
6a8f1d0ae16211f33976b97b424139b9a2f2285c
835
package edu.isistan.racecondition; import edu.isistan.racecondition.account.LockAccount; public class LockMain { public static void main(String[] args) { Account a1 = new LockAccount(1, 1000); Account a2 = new LockAccount(2, 1000); Thread t1 = new Thread(new Transfer(a1, a2, 100)); Thread t2 = new Thread(new Transfer(a2, a1, 100)); long time = System.currentTimeMillis(); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } time = System.currentTimeMillis() - time; System.out.println("Finishing"); System.out.println(a1); System.out.println(a2); System.out.println("The program run for "+time+" ms."); } }
28.793103
63
0.579641
59e8f0351b431e0e1c22bc4edb38b08251a4ab14
1,108
package com.shiwuliang.optional; import java.util.Optional; import java.util.function.Function; /** * OptionalTest * * @author ziyuan * @since 2017-08-15 */ public class OptionalTest { private static class User { private String phone; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } public static void main(String[] args) { User u = null; Optional<User> userOpt = Optional.ofNullable(u); Optional<String> phOpt1 = userOpt.flatMap((usr) -> Optional.ofNullable(usr.getPhone())); //为什么user为null,但是user.getPhone不会报错呢,因为这个时候的userOpt其实已经是一个空optional了 Optional<String> phOpt2 = userOpt.flatMap(new Function<User, Optional<String>>() { @Override public Optional<String> apply(User user) { return Optional.ofNullable(user.getPhone()); } }); //这两种都不会出错 System.out.println(phOpt1.orElse("0000")); System.out.println(phOpt2.orElse("0000")); } }
24.086957
96
0.605596
f8eeb1fae791df71e138770a33ff78e0ef97e1c5
2,568
package fr.catcore.gamegui.codec; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import java.util.UUID; public class GameCreatorHelper { private static final Object2ObjectMap<UUID, CompoundTag> CURRENT_EDITED_CONFIG = new Object2ObjectOpenHashMap<>(); private static final Object2ObjectMap<UUID, String> CURRENT_EDITED_FIELD = new Object2ObjectOpenHashMap<>(); public static void startCreatingConfig(UUID playerUUID, CompoundTag configTag) { CURRENT_EDITED_CONFIG.put(playerUUID, configTag); CURRENT_EDITED_FIELD.put(playerUUID, ""); } public static void setEditingField(UUID playerUUID, String fieldName) { CURRENT_EDITED_FIELD.replace(playerUUID, fieldName); } public static String getEditingField(UUID playerUUID) { return CURRENT_EDITED_FIELD.get(playerUUID); } public static Tag getEditingFieldValue(UUID playerUUID) { CompoundTag compoundTag = CURRENT_EDITED_CONFIG.get(playerUUID); String fieldId = CURRENT_EDITED_FIELD.get(playerUUID); String[] parts = fieldId.split("/"); Tag result = null; for (String part : parts) { result = compoundTag.get(part); if (result instanceof CompoundTag) { compoundTag = (CompoundTag) result; } else { break; } } return result; } public static void setEditingFieldValue(UUID playerUUID, Tag value) { CompoundTag compoundTag = CURRENT_EDITED_CONFIG.get(playerUUID); String fieldId = CURRENT_EDITED_FIELD.get(playerUUID); String[] parts = fieldId.split("/"); Tag result = null; for (String part : parts) { result = compoundTag.get(part); if (result instanceof CompoundTag) { compoundTag = (CompoundTag) result; } else { compoundTag.put(part, value); } } } public static CompoundTag getPlayerCurrentConfig(UUID playerUUID) { return CURRENT_EDITED_CONFIG.getOrDefault(playerUUID, new CompoundTag()); } public static void clearPlayerCurrentConfig(UUID playerUUID) { CURRENT_EDITED_CONFIG.remove(playerUUID); } public static String[] getPossibleChars() { return new String[]{" ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}; } }
35.178082
137
0.651869
8f6147c15a36191e8229bbf2a47ea63686f86c12
261
package softuni.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import softuni.entities.Camera; @Repository public interface CameraRepository extends JpaRepository<Camera,Long> { }
26.1
70
0.850575
98bdecfd0ccb4049c97d41b9e49e32bac22f8c98
646
package com.saggezza.ecommerce.response; import com.fasterxml.jackson.annotation.JsonProperty; /** * Token Response Data * * @author Prashant CHaudhary * */ public class TokenResponseData { @JsonProperty("access_token") private String accessToken; @JsonProperty("token_expiry_time") private long tokenExpiryTime; public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public long getTokenExpiryTime() { return tokenExpiryTime; } public void setTokenExpiryTime(long tokenExpiryTime) { this.tokenExpiryTime = tokenExpiryTime; } }
17.944444
55
0.763158
ec9e6867dc4c0915bb18c199425ebb7395c8ec1c
710
package ca.d4nish1234.exercise.crackingthecodinginterviewbook; public class E1_1_IsUniqueChars { public static void main(String[] args) { System.out.println(isUniqueChars(new char [] {'a','b'})); System.out.println(isUniqueChars(new char [] {'a','b','C','c','B'})); System.out.println(isUniqueChars(new char [] {'a','b','C','c','B','a'})); } static boolean isUniqueChars(char [] charList) { System.out.print("is char list unique: "); System.out.println(charList); boolean [] boolList = new boolean [128]; // z has the highest char int value of 122 for (char c : charList) { if (boolList[c] == false ) { boolList[c] = true; } else { return false; } } return true; } }
28.4
85
0.64507
a75ae342cbc2d13a2c4face8e47408bf5ae0d5ff
4,082
package net.canarymod.api.chat; /** * Wrapper interface for Minecraft native ChatStyle * * @author Jason (darkdiplomat) */ public interface ChatStyle extends Cloneable { /** * Gets the {@link ChatFormatting} for this {@code ChatStyle} * * @return {@link ChatFormatting} */ ChatFormatting getColor(); /** * Checks if this {@code ChatStyle} is bold * * @return {@code true} if bold; {@code false} if not */ boolean isBold(); /** * Checks if this {@code ChatStyle} is italic * * @return {@code true} if italic; {@code false} if not */ boolean isItalic(); /** * Checks if this {@code ChatStyle} is strikethrough * * @return {@code true} if strikethrough; {@code false} if not */ boolean isStrikethrough(); /** * Checks if this {@code ChatStyle} is underlined * * @return {@code true} if underlined; {@code false} if not */ boolean isUnderlined(); /** * Checks if this {@code ChatStyle} is obfuscated (random) * * @return {@code true} if obfuscated; {@code false} if not */ boolean isObfuscated(); /** * Checks if this {@code ChatStyle} is empty * * @return {@code true} if empty; {@code false} if not */ boolean isEmpty(); /** * Gets the assigned {@link ClickEvent} * * @return {@link ClickEvent} */ ClickEvent getChatClickEvent(); /** * Gets the assigned {@link HoverEvent} * * @return {@link HoverEvent} */ HoverEvent getChatHoverEvent(); /** * Sets the {@link ChatFormatting} of this {@code ChatStyle} * * @param color * the {@link ChatFormatting} color * * @return {@code this} */ ChatStyle setColor(ChatFormatting color); /** * Sets if this {@code ChatStyle} is bold * * @param bold * {@code true} if bold; {@code false} if not * * @return {@code this} */ ChatStyle setBold(boolean bold); /** * Sets if this {@code ChatStyle} is italic * * @param italic * {@code true} if bold; {@code false} if not * * @return {@code this} */ ChatStyle setItalic(boolean italic); /** * Sets if this {@code ChatStyle} is strikethrough * * @param strikethrough * {@code true} if strikethrough; {@code false} if not * * @return {@code this} */ ChatStyle setStrikethrough(boolean strikethrough); /** * Sets if this {@code ChatStyle} is bold * * @param underlined * {@code true} if underlined; {@code false} if not * * @return {@code this} */ ChatStyle setUnderlined(boolean underlined); /** * Sets if this {@code ChatStyle} is bold * * @param obfuscated * {@code true} if obfuscated; {@code false} if not * * @return {@code this} */ ChatStyle setObfuscated(boolean obfuscated); /** * Sets the {@link ClickEvent} of this {@code ChatStyle} * * @param clickEvent * the {@link ClickEvent} to be set * * @return {@code this} */ ChatStyle setChatClickEvent(ClickEvent clickEvent); /** * Sets the {@link HoverEvent} of this {@code ChatStyle} * * @param hoverEvent * the {@link HoverEvent} to be set * * @return {@code this} */ ChatStyle setChatHoverEvent(HoverEvent hoverEvent); /** * Sets the {@code ChatStyle} parent of this {@code ChatStyle} * * @param chatStyle * the {@code ChatStyle} to set as parent * * @return {@code this} */ ChatStyle setParentStyle(ChatStyle chatStyle); /** * Gets the parent {@code ChatStyle} of this {@code ChatStyle} * * @return the parent {@code ChatStyle} */ ChatStyle getParentStyle(); /** * Clones this {@code ChatStyle} * * @return {@code ChatStyle} clone */ ChatStyle clone(); }
23.062147
66
0.554875
4c2a46b8526ebba36d9ba34ce4d63c101ff3ca6a
809
package accounts.rest.api; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; import accounts.businesslogic.interfaces.AccountService; import accounts.businesslogic.services.SimpleAccountService; import accounts.rest.AccountServiceFactory; @Path("accounts/{id}") public class AccountResource { private AccountService accountService; public AccountResource() { this.accountService = new AccountServiceFactory().getService(); } @GET public Response getAccount(@PathParam("id") String id) { var account = this.accountService.getAccount(id); if (account == null) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(account).build(); } }
25.28125
71
0.714462
7f3d40c498a67bb6ad13593a8837dbeca15fc8e8
1,226
package io.leopard.data.alldb; import io.leopard.json.Json; import io.leopard.redis.Redis; public class StringsImpl { private Redis redis; private int seconds; private String keyPattern; public Redis getRedis() { return redis; } public void setRedis(Redis redis) { this.redis = redis; } public String getKeyPattern() { return keyPattern; } public void setKeyPattern(String keyPattern) { this.keyPattern = keyPattern; } public int getSeconds() { return seconds; } public void setSeconds(int seconds) { this.seconds = seconds; } public boolean set(Object bean, Object... keys) { String key = this.getKey(keys); String json = Json.toJson(bean); if (seconds > 0) { redis.set(key, json, seconds);// 1小时过期 } else { redis.set(key, json);// 1小时过期 } return true; } public <T> T get(Class<T> elementType, Object... keys) { String key = this.getKey(keys); System.err.println("strings key:" + key); String json = redis.get(key); return Json.toObject(json, elementType); } protected String getKey(Object... keys) { String key = keyPattern; for (int i = 0; i < keys.length; i++) { key = key.replace("$" + (i + 1), keys[i].toString()); } return key; } }
18.575758
57
0.663132
796890491a4323ee93817380926f941104db84c4
633
package com.company.Simulation.SimulationFunctions; import com.company.Simulation.SimulationVariables.SimulationGlobals; import com.company.Simulation.SimulationVariables.WaveFront; import java.util.ArrayList; public class InterProcessComputations { /** * Основная функция для выполнения операций, происходящих внутри симуляции */ public static ArrayList<WaveFront> getResult(ArrayList<WaveFront> prevWavePicture) { ArrayList<WaveFront> wavePicture = new ArrayList<>(prevWavePicture); //System.out.print("A"); SimulationGlobals.nextSimulationTime(); return wavePicture; } }
30.142857
88
0.755134
4e8688b261ed0a4e74430734baa903ae3e4eae5f
2,495
package com.aveng.wapp.web.rest; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.aveng.wapp.service.DiffService; import com.aveng.wapp.service.dto.Diff; import com.aveng.wapp.service.dto.DiffType; import com.aveng.wapp.service.dto.StringDiff; import com.aveng.wapp.service.dto.StringDiffResult; import com.aveng.wapp.web.rest.model.ApiResponse; import lombok.extern.slf4j.Slf4j; /** * @author apaydin */ @RestController @RequestMapping("/v1/diff") @Slf4j public class DiffController { private DiffService diffService; @Autowired public DiffController(DiffService diffService) { this.diffService = diffService; } @PostMapping(value = "/{id}/left") public ResponseEntity<ApiResponse<Diff>> acceptLeftDiff(@PathVariable long id, @RequestBody String base64EncodedInput) { log.info("Accepted left input: {} for id: {}", base64EncodedInput, id); Diff diff = diffService.acceptDiffInput(id, base64EncodedInput, DiffType.LEFT); return ResponseEntity.ok(ApiResponse.<Diff>builder() .message("Left diff accepted") .data(diff) .build()); } @PostMapping(value = "/{id}/right") public ResponseEntity<ApiResponse<Diff>> acceptRightDiff(@PathVariable long id, @RequestBody String base64EncodedInput) { log.info("Accepted right input: {} for id: {}", base64EncodedInput, id); Diff diff = diffService.acceptDiffInput(id, base64EncodedInput, DiffType.RIGHT); return ResponseEntity.ok(ApiResponse.<Diff>builder() .message("right diff accepted") .data(diff) .build()); } @GetMapping("/{id}") public ResponseEntity<ApiResponse<List<StringDiff>>> retrieveDiff(@PathVariable long id) { StringDiffResult diffResult = diffService.diff(id); return ResponseEntity.ok(ApiResponse.<List<StringDiff>>builder() .message(diffResult.getMessage()) .data(diffResult.getStringDiffs()) .build()); } }
32.402597
94
0.71503
546c6c56eb5dd26c5d707c845ede0c7d9354f6e4
1,331
/* * Copyright 2012-2013 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 lombok.core; /** * @author Andres Almiray */ public interface BaseConstants { String WILDCARD = "?"; String R = "R"; String T = "T"; String VOID = "void"; String BOOLEAN = "boolean"; String JAVA_LANG_OBJECT = "java.lang.Object"; String JAVA_LANG_STRING = "java.lang.String"; String GROOVY_LANG_CLOSURE = "groovy.lang.Closure"; String GRIFFON_UTIL_RUNNABLEWITHARGS = "griffon.util.RunnableWithArgs"; String GRIFFON_UTIL_CALLABLEWITHARGS = "griffon.util.CallableWithArgs"; String JAVA_UTIL_MAP = "java.util.Map"; String JAVA_UTIL_LIST = "java.util.List"; String JAVA_LANG_RUNNABLE = "java.lang.Runnable"; String JAVA_NET_URL = "java.net.URL"; }
35.026316
75
0.717506
c15f721f1365b24ab8113e0aa06350781633c956
341
package com.example.project05mongodb; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Project05MongodbApplication { public static void main(String[] args) { SpringApplication.run(Project05MongodbApplication.class, args); } }
24.357143
68
0.835777
5d0c9178734e55ea4023fe29369661f6384d3bfc
12,575
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|optimizer operator|. name|ppr package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|api operator|. name|FieldSchema import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|api operator|. name|FileMetadataExprType import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|FileFormatProxy import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|PartitionExpressionProxy import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|api operator|. name|MetaException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|SerializationUtilities import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|io operator|. name|orc operator|. name|OrcFileFormatProxy import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|io operator|. name|orc operator|. name|OrcInputFormat import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|io operator|. name|sarg operator|. name|ConvertAstToSearchArg import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|io operator|. name|sarg operator|. name|SearchArgument import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|HiveException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse operator|. name|SemanticException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|ExprNodeDescUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|ExprNodeGenericFuncDesc import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|serde2 operator|. name|typeinfo operator|. name|PrimitiveTypeInfo import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|serde2 operator|. name|typeinfo operator|. name|TypeInfoFactory import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_comment comment|/** * The basic implementation of PartitionExpressionProxy that uses ql package classes. */ end_comment begin_class specifier|public class|class name|PartitionExpressionForMetastore implements|implements name|PartitionExpressionProxy block|{ specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|PartitionExpressionForMetastore operator|. name|class argument_list|) decl_stmt|; annotation|@ name|Override specifier|public name|String name|convertExprToFilter parameter_list|( name|byte index|[] name|exprBytes parameter_list|, name|String name|defaultPartitionName parameter_list|) throws|throws name|MetaException block|{ name|ExprNodeGenericFuncDesc name|expr init|= name|deserializeExpr argument_list|( name|exprBytes argument_list|) decl_stmt|; if|if condition|( operator|( name|defaultPartitionName operator|!= literal|null operator|) operator|&& operator|( operator|! name|defaultPartitionName operator|. name|isEmpty argument_list|() operator|) condition|) block|{ try|try block|{ name|ExprNodeDescUtils operator|. name|replaceNullFiltersWithDefaultPartition argument_list|( name|expr argument_list|, name|defaultPartitionName argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|SemanticException name|ex parameter_list|) block|{ name|LOG operator|. name|error argument_list|( literal|"Failed to replace \"is null\" and \"is not null\" expression with default partition" argument_list|, name|ex argument_list|) expr_stmt|; throw|throw operator|new name|MetaException argument_list|( name|ex operator|. name|getMessage argument_list|() argument_list|) throw|; block|} block|} return|return name|expr operator|. name|getExprString argument_list|() return|; block|} annotation|@ name|Override specifier|public name|boolean name|filterPartitionsByExpr parameter_list|( name|List argument_list|< name|FieldSchema argument_list|> name|partColumns parameter_list|, name|byte index|[] name|exprBytes parameter_list|, name|String name|defaultPartitionName parameter_list|, name|List argument_list|< name|String argument_list|> name|partitionNames parameter_list|) throws|throws name|MetaException block|{ name|List argument_list|< name|String argument_list|> name|partColumnNames init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; name|List argument_list|< name|PrimitiveTypeInfo argument_list|> name|partColumnTypeInfos init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; for|for control|( name|FieldSchema name|fs range|: name|partColumns control|) block|{ name|partColumnNames operator|. name|add argument_list|( name|fs operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|partColumnTypeInfos operator|. name|add argument_list|( name|TypeInfoFactory operator|. name|getPrimitiveTypeInfo argument_list|( name|fs operator|. name|getType argument_list|() argument_list|) argument_list|) expr_stmt|; block|} name|ExprNodeGenericFuncDesc name|expr init|= name|deserializeExpr argument_list|( name|exprBytes argument_list|) decl_stmt|; try|try block|{ name|ExprNodeDescUtils operator|. name|replaceEqualDefaultPartition argument_list|( name|expr argument_list|, name|defaultPartitionName argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|SemanticException name|ex parameter_list|) block|{ name|LOG operator|. name|error argument_list|( literal|"Failed to replace default partition" argument_list|, name|ex argument_list|) expr_stmt|; throw|throw operator|new name|MetaException argument_list|( name|ex operator|. name|getMessage argument_list|() argument_list|) throw|; block|} try|try block|{ name|long name|startTime init|= name|System operator|. name|nanoTime argument_list|() decl_stmt|, name|len init|= name|partitionNames operator|. name|size argument_list|() decl_stmt|; name|boolean name|result init|= name|PartitionPruner operator|. name|prunePartitionNames argument_list|( name|partColumnNames argument_list|, name|partColumnTypeInfos argument_list|, name|expr argument_list|, name|defaultPartitionName argument_list|, name|partitionNames argument_list|) decl_stmt|; name|double name|timeMs init|= operator|( name|System operator|. name|nanoTime argument_list|() operator|- name|startTime operator|) operator|/ literal|1000000.0 decl_stmt|; name|LOG operator|. name|debug argument_list|( literal|"Pruning " operator|+ name|len operator|+ literal|" partition names took " operator|+ name|timeMs operator|+ literal|"ms" argument_list|) expr_stmt|; return|return name|result return|; block|} catch|catch parameter_list|( name|HiveException name|ex parameter_list|) block|{ name|LOG operator|. name|error argument_list|( literal|"Failed to apply the expression" argument_list|, name|ex argument_list|) expr_stmt|; throw|throw operator|new name|MetaException argument_list|( name|ex operator|. name|getMessage argument_list|() argument_list|) throw|; block|} block|} specifier|private name|ExprNodeGenericFuncDesc name|deserializeExpr parameter_list|( name|byte index|[] name|exprBytes parameter_list|) throws|throws name|MetaException block|{ name|ExprNodeGenericFuncDesc name|expr init|= literal|null decl_stmt|; try|try block|{ name|expr operator|= name|SerializationUtilities operator|. name|deserializeExpressionFromKryo argument_list|( name|exprBytes argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|ex parameter_list|) block|{ name|LOG operator|. name|error argument_list|( literal|"Failed to deserialize the expression" argument_list|, name|ex argument_list|) expr_stmt|; throw|throw operator|new name|MetaException argument_list|( name|ex operator|. name|getMessage argument_list|() argument_list|) throw|; block|} if|if condition|( name|expr operator|== literal|null condition|) block|{ throw|throw operator|new name|MetaException argument_list|( literal|"Failed to deserialize expression - ExprNodeDesc not present" argument_list|) throw|; block|} return|return name|expr return|; block|} annotation|@ name|Override specifier|public name|FileFormatProxy name|getFileFormatProxy parameter_list|( name|FileMetadataExprType name|type parameter_list|) block|{ switch|switch condition|( name|type condition|) block|{ case|case name|ORC_SARG case|: return|return operator|new name|OrcFileFormatProxy argument_list|() return|; default|default: throw|throw operator|new name|RuntimeException argument_list|( literal|"Unsupported format " operator|+ name|type argument_list|) throw|; block|} block|} annotation|@ name|Override specifier|public name|FileMetadataExprType name|getMetadataType parameter_list|( name|String name|inputFormat parameter_list|) block|{ try|try block|{ name|Class argument_list|< name|? argument_list|> name|ifClass init|= name|Class operator|. name|forName argument_list|( name|inputFormat argument_list|) decl_stmt|; if|if condition|( name|OrcInputFormat operator|. name|class operator|. name|isAssignableFrom argument_list|( name|ifClass argument_list|) condition|) block|{ return|return name|FileMetadataExprType operator|. name|ORC_SARG return|; block|} return|return literal|null return|; block|} catch|catch parameter_list|( name|Throwable name|t parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Can't create the class for input format " operator|+ name|inputFormat argument_list|, name|t argument_list|) expr_stmt|; return|return literal|null return|; block|} block|} annotation|@ name|Override specifier|public name|SearchArgument name|createSarg parameter_list|( name|byte index|[] name|expr parameter_list|) block|{ return|return name|ConvertAstToSearchArg operator|. name|create argument_list|( name|expr argument_list|) return|; block|} block|} end_class end_unit
14.034598
813
0.804851
a40f77e86e35339e33cea46867945ef9762458a4
300
package com.shekhargulati.java8_tutorial.ch02; /** * * Example of compiler unable to detect lambda expression types */ public class Example2_Lambda { public static void main(String[] args) { // Comparator comparator = (first, second) -> first.length() - second.length(); } }
16.666667
86
0.676667
468049a9e07a128073b18969445868dea9fd318e
1,020
package com.sensinggo; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import java.util.Arrays; import java.util.List; import kotlin.Metadata; import kotlin.collections.CollectionsKt; import kotlin.jvm.internal.Intrinsics; import org.jetbrains.annotations.NotNull; public final class sensinggoPackage implements ReactPackage { @NotNull public List createNativeModules(@NotNull ReactApplicationContext reactContext) { Intrinsics.checkParameterIsNotNull(reactContext, "reactContext"); List var10000 = Arrays.asList((NativeModule)(new sensinggoModule(reactContext))); Intrinsics.checkExpressionValueIsNotNull(var10000, "Arrays.asList<NativeModu…nggoModule(reactContext))"); return var10000; } @NotNull public List createViewManagers(@NotNull ReactApplicationContext reactContext) { Intrinsics.checkParameterIsNotNull(reactContext, "reactContext"); return CollectionsKt.emptyList(); } }
35.172414
109
0.812745
c809cad93d20408e52fa9a6f568e4f0e6e663148
5,576
/* * Copyright (C) 2016 Jecelyin Peng <jecelyin@gmail.com> * * This file is part of 920 Text Editor. * * 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.jecelyin.editor2.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.jecelyin.common.widget.CheckableImageView; import com.jecelyin.editor2.Pref; import com.jecelyin.editor2.R; import com.jecelyin.editor2.common.Command; import com.jecelyin.editor2.view.menu.MenuFactory; import com.jecelyin.editor2.view.menu.MenuGroup; import com.jecelyin.editor2.view.menu.MenuItemInfo; import java.util.ArrayList; import java.util.List; /** * @author Jecelyin Peng <jecelyin@gmail.com> */ public class MainMenuAdapter extends RecyclerView.Adapter { private static final int ITEM_TYPE_GROUP = 1; private final List<MenuItemInfo> menuItems; private final LayoutInflater inflater; private MenuItem.OnMenuItemClickListener menuItemClickListener; public MainMenuAdapter(Context context) { inflater = LayoutInflater.from(context); MenuFactory menuFactory = MenuFactory.getInstance(context); MenuGroup[] groups = MenuGroup.values(); menuItems = new ArrayList<MenuItemInfo>(); for (MenuGroup group : groups) { if(group.getNameResId() == 0) continue; //top group menuItems.add(new MenuItemInfo(group, 0, Command.CommandEnum.NONE, 0, 0)); menuItems.addAll(menuFactory.getMenuItemsWithoutToolbarMenu(group)); } } public void setMenuItemClickListener(MenuItem.OnMenuItemClickListener menuItemClickListener) { this.menuItemClickListener = menuItemClickListener; } @Override public int getItemViewType(int position) { return menuItems.get(position).getItemId() == 0 ? ITEM_TYPE_GROUP : super.getItemViewType(position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == ITEM_TYPE_GROUP) { return new GroupViewHolder(inflater.inflate(R.layout.main_menu_group, parent, false)); } else { return new ItemViewHolder(inflater.inflate(R.layout.main_menu_item, parent, false)); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final MenuItemInfo item = menuItems.get(position); if(holder instanceof ItemViewHolder) { final ItemViewHolder vh = (ItemViewHolder)holder; vh.mTextView.setText(item.getTitleResId()); vh.mTextView.setCompoundDrawablesWithIntrinsicBounds(item.getIconResId(), 0, 0, 0); vh.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(menuItemClickListener != null) { menuItemClickListener.onMenuItemClick(item); if(item.getItemId() == R.id.m_readonly) { vh.mCheckBox.setChecked(!vh.mCheckBox.isChecked()); } } } }); if(item.getItemId() == R.id.m_readonly) { vh.mCheckBox.setVisibility(View.VISIBLE); vh.mCheckBox.setChecked(Pref.getInstance(vh.itemView.getContext()).isReadOnly()); } else { vh.mCheckBox.setVisibility(View.GONE); } } else { GroupViewHolder vh = (GroupViewHolder)holder; vh.mNameTextView.setText(item.getGroup().getNameResId()); } } @Override public int getItemCount() { return menuItems == null ? 0 : menuItems.size(); } /** * This class contains all butterknife-injected Views & Layouts from layout file 'main_menu_item.xml' * for easy to all layout elements. * * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast) */ static class ItemViewHolder extends RecyclerView.ViewHolder { TextView mTextView; CheckableImageView mCheckBox; ItemViewHolder(View view) { super(view); mTextView = (TextView) view.findViewById(R.id.textView); mCheckBox = (CheckableImageView) view.findViewById(R.id.checkbox); } } /** * This class contains all butterknife-injected Views & Layouts from layout file 'main_menu_group.xml' * for easy to all layout elements. * * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast) */ static class GroupViewHolder extends RecyclerView.ViewHolder { TextView mNameTextView; GroupViewHolder(View view) { super(view); mNameTextView = (TextView) view.findViewById(R.id.nameTextView); } } }
37.422819
108
0.6684
ea766e38c3a4fa0512babf12261ddbb3a03dfa69
3,968
/* * 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 de.ubleipzig.xslt; import static de.ubleipzig.xslt.MarcXMLWriter.removeUTFCharacters; import static de.ubleipzig.xslt.MarcXMLWriter.writeMarcXMLtoFile; import static java.nio.file.Paths.get; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.params.CursorMarkParams; import org.junit.Test; import org.marc4j.MarcReader; import org.marc4j.MarcStreamReader; import org.marc4j.MarcXmlWriter; import org.marc4j.marc.Record; public class SolrFullRecordTest { private String testResource = "fr-ruhnken.mrc"; @Test public void testGetDocumentFromSolr() throws IOException, SolrServerException { final String urlString = "https://index.ub.uni-leipzig.de/solr/biblio"; final HttpSolrClient solr = new HttpSolrClient.Builder(urlString).build(); final SolrQuery query = new SolrQuery(); query.addSort("id", SolrQuery.ORDER.asc); String cursorMark = CursorMarkParams.CURSOR_MARK_START; boolean done = false; query.set("q", "title:\"[Theologische Sammelhandschrift] - Ms 152\""); query.setRows(50); while (!done) { query.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark); final QueryResponse response = solr.query(query); final String nextCursorMark = response.getNextCursorMark(); for (SolrDocument doc : response.getResults()) { final String fr = (String) doc.getFieldValue("fullrecord"); final String id = (String) doc.getFieldValue("id"); writeMarcXMLtoFile(fr, id); } if (cursorMark.equals(nextCursorMark)) { done = true; } cursorMark = nextCursorMark; } } @Test public void testMarcReaderXmlWriter() throws Exception { final String path = get(".").toAbsolutePath().normalize().toString(); final String abspath = path + "/src/test/resources/marc21/" + testResource; final String content = new String(Files.readAllBytes(Paths.get(abspath))); final StringBuffer sbf = removeUTFCharacters(content); final byte[] bytes = sbf.toString().getBytes(); final InputStream input = new ByteArrayInputStream(bytes); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final MarcXmlWriter writer = new MarcXmlWriter(out, true); final MarcReader reader = new MarcStreamReader(input); while (reader.hasNext()) { final Record record = reader.next(); writer.write(record); } writer.close(); final FileOutputStream fos = new FileOutputStream(new File("/tmp/out_" + testResource)); out.writeTo(fos); final String result = new String(out.toByteArray()); System.out.println(result); //assertXMLEqual(new String(out.toByteArray()), TestUtils.readFileIntoString("/fromsolr // .mrc")); } }
42.212766
96
0.695817
e611f27c55aa5151f3973c5a3750c101b0db6ed9
2,492
package gui; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import classes.Main; /** * Initial menu window when program launches * @author jonpaulsimonelli */ public class MenuWindow extends JFrame { private JPanel mainPanel, playPanel, loadPanel, exitPanel, aboutPanel; private JTextArea textArea; private JButton playButton, loadButton, confirmLoadButton, quitButton, aboutButton; /** * Called when loadButton is pressed */ private void load() { textArea = new JTextArea(); textArea.setSize(500,100); confirmLoadButton = new JButton("OK"); confirmLoadButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { confirmLoad(); } }); loadPanel.add(textArea, BorderLayout.CENTER); loadPanel.add(confirmLoadButton, BorderLayout.EAST); } /** * Called when confirmLoadButton is pressed */ private void confirmLoad() { Main.setQUESTIONS(new File(textArea.getText() + ".txt")); playButton.setVisible(true); } public MenuWindow() { mainPanel = new JPanel(new GridLayout(3,1,100,100)); playPanel = new JPanel(); loadPanel = new JPanel(new GridLayout(1,2,100,100)); exitPanel = new JPanel(); playButton = new JButton("Play"); playButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { Main.playGame(); } }); playButton.setVisible(false); playPanel.add(playButton); loadButton = new JButton("Load"); loadButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { load(); } }); loadPanel.add(loadButton, BorderLayout.WEST); loadPanel.setBounds(new Rectangle(10,20)); textArea = new JTextArea(); loadPanel.add(textArea, BorderLayout.CENTER); quitButton = new JButton("Quit"); quitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { Main.EXIT(); } }); exitPanel.add(quitButton); mainPanel.add(playPanel); mainPanel.add(loadPanel); mainPanel.add(exitPanel); add(mainPanel); setSize(Main.getMENU_DIM()); setTitle(Main.PLAY_TITLE + " Configuation"); setVisible(true); } public static void main(String[] args) { MenuWindow mw = new MenuWindow(); } }
25.690722
86
0.723917
7033241ecf97e7fa0cc645609be111138f333495
1,061
/** * This file was auto-generated by the Titanium Module SDK helper for Android * Appcelerator Titanium Mobile * Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. * */ package ti.animation; import org.appcelerator.kroll.KrollModule; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.titanium.TiApplication; import org.appcelerator.kroll.common.Log; import org.appcelerator.kroll.common.TiConfig; @Kroll.module(name="TiAnimation", id="ti.animation") public class TiAnimationModule extends KrollModule { // Standard Debugging variables private static final String LCAT = "TiAnimationModule"; private static final boolean DBG = TiConfig.LOGD; public TiAnimationModule() { super(); } @Kroll.onAppCreate public static void onAppCreate(TiApplication app) { Log.d(LCAT, "inside onAppCreate"); // put module init code that needs to run when the application is created } }
27.205128
77
0.774741
571d78d0ad166f7b6d6340dcb380b2200f9b1590
5,271
/* * Java * * Copyright 2016-2018 IS2T. All rights reserved. * For demonstration purpose only. * IS2T PROPRIETARY. Use is subject to license terms. */ package com.microej.demo.smarthome; import com.microej.demo.smarthome.page.DashBoardPage; import com.microej.demo.smarthome.page.GraphPage; import com.microej.demo.smarthome.page.InformationPage; import com.microej.demo.smarthome.page.MenuNavigatorPage; import com.microej.demo.smarthome.page.MenuPage; import com.microej.demo.smarthome.page.SmartHomePage; import com.microej.demo.smarthome.style.ClassSelectors; import com.microej.demo.smarthome.style.StylePopulator; import ej.bon.Timer; import ej.bon.TimerTask; import ej.bon.Util; import ej.components.dependencyinjection.ServiceLoaderFactory; import ej.microui.MicroUI; import ej.mwt.Desktop; import ej.mwt.Panel; import ej.widget.container.transition.CircleSplashScreenshotTransitionContainer; import ej.widget.container.transition.SplashScreenshotTransitionContainer; import ej.widget.listener.OnClickListener; import ej.widget.navigation.page.Page; /** * The entry point of smarthome. */ public class Main { private static final int ANIMATION_DURATION = 200; public static final boolean USE_ANIMATION = true; // The time used at boot time (realistic dummy value). private static final long START_TIME = 1467324067060l; private static OnClickListener ON_CLICK_LISTENER; private static SplashScreenshotTransitionContainer TRANSITION_CONTAINER; private static SmartHomePage MAIN_PAGE; private static HomeRobot AUTOMATON; private static Page CURRENT_PAGE; private Main(){ // Avoid instantiation. } /** * Entry point. * * @param args * not used. */ public static void main(final String[] args) { // Sets a default starting time to avoid 0:00. if (System.currentTimeMillis() < START_TIME) { Util.setCurrentTimeMillis(START_TIME); } ServiceLoaderFactory.getServiceLoader().getService(Timer.class, Timer.class).schedule(new TimerTask() { @Override public void run() { Thread.currentThread().setName("MainTimer"); //$NON-NLS-1$ } }, 0); MicroUI.start(); StylePopulator.initializeStylesheet(); MAIN_PAGE = new SmartHomePage(); // Set clicklistener for home button (used in sandboxed). if (ON_CLICK_LISTENER != null) { MAIN_PAGE.addOnClickListener(ON_CLICK_LISTENER); } // Create the main page. TRANSITION_CONTAINER = new CircleSplashScreenshotTransitionContainer(true); TRANSITION_CONTAINER.addClassSelector(ClassSelectors.PICKER); TRANSITION_CONTAINER.setDuration(ANIMATION_DURATION); backToMainPage(); Desktop desktop = new Desktop(); final Panel panel = new Panel(); panel.setWidget(TRANSITION_CONTAINER); panel.showFullScreen(desktop); desktop.show(); // Create and launch the automaton AUTOMATON = new HomeRobot(); AUTOMATON.arm(); } /** * Gets a page using its simple class name from the main page * * @param pageName * the simple class name of the page * * @return the corresponding page */ public static MenuPage getPage(String pageName) { return MAIN_PAGE.getPage(pageName); } /** * Gets the graph page * * @return the graph page */ public static GraphPage getGraphPage() { GraphPage graphPage = null; MenuPage mpDashboard = MAIN_PAGE.getPage(DashBoardPage.class.getName()); if (mpDashboard instanceof MenuNavigatorPage) { MenuNavigatorPage mnpDashboard = (MenuNavigatorPage) mpDashboard; MenuPage page = mnpDashboard.getPage(GraphPage.class.getName()); if (page instanceof GraphPage) { graphPage = (GraphPage) page; } } return graphPage; } /** * Gets the information page * * @return the information page */ public static InformationPage getInformationPage() { InformationPage informationPage = null; MenuPage mpDashboard = MAIN_PAGE.getPage(DashBoardPage.class.getName()); if (mpDashboard instanceof MenuNavigatorPage) { MenuNavigatorPage mnpDashboard = (MenuNavigatorPage) mpDashboard; MenuPage page = mnpDashboard.getPage(InformationPage.class.getName()); if (page instanceof InformationPage) { informationPage = (InformationPage) page; } } return informationPage; } /** * Sets the onClickListener for the store button. It needs to be set before the main is called. * * @param onClickListener * the onClickListener to set. */ public static void setOnClickListener(final OnClickListener onClickListener) { Main.ON_CLICK_LISTENER = onClickListener; } /** * Stop the robot and its timer. */ public static void stopRobot() { AUTOMATON.stop(); } /** * Go back to the main page. */ public static void backToMainPage() { CURRENT_PAGE = MAIN_PAGE; TRANSITION_CONTAINER.show(MAIN_PAGE, false); } public static Page getCurrentPage() { Page page = CURRENT_PAGE; if(page == MAIN_PAGE){ return MAIN_PAGE.getCurrentPage(); } return page; } public static MenuPage getDisplayedPage() { return MAIN_PAGE.getCurrentPage(); } public static void SetAnchor(int sourceX, int sourceY) { TRANSITION_CONTAINER.setAnchor(sourceX, sourceY); } public static void Show(Page page, boolean forward) { CURRENT_PAGE = page; TRANSITION_CONTAINER.show(page, forward); } }
26.355
105
0.743312
84fcf624f64e0754614693902d1122c367668f1c
7,020
/* * Copyright (c) 2014, Thoughtworks Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. */ package org.clintonhealthaccess.lmis.app.activities; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.inject.Inject; import org.clintonhealthaccess.lmis.app.R; import org.clintonhealthaccess.lmis.app.models.User; import org.clintonhealthaccess.lmis.app.services.AlertsService; import org.clintonhealthaccess.lmis.app.services.CommodityActionService; import org.clintonhealthaccess.lmis.app.services.CommodityService; import org.clintonhealthaccess.lmis.app.services.OrderService; import org.clintonhealthaccess.lmis.app.services.StockService; import org.clintonhealthaccess.lmis.app.services.UserService; import org.clintonhealthaccess.lmis.app.sms.SmsSyncService; import java.io.Serializable; import roboguice.inject.InjectResource; import roboguice.inject.InjectView; import static android.view.View.OnClickListener; import static android.widget.Toast.LENGTH_SHORT; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.clintonhealthaccess.lmis.app.R.id; import static org.clintonhealthaccess.lmis.app.R.layout; public class RegisterActivity extends OrmLiteActivity implements Serializable { @Inject private UserService userService; @Inject private CommodityService commodityService; @Inject private StockService stockService; @Inject private OrderService orderService; @Inject private SmsSyncService smsSyncService; @Inject private CommodityActionService commodityActionService; @Inject private AlertsService alertsService; @InjectView(id.textUsername) private TextView textUsername; @InjectView(id.textPassword) private TextView textPassword; @InjectResource(R.string.registration_successful_message) private String registrationSuccessfulMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(layout.activity_register); getSupportActionBar().setDisplayUseLogoEnabled(false); Button registerButton = (Button) findViewById(id.buttonRegister); registerButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { validateAndRegister(); } }); } private void validateAndRegister() { String username = textUsername.getText().toString(); String password = textPassword.getText().toString(); if (isBlank(username)) { textUsername.setError(getString(R.string.username_error)); return; } if (isBlank(password)) { textPassword.setError(getString(R.string.password_error)); return; } doRegister(username, password); } protected void doRegister(final String username, final String password) { AsyncTask<Void, Void, Boolean> registerTask = new RegisterTask(username, password); registerTask.execute(); } private class RegisterTask extends AsyncTask<Void, Void, Boolean> { private final String username; private final String password; private Exception failureCause; private ProgressDialog dialog; public RegisterTask(String username, String password) { this.username = username; this.password = password; } @Override protected void onPreExecute() { super.onPreExecute(); this.dialog = new ProgressDialog(RegisterActivity.this); this.dialog.setMessage("Registering..."); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); this.dialog.show(); } @Override protected Boolean doInBackground(Void... params) { User user; try { user = userService.register(username, password); Log.i("Inital sync:", "initializing"); commodityService.initialise(user); Log.i("Inital sync:", "<========== syncing Order Reasons"); orderService.syncOrderReasons(); Log.i("Inital sync:", "<========== syncing Order Types"); orderService.syncOrderTypes(); smsSyncService.syncGatewayNumber(); alertsService.updateLowStockAlerts(); } catch (Exception e) { this.failureCause = e; //Log.e("Registration Error", e.getLocalizedMessage()); e.printStackTrace(); return false; } return true; } @Override protected void onPostExecute(Boolean succeeded) { if (dialog.isShowing()) { dialog.dismiss(); } if (succeeded) { startActivity(new Intent(getApplicationContext(), HomeActivity.class)); finish(); } String toastMessage = succeeded ? registrationSuccessfulMessage : failureCause.getMessage(); Toast.makeText(getApplicationContext(), toastMessage, LENGTH_SHORT).show(); Log.e("Registration", toastMessage+" "); } } }
36.947368
104
0.691595
d408fd9705611180b7e0fc95bdbe8d1754ad168a
844
package com.gigya.android.sdk.api; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.gigya.android.sdk.network.adapter.RestAdapter; public class GigyaApiHttpRequest { private RestAdapter.HttpMethod httpMethod; private String url; private String encodedParams; GigyaApiHttpRequest( @NonNull RestAdapter.HttpMethod httpMethod, @NonNull String url, @Nullable String encodedParams) { this.httpMethod = httpMethod; this.url = url; this.encodedParams = encodedParams; } @NonNull public RestAdapter.HttpMethod getHttpMethod() { return httpMethod; } @NonNull public String getUrl() { return url; } @Nullable public String getEncodedParams() { return encodedParams; } }
21.641026
57
0.670616
36200341ab36a7ceb9725b12e1fbf5c8af5a1a2f
98
GlobalConfiguration globalConfig = new GlobalConfigurationBuilder() .jmx().enable() .build();
24.5
67
0.755102
3c89accacfa0a9832d397fb7f7f331aaa18c5bc0
1,285
package charactermanaj.util; import java.util.AbstractList; import java.util.Arrays; /** * 関連もしくは類似するリソースをまとめて取り扱うためにグループ化するためのクラス.<br> * * @author seraphy */ public class ResourceNames extends AbstractList<String> { private final String[] resourceNames; public ResourceNames(String[] resourceNames) { if (resourceNames == null) { throw new IllegalArgumentException(); } this.resourceNames = resourceNames; } /** * 順次を逆転させた新しいインスタンスを返す * * @return 順序を逆転させたインスタンス */ public ResourceNames reverse() { int len = resourceNames.length; String[] tmp = new String[len]; for (int idx = 0; idx < len; idx++) { tmp[len - idx - 1] = resourceNames[idx]; } return new ResourceNames(tmp); } @Override public int hashCode() { return Arrays.hashCode(resourceNames); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj instanceof ResourceNames) { ResourceNames o = (ResourceNames) obj; return Arrays.equals(resourceNames, o.resourceNames); } return false; } @Override public int size() { return resourceNames.length; } @Override public String get(int index) { return resourceNames[index]; } }
20.396825
58
0.654475
a7a707ffd17f88b0ef8e8195b8deee808170582c
822
package polys; import cellsociety_team13.Shape; /** * Class which creates a Triangle Shape that is pointing downwards, extension of Shape * @author Miguel Anderson (mra21), Andres Lebbos (afl13) */ public class Triangle_Down extends Triangle{ public static final double startingAngle = 30; /** * Constructor which makes a normal, unscaled triangle that is pointed downwards */ public Triangle_Down() { super(startingAngle); } /** * Returns a triangle that is facing upwards. This is to be used when creating a grid of * alternating upwards and downwards pointing triangles. * @return upwards triangle */ @Override public Shape changeNext() { return new Triangle_Up(); } @Override public int getType() { return 4; } @Override public Shape copy() { return new Triangle_Down(); } }
21.076923
89
0.722628
20b9e3871690928e1523805b2b04fd4722ef187c
5,594
package com.androidhuman.example.simplegithub.ui.signin; import com.androidhuman.example.simplegithub.BuildConfig; import com.androidhuman.example.simplegithub.R; import com.androidhuman.example.simplegithub.api.AuthApi; import com.androidhuman.example.simplegithub.api.GithubApiProvider; import com.androidhuman.example.simplegithub.api.model.GithubAccessToken; import com.androidhuman.example.simplegithub.data.AuthTokenProvider; import com.androidhuman.example.simplegithub.ui.main.MainActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.customtabs.CustomTabsIntent; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SignInActivity extends AppCompatActivity { Button btnStart; ProgressBar progress; AuthApi api; AuthTokenProvider authTokenProvider; Call<GithubAccessToken> accessTokenCall; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); btnStart = findViewById(R.id.btnActivitySignInStart); progress = findViewById(R.id.pbActivitySignIn); /* * 1. 버튼 클릭. * 버튼 초기화 과정. * 버튼을 누르면 Github 사용자 인증 웹페이지로 이동하게된다. * 웹페이지 주소는 Github 애플리케이션의 Client ID를 넣어준다. * 웹피이지는 크롬 커스텀 탭을 사용하여 표시한다. */ btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Uri authUri = new Uri.Builder().scheme("https").authority("github.com") .appendPath("login") .appendPath("oauth") .appendPath("authorize") .appendQueryParameter("client_id", BuildConfig.GITHUB_CLIENT_ID) .build(); CustomTabsIntent intent = new CustomTabsIntent.Builder().build(); intent.launchUrl(SignInActivity.this, authUri); } }); /* * authTokenProvider 를 사용하여 사용자 인증 토큰이 있는지 여부를 확인하고, * 만약 인증 토큰이 있다면 메인 액티비티로 이동한다. */ api = GithubApiProvider.provideAuthApi(); authTokenProvider = new AuthTokenProvider(this); if (null != authTokenProvider.getToken()) { launchMainActivity(); } } /* * 2. 액세스 토큰 요청 * 버튼을 눌러 웹페이지에서 사용자 인증이 완료되면 * simplegithub://authrize?code={액세스 토큰 교환용 코드} 형태의 주소로 페이지가 리디렉션됩니다. * 이때 SignInActivity 가 이 형태의 주소를 열 수 있도록 매니페스트에 선언했으므로 SignInActivity 가 열리며, * 액티비티가 열리는 시점에 SignInActivity 가 화면에 표시되고 있는 상태이므로 onCreate() 콜백 대신 * onNewIntent() 콜백이 호출됩니다. * 이때, 인텐트 내 data 필드에는 이 액티비티를 호출하기 위해 사용한 주소가 들어 있으며, * 이 주소에는 액세스 토큰과 교환할 수 있는 코드가 쿼리 매개변수(query parameter) 형태로 포함되어 있습니다. * 따라서 코드를 주소에서 추출하여 액세스 토큰을 요청합니다. */ @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); showProgress(); Uri uri = intent.getData(); if (null == uri) { throw new IllegalArgumentException("No data exists"); } String code = uri.getQueryParameter("code"); if (null == code) { throw new IllegalStateException("No code exists"); } getAccessToken(code); } /* * 3. 액세스 토큰 추출 * 액세스 토큰은 REST API 를 사용하여 발급받으며, Github 애플리케이션의 Client ID 와 Client Secret, * 그리고 앞에서 사용자 인증이 완료된 후 받은 코드를 함께 전달합니다. * 액세스 토큰을 정상적으로 발급받았다면 이후 이를 계속 사용할 수 있도록 저장한 후 메인 액티비티로 이동합니다. */ private void getAccessToken(@NonNull String code) { showProgress(); accessTokenCall = api.getAccessToken( BuildConfig.GITHUB_CLIENT_ID, BuildConfig.GITHUB_CLIENT_SECRET, code); accessTokenCall.enqueue(new Callback<GithubAccessToken>() { @Override public void onResponse(Call<GithubAccessToken> call, Response<GithubAccessToken> response) { hideProgress(); GithubAccessToken token = response.body(); if (response.isSuccessful() && null != token) { authTokenProvider.updateToken(token.accessToken); launchMainActivity(); } else { showError(new IllegalStateException( "Not successful: " + response.message())); } } @Override public void onFailure(Call<GithubAccessToken> call, Throwable t) { hideProgress(); showError(t); } }); } private void showProgress() { btnStart.setVisibility(View.GONE); progress.setVisibility(View.VISIBLE); } private void hideProgress() { btnStart.setVisibility(View.VISIBLE); progress.setVisibility(View.GONE); } private void showError(Throwable throwable) { Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); } private void launchMainActivity() { startActivity(new Intent( SignInActivity.this, MainActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } }
33.100592
88
0.630497
c40c4439d93d9daeb7900432bce31293acf54b32
6,531
package com.example.handler; import java.util.HashMap; import java.util.Map; import com.example.handler.utils.AuthHandlerUtil; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.MessageContext; import org.apache.synapse.core.axis2.Axis2MessageContext; import org.apache.synapse.core.axis2.Axis2Sender; import org.apache.synapse.rest.Handler; import org.wso2.micro.integrator.security.user.api.UserStoreException; import com.google.gson.Gson; /** * @author janaka */ public class APIAuthHandler implements Handler { private static final Log LOG = LogFactory.getLog(APIAuthHandler.class); private String userName; private String password; private String domain; private String[] allowedRoles; public void addProperty(String arg0, Object arg1) { // TODO Auto-generated method stub } public Map getProperties() { // TODO Auto-generated method stub return null; } /** * Set roles Get the property set in the ESB handler with the name 'roles' * * @param roles comma separated list of roles */ public void setRoles(String roles) { if (roles != null) { this.allowedRoles = roles.split(","); } } /** * Set domain Get the property set in the ESB handler with the name 'domain' * * @param domain * user store domain */ public void setDomain(String domain) { this.domain = domain; } /** * Handle the request * Process the basicAuth header and retrieve credentials * Expose the user name to security context */ public boolean handleRequest(MessageContext messageContext) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); Object headers = axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); ConfigurationContext axis2ConfigurationContext = axis2MessageContext.getConfigurationContext(); int tenantId = -1234; LOG.debug("Rest API APIAuthHandler tenant: " + tenantId); boolean isSuccessful = false; if ( headers instanceof Map) { Map headersMap = (Map) headers; String authHeader = (String) headersMap.get(AuthHandlerConstants.AUTHORIZATION); AuthHandlerUtil authHandlerUtil = new AuthHandlerUtil(); if ((!StringUtils.isEmpty(authHeader) ) && authHandlerUtil.getSecurityScheme(authHeader).equals(AuthHandlerConstants.BASIC_SEC_SCHEME)) { String credentials = authHandlerUtil.getCredentialString(authHeader); if (credentials != null) { credentials = credentials.trim(); try { isSuccessful = processSecurity(credentials, tenantId); if (isSuccessful) { // expose security context to messageContext AuthHandlerUtil authUtil = new AuthHandlerUtil(); AuthHandlerUtil.Credential cred = authUtil.getDecodedCredentials(credentials); Map<String, Object> secContextMap = new HashMap<String, Object>(); secContextMap.put(AuthHandlerConstants.ISSUER, cred.getUserName()); secContextMap.put(AuthHandlerConstants.CLAIMS, new HashMap<String, Object>()); Gson gson = new Gson(); String secContext = gson.toJson(secContextMap); messageContext.setProperty(AuthHandlerConstants.SEC_CONTEXT,secContext); LOG.debug("User with username : " + userName + " authenticated successfully"); } else { headersMap.clear(); axis2MessageContext.setProperty(AuthHandlerConstants.HTTP_SC,AuthHandlerConstants.FORBIDDEN_CODE); axis2MessageContext.setProperty(AuthHandlerConstants.NO_ENTITY_BODY, true); messageContext.setProperty(AuthHandlerConstants.RESPONSE, "true"); messageContext.setTo(null); Axis2Sender.sendBack(messageContext); } } catch (UserStoreException e) { LOG.error("Unable to execute the authentication process : ",e); } catch (Exception e) { LOG.error("Unable to execute the authentication process : ",e); } } } else { LOG.info("Security headers not present and Unable to complete the authentication process "); } } return isSuccessful; } public boolean handleResponse(MessageContext arg0) { // TODO Auto-generated method stub return true; } /** * Process the details in authorization header to validate the user * * @param credentials * username and password sent in the header * @param tenantId * tenantID * @return if the user is valid or not * * @throws UserStoreException throwing UserStoreException */ public boolean processSecurity(String credentials, int tenantId) throws UserStoreException { boolean isAllowed = false; String decodedCredentials; if (credentials != null) { decodedCredentials = new String(new Base64().decode(credentials.getBytes())); userName = decodedCredentials.split(":")[0]; password = decodedCredentials.split(":")[1]; } if (userName != null && password != null && allowedRoles != null) { UserValidationManager userValidationManager = new UserValidationManager(); isAllowed = userValidationManager.validateUser(domain, userName, password, allowedRoles, tenantId); } else { LOG.debug("Username or password not provided"); } if (!isAllowed) { LOG.info("Unable to authenticate the user with the UserName : " + userName); } return isAllowed; } }
39.107784
134
0.613995
d82516ba0549464d732cb1a579dd49f4724af729
394
package com.fx.client.gui.uicomponents.main.components; import io.datafx.controller.ViewController; import javax.annotation.PostConstruct; /** * @description: * @className: UserInfoController * @author: liwen * @date: 2020/8/16 10:52 */ @ViewController("/fxml/main/components/skin_info.fxml") public class SkinInfoController { @PostConstruct private void init() { } }
15.76
55
0.72335
d085575f17b839b07b1c68ebbbcf0b92b7b35153
934
package nl.pc.service.filter.field; import nl.pc.model.mongodb.RootEntity; import org.mongodb.morphia.query.Query; import java.util.function.Function; /** * Checks if a field contains a value * @param <ENTITY> */ public abstract class ContainsFilter<ENTITY extends RootEntity> extends SingleFieldFilter<ENTITY, String> { private final boolean ignoreCase; public ContainsFilter(String value, String fieldName, boolean ignoreCase) { super(value, fieldName); this.ignoreCase = ignoreCase; } @Override public boolean shouldApply() { return super.shouldApply() && !getValue().isEmpty(); } @Override public Function<Query<ENTITY>, Query<ENTITY>> addFilterToQuery() { return (query) -> ignoreCase ? query.field(getFieldName()).containsIgnoreCase(getValue()) : query.field(getFieldName()).contains(getValue()); } }
26.685714
107
0.670236
1feecadc00f630606d48f479ff7b8bb9699c7622
8,404
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.amap.api.mapcore.util; import javax.microedition.khronos.egl.*; // Referenced classes of package com.amap.api.mapcore.util: // m class m$b extends m$a { private int a(EGL10 egl10, EGLDisplay egldisplay, EGLConfig eglconfig, int k, int l) { if(egl10.eglGetConfigAttrib(egldisplay, eglconfig, k, j)) //* 0 0:aload_1 //* 1 1:aload_2 //* 2 2:aload_3 //* 3 3:iload 4 //* 4 5:aload_0 //* 5 6:getfield #27 <Field int[] j> //* 6 9:invokeinterface #48 <Method boolean EGL10.eglGetConfigAttrib(EGLDisplay, EGLConfig, int, int[])> //* 7 14:ifeq 24 return j[0]; // 8 17:aload_0 // 9 18:getfield #27 <Field int[] j> // 10 21:iconst_0 // 11 22:iaload // 12 23:ireturn else return l; // 13 24:iload 5 // 14 26:ireturn } public EGLConfig a(EGL10 egl10, EGLDisplay egldisplay, EGLConfig aeglconfig[]) { int l = aeglconfig.length; // 0 0:aload_3 // 1 1:arraylength // 2 2:istore 5 for(int k = 0; k < l; k++) //* 3 4:iconst_0 //* 4 5:istore 4 //* 5 7:iload 4 //* 6 9:iload 5 //* 7 11:icmpge 170 { EGLConfig eglconfig = aeglconfig[k]; // 8 14:aload_3 // 9 15:iload 4 // 10 17:aaload // 11 18:astore 10 int i1 = a(egl10, egldisplay, eglconfig, 12325, 0); // 12 20:aload_0 // 13 21:aload_1 // 14 22:aload_2 // 15 23:aload 10 // 16 25:sipush 12325 // 17 28:iconst_0 // 18 29:invokespecial #51 <Method int a(EGL10, EGLDisplay, EGLConfig, int, int)> // 19 32:istore 6 int j1 = a(egl10, egldisplay, eglconfig, 12326, 0); // 20 34:aload_0 // 21 35:aload_1 // 22 36:aload_2 // 23 37:aload 10 // 24 39:sipush 12326 // 25 42:iconst_0 // 26 43:invokespecial #51 <Method int a(EGL10, EGLDisplay, EGLConfig, int, int)> // 27 46:istore 7 if(i1 < g || j1 < h) continue; // 28 48:iload 6 // 29 50:aload_0 // 30 51:getfield #37 <Field int g> // 31 54:icmplt 161 // 32 57:iload 7 // 33 59:aload_0 // 34 60:getfield #39 <Field int h> // 35 63:icmplt 161 i1 = a(egl10, egldisplay, eglconfig, 12324, 0); // 36 66:aload_0 // 37 67:aload_1 // 38 68:aload_2 // 39 69:aload 10 // 40 71:sipush 12324 // 41 74:iconst_0 // 42 75:invokespecial #51 <Method int a(EGL10, EGLDisplay, EGLConfig, int, int)> // 43 78:istore 6 j1 = a(egl10, egldisplay, eglconfig, 12323, 0); // 44 80:aload_0 // 45 81:aload_1 // 46 82:aload_2 // 47 83:aload 10 // 48 85:sipush 12323 // 49 88:iconst_0 // 50 89:invokespecial #51 <Method int a(EGL10, EGLDisplay, EGLConfig, int, int)> // 51 92:istore 7 int k1 = a(egl10, egldisplay, eglconfig, 12322, 0); // 52 94:aload_0 // 53 95:aload_1 // 54 96:aload_2 // 55 97:aload 10 // 56 99:sipush 12322 // 57 102:iconst_0 // 58 103:invokespecial #51 <Method int a(EGL10, EGLDisplay, EGLConfig, int, int)> // 59 106:istore 8 int l1 = a(egl10, egldisplay, eglconfig, 12321, 0); // 60 108:aload_0 // 61 109:aload_1 // 62 110:aload_2 // 63 111:aload 10 // 64 113:sipush 12321 // 65 116:iconst_0 // 66 117:invokespecial #51 <Method int a(EGL10, EGLDisplay, EGLConfig, int, int)> // 67 120:istore 9 if(i1 == c && j1 == d && k1 == e && l1 == f) //* 68 122:iload 6 //* 69 124:aload_0 //* 70 125:getfield #29 <Field int c> //* 71 128:icmpne 161 //* 72 131:iload 7 //* 73 133:aload_0 //* 74 134:getfield #31 <Field int d> //* 75 137:icmpne 161 //* 76 140:iload 8 //* 77 142:aload_0 //* 78 143:getfield #33 <Field int e> //* 79 146:icmpne 161 //* 80 149:iload 9 //* 81 151:aload_0 //* 82 152:getfield #35 <Field int f> //* 83 155:icmpne 161 return eglconfig; // 84 158:aload 10 // 85 160:areturn } // 86 161:iload 4 // 87 163:iconst_1 // 88 164:iadd // 89 165:istore 4 //* 90 167:goto 7 return null; // 91 170:aconst_null // 92 171:areturn } protected int c; protected int d; protected int e; protected int f; protected int g; protected int h; final m i; private int j[]; public m$b(m m1, int k, int l, int i1, int j1, int k1, int l1) { i = m1; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #22 <Field m i> super(m1, new int[] { 12324, k, 12323, l, 12322, i1, 12321, j1, 12325, k1, 12326, l1, 12344 }); // 3 5:aload_0 // 4 6:aload_1 // 5 7:bipush 13 // 6 9:newarray int[] // 7 11:dup // 8 12:iconst_0 // 9 13:sipush 12324 // 10 16:iastore // 11 17:dup // 12 18:iconst_1 // 13 19:iload_2 // 14 20:iastore // 15 21:dup // 16 22:iconst_2 // 17 23:sipush 12323 // 18 26:iastore // 19 27:dup // 20 28:iconst_3 // 21 29:iload_3 // 22 30:iastore // 23 31:dup // 24 32:iconst_4 // 25 33:sipush 12322 // 26 36:iastore // 27 37:dup // 28 38:iconst_5 // 29 39:iload 4 // 30 41:iastore // 31 42:dup // 32 43:bipush 6 // 33 45:sipush 12321 // 34 48:iastore // 35 49:dup // 36 50:bipush 7 // 37 52:iload 5 // 38 54:iastore // 39 55:dup // 40 56:bipush 8 // 41 58:sipush 12325 // 42 61:iastore // 43 62:dup // 44 63:bipush 9 // 45 65:iload 6 // 46 67:iastore // 47 68:dup // 48 69:bipush 10 // 49 71:sipush 12326 // 50 74:iastore // 51 75:dup // 52 76:bipush 11 // 53 78:iload 7 // 54 80:iastore // 55 81:dup // 56 82:bipush 12 // 57 84:sipush 12344 // 58 87:iastore // 59 88:invokespecial #25 <Method void m$a(m, int[])> j = new int[1]; // 60 91:aload_0 // 61 92:iconst_1 // 62 93:newarray int[] // 63 95:putfield #27 <Field int[] j> c = k; // 64 98:aload_0 // 65 99:iload_2 // 66 100:putfield #29 <Field int c> d = l; // 67 103:aload_0 // 68 104:iload_3 // 69 105:putfield #31 <Field int d> e = i1; // 70 108:aload_0 // 71 109:iload 4 // 72 111:putfield #33 <Field int e> f = j1; // 73 114:aload_0 // 74 115:iload 5 // 75 117:putfield #35 <Field int f> g = k1; // 76 120:aload_0 // 77 121:iload 6 // 78 123:putfield #37 <Field int g> h = l1; // 79 126:aload_0 // 80 127:iload 7 // 81 129:putfield #39 <Field int h> // 82 132:return } }
32.323077
111
0.43872
87a68a7bf9d045a49de2e9c6a33af878a9318b89
2,595
package com.akavrt.csp.enumerator; import com.akavrt.csp.Order; import com.akavrt.csp.Problem; /** * <p>Pattern enumerator based on algorithm proposed by Pierce (1964). Can be used to evaluate the * number of both effective and feasible patterns for a particular 1D-CSP.</p> * * @author Victor Balabanov <akavrt@gmail.com> */ public class Enumerator { private final long stockLength; private final long[] lengths; private final long[] demands; private final long[] cuts; private final long minOrderLength; private long effectiveCounter; private long feasibleCounter; public Enumerator(Problem problem) { stockLength = problem.getStockLength(); problem.prepare(); lengths = new long[problem.size()]; demands = new long[problem.size()]; for (int i = 0; i < problem.size(); i++) { Order order = problem.getOrder(i); lengths[i] = order.getLength(); demands[i] = order.getDemand(); } minOrderLength = lengths[lengths.length - 1]; cuts = new long[problem.size()]; } /** * <p>Pierce used term 'dominating processes' to denote the set of effective patterns.</p> * * @return number of effective patterns. */ public long getEffectivePatternsCount() { return effectiveCounter; } /** * <p>Pierce used term 'exhaustive processes' to denote the set of feasible patterns.</p> * * @return number of feasible patterns. */ public long getFeasiblePatternsCount() { return feasibleCounter; } /** * <p>Enumerates patterns in sequential manner using algorithm proposed by Pierce (1964).</p> */ public void enumerate() { effectiveCounter = 0; feasibleCounter = 0; int j = -1; do { if (j >= 0) { cuts[j]--; } long unused = stockLength; int k = -1; for (int i = 0; i < cuts.length; i++) { if (i > j) { long upperBound = unused / lengths[i]; cuts[i] = Math.min(upperBound, demands[i]); } unused -= cuts[i] * lengths[i]; if (cuts[i] > 0) { k = i; } } j = k; if (unused < stockLength) { feasibleCounter++; if (unused < minOrderLength) { effectiveCounter++; } } } while (j >= 0); } }
26.479592
98
0.533719
0473cc758bcfe1a59c3ccfc4f8e4d1ddfe171113
2,226
package org.xmlactions.action.actions; import org.apache.bsf.BSFException; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.lang.text.StrSubstitutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmlactions.action.config.IExecContext; import org.xmlactions.common.scripting.Scripting; import org.xmlactions.common.text.ReplaceMarkers; public class ActionUtils { private static final Logger log = LoggerFactory.getLogger(ActionUtils.class); public static String evaluateCalculation(IExecContext execContext, String exp) throws BSFException { String script = null; script = convertExpressionAmps(StrSubstitutor.replace(exp, execContext)); // log.debug("expression:" + exp + " script:" + script); Object result = Scripting.getInstance().evaluate(script); return ConvertUtils.convert(result, Integer.class).toString(); } /** * Evaluates a JavaScript expression. * * @param execContext * @param exp * @return true of expression evaluates to true or false if expression * evaluates to false or has an expression exception */ public static boolean evaluateExpression(IExecContext execContext, String exp) { // first replace any markers exp = execContext.replace(exp); String script = null; try { //script = convertExpressionAmps(execContext.replace(exp)); script = convertExpressionAmps(ReplaceMarkers.replace(exp, execContext)); if (log.isDebugEnabled()) { log.debug("expression:" + exp + " script:" + script); } Object result = Scripting.getInstance().evaluate(script); if (result instanceof Boolean) return ((Boolean) result).booleanValue(); else return new Boolean((String) result).booleanValue(); } catch (BSFException ex) { throw new IllegalArgumentException(ex.getMessage(), ex); } catch (Exception ex) { log.error(ex.getMessage() + "\nin script:" + script); } return false; } public static String convertExpressionAmps(String in) { in = in.replaceAll("&lt;", "<"); // log.debug("in:" + in); in = in.replaceAll("&gt;", ">"); // log.debug("in:" + in); in = in.replaceAll("&amp;", "&"); // log.debug("in:" + in); return in; } }
30.081081
99
0.704852
b7ef082fa2ec71d73add5293fc06cc5a2dd11251
33
public class TDCoSimHelics { }
6.6
28
0.727273
5af16bdc57f9258d42140d8969f6096fe5677e87
10,059
// Automatically generated by xdrgen // DO NOT EDIT or your changes may be overwritten package org.stellar.sdk.xdr; import java.io.IOException; import com.google.common.base.Objects; import java.util.Arrays; // === xdr source ============================================================ // struct InnerTransactionResult // { // // Always 0. Here for binary compatibility. // int64 feeCharged; // // union switch (TransactionResultCode code) // { // // txFEE_BUMP_INNER_SUCCESS is not included // case txSUCCESS: // case txFAILED: // OperationResult results<>; // case txTOO_EARLY: // case txTOO_LATE: // case txMISSING_OPERATION: // case txBAD_SEQ: // case txBAD_AUTH: // case txINSUFFICIENT_BALANCE: // case txNO_ACCOUNT: // case txINSUFFICIENT_FEE: // case txBAD_AUTH_EXTRA: // case txINTERNAL_ERROR: // case txNOT_SUPPORTED: // // txFEE_BUMP_INNER_FAILED is not included // case txBAD_SPONSORSHIP: // case txBAD_MIN_SEQ_AGE_OR_GAP: // case txMALFORMED: // void; // } // result; // // // reserved for future use // union switch (int v) // { // case 0: // void; // } // ext; // }; // =========================================================================== public class InnerTransactionResult implements XdrElement { public InnerTransactionResult () {} private Int64 feeCharged; public Int64 getFeeCharged() { return this.feeCharged; } public void setFeeCharged(Int64 value) { this.feeCharged = value; } private InnerTransactionResultResult result; public InnerTransactionResultResult getResult() { return this.result; } public void setResult(InnerTransactionResultResult value) { this.result = value; } private InnerTransactionResultExt ext; public InnerTransactionResultExt getExt() { return this.ext; } public void setExt(InnerTransactionResultExt value) { this.ext = value; } public static void encode(XdrDataOutputStream stream, InnerTransactionResult encodedInnerTransactionResult) throws IOException{ Int64.encode(stream, encodedInnerTransactionResult.feeCharged); InnerTransactionResultResult.encode(stream, encodedInnerTransactionResult.result); InnerTransactionResultExt.encode(stream, encodedInnerTransactionResult.ext); } public void encode(XdrDataOutputStream stream) throws IOException { encode(stream, this); } public static InnerTransactionResult decode(XdrDataInputStream stream) throws IOException { InnerTransactionResult decodedInnerTransactionResult = new InnerTransactionResult(); decodedInnerTransactionResult.feeCharged = Int64.decode(stream); decodedInnerTransactionResult.result = InnerTransactionResultResult.decode(stream); decodedInnerTransactionResult.ext = InnerTransactionResultExt.decode(stream); return decodedInnerTransactionResult; } @Override public int hashCode() { return Objects.hashCode(this.feeCharged, this.result, this.ext); } @Override public boolean equals(Object object) { if (!(object instanceof InnerTransactionResult)) { return false; } InnerTransactionResult other = (InnerTransactionResult) object; return Objects.equal(this.feeCharged, other.feeCharged) && Objects.equal(this.result, other.result) && Objects.equal(this.ext, other.ext); } public static final class Builder { private Int64 feeCharged; private InnerTransactionResultResult result; private InnerTransactionResultExt ext; public Builder feeCharged(Int64 feeCharged) { this.feeCharged = feeCharged; return this; } public Builder result(InnerTransactionResultResult result) { this.result = result; return this; } public Builder ext(InnerTransactionResultExt ext) { this.ext = ext; return this; } public InnerTransactionResult build() { InnerTransactionResult val = new InnerTransactionResult(); val.setFeeCharged(feeCharged); val.setResult(result); val.setExt(ext); return val; } } public static class InnerTransactionResultResult { public InnerTransactionResultResult () {} TransactionResultCode code; public TransactionResultCode getDiscriminant() { return this.code; } public void setDiscriminant(TransactionResultCode value) { this.code = value; } private OperationResult[] results; public OperationResult[] getResults() { return this.results; } public void setResults(OperationResult[] value) { this.results = value; } public static final class Builder { private TransactionResultCode discriminant; private OperationResult[] results; public Builder discriminant(TransactionResultCode discriminant) { this.discriminant = discriminant; return this; } public Builder results(OperationResult[] results) { this.results = results; return this; } public InnerTransactionResultResult build() { InnerTransactionResultResult val = new InnerTransactionResultResult(); val.setDiscriminant(discriminant); val.setResults(results); return val; } } public static void encode(XdrDataOutputStream stream, InnerTransactionResultResult encodedInnerTransactionResultResult) throws IOException { //Xdrgen::AST::Identifier //TransactionResultCode stream.writeInt(encodedInnerTransactionResultResult.getDiscriminant().getValue()); switch (encodedInnerTransactionResultResult.getDiscriminant()) { case txSUCCESS: case txFAILED: int resultssize = encodedInnerTransactionResultResult.getResults().length; stream.writeInt(resultssize); for (int i = 0; i < resultssize; i++) { OperationResult.encode(stream, encodedInnerTransactionResultResult.results[i]); } break; case txTOO_EARLY: case txTOO_LATE: case txMISSING_OPERATION: case txBAD_SEQ: case txBAD_AUTH: case txINSUFFICIENT_BALANCE: case txNO_ACCOUNT: case txINSUFFICIENT_FEE: case txBAD_AUTH_EXTRA: case txINTERNAL_ERROR: case txNOT_SUPPORTED: case txBAD_SPONSORSHIP: case txBAD_MIN_SEQ_AGE_OR_GAP: case txMALFORMED: break; } } public void encode(XdrDataOutputStream stream) throws IOException { encode(stream, this); } public static InnerTransactionResultResult decode(XdrDataInputStream stream) throws IOException { InnerTransactionResultResult decodedInnerTransactionResultResult = new InnerTransactionResultResult(); TransactionResultCode discriminant = TransactionResultCode.decode(stream); decodedInnerTransactionResultResult.setDiscriminant(discriminant); switch (decodedInnerTransactionResultResult.getDiscriminant()) { case txSUCCESS: case txFAILED: int resultssize = stream.readInt(); decodedInnerTransactionResultResult.results = new OperationResult[resultssize]; for (int i = 0; i < resultssize; i++) { decodedInnerTransactionResultResult.results[i] = OperationResult.decode(stream); } break; case txTOO_EARLY: case txTOO_LATE: case txMISSING_OPERATION: case txBAD_SEQ: case txBAD_AUTH: case txINSUFFICIENT_BALANCE: case txNO_ACCOUNT: case txINSUFFICIENT_FEE: case txBAD_AUTH_EXTRA: case txINTERNAL_ERROR: case txNOT_SUPPORTED: case txBAD_SPONSORSHIP: case txBAD_MIN_SEQ_AGE_OR_GAP: case txMALFORMED: break; } return decodedInnerTransactionResultResult; } @Override public int hashCode() { return Objects.hashCode(Arrays.hashCode(this.results), this.code); } @Override public boolean equals(Object object) { if (!(object instanceof InnerTransactionResultResult)) { return false; } InnerTransactionResultResult other = (InnerTransactionResultResult) object; return Arrays.equals(this.results, other.results) && Objects.equal(this.code, other.code); } } public static class InnerTransactionResultExt { public InnerTransactionResultExt () {} Integer v; public Integer getDiscriminant() { return this.v; } public void setDiscriminant(Integer value) { this.v = value; } public static final class Builder { private Integer discriminant; public Builder discriminant(Integer discriminant) { this.discriminant = discriminant; return this; } public InnerTransactionResultExt build() { InnerTransactionResultExt val = new InnerTransactionResultExt(); val.setDiscriminant(discriminant); return val; } } public static void encode(XdrDataOutputStream stream, InnerTransactionResultExt encodedInnerTransactionResultExt) throws IOException { //Xdrgen::AST::Typespecs::Int //Integer stream.writeInt(encodedInnerTransactionResultExt.getDiscriminant().intValue()); switch (encodedInnerTransactionResultExt.getDiscriminant()) { case 0: break; } } public void encode(XdrDataOutputStream stream) throws IOException { encode(stream, this); } public static InnerTransactionResultExt decode(XdrDataInputStream stream) throws IOException { InnerTransactionResultExt decodedInnerTransactionResultExt = new InnerTransactionResultExt(); Integer discriminant = stream.readInt(); decodedInnerTransactionResultExt.setDiscriminant(discriminant); switch (decodedInnerTransactionResultExt.getDiscriminant()) { case 0: break; } return decodedInnerTransactionResultExt; } @Override public int hashCode() { return Objects.hashCode(this.v); } @Override public boolean equals(Object object) { if (!(object instanceof InnerTransactionResultExt)) { return false; } InnerTransactionResultExt other = (InnerTransactionResultExt) object; return Objects.equal(this.v, other.v); } } }
31.832278
144
0.702257
25640feda449e34a4f110fe538ae834e0b3efdc2
413
package com.cezarykluczynski.stapi.model.video_release.repository; import com.cezarykluczynski.stapi.model.common.repository.CriteriaMatcher; import com.cezarykluczynski.stapi.model.video_release.dto.VideoReleaseRequestDTO; import com.cezarykluczynski.stapi.model.video_release.entity.VideoRelease; public interface VideoReleaseRepositoryCustom extends CriteriaMatcher<VideoReleaseRequestDTO, VideoRelease> { }
45.888889
109
0.878935
0efe3aed277de7f892d5ad2c3f8de7275b299099
5,260
package br.com.fernando.ch05_working_with_streams.part07_Building_streams; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.stream.Stream; // Building streams public class Test { // This section shows how you can create a stream from a sequence of values, from an array, // from a file, and even from a generative function to create infinite streams! // // Streams from values public static void test1() { // You can create a stream with explicit values by using the static method Stream.of, which can // take any number of parameters. // final Stream<String> stream = Stream.of("Java 8 ", "Lambdas ", "In ", "Action"); stream.map(String::toUpperCase).forEach(System.out::println); // You can get an empty stream using the empty method as follows: final Stream<String> emptyStream = Stream.empty(); System.out.println(emptyStream); } // Streams from arrays public static void test2() { // You can create a stream from an array using the static method Arrays.stream, which takes an // array as parameter. final int[] numbers = { 2, 3, 5, 7, 13 }; final int sum = Arrays.stream(numbers).sum(); // The sum is 41 System.out.println(sum); } // Streams from files public static void test3() { // Java’s NIO API (non-blocking I/O), which is used for I/O operations such as processing a file, // has been updated to take advantage of the Streams API. Many static methods in // java.nio.file.Files return a stream. For example, a useful method is Files.lines, which returns a // stream of lines as strings from a given file long uniqueWords = 0; try (final Stream<String> lines = Files.lines(Paths.get("data"), Charset.defaultCharset())) { // Streams are autoclosable. uniqueWords = lines.flatMap(line -> Arrays.stream(line.split(" "))) // Generate a stream of words .distinct() // Remove duplicates. .count(); // Count the number of unique words. } catch (final Exception e) { throw new IllegalStateException(e); // Deal with the exception if one occurs when opening the file } // You use Files.lines to return a stream where each element is a line in the given file. You then // split each line into words by calling the split method on line. Notice how you use flatMap to // produce one flattened stream of words instead of multiple streams of words for each line. Finally, // you count each distinct word in the stream by chaining the methods distinct and count. System.out.println(uniqueWords); } // Streams from functions: creating infinite streams! public static void test4() { // The Streams API provides two static methods to generate a stream from a function: Stream.iterate and Stream.generate. // Iterate // The iterate method takes an initial value, here 0, and a lambda (of type Unary-Operator<T>) to // apply successively on each new value produced. Here you return the previous element added with 2 using the lambda n -> n + 2. A Stream.iterate(0, n -> n + 2) // .limit(10) // .forEach(System.out::println); // Note that this operation produces an infinite stream—the stream doesn’t have an end because values are // computed on demand and can be computed forever // Fibonacci tuples series // How does it work? iterate needs a lambda to specify the successor element. In the case of the // tuple (3, 5) the successor is (5, 3+5) = (5, 8). Stream.iterate(new int[] { 0, 1 }, t -> new int[] { t[1], t[0] + t[1] }) // .limit(10) // .map(t -> t[0]) // .forEach(System.out::println); // // Generate // Similarly to the method iterate, the method generate lets you produce an infinite stream of // values computed on demand. But generate doesn’t apply successively a function on each new // produced value. It takes a lambda of type Supplier<T> to provide new values. Let’s look at an // example of how to use it: Stream.generate(Math::random) // .limit(5) // .forEach(System.out::println); // Using generate so you can compare it with the approach using the iterate method! // But it’s important to note that a supplier that’s stateful isn’t safe to use in parallel code. // So what follows is shown just for completeness but should be avoided! // // The generate method will use the given supplier and repeatedly call the getAsInt method, which // always returns 2. But the difference between the anonymous class used here and a lambda is // that the anonymous class can define state via fields, which the getAsInt method can modify. // This is an example of a side effect. All lambdas you’ve seen so far were side-effect free; they didn’t // change any state. } public static void main(String[] args) { } }
45.73913
138
0.647529
1d449997926a70b50d319d7071f53e5d66a5b3ce
423
package com.efurture.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages={"com.efurture.mybatis.conf", "com.efurture.mustache.conf", "com.efurture.web.controller"}) public class AppApplication { public static void main(String[] args) { SpringApplication.run(AppApplication.class, args); } }
21.15
69
0.78487
6cdac1e0b9a7de3a72ccfb9dfd3251a4cb947a27
1,005
package ru.job4j.io.chat; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.stream.Stream; /** * @author Anton Kondratkov * @since 28.07.19. * Класс содержит метод, который добавляет фразы из файла в список. * И метод рандомно выводящий их в чат из списка. **/ public class AnswerFileSource implements AnswerSource { private final List<String> phrases = new ArrayList<>(); private final Random random = new Random(); public AnswerFileSource(URI fileUri) throws IOException { readPhraseFromFile(fileUri); } @Override public String getAnswer() { return phrases.get(random.nextInt(phrases.size())); } private void readPhraseFromFile(URI file) throws IOException { try (Stream<String> linesStream = Files.lines(Paths.get(file))) { linesStream.forEach(phrases::add); } } }
27.916667
73
0.703483
59b61b54d076bfff52f74cff06e8b5a9d916c831
1,332
/** * Copyright 2015 SPeCS. * * 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. under the License. */ package org.specs.matisselib.tests.ssa; import java.util.Locale; import pt.up.fe.specs.util.providers.ResourceProvider; public enum SsaResource implements ResourceProvider { SIMPLE, BRANCH, FOR, LOGICAL_AND, LOGICAL_OR, USE_IN, XWHILE, MULTI_END, CELL_END, WHILE_BREAK, FOR_BREAK, FOR_BREAK2, GLOBALS, GLOBALS_SET, GLOBALS_GET, DELETION, DELETION2; private static final String path = "ssa"; @Override public String getResource() { return SsaResource.path + "/" + name().toLowerCase(Locale.UK) + ".m"; } public String getExpectedResource() { return SsaResource.path + "/" + name().toLowerCase(Locale.UK) + ".txt"; } }
26.64
118
0.691441
7ae10862fb1df98903a2e68e717e6c180d974c06
5,911
package org.shypl.biser.csi.server; import org.shypl.biser.csi.ByteBuffer; import org.shypl.biser.csi.ConnectionCloseReason; import org.shypl.biser.csi.ProtocolException; import org.shypl.common.concurrent.Worker; import org.shypl.common.concurrent.WrappedTaskWorker; import org.shypl.common.slf4j.PrefixedLoggerProxy; import org.shypl.common.util.Cancelable; import org.shypl.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.SocketAddress; import java.util.concurrent.TimeUnit; class Connection implements ChannelHandler { private static long ID_COUNTER; private synchronized static long nextId() { return ++ID_COUNTER; } private final long id; private final Server server; private final Channel channel; private final Logger logger; private final Worker worker; private final Cancelable activityTimeout; private volatile boolean opened; private boolean closed; private boolean activity; private ConnectionProcessor processor; private byte[] readerData; private int readerCursor; public Connection(Server server, Channel channel) { id = nextId(); this.server = server; this.channel = channel; logger = new PrefixedLoggerProxy(LoggerFactory.getLogger(Connection.class), "[" + server.getApi().getName() + '#' + channel.getRemoteAddress() + "] "); worker = new WrappedTaskWorker(server.getExecutorsProvider().getConnectionExecutorService(), this::wrapWorkerTask); logger.debug("Open"); opened = true; setProcessor(new ConnectionProcessorReception()); activityTimeout = worker.scheduleTaskPeriodic(this::checkActivity, server.getSettings().getConnectionActivityTimeout(), TimeUnit.SECONDS); } public void cancelCheckActivityTimeout() { activityTimeout.cancel(); } public boolean isOpened() { return opened; } public long getId() { return id; } public SocketAddress getRemoteAddress() { return channel.getRemoteAddress(); } public Server getServer() { return server; } public Logger getLogger() { return logger; } public void setProcessor(ConnectionProcessor processor) { this.processor = processor; processor.init(this); } @Override public void handleChannelData(byte[] bytes) { worker.addTask(() -> { if (logger.isTraceEnabled()) { logger.trace(">> {}", StringUtils.toString(bytes)); } if (server.getSettings().isEmulateDelayInConnectionDataProcessing()) { try { Thread.sleep(server.getSettings().getEmulateDelayInConnectionDataProcessingMillis()); } catch (InterruptedException e) { logger.error("EmulateDelayInConnectionDataProcessing interrupted", e); syncClose(ConnectionCloseReason.SERVER_ERROR); } } activity = true; readerData = bytes; readerCursor = 0; while (isReadable()) { try { processor.processData(); } catch (ProtocolException e) { logger.debug("Protocol broken", e); syncClose(ConnectionCloseReason.PROTOCOL_BROKEN); } catch (Throwable e) { logger.error("Error on process data", e); syncClose(ConnectionCloseReason.SERVER_ERROR); } } readerData = null; }); } @Override public void handleChannelClose() { worker.addTask(() -> { activityTimeout.cancel(); logger.debug("Close"); boolean breaking = opened; opened = false; closed = true; processor.processClose(breaking); server.releaseConnection(this); processor.destroy(); processor = null; }); } public void send(byte b) { worker.addTask(() -> syncSend(b)); } public void send(byte[] bytes) { worker.addTask(() -> syncSend(bytes)); } public void close(ConnectionCloseReason reason) { worker.addTask(() -> syncClose(reason)); } void syncSend(byte[] bytes) { writeToChannel(bytes); } void syncSend(byte b) { writeToChannel(b); } void syncClose() { if (opened) { opened = false; channel.close(); } } void syncClose(ConnectionCloseReason reason) { if (opened) { opened = false; writeToChannel(ConnectionCloseReason.getProtocolFlag(reason)); channel.close(); } } byte read() { return readerData[readerCursor++]; } int read(ByteBuffer target, int length) { length = Math.min(getReadableBytesLength(), length); if (length > 0) { target.writeBytes(readerData, readerCursor, length); readerCursor += length; } return length; } int read(ByteBuffer target) { return read(target, getReadableBytesLength()); } int read(byte[] target, int offset) { return read(target, offset, target.length - offset); } int read(byte[] target, int offset, int length) { length = Math.min(readerData.length - readerCursor, length); if (length > 0) { System.arraycopy(readerData, readerCursor, target, offset, length); readerCursor += length; } return length; } boolean isReadable() { return opened && readerData.length > readerCursor; } int getReadableBytesLength() { return readerData.length - readerCursor; } private void checkActivity() { if (activity) { activity = false; } else { logger.debug("Activity timeout expired"); activityTimeout.cancel(); writeToChannel(ConnectionCloseReason.getProtocolFlag(ConnectionCloseReason.ACTIVITY_TIMEOUT_EXPIRED)); channel.close(); } } private void writeToChannel(byte b) { if (logger.isTraceEnabled()) { logger.trace("<< {}", '[' + StringUtils.toString(b) + ']'); } channel.write(b); } private void writeToChannel(byte[] bytes) { if (logger.isTraceEnabled()) { logger.trace("<< {}", StringUtils.toString(bytes)); } channel.write(bytes); } private Runnable wrapWorkerTask(Runnable task) { return () -> { if (closed) { logger.debug("Can't run task on closed connection"); } else { task.run(); } }; } }
23.549801
153
0.688716
fcdad420564213b189d0a01294bf80cc7c71f239
2,943
/* * This software is Copyright by the Board of Trustees of Michigan * State University (c) Copyright 2014, 2015. * * You may use this software under the terms of the GNU public license * (GPL). The terms of this license are described at: * http://www.gnu.org/licenses/gpl.txt * * Contact Information: * Facility for Rare Isotope Beam * Michigan State University * East Lansing, MI 48824-1321 * http://frib.msu.edu */ package org.openepics.discs.hourlog.ent; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author vuppala */ @Entity @Table(name = "mode_event") @XmlRootElement @NamedQueries({ @NamedQuery(name = "ModeEvent.findAll", query = "SELECT m FROM ModeEvent m"), @NamedQuery(name = "ModeEvent.findById", query = "SELECT m FROM ModeEvent m WHERE m.id = :id")}) public class ModeEvent implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @JoinColumn(name = "event", referencedColumnName = "event_id") @ManyToOne(optional = false) private Event event; @JoinColumn(name = "mode", referencedColumnName = "mode_id") @ManyToOne(optional = false) private Mode mode; public ModeEvent() { } public ModeEvent(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Event getEvent() { return event; } public void setEvent(Event event) { this.event = event; } public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ModeEvent)) { return false; } ModeEvent other = (ModeEvent) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "org.openepics.discs.hourlog.ent.ModeEvent[ id=" + id + " ]"; } }
26.276786
102
0.641862
99862f74c4dae61c5fb2dabef6770ecf77229626
2,102
package io.github.tesla.filter.support.enums; import java.util.Set; import org.springframework.core.annotation.AnnotationUtils; import io.github.tesla.common.dto.ServiceDTO; import io.github.tesla.filter.service.annotation.AuthType; import io.github.tesla.filter.service.definition.PluginDefinition; import io.github.tesla.filter.support.plugins.FilterMetadata; import io.github.tesla.filter.utils.ClassUtils; public class AuthTypeEnum { private String authType; private Class<? extends PluginDefinition> clazz; AuthTypeEnum(Class clz) { AuthType annotation = AnnotationUtils.findAnnotation(clz, AuthType.class); this.authType = annotation.authType(); this.clazz = annotation.definitionClazz(); } public static AuthTypeEnum fromType(String authType) { Set<Class<?>> allClasses = ClassUtils.findAllClasses(FilterMetadata.FILTER_SCAN_PACKAGE, AuthType.class); for (Class clz : allClasses) { if (authType.equals(AnnotationUtils.findAnnotation(clz, AuthType.class).authType())) { return new AuthTypeEnum(clz); } } return null; } public static String validate(String authType, String paramJson, ServiceDTO serviceDTO) { AuthTypeEnum authTypeEnum = fromType(authType); if (authTypeEnum == null) { throw new RuntimeException(FilterMetadata.errorMsg(authType)); } if (authTypeEnum.getClazz() == null) { return paramJson; } try { PluginDefinition instance = authTypeEnum.getClazz().newInstance(); return instance.validate(paramJson, serviceDTO); } catch (Exception e) { throw new RuntimeException(e); } } public String getAuthType() { return authType; } public void setAuthType(String authType) { this.authType = authType; } public Class<? extends PluginDefinition> getClazz() { return clazz; } public void setClazz(Class<? extends PluginDefinition> clazz) { this.clazz = clazz; } }
31.848485
113
0.672217
7302f974037cecc54c9ef74f1c6de880ab80d985
757
/** * */ package com.example.DTO; /** * @author mindfire * */ public class UserDetailsDTO { private String userName; private String password; public UserDetailsDTO(){ } public UserDetailsDTO(String sUserName, String password) { super(); this.userName = sUserName; this.password = password; } /** * @return the sUserName */ public String getsUserName() { return userName; } /** * @param sUserName the sUserName to set */ public void setsUserName(String sUserName) { this.userName = sUserName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } }
15.14
59
0.659181
ffd8095822bffe8d74fedc85d06684407cfcd44e
6,419
package com.github.piasy.oauth3.github.presenter; import android.text.TextUtils; import android.util.Log; import android.util.Pair; import com.github.piasy.oauth3.github.GitHubOAuth; import com.github.piasy.oauth3.github.model.ApiErrorAwareConverterFactory; import com.github.piasy.oauth3.github.model.AuthApi; import com.github.piasy.oauth3.github.model.AutoGsonAdapterFactory; import com.github.piasy.oauth3.github.model.GitHubError; import com.github.piasy.oauth3.github.model.GitHubToken; import com.github.piasy.oauth3.github.model.GitHubUser; import com.github.piasy.oauth3.github.model.UserApi; import com.github.piasy.oauth3.github.view.OAuthResult; import com.github.piasy.oauth3.github.view.OAuthView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.internal.functions.Functions; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.Subject; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by Piasy{github.com/Piasy} on 26/12/2016. */ public class OAuthPresenter { private static final Pair<OAuthResult, String> STOP_WAITING = Pair.create(null, null); private static final int WAIT_CODE_TIMEOUT_SECONDS = 3; private final GitHubOAuth mGitHubOAuth; private final CompositeDisposable mDisposable; private final AuthApi mAuthApi; private final UserApi mUserApi; private OAuthView mOAuthView; public OAuthPresenter(GitHubOAuth gitHubOAuth) { mGitHubOAuth = gitHubOAuth; mDisposable = new CompositeDisposable(); Gson gson = new GsonBuilder() .registerTypeAdapterFactory(AutoGsonAdapterFactory.create()) .create(); OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); if (mGitHubOAuth.debug()) { httpClientBuilder.addInterceptor( new HttpLoggingInterceptor(message -> Log.d(GitHubOAuth.TAG, message)) .setLevel(HttpLoggingInterceptor.Level.BODY)); } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .client(httpClientBuilder.build()) .addCallAdapterFactory( RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .addConverterFactory( new ApiErrorAwareConverterFactory(GsonConverterFactory.create(gson), GitHubError.class)); mAuthApi = retrofitBuilder .baseUrl(AuthApi.BASE_URL) .build() .create(AuthApi.class); mUserApi = retrofitBuilder .baseUrl(UserApi.BASE_URL) .build() .create(UserApi.class); // see https://github.com/ReactiveX/RxJava/issues/4996#issuecomment-272686780 RxJavaPlugins.setErrorHandler(Functions.emptyConsumer()); } public void attach(OAuthView oAuthView) { mOAuthView = oAuthView; } public void getAuthInfo(String code, String state) { Observable<GitHubToken> tokenInfo = mAuthApi .accessToken(mGitHubOAuth.clientId(), mGitHubOAuth.clientSecret(), code, state) .publish() .autoConnect(2); Observable<GitHubUser> userInfo = tokenInfo .flatMap(token -> mUserApi.user("token " + token.access_token())); Disposable disposable = Observable.zip(tokenInfo, userInfo, Pair::create) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(pair -> { if (mOAuthView != null) { mOAuthView.authSuccess(pair.first.access_token(), pair.second); } }, throwable -> { Log.d(GitHubOAuth.TAG, "Presenter: consume " + throwable); if (mOAuthView != null) { if (throwable instanceof GitHubError) { mOAuthView.authFail(GitHubOAuth.ERROR_API_FAIL, ((GitHubError) throwable).error()); } else { unknownFailure(); } } }); mDisposable.add(disposable); } public void destroy() { mDisposable.dispose(); } public void waitCode(Subject<Pair<OAuthResult, String>> oAuthResultSubject) { Disposable disposable = Observable.merge( Observable.just(STOP_WAITING) .delay(WAIT_CODE_TIMEOUT_SECONDS, TimeUnit.SECONDS), oAuthResultSubject) .take(1) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(pair -> { if (mOAuthView != null) { if (pair == STOP_WAITING) { mOAuthView.authFail(GitHubOAuth.ERROR_UNKNOWN_ERROR, "Code didn't arrived in time."); } else if (!TextUtils.isEmpty(pair.second)) { mOAuthView.authFail(GitHubOAuth.ERROR_OAUTH_FAIL, pair.second); } else { mOAuthView.codeArrived(pair.first); getAuthInfo(pair.first.code(), pair.first.state()); } } }, throwable -> { if (mOAuthView != null) { unknownFailure(); } }); mDisposable.add(disposable); } private void unknownFailure() { mOAuthView.authFail(GitHubOAuth.ERROR_UNKNOWN_ERROR, "Auth fail for unknown reason."); } }
40.88535
95
0.599626
3da5133000088932ec06d0e9ff220722af7d1204
718
package com.my.mq.remoting.enums; /** * @author handx * @version 1.0.0 * @ClassName LanguageType.java * @Description 支持的语言 * @createTime 2020年10月28日 22:45:00 */ public enum LanguageType { JAVA((byte) 0), CPP((byte) 1), PYTHON((byte) 2), HTTP((byte) 3), GO((byte) 4), PHP((byte) 5); private byte type; LanguageType(byte type) { this.type = type; } public static LanguageType getByType(byte type) { for (LanguageType languageCode : LanguageType.values()) { if (languageCode.getType() == type) { return languageCode; } } return null; } public byte getType() { return type; } }
18.894737
65
0.561281
2aa148961f3ebb3bf9a74c8a3e77f13703ade940
2,122
package com.andrey7mel.stepbystep.integration.view; import android.view.LayoutInflater; import android.view.ViewGroup; import com.andrey7mel.stepbystep.R; import com.andrey7mel.stepbystep.integration.other.IntegrationBaseTest; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.MainActivity; import com.andrey7mel.stepbystep.view.fragments.RepoListFragment; import org.junit.Before; import org.junit.Test; import org.robolectric.Robolectric; import java.util.List; import javax.inject.Inject; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; public class RepoListFragmentTest extends IntegrationBaseTest { @Inject protected List<Repository> repoList; private RepoListFragment repoListFragment; private MainActivity activity; @Override @Before public void setUp() throws Exception { super.setUp(); component.inject(this); repoListFragment = spy(new RepoListFragment()); activity = Robolectric.setupActivity(MainActivity.class); repoListFragment.onAttach(activity); doAnswer(invocation -> TestConst.TEST_OWNER) .when(repoListFragment) .getUserName(); } @Test public void testOnCreate() { repoListFragment.onCreate(null); repoListFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), null); repoListFragment.onClickSearch(null); repoListFragment.onStop(); verify(repoListFragment).showRepoList(repoList); } @Test public void testOnCreateWithError() { setErrorAnswerWebServer(); repoListFragment.onCreate(null); repoListFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), null); repoListFragment.onClickSearch(null); repoListFragment.onStop(); verify(repoListFragment).showError(TestConst.ERROR_RESPONSE_500); } }
31.205882
126
0.741753
0bf4ed730edfce279a753683ab361f5460bd4d6b
182
package tw.com.softleader.ldap.entity; import lombok.Getter; import lombok.Setter; @Getter @Setter public class Node { private String parentName; private String name; }
12.133333
38
0.741758
7c3b93e62bf1e74582cfe55fddd098160657be3e
1,741
package org.openexi.fujitsu.proc.grammars; import org.openexi.fujitsu.proc.common.EventTypeList; public final class EventTypeSchemaAttribute extends EventTypeSchema { private final boolean m_useSpecificType; EventTypeSchemaAttribute(int attr, String uri, String name, int index, int serial, Grammar ownerGrammar, EventTypeList eventTypeList) { this(attr, true, uri, name, index, serial, ownerGrammar, eventTypeList); } EventTypeSchemaAttribute(int attr, boolean useSpecificType, String uri, String name, int index, int serial, Grammar ownerGrammar, EventTypeList eventTypeList) { super(attr, uri, name, index, serial, EVENT_CODE_DEPTH_ONE, ownerGrammar, eventTypeList, ITEM_SCHEMA_AT); m_useSpecificType = useSpecificType; } /////////////////////////////////////////////////////////////////////////// // Accessors /////////////////////////////////////////////////////////////////////////// public boolean useSpecificType() { return m_useSpecificType; } /////////////////////////////////////////////////////////////////////////// // Implementation of EventType interface /////////////////////////////////////////////////////////////////////////// @Override boolean isContent() { return false; } /////////////////////////////////////////////////////////////////////////// // Implementation of EventTypeSchema interface /////////////////////////////////////////////////////////////////////////// @Override EventTypeSchema duplicate(EventTypeList eventTypeList) { return new EventTypeSchemaAttribute( m_substance, m_uri, m_name, index, serial, m_ownerGrammar, eventTypeList); } @Override boolean isAugmented() { return false; } }
32.849057
110
0.54911
51e4d32caf5df01eb809027e5b2d2268f1c3b754
18,979
import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.ggp.base.util.gdl.grammar.Gdl; import org.ggp.base.util.gdl.grammar.GdlConstant; import org.ggp.base.util.gdl.grammar.GdlDistinct; import org.ggp.base.util.gdl.grammar.GdlFunction; import org.ggp.base.util.gdl.grammar.GdlLiteral; import org.ggp.base.util.gdl.grammar.GdlPool; import org.ggp.base.util.gdl.grammar.GdlRelation; import org.ggp.base.util.gdl.grammar.GdlRule; import org.ggp.base.util.gdl.grammar.GdlSentence; import org.ggp.base.util.gdl.grammar.GdlTerm; import org.ggp.base.util.propnet.architecture.Component; import org.ggp.base.util.propnet.architecture.PropNet; import org.ggp.base.util.propnet.architecture.components.And; import org.ggp.base.util.propnet.architecture.components.Constant; import org.ggp.base.util.propnet.architecture.components.Not; import org.ggp.base.util.propnet.architecture.components.Or; import org.ggp.base.util.propnet.architecture.components.Proposition; import org.ggp.base.util.propnet.architecture.components.Transition; import org.ggp.base.util.propnet.factory.LegacyPropNetFactory; import org.ggp.base.util.propnet.factory.OptimizingPropNetFactory; import org.ggp.base.util.statemachine.MachineState; import org.ggp.base.util.statemachine.Move; import org.ggp.base.util.statemachine.Role; import org.ggp.base.util.statemachine.StateMachine; import org.ggp.base.util.statemachine.exceptions.GoalDefinitionException; import org.ggp.base.util.statemachine.exceptions.MoveDefinitionException; import org.ggp.base.util.statemachine.exceptions.TransitionDefinitionException; import org.ggp.base.util.statemachine.implementation.prover.query.ProverQueryBuilder; public class HopefullyBetterPropnetStateMachineQuestionMark extends StateMachine { public PropNet propnet; private List<Role> roles; private Proposition[] basePropositions; private Proposition[] inputPropositions; private ArrayList<Map<GdlTerm, GdlSentence>> inputMap; private Map<Role, Proposition[]> legalPropositions; public List<Gdl> description; private boolean factoringEnabled = false; public boolean zeroSum = true; @Override public List<Move> findActions(Role role) throws MoveDefinitionException { Set<Proposition> legalProps = this.propnet.getLegalPropositions().get(role); ArrayList<Move> legalMoves = new ArrayList<Move>(); for (Proposition p : legalProps) { legalMoves.add(this.getMoveFromProposition(p)); } return legalMoves; } private void bfs(Component c) { if (c.connectedToTerminal) return; c.connectedToTerminal = true; for (Component cc : c.getInputs()) bfs(cc); } private void sanitizeDistinctHelper(Gdl gdl, List<Gdl> in, List<Gdl> out) { if (!(gdl instanceof GdlRule)) { out.add(gdl); return; } GdlRule rule = (GdlRule) gdl; for (GdlLiteral lit : rule.getBody()) { if (lit instanceof GdlDistinct) { GdlDistinct d = (GdlDistinct) lit; GdlTerm a = d.getArg1(); GdlTerm b = d.getArg2(); if (!(a instanceof GdlFunction) && !(b instanceof GdlFunction)) continue; if (!(a instanceof GdlFunction && b instanceof GdlFunction)) return; GdlSentence af = ((GdlFunction) a).toSentence(); GdlSentence bf = ((GdlFunction) b).toSentence(); if (!af.getName().equals(bf.getName())) return; if (af.arity() != bf.arity()) return; for (int i = 0; i < af.arity(); i++) { List<GdlLiteral> ruleBody = new ArrayList<>(); for (GdlLiteral newLit : rule.getBody()) { if (newLit != lit) ruleBody.add(newLit); else ruleBody.add(GdlPool.getDistinct(af.get(i), bf.get(i))); } GdlRule newRule = GdlPool.getRule(rule.getHead(), ruleBody); in.add(newRule); } return; } } for (GdlLiteral lit : rule.getBody()) { if (lit instanceof GdlDistinct) { break; } } out.add(rule); } private List<Gdl> sanitizeDistinct(List<Gdl> description) { List<Gdl> out = new ArrayList<>(); for (int i = 0; i < description.size(); i++) { sanitizeDistinctHelper(description.get(i), description, out); } return out; } private void resetall() { for (Component c : this.propnet.getComponents()) c.connectedToTerminal = false; } @Override public void initialize(List<Gdl> description) { description = sanitizeDistinct(description); this.description = description; // create propnet try { this.propnet = OptimizingPropNetFactory.create(description); } catch (Exception e) { this.propnet = LegacyPropNetFactory.create(description); } System.out.println("[PROPNET] Finished Building Propnet"); for (Role r : this.propnet.getRoles()) { for (Proposition p : this.propnet.getGoalPropositions().get(r)) { if (this.getGoalValue(p) != 0 && this.getGoalValue(p) != 100 && this.getGoalValue(p) != 50) { this.zeroSum = false; } } if (!this.zeroSum) break; } // check zero-sum if (this.zeroSum) System.out.println("[PROPNET] This Game is Zero-Sum"); else System.out.println("[PROPNET] This Game is NOT Zero-Sum"); // mark input/bases for (Proposition p : this.propnet.getInputPropositions().values()) p.setInput(true); for (Proposition p : this.propnet.getBasePropositions().values()) p.setBase(true); for (Role r : this.propnet.getRoles()) { for (Proposition p : this.propnet.getLegalPropositions().get(r)) p.setLegal(true); for (Proposition p : this.propnet.getGoalPropositions().get(r)) p.setGoal(true); } // optimization System.out.println("[PROPNET] Begin Optimizing View Propositions"); int numberTrimmed = 0; Set<Proposition> propsToRemove = new HashSet<>(); for (Proposition p : this.propnet.getPropositions()) { if (p.isBase() || p.isInput() || p.isGoal() || p.isLegal()) continue; else if (p.equals(this.propnet.getInitProposition())) continue; else if (p.equals(this.propnet.getTerminalProposition())) continue; else if (this.propnet.getLegalInputMap().get(p) != null) continue; else { if (p.getInputs().size() == 1 && p.getOutputs().size() == 1) { Component inputComp = p.getSingleInput(); Component outputComp = p.getSingleOutput(); inputComp.removeOutput(p); outputComp.removeInput(p); inputComp.addOutput(outputComp); outputComp.addInput(inputComp); propsToRemove.add(p); numberTrimmed++; } } } for (Proposition p : propsToRemove) this.propnet.removeComponent(p); System.out.println("[PROPNET] Trimmed " + numberTrimmed + " View Propositions"); // do some bs factoring // System.out.println("[PROPNET] Terminal Inputs: " + this.propnet.getTerminalProposition().getSingleInput().getInputs().size()); // bfs(this.propnet.getTerminalProposition()); // ArrayList<Component> toRemove = new ArrayList<>(); // for (Proposition p : this.propnet.getBasePropositions().values()) { // if (!p.connectedToTerminal) toRemove.add(p); // } // int tempNumberOfTotalInputs = this.propnet.getInputPropositions().size(); // System.out.println("Total # of Legals: " + this.propnet.getInputPropositions().size()); // if (this.propnet.getRoles().size() == 1) { // for (Proposition p : this.propnet.getInputPropositions().values()) { // if (!p.connectedToTerminal) { // toRemove.add(this.propnet.getLegalInputMap().get(p)); // } // } // // if (toRemove.size() == 0) { // best buttons // Component or = this.propnet.getTerminalProposition().getSingleInput(); // if ((or instanceof Or)) { // for (Component c : or.getInputs()) { // resetall(); // bfs(c); // // for (Proposition p : this.propnet.getInputPropositions().values()) { // if (!p.connectedToTerminal) { // toRemove.add(this.propnet.getLegalInputMap().get(p)); // } // } // // if (toRemove.size() != tempNumberOfTotalInputs) break; // else { // toRemove.clear(); // } // } // } // } // if (toRemove.size() == 0) { // another attempt // for (Component c : this.propnet.getInputPropositions().values()) c.setInput(true); // for (Component c : this.propnet.getBasePropositions().values()) c.setBase(true); // Component or = this.propnet.getTerminalProposition().getSingleInput(); // if ((or instanceof Or)) { // for (Component c : or.getInputs()) { // resetall(); // Set<Component> comps = new HashSet<>(); // this.connectedBases(c, comps); // // System.out.println("Connected BASES: " + comps); // // for (Component cc : comps) if (cc.isBase()) System.out.println("well, I am a base"); // for (Component cc : comps) findConnectedInputs(cc.getSingleInput(), cc); // // for (Proposition p : this.propnet.getInputPropositions().values()) { // if (!p.connectedToTerminal) { // toRemove.add(this.propnet.getLegalInputMap().get(p)); // } // } // // if (toRemove.size() != tempNumberOfTotalInputs) break; // else { // if (toRemove.size() == tempNumberOfTotalInputs) System.out.println("oops"); // toRemove.clear(); // } // } // } // } // // System.out.println("Removing #: " + toRemove.size()); // for (Component p : toRemove) { // System.out.println("REMOVING: " + p); // p.toIgnore = true; // // this.propnet.removeComponent(p); // } // for (Component p : this.propnet.getInputPropositions().values()) { // Component c = this.propnet.getLegalInputMap().get(p); // if (!c.toIgnore) System.out.println("REMAINING: " + c); // } // } // more optimizations + crystalization this.roles = propnet.getRoles(); for (Component c : this.propnet.getComponents()) c.crystalize(); this.basePropositions = new Proposition[this.propnet.getBasePropositions().size()]; this.inputPropositions = new Proposition[this.propnet.getInputPropositions().size()]; this.legalPropositions = new HashMap<>(); for (Component c : this.propnet.getComponents()) { if ((c instanceof Constant)) c.setPreviousValue(!c.getValue()); else c.setPreviousValue(false); } List<Proposition> bases = new ArrayList<Proposition>(this.propnet.getBasePropositions().values()); for (int i = 0; i < this.basePropositions.length; i++) { this.basePropositions[i] = bases.get(i); this.basePropositions[i].setBase(true); } List<Proposition> inputs = new ArrayList<Proposition>(this.propnet.getInputPropositions().values()); for (int i = 0; i < this.inputPropositions.length; i++) { this.inputPropositions[i] = inputs.get(i); this.inputPropositions[i].setInput(true); } Map<Role, Set<Proposition>> legalprops = this.propnet.getLegalPropositions(); for (Role r : this.roles) { Set<Proposition> legals = legalprops.get(r); Proposition[] ps = new Proposition[legals.size()]; int i = 0; for (Proposition p : legals) { ps[i] = p; i++; } this.legalPropositions.put(r, ps); } this.inputMap = new ArrayList<>(); for (Role r : this.roles) { Set<Proposition> moves = this.propnet.getLegalPropositions().get(r); Map<GdlTerm, GdlSentence> buf = new HashMap<>(); for (Proposition p : moves) { GdlSentence moveSentence = ProverQueryBuilder.toDoes(r, new Move(p.getName().get(1))); buf.put(p.getName().get(1), moveSentence); // System.out.println("key: " + p.getName().get(1) + " | value: " + moveSentence); } this.inputMap.add(buf); } // System.out.println("input map: " + this.inputMap); //System.out.println("Wrote propnet to disk."); //this.propnet.renderToFile("C:\\Users\\panch\\Desktop\\knightstour.dot"); System.out.println("Finished Initializing StateMachine"); } @Override public int getGoal(MachineState state, Role role) throws GoalDefinitionException { this.markbases(state); for (Component c : this.basePropositions) forwardprop(c); Set<Proposition> goalProps = this.propnet.getGoalPropositions().get(role); for (Proposition p : goalProps) { if (p.getValue()) return this.getGoalValue(p); } return 0; } @Override public boolean isTerminal(MachineState state) { this.markbases(state); for (Component c : this.basePropositions) forwardprop(c); return this.propnet.getTerminalProposition().getValue(); // for (Component c : this.propnet.getTerminalProposition().fasterGetInputs()) { // if (!c.getValue()) return false; // } // // return true; } @Override public List<Role> getRoles() { return this.roles; } @Override public MachineState getInitialState() { for (Component c : this.propnet.getComponents()) { // check what subclass of component if ((c instanceof And)) ((And) c).useFastMethod = true; if ((c instanceof Or)) ((Or) c).useFastMethod = true; if ((c instanceof Transition)) ((Transition) c).useFastMode = true; } for (Component c : this.propnet.getComponents()) if ((c instanceof Constant)) forwardprop(c); Proposition initProp = this.propnet.getInitProposition(); if (initProp != null) { this.propnet.getInitProposition().setValue(true); for (Component c : this.propnet.getComponents()) if ((c instanceof Not)) forwardprop(c); forwardprop(this.propnet.getInitProposition()); } Set<GdlSentence> state = new HashSet<GdlSentence>(); BitSet activeStates = new BitSet(this.basePropositions.length); for (int i = 0; i < this.basePropositions.length; i++) { boolean val = this.basePropositions[i].fasterGetSingleInput().getValue(); activeStates.set(i, val); if (val) { state.add(this.basePropositions[i].getName()); } } System.out.println("INITIAL STATE VALUES: " + state); if (initProp != null) { this.propnet.getInitProposition().setValue(false); forwardprop(this.propnet.getInitProposition()); System.out.println("Turning off init prop..."); } return new MachineState(state, activeStates); } @Override public List<Move> getLegalMoves(MachineState state, Role role) throws MoveDefinitionException { this.markbases(state); for (Component c : this.basePropositions) forwardprop(c); // for (Component c : this.propnet.getComponents()) c.setPreviousValue(c.getValue()); Proposition[] legalProps = this.legalPropositions.get(role); ArrayList<Move> moves = new ArrayList<Move>(); for (Proposition p : legalProps) { // if (this.factoringEnabled && p.toIgnore) continue; if (p.getValue()) moves.add(this.getMoveFromProposition(p)); } // if (moves.size() == 0 && this.factoringEnabled) { // LOL // this.factoringEnabled = false; // System.out.println("FACTORING IS NOW OFF"); // for (Proposition p : legalProps) { // if (this.factoringEnabled && p.toIgnore) continue; // if (p.getValue()) moves.add(this.getMoveFromProposition(p)); // } // } // System.out.println("Legal Moves: " + moves); return moves; } @Override public MachineState getNextState(MachineState state, List<Move> moves) throws TransitionDefinitionException { this.markactions(moves); this.markbases(state); for (Component c : this.basePropositions) forwardprop(c); for (Component c : this.inputPropositions) forwardprop(c); // for (Component c : this.propnet.getComponents()) c.setPreviousValue(c.getValue()); Set<GdlSentence> gdlState = new HashSet<GdlSentence>(); BitSet activeStates = new BitSet(this.basePropositions.length); for (int i = 0; i < this.basePropositions.length; i++) { boolean val = this.basePropositions[i].fasterGetSingleInput().getValue(); activeStates.set(i, val); if (val) { gdlState.add(this.basePropositions[i].getName()); } } // System.out.println("NEXT STATE VALUES: " + gdlState); return new MachineState(gdlState, activeStates); } // ---------------------------------------------- private void forwardprop(Component c) { boolean c_val = c.getValue(); if (c_val == c.previousValue()) return; c.setPreviousValue(c_val); if ((c instanceof Transition)) return; for (Component o : c.fasterGetOutputs()) { if ((o instanceof Proposition)) { o.setPreviousValue(o.getValue()); ((Proposition) o).setValue(c_val); } else if ((o instanceof And)) ((And) o).counter += (c_val) ? 1 : -1; else if ((o instanceof Or)) ((Or) o).counter += (c_val) ? 1 : -1; else if ((o instanceof Transition)) { o.setPreviousValue(o.getValue()); ((Transition) o).setValue(c_val); } forwardprop(o); } } private void markbases(MachineState s) { BitSet activeBits = s.getPropContents(); for (int i = 0; i < this.basePropositions.length; i++) { this.basePropositions[i].setPreviousValue(this.basePropositions[i].getValue()); this.basePropositions[i].setValue(activeBits.get(i)); // if (activeBits.get(i)) { // System.out.println("True: " + this.basePropositions[i].getName()); // } } // for (Proposition p : this.basePropositions) { // p.setPreviousValue(p.getValue()); // p.setValue(false); // } // for (GdlSentence sentence : s.getContents()) { // this.propnet.getBasePropositions().get(sentence).setValue(true); // } } private void markactions(List<Move> moves) { for (Proposition p : this.inputPropositions) { p.setPreviousValue(p.getValue()); p.setValue(false); } GdlSentence[] gdlMoves = toDoes(moves); for (GdlSentence m : gdlMoves) { this.propnet.getInputPropositions().get(m).setValue(true); } } private GdlSentence[] toDoes(List<Move> moves) { GdlSentence[] doeses = new GdlSentence[moves.size()]; for (int i = 0; i < moves.size(); i++) { doeses[i] = this.inputMap.get(i).get(moves.get(i).getContents()); } return doeses; } /** * Takes in a Legal Proposition and returns the appropriate corresponding Move * @param p * @return a PropNetMove */ public Move getMoveFromProposition(Proposition p) { return new Move(p.getName().get(1)); } /** * Helper method for parsing the value of a goal proposition * @param goalProposition * @return the integer value of the goal proposition */ private int getGoalValue(Proposition goalProposition) { GdlRelation relation = (GdlRelation) goalProposition.getName(); GdlConstant constant = (GdlConstant) relation.get(1); return Integer.parseInt(constant.toString()); } // ---------------------------------------------- }
38.341414
131
0.654987