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
2b9a1be65586ba49a820243035b5a50f50da7041
450
package evolutions; import org.junit.Test; import play.db.Database; import play.db.evolutions.Evolutions; import utils.WithFlowUpApplication; public class EvolutionsTest extends WithFlowUpApplication { @Test public void executesUpAndDownEvolutionsWithoutErrors() { Database database = app.injector().instanceOf(Database.class); Evolutions.cleanupEvolutions(database); Evolutions.applyEvolutions(database); } }
25
70
0.764444
fc4c94716081efc2a0229c475fe78c4adf14c11e
1,014
package com.aswin.dao; public class DBConstants { public static final String SCHEMA = "Super_Market"; public class User { public static final String CUSTOMERTABLE = "Customer"; public static final String REPTABLE = "S_Representative"; public static final String BillTABLE = "Bill"; public static final String PRODUCTSBUYEDTABLE = "Products_Buyed"; public static final String STOCKTABLE = "Stocks"; public static final String PAYMENTMODETABLE = "Payment_Mode"; public static final String DESIGNATIONTABLE = "Designation"; // public static final String CONTENTID = "ContentID"; // public static final String HEADING = "Heading"; // public static final String CONTENTVALUE = "ContentValue"; // public static final String ADDEDTIME = "AddedTime"; // public static final String MODIFIEDTIME = "ModifiedTime"; } public static final String MYSQL_USER_NAME = "root"; public static final String MYSQL_PASSWORD = ""; public static final String MYSQL_DRIVER = "com.mysql.cj.jdbc.Driver"; }
44.086957
73
0.754438
cdc94c44c545994d782fcfadc72e74840f60f50d
1,916
import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; public class MapDistricts { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); List<String> tokens = Arrays.asList(scanner.nextLine().split(" ")); int bound = Integer.parseInt(scanner.nextLine()); HashMap<String, List<Integer>> cities = new HashMap<>(); for (String token : tokens) { String city = token.split(":")[0]; int population = Integer.parseInt(token.split(":")[1]); cities.putIfAbsent(city, new ArrayList<>()); cities.get(city).add(population); } cities.entrySet().stream() .filter(getFilterByPopulationPredicate(bound)) .sorted(getSortByDescendingPopulationComparator()) .forEach(getPrintMapEntryConsumer()); } private static Consumer<? super Map.Entry<String, List<Integer>>> getPrintMapEntryConsumer() { return kv -> { System.out.print(kv.getKey() + ": "); kv.getValue().stream() .sorted((s1, s2) -> s2.compareTo(s1)) .limit(5) .forEach(dp -> System.out.print(dp + " ")); System.out.println(); }; } private static Comparator<? super Map.Entry<String, List<Integer>>> getSortByDescendingPopulationComparator() { return (kv1, kv2) -> Integer.compare( kv2.getValue().stream().mapToInt(Integer::valueOf).sum(), kv1.getValue().stream().mapToInt(Integer::valueOf).sum()); } private static Predicate<? super Map.Entry<String, List<Integer>>> getFilterByPopulationPredicate(int bound) { return kv -> kv.getValue().stream() .mapToInt(Integer::valueOf) .sum() >= bound; } }
38.32
115
0.573591
29cbfc5bf62b1928f395e6856b5d17ce37a56465
15,148
package ru.r2cloud.jradio.ledsat; import java.io.DataInputStream; import java.io.IOException; import ru.r2cloud.jradio.util.StreamUtils; public class LedSatTelemetry { private int telemetryId; private int unixMillis; private long unixSeconds; private int tlmProcessTimeMillis; private int panelXVoltage; private int panelYVoltage; private int panelZVoltage; private int panelXCurrent; private int panelYCurrent; private int panelZCurrent; private int epsBootCause; private int epsBatteryMode; private int mpttXTemperature; private int mpttYTemperature; private int epsTemperature; private int batter1Temperature; private int batter2Temperature; private int batter3Temperature; private int panelTotalCurrent; private int systemConsumedCurrent; private int batteryVoltage; private float gpsCurrent; private int epsBootCount; private float paTransceiverTemperature; private long transceiverTxCount; private long transceiverRxCount; private int lastRssi; private int radioBootCounter; private float obc1Temperature; private float obc2Temperature; private float gyroX; private float gyroY; private float gyroZ; private int magnetometerX; private int magnetometerY; private int magnetometerZ; private float panelXpTemperature; private float panelYpTemperature; private float panelXmTemperature; private float panelYmTemperature; private float panelZpTemperature; private float panelZmTemperature; private int sunSensorXp; private int sunSensorYp; private int sunSensorZp; private int sunSensorXm; private int sunSensorYm; private int sunSensorZm; private int epsOutputsStatus; private int obcBootCounter; private int ledStatus; private int gpsStatus; private long gpsFixTime; private float gpsLatitude; private float gpsLongitude; private long gpsAltitude; private int softwareStatus; private float externalGyroX; private float externalGyroY; private float externalGyroZ; private int externalMagnetometerX; private int externalMagnetometerY; private int externalMagnetometerZ; public LedSatTelemetry() { // do nothing } public LedSatTelemetry(DataInputStream dis) throws IOException { telemetryId = dis.readUnsignedShort(); unixMillis = dis.readUnsignedShort(); unixSeconds = StreamUtils.readUnsignedInt(dis); tlmProcessTimeMillis = dis.readUnsignedShort(); panelXVoltage = dis.readUnsignedShort(); panelYVoltage = dis.readUnsignedShort(); panelZVoltage = dis.readUnsignedShort(); panelXCurrent = dis.readUnsignedShort(); panelYCurrent = dis.readUnsignedShort(); panelZCurrent = dis.readUnsignedShort(); epsBootCause = dis.readUnsignedByte(); epsBatteryMode = dis.readUnsignedByte(); mpttXTemperature = dis.readShort(); mpttYTemperature = dis.readShort(); epsTemperature = dis.readShort(); batter1Temperature = dis.readShort(); batter2Temperature = dis.readShort(); batter3Temperature = dis.readShort(); panelTotalCurrent = dis.readUnsignedShort(); systemConsumedCurrent = dis.readUnsignedShort(); batteryVoltage = dis.readUnsignedShort(); gpsCurrent = dis.readUnsignedByte() / 0.15f; dis.skipBytes(1); epsBootCount = dis.readUnsignedShort(); paTransceiverTemperature = dis.readShort() / 10.0f; transceiverTxCount = StreamUtils.readUnsignedInt(dis); transceiverRxCount = StreamUtils.readUnsignedInt(dis); lastRssi = dis.readUnsignedShort(); radioBootCounter = dis.readUnsignedShort(); obc1Temperature = dis.readShort() / 10.0f; obc2Temperature = dis.readShort() / 10.0f; gyroX = dis.readShort() / 100.0f; gyroY = dis.readShort() / 100.0f; gyroZ = dis.readShort() / 100.0f; magnetometerX = dis.readShort(); magnetometerY = dis.readShort(); magnetometerZ = dis.readShort(); panelXpTemperature = dis.readShort() / 100.0f; panelYpTemperature = dis.readShort() / 100.0f; panelXmTemperature = dis.readShort() / 100.0f; panelYmTemperature = dis.readShort() / 100.0f; panelZpTemperature = dis.readShort() / 100.0f; panelZmTemperature = dis.readShort() / 100.0f; sunSensorXp = dis.readUnsignedShort(); sunSensorYp = dis.readUnsignedShort(); sunSensorZp = dis.readUnsignedShort(); sunSensorXm = dis.readUnsignedShort(); sunSensorYm = dis.readUnsignedShort(); sunSensorZm = dis.readUnsignedShort(); epsOutputsStatus = dis.readUnsignedByte(); dis.skipBytes(1); obcBootCounter = dis.readUnsignedShort(); ledStatus = dis.readUnsignedByte(); dis.skipBytes(1); gpsStatus = dis.readUnsignedByte(); dis.skipBytes(1); gpsFixTime = StreamUtils.readUnsignedInt(dis); gpsLatitude = dis.readInt() / 1000000.0f; gpsLongitude = dis.readInt() / 1000000.0f; gpsAltitude = dis.readInt(); softwareStatus = dis.readUnsignedByte(); dis.skipBytes(1); externalGyroX = dis.readShort() / 100.0f; externalGyroY = dis.readShort() / 100.0f; externalGyroZ = dis.readShort() / 100.0f; externalMagnetometerX = dis.readShort(); externalMagnetometerY = dis.readShort(); externalMagnetometerZ = dis.readShort(); dis.skipBytes(2); } public int getTelemetryId() { return telemetryId; } public void setTelemetryId(int telemetryId) { this.telemetryId = telemetryId; } public int getUnixMillis() { return unixMillis; } public void setUnixMillis(int unixMillis) { this.unixMillis = unixMillis; } public long getUnixSeconds() { return unixSeconds; } public void setUnixSeconds(long unixSeconds) { this.unixSeconds = unixSeconds; } public int getTlmProcessTimeMillis() { return tlmProcessTimeMillis; } public void setTlmProcessTimeMillis(int tlmProcessTimeMillis) { this.tlmProcessTimeMillis = tlmProcessTimeMillis; } public int getPanelXVoltage() { return panelXVoltage; } public void setPanelXVoltage(int panelXVoltage) { this.panelXVoltage = panelXVoltage; } public int getPanelYVoltage() { return panelYVoltage; } public void setPanelYVoltage(int panelYVoltage) { this.panelYVoltage = panelYVoltage; } public int getPanelZVoltage() { return panelZVoltage; } public void setPanelZVoltage(int panelZVoltage) { this.panelZVoltage = panelZVoltage; } public int getPanelXCurrent() { return panelXCurrent; } public void setPanelXCurrent(int panelXCurrent) { this.panelXCurrent = panelXCurrent; } public int getPanelYCurrent() { return panelYCurrent; } public void setPanelYCurrent(int panelYCurrent) { this.panelYCurrent = panelYCurrent; } public int getPanelZCurrent() { return panelZCurrent; } public void setPanelZCurrent(int panelZCurrent) { this.panelZCurrent = panelZCurrent; } public int getEpsBootCause() { return epsBootCause; } public void setEpsBootCause(int epsBootCause) { this.epsBootCause = epsBootCause; } public int getEpsBatteryMode() { return epsBatteryMode; } public void setEpsBatteryMode(int epsBatteryMode) { this.epsBatteryMode = epsBatteryMode; } public int getMpttXTemperature() { return mpttXTemperature; } public void setMpttXTemperature(int mpttXTemperature) { this.mpttXTemperature = mpttXTemperature; } public int getMpttYTemperature() { return mpttYTemperature; } public void setMpttYTemperature(int mpttYTemperature) { this.mpttYTemperature = mpttYTemperature; } public int getEpsTemperature() { return epsTemperature; } public void setEpsTemperature(int epsTemperature) { this.epsTemperature = epsTemperature; } public int getBatter1Temperature() { return batter1Temperature; } public void setBatter1Temperature(int batter1Temperature) { this.batter1Temperature = batter1Temperature; } public int getBatter2Temperature() { return batter2Temperature; } public void setBatter2Temperature(int batter2Temperature) { this.batter2Temperature = batter2Temperature; } public int getBatter3Temperature() { return batter3Temperature; } public void setBatter3Temperature(int batter3Temperature) { this.batter3Temperature = batter3Temperature; } public int getPanelTotalCurrent() { return panelTotalCurrent; } public void setPanelTotalCurrent(int panelTotalCurrent) { this.panelTotalCurrent = panelTotalCurrent; } public int getSystemConsumedCurrent() { return systemConsumedCurrent; } public void setSystemConsumedCurrent(int systemConsumedCurrent) { this.systemConsumedCurrent = systemConsumedCurrent; } public int getBatteryVoltage() { return batteryVoltage; } public void setBatteryVoltage(int batteryVoltage) { this.batteryVoltage = batteryVoltage; } public float getGpsCurrent() { return gpsCurrent; } public void setGpsCurrent(float gpsCurrent) { this.gpsCurrent = gpsCurrent; } public int getEpsBootCount() { return epsBootCount; } public void setEpsBootCount(int epsBootCount) { this.epsBootCount = epsBootCount; } public float getPaTransceiverTemperature() { return paTransceiverTemperature; } public void setPaTransceiverTemperature(float paTransceiverTemperature) { this.paTransceiverTemperature = paTransceiverTemperature; } public long getTransceiverTxCount() { return transceiverTxCount; } public void setTransceiverTxCount(long transceiverTxCount) { this.transceiverTxCount = transceiverTxCount; } public long getTransceiverRxCount() { return transceiverRxCount; } public void setTransceiverRxCount(long transceiverRxCount) { this.transceiverRxCount = transceiverRxCount; } public int getLastRssi() { return lastRssi; } public void setLastRssi(int lastRssi) { this.lastRssi = lastRssi; } public int getRadioBootCounter() { return radioBootCounter; } public void setRadioBootCounter(int radioBootCounter) { this.radioBootCounter = radioBootCounter; } public float getObc1Temperature() { return obc1Temperature; } public void setObc1Temperature(float obc1Temperature) { this.obc1Temperature = obc1Temperature; } public float getObc2Temperature() { return obc2Temperature; } public void setObc2Temperature(float obc2Temperature) { this.obc2Temperature = obc2Temperature; } public float getGyroX() { return gyroX; } public void setGyroX(float gyroX) { this.gyroX = gyroX; } public float getGyroY() { return gyroY; } public void setGyroY(float gyroY) { this.gyroY = gyroY; } public float getGyroZ() { return gyroZ; } public void setGyroZ(float gyroZ) { this.gyroZ = gyroZ; } public int getMagnetometerX() { return magnetometerX; } public void setMagnetometerX(int magnetometerX) { this.magnetometerX = magnetometerX; } public int getMagnetometerY() { return magnetometerY; } public void setMagnetometerY(int magnetometerY) { this.magnetometerY = magnetometerY; } public int getMagnetometerZ() { return magnetometerZ; } public void setMagnetometerZ(int magnetometerZ) { this.magnetometerZ = magnetometerZ; } public float getPanelXpTemperature() { return panelXpTemperature; } public void setPanelXpTemperature(float panelXpTemperature) { this.panelXpTemperature = panelXpTemperature; } public float getPanelYpTemperature() { return panelYpTemperature; } public void setPanelYpTemperature(float panelYpTemperature) { this.panelYpTemperature = panelYpTemperature; } public float getPanelXmTemperature() { return panelXmTemperature; } public void setPanelXmTemperature(float panelXmTemperature) { this.panelXmTemperature = panelXmTemperature; } public float getPanelYmTemperature() { return panelYmTemperature; } public void setPanelYmTemperature(float panelYmTemperature) { this.panelYmTemperature = panelYmTemperature; } public float getPanelZpTemperature() { return panelZpTemperature; } public void setPanelZpTemperature(float panelZpTemperature) { this.panelZpTemperature = panelZpTemperature; } public float getPanelZmTemperature() { return panelZmTemperature; } public void setPanelZmTemperature(float panelZmTemperature) { this.panelZmTemperature = panelZmTemperature; } public int getSunSensorXp() { return sunSensorXp; } public void setSunSensorXp(int sunSensorXp) { this.sunSensorXp = sunSensorXp; } public int getSunSensorYp() { return sunSensorYp; } public void setSunSensorYp(int sunSensorYp) { this.sunSensorYp = sunSensorYp; } public int getSunSensorZp() { return sunSensorZp; } public void setSunSensorZp(int sunSensorZp) { this.sunSensorZp = sunSensorZp; } public int getSunSensorXm() { return sunSensorXm; } public void setSunSensorXm(int sunSensorXm) { this.sunSensorXm = sunSensorXm; } public int getSunSensorYm() { return sunSensorYm; } public void setSunSensorYm(int sunSensorYm) { this.sunSensorYm = sunSensorYm; } public int getSunSensorZm() { return sunSensorZm; } public void setSunSensorZm(int sunSensorZm) { this.sunSensorZm = sunSensorZm; } public int getEpsOutputsStatus() { return epsOutputsStatus; } public void setEpsOutputsStatus(int epsOutputsStatus) { this.epsOutputsStatus = epsOutputsStatus; } public int getObcBootCounter() { return obcBootCounter; } public void setObcBootCounter(int obcBootCounter) { this.obcBootCounter = obcBootCounter; } public int getLedStatus() { return ledStatus; } public void setLedStatus(int ledStatus) { this.ledStatus = ledStatus; } public int getGpsStatus() { return gpsStatus; } public void setGpsStatus(int gpsStatus) { this.gpsStatus = gpsStatus; } public long getGpsFixTime() { return gpsFixTime; } public void setGpsFixTime(long gpsFixTime) { this.gpsFixTime = gpsFixTime; } public float getGpsLatitude() { return gpsLatitude; } public void setGpsLatitude(float gpsLatitude) { this.gpsLatitude = gpsLatitude; } public float getGpsLongitude() { return gpsLongitude; } public void setGpsLongitude(float gpsLongitude) { this.gpsLongitude = gpsLongitude; } public long getGpsAltitude() { return gpsAltitude; } public void setGpsAltitude(long gpsAltitude) { this.gpsAltitude = gpsAltitude; } public int getSoftwareStatus() { return softwareStatus; } public void setSoftwareStatus(int softwareStatus) { this.softwareStatus = softwareStatus; } public float getExternalGyroX() { return externalGyroX; } public void setExternalGyroX(float externalGyroX) { this.externalGyroX = externalGyroX; } public float getExternalGyroY() { return externalGyroY; } public void setExternalGyroY(float externalGyroY) { this.externalGyroY = externalGyroY; } public float getExternalGyroZ() { return externalGyroZ; } public void setExternalGyroZ(float externalGyroZ) { this.externalGyroZ = externalGyroZ; } public int getExternalMagnetometerX() { return externalMagnetometerX; } public void setExternalMagnetometerX(int externalMagnetometerX) { this.externalMagnetometerX = externalMagnetometerX; } public int getExternalMagnetometerY() { return externalMagnetometerY; } public void setExternalMagnetometerY(int externalMagnetometerY) { this.externalMagnetometerY = externalMagnetometerY; } public int getExternalMagnetometerZ() { return externalMagnetometerZ; } public void setExternalMagnetometerZ(int externalMagnetometerZ) { this.externalMagnetometerZ = externalMagnetometerZ; } }
23.126718
74
0.767626
8da47436876c562159b904165a15de38b3fe4260
1,401
package malekire.devilrycraft.util; import jdk.nashorn.internal.ir.Block; import malekire.devilrycraft.Devilrycraft; import malekire.devilrycraft.items.PortableHole; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import malekire.devilrycraft.util.DevilryBlocks.*; import net.minecraft.util.Identifier; import java.util.ArrayList; import static malekire.devilrycraft.util.DevilryBlocks.VIS_CRYSTAL_BLOCK; public class DevilryItems { public static final FabricItemSettings DevilryDefaultItemSetting = new FabricItemSettings().group(ItemGroup.MISC); public static ArrayList<ItemRegistryHelper> items = new ArrayList<>(); public static final BlockItem VIS_CRYSTAL_BLOCK_ITEM = new BlockItem(VIS_CRYSTAL_BLOCK, DevilryDefaultItemSetting); public static final Item PORTABLE_HOLE = new BlockItem(DevilryBlocks.PORTABLE_HOLE_BLOCK, DevilryDefaultItemSetting); static { add(VIS_CRYSTAL_BLOCK_ITEM, "vis_crystal_block"); add(new BlockItem(DevilryBlocks.MAGICAL_CAULDRON_BLOCK, new FabricItemSettings().group(ItemGroup.MISC)), "magical_cauldron"); add(PORTABLE_HOLE, "portable_hole"); } public static void add(Item item2, String name) { items.add(new ItemRegistryHelper(item2, new Identifier(Devilrycraft.MOD_ID, name))); } }
45.193548
133
0.797288
4250e842031d97810743f0e09f92ce08127500ee
14,856
/** * * * The MIT License : http://www.opensource.org/licenses/mit-license.php * Copyright (c) 2010 Kowshik Prakasam * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.android.wordzap.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.EmptyStackException; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Vector; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.android.wordzap.datamodel.LetterGrid; import com.android.wordzap.exceptions.InvalidGridSizeException; import com.android.wordzap.exceptions.InvalidStackOperationException; import com.android.wordzap.exceptions.WordStackOverflowException; /* * JUnit Test Cases for class LetterGrid * */ public class LetterGridTest { private int rows; private int cols; private int negativeRows; private int negativeCols; @Before public void setUp() throws Exception { /* * Generating random positive and negative wordLimit values These will * be used across all WordStack objects created for unit testing */ this.rows = 0; Random rand = new Random(); while (this.rows <= 0) { this.rows = rand.nextInt(); } this.negativeRows = this.rows * -1; this.cols = 0; while (this.cols <= 0) { this.cols = rand.nextInt(); } this.negativeCols = this.cols * -1; } @After public void tearDown() throws Exception { } /* * Tests for the constructor of LetterGrid class */ @Test public void testLetterGrid() throws InvalidGridSizeException { boolean exceptionCaught = false; LetterGrid testGrid; try { testGrid = new LetterGrid(this.rows, this.negativeCols); } catch (InvalidGridSizeException e) { exceptionCaught = true; } assertTrue( "The constructor LetterGrid(rows,cols) DIDNOT throw InvalidGridSizeException when negative columns was passed", exceptionCaught); exceptionCaught = false; try { testGrid = new LetterGrid(this.negativeRows, this.cols); } catch (InvalidGridSizeException e) { exceptionCaught = true; } assertTrue( "The constructor LetterGrid(rows,cols) DIDNOT throw InvalidGridSizeException when negative rows was passed", exceptionCaught); exceptionCaught = false; try { testGrid = new LetterGrid(this.negativeRows, this.negativeCols); } catch (InvalidGridSizeException e) { exceptionCaught = true; } assertTrue( "The constructor LetterGrid(rows,cols) DIDNOT throw InvalidGridSizeException when negative rows and cols were passed", exceptionCaught); exceptionCaught = false; try { testGrid = new LetterGrid(0, this.cols); } catch (InvalidGridSizeException e) { exceptionCaught = true; } assertTrue( "The constructor LetterGrid(rows,cols) DIDNOT throw InvalidGridSizeException when rows was passed with a zero value", exceptionCaught); exceptionCaught = false; try { testGrid = new LetterGrid(this.rows, 0); } catch (InvalidGridSizeException e) { exceptionCaught = true; } assertTrue( "The constructor LetterGrid(rows,cols) DIDNOT throw InvalidGridSizeException when cols was passed with a zero value", exceptionCaught); exceptionCaught = false; try { testGrid = new LetterGrid(0, 0); } catch (InvalidGridSizeException e) { exceptionCaught = true; } assertTrue( "The constructor LetterGrid(rows,cols) DIDNOT throw InvalidGridSizeException when rows and cols were passed a zero value", exceptionCaught); } /* * Tests for getRows() method */ @Test public void testGetRows() throws InvalidGridSizeException { LetterGrid testGrid = new LetterGrid(this.rows, this.cols); assertTrue(this.rows == testGrid.getRowLimit()); } /* * Tests for getCols() method */ @Test public void testGetCols() throws InvalidGridSizeException { LetterGrid testGrid = new LetterGrid(this.rows, this.cols); assertTrue(this.cols == testGrid.getColLimit()); } /* * Tests for putLetter() method */ @Test public void testPutLetterAndIsWordLockedAtTop() throws InvalidGridSizeException, WordStackOverflowException, InvalidStackOperationException { LetterGrid testGrid = this.genSmallGrid(); int randSmallRows = testGrid.getRowLimit(); int randSmallCols = testGrid.getColLimit(); Random rand = new Random(); // Testing putLetter() while randomly populating the entire letter grid char testLetter = genRandomChar(); for (int rowIndex = 0; rowIndex < randSmallRows; rowIndex++) { int randWordLimit; do { randWordLimit = rand.nextInt(randSmallCols); } while (randWordLimit <= 0); String targetWord = ""; for (int colIndex = 0; colIndex < randWordLimit; colIndex++) { Map<String, String> map = testGrid.putLetter(testLetter); targetWord += testLetter; assertEquals(Integer.parseInt(map.get(LetterGrid.ROW_KEY)), rowIndex); assertEquals(Integer.parseInt(map.get(LetterGrid.COL_KEY)), targetWord.length() - 1); } testGrid.lockWordAtTop(); assertTrue(testGrid.isWordLockedAtTop()); assertEquals(testGrid.getWordAtTop(), targetWord); } // Stack overflow expected in testGrid object boolean exceptionCaught = false; try { testGrid.putLetter(testLetter); } catch (WordStackOverflowException overflwEx) { exceptionCaught = true; } assertTrue( "The method putLetter(letter) didnot throw exception : WordStackOverflowException during a simulated stack overflow", exceptionCaught); } /* * Tests for popLetter() and peekLetter() methods */ @Test public void testPopPeekLetters() throws InvalidGridSizeException, EmptyStackException, WordStackOverflowException, InvalidStackOperationException { LetterGrid testGrid = this.genPopulatedSmallGrid(); int numRows = testGrid.getRowLimit(); int numCols = testGrid.getColLimit(); /* * Removing the entire grid of letters and checking if popLetter() works * fine for each row. */ boolean exceptionCaught = false; for (int rowIndex = numRows - 1; rowIndex >= 0; rowIndex--) { String wordAtTop = testGrid.getWordAtTop(); testGrid.unlockWordAtTop(); for (int colIndex = numCols - 1; colIndex >= 0; colIndex--) { Map<String, String> peekMap = testGrid.peekLetter(); Map<String, String> popMap = testGrid.popLetter(); char letterAtTop = peekMap.get(LetterGrid.LETTER_KEY).charAt(0); char poppedLetter = popMap.get(LetterGrid.LETTER_KEY).charAt(0); assertEquals(Integer.parseInt(popMap.get(LetterGrid.ROW_KEY)), rowIndex); assertEquals(Integer.parseInt(popMap.get(LetterGrid.COL_KEY)), colIndex); assertEquals(poppedLetter, wordAtTop.charAt(colIndex)); assertEquals(Integer.parseInt(peekMap.get(LetterGrid.ROW_KEY)), rowIndex); assertEquals(Integer.parseInt(peekMap.get(LetterGrid.COL_KEY)), colIndex); assertEquals(letterAtTop, wordAtTop.charAt(colIndex)); assertEquals(testGrid.getWordAtTop(), wordAtTop.substring(0, colIndex)); } /* * Checking if popLetter() throws EmptyStackException */ exceptionCaught = false; try { testGrid.popLetter(); } catch (EmptyStackException ex) { exceptionCaught = true; } assertTrue( "popLetter() FAILED to throw exception when empty stack at the top was popped", exceptionCaught); /* * Checking if peekLetter() throws EmptyStackException */ exceptionCaught = false; try { testGrid.peekLetter(); } catch (EmptyStackException ex) { exceptionCaught = true; } assertTrue( "peekLetter() FAILED to throw exception when empty stack at the top was peeked at", exceptionCaught); testGrid.removeWordAtTop(); } /* * Internal grid of letters is empty now and popLetter() should throw * EmptyStackException */ exceptionCaught = false; try { testGrid.popLetter(); } catch (EmptyStackException ex) { exceptionCaught = true; } assertTrue( "popLetter() FAILED to throw exception when empty internal stack of words in LetterGrid was popped", exceptionCaught); /* * Internal grid of letters is empty now and peekLetter() should throw * EmptyStackException */ exceptionCaught = false; try { testGrid.peekLetter(); } catch (EmptyStackException ex) { exceptionCaught = true; } assertTrue( "peekLetter() FAILED to throw exception when empty internal stack of words in LetterGrid was peeked at", exceptionCaught); } /* * Tests for getTopWord() method */ @Test public void testGetTopWord() throws EmptyStackException, InvalidStackOperationException, WordStackOverflowException { LetterGrid testGrid = this.genPopulatedSmallGrid(); int numRows = testGrid.getRowLimit(); int numCols = testGrid.getColLimit(); for (int rowIndex = 0; rowIndex < numRows; rowIndex++) { String wordBeforePop = testGrid.getWordAtTop(); testGrid.unlockWordAtTop(); String poppedWord = ""; for (int colIndex = numCols - 1; colIndex >= 0; colIndex--) { char poppedLetter = testGrid.popLetter().get( LetterGrid.LETTER_KEY).charAt(0); poppedWord = poppedLetter + poppedWord; } testGrid.removeWordAtTop(); assertEquals(poppedWord, wordBeforePop); } /* * Internal grid of letters is empty now and getTopWord() should throw * EmptyStackException */ boolean exceptionCaught = false; try { testGrid.getWordAtTop(); } catch (EmptyStackException ex) { exceptionCaught = true; } assertTrue( "getTopWord() FAILED to throw exception when there is an empty internal stack of words in LetterGrid", exceptionCaught); } /* * Tests getWordList() method */ @Test public void testGetWordList() throws WordStackOverflowException, InvalidStackOperationException { LetterGrid testGrid = this.genPopulatedSmallGrid(); int numRows = testGrid.getRowLimit(); int numCols = testGrid.getColLimit(); List<String> wordList = testGrid.getWordList(); List<String> poppedWordList = new Vector<String>(); for (int rowIndex = 0; rowIndex < numRows; rowIndex++) { String word = testGrid.getWordAtTop(); poppedWordList.add(word); testGrid.removeWordAtTop(); } /* * Reversing popped stack so that it can be compared with output of * LetterGrid.getWordList() */ Collections.reverse(poppedWordList); assertEquals(poppedWordList, wordList); } /* * Tests clearGrid() method */ @Test public void testClearGrid() throws WordStackOverflowException, InvalidStackOperationException { LetterGrid testGrid = this.genPopulatedSmallGrid(); testGrid.clearGrid(); boolean exceptionCaught = false; try { testGrid.popLetter(); } catch (EmptyStackException ex) { exceptionCaught = true; } assertTrue( "clearGrid() method FAILED to clear grid and therefore popLetter() method FAILED to throw exception when there is NO empty internal stack of words in LetterGrid", exceptionCaught); } /* * Tests lockWordAtTop() and unlockWordAtTop() */ @Test public void testLockAndUnlockWordAtTop() throws WordStackOverflowException, InvalidStackOperationException { LetterGrid testGrid = this.genPopulatedSmallGrid(); int numRows = testGrid.getRowLimit(); int numCols = testGrid.getColLimit(); boolean exceptionCaught = false; testGrid.lockWordAtTop(); for (int rowIndex = 0; rowIndex < numRows; rowIndex++) { try { testGrid.popLetter(); } catch (InvalidStackOperationException ex) { exceptionCaught = true; } assertTrue( "lockWordAtTop() FAILED to lock the word at top of stack. So, popLetter() succeeded and FAILED to throw InvalidOperationException.", exceptionCaught); testGrid.unlockWordAtTop(); testGrid.popLetter(); testGrid.removeWordAtTop(); } } /* * Tests removeWordAtTop() */ @Test public void testRemoveWordAtTop() throws EmptyStackException, InvalidStackOperationException, WordStackOverflowException { LetterGrid testGrid = this.genPopulatedSmallGrid(); int numRows = testGrid.getRowLimit(); int numCols = testGrid.getColLimit(); /* * Removing each word and comparing it with the list representation if * LetterGrid */ List<String> wordList = testGrid.getWordList(); for (int rowIndex = numRows - 1; rowIndex >= 0; rowIndex--) { assertEquals(testGrid.removeWordAtTop(), wordList.get(rowIndex)); } } // Generate a random character private char genRandomChar() { char letter = 'A'; int offset = new Random().nextInt(); if (offset < 0) { offset *= -1; } offset = offset % 26; return (char) (letter + offset); } // Returns a populated small grid of letters private LetterGrid genPopulatedSmallGrid() throws WordStackOverflowException, InvalidStackOperationException { LetterGrid testGrid = this.genSmallGrid(); int numRows = testGrid.getRowLimit(); int numCols = testGrid.getColLimit(); char letter = genRandomChar(); for (int rowIndex = 0; rowIndex < numRows; rowIndex++) { for (int colIndex = 0; colIndex < numCols; colIndex++) { testGrid.putLetter(letter); letter = genRandomChar(); } /* * Lock word at top after completing word at top of stack */ testGrid.lockWordAtTop(); } return testGrid; } // Generates a small grid of letters of size not greater than 200 X 200 private LetterGrid genSmallGrid() { // Generating random small values for rows and cols int randSmallRows, randSmallCols; Random rand = new Random(); do { randSmallRows = rand.nextInt(200); } while (randSmallRows <= 0); do { randSmallCols = rand.nextInt(200); } while (randSmallCols <= 0); LetterGrid testGrid = null; try { testGrid = new LetterGrid(randSmallRows, randSmallCols); } catch (InvalidGridSizeException ex) { } return testGrid; } }
28.297143
166
0.719305
3486a81eddfe272ae2f8e402acb83bdc1589eac2
467
package com.touhidapps.databindingexample.model; public class Person { public String firstName; public String lastName; public String imgUrl; public Person(String firstName, String lastName, String imgUrl) { this.firstName = firstName; this.lastName = lastName; this.imgUrl = imgUrl; } public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } }
23.35
69
0.670236
c32be047243e5cbabd01dffda989d98f0d4f916e
849
package org.fz.nettyx.codec; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageCodec; import java.nio.charset.Charset; import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * @author fengbinbin * @version 1.0 * @since 2021/4/9 16:35 */ @Slf4j @RequiredArgsConstructor public class StringMessageCodec extends ByteToMessageCodec<String> { private final Charset charset; @Override protected void encode(ChannelHandlerContext channelHandlerContext, String msg, ByteBuf byteBuf) { byteBuf.writeBytes(msg.getBytes(charset)); } @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) { list.add(byteBuf.toString(charset)); } }
25.727273
108
0.763251
c1c9e5bf4decebea436421f7e6f851efb92de0ee
729
package org.openscience.sherlock.dbservice.dataset.db.service; import org.openscience.sherlock.dbservice.dataset.db.model.MultiplicitySectionsSettingsRecord; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public interface MultiplicitySectionsSettingsService { Mono<Long> count(); Flux<MultiplicitySectionsSettingsRecord> findAll(); Mono<MultiplicitySectionsSettingsRecord> findById(final String id); Mono<MultiplicitySectionsSettingsRecord> findByNucleus(final String nucleus); // insertions/deletions Mono<MultiplicitySectionsSettingsRecord> insert( final MultiplicitySectionsSettingsRecord multiplicitySectionsSettingsRecord); Mono<Void> deleteAll(); }
30.375
94
0.806584
a87b4013470a073b78c449f20d46a58a08cde4c7
85
package com.gewei.commons.ueditor.define; public enum ActionState { UNKNOW_ERROR }
14.166667
41
0.8
3d79d333e13de96832a43aa2bacb612d383936c0
1,566
/* * Copyright (c) 2020. * Created by YoloSanta * Created On 10/22/20, 1:23 AM */ package net.hcriots.hcfactions.persist.maps; import net.hcriots.hcfactions.persist.PersistMap; import org.bson.types.ObjectId; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class ChatSpyMap extends PersistMap<List<ObjectId>> { public ChatSpyMap() { super("ChatSpy", "ChatSpy"); } @Override public String getRedisValue(List<ObjectId> teams) { StringBuilder stringBuilder = new StringBuilder(); for (ObjectId team : teams) { stringBuilder.append(team).append(","); } if (stringBuilder.length() > 1) { stringBuilder.setLength(stringBuilder.length() - 1); } return (stringBuilder.toString()); } @Override public List<ObjectId> getJavaObject(String str) { List<ObjectId> results = new ArrayList<>(); for (String split : str.split(",")) { if (split.equals("")) { continue; } results.add(new ObjectId(split)); } return (results); } @Override public void setCredits(int i) { } @Override public Object getMongoValue(List<ObjectId> teams) { return (teams); } public List<ObjectId> getChatSpy(UUID check) { return (contains(check) ? getValue(check) : new ArrayList<ObjectId>()); } public void setChatSpy(UUID update, List<ObjectId> teams) { updateValueAsync(update, teams); } }
22.371429
79
0.607918
6b497315b9c175e9b141ab093b3479fe6c32d889
4,525
/* * Copyright 2018 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.pipelinetemplate.tasks.v2; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.spinnaker.orca.api.pipeline.RetryableTask; import com.netflix.spinnaker.orca.api.pipeline.TaskResult; import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus; import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution; import com.netflix.spinnaker.orca.front50.Front50Service; import com.netflix.spinnaker.orca.pipeline.model.StageExecutionImpl; import com.netflix.spinnaker.orca.pipelinetemplate.v2schema.model.V2PipelineTemplate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.commons.codec.binary.Base64; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import retrofit.client.Response; @Component public class UpdateV2PipelineTemplateTask implements RetryableTask, SaveV2PipelineTemplateTask { @Autowired(required = false) private Front50Service front50Service; @Autowired private ObjectMapper pipelineTemplateObjectMapper; @SuppressWarnings("unchecked") @Override public TaskResult execute(StageExecution stage) { if (front50Service == null) { throw new UnsupportedOperationException( "Front50 is not enabled, no way to save pipeline templates. Fix this by setting front50.enabled: true"); } if (!stage.getContext().containsKey("pipelineTemplate")) { throw new IllegalArgumentException("Missing required task parameter (pipelineTemplate)"); } if (!(stage.getContext().get("pipelineTemplate") instanceof String) || !Base64.isBase64((String) stage.getContext().get("pipelineTemplate"))) { throw new IllegalArgumentException( "'pipelineTemplate' context key must be a base64-encoded string: Ensure you're on the most recent version of gate"); } List<String> missingParams = new ArrayList<>(); if (!stage.getContext().containsKey("id")) { missingParams.add("id"); } if (!stage.getContext().containsKey("pipelineTemplate")) { missingParams.add("pipelineTemplate"); } if (!missingParams.isEmpty()) { throw new IllegalArgumentException( "Missing required task parameter (" + StringUtils.arrayToCommaDelimitedString(missingParams.toArray()) + ")"); } V2PipelineTemplate pipelineTemplate = ((StageExecutionImpl) stage) .decodeBase64( "/pipelineTemplate", V2PipelineTemplate.class, pipelineTemplateObjectMapper); validate(pipelineTemplate); String tag = (String) stage.getContext().get("tag"); Response response = front50Service.updateV2PipelineTemplate( (String) stage.getContext().get("id"), tag, (Map<String, Object>) ((StageExecutionImpl) stage) .decodeBase64("/pipelineTemplate", Map.class, pipelineTemplateObjectMapper)); // TODO(jacobkiefer): Reduce duplicated code. String templateId = StringUtils.isEmpty(tag) ? pipelineTemplate.getId() : String.format("%s:%s", pipelineTemplate.getId(), tag); Map<String, Object> outputs = new HashMap<>(); outputs.put("notification.type", "updatepipelinetemplate"); outputs.put("pipelineTemplate.id", templateId); if (response.getStatus() == HttpStatus.OK.value()) { return TaskResult.builder(ExecutionStatus.SUCCEEDED).context(outputs).build(); } return TaskResult.builder(ExecutionStatus.TERMINAL).context(outputs).build(); } @Override public long getBackoffPeriod() { return 15000; } @Override public long getTimeout() { return TimeUnit.MINUTES.toMillis(1); } }
36.788618
126
0.722652
6b16877a7f52fd35c435421e49099347e45470e4
2,755
/******************************************************************************* * Copyright 2013 SAP AG * * 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.sap.core.odata.core.edm.provider; import com.sap.core.odata.api.edm.EdmAnnotatable; import com.sap.core.odata.api.edm.EdmAnnotations; import com.sap.core.odata.api.edm.EdmAssociation; import com.sap.core.odata.api.edm.EdmAssociationEnd; import com.sap.core.odata.api.edm.EdmException; import com.sap.core.odata.api.edm.EdmMultiplicity; import com.sap.core.odata.api.edm.EdmTypeKind; import com.sap.core.odata.api.edm.provider.Association; import com.sap.core.odata.api.edm.provider.AssociationEnd; public class EdmAssociationImplProv extends EdmNamedImplProv implements EdmAssociation, EdmAnnotatable { private Association association; private String namespace; public EdmAssociationImplProv(final EdmImplProv edm, final Association association, final String namespace) throws EdmException { super(edm, association.getName()); this.association = association; this.namespace = namespace; } @Override public String getNamespace() throws EdmException { return namespace; } @Override public EdmTypeKind getKind() { return EdmTypeKind.ASSOCIATION; } @Override public EdmAssociationEnd getEnd(final String role) throws EdmException { AssociationEnd end = association.getEnd1(); if (end.getRole().equals(role)) { return new EdmAssociationEndImplProv(edm, end); } end = association.getEnd2(); if (end.getRole().equals(role)) { return new EdmAssociationEndImplProv(edm, end); } return null; } @Override public EdmAnnotations getAnnotations() throws EdmException { return new EdmAnnotationsImplProv(association.getAnnotationAttributes(), association.getAnnotationElements()); } public EdmMultiplicity getEndMultiplicity(final String role) { if (association.getEnd1().getRole().equals(role)) { return association.getEnd1().getMultiplicity(); } if (association.getEnd2().getRole().equals(role)) { return association.getEnd2().getMultiplicity(); } return null; } }
34.012346
131
0.704537
12252f760807411f9058a84726168214d97aa632
2,685
package io.iconator.core.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import io.iconator.commons.model.db.SaleTier.StatusType; import javax.validation.constraints.NotNull; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; @JsonIgnoreProperties(ignoreUnknown = true) public class SaleTierResponse { @JsonProperty("tierNo") private long tierNo; @JsonProperty("name") private String name; @JsonProperty("type") private StatusType type; @JsonProperty("startDate") private Date startDate; @JsonProperty("endDate") private Date endDate; @JsonProperty("discount") private BigDecimal discount; @JsonProperty("amount") private BigInteger amount; @JsonProperty("maxAmount") private BigInteger maxAmount; public SaleTierResponse() { } public SaleTierResponse(long tierNo, @NotNull String name, @NotNull StatusType statusType, @NotNull Date startDate, @NotNull Date endDate, @NotNull BigDecimal discount, @NotNull BigInteger amount, @NotNull BigInteger maxAmount) { this.tierNo = tierNo; this.name = name; this.type = statusType; this.startDate = startDate; this.endDate = endDate; this.discount = discount; this.amount = amount; this.maxAmount = maxAmount; } public long getTierNo() { return tierNo; } public String getName() { return name; } public StatusType getType() { return type; } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } public BigDecimal getDiscount() { return discount; } public BigInteger getAmount() { return amount; } public BigInteger getMaxAmount() { return maxAmount; } public void setTierNo(long tierNo) { this.tierNo = tierNo; } public void setName(String name) { this.name = name; } public void setType(StatusType type) { this.type = type; } public void setStartDate(Date startDate) { this.startDate = startDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public void setDiscount(BigDecimal discount) { this.discount = discount; } public void setAmount(BigInteger amount) { this.amount = amount; } public void setMaxAmount(BigInteger maxAmount) { this.maxAmount = maxAmount; } }
22.190083
94
0.634264
bb59e1ef17750879b2f711819e186c47deebd7e5
8,063
package org.springframework.context.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import example.scannable.DefaultNamedComponent; import org.junit.Test; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import static org.junit.Assert.*; public class AnnotationBeanNameGeneratorTests { private AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator(); /** * 测试 基于指定bean上注解的value值,对bean进行命名。 * @see AnnotationBeanNameGenerator#generateBeanName(org.springframework.beans.factory.config.BeanDefinition, org.springframework.beans.factory.support.BeanDefinitionRegistry) * @see AnnotationBeanNameGenerator#determineBeanNameFromAnnotation(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition) * @see AnnotationConfigUtils#attributesFor(org.springframework.core.type.AnnotatedTypeMetadata, java.lang.String) */ @Test public void generateBeanNameWithNamedComponent() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentWithName.class); String beanName = beanNameGenerator.generateBeanName(bd, null); assertNotNull("The generated beanName must *never* be null.", beanName); assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName)); assertEquals("walden", beanName); } /** * 测试同时使用 @Service("jordan") 和 @Component("walden") 情况下,生成bean名称触发异常。 */ @Test(expected = IllegalStateException.class) public void testGenerateBeanNameWithMultipartComponent() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(MultipartComponentWithName.class); beanNameGenerator.generateBeanName(bd, null); } /** * 测试,指定类再没有注解的情况下,也 走buildDefaultBeanName()分支 */ @Test public void testGenerateBeanNameNoAnnotationComponent() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(NoAnnotationComponent.class); String beanName = beanNameGenerator.generateBeanName(bd, null); assertEquals("annotationBeanNameGeneratorTests.NoAnnotationComponent", beanName); } /** * 测试 基于指定bean上注解的value 的默认值 (String value() default "thoreau";),对bean进行命名。 */ @Test public void generateBeanNameWithDefaultNamedComponent() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(DefaultNamedComponent.class); String beanName = beanNameGenerator.generateBeanName(bd, null); assertNotNull("The generated beanName must *never* be null.", beanName); assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName)); assertEquals("thoreau", beanName); } /** * 测试 获取获取指定类的简名。 * 由于determineBeanNameFromAnnotation()返回" ",所以走buildDefaultBeanName()分支 * @see AnnotationBeanNameGenerator#determineBeanNameFromAnnotation(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition) * @see AnnotationBeanNameGenerator#buildDefaultBeanName(org.springframework.beans.factory.config.BeanDefinition) */ @Test public void generateBeanNameWithNamedComponentWhereTheNameIsBlank() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentWithBlankName.class); String beanName = beanNameGenerator.generateBeanName(bd, null); assertNotNull("The generated beanName must *never* be null.", beanName); assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName)); String expectedGeneratedBeanName = beanNameGenerator.buildDefaultBeanName(bd);// annotationBeanNameGeneratorTests.ComponentWithBlankName assertEquals(expectedGeneratedBeanName, beanName); assertEquals("annotationBeanNameGeneratorTests.ComponentWithBlankName", beanName); } /** * 测试 获取获取指定类的简名。 * 由于determineBeanNameFromAnnotation()返回 null ,所以走buildDefaultBeanName()分支 */ @Test public void generateBeanNameWithAnonymousComponentYieldsGeneratedBeanName() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnonymousComponent.class); String beanName = beanNameGenerator.generateBeanName(bd, null); assertNotNull("The generated beanName must *never* be null.", beanName); assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName)); String expectedGeneratedBeanName = beanNameGenerator.buildDefaultBeanName(bd); assertEquals(expectedGeneratedBeanName, beanName); assertEquals("annotationBeanNameGeneratorTests.AnonymousComponent", beanName); } // 测试 @Service("henry") 注解生成的bean名称 @Test public void generateBeanNameFromMetaComponentWithStringValue() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentFromStringMeta.class); String beanName = beanNameGenerator.generateBeanName(bd, null); assertEquals("henry", beanName); } /** * 测试 * 由于 注解的value值不是String类,所以走buildDefaultBeanName()分支 */ @Test public void generateBeanNameFromMetaComponentWithNonStringValue() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentFromNonStringMeta.class); String beanName = beanNameGenerator.generateBeanName(bd, null); assertEquals("annotationBeanNameGeneratorTests.ComponentFromNonStringMeta", beanName); } /** * @since 4.0.1 * @see https://jira.spring.io/browse/SPR-11360 */ @Test public void generateBeanNameFromComposedControllerAnnotationWithoutName() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComposedControllerAnnotationWithoutName.class); String beanName = beanNameGenerator.generateBeanName(bd, null); String expectedGeneratedBeanName = beanNameGenerator.buildDefaultBeanName(bd); assertEquals(expectedGeneratedBeanName, beanName); assertEquals("annotationBeanNameGeneratorTests.ComposedControllerAnnotationWithoutName", beanName); } /** * @since 4.0.1 * @see https://jira.spring.io/browse/SPR-11360 */ @Test public void generateBeanNameFromComposedControllerAnnotationWithBlankName() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComposedControllerAnnotationWithBlankName.class); String beanName = beanNameGenerator.generateBeanName(bd, null); String expectedGeneratedBeanName = beanNameGenerator.buildDefaultBeanName(bd); assertEquals(expectedGeneratedBeanName, beanName); } /** * @since 4.0.1 * @see https://jira.spring.io/browse/SPR-11360 */ @Test public void generateBeanNameFromComposedControllerAnnotationWithStringValue() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComposedControllerAnnotationWithStringValue.class); String beanName = beanNameGenerator.generateBeanName(bd, null); assertEquals("restController", beanName); } private static class NoAnnotationComponent {} @Service("jordan") @Component("walden") private static class MultipartComponentWithName {} @Component("walden") private static class ComponentWithName {} @Component(" ") private static class ComponentWithBlankName {} @Component private static class AnonymousComponent {} @Service("henry") private static class ComponentFromStringMeta {} @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Component public @interface NonStringMetaComponent { long value(); } @NonStringMetaComponent(123) private static class ComponentFromNonStringMeta {} /** * @see org.springframework.web.bind.annotation.RestController */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Controller public static @interface TestRestController { String value() default ""; } @TestRestController public static class ComposedControllerAnnotationWithoutName {} @TestRestController(" ") public static class ComposedControllerAnnotationWithBlankName {} @TestRestController("restController") public static class ComposedControllerAnnotationWithStringValue {} }
40.114428
176
0.811733
0e47608ccd8eb327561b002b1323fa369e7e55d3
7,866
package com.braintreepayments.api; import android.content.Context; import com.braintreepayments.api.interfaces.BraintreeErrorListener; import com.braintreepayments.api.interfaces.HttpResponseCallback; import com.braintreepayments.api.internal.ManifestValidator; import com.braintreepayments.api.models.Authorization; import com.braintreepayments.api.models.Configuration; import com.braintreepayments.api.models.ThreeDSecurePostalAddress; import com.braintreepayments.api.models.ThreeDSecureRequest; import com.braintreepayments.testutils.TestConfigurationBuilder; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import static com.braintreepayments.testutils.FixturesHelper.stringFromFixture; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.spy; @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*", "org.json.*", "javax.crypto.*" }) @PrepareForTest({ ManifestValidator.class }) public class ThreeDSecureUnitTest { @Rule public PowerMockRule mPowerMockRule = new PowerMockRule(); private MockFragmentBuilder mMockFragmentBuilder; private BraintreeFragment mFragment; @Before public void setup() throws Exception { spy(ManifestValidator.class); doReturn(true).when(ManifestValidator.class, "isUrlSchemeDeclaredInAndroidManifest", any(Context.class), anyString(), any(Class.class)); Configuration configuration = new TestConfigurationBuilder() .threeDSecureEnabled(true) .buildConfiguration(); mMockFragmentBuilder = new MockFragmentBuilder() .authorization(Authorization.fromString(stringFromFixture("base_64_client_token.txt"))) .configuration(configuration); mFragment = mMockFragmentBuilder.build(); mFragment.addListener(new BraintreeErrorListener() { @Override public void onError(Exception error) { fail(error.getMessage()); } }); } @Test public void performVerification_sendsAllParamatersInLookupRequest() throws InterruptedException, JSONException { ThreeDSecureRequest request = new ThreeDSecureRequest() .nonce("a-nonce") .amount("1.00") .shippingMethod("01") .mobilePhoneNumber("8101234567") .email("test@example.com") .billingAddress(new ThreeDSecurePostalAddress() .firstName("Joe") .lastName("Guy") .streetAddress("555 Smith Street") .extendedAddress("#5") .locality("Oakland") .region("CA") .postalCode("12345") .countryCodeAlpha2("US") .phoneNumber("12345678")); ThreeDSecure.performVerification(mFragment, request); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(mFragment.getHttpClient()).post(anyString(), captor.capture(), any(HttpResponseCallback.class)); JSONObject body = new JSONObject(captor.getValue()); assertEquals("1.00", body.getString("amount")); JSONObject customer = body.getJSONObject("customer"); assertEquals("8101234567", customer.getString("mobilePhoneNumber")); assertEquals("test@example.com", customer.getString("email")); assertEquals("01", customer.getString("shippingMethod")); JSONObject billingAddress = customer.getJSONObject("billingAddress"); assertEquals("Joe", billingAddress.getString("firstName")); assertEquals("Guy", billingAddress.getString("lastName")); assertEquals("555 Smith Street", billingAddress.getString("line1")); assertEquals("#5", billingAddress.getString("line2")); assertEquals("Oakland", billingAddress.getString("city")); assertEquals("CA", billingAddress.getString("state")); assertEquals("12345", billingAddress.getString("postalCode")); assertEquals("US", billingAddress.getString("countryCode")); assertEquals("12345678", billingAddress.getString("phoneNumber")); } @Test public void performVerification_sendsMinimumParamatersInLookupRequest() throws InterruptedException, JSONException { ThreeDSecureRequest request = new ThreeDSecureRequest() .nonce("a-nonce") .amount("1.00"); ThreeDSecure.performVerification(mFragment, request); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(mFragment.getHttpClient()).post(anyString(), captor.capture(), any(HttpResponseCallback.class)); JSONObject body = new JSONObject(captor.getValue()); assertEquals("1.00", body.getString("amount")); JSONObject customer = body.getJSONObject("customer"); assertTrue(customer.isNull("mobilePhoneNumber")); assertTrue(customer.isNull("email")); assertTrue(customer.isNull("shippingMethod")); assertTrue(customer.isNull("billingAddress")); } @Test public void performVerification_sendsPartialParamatersInLookupRequest() throws InterruptedException, JSONException { ThreeDSecureRequest request = new ThreeDSecureRequest() .nonce("a-nonce") .amount("1.00") .email("test@example.com") .billingAddress(new ThreeDSecurePostalAddress() .firstName("Joe") .lastName("Guy") .streetAddress("555 Smith Street") .locality("Oakland") .region("CA") .postalCode("12345") .countryCodeAlpha2("US")); ThreeDSecure.performVerification(mFragment, request); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(mFragment.getHttpClient()).post(anyString(), captor.capture(), any(HttpResponseCallback.class)); JSONObject body = new JSONObject(captor.getValue()); assertEquals("1.00", body.getString("amount")); JSONObject customer = body.getJSONObject("customer"); assertTrue(customer.isNull("mobilePhoneNumber")); assertEquals("test@example.com", customer.getString("email")); assertTrue(customer.isNull("shippingMethod")); JSONObject billingAddress = customer.getJSONObject("billingAddress"); assertEquals("Joe", billingAddress.getString("firstName")); assertEquals("Guy", billingAddress.getString("lastName")); assertEquals("555 Smith Street", billingAddress.getString("line1")); assertTrue(billingAddress.isNull("line2")); assertEquals("Oakland", billingAddress.getString("city")); assertEquals("CA", billingAddress.getString("state")); assertEquals("12345", billingAddress.getString("postalCode")); assertEquals("US", billingAddress.getString("countryCode")); assertTrue(billingAddress.isNull("phoneNumber")); } }
43.458564
144
0.680651
85149a5a55598ec2230ca4ddbaa801f1d8863b76
1,755
/** * Siox_Segmentation plug-in for ImageJ and Fiji. * 2009 Ignacio Arganda-Carreras, Johannes Schindelin, Stephan Saalfeld * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt ) * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ package siox; import ij.IJ; import ij.ImagePlus; import ij.plugin.PlugIn; /** * Fiji plugin to run SIOX: Simple Interactive Object Extraction. * * @author Ignacio Arganda-Carreras (ignacio.arganda at gmail.com) * */ public class Siox_Segmentation implements PlugIn { /** input image to be segmented */ private ImagePlus inputImage = null; public static void main(String[] args) { ij.ImageJ.main(args); IJ.run("Leaf (36K)"); Siox_Segmentation s = new Siox_Segmentation(); s.run(null); } //@Override public void run(String args) { this.inputImage = IJ.getImage(); if(inputImage.getType() != ImagePlus.COLOR_RGB) { IJ.error("SIOX Segmentation", "SIOX works only on RGB images"); return; } if(inputImage.getNSlices() > 1) { IJ.error("SIOX Segmentation", "SIOX does not support stacks"); return; } new SegmentationGUI(this.inputImage); } }// end class Siox_Segmentation
24.041096
86
0.711681
9fd20faa36cef4b21380f3279aaf24e72dcd0bee
898
package com.planet.shop.admin.service.impl; import com.planet.shop.mbg.mapper.UmsMemberLevelMapper; import com.planet.shop.mbg.model.UmsMemberLevel; import com.planet.shop.mbg.model.UmsMemberLevelExample; import com.planet.shop.admin.service.UmsMemberLevelService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 会员等级管理Service实现类 * Created by macro on 2018/4/26. */ @Service public class UmsMemberLevelServiceImpl implements UmsMemberLevelService { @Autowired private UmsMemberLevelMapper memberLevelMapper; @Override public List<UmsMemberLevel> list(Integer defaultStatus) { UmsMemberLevelExample example = new UmsMemberLevelExample(); example.createCriteria().andDefaultStatusEqualTo(defaultStatus); return memberLevelMapper.selectByExample(example); } }
33.259259
73
0.796214
65eac618516559a406064dde9838be7de8313f8f
304
package com.ref.interfaces.activityDiagram; public interface IActivity extends INamedElement{ IActivityDiagram getActivityDiagram(); void setActivityDiagram(IActivityDiagram activityDiagram); IActivityNode[] getActivityNodes(); void setName(String nameAD); IPartition [] getPartitions(); }
19
59
0.802632
866d92295f2d0d08bf27b510be08c94610f3c251
1,858
package com.bjit.finalproject.service; import com.bjit.finalproject.model.Employee; import com.bjit.finalproject.model.Leaves; import com.bjit.finalproject.repository.EmployeesRepository; import com.bjit.finalproject.repository.LeavesRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; @Service public class LeavesService { @Autowired LeavesRepository leavesRepository; public List<Leaves> getAll() { List<Leaves> leaves = new ArrayList<Leaves>(); // leavesRepository.findAll().forEach(e -> leaves.add(e)); leavesRepository.findAll().forEach(e -> { int i = e.getNumberOfDays(); e.setTotalDays(e.getTotalDays() + i); leaves.add(e); }); return leaves; } public Leaves getLeavesById(int id) { return leavesRepository.findById(id).get(); } public void saveOrUpdate(Leaves leaves) { long diff = leaves.getEndDate().getTime()-leaves.getStartDate().getTime(); leaves.setNumberOfDays(Math.toIntExact(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS))); if(leaves.getRequestType().equals("Leave Request")){ leaves.setNumberOfDays(leaves.getNumberOfDays()*(-1)); } // List<Leaves> leavesList = new ArrayList<Leaves>(); // leavesRepository.findAll().forEach(e -> { // int i = e.getNumberOfDays(); // e.setTotalDays(e.getTotalDays() + i); //// leavesList.add(e); // }); leavesRepository.save(leaves); } public void delete(int id) { leavesRepository.deleteById(id); } public void update(Leaves leaves, int id) { leavesRepository.save(leaves); } }
30.966667
100
0.662002
8e82ec022b26099e128553790446cf6a9081033a
3,400
/* =========================================================================== * Copyright (C) 2017 CapsicoHealth Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package wanda.ldap; import java.io.IOException; import java.io.PrintWriter; import java.time.ZonedDateTime; import java.util.List; import tilda.utils.json.JSONUtil; public class LdapGroup { private String name; private String samaccountname; private String cn; private String description; private String email; private String dn; private ZonedDateTime whenCreated; private ZonedDateTime whenChanged; public static void printGroups( List<LdapGroup> groups, PrintWriter Out) throws IOException { boolean First = true; Out.println("[ "); for (LdapGroup ldapGroup : groups) { if (First == true) { Out.print(" "); First = false; } else Out.print(" ,"); ldapGroup.toJSON(Out); } Out.println(" ]"); } public void toJSON(PrintWriter Out) throws IOException { Out.println(" {"); JSONUtil.print(Out, "name", true, this.name); JSONUtil.print(Out, "samaccountname", false, this.samaccountname); JSONUtil.print(Out, "cn", false, this.cn); JSONUtil.print(Out, "description", false, this.description); JSONUtil.print(Out, "email", false, this.email); JSONUtil.print(Out, "whenCreated", false, this.whenCreated); JSONUtil.print(Out, "whenChanged", false, this.whenChanged); Out.println(" }"); } public LdapGroup(String cn) { super(); this.cn = cn; } public String getSamaccountname() { return samaccountname; } public void setSamaccountname(String samaccountname) { this.samaccountname = samaccountname; } public String getDn() { return dn; } public void setDn(String dn) { this.dn = dn; } public String getCn() { return cn; } public void setCn(String cn) { this.cn = cn; } public String toString(){ return "Name: " + getName() + " samaccountname: " + getSamaccountname() + " eMail: " + getEmail() + " CN: " + getCn() + " DN: " + getDn() + " description: " + getDescription(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public ZonedDateTime getWhenCreated() { return whenCreated; } public void setWhenCreated(ZonedDateTime whenCreated) { this.whenCreated = whenCreated; } public ZonedDateTime getWhenChanged() { return whenChanged; } public void setWhenChanged(ZonedDateTime whenChanged) { this.whenChanged = whenChanged; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
26.356589
179
0.656176
008afb2a99f87f3494960876a7159260310bbb75
5,649
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2018 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import android.os.Parcel; import com.google.gson.JsonObject; import com.kaltura.client.Params; import com.kaltura.client.enums.Language; import com.kaltura.client.enums.TranscriptProviderType; import com.kaltura.client.utils.GsonParser; import com.kaltura.client.utils.request.MultiRequestBuilder; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") @MultiRequestBuilder.Tokenizer(TranscriptAsset.Tokenizer.class) public class TranscriptAsset extends AttachmentAsset { public interface Tokenizer extends AttachmentAsset.Tokenizer { String accuracy(); String humanVerified(); String language(); String providerType(); } /** * The accuracy of the transcript - values between 0 and 1 */ private Double accuracy; /** * Was verified by human or machine */ private Boolean humanVerified; /** * The language of the transcript */ private Language language; /** * The provider of the transcript */ private TranscriptProviderType providerType; // accuracy: public Double getAccuracy(){ return this.accuracy; } public void setAccuracy(Double accuracy){ this.accuracy = accuracy; } public void accuracy(String multirequestToken){ setToken("accuracy", multirequestToken); } // humanVerified: public Boolean getHumanVerified(){ return this.humanVerified; } public void setHumanVerified(Boolean humanVerified){ this.humanVerified = humanVerified; } public void humanVerified(String multirequestToken){ setToken("humanVerified", multirequestToken); } // language: public Language getLanguage(){ return this.language; } public void setLanguage(Language language){ this.language = language; } public void language(String multirequestToken){ setToken("language", multirequestToken); } // providerType: public TranscriptProviderType getProviderType(){ return this.providerType; } public void setProviderType(TranscriptProviderType providerType){ this.providerType = providerType; } public void providerType(String multirequestToken){ setToken("providerType", multirequestToken); } public TranscriptAsset() { super(); } public TranscriptAsset(JsonObject jsonObject) throws APIException { super(jsonObject); if(jsonObject == null) return; // set members values: accuracy = GsonParser.parseDouble(jsonObject.get("accuracy")); humanVerified = GsonParser.parseBoolean(jsonObject.get("humanVerified")); language = Language.get(GsonParser.parseString(jsonObject.get("language"))); providerType = TranscriptProviderType.get(GsonParser.parseString(jsonObject.get("providerType"))); } public Params toParams() { Params kparams = super.toParams(); kparams.add("objectType", "KalturaTranscriptAsset"); kparams.add("accuracy", this.accuracy); kparams.add("humanVerified", this.humanVerified); kparams.add("language", this.language); kparams.add("providerType", this.providerType); return kparams; } public static final Creator<TranscriptAsset> CREATOR = new Creator<TranscriptAsset>() { @Override public TranscriptAsset createFromParcel(Parcel source) { return new TranscriptAsset(source); } @Override public TranscriptAsset[] newArray(int size) { return new TranscriptAsset[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeValue(this.accuracy); dest.writeValue(this.humanVerified); dest.writeInt(this.language == null ? -1 : this.language.ordinal()); dest.writeInt(this.providerType == null ? -1 : this.providerType.ordinal()); } public TranscriptAsset(Parcel in) { super(in); this.accuracy = (Double)in.readValue(Double.class.getClassLoader()); this.humanVerified = (Boolean)in.readValue(Boolean.class.getClassLoader()); int tmpLanguage = in.readInt(); this.language = tmpLanguage == -1 ? null : Language.values()[tmpLanguage]; int tmpProviderType = in.readInt(); this.providerType = tmpProviderType == -1 ? null : TranscriptProviderType.values()[tmpProviderType]; } }
31.038462
108
0.679589
0288acee9cbedafbc66b15296e1e745591e9046c
57,584
/* * 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.idea.refactoring.changeSignature; import com.intellij.codeInsight.NullableNotNullManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.OverridingMethodsSearch; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.changeSignature.*; import com.intellij.refactoring.rename.ResolveSnapshotProvider; import com.intellij.refactoring.rename.UnresolvableCollisionUsageInfo; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.refactoring.util.MoveRenameUsageInfo; import com.intellij.refactoring.util.RefactoringUIUtil; import com.intellij.refactoring.util.TextOccurrencesUtil; import com.intellij.usageView.UsageInfo; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashSet; import com.intellij.util.containers.MultiMap; import kotlin.KotlinPackage; import kotlin.Unit; import kotlin.jvm.functions.Function1; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.analyzer.AnalyzerPackage; import org.jetbrains.kotlin.asJava.AsJavaPackage; import org.jetbrains.kotlin.asJava.KotlinLightMethod; import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.idea.JetFileType; import org.jetbrains.kotlin.idea.caches.resolve.ResolvePackage; import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde; import org.jetbrains.kotlin.idea.codeInsight.JetFileReferencesResolver; import org.jetbrains.kotlin.idea.core.refactoring.RefactoringPackage; import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.*; import org.jetbrains.kotlin.idea.references.JetSimpleNameReference; import org.jetbrains.kotlin.idea.references.ReferencesPackage; import org.jetbrains.kotlin.idea.search.usagesSearch.UsagesSearchPackage; import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers; import org.jetbrains.kotlin.kdoc.psi.impl.KDocName; import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor; import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.psi.*; import org.jetbrains.kotlin.psi.psiUtil.PsiUtilPackage; import org.jetbrains.kotlin.psi.typeRefHelpers.TypeRefHelpersPackage; import org.jetbrains.kotlin.renderer.DescriptorRenderer; import org.jetbrains.kotlin.resolve.BindingContext; import org.jetbrains.kotlin.resolve.BindingTraceContext; import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils; import org.jetbrains.kotlin.resolve.DescriptorUtils; import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage; import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall; import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo; import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind; import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode; import org.jetbrains.kotlin.resolve.scopes.JetScope; import org.jetbrains.kotlin.resolve.scopes.UsageLocation; import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue; import org.jetbrains.kotlin.resolve.scopes.receivers.ThisReceiver; import org.jetbrains.kotlin.types.JetType; import org.jetbrains.kotlin.types.TypeUtils; import java.util.*; public class JetChangeSignatureUsageProcessor implements ChangeSignatureUsageProcessorEx { // This is special 'PsiElement' whose purpose is to wrap JetMethodDescriptor so that it can be kept in the usage list private static class OriginalJavaMethodDescriptorWrapper extends UsageInfo { JetMethodDescriptor originalJavaMethodDescriptor; public OriginalJavaMethodDescriptorWrapper(@NotNull PsiElement element) { super(element); } } private static class DummyJetChangeInfo extends JetChangeInfo { public DummyJetChangeInfo( @NotNull PsiElement method, @NotNull JetMethodDescriptor methodDescriptor ) { super(methodDescriptor, "", null, "", Visibilities.INTERNAL, Collections.<JetParameterInfo>emptyList(), null, method, Collections.<PsiElement>emptyList()); } } @Nullable private static OriginalJavaMethodDescriptorWrapper getOriginalJavaMethodDescriptorWrapper(@NotNull UsageInfo[] usages) { return KotlinPackage.firstOrNull(KotlinPackage.filterIsInstance(usages, OriginalJavaMethodDescriptorWrapper.class)); } // It's here to prevent O(usage_count^2) performance private boolean initializedOriginalDescriptor; @Override public UsageInfo[] findUsages(ChangeInfo info) { initializedOriginalDescriptor = false; Set<UsageInfo> result = new HashSet<UsageInfo>(); result.add(new OriginalJavaMethodDescriptorWrapper(info.getMethod())); if (info instanceof JetChangeInfo) { findAllMethodUsages((JetChangeInfo) info, result); } else { findSAMUsages(info, result); findConstructorDelegationUsages(info, result); findKotlinOverrides(info, result); if (info instanceof JavaChangeInfo) { findKotlinCallers((JavaChangeInfo) info, result); } } return result.toArray(new UsageInfo[result.size()]); } private static void findAllMethodUsages(JetChangeInfo changeInfo, Set<UsageInfo> result) { for (UsageInfo functionUsageInfo : ChangeSignaturePackage.getAffectedCallables(changeInfo)) { if (functionUsageInfo instanceof JetCallableDefinitionUsage) { findOneMethodUsages((JetCallableDefinitionUsage) functionUsageInfo, changeInfo, result); } else if (functionUsageInfo instanceof KotlinCallerUsage) { findCallerUsages((KotlinCallerUsage) functionUsageInfo, changeInfo, result); } else { result.add(functionUsageInfo); boolean propagationTarget = functionUsageInfo instanceof CallerUsageInfo || (functionUsageInfo instanceof OverriderUsageInfo && !((OverriderUsageInfo) functionUsageInfo).isOriginalOverrider()); PsiElement callee = functionUsageInfo.getElement(); if (callee == null) continue; SearchScope scope = callee.getUseScope(); if (scope instanceof GlobalSearchScope) { scope = GlobalSearchScope.getScopeRestrictedByFileTypes((GlobalSearchScope) scope, JetFileType.INSTANCE); } for (PsiReference reference : ReferencesSearch.search(callee, scope)) { PsiElement element = reference.getElement(); JetCallElement callElement = PsiTreeUtil.getParentOfType(element, JetCallElement.class); JetExpression calleeExpression = callElement != null ? callElement.getCalleeExpression() : null; if (calleeExpression != null && PsiTreeUtil.isAncestor(calleeExpression, element, false)) { result.add(propagationTarget ? new KotlinCallerCallUsage(callElement) : new JetFunctionCallUsage(callElement, changeInfo.getMethodDescriptor().getOriginalPrimaryCallable())); } } } } } private static void findCallerUsages(KotlinCallerUsage callerUsage, JetChangeInfo changeInfo, final Set<UsageInfo> result) { result.add(callerUsage); JetNamedDeclaration element = callerUsage.getElement(); if (element == null) return; for (PsiReference ref : ReferencesSearch.search(element, element.getUseScope())) { PsiElement refElement = ref.getElement(); JetCallElement callElement = PsiTreeUtil.getParentOfType(refElement, JetCallElement.class); if (callElement != null && PsiTreeUtil.isAncestor(callElement.getCalleeExpression(), refElement, false)) { result.add(new KotlinCallerCallUsage(callElement)); } } JetElement body = ChangeSignaturePackage.getDeclarationBody(element); final Set<String> newParameterNames = KotlinPackage.mapTo( changeInfo.getNonReceiverParameters(), new HashSet<String>(), new Function1<JetParameterInfo, String>() { @Override public String invoke(JetParameterInfo info) { return info.getName(); } } ); if (body != null) { final DeclarationDescriptor callerDescriptor = ResolvePackage.resolveToDescriptor(element); final BindingContext context = ResolvePackage.analyze(body); body.accept( new JetTreeVisitorVoid() { @Override public void visitSimpleNameExpression(@NotNull JetSimpleNameExpression expression) { final String currentName = expression.getReferencedName(); if (!newParameterNames.contains(currentName)) return; ResolvedCall<? extends CallableDescriptor> resolvedCall = CallUtilPackage.getResolvedCall(expression, context); if (resolvedCall == null) return; if (resolvedCall.getExplicitReceiverKind() != ExplicitReceiverKind.NO_EXPLICIT_RECEIVER) return; CallableDescriptor resultingDescriptor = resolvedCall.getResultingDescriptor(); if (!(resultingDescriptor instanceof VariableDescriptor)) return; // Do not report usages of duplicated parameter if (resultingDescriptor instanceof ValueParameterDescriptor && resultingDescriptor.getContainingDeclaration() == callerDescriptor) return; JetElement callElement = resolvedCall.getCall().getCallElement(); ReceiverValue receiver = resolvedCall.getExtensionReceiver(); if (!(receiver instanceof ThisReceiver)) { receiver = resolvedCall.getDispatchReceiver(); } if (receiver instanceof ThisReceiver) { result.add(new JetImplicitThisUsage(callElement, ((ThisReceiver) receiver).getDeclarationDescriptor())); } else if (!receiver.exists()) { result.add( new UnresolvableCollisionUsageInfo(callElement, null) { @Override public String getDescription() { return "There is already a variable '" + currentName + "' in " + IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_IN_TYPES.render(callerDescriptor) + ". It will conflict with the new parameter."; } } ); } } } ); } } private static void findOneMethodUsages( @NotNull JetCallableDefinitionUsage<?> functionUsageInfo, final JetChangeInfo changeInfo, final Set<UsageInfo> result ) { boolean isInherited = functionUsageInfo.isInherited(); if (isInherited) { result.add(functionUsageInfo); } PsiElement functionPsi = functionUsageInfo.getElement(); if (functionPsi == null) return; for (PsiReference reference : ReferencesSearch.search(functionPsi, functionPsi.getUseScope())) { PsiElement element = reference.getElement(); if (functionPsi instanceof JetClass && reference.resolve() != functionPsi) continue; if (element instanceof JetReferenceExpression) { PsiElement parent = element.getParent(); if (parent instanceof JetCallExpression) result.add(new JetFunctionCallUsage((JetCallExpression) parent, functionUsageInfo)); else if (parent instanceof JetUserType && parent.getParent() instanceof JetTypeReference) { parent = parent.getParent().getParent(); if (parent instanceof JetConstructorCalleeExpression && parent.getParent() instanceof JetDelegatorToSuperCall) result.add(new JetFunctionCallUsage((JetDelegatorToSuperCall)parent.getParent(), functionUsageInfo)); } else if (element instanceof JetSimpleNameExpression && (functionPsi instanceof JetProperty || functionPsi instanceof JetParameter)) { result.add(new JetPropertyCallUsage((JetSimpleNameExpression) element)); } } } String oldName = ChangeSignaturePackage.getOldName(changeInfo); if (oldName != null) TextOccurrencesUtil.findNonCodeUsages(functionPsi, oldName, true, true, changeInfo.getNewName(), result); List<JetParameter> oldParameters = PsiUtilPackage.getValueParameters((JetNamedDeclaration) functionPsi); JetParameterInfo newReceiverInfo = changeInfo.getReceiverParameterInfo(); for (JetParameterInfo parameterInfo : changeInfo.getNewParameters()) { if (parameterInfo.getOldIndex() >= 0 && parameterInfo.getOldIndex() < oldParameters.size()) { JetParameter oldParam = oldParameters.get(parameterInfo.getOldIndex()); String oldParamName = oldParam.getName(); if (parameterInfo == newReceiverInfo || (oldParamName != null && !oldParamName.equals(parameterInfo.getName()))) { for (PsiReference reference : ReferencesSearch.search(oldParam, oldParam.getUseScope())) { PsiElement element = reference.getElement(); if ((element instanceof JetSimpleNameExpression || element instanceof KDocName) && !(element.getParent() instanceof JetValueArgumentName)) // Usages in named arguments of the calls usage will be changed when the function call is changed { JetParameterUsage parameterUsage = new JetParameterUsage((JetElement) element, parameterInfo, functionUsageInfo); result.add(parameterUsage); } } } } } if (functionPsi instanceof JetFunction && newReceiverInfo != changeInfo.getMethodDescriptor().getReceiver()) { findOriginalReceiversUsages(functionUsageInfo, result, changeInfo); } if (functionPsi instanceof JetClass && ((JetClass) functionPsi).isEnum()) { for (JetDeclaration declaration : ((JetClass) functionPsi).getDeclarations()) { if (declaration instanceof JetEnumEntry && ((JetEnumEntry) declaration).getDelegationSpecifiers().isEmpty()) { result.add(new JetEnumEntryWithoutSuperCallUsage((JetEnumEntry) declaration)); } } } UsagesSearchPackage.processDelegationCallConstructorUsages( functionPsi, functionPsi.getUseScope(), new Function1<JetConstructorDelegationCall, Unit>() { @Override public Unit invoke(JetConstructorDelegationCall element) { result.add(new JetConstructorDelegationCallUsage(element, changeInfo)); return null; } } ); } private static void processInternalReferences( JetCallableDefinitionUsage functionUsageInfo, JetTreeVisitor<BindingContext> visitor ) { JetFunction jetFunction = (JetFunction) functionUsageInfo.getDeclaration(); JetExpression body = jetFunction.getBodyExpression(); if (body != null) { body.accept(visitor, ResolvePackage.analyze(body, BodyResolveMode.FULL)); } for (JetParameter parameter : jetFunction.getValueParameters()) { JetExpression defaultValue = parameter.getDefaultValue(); if (defaultValue != null) { defaultValue.accept(visitor, ResolvePackage.analyze(defaultValue, BodyResolveMode.FULL)); } } } private static void findOriginalReceiversUsages( @NotNull final JetCallableDefinitionUsage<?> functionUsageInfo, @NotNull final Set<UsageInfo> result, @NotNull final JetChangeInfo changeInfo ) { final JetParameterInfo originalReceiverInfo = changeInfo.getMethodDescriptor().getReceiver(); final CallableDescriptor callableDescriptor = functionUsageInfo.getOriginalCallableDescriptor(); processInternalReferences( functionUsageInfo, new JetTreeVisitor<BindingContext>() { private void processExplicitThis( @NotNull JetSimpleNameExpression expression, @NotNull ReceiverParameterDescriptor receiverDescriptor ) { if (originalReceiverInfo != null && !changeInfo.hasParameter(originalReceiverInfo)) return; if (!(expression.getParent() instanceof JetThisExpression)) return; if (receiverDescriptor == callableDescriptor.getExtensionReceiverParameter()) { assert originalReceiverInfo != null : "No original receiver info provided: " + functionUsageInfo.getDeclaration().getText(); result.add(new JetParameterUsage(expression, originalReceiverInfo, functionUsageInfo)); } else { ClassifierDescriptor targetDescriptor = receiverDescriptor.getType().getConstructor().getDeclarationDescriptor(); assert targetDescriptor != null : "Receiver type has no descriptor: " + functionUsageInfo.getDeclaration().getText(); result.add(new JetNonQualifiedOuterThisUsage((JetThisExpression) expression.getParent(), targetDescriptor)); } } private void processImplicitThis( @NotNull JetElement callElement, @NotNull ThisReceiver receiverValue ) { DeclarationDescriptor targetDescriptor = receiverValue.getDeclarationDescriptor(); if (targetDescriptor == callableDescriptor) { assert originalReceiverInfo != null : "No original receiver info provided: " + functionUsageInfo.getDeclaration().getText(); result.add(new JetImplicitThisToParameterUsage(callElement, originalReceiverInfo, functionUsageInfo)); } else { result.add(new JetImplicitThisUsage(callElement, targetDescriptor)); } } @Override public Void visitSimpleNameExpression(@NotNull JetSimpleNameExpression expression, BindingContext context) { ResolvedCall<? extends CallableDescriptor> resolvedCall = CallUtilPackage.getResolvedCall(expression, context); if (resolvedCall == null) return null; CallableDescriptor resultingDescriptor = resolvedCall.getResultingDescriptor(); if (resultingDescriptor instanceof ReceiverParameterDescriptor) { processExplicitThis(expression, (ReceiverParameterDescriptor) resultingDescriptor); return null; } ReceiverValue receiverValue = resolvedCall.getExtensionReceiver(); if (!receiverValue.exists()) { receiverValue = resolvedCall.getDispatchReceiver(); } if (receiverValue instanceof ThisReceiver) { processImplicitThis(resolvedCall.getCall().getCallElement(), (ThisReceiver) receiverValue); } return null; } } ); } private static void findSAMUsages(ChangeInfo changeInfo, Set<UsageInfo> result) { PsiElement method = changeInfo.getMethod(); if (!RefactoringPackage.isTrueJavaMethod(method)) return; FunctionDescriptor methodDescriptor = ResolvePackage.getJavaMethodDescriptor((PsiMethod) method); assert methodDescriptor != null; DeclarationDescriptor containingDescriptor = methodDescriptor.getContainingDeclaration(); if (!(containingDescriptor instanceof JavaClassDescriptor)) return; if (((JavaClassDescriptor) containingDescriptor).getFunctionTypeForSamInterface() == null) return; PsiClass samClass = ((PsiMethod) method).getContainingClass(); if (samClass == null) return; for (PsiReference ref : ReferencesSearch.search(samClass)) { if (!(ref instanceof JetSimpleNameReference)) continue; JetSimpleNameExpression callee = ((JetSimpleNameReference) ref).getExpression(); JetCallExpression callExpression = PsiTreeUtil.getParentOfType(callee, JetCallExpression.class); if (callExpression == null || callExpression.getCalleeExpression() != callee) continue; List<? extends ValueArgument> arguments = callExpression.getValueArguments(); if (arguments.size() != 1) continue; JetExpression argExpression = arguments.get(0).getArgumentExpression(); if (!(argExpression instanceof JetFunctionLiteralExpression)) continue; BindingContext context = ResolvePackage.analyze(callExpression, BodyResolveMode.FULL); JetFunctionLiteral functionLiteral = ((JetFunctionLiteralExpression) argExpression).getFunctionLiteral(); FunctionDescriptor functionDescriptor = context.get(BindingContext.FUNCTION, functionLiteral); assert functionDescriptor != null : "No descriptor for " + functionLiteral.getText(); JetType samCallType = context.getType(callExpression); if (samCallType == null) continue; result.add(new DeferredJavaMethodOverrideOrSAMUsage(functionLiteral, functionDescriptor, samCallType)); } } private static void findConstructorDelegationUsages(@NotNull ChangeInfo changeInfo, @NotNull final Set<UsageInfo> result) { PsiElement method = changeInfo.getMethod(); if (!(RefactoringPackage.isTrueJavaMethod(method))) return; PsiMethod psiMethod = (PsiMethod) method; if (!psiMethod.isConstructor()) return; UsagesSearchPackage.processDelegationCallConstructorUsages( psiMethod, psiMethod.getUseScope(), new Function1<JetConstructorDelegationCall, Unit>() { @Override public Unit invoke(JetConstructorDelegationCall element) { result.add(new JavaConstructorDeferredUsageInDelegationCall(element)); return null; } } ); } private static void findKotlinOverrides(ChangeInfo changeInfo, Set<UsageInfo> result) { PsiElement method = changeInfo.getMethod(); if (!RefactoringPackage.isTrueJavaMethod(method)) return; for (PsiMethod overridingMethod : OverridingMethodsSearch.search((PsiMethod) method)) { PsiElement unwrappedElement = AsJavaPackage.getNamedUnwrappedElement(overridingMethod); if (!(unwrappedElement instanceof JetNamedFunction)) continue; JetNamedFunction function = (JetNamedFunction) unwrappedElement; FunctionDescriptor functionDescriptor = (FunctionDescriptor) ResolvePackage.resolveToDescriptor(function); result.add(new DeferredJavaMethodOverrideOrSAMUsage(function, functionDescriptor, null)); findDeferredUsagesOfParameters(changeInfo, result, function, functionDescriptor); } } private static void findKotlinCallers(JavaChangeInfo changeInfo, Set<UsageInfo> result) { PsiElement method = changeInfo.getMethod(); if (!RefactoringPackage.isTrueJavaMethod(method)) return; for (PsiMethod primaryCaller : changeInfo.getMethodsToPropagateParameters()) { addDeferredCallerIfPossible(result, primaryCaller); for (PsiMethod overridingCaller : OverridingMethodsSearch.search(primaryCaller)) { addDeferredCallerIfPossible(result, overridingCaller); } } } private static void addDeferredCallerIfPossible(Set<UsageInfo> result, PsiMethod overridingCaller) { PsiElement unwrappedElement = AsJavaPackage.getNamedUnwrappedElement(overridingCaller); if (unwrappedElement instanceof JetFunction || unwrappedElement instanceof JetClass) { result.add(new DeferredJavaMethodKotlinCallerUsage((JetNamedDeclaration) unwrappedElement)); } } private static void findDeferredUsagesOfParameters( ChangeInfo changeInfo, Set<UsageInfo> result, JetNamedFunction function, FunctionDescriptor functionDescriptor ) { final JetCallableDefinitionUsage<?> functionInfoForParameters = new JetCallableDefinitionUsage<PsiElement>(function, functionDescriptor, null, null); List<JetParameter> oldParameters = PsiUtilPackage.getValueParameters(function); ParameterInfo[] parameters = changeInfo.getNewParameters(); for (int i = 0; i < parameters.length; i++) { final int paramIndex = i; ParameterInfo parameterInfo = parameters[paramIndex]; if (parameterInfo.getOldIndex() >= 0 && parameterInfo.getOldIndex() < oldParameters.size()) { JetParameter oldParam = oldParameters.get(parameterInfo.getOldIndex()); String oldParamName = oldParam.getName(); if (oldParamName != null && !oldParamName.equals(parameterInfo.getName())) { for (PsiReference reference : ReferencesSearch.search(oldParam, oldParam.getUseScope())) { final PsiElement element = reference.getElement(); if ((element instanceof JetSimpleNameExpression || element instanceof KDocName) && !(element.getParent() instanceof JetValueArgumentName)) // Usages in named arguments of the calls usage will be changed when the function call is changed { result.add( new JavaMethodDeferredKotlinUsage<JetElement>((JetElement) element) { @NotNull @Override public JavaMethodKotlinUsageWithDelegate<JetElement> resolve(@NotNull JetChangeInfo javaMethodChangeInfo) { return new JavaMethodKotlinUsageWithDelegate<JetElement>((JetElement) element, javaMethodChangeInfo) { @NotNull @Override public JetUsageInfo<JetElement> getDelegateUsage() { return new JetParameterUsage((JetElement) element, getJavaMethodChangeInfo().getNewParameters()[paramIndex], functionInfoForParameters); } }; } } ); } } } } } } @Override public MultiMap<PsiElement, String> findConflicts(ChangeInfo info, Ref<UsageInfo[]> refUsages) { MultiMap<PsiElement, String> result = new MultiMap<PsiElement, String>(); // Delete OverriderUsageInfo and CallerUsageInfo for Kotlin declarations since they can't be processed correctly // TODO (OverriderUsageInfo only): Drop when OverriderUsageInfo.getElement() gets deleted UsageInfo[] usageInfos = refUsages.get(); List<UsageInfo> adjustedUsages = KotlinPackage.filterNot( usageInfos, new Function1<UsageInfo, Boolean>() { @Override public Boolean invoke(UsageInfo info) { return getOverriderOrCaller(info) instanceof KotlinLightMethod; } } ); if (adjustedUsages.size() < usageInfos.length) { refUsages.set(adjustedUsages.toArray(new UsageInfo[adjustedUsages.size()])); } if (!(info instanceof JetChangeInfo)) return result; Set<String> parameterNames = new HashSet<String>(); JetChangeInfo changeInfo = (JetChangeInfo) info; PsiElement function = info.getMethod(); PsiElement element = function != null ? function : changeInfo.getContext(); BindingContext bindingContext = ResolvePackage.analyze((JetElement) element, BodyResolveMode.FULL); CallableDescriptor oldDescriptor = ChangeSignaturePackage.getOriginalBaseFunctionDescriptor(changeInfo); DeclarationDescriptor containingDeclaration = oldDescriptor.getContainingDeclaration(); JetScope parametersScope = null; if (oldDescriptor instanceof ConstructorDescriptor && containingDeclaration instanceof ClassDescriptorWithResolutionScopes) parametersScope = ((ClassDescriptorWithResolutionScopes) containingDeclaration).getScopeForInitializerResolution(); else if (function instanceof JetFunction) parametersScope = org.jetbrains.kotlin.idea.refactoring.RefactoringPackage.getBodyScope((JetFunction) function, bindingContext); JetScope callableScope = org.jetbrains.kotlin.idea.refactoring.RefactoringPackage.getContainingScope(oldDescriptor, bindingContext); JetMethodDescriptor.Kind kind = ChangeSignaturePackage.getKind(changeInfo); if (!kind.getIsConstructor() && callableScope != null && !info.getNewName().isEmpty()) { Name newName = Name.identifier(info.getNewName()); Collection<? extends CallableDescriptor> conflicts = oldDescriptor instanceof FunctionDescriptor ? callableScope.getFunctions(newName, UsageLocation.NO_LOCATION) : callableScope.getProperties(newName, UsageLocation.NO_LOCATION); for (CallableDescriptor conflict : conflicts) { if (conflict == oldDescriptor) continue; PsiElement conflictElement = DescriptorToSourceUtils.descriptorToDeclaration(conflict); if (conflictElement == changeInfo.getMethod()) continue; if (getCallableParameterTypes(conflict).equals(getCallableParameterTypes(oldDescriptor))) { result.putValue(conflictElement, "Function already exists: '" + DescriptorRenderer.SHORT_NAMES_IN_TYPES.render(conflict) + "'"); break; } } } for (JetParameterInfo parameter : changeInfo.getNonReceiverParameters()) { JetValVar valOrVar = parameter.getValOrVar(); String parameterName = parameter.getName(); if (!parameterNames.add(parameterName)) { result.putValue(element, "Duplicating parameter '" + parameterName + "'"); } if (parametersScope != null) { if (kind == JetMethodDescriptor.Kind.PRIMARY_CONSTRUCTOR && valOrVar != JetValVar.None) { for (VariableDescriptor property : parametersScope.getProperties(Name.identifier(parameterName), UsageLocation.NO_LOCATION)) { PsiElement propertyDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(property); if (propertyDeclaration != null && !(propertyDeclaration.getParent() instanceof JetParameterList)) { result.putValue(propertyDeclaration, "Duplicating property '" + parameterName + "'"); break; } } } else if (function instanceof JetFunction) { VariableDescriptor variable = parametersScope.getLocalVariable(Name.identifier(parameterName)); if (variable != null && !(variable instanceof ValueParameterDescriptor)) { PsiElement conflictElement = DescriptorToSourceUtils.descriptorToDeclaration(variable); result.putValue(conflictElement, "Duplicating local variable '" + parameterName + "'"); } } } } JetParameterInfo newReceiverInfo = changeInfo.getReceiverParameterInfo(); JetParameterInfo originalReceiverInfo = changeInfo.getMethodDescriptor().getReceiver(); if (function instanceof JetCallableDeclaration && newReceiverInfo != originalReceiverInfo) { findReceiverIntroducingConflicts(result, function, newReceiverInfo); findInternalExplicitReceiverConflicts(refUsages.get(), result, originalReceiverInfo); findThisLabelConflicts((JetChangeInfo) info, refUsages, result, changeInfo, function); } for (UsageInfo usageInfo : usageInfos) { if (!(usageInfo instanceof KotlinCallerUsage)) continue; JetNamedDeclaration caller = (JetNamedDeclaration) usageInfo.getElement(); DeclarationDescriptor callerDescriptor = ResolvePackage.resolveToDescriptor(caller); findParameterDuplicationInCaller(result, changeInfo, caller, callerDescriptor); } return result; } private static void findParameterDuplicationInCaller( MultiMap<PsiElement, String> result, JetChangeInfo changeInfo, JetNamedDeclaration caller, DeclarationDescriptor callerDescriptor ) { List<JetParameter> valueParameters = PsiUtilPackage.getValueParameters(caller); Map<String, JetParameter> existingParameters = KotlinPackage.toMap( valueParameters, new Function1<JetParameter, String>() { @Override public String invoke(JetParameter parameter) { return parameter.getName(); } } ); for (JetParameterInfo parameterInfo : changeInfo.getNonReceiverParameters()) { if (!(parameterInfo.getIsNewParameter())) continue; String name = parameterInfo.getName(); JetParameter parameter = existingParameters.get(name); if (parameter != null) { result.putValue(parameter, "There is already a parameter '" + name + "' in " + IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_IN_TYPES.render(callerDescriptor) + ". It will conflict with the new parameter."); } } } private static void findThisLabelConflicts( JetChangeInfo info, Ref<UsageInfo[]> refUsages, MultiMap<PsiElement, String> result, JetChangeInfo changeInfo, PsiElement function ) { JetPsiFactory psiFactory = new JetPsiFactory(function.getProject()); for (UsageInfo usageInfo : refUsages.get()) { if (!(usageInfo instanceof JetParameterUsage)) continue; String newExprText = ((JetParameterUsage) usageInfo).getReplacementText(changeInfo); if (!newExprText.startsWith("this@")) continue; if (usageInfo.getElement() instanceof KDocName) continue; // TODO support converting parameter to receiver in KDoc JetExpression originalExpr = (JetExpression) usageInfo.getElement(); JetScope scope = ResolvePackage.analyze(originalExpr, BodyResolveMode.FULL) .get(BindingContext.RESOLUTION_SCOPE, originalExpr); if (scope == null) continue; JetThisExpression newExpr = (JetThisExpression) psiFactory.createExpression(newExprText); JetSimpleNameExpression labelExpr = newExpr.getTargetLabel(); if (labelExpr == null) continue; BindingContext newContext = AnalyzerPackage.analyzeInContext(newExpr, scope, new BindingTraceContext(), DataFlowInfo.EMPTY, TypeUtils.NO_EXPECTED_TYPE, DescriptorUtils.getContainingModule(scope.getContainingDeclaration())); if (newContext.get(BindingContext.AMBIGUOUS_LABEL_TARGET, labelExpr) != null) { result.putValue( originalExpr, "Parameter reference can't be safely replaced with " + newExprText + " since " + labelExpr.getText() + " is ambiguous in this context" ); } } } private static void findInternalExplicitReceiverConflicts( UsageInfo[] usages, MultiMap<PsiElement, String> result, JetParameterInfo originalReceiverInfo ) { if (originalReceiverInfo == null) { for (UsageInfo usageInfo : usages) { if (!(usageInfo instanceof JetFunctionCallUsage || usageInfo instanceof JetPropertyCallUsage)) continue; JetElement callElement = (JetElement) usageInfo.getElement(); if (callElement == null) continue; PsiElement parent = callElement.getParent(); if (parent instanceof JetQualifiedExpression && ((JetQualifiedExpression) parent).getSelectorExpression() == callElement) { String message = "Explicit receiver is already present in call element: " + CommonRefactoringUtil.htmlEmphasize(parent.getText()); result.putValue(callElement, message); } } } } private static void findReceiverIntroducingConflicts( MultiMap<PsiElement, String> result, PsiElement callable, JetParameterInfo newReceiverInfo ) { if (newReceiverInfo != null && (callable instanceof JetNamedFunction) && ((JetNamedFunction) callable).getBodyExpression() != null) { Map<JetReferenceExpression, BindingContext> noReceiverRefToContext = KotlinPackage.filter( JetFileReferencesResolver.INSTANCE$.resolve((JetNamedFunction) callable, true, true), new Function1<Map.Entry<? extends JetReferenceExpression, ? extends BindingContext>, Boolean>() { @Override public Boolean invoke(Map.Entry<? extends JetReferenceExpression, ? extends BindingContext> entry) { ResolvedCall<?> resolvedCall = CallUtilPackage.getResolvedCall(entry.getKey(), entry.getValue()); return resolvedCall != null && !resolvedCall.getDispatchReceiver().exists() && !resolvedCall.getExtensionReceiver().exists(); } } ); JetPsiFactory psiFactory = new JetPsiFactory(callable.getProject()); JetFile tempFile = RefactoringPackage.createTempCopy( (JetFile) callable.getContainingFile(), new Function1<String, String>() { @Override public String invoke(String s) { return s; } } ); JetNamedFunction functionWithReceiver = PsiTreeUtil.getParentOfType(tempFile.findElementAt(callable.getTextOffset()), JetNamedFunction.class); JetTypeReference receiverTypeRef = psiFactory.createType(newReceiverInfo.getCurrentTypeText()); TypeRefHelpersPackage.setReceiverTypeReference(functionWithReceiver, receiverTypeRef); //noinspection ConstantConditions BindingContext newContext = ResolvePackage.analyze(functionWithReceiver.getBodyExpression(), BodyResolveMode.FULL); //noinspection ConstantConditions int originalOffset = ((JetNamedFunction) callable).getBodyExpression().getTextOffset(); JetExpression newBody = functionWithReceiver.getBodyExpression(); for (Map.Entry<JetReferenceExpression, BindingContext> entry : noReceiverRefToContext.entrySet()) { JetReferenceExpression originalRef = entry.getKey(); BindingContext originalContext = entry.getValue(); //noinspection ConstantConditions JetReferenceExpression newRef = PsiTreeUtil.getParentOfType( newBody.findElementAt(originalRef.getTextOffset() - originalOffset), JetReferenceExpression.class ); ResolvedCall<?> newResolvedCall = CallUtilPackage.getResolvedCall(newRef, newContext); if (newResolvedCall == null || newResolvedCall.getExtensionReceiver().exists() || newResolvedCall.getDispatchReceiver().exists()) { //noinspection ConstantConditions CallableDescriptor descriptor = CallUtilPackage.getResolvedCall(originalRef, originalContext).getCandidateDescriptor(); PsiElement declaration = DescriptorToSourceUtilsIde.INSTANCE$.getAnyDeclaration(callable.getProject(), descriptor); String prefix = declaration != null ? RefactoringUIUtil.getDescription(declaration, true) : originalRef.getText(); result.putValue( originalRef, KotlinPackage.capitalize(prefix + " will no longer be accessible after signature change") ); } } } } private static List<JetType> getCallableParameterTypes(CallableDescriptor descriptor) { return ContainerUtil.map(descriptor.getValueParameters(), new Function<ValueParameterDescriptor, JetType>() { @Override public JetType fun(ValueParameterDescriptor descriptor) { return descriptor.getType(); } }); } private static boolean isJavaMethodUsage(UsageInfo usageInfo) { // MoveRenameUsageInfo corresponds to non-Java usage of Java method return usageInfo instanceof JavaMethodDeferredKotlinUsage || usageInfo instanceof MoveRenameUsageInfo; } @Nullable private static UsageInfo createReplacementUsage(UsageInfo originalUsageInfo, JetChangeInfo javaMethodChangeInfo, UsageInfo[] allUsages) { if (originalUsageInfo instanceof JavaMethodDeferredKotlinUsage) { return ((JavaMethodDeferredKotlinUsage<?>) originalUsageInfo).resolve(javaMethodChangeInfo); } JetCallElement callElement = PsiTreeUtil.getParentOfType(originalUsageInfo.getElement(), JetCallElement.class); if (callElement == null) return null; PsiReference ref = originalUsageInfo.getReference(); PsiElement refTarget = ref != null ? ref.resolve() : null; return new JavaMethodKotlinCallUsage(callElement, javaMethodChangeInfo, refTarget != null && ChangeSignaturePackage.isCaller(refTarget, allUsages)); } private static boolean canCreateReplacementUsage(UsageInfo originalUsageInfo) { if (originalUsageInfo instanceof JavaMethodDeferredKotlinUsage) return true; return PsiTreeUtil.getParentOfType(originalUsageInfo.getElement(), JetCallElement.class) != null; } private static class NullabilityPropagator { private final NullableNotNullManager nullManager; private final JavaPsiFacade javaPsiFacade; private final JavaCodeStyleManager javaCodeStyleManager; private final PsiAnnotation methodAnnotation; private final PsiAnnotation[] parameterAnnotations; public NullabilityPropagator(@NotNull PsiMethod baseMethod) { Project project = baseMethod.getProject(); this.nullManager = NullableNotNullManager.getInstance(project); this.javaPsiFacade = JavaPsiFacade.getInstance(project); this.javaCodeStyleManager = JavaCodeStyleManager.getInstance(project); this.methodAnnotation = getNullabilityAnnotation(baseMethod); this.parameterAnnotations = ContainerUtil.map2Array( baseMethod.getParameterList().getParameters(), PsiAnnotation.class, new Function<PsiParameter, PsiAnnotation>() { @Override public PsiAnnotation fun(PsiParameter parameter) { return getNullabilityAnnotation(parameter); } } ); } @Nullable private PsiAnnotation getNullabilityAnnotation(@NotNull PsiModifierListOwner element) { PsiAnnotation nullAnnotation = nullManager.getNullableAnnotation(element, false); PsiAnnotation notNullAnnotation = nullManager.getNotNullAnnotation(element, false); if ((nullAnnotation == null) == (notNullAnnotation == null)) return null; return nullAnnotation != null ? nullAnnotation : notNullAnnotation; } private void addNullabilityAnnotationIfApplicable(@NotNull PsiModifierListOwner element, @Nullable PsiAnnotation annotation) { PsiAnnotation nullableAnnotation = nullManager.getNullableAnnotation(element, false); PsiAnnotation notNullAnnotation = nullManager.getNotNullAnnotation(element, false); if (notNullAnnotation != null && nullableAnnotation == null && element instanceof PsiMethod) return; String annotationQualifiedName = annotation != null ? annotation.getQualifiedName() : null; if (annotationQualifiedName != null && javaPsiFacade.findClass(annotationQualifiedName, element.getResolveScope()) == null) return; if (notNullAnnotation != null) { notNullAnnotation.delete(); } if (nullableAnnotation != null) { nullableAnnotation.delete(); } if (annotationQualifiedName == null) return; PsiModifierList modifierList = element.getModifierList(); if (modifierList != null) { modifierList.addAnnotation(annotationQualifiedName); javaCodeStyleManager.shortenClassReferences(element); } } public void processMethod(@NotNull PsiMethod currentMethod) { PsiParameter[] currentParameters = currentMethod.getParameterList().getParameters(); addNullabilityAnnotationIfApplicable(currentMethod, methodAnnotation); for (int i = 0; i < parameterAnnotations.length; i++) { addNullabilityAnnotationIfApplicable(currentParameters[i], parameterAnnotations[i]); } } } private static boolean isOverriderOrCaller(UsageInfo usage) { return usage instanceof OverriderUsageInfo || usage instanceof CallerUsageInfo; } @Nullable private static PsiMethod getOverriderOrCaller(UsageInfo usage) { if (usage instanceof OverriderUsageInfo) return ((OverriderUsageInfo) usage).getOverridingMethod(); if (usage instanceof CallerUsageInfo) { PsiElement element = usage.getElement(); return element instanceof PsiMethod ? (PsiMethod) element : null; } return null; } @Override public boolean processUsage(ChangeInfo changeInfo, UsageInfo usageInfo, boolean beforeMethodChange, UsageInfo[] usages) { PsiElement method = changeInfo.getMethod(); boolean isJavaMethodUsage = isJavaMethodUsage(usageInfo); if (usageInfo instanceof KotlinWrapperForJavaUsageInfos) { List<JavaChangeInfo> javaChangeInfos = ((JetChangeInfo) changeInfo).getOrCreateJavaChangeInfos(); assert javaChangeInfos != null : "JavaChangeInfo not found: " + method.getText(); KotlinWrapperForJavaUsageInfos wrapperForJavaUsageInfos = (KotlinWrapperForJavaUsageInfos) usageInfo; UsageInfo[] javaUsageInfos = wrapperForJavaUsageInfos.getJavaUsageInfos(); ChangeSignatureUsageProcessor[] processors = ChangeSignatureUsageProcessor.EP_NAME.getExtensions(); for (JavaChangeInfo javaChangeInfo : javaChangeInfos) { // Match names so that getter/setter usages are not confused with each other if (!javaChangeInfo.getOldName().equals(wrapperForJavaUsageInfos.getJavaChangeInfo().getOldName())) continue; NullabilityPropagator nullabilityPropagator = new NullabilityPropagator(javaChangeInfo.getMethod()); for (UsageInfo usage : javaUsageInfos) { if (isOverriderOrCaller(usage) && beforeMethodChange) continue; for (ChangeSignatureUsageProcessor processor : processors) { if (processor instanceof JetChangeSignatureUsageProcessor) continue; if (isOverriderOrCaller(usage)) { processor.processUsage(javaChangeInfo, usage, true, javaUsageInfos); } if (processor.processUsage(javaChangeInfo, usage, beforeMethodChange, javaUsageInfos)) break; } if (usage instanceof OverriderUsageInfo && ((OverriderUsageInfo) usage).isOriginalOverrider()) { PsiMethod overridingMethod = ((OverriderUsageInfo) usage).getOverridingMethod(); if (overridingMethod != null && !(overridingMethod instanceof KotlinLightMethod)) { nullabilityPropagator.processMethod(overridingMethod); } } } } } if (beforeMethodChange) { if (!(method instanceof PsiMethod) || initializedOriginalDescriptor) return true; OriginalJavaMethodDescriptorWrapper descriptorWrapper = getOriginalJavaMethodDescriptorWrapper(usages); if (descriptorWrapper == null || descriptorWrapper.originalJavaMethodDescriptor != null) return true; FunctionDescriptor methodDescriptor = ResolvePackage.getJavaMethodDescriptor((PsiMethod) method); assert methodDescriptor != null; descriptorWrapper.originalJavaMethodDescriptor = new JetChangeSignatureData(methodDescriptor, method, Collections.singletonList(methodDescriptor)); // This change info is used as a placeholder before primary method update // It gets replaced with real change info afterwards JetChangeInfo dummyChangeInfo = new DummyJetChangeInfo(changeInfo.getMethod(), descriptorWrapper.originalJavaMethodDescriptor); for (int i = 0; i < usages.length; i++) { UsageInfo oldUsageInfo = usages[i]; if (!isJavaMethodUsage(oldUsageInfo)) continue; UsageInfo newUsageInfo = createReplacementUsage(oldUsageInfo, dummyChangeInfo, usages); if (newUsageInfo != null) { usages[i] = newUsageInfo; } } initializedOriginalDescriptor = true; return true; } PsiElement element = usageInfo.getElement(); if (element == null) return false; if (usageInfo instanceof JavaMethodKotlinUsageWithDelegate) { JavaMethodKotlinUsageWithDelegate usageWithDelegate = (JavaMethodKotlinUsageWithDelegate) usageInfo; // Do not call getOriginalJavaMethodDescriptorWrapper() on each usage to avoid O(usage_count^2) performance if (((JavaMethodKotlinUsageWithDelegate) usageInfo).getJavaMethodChangeInfo() instanceof DummyJetChangeInfo) { OriginalJavaMethodDescriptorWrapper descriptorWrapper = getOriginalJavaMethodDescriptorWrapper(usages); JetMethodDescriptor methodDescriptor = descriptorWrapper != null ? descriptorWrapper.originalJavaMethodDescriptor : null; if (methodDescriptor == null) return true; JetChangeInfo javaMethodChangeInfo = ChangeSignaturePackage.toJetChangeInfo(changeInfo, methodDescriptor); for (UsageInfo info : usages) { if (info instanceof JavaMethodKotlinUsageWithDelegate) { ((JavaMethodKotlinUsageWithDelegate) info).setJavaMethodChangeInfo(javaMethodChangeInfo); } } } return usageWithDelegate.processUsage(usages); } if (usageInfo instanceof MoveRenameUsageInfo && isJavaMethodUsage) { JetSimpleNameExpression callee = PsiTreeUtil.getParentOfType(usageInfo.getElement(), JetSimpleNameExpression.class, false); PsiReference ref = callee != null ? ReferencesPackage.getMainReference(callee) : null; if (ref instanceof JetSimpleNameReference) { ((JetSimpleNameReference) ref).handleElementRename(((PsiMethod)method).getName()); return true; } return false; } return usageInfo instanceof JetUsageInfo ? ((JetUsageInfo) usageInfo).processUsage((JetChangeInfo) changeInfo, element, usages) : true; } @Override public boolean processPrimaryMethod(ChangeInfo changeInfo) { if (!(changeInfo instanceof JetChangeInfo)) return false; JetChangeInfo jetChangeInfo = (JetChangeInfo) changeInfo; for (JetCallableDefinitionUsage primaryFunction : jetChangeInfo.getMethodDescriptor().getPrimaryCallables()) { primaryFunction.processUsage(jetChangeInfo, primaryFunction.getDeclaration(), UsageInfo.EMPTY_ARRAY); } jetChangeInfo.primaryMethodUpdated(); return true; } @Override public boolean shouldPreviewUsages(ChangeInfo changeInfo, UsageInfo[] usages) { return false; } @Override public boolean setupDefaultValues(ChangeInfo changeInfo, Ref<UsageInfo[]> refUsages, Project project) { return false; } @Override public void registerConflictResolvers(List<ResolveSnapshotProvider.ResolveSnapshot> snapshots, @NotNull ResolveSnapshotProvider resolveSnapshotProvider, UsageInfo[] usages, ChangeInfo changeInfo) { } }
52.829358
201
0.633058
f13dc159c3089587520db56cb4c69a61fd1c7f85
1,197
package my.lux.brand.addressbook.tests; import my.lux.brand.addressbook.model.GroupData; import my.lux.brand.addressbook.model.Groups; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Set; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class GroupDeletionTests extends TestBase{ @BeforeMethod public void ensurePreconditions(){ if (app.db().groups().size() == 0) { app.goTo().groupPage(); app.group().create(new GroupData() .withName("newGroup") .withHeader("newHeader") .withFooter("newFooter")); } } @Test public void testGroupDeletion() { Groups before = app.db().groups(); GroupData deletedGroup = before.iterator().next(); app.goTo().groupPage(); app.group().delete(deletedGroup); assertThat(app.group().count(), equalTo(before.size() - 1)); Groups after = app.db().groups(); assertThat(after, equalTo(before.without(deletedGroup))); verifyGroupListInUI(); } }
29.925
68
0.642439
5aa431ff55d29a14eabe0a75f7e655b31d2d4f16
2,486
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.common.util; import org.junit.Test; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Unit tests for class {@link SumHelper}. * * @see SumHelper * */ public class SumHelperTest{ @Test public void testSumDouble() { List<Double> linkedList = new LinkedList<>(); Double doubleValue = new Double(2832); linkedList.add(doubleValue); Double result = SumHelper.sumDouble(linkedList); assertTrue(linkedList.contains(result)); assertEquals(result, doubleValue, 0.01); assertEquals(2832.0, result, 0.01); assertEquals(1, linkedList.size()); } @Test public void testSumIntegerReturningLongWhereShortValueIsPositive() { List<Integer> linkedList = new LinkedList<>(); Integer integer = Integer.valueOf(4584); linkedList.add(integer); Long result = SumHelper.sumInteger(linkedList); assertTrue(linkedList.contains(integer)); assertNotNull(result); assertEquals(4584L, (long) result); assertEquals(1, linkedList.size()); } @Test public void testSumLong() { List<Integer> linkedList = new LinkedList<>(); Long resultOne = SumHelper.sumInteger(linkedList); assertEquals(0L, (long) resultOne); assertEquals(0, linkedList.size()); List<Long> linkedListTwo = new LinkedList<>(); linkedListTwo.add(resultOne); Long resultTwo = SumHelper.sumLong(linkedListTwo); assertEquals(0L, (long) resultTwo); assertEquals(1, linkedListTwo.size()); } }
30.317073
75
0.708769
e5cf4ecc825a60ec643d4d3fd34b980b28f3b7e6
2,190
package model; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.List; @Entity @NoArgsConstructor @AllArgsConstructor // Consulta para obtener todos @NamedQuery(name = "Departamento.findAll", query = "SELECT d FROM departamento d") // Consulta para obtener todos los post dado el id de un usuario //@NamedQuery(name = "Departamento.getByUserId", query = "SELECT p FROM Departamento p WHERE p.user.id = ?1") @Table(name = "departamento") // Ojo con la minuscula que en la tabla está así public class DepartamentoJPA { private long id; private String nombre; private long presupuesto; private Programador jefe; private List<Programador> programadores; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) public long getId() { return id; } public void setId(long id) { this.id = id; } @Basic @Column(name = "nombre", nullable = false, length = 250) public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Basic @Column(name = "presupuesto", nullable = false, length = 250) public long getPresupuesto() { return presupuesto; } public void setPresupuesto(long presupuesto) { this.presupuesto = presupuesto; } /* //@ManyToOne //@JoinColumn(name = "programador_id", referencedColumnName = "id", nullable = false) @OneToOne @JoinColumn(name = "programador_id", referencedColumnName = "id", nullable = false) public Programador getJefe() { return jefe; } public void setJefe(Programador jefe) { this.jefe = jefe; } // Pongo EAGER porque están en contexto diferentes y debememos conseguirlo @OneToMany(fetch = FetchType.EAGER, mappedBy = "programador", cascade = CascadeType. REMOVE) // cascade = CascadeType.ALL public List<Programador> getProgramadores() { return programadores; } public void setProgramadores(List<Programador> programadores) { this.programadores = programadores; } */ }
28.441558
125
0.673973
0dc49f28d0859bdae3a4f623f3c709337a5a95fd
25,709
package demos.gettablecolumns; import gudusoft.gsqlparser.*; import gudusoft.gsqlparser.nodes.TColumnWithSortOrder; import gudusoft.gsqlparser.nodes.TObjectName; import gudusoft.gsqlparser.nodes.TTable; import gudusoft.gsqlparser.nodes.TTypeName; import gudusoft.gsqlparser.stmt.TStoredProcedureSqlStatement; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Stack; import demos.joinRelationAnalyze.joinRelationAnalyze; class myMetaDB implements IMetaDatabase { String columns[][] = { {"server","db","DW","AcctInfo_PT","ACCT_ID"}, {"server","db","DW","ImSysInfo_BC","ACCT_ID"}, {"server","db","DW","AcctInfo_PT","SystemOfRec"}, {"server","db","DW","ImSysInfo_BC","SystemOfRec"}, {"server","db","DW","AcctInfo_PT","OfficerCode"}, {"server","db","DW","ImSysInfo_BC","OpeningDate"}, }; public boolean checkColumn(String server, String database,String schema, String table, String column){ boolean bServer,bDatabase,bSchema,bTable,bColumn,bRet = false; for (int i=0; i<columns.length;i++){ if ((server == null)||(server.length() == 0)){ bServer = true; }else{ bServer = columns[i][0].equalsIgnoreCase(server); } if (!bServer) continue; if ((database == null)||(database.length() == 0)){ bDatabase = true; }else{ bDatabase = columns[i][1].equalsIgnoreCase(database); } if (!bDatabase) continue; if ((schema == null)||(schema.length() == 0)){ bSchema = true; }else{ bSchema = columns[i][2].equalsIgnoreCase(schema); } if (!bSchema) continue; bTable = columns[i][3].equalsIgnoreCase(table); if (!bTable) continue; bColumn = columns[i][4].equalsIgnoreCase(column); if (!bColumn) continue; bRet =true; break; } return bRet; } } class TInfoRecord { public String getSPString(){ if (getSPName() == null) return "N/A"; else return getSPName().toString(); } String getTableStr(TTable table){ String tableName =""; if (table.getTableType() == ETableSource.subquery) { tableName = "(subquery, alias:" + table.getAliasName() + ")"; }else{ tableName = table.getTableName().toString(); if (table.isLinkTable()){ tableName = tableName+"("+table.getLinkTable().getTableName().toString()+")"; }else if (table.isCTEName()){ tableName = tableName+"(CTE)"; } } return tableName; } public String getFullColumnName(){ if (dbObjectType != EDbObjectType.column) return ""; String columnName = getColumn().getColumnNameOnly(); if (getTable() != null && getTable( ).getObjectNameReferences( ).searchColumnReference( getColumn() )!=-1){ if (getTableStr(getTable()).length() > 0){ columnName = getTableStr(getTable())+"."+columnName; } schemaName = getTable().getPrefixSchema(); if (schemaName.length() > 0) { columnName = schemaName+"."+columnName; } return columnName; } return getColumn().toString( ); } public String printMe(boolean includingTitle){ String spTitle="\nfilename|spname|object type\n"; String tableTitle="\nfilename|spname|object type|schema|table|table effect\n"; String columnTitle="\nfilename|spname|object type|schema|table|column|location|coordinate|datatype\n"; String indexTitle="\nfilename|spname|object type|schema|index|table|column|location|coordinate\n"; String schemaName = "N/A"; String tableName = "unknownTable"; String indexName = "unknownIndex"; StringBuffer sb = new StringBuffer (1024); switch (dbObjectType){ case procedure: if (includingTitle) sb.append(spTitle); sb.append(getFileName()+"|"+getSPName().toString()+"|"+dbObjectType); break; case table: if (includingTitle) sb.append(tableTitle); tableName = getTableStr(getTable()); schemaName = getTable().getPrefixSchema(); if (schemaName.length() == 0) schemaName ="N/A"; sb.append(getFileName()+"|"+getSPString()+"|"+dbObjectType+"|"+schemaName+"|"+tableName+"|"+getTable().getEffectType()); break; case column: if (includingTitle) sb.append(columnTitle); if (getTable() != null){ //it's an orphan column tableName = getTableStr(getTable()); schemaName = getTable().getPrefixSchema(); if (schemaName.length() == 0) schemaName ="N/A"; }else{ tableName = "missed"; } String datatypeStr = ""; if ((getColumn().getLinkedColumnDef() != null)){ //column in create table, add datatype information as well TTypeName datatype = getColumn().getLinkedColumnDef().getDatatype(); datatypeStr = datatype.getDataTypeName(); if (datatype.getLength() != null){ datatypeStr = datatypeStr+":"+datatype.getLength().toString(); } else if (datatype.getPrecision() != null){ datatypeStr = datatypeStr+":"+datatype.getPrecision().toString(); if (datatype.getScale() != null){ datatypeStr = datatypeStr+":"+datatype.getScale().toString(); } } } sb.append(getFileName()+"|"+getSPString()+"|"+dbObjectType+"|"+schemaName+"|"+tableName+"|"+getColumn().toString()+"|"+getColumn().getLocation()+"|("+getColumn().coordinate()+")|"+datatypeStr); break; case index: if (includingTitle) sb.append(indexTitle); if (getTable() != null){ schemaName = getTable().getPrefixSchema(); if (schemaName.length() == 0) schemaName ="N/A"; tableName = getTable().getTableName().toString(); } if (getIndex() != null){ indexName = getIndex().toString(); } sb.append(getFileName()+"|"+getSPString()+"|"+dbObjectType+"|"+schemaName+"|"+indexName+"|"+tableName+"|"+getColumn().toString()+"|"+getColumn().getLocation()+"|("+getColumn().coordinate()+")"); break; } return sb.toString(); } private TObjectName index; public void setIndex(TObjectName index) { this.index = index; } public TObjectName getIndex() { return index; } private EDbObjectType dbObjectType; public void setDbObjectType(EDbObjectType dbObjectType) { this.dbObjectType = dbObjectType; } public EDbObjectType getDbObjectType() { return dbObjectType; } public TInfoRecord(){ } public TInfoRecord(EDbObjectType dbObjectType){ this.dbObjectType = dbObjectType; } public TInfoRecord(TTable table){ this.table = table; this.dbObjectType = EDbObjectType.table; } public TInfoRecord(TInfoRecord clone, EDbObjectType dbObjectType){ this.fileName = clone.fileName; this.SPName = clone.SPName; this.table = clone.table; this.column = clone.column; this.dbObjectType = dbObjectType; } private String fileName = "N/A"; private TObjectName SPName ; //stored procedure name public void setFileName(String fileName) { this.fileName = fileName; } public void setSPName(TObjectName SPName) { this.SPName = SPName; } public void setSchemaName(String schemaName) { this.schemaName = schemaName; } public String getFileName() { return fileName; } public TObjectName getSPName() { return SPName; } public String getSchemaName() { return schemaName; } private String schemaName; // public String tableName; // public String columnName; private TTable table; public void setTable(TTable table) { this.table = table; } public void setColumn(TObjectName column) { this.column = column; } public TTable getTable() { return table; } public TObjectName getColumn() { return column; } private TObjectName column; } public class TGetTableColumn{ private EDbVendor dbVendor; private String queryStr; private TGSqlParser sqlParser; private IMetaDatabase metaDatabase = null; public void setMetaDatabase(IMetaDatabase metaDatabase) { this.metaDatabase = metaDatabase; sqlParser.setMetaDatabase(metaDatabase); } private StringBuffer functionlist,schemalist, triggerlist,sequencelist,databaselist; public StringBuffer infos; public StringBuffer outList; private ArrayList<TInfoRecord> infoList; private ArrayList<String> fieldlist,tablelist,indexList; private StringBuffer tableColumnList; private String newline = "\n"; private String sqlFileName ="N/A"; public boolean isConsole; public boolean listStarColumn; public boolean showTableEffect; public boolean showColumnLocation; public boolean showDatatype; public boolean showIndex; public boolean linkOrphanColumnToFirstTable; public boolean showDetail = false; public boolean showSummary = true; public boolean showTreeStructure = false; public boolean showBySQLClause = false; public boolean showJoin = false; private Stack<TStoredProcedureSqlStatement> spList; String dotChar = "."; public TGetTableColumn(EDbVendor pDBVendor){ dbVendor = pDBVendor; sqlParser = new TGSqlParser(dbVendor); //sqlParser.setMetaDatabase(new myMetaDB()); if (dbVendor == EDbVendor.dbvdax){ dotChar = ""; } tablelist = new ArrayList<String>(); fieldlist = new ArrayList<String>(); indexList = new ArrayList<String>(); infoList = new ArrayList<TInfoRecord>(); spList = new Stack<TStoredProcedureSqlStatement>(); infos = new StringBuffer(); functionlist = new StringBuffer(); schemalist = new StringBuffer(); triggerlist = new StringBuffer(); sequencelist = new StringBuffer(); databaselist = new StringBuffer(); tableColumnList = new StringBuffer(); outList = new StringBuffer(); isConsole = true; listStarColumn = false; showTreeStructure = false; showTableEffect = false; showColumnLocation = false; linkOrphanColumnToFirstTable = true; showDatatype = false; showIndex = false; } public void runText(String pQuery){ run(pQuery,false); } public void runFile(String pFileName){ sqlFileName = pFileName; run(pFileName,true); } String numberOfSpace(int pNum){ String ret=""; for(int i=0;i<pNum;i++){ ret = ret+" "; } return ret; } public StringBuffer getInfos() { return infos; } protected void run(String pQuery, boolean isFile){ queryStr = pQuery; if (isFile) sqlParser.sqlfilename = pQuery; else sqlParser.sqltext = pQuery; int iRet = sqlParser.parse(); if (iRet != 0){ if(isConsole) System.out.println(sqlParser.getErrormessage()); else throw new RuntimeException(sqlParser.getErrormessage()); return; } outList.setLength(0); tablelist.clear(); fieldlist.clear(); indexList.clear(); for(int i=0;i<sqlParser.sqlstatements.size();i++){ analyzeStmt(sqlParser.sqlstatements.get(i),0); } // print detailed info if (showDetail){ boolean includingTitle = true; for(int i=0;i<infoList.size();i++){ if (i>0){ includingTitle = !(infoList.get(i).getDbObjectType() == infoList.get(i-1).getDbObjectType()); } outputResult( infoList.get( i ).printMe( includingTitle ) ); } } // print summary info if (showSummary){ removeDuplicateAndSort(tablelist); removeDuplicateAndSort(fieldlist); removeDuplicateAndSort(indexList); printArray("Tables:", tablelist); printArray("Fields:",fieldlist); if(showIndex && (indexList.size() > 0)){ printArray("Indexs:",indexList); } } // print tree structure if (showTreeStructure){ outputResult( infos.toString( ) ); } if (showBySQLClause){ ArrayList<ETableEffectType> tableEffectTypes = new ArrayList<ETableEffectType>(); ArrayList<ESqlClause> columnClauses = new ArrayList<ESqlClause>(); for(int i=0;i<infoList.size();i++){ if (infoList.get(i).getDbObjectType() == EDbObjectType.table){ if (!tableEffectTypes.contains(infoList.get(i).getTable().getEffectType())){ tableEffectTypes.add(infoList.get(i).getTable().getEffectType()); } } } outputResult("Tables:"); for(int j=0;j<tableEffectTypes.size();j++){ outputResult("\t"+tableEffectTypes.get(j).toString()); for(int i=0;i<infoList.size();i++){ if (infoList.get(i).getDbObjectType() == EDbObjectType.table){ TTable lcTable = infoList.get(i).getTable(); if (lcTable.getEffectType() == tableEffectTypes.get(j)){ outputResult("\t\t" + lcTable.toString()+ "("+lcTable.getTableName().coordinate()+")"); } } } } // column for(int i=0;i<infoList.size();i++){ if (infoList.get(i).getDbObjectType() == EDbObjectType.column){ if (!columnClauses.contains(infoList.get(i).getColumn().getLocation())){ columnClauses.add(infoList.get(i).getColumn().getLocation()); } } } outputResult("Columns:"); for(int j=0;j<columnClauses.size();j++){ outputResult("\t"+columnClauses.get(j).toString()); for(int i=0;i<infoList.size();i++){ if (infoList.get(i).getDbObjectType() == EDbObjectType.column){ TObjectName lcColumn = infoList.get(i).getColumn(); if (lcColumn.getLocation() == columnClauses.get(j)){ outputResult("\t\t" + infoList.get(i).getFullColumnName()+ "("+lcColumn.coordinate()+")"); } } } } } if(showJoin){ joinRelationAnalyze analysis = new joinRelationAnalyze( sqlParser, showColumnLocation ); outputResult( analysis.getAnalysisResult( ) ); } // System.out.println("Fields:"+newline+fieldlist.toString()); } private void outputResult( String result) { if (isConsole){ System.out.println(result); //System.out.println(TBaseType.toHex(result,"UTF-8")); }else { //if(outList.length()>0) // outList.append(newline); outList.append(result).append( newline); } } void printArray(String pTitle,ArrayList<String> pList){ outputResult( pTitle ); Object str[] = pList.toArray( ); for ( int i = 0; i < str.length; i++ ) { outputResult( str[i].toString( ) ); } } void removeDuplicateAndSort(ArrayList <String> pList){ Collections.sort(pList, new SortIgnoreCase() ); for ( int i = 0 ; i < pList.size() - 1 ; i ++ ) { for ( int j = pList.size() - 1 ; j > i; j -- ) { if (pList.get(j).equalsIgnoreCase((pList.get(i)))) { pList.remove(j); } } } } protected void analyzeStmt(TCustomSqlStatement stmt, int pNest){ TTable lcTable = null; TObjectName lcColumn = null; String tn = "",cn=""; if (stmt instanceof TStoredProcedureSqlStatement){ spList.push((TStoredProcedureSqlStatement)stmt); TInfoRecord spRecord = new TInfoRecord(EDbObjectType.procedure); spRecord.setSPName(spList.peek().getStoredProcedureName()); } //System.out.println( numberOfSpace(pNest)+ stmt.sqlstatementtype); infos.append(numberOfSpace(pNest) + stmt.sqlstatementtype+newline); for(int i=0;i<stmt.tables.size();i++){ //if (stmt.tables.getTable(i).isBaseTable()) //{ lcTable = stmt.tables.getTable(i); TInfoRecord tableRecord = new TInfoRecord(lcTable); tableRecord.setFileName(this.sqlFileName); if (spList.size() > 0){ tableRecord.setSPName(spList.peek().getStoredProcedureName()); } infoList.add(tableRecord); if (lcTable.getTableType() == ETableSource.subquery) { tn = "(subquery, alias:" + lcTable.getAliasName() + ")"; }else{ tn = lcTable.getTableName().toString(); if (lcTable.isLinkTable()){ tn = tn+"("+lcTable.getLinkTable().getTableName().toString()+")"; }else if (lcTable.isCTEName()){ tn = tn+"(CTE)"; } } //System.out.println(numberOfSpace(pNest+1)+tn.getName()); if ((showTableEffect) &&(lcTable.isBaseTable())){ infos.append(numberOfSpace(pNest+1)+ tn+"("+lcTable.getEffectType()+")"+newline); }else{ infos.append(numberOfSpace(pNest+1)+ tn+newline); } tableColumnList.append(","+tn); if (!((lcTable.getTableType() == ETableSource.subquery) || (lcTable.isCTEName()))) { if (lcTable.isLinkTable()){ // tablelist.append(lcTable.getLinkTable().toString()+newline); tablelist.add(lcTable.getLinkTable().toString()); }else{ // tablelist.append(lcTable.toString()+newline); tablelist.add(lcTable.getTableName().toString()); } } for (int j=0;j<stmt.tables.getTable(i).getLinkedColumns().size();j++){ lcColumn = stmt.tables.getTable(i).getLinkedColumns().getObjectName(j); TInfoRecord columnRecord = new TInfoRecord(tableRecord,EDbObjectType.column); columnRecord.setColumn(lcColumn); infoList.add(columnRecord); cn = lcColumn.getColumnNameOnly(); if ((showDatatype)&&(lcColumn.getLinkedColumnDef() != null)){ //column in create table, add datatype information as well TTypeName datatype = lcColumn.getLinkedColumnDef().getDatatype(); cn = cn + ":"+datatype.getDataTypeName(); if (datatype.getLength() != null){ cn = cn+":"+datatype.getLength().toString(); } else if (datatype.getPrecision() != null){ cn = cn+":"+datatype.getPrecision().toString(); if (datatype.getScale() != null){ cn = cn+":"+datatype.getScale().toString(); } } } //System.out.println(numberOfSpace(pNest+2)+cn.getColumnNameOnly()); if (showColumnLocation){ String posStr = ""; // if ( lcColumn.getColumnToken() != null) { // TSourceToken lcStartToken = lcColumn.getColumnToken(); // posStr ="("+ lcStartToken.lineNo+","+lcStartToken.columnNo+ ")"; // } infos.append(numberOfSpace(pNest+3)+ lcColumn.getColumnNameOnly()+posStr+"("+lcColumn.getLocation()+")"+newline); }else{ infos.append(numberOfSpace(pNest+3)+ lcColumn.getColumnNameOnly()+newline); } if (!((lcTable.getTableType() == ETableSource.subquery)||(lcTable.isCTEName()))){ if ((listStarColumn) || (!(lcColumn.getColumnNameOnly().equals("*")))){ if (lcTable.isLinkTable()){ fieldlist.add(lcTable.getLinkTable().getTableName() + dotChar + cn ); }else{ fieldlist.add(tn + dotChar + cn ); } } } tableColumnList.append(","+tn+dotChar+ cn); } //} } if (stmt.getOrphanColumns().size() > 0){ infos.append(numberOfSpace(pNest+1)+" orphan columns:"+newline); String oc = ""; for (int k=0;k<stmt.getOrphanColumns().size();k++){ TInfoRecord columnRecord = new TInfoRecord(EDbObjectType.column); columnRecord.setColumn(stmt.getOrphanColumns().getObjectName(k)); columnRecord.setFileName(this.sqlFileName); infoList.add(columnRecord); oc = stmt.getOrphanColumns().getObjectName(k).getColumnNameOnly();// stmt.getOrphanColumns().getObjectName(k).toString(); if (showColumnLocation){ infos.append(numberOfSpace(pNest+3)+oc+"("+stmt.getOrphanColumns().getObjectName(k).getLocation()+")"+newline); }else{ infos.append(numberOfSpace(pNest+3)+oc+newline); } if ((linkOrphanColumnToFirstTable)&&(stmt.getFirstPhysicalTable() != null)){ if ((listStarColumn) ||(!(oc.equalsIgnoreCase("*")))) fieldlist.add(stmt.getFirstPhysicalTable().toString() + dotChar + oc ); columnRecord.setTable(stmt.getFirstPhysicalTable()); }else { fieldlist.add("missed"+dotChar + oc+"("+stmt.getOrphanColumns().getObjectName(k).coordinate()+")" ); } tableColumnList.append(",missed"+dotChar+oc+newline); } } for(int i=0;i<stmt.getIndexColumns().size();i++){ TColumnWithSortOrder indexColumn = stmt.getIndexColumns().getElement(i); TInfoRecord indexRecord = new TInfoRecord(EDbObjectType.index); indexRecord.setColumn(indexColumn.getColumnName()); indexRecord.setFileName(this.sqlFileName); infoList.add(indexRecord); String tableName = "unknownTable"; String indexName = "unknownIndex"; if (indexColumn.getOwnerTable() != null){ tableName = indexColumn.getOwnerTable().getTableName().toString(); indexRecord.setTable(indexColumn.getOwnerTable()); } if (indexColumn.getOwnerConstraint() != null){ indexName = indexColumn.getOwnerConstraint().getConstraintName().toString(); indexRecord.setIndex(indexColumn.getOwnerConstraint().getConstraintName()); } indexList.add(tableName + ":" + indexColumn.getColumnName().toString()+":"+indexName); } for (int i=0;i<stmt.getStatements().size();i++){ analyzeStmt(stmt.getStatements().get(i),pNest+1); } if (stmt instanceof TStoredProcedureSqlStatement){ spList.pop(); } } } class SortIgnoreCase implements Comparator<Object> { public int compare(Object o1, Object o2) { String s1 = (String) o1; String s2 = (String) o2; return s1.toLowerCase().compareTo(s2.toLowerCase()); } }
36.885222
211
0.53561
85f11a0f3cd0972cd32aa29a22d71906ee28722e
46,823
// $ANTLR 3.1b1 gUnit.g 2008-05-14 15:52:07 package org.antlr.gunit; import org.antlr.runtime.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; public class gUnitLexer extends Lexer { public static final int RETVAL=7; public static final int AST=10; public static final int NESTED_ACTION=17; public static final int T__28=28; public static final int EXT=11; public static final int T__23=23; public static final int WS=21; public static final int STRING=8; public static final int ACTION=6; public static final int T__22=22; public static final int ESC=14; public static final int XDIGIT=20; public static final int T__29=29; public static final int NESTED_AST=16; public static final int T__30=30; public static final int CHAR_LITERAL=19; public static final int EOF=-1; public static final int T__27=27; public static final int STRING_LITERAL=18; public static final int T__24=24; public static final int T__26=26; public static final int ML_STRING=9; public static final int T__25=25; public static final int ML_COMMENT=13; public static final int SL_COMMENT=12; public static final int DOC_COMMENT=4; public static final int ID=5; public static final int NESTED_RETVAL=15; // delegates // delegators public gUnitLexer() {;} public gUnitLexer(CharStream input) { this(input, new RecognizerSharedState()); } public gUnitLexer(CharStream input, RecognizerSharedState state) { super(input,state); } public String getGrammarFileName() { return "gUnit.g"; } // $ANTLR start T__22 public final void mT__22() throws RecognitionException { try { int _type = T__22; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:9:7: ( 'gunit' ) // gUnit.g:9:9: 'gunit' { match("gunit"); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end T__22 // $ANTLR start T__23 public final void mT__23() throws RecognitionException { try { int _type = T__23; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:10:7: ( 'walks' ) // gUnit.g:10:9: 'walks' { match("walks"); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end T__23 // $ANTLR start T__24 public final void mT__24() throws RecognitionException { try { int _type = T__24; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:11:7: ( ';' ) // gUnit.g:11:9: ';' { match(';'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end T__24 // $ANTLR start T__25 public final void mT__25() throws RecognitionException { try { int _type = T__25; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:12:7: ( '@header' ) // gUnit.g:12:9: '@header' { match("@header"); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end T__25 // $ANTLR start T__26 public final void mT__26() throws RecognitionException { try { int _type = T__26; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:13:7: ( ':' ) // gUnit.g:13:9: ':' { match(':'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end T__26 // $ANTLR start T__27 public final void mT__27() throws RecognitionException { try { int _type = T__27; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:14:7: ( 'OK' ) // gUnit.g:14:9: 'OK' { match("OK"); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end T__27 // $ANTLR start T__28 public final void mT__28() throws RecognitionException { try { int _type = T__28; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:15:7: ( 'FAIL' ) // gUnit.g:15:9: 'FAIL' { match("FAIL"); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end T__28 // $ANTLR start T__29 public final void mT__29() throws RecognitionException { try { int _type = T__29; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:16:7: ( 'returns' ) // gUnit.g:16:9: 'returns' { match("returns"); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end T__29 // $ANTLR start T__30 public final void mT__30() throws RecognitionException { try { int _type = T__30; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:17:7: ( '->' ) // gUnit.g:17:9: '->' { match("->"); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end T__30 // $ANTLR start SL_COMMENT public final void mSL_COMMENT() throws RecognitionException { try { int _type = SL_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:134:3: ( '//' (~ ( '\\r' | '\\n' ) )* ( '\\r' )? '\\n' ) // gUnit.g:134:5: '//' (~ ( '\\r' | '\\n' ) )* ( '\\r' )? '\\n' { match("//"); // gUnit.g:134:10: (~ ( '\\r' | '\\n' ) )* loop1: do { int alt1=2; int LA1_0 = input.LA(1); if ( ((LA1_0>='\u0000' && LA1_0<='\t')||(LA1_0>='\u000B' && LA1_0<='\f')||(LA1_0>='\u000E' && LA1_0<='\uFFFE')) ) { alt1=1; } switch (alt1) { case 1 : // gUnit.g:134:10: ~ ( '\\r' | '\\n' ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='\t')||(input.LA(1)>='\u000B' && input.LA(1)<='\f')||(input.LA(1)>='\u000E' && input.LA(1)<='\uFFFE') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop1; } } while (true); // gUnit.g:134:24: ( '\\r' )? int alt2=2; int LA2_0 = input.LA(1); if ( (LA2_0=='\r') ) { alt2=1; } switch (alt2) { case 1 : // gUnit.g:134:24: '\\r' { match('\r'); } break; } match('\n'); _channel=HIDDEN; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end SL_COMMENT // $ANTLR start ML_COMMENT public final void mML_COMMENT() throws RecognitionException { try { int _type = ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:138:2: ( '/*' ( . )* '*/' ) // gUnit.g:138:4: '/*' ( . )* '*/' { match("/*"); _channel=HIDDEN; // gUnit.g:138:28: ( . )* loop3: do { int alt3=2; int LA3_0 = input.LA(1); if ( (LA3_0=='*') ) { int LA3_1 = input.LA(2); if ( (LA3_1=='/') ) { alt3=2; } else if ( ((LA3_1>='\u0000' && LA3_1<='.')||(LA3_1>='0' && LA3_1<='\uFFFE')) ) { alt3=1; } } else if ( ((LA3_0>='\u0000' && LA3_0<=')')||(LA3_0>='+' && LA3_0<='\uFFFE')) ) { alt3=1; } switch (alt3) { case 1 : // gUnit.g:138:28: . { matchAny(); } break; default : break loop3; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end ML_COMMENT // $ANTLR start STRING public final void mSTRING() throws RecognitionException { try { int _type = STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:141:8: ( '\"' ( ESC | ~ ( '\\\\' | '\"' ) )* '\"' ) // gUnit.g:141:10: '\"' ( ESC | ~ ( '\\\\' | '\"' ) )* '\"' { match('\"'); // gUnit.g:141:14: ( ESC | ~ ( '\\\\' | '\"' ) )* loop4: do { int alt4=3; int LA4_0 = input.LA(1); if ( (LA4_0=='\\') ) { alt4=1; } else if ( ((LA4_0>='\u0000' && LA4_0<='!')||(LA4_0>='#' && LA4_0<='[')||(LA4_0>=']' && LA4_0<='\uFFFE')) ) { alt4=2; } switch (alt4) { case 1 : // gUnit.g:141:16: ESC { mESC(); } break; case 2 : // gUnit.g:141:22: ~ ( '\\\\' | '\"' ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFE') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop4; } } while (true); match('\"'); setText(getText().substring(1, getText().length()-1)); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end STRING // $ANTLR start ML_STRING public final void mML_STRING() throws RecognitionException { try { int _type = ML_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:145:2: ( '<<' ( . )* '>>' ) // gUnit.g:145:4: '<<' ( . )* '>>' { match("<<"); // gUnit.g:145:9: ( . )* loop5: do { int alt5=2; int LA5_0 = input.LA(1); if ( (LA5_0=='>') ) { int LA5_1 = input.LA(2); if ( (LA5_1=='>') ) { alt5=2; } else if ( ((LA5_1>='\u0000' && LA5_1<='=')||(LA5_1>='?' && LA5_1<='\uFFFE')) ) { alt5=1; } } else if ( ((LA5_0>='\u0000' && LA5_0<='=')||(LA5_0>='?' && LA5_0<='\uFFFE')) ) { alt5=1; } switch (alt5) { case 1 : // gUnit.g:145:9: . { matchAny(); } break; default : break loop5; } } while (true); match(">>"); if ( getText().charAt(2)=='\n' && getText().charAt(getText().length()-3)=='\n' ) { setText(getText().substring(3, getText().length()-3)); } else if ( getText().charAt(2)=='\n' ) { setText(getText().substring(3, getText().length()-2)); } else if ( getText().charAt(getText().length()-3)=='\n' ) { setText(getText().substring(2, getText().length()-3)); } else { setText(getText().substring(2, getText().length()-2)); } } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end ML_STRING // $ANTLR start ID public final void mID() throws RecognitionException { try { int _type = ID; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:162:4: ( ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* ) // gUnit.g:162:6: ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* { if ( (input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} // gUnit.g:162:29: ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* loop6: do { int alt6=2; int LA6_0 = input.LA(1); if ( ((LA6_0>='0' && LA6_0<='9')||(LA6_0>='A' && LA6_0<='Z')||LA6_0=='_'||(LA6_0>='a' && LA6_0<='z')) ) { alt6=1; } switch (alt6) { case 1 : // gUnit.g: { if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop6; } } while (true); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end ID // $ANTLR start EXT public final void mEXT() throws RecognitionException { try { int _type = EXT; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:164:5: ( '.' ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' )+ ) // gUnit.g:164:7: '.' ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' )+ { match('.'); // gUnit.g:164:10: ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' )+ int cnt7=0; loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( ((LA7_0>='0' && LA7_0<='9')||(LA7_0>='A' && LA7_0<='Z')||(LA7_0>='a' && LA7_0<='z')) ) { alt7=1; } switch (alt7) { case 1 : // gUnit.g: { if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||(input.LA(1)>='a' && input.LA(1)<='z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : if ( cnt7 >= 1 ) break loop7; EarlyExitException eee = new EarlyExitException(7, input); throw eee; } cnt7++; } while (true); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end EXT // $ANTLR start RETVAL public final void mRETVAL() throws RecognitionException { try { int _type = RETVAL; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:166:8: ( NESTED_RETVAL ) // gUnit.g:166:10: NESTED_RETVAL { mNESTED_RETVAL(); setText(getText().substring(1, getText().length()-1)); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end RETVAL // $ANTLR start NESTED_RETVAL public final void mNESTED_RETVAL() throws RecognitionException { try { // gUnit.g:170:15: ( '[' ( options {greedy=false; } : NESTED_RETVAL | . )* ']' ) // gUnit.g:171:2: '[' ( options {greedy=false; } : NESTED_RETVAL | . )* ']' { match('['); // gUnit.g:172:2: ( options {greedy=false; } : NESTED_RETVAL | . )* loop8: do { int alt8=3; int LA8_0 = input.LA(1); if ( (LA8_0==']') ) { alt8=3; } else if ( (LA8_0=='[') ) { alt8=1; } else if ( ((LA8_0>='\u0000' && LA8_0<='Z')||LA8_0=='\\'||(LA8_0>='^' && LA8_0<='\uFFFE')) ) { alt8=2; } switch (alt8) { case 1 : // gUnit.g:173:4: NESTED_RETVAL { mNESTED_RETVAL(); } break; case 2 : // gUnit.g:174:4: . { matchAny(); } break; default : break loop8; } } while (true); match(']'); } } finally { } } // $ANTLR end NESTED_RETVAL // $ANTLR start AST public final void mAST() throws RecognitionException { try { int _type = AST; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:179:5: ( NESTED_AST ( ( ' ' )? NESTED_AST )* ) // gUnit.g:179:7: NESTED_AST ( ( ' ' )? NESTED_AST )* { mNESTED_AST(); // gUnit.g:179:18: ( ( ' ' )? NESTED_AST )* loop10: do { int alt10=2; int LA10_0 = input.LA(1); if ( (LA10_0==' '||LA10_0=='(') ) { alt10=1; } switch (alt10) { case 1 : // gUnit.g:179:19: ( ' ' )? NESTED_AST { // gUnit.g:179:19: ( ' ' )? int alt9=2; int LA9_0 = input.LA(1); if ( (LA9_0==' ') ) { alt9=1; } switch (alt9) { case 1 : // gUnit.g:179:19: ' ' { match(' '); } break; } mNESTED_AST(); } break; default : break loop10; } } while (true); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end AST // $ANTLR start NESTED_AST public final void mNESTED_AST() throws RecognitionException { try { // gUnit.g:182:12: ( '(' ( options {greedy=false; } : NESTED_AST | . )* ')' ) // gUnit.g:183:2: '(' ( options {greedy=false; } : NESTED_AST | . )* ')' { match('('); // gUnit.g:184:2: ( options {greedy=false; } : NESTED_AST | . )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0==')') ) { alt11=3; } else if ( (LA11_0=='(') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='\'')||(LA11_0>='*' && LA11_0<='\uFFFE')) ) { alt11=2; } switch (alt11) { case 1 : // gUnit.g:185:4: NESTED_AST { mNESTED_AST(); } break; case 2 : // gUnit.g:186:4: . { matchAny(); } break; default : break loop11; } } while (true); match(')'); } } finally { } } // $ANTLR end NESTED_AST // $ANTLR start ACTION public final void mACTION() throws RecognitionException { try { int _type = ACTION; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:192:2: ( NESTED_ACTION ) // gUnit.g:192:4: NESTED_ACTION { mNESTED_ACTION(); setText(getText().substring(1, getText().length()-1)); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end ACTION // $ANTLR start NESTED_ACTION public final void mNESTED_ACTION() throws RecognitionException { try { // gUnit.g:196:15: ( '{' ( options {greedy=false; k=3; } : NESTED_ACTION | STRING_LITERAL | CHAR_LITERAL | . )* '}' ) // gUnit.g:197:2: '{' ( options {greedy=false; k=3; } : NESTED_ACTION | STRING_LITERAL | CHAR_LITERAL | . )* '}' { match('{'); // gUnit.g:198:2: ( options {greedy=false; k=3; } : NESTED_ACTION | STRING_LITERAL | CHAR_LITERAL | . )* loop12: do { int alt12=5; alt12 = dfa12.predict(input); switch (alt12) { case 1 : // gUnit.g:199:4: NESTED_ACTION { mNESTED_ACTION(); } break; case 2 : // gUnit.g:200:4: STRING_LITERAL { mSTRING_LITERAL(); } break; case 3 : // gUnit.g:201:4: CHAR_LITERAL { mCHAR_LITERAL(); } break; case 4 : // gUnit.g:202:4: . { matchAny(); } break; default : break loop12; } } while (true); match('}'); } } finally { } } // $ANTLR end NESTED_ACTION // $ANTLR start CHAR_LITERAL public final void mCHAR_LITERAL() throws RecognitionException { try { // gUnit.g:209:2: ( '\\'' ( ESC | ~ ( '\\'' | '\\\\' ) ) '\\'' ) // gUnit.g:209:4: '\\'' ( ESC | ~ ( '\\'' | '\\\\' ) ) '\\'' { match('\''); // gUnit.g:209:9: ( ESC | ~ ( '\\'' | '\\\\' ) ) int alt13=2; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFE')) ) { alt13=2; } else { NoViableAltException nvae = new NoViableAltException("", 13, 0, input); throw nvae; } switch (alt13) { case 1 : // gUnit.g:209:11: ESC { mESC(); } break; case 2 : // gUnit.g:209:17: ~ ( '\\'' | '\\\\' ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFE') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; } match('\''); } } finally { } } // $ANTLR end CHAR_LITERAL // $ANTLR start STRING_LITERAL public final void mSTRING_LITERAL() throws RecognitionException { try { // gUnit.g:214:2: ( '\"' ( ESC | ~ ( '\\\\' | '\"' ) )* '\"' ) // gUnit.g:214:4: '\"' ( ESC | ~ ( '\\\\' | '\"' ) )* '\"' { match('\"'); // gUnit.g:214:8: ( ESC | ~ ( '\\\\' | '\"' ) )* loop14: do { int alt14=3; int LA14_0 = input.LA(1); if ( (LA14_0=='\\') ) { alt14=1; } else if ( ((LA14_0>='\u0000' && LA14_0<='!')||(LA14_0>='#' && LA14_0<='[')||(LA14_0>=']' && LA14_0<='\uFFFE')) ) { alt14=2; } switch (alt14) { case 1 : // gUnit.g:214:10: ESC { mESC(); } break; case 2 : // gUnit.g:214:16: ~ ( '\\\\' | '\"' ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFE') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop14; } } while (true); match('\"'); } } finally { } } // $ANTLR end STRING_LITERAL // $ANTLR start ESC public final void mESC() throws RecognitionException { try { // gUnit.g:218:5: ( '\\\\' ( 'n' | 'r' | 't' | 'b' | 'f' | '\"' | '\\'' | '\\\\' | '>' | 'u' XDIGIT XDIGIT XDIGIT XDIGIT | . ) ) // gUnit.g:218:7: '\\\\' ( 'n' | 'r' | 't' | 'b' | 'f' | '\"' | '\\'' | '\\\\' | '>' | 'u' XDIGIT XDIGIT XDIGIT XDIGIT | . ) { match('\\'); // gUnit.g:219:3: ( 'n' | 'r' | 't' | 'b' | 'f' | '\"' | '\\'' | '\\\\' | '>' | 'u' XDIGIT XDIGIT XDIGIT XDIGIT | . ) int alt15=11; alt15 = dfa15.predict(input); switch (alt15) { case 1 : // gUnit.g:219:5: 'n' { match('n'); } break; case 2 : // gUnit.g:220:5: 'r' { match('r'); } break; case 3 : // gUnit.g:221:5: 't' { match('t'); } break; case 4 : // gUnit.g:222:5: 'b' { match('b'); } break; case 5 : // gUnit.g:223:5: 'f' { match('f'); } break; case 6 : // gUnit.g:224:5: '\"' { match('\"'); } break; case 7 : // gUnit.g:225:5: '\\'' { match('\''); } break; case 8 : // gUnit.g:226:5: '\\\\' { match('\\'); } break; case 9 : // gUnit.g:227:5: '>' { match('>'); } break; case 10 : // gUnit.g:228:5: 'u' XDIGIT XDIGIT XDIGIT XDIGIT { match('u'); mXDIGIT(); mXDIGIT(); mXDIGIT(); mXDIGIT(); } break; case 11 : // gUnit.g:229:5: . { matchAny(); } break; } } } finally { } } // $ANTLR end ESC // $ANTLR start XDIGIT public final void mXDIGIT() throws RecognitionException { try { // gUnit.g:234:8: ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ) // gUnit.g: { if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='F')||(input.LA(1)>='a' && input.LA(1)<='f') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } } finally { } } // $ANTLR end XDIGIT // $ANTLR start WS public final void mWS() throws RecognitionException { try { int _type = WS; int _channel = DEFAULT_TOKEN_CHANNEL; // gUnit.g:240:4: ( ( ' ' | '\\t' | ( '\\r' )? '\\n' )+ ) // gUnit.g:240:6: ( ' ' | '\\t' | ( '\\r' )? '\\n' )+ { // gUnit.g:240:6: ( ' ' | '\\t' | ( '\\r' )? '\\n' )+ int cnt17=0; loop17: do { int alt17=4; switch ( input.LA(1) ) { case ' ': { alt17=1; } break; case '\t': { alt17=2; } break; case '\n': case '\r': { alt17=3; } break; } switch (alt17) { case 1 : // gUnit.g:240:8: ' ' { match(' '); } break; case 2 : // gUnit.g:241:5: '\\t' { match('\t'); } break; case 3 : // gUnit.g:242:5: ( '\\r' )? '\\n' { // gUnit.g:242:5: ( '\\r' )? int alt16=2; int LA16_0 = input.LA(1); if ( (LA16_0=='\r') ) { alt16=1; } switch (alt16) { case 1 : // gUnit.g:242:5: '\\r' { match('\r'); } break; } match('\n'); } break; default : if ( cnt17 >= 1 ) break loop17; EarlyExitException eee = new EarlyExitException(17, input); throw eee; } cnt17++; } while (true); _channel=HIDDEN; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end WS public void mTokens() throws RecognitionException { // gUnit.g:1:8: ( T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | SL_COMMENT | ML_COMMENT | STRING | ML_STRING | ID | EXT | RETVAL | AST | ACTION | WS ) int alt18=19; alt18 = dfa18.predict(input); switch (alt18) { case 1 : // gUnit.g:1:10: T__22 { mT__22(); } break; case 2 : // gUnit.g:1:16: T__23 { mT__23(); } break; case 3 : // gUnit.g:1:22: T__24 { mT__24(); } break; case 4 : // gUnit.g:1:28: T__25 { mT__25(); } break; case 5 : // gUnit.g:1:34: T__26 { mT__26(); } break; case 6 : // gUnit.g:1:40: T__27 { mT__27(); } break; case 7 : // gUnit.g:1:46: T__28 { mT__28(); } break; case 8 : // gUnit.g:1:52: T__29 { mT__29(); } break; case 9 : // gUnit.g:1:58: T__30 { mT__30(); } break; case 10 : // gUnit.g:1:64: SL_COMMENT { mSL_COMMENT(); } break; case 11 : // gUnit.g:1:75: ML_COMMENT { mML_COMMENT(); } break; case 12 : // gUnit.g:1:86: STRING { mSTRING(); } break; case 13 : // gUnit.g:1:93: ML_STRING { mML_STRING(); } break; case 14 : // gUnit.g:1:103: ID { mID(); } break; case 15 : // gUnit.g:1:106: EXT { mEXT(); } break; case 16 : // gUnit.g:1:110: RETVAL { mRETVAL(); } break; case 17 : // gUnit.g:1:117: AST { mAST(); } break; case 18 : // gUnit.g:1:121: ACTION { mACTION(); } break; case 19 : // gUnit.g:1:128: WS { mWS(); } break; } } protected DFA12 dfa12 = new DFA12(this); protected DFA15 dfa15 = new DFA15(this); protected DFA18 dfa18 = new DFA18(this); static final String DFA12_eotS = "\116\uffff"; static final String DFA12_eofS = "\116\uffff"; static final String DFA12_minS = "\1\0\2\uffff\2\0\1\uffff\1\0\2\uffff\3\0\1\uffff\2\0\1\uffff\2\0"+ "\74\uffff"; static final String DFA12_maxS = "\1\ufffe\2\uffff\2\ufffe\1\uffff\1\ufffe\2\uffff\3\ufffe\1\uffff"+ "\2\ufffe\1\uffff\2\ufffe\74\uffff"; static final String DFA12_acceptS = "\1\uffff\1\5\1\1\2\uffff\1\4\1\uffff\1\4\1\2\3\uffff\1\4\5\uffff"+ "\37\2\2\uffff\1\3\5\uffff\1\3\2\uffff\15\3\3\uffff\1\3\1\uffff"; static final String DFA12_specialS = "\116\uffff}>"; static final String[] DFA12_transitionS = { "\42\5\1\3\4\5\1\4\123\5\1\2\1\5\1\1\uff81\5", "", "", "\42\13\1\10\4\13\1\12\64\13\1\6\36\13\1\11\1\13\1\7\uff81\13", "\42\21\1\16\4\21\1\5\64\21\1\20\36\21\1\15\1\21\1\14\uff81\21", "", "\42\36\1\27\4\36\1\30\26\36\1\32\35\36\1\31\5\36\1\25\3\36\1"+ "\26\7\36\1\22\3\36\1\23\1\36\1\24\1\33\5\36\1\35\1\36\1\34\uff81"+ "\36", "", "", "\42\44\1\40\4\44\1\41\64\44\1\43\36\44\1\37\1\44\1\42\uff81"+ "\44", "\42\51\1\50\4\51\1\52\64\51\1\45\36\51\1\47\1\51\1\46\uff81"+ "\51", "\42\60\1\55\4\60\1\56\64\60\1\57\36\60\1\54\1\60\1\53\uff81"+ "\60", "", "\47\5\1\63\uffd7\5", "\47\5\1\71\uffd7\5", "", "\42\110\1\76\4\110\1\77\26\110\1\106\35\110\1\105\5\110\1\103"+ "\3\110\1\104\7\110\1\100\3\110\1\101\1\110\1\102\1\107\5\110"+ "\1\75\1\110\1\74\uff81\110", "\47\5\1\114\uffd7\5", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" }; static final short[] DFA12_eot = DFA.unpackEncodedString(DFA12_eotS); static final short[] DFA12_eof = DFA.unpackEncodedString(DFA12_eofS); static final char[] DFA12_min = DFA.unpackEncodedStringToUnsignedChars(DFA12_minS); static final char[] DFA12_max = DFA.unpackEncodedStringToUnsignedChars(DFA12_maxS); static final short[] DFA12_accept = DFA.unpackEncodedString(DFA12_acceptS); static final short[] DFA12_special = DFA.unpackEncodedString(DFA12_specialS); static final short[][] DFA12_transition; static { int numStates = DFA12_transitionS.length; DFA12_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { DFA12_transition[i] = DFA.unpackEncodedString(DFA12_transitionS[i]); } } class DFA12 extends DFA { public DFA12(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 12; this.eot = DFA12_eot; this.eof = DFA12_eof; this.min = DFA12_min; this.max = DFA12_max; this.accept = DFA12_accept; this.special = DFA12_special; this.transition = DFA12_transition; } public String getDescription() { return "()* loopback of 198:2: ( options {greedy=false; k=3; } : NESTED_ACTION | STRING_LITERAL | CHAR_LITERAL | . )*"; } } static final String DFA15_eotS = "\12\uffff\1\13\2\uffff"; static final String DFA15_eofS = "\15\uffff"; static final String DFA15_minS = "\1\0\11\uffff\1\60\2\uffff"; static final String DFA15_maxS = "\1\ufffe\11\uffff\1\146\2\uffff"; static final String DFA15_acceptS = "\1\uffff\1\1\1\2\1\3\1\4\1\5\1\6\1\7\1\10\1\11\1\uffff\1\13\1\12"; static final String DFA15_specialS = "\15\uffff}>"; static final String[] DFA15_transitionS = { "\42\13\1\6\4\13\1\7\26\13\1\11\35\13\1\10\5\13\1\4\3\13\1\5"+ "\7\13\1\1\3\13\1\2\1\13\1\3\1\12\uff89\13", "", "", "", "", "", "", "", "", "", "\12\14\7\uffff\6\14\32\uffff\6\14", "", "" }; static final short[] DFA15_eot = DFA.unpackEncodedString(DFA15_eotS); static final short[] DFA15_eof = DFA.unpackEncodedString(DFA15_eofS); static final char[] DFA15_min = DFA.unpackEncodedStringToUnsignedChars(DFA15_minS); static final char[] DFA15_max = DFA.unpackEncodedStringToUnsignedChars(DFA15_maxS); static final short[] DFA15_accept = DFA.unpackEncodedString(DFA15_acceptS); static final short[] DFA15_special = DFA.unpackEncodedString(DFA15_specialS); static final short[][] DFA15_transition; static { int numStates = DFA15_transitionS.length; DFA15_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { DFA15_transition[i] = DFA.unpackEncodedString(DFA15_transitionS[i]); } } class DFA15 extends DFA { public DFA15(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 15; this.eot = DFA15_eot; this.eof = DFA15_eof; this.min = DFA15_min; this.max = DFA15_max; this.accept = DFA15_accept; this.special = DFA15_special; this.transition = DFA15_transition; } public String getDescription() { return "219:3: ( 'n' | 'r' | 't' | 'b' | 'f' | '\"' | '\\'' | '\\\\' | '>' | 'u' XDIGIT XDIGIT XDIGIT XDIGIT | . )"; } } static final String DFA18_eotS = "\1\uffff\2\15\3\uffff\3\15\12\uffff\2\15\1\34\2\15\2\uffff\2\15"+ "\1\uffff\4\15\1\45\1\15\1\47\1\50\1\uffff\1\15\2\uffff\1\15\1\53"+ "\1\uffff"; static final String DFA18_eofS = "\54\uffff"; static final String DFA18_minS = "\1\11\1\165\1\141\3\uffff\1\113\1\101\1\145\1\uffff\1\52\10\uffff"+ "\1\156\1\154\1\60\1\111\1\164\2\uffff\1\151\1\153\1\uffff\1\114"+ "\1\165\1\164\1\163\1\60\1\162\2\60\1\uffff\1\156\2\uffff\1\163\1"+ "\60\1\uffff"; static final String DFA18_maxS = "\1\173\1\165\1\141\3\uffff\1\113\1\101\1\145\1\uffff\1\57\10\uffff"+ "\1\156\1\154\1\172\1\111\1\164\2\uffff\1\151\1\153\1\uffff\1\114"+ "\1\165\1\164\1\163\1\172\1\162\2\172\1\uffff\1\156\2\uffff\1\163"+ "\1\172\1\uffff"; static final String DFA18_acceptS = "\3\uffff\1\3\1\4\1\5\3\uffff\1\11\1\uffff\1\14\1\15\1\16\1\17\1"+ "\20\1\21\1\22\1\23\5\uffff\1\12\1\13\2\uffff\1\6\10\uffff\1\7\1"+ "\uffff\1\1\1\2\2\uffff\1\10"; static final String DFA18_specialS = "\54\uffff}>"; static final String[] DFA18_transitionS = { "\2\22\2\uffff\1\22\22\uffff\1\22\1\uffff\1\13\5\uffff\1\20\4"+ "\uffff\1\11\1\16\1\12\12\uffff\1\5\1\3\1\14\3\uffff\1\4\5\15"+ "\1\7\10\15\1\6\13\15\1\17\3\uffff\1\15\1\uffff\6\15\1\1\12\15"+ "\1\10\4\15\1\2\3\15\1\21", "\1\23", "\1\24", "", "", "", "\1\25", "\1\26", "\1\27", "", "\1\31\4\uffff\1\30", "", "", "", "", "", "", "", "", "\1\32", "\1\33", "\12\15\7\uffff\32\15\4\uffff\1\15\1\uffff\32\15", "\1\35", "\1\36", "", "", "\1\37", "\1\40", "", "\1\41", "\1\42", "\1\43", "\1\44", "\12\15\7\uffff\32\15\4\uffff\1\15\1\uffff\32\15", "\1\46", "\12\15\7\uffff\32\15\4\uffff\1\15\1\uffff\32\15", "\12\15\7\uffff\32\15\4\uffff\1\15\1\uffff\32\15", "", "\1\51", "", "", "\1\52", "\12\15\7\uffff\32\15\4\uffff\1\15\1\uffff\32\15", "" }; static final short[] DFA18_eot = DFA.unpackEncodedString(DFA18_eotS); static final short[] DFA18_eof = DFA.unpackEncodedString(DFA18_eofS); static final char[] DFA18_min = DFA.unpackEncodedStringToUnsignedChars(DFA18_minS); static final char[] DFA18_max = DFA.unpackEncodedStringToUnsignedChars(DFA18_maxS); static final short[] DFA18_accept = DFA.unpackEncodedString(DFA18_acceptS); static final short[] DFA18_special = DFA.unpackEncodedString(DFA18_specialS); static final short[][] DFA18_transition; static { int numStates = DFA18_transitionS.length; DFA18_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { DFA18_transition[i] = DFA.unpackEncodedString(DFA18_transitionS[i]); } } class DFA18 extends DFA { public DFA18(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 18; this.eot = DFA18_eot; this.eof = DFA18_eof; this.min = DFA18_min; this.max = DFA18_max; this.accept = DFA18_accept; this.special = DFA18_special; this.transition = DFA18_transition; } public String getDescription() { return "1:1: Tokens : ( T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | SL_COMMENT | ML_COMMENT | STRING | ML_STRING | ID | EXT | RETVAL | AST | ACTION | WS );"; } } }
27.575383
197
0.371655
904c0f39e8da24d5c614011272ef0ed44cf2f3de
466
package javapolymorphism; public class Circle extends Shape { private double radius; Circle(double r) { radius = r; } @Override public void draw() { System.out.println("Circle.draw(), radius = "+radius); } @Override public void erase() { System.out.println("Circle.erase()"); } // переопределение закрытых методов не выполняется public void f() { System.out.println("Circle.f()"); } }
22.190476
62
0.596567
86c415a4f1b847095d9bcd32772fe5ced2e3a9ea
4,780
/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.internal.model.source; import java.util.Map; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeMirror; import org.mapstruct.ap.internal.gem.EnumMappingGem; import org.mapstruct.ap.internal.util.FormattingMessager; import org.mapstruct.ap.internal.util.Strings; import org.mapstruct.ap.spi.EnumTransformationStrategy; import static org.mapstruct.ap.internal.util.Message.ENUMMAPPING_INCORRECT_TRANSFORMATION_STRATEGY; import static org.mapstruct.ap.internal.util.Message.ENUMMAPPING_MISSING_CONFIGURATION; import static org.mapstruct.ap.internal.util.Message.ENUMMAPPING_NO_ELEMENTS; /** * @author Filip Hrisafov */ public class EnumMappingOptions extends DelegatingOptions { private final EnumMappingGem enumMapping; private final boolean inverse; private final boolean valid; private EnumMappingOptions(EnumMappingGem enumMapping, boolean inverse, boolean valid, DelegatingOptions next) { super( next ); this.enumMapping = enumMapping; this.inverse = inverse; this.valid = valid; } @Override public boolean hasAnnotation() { return enumMapping != null; } public boolean isValid() { return valid; } public boolean hasNameTransformationStrategy() { return hasAnnotation() && Strings.isNotEmpty( getNameTransformationStrategy() ); } public String getNameTransformationStrategy() { return enumMapping.nameTransformationStrategy().getValue(); } public String getNameTransformationConfiguration() { return enumMapping.configuration().getValue(); } @Override public TypeMirror getUnexpectedValueMappingException() { if ( enumMapping != null && enumMapping.unexpectedValueMappingException().hasValue() ) { return enumMapping.unexpectedValueMappingException().getValue(); } return next().getUnexpectedValueMappingException(); } public boolean isInverse() { return inverse; } public EnumMappingOptions inverse() { return new EnumMappingOptions( enumMapping, true, valid, next() ); } public static EnumMappingOptions getInstanceOn(ExecutableElement method, MapperOptions mapperOptions, Map<String, EnumTransformationStrategy> enumTransformationStrategies, FormattingMessager messager) { EnumMappingGem enumMapping = EnumMappingGem.instanceOn( method ); if ( enumMapping == null ) { return new EnumMappingOptions( null, false, true, mapperOptions ); } else if ( !isConsistent( enumMapping, method, enumTransformationStrategies, messager ) ) { return new EnumMappingOptions( null, false, false, mapperOptions ); } return new EnumMappingOptions( enumMapping, false, true, mapperOptions ); } private static boolean isConsistent(EnumMappingGem gem, ExecutableElement method, Map<String, EnumTransformationStrategy> enumTransformationStrategies, FormattingMessager messager) { String strategy = gem.nameTransformationStrategy().getValue(); String configuration = gem.configuration().getValue(); boolean isConsistent = false; if ( Strings.isNotEmpty( strategy ) || Strings.isNotEmpty( configuration ) ) { if ( !enumTransformationStrategies.containsKey( strategy ) ) { String registeredStrategies = Strings.join( enumTransformationStrategies.keySet(), ", " ); messager.printMessage( method, gem.mirror(), gem.nameTransformationStrategy().getAnnotationValue(), ENUMMAPPING_INCORRECT_TRANSFORMATION_STRATEGY, strategy, registeredStrategies ); return false; } else if ( Strings.isEmpty( configuration ) ) { messager.printMessage( method, gem.mirror(), gem.configuration().getAnnotationValue(), ENUMMAPPING_MISSING_CONFIGURATION ); return false; } isConsistent = true; } isConsistent = isConsistent || gem.unexpectedValueMappingException().hasValue(); if ( !isConsistent ) { messager.printMessage( method, gem.mirror(), ENUMMAPPING_NO_ELEMENTS ); } return isConsistent; } }
33.661972
116
0.653975
1a22e346c9ab0b2cca41fea3a7a35df6ffd8f8a5
2,173
package info.sleeplessacorn.nomagi.core.data; import info.sleeplessacorn.nomagi.Nomagi; import net.minecraft.client.resources.I18n; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.world.gen.structure.template.Template; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.io.IOException; import java.io.InputStream; public final class RoomData { private final ResourceLocation schematic; private final Template template; private final String name; private final String description; private final String file; public RoomData(ResourceLocation schematic) { String domain = schematic.getResourceDomain(); String path = schematic.getResourcePath(); this.schematic = schematic; this.template = getTemplateFromSchematic(schematic); this.name = String.format("room.%s.%s.name", domain, path); this.description = String.format("room.%s.%s.desc", domain, path); this.file = String.format("/assets/%s/rooms/nbt/%s.nbt", domain, path); } public RoomData(String schematic) { this(new ResourceLocation(Nomagi.ID, schematic)); } @SideOnly(Side.CLIENT) public String getName() { return I18n.format(name); } @SideOnly(Side.CLIENT) public String getDescription() { return I18n.format(description); } public ResourceLocation getSchematic() { return schematic; } public Template getTemplate() { return template; } private Template getTemplateFromSchematic(ResourceLocation schematic) { try { InputStream stream = Nomagi.class.getResourceAsStream(file); NBTTagCompound nbt = CompressedStreamTools.readCompressed(stream); Template template = new Template(); template.read(nbt); return template; } catch (IOException ignored) { Nomagi.LOGGER.error("Failed to parse NBT file for room <{}>!", schematic.toString()); return null; } } }
31.955882
97
0.687989
6675241a9371aac4a98e0c4c6ec2b702bf07f7d1
225
package com.avanse.springboot.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.avanse.springboot.model.Header; public interface HeaderRepository extends JpaRepository<Header, Long> { }
22.5
71
0.831111
732eef710ad1ec87391f41d86a2ec5da333611d3
658
package com.infdot.net.event.server; import com.infdot.net.event.Output; import com.infdot.net.event.User; import com.infdot.net.event.message.Message; /** * Client representation on the server side. * * @author Raivo Laanemets */ public abstract class Client extends User { private final Output output; private final ServerContext serverContext; public Client(Output output, ServerContext serverContext) { this.output = output; this.serverContext = serverContext; registerReceiver(this); } protected final void send(Message message) { output.send(message); } public ServerContext getServerContext() { return serverContext; } }
21.225806
60
0.758359
2b628aa30d338dd53cef1f07274d216fc9f3df83
7,786
package com.howietian.chenyan.competition; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.gson.Gson; import com.howietian.chenyan.BaseFragment; import com.howietian.chenyan.R; import com.howietian.chenyan.adapters.CompetitionAdapter; import com.howietian.chenyan.app.Constant; import com.howietian.chenyan.entities.Competition; import com.howietian.chenyan.home.MRankDetailActivity; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.datatype.BmobDate; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.FindListener; import static android.app.Activity.RESULT_OK; /** * A simple {@link Fragment} subclass. */ public class CompetitionFragment extends BaseFragment { public CompetitionFragment() { // Required empty public constructor } @Bind(R.id.recycleView) RecyclerView recycleView; @Bind(R.id.swipeLayout_article) SmartRefreshLayout swipeLayoutRank; private static final String COMPETITION_FRAGMENT = "competition_fragment"; private List<Competition> ranks = new ArrayList<>(); private CompetitionAdapter competitionAdapter; private LinearLayoutManager manager; private int lastVisibleItem; private int limit = Constant.LIMIT; public static final String FROM_Competition = "from_competition"; private static final int ARTICLE_REQUEST_CODE = 0; private static final int PULL_REFRESH = 0; private static final int LOAD_MORE = 1; private String lastTime; int currentPosition; public static CompetitionFragment newInstance(String args) { CompetitionFragment fragment = new CompetitionFragment(); Bundle bundle = new Bundle(); bundle.putString(COMPETITION_FRAGMENT, args); fragment.setArguments(bundle); return fragment; } @Override public View createMyView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_competion, container, false); } @Override public void init() { super.init(); swipeLayoutRank.autoRefresh(); manager = new LinearLayoutManager(getContext()); /** * 初始化加载数据 */ getData(PULL_REFRESH); competitionAdapter = new CompetitionAdapter(getContext(), ranks); // 设置布局方向 recycleView.setLayoutManager(manager); // 提高性能 recycleView.setHasFixedSize(true); // 设置Adapter recycleView.setAdapter(competitionAdapter); setItemClick(); refresh(); loadMore(); } /** * RecycleView Item 的点击事件 */ private void setItemClick() { competitionAdapter.setOnItemClickListener(new CompetitionAdapter.onItemClickListener() { @Override public void onClick(int position) { Intent intent = new Intent(getContext(), CompetitionDetailActivity.class); /** * 把Article对象转化为通过Gson转化为字符串,传递到详情页 */ currentPosition = position; Competition rank = ranks.get(position); String msg = new Gson().toJson(rank, Competition.class); intent.putExtra(FROM_Competition, msg); startActivityForResult(intent, ARTICLE_REQUEST_CODE); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ARTICLE_REQUEST_CODE && resultCode == RESULT_OK) { String commentNum = data.getStringExtra("commentNum"); ArrayList<String> likeIdList = data.getStringArrayListExtra("likeIdList"); Competition rank = ranks.get(currentPosition); Log.e("测试", commentNum); rank.setCommentNum(Integer.valueOf(commentNum)); rank.setLikeIdList(likeIdList); ranks.set(currentPosition, rank); } } /** * 刷新操作 */ private void refresh() { swipeLayoutRank.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(RefreshLayout refreshlayout) { getData(PULL_REFRESH); } }); } private void loadMore() { // 最后一个可以看到的item swipeLayoutRank.setOnLoadmoreListener(new OnLoadmoreListener() { @Override public void onLoadmore(RefreshLayout refreshlayout) { getData(LOAD_MORE); } }); } /** * 分页获取数据,分别为下拉刷新,上拉加载 */ private void getData(final int type) { BmobQuery<Competition> query = new BmobQuery<>(); query.order("-createdAt"); // 设置每页查询的item数目 query.setLimit(limit); // 加载更多 if (type == LOAD_MORE) { Date date = null; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { date = dateFormat.parse(lastTime); } catch (ParseException e) { e.printStackTrace(); } // 只查询小于等于最后一个item发表时间的数据 query.addWhereLessThanOrEqualTo("createdAt", new BmobDate(date)); } query.findObjects(new FindListener<Competition>() { @Override public void done(List<Competition> list, BmobException e) { if (e == null) { if (list.size() > 0) { if (type == PULL_REFRESH) { ranks.clear(); } ranks.addAll(list); competitionAdapter.notifyDataSetChanged(); // 获得最后一个item的创建时间 lastTime = ranks.get(ranks.size() - 1).getCreatedAt(); if (type == LOAD_MORE) { swipeLayoutRank.finishLoadmore(); } else { swipeLayoutRank.finishRefresh(); } } else { if (type == LOAD_MORE) { showToast(getString(R.string.no_data)); swipeLayoutRank.finishLoadmore(); } else { showToast(getString(R.string.no_data_article)); swipeLayoutRank.finishRefresh(); } } } else { showToast("请求服务器异常" + e.getMessage() + e.getErrorCode()); Log.e("测试", e.getMessage() + "==>" + e.getErrorCode()); if (type == PULL_REFRESH) { swipeLayoutRank.finishRefresh(); } else { swipeLayoutRank.finishLoadmore(); } } } }); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
31.144
103
0.601336
615a9fe2bfbec4813527468fb6d0d2af2b5337c6
2,350
package com.sap.cloud.lm.sl.cf.core.parser; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.cloudfoundry.client.lib.domain.CloudTask; import org.cloudfoundry.client.lib.domain.ImmutableCloudTask; import com.sap.cloud.lm.sl.cf.core.validators.parameters.TasksValidator; import com.sap.cloud.lm.sl.mta.util.PropertiesUtil; public class TaskParametersParser implements ParametersParser<List<CloudTask>> { private final String parameterName; private final CloudTaskMapper cloudTaskMapper = new CloudTaskMapper(); public TaskParametersParser(String parameterName) { this.parameterName = parameterName; } @Override public List<CloudTask> parse(List<Map<String, Object>> parametersList) { @SuppressWarnings("unchecked") List<Map<String, Object>> tasks = (List<Map<String, Object>>) PropertiesUtil.getPropertyValue(parametersList, parameterName, Collections.emptyList()); return tasks.stream() .map(cloudTaskMapper::toCloudTask) .collect(Collectors.toList()); } public static class CloudTaskMapper { public CloudTask toCloudTask(Map<String, Object> rawTask) { return ImmutableCloudTask.builder() .name(getProperty(rawTask, TasksValidator.TASK_NAME_KEY)) .command(getProperty(rawTask, TasksValidator.TASK_COMMAND_KEY)) .memory(parseMemory(rawTask)) .diskQuota(parseDiskQuota(rawTask)) .build(); } private Integer parseMemory(Map<String, Object> rawTask) { return MemoryParametersParser.parseMemory(getProperty(rawTask, TasksValidator.TASK_MEMORY_KEY)); } private Integer parseDiskQuota(Map<String, Object> rawTask) { return MemoryParametersParser.parseMemory(getProperty(rawTask, TasksValidator.TASK_DISK_QUOTA_KEY)); } @SuppressWarnings("unchecked") private <T> T getProperty(Map<String, Object> rawTask, String key) { return (T) rawTask.get(key); } } }
38.52459
132
0.631489
e3f45aa702c92cabe27851115e25ef30b8b8bd5b
640
package org.openvasp.client.service; import org.openvasp.client.model.EncryptionType; import org.openvasp.client.model.Topic; import org.openvasp.client.model.VaspMessage; /** * @author Olexandr_Bilovol@epam.com */ public interface MessageService { void send( Topic topic, EncryptionType encType, String key, VaspMessage message); long addTopicListener( Topic topic, EncryptionType encType, String key, TopicListener<VaspMessage> listener); void removeTopicListener( Topic topic, long listenerId); }
22.068966
49
0.6375
59e42c0f521f6a026005b2bdba847172fa7c6823
1,650
package com.web.produce.dao; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import com.web.produce.entity.CardData; import com.web.produce.entity.PatchCard; import java.util.Date; import java.util.List; import java.util.Map; public interface PatchCardDao extends CrudRepository<PatchCard, Long>,JpaSpecificationExecutor<PatchCard>{ public List<PatchCard> findAll(); public List<PatchCard> findByDelFlag(Integer delFlag); public PatchCard findById(long id); public int countByDelFlagAndEmpIdAndSignTimeAndSignDate(Integer delFlag,Long empId,String signTime,String signDate); @Query(value = "select c.class_no,c.id,c.class_name from MES_BASE_CLASS_TYPE c where c.del_flag=0 ", nativeQuery = true) public List<Map<String, Object>> queryClass(); // TO_DATE(?4, 'SYYYY-MM-DD HH24:MI:SS') @Modifying @Query(value = "INSERT INTO MES_ATT_SIGN_CARD(ID,EMP_ID,TASK_NO, CARD_TYPE, SIGN_DATE, CHECK_STATUS, CREATE_BY," + " CREATE_DATE, DEL_FLAG, CLASS_ID, LINE_ID, HOUR_TYPE, SIGN_TIME, " + " WORK_DATE) VALUES (seq_mes_att_sign_card.nextval, " + " ?1,?2,?3,?4,?5,?6,?7,0,?8,?9,?10,?11,?12)",nativeQuery = true) public Integer insertWithSeq(Long empId,String taskNo,String cardType,String signDate,Integer checkStatus,Long createBy, Date createDate,Long classId, Long lineId, String hourType,String signTime,String workDate); }
41.25
121
0.785455
c6877f018c8d5f6c63d7b08124456593819ab16a
3,600
package com.stylefeng.guns.core.log.factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.stylefeng.guns.common.constant.enums.LogSucceed; import com.stylefeng.guns.common.constant.enums.LogType; import com.stylefeng.guns.common.persistence.model.logs.LoginLog; import com.stylefeng.guns.common.persistence.model.logs.OperationLog; import com.stylefeng.guns.core.log.LogManager; import com.stylefeng.guns.core.util.SpringContextHolder; import com.stylefeng.guns.core.util.ToolUtil; import com.stylefeng.guns.modular.biz.service.ISystemLogService; /** * 日志操作任务创建工厂 */ public class LogTaskFactory { private static Logger logger = LoggerFactory.getLogger(LogManager.class); private static ISystemLogService systemLogService = SpringContextHolder.getBean(ISystemLogService.class); public static Runnable loginLog(final Integer userId, final String ip) { return new Runnable() { @Override public void run() { try { LoginLog loginLog = LogFactory.createLoginLog(LogType.LOGIN, userId, null, ip); systemLogService.saveLoginLog(loginLog); } catch (Exception e) { logger.error("创建登录日志异常!", e); } } }; } public static Runnable loginLog(final String username, final String msg, final String ip) { return new Runnable() { @Override public void run() { LoginLog loginLog = LogFactory.createLoginLog(LogType.LOGIN_FAIL, null, "账号:" + username + "," + msg, ip); try { systemLogService.saveLoginLog(loginLog); } catch (Exception e) { logger.error("创建登录失败异常!", e); } } }; } public static Runnable exitLog(final Integer userId, final String ip) { return new Runnable() { @Override public void run() { LoginLog loginLog = LogFactory.createLoginLog(LogType.EXIT, userId, null, ip); try { systemLogService.saveLoginLog(loginLog); } catch (Exception e) { logger.error("创建退出日志异常!", e); } } }; } public static Runnable bussinessLog(final Integer userId, final String bussinessName, final String clazzName, final String methodName, final String msg) { return new Runnable() { @Override public void run() { OperationLog operationLog = LogFactory.createOperationLog(LogType.BUSSINESS, userId, bussinessName, clazzName, methodName, msg, LogSucceed.SUCCESS); try { systemLogService.saveOperationLog(operationLog); } catch (Exception e) { logger.error("创建业务日志异常!", e); } } }; } public static Runnable exceptionLog(final Integer userId, final Exception exception) { return new Runnable() { @Override public void run() { String msg = ToolUtil.getExceptionMsg(exception); OperationLog operationLog = LogFactory.createOperationLog(LogType.EXCEPTION, userId, "", null, null, msg, LogSucceed.FAIL); try { systemLogService.saveOperationLog(operationLog); } catch (Exception e) { logger.error("创建异常日志异常!", e); } } }; } }
37.894737
139
0.586111
86dccd5763106af238fa2823655e2e46da6be1b8
2,659
// 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 com.intellij.codeInsight; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import consulo.disposer.Disposable; import consulo.util.dataholder.Key; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.TestOnly; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public abstract class AutoPopupController implements Disposable { /** * Settings this user data key to the editor with a completion provider * makes the autopopup scheduling ignore the state of the corresponding setting. * <p/> * This doesn't affect other conditions when autopopup is not possible (e.g. power save mode). */ public static final Key<Boolean> ALWAYS_AUTO_POPUP = Key.create("Always Show Completion Auto-Popup"); /** * If editor has Boolean.TRUE by this key completion popup would be shown without advertising text at the bottom. */ public static final Key<Boolean> NO_ADS = Key.create("Show Completion Auto-Popup without Ads"); /** * If editor has Boolean.TRUE by this key completion popup would be shown every time when editor gets focus. * For example this key can be used for TextFieldWithAutoCompletion. * (TextFieldWithAutoCompletion looks like standard JTextField and completion shortcut is not obvious to be active) */ public static final Key<Boolean> AUTO_POPUP_ON_FOCUS_GAINED = Key.create("Show Completion Auto-Popup On Focus Gained"); public static AutoPopupController getInstance(@Nonnull Project project) { return project.getComponent(AutoPopupController.class); } public abstract void autoPopupMemberLookup(Editor editor, @Nullable Condition<? super PsiFile> condition); public abstract void autoPopupMemberLookup(Editor editor, CompletionType completionType, @Nullable Condition<? super PsiFile> condition); public abstract void scheduleAutoPopup(@Nonnull Editor editor, @Nonnull CompletionType completionType, @Nullable Condition<? super PsiFile> condition); public abstract void scheduleAutoPopup(Editor editor); public abstract void cancelAllRequests(); public abstract void autoPopupParameterInfo(@Nonnull Editor editor, @Nullable Object highlightedMethod); @TestOnly public abstract void waitForDelayedActions(long timeout, @Nonnull TimeUnit unit) throws TimeoutException; }
44.316667
153
0.793155
7a34e28c55702903835aa2eedb63e924d4cbab16
183
package org.thingworld.event; public interface IEventMgr { String getTypeName(); String renderEntity(Event obj) throws Exception ; Event rehydrate(String json) throws Exception; }
22.875
50
0.797814
85e6c7647c5783d9ef5998e901b413bc4af4ffdb
324
package ArrayAssignment; class ArrayProduct { public static void main(String []args) { int arr1[]=new int[]{1,2,3,4,5}; int arr2[]=new int []{5,6,7,8,9}; int product=0; for(int i=0;i<arr1.length;i++) { for(int j=0;j<arr2.length;j++) { product = arr1[i]* arr2[j]; } } System.out.println(product); } }
14.727273
39
0.604938
2ef60042d4f2cd48e910301aed6198ac32a97651
659
package de.dlr.ivf.tapas.execution.sequential.action; import de.dlr.ivf.tapas.plan.TPS_PlanningContext; import de.dlr.ivf.tapas.execution.sequential.communication.TPS_HouseholdCarMediator; public class TPS_CarCheckInAction implements TPS_PlanStateAction { private TPS_HouseholdCarMediator car_mediator; private TPS_PlanningContext pc; public TPS_CarCheckInAction(TPS_HouseholdCarMediator car_mediator, TPS_PlanningContext pc){ this.car_mediator = car_mediator; this.pc = pc; } @Override public void run() { //this.car_mediator.checkinCar(this.pc.carForThisPlan); pc.carForThisPlan = null; } }
28.652174
95
0.757208
96f51b446d578acba251a27ffbda4d101f4aefb0
2,560
package seedu.thanepark.logic.commands; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.thanepark.commons.core.Messages.MESSAGE_RIDES_LISTED_OVERVIEW; import static seedu.thanepark.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.thanepark.testutil.TypicalRides.getTypicalThanePark; import java.util.Collections; import org.junit.Test; import seedu.thanepark.logic.CommandHistory; import seedu.thanepark.model.Model; import seedu.thanepark.model.ModelManager; import seedu.thanepark.model.UserPrefs; import seedu.thanepark.model.ride.RideStatusPredicate; import seedu.thanepark.model.ride.Status; /** * Contains integration tests (interaction with the Model) for {@code ViewStatusCommand}. */ public class ViewStatusCommandTest { private Model model = new ModelManager(getTypicalThanePark(), new UserPrefs()); private Model expectedModel = new ModelManager(getTypicalThanePark(), new UserPrefs()); private CommandHistory commandHistory = new CommandHistory(); @Test public void equals() { RideStatusPredicate firstPredicate = new RideStatusPredicate(Status.OPEN); RideStatusPredicate secondPredicate = new RideStatusPredicate(Status.MAINTENANCE); ViewStatusCommand firstCommand = new ViewStatusCommand(firstPredicate); ViewStatusCommand secondCommand = new ViewStatusCommand(secondPredicate); ViewStatusCommand thirdCommand = new ViewStatusCommand(firstPredicate); // same object -> returns true assertTrue(firstCommand.equals(firstCommand)); // same value -> returns true assertTrue(firstCommand.equals(thirdCommand)); // null -> returns false assertFalse(firstCommand.equals(null)); // different type -> returns false assertFalse(firstCommand.equals("open")); // different status -> returns false assertFalse(firstCommand.equals(secondCommand)); } @Test public void execute_noRideFound() { String expectedMessage = String.format(MESSAGE_RIDES_LISTED_OVERVIEW, 0); RideStatusPredicate predicate = new RideStatusPredicate(Status.MAINTENANCE); ViewStatusCommand command = new ViewStatusCommand(predicate); expectedModel.updateFilteredRideList(predicate); assertCommandSuccess(command, model, commandHistory, expectedMessage, expectedModel); assertEquals(Collections.emptyList(), model.getFilteredRideList()); } }
39.384615
93
0.761328
b12444cface029589f8585ff101cba1cab085869
3,551
package org.bpmscript.exec.java; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import junit.framework.TestCase; import org.bpmscript.benchmark.Benchmark; import org.bpmscript.benchmark.IBenchmarkCallback; import org.bpmscript.benchmark.IBenchmarkPrinter; import org.bpmscript.benchmark.IWaitForCallback; import org.bpmscript.integration.internal.ExceptionMessage; import org.bpmscript.integration.internal.IInternalMessage; import org.bpmscript.integration.internal.InvocationMessage; import org.bpmscript.integration.internal.adapter.RecordingAdapter; import org.bpmscript.integration.internal.memory.MemoryIntegrationTestSupport; import org.bpmscript.integration.internal.memory.MemoryMessageBus; import org.bpmscript.loanbroker.LoanRequest; import org.bpmscript.process.BpmScriptEngine; import org.bpmscript.process.IVersionedDefinitionManager; import org.bpmscript.test.IServiceLookup; import org.bpmscript.test.ITestCallback; /** * Have one script call another, using in memory bus and engine */ public class JavaLoanBrokerTest extends TestCase { private final transient org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory .getLog(getClass()); public void testChannel() throws Exception { MemoryIntegrationTestSupport integrationTestSupport = new MemoryIntegrationTestSupport(); integrationTestSupport.execute(new ITestCallback<IServiceLookup>() { public void execute(final IServiceLookup services) throws Exception { final int total = 100; final MemoryMessageBus bus = services.get("bus"); final BpmScriptEngine engine = services.get("engine"); IVersionedDefinitionManager processManager = engine.getVersionedDefinitionManager(); processManager.createDefinition("id", new JavaProcessDefinition("loanBroker", LoanBrokerProcess.class.getName())); IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() { public void execute(int count) throws Exception { InvocationMessage message = new InvocationMessage(); message.setArgs(null, "loanBroker", "requestBestRate", new Object[] { new LoanRequest("asdf", 1, 1000) }); message.setReplyTo("recorder"); bus.send("bpmscript-first", message); log.debug("sent message"); } }, new IWaitForCallback() { public void call() throws Exception { RecordingAdapter recorder = services.get("recording"); BlockingQueue<IInternalMessage> internalMessages = recorder.getMessages(); for(int i = 0; i < total; i++) { Object result = internalMessages.poll(total, TimeUnit.SECONDS); assertNotNull(result); if (result instanceof ExceptionMessage) { ExceptionMessage exceptionMessage = (ExceptionMessage) result; log.error(exceptionMessage.getThrowable(), exceptionMessage.getThrowable()); fail(exceptionMessage.getThrowable().getMessage()); } } } }, false)); } }); } }
46.723684
130
0.642636
f501c0cdad1c6c3d0903e8859b961402a25a4105
4,233
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.proxy2.interceptor; import java.io.Serializable; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.proxy2.Interceptor; import org.apache.commons.proxy2.Invocation; import org.apache.commons.proxy2.interceptor.matcher.InvocationMatcher; /** * A {@link SwitchInterceptor} maintains a list of * {@link org.apache.commons.proxy2.interceptor.matcher.InvocationMatcher}/{@link Interceptor} pairs. Each invocation * will be checked against the registered InvocationMatchers. If one matches the current invocation, then the * corresponding Interceptor will be called. If no InvocationMatchers match, the * {@link org.apache.commons.proxy2.Invocation#proceed()} method is called with no interception. */ public class SwitchInterceptor implements Interceptor, Serializable { //****************************************************************************************************************** // Fields //****************************************************************************************************************** private static final long serialVersionUID = 1L; private final List<Pair<InvocationMatcher, Interceptor>> cases = new CopyOnWriteArrayList<Pair<InvocationMatcher, Interceptor>>(); //****************************************************************************************************************** // Constructors //****************************************************************************************************************** public SwitchInterceptor() { } //****************************************************************************************************************** // Interceptor Implementation //****************************************************************************************************************** @Override public Object intercept(Invocation invocation) throws Throwable { for (Pair<InvocationMatcher, Interceptor> currentCase : cases) { if (currentCase.getLeft().matches(invocation)) { return currentCase.getRight().intercept(invocation); } } return invocation.proceed(); } //****************************************************************************************************************** // Other Methods //****************************************************************************************************************** public CaseBuilder when(InvocationMatcher matcher) { return new CaseBuilder(matcher); } //****************************************************************************************************************** // Inner Classes //****************************************************************************************************************** public class CaseBuilder { private final InvocationMatcher matcher; private CaseBuilder(InvocationMatcher matcher) { this.matcher = matcher; } public SwitchInterceptor then(Interceptor interceptor) { cases.add(new ImmutablePair<InvocationMatcher, Interceptor>(matcher, interceptor)); return SwitchInterceptor.this; } } }
41.5
120
0.513111
a816d8276cba41e78339fc6aed2bc2308f0f515a
1,414
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 申请电子签章 * * @author auto create * @since 1.0, 2022-05-31 15:23:26 */ public class AlipayDataBillEreceiptApplyModel extends AlipayObject { private static final long serialVersionUID = 6392165547979899758L; /** * 授权商户pid。需调用方获取商户授权,才可使用。 */ @ApiField("bill_user_id") private String billUserId; /** * 根据不同业务类型,传入不同参数。 格式如下: * ACCOUNT_LOG_DETAIL - 传入账务流水号,示例:117007*********9151 * ACCOUNT_FLOW_DETAIL - 传入流水日期区间示例:20220301-20220331 * FUND_DETAIL - 传入资金单据号,示例:2022051511007***************0731 * ACCOUNT_LOG_SUM_DAILY - 传入日期,示例:2022-01-01 * ACCOUNT_LOG_SUM_MONTHLY - 传入月份,示例:2022-01 */ @ApiField("key") private String key; /** * 申请的类型。可传入: * ACCOUNT_LOG_DETAIL - 余额收支证明 * ACCOUNT_FLOW_DETAIL - 余额收支流水证明 * FUND_DETAIL - 转入转出收支证明 * ACCOUNT_LOG_SUM_DAILY - 收支汇总证明(日汇总) * ACCOUNT_LOG_SUM_MONTHLY - 收支汇总证明(月汇总) */ @ApiField("type") private String type; public String getBillUserId() { return this.billUserId; } public void setBillUserId(String billUserId) { this.billUserId = billUserId; } public String getKey() { return this.key; } public void setKey(String key) { this.key = key; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } }
21.104478
69
0.687412
f748365a720fa412832753000cbda59495f82caf
3,553
/* * Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * * 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.maxkey.autoconfigure; import com.nimbusds.jose.JOSEException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import org.maxkey.authn.support.jwt.JwtLoginService; import org.maxkey.crypto.jose.keystore.JWKSetKeyStore; import org.maxkey.crypto.jwt.signer.service.impl.DefaultJwtSigningAndValidationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; @Configuration public class JwtAuthnAutoConfiguration implements InitializingBean { private static final Logger _logger = LoggerFactory.getLogger(JwtAuthnAutoConfiguration.class); /** * jwt Login JwkSetKeyStore. * @return */ @Bean(name = "jwtLoginJwkSetKeyStore") public JWKSetKeyStore jwtLoginJwkSetKeyStore() { JWKSetKeyStore jwkSetKeyStore = new JWKSetKeyStore(); ClassPathResource classPathResource = new ClassPathResource("/config/loginjwkkeystore.jwks"); jwkSetKeyStore.setLocation(classPathResource); _logger.debug("JWT Login JwkSet KeyStore init."); return jwkSetKeyStore; } /** * jwt Login ValidationService. * @return * @throws JOSEException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException */ @Bean(name = "jwtLoginValidationService") public DefaultJwtSigningAndValidationService jwtLoginValidationService( JWKSetKeyStore jwtLoginJwkSetKeyStore) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { DefaultJwtSigningAndValidationService jwtSignerValidationService = new DefaultJwtSigningAndValidationService(jwtLoginJwkSetKeyStore); jwtSignerValidationService.setDefaultSignerKeyId("maxkey_rsa"); jwtSignerValidationService.setDefaultSigningAlgorithmName("RS256"); _logger.debug("JWT Login Signing and Validation init."); return jwtSignerValidationService; } /** * Jwt LoginService. * @return */ @Bean(name = "jwtLoginService") public JwtLoginService jwtLoginService( @Value("${maxkey.login.jwt.issuer}") String issuer, DefaultJwtSigningAndValidationService jwtLoginValidationService) { JwtLoginService jwtLoginService = new JwtLoginService( jwtLoginValidationService, issuer ); _logger.debug("JWT Login Service init."); return jwtLoginService; } @Override public void afterPropertiesSet() throws Exception { // TODO Auto-generated method stub } }
37.010417
101
0.726147
033ae575f503f08e2e6ce457ba9d77bbda35c433
3,526
package com.ToxicBakery.app.screenshot_redaction.ocr.engine; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.IntRange; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.ToxicBakery.app.screenshot_redaction.R; import com.ToxicBakery.app.screenshot_redaction.ActivityTest; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Collection; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(AndroidJUnit4.class) public class TessTwoOcrEngineTest { @Rule public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class); private Context getContext() { return activityTestRule.getActivity(); } private static Bitmap genBitmap(int width, int height, String text) { Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Paint paint = new Paint(); Canvas canvas = new Canvas(bitmap); canvas.drawColor(Color.WHITE); paint.setColor(Color.BLACK); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); paint.setTextAlign(Paint.Align.CENTER); paint.setTextSize(24.0f); canvas.drawText(text, width / 2, height / 2, paint); return bitmap; } @Before public void setUp() throws Exception { File tessData = new File(getContext().getExternalFilesDir(null), "tessdata"); assertTrue(tessData.exists() || tessData.mkdirs()); File target = new File(tessData, "eng.traineddata"); InputStream inputStream = getContext().getResources() .openRawResource(R.raw.eng); OutputStream outputStream = new FileOutputStream(target); IOUtils.copyLarge(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } @Test public void testGetWordResults() throws Exception { Bitmap bitmap = genBitmap(640, 480, "Hello"); TessTwoOcrEngine tessTwoOcrEngine = new TessTwoOcrEngine(); tessTwoOcrEngine.init(getContext()); Collection<OcrWordResult> wordResults = tessTwoOcrEngine.getWordResults(bitmap, new EmptyProgress()); tessTwoOcrEngine.recycle(); assertEquals(1, wordResults.size()); OcrWordResult[] ocrWordResults = wordResults.toArray(new OcrWordResult[1]); assertEquals("Hello", ocrWordResults[0].getWord()); assertTrue(ocrWordResults[0].getWordConfidence() > 0.9d); } @Test public void testBlankImage() throws Exception { Bitmap bitmap = genBitmap(640, 480, ""); TessTwoOcrEngine tessTwoOcrEngine = new TessTwoOcrEngine(); tessTwoOcrEngine.init(getContext()); Collection<OcrWordResult> wordResults = tessTwoOcrEngine.getWordResults(bitmap, new EmptyProgress()); tessTwoOcrEngine.recycle(); assertEquals(0, wordResults.size()); } static class EmptyProgress implements IOcrEngine.IOcrProgress { @Override public void onProgress(@IntRange(from = 0, to = 100) int progress) { } } }
32.953271
109
0.711004
4d348b96823476f865c92e456f6fec42b7fb4ff2
422
package fr.eurecom.adel.shell; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan("fr.eurecom.adel") public class ADELShellApplication { public static void main(final String... args) { SpringApplication.run(ADELShellApplication.class, args); } }
30.142857
68
0.824645
086670312061965f419f2be646921ba3d9e4dad7
2,867
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.ci.github.pure; import com.google.common.base.Strings; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import org.apache.ignite.ci.github.GitHubBranchShort; import org.apache.ignite.ci.github.PullRequest; import org.apache.ignite.ci.tcbot.conf.IGitHubConfig; import org.jetbrains.annotations.Nullable; import javax.annotation.Nonnull; /** * GitHub pure connection */ public interface IGitHubConnection { public void init(String srvCode); /** */ public PullRequest getPullRequest(Integer id); /** * Send POST request with given body. * * @param url Url. * @param body Request body. * @return {@code True} - if GitHub was notified. {@code False} - otherwise. */ public boolean notifyGit(String url, String body); /** * @param fullUrl Full url - null for first page, not null for next page. * @param outLinkNext Out link for return next page full url. */ public List<PullRequest> getPullRequestsPage(@Nullable String fullUrl, @Nullable AtomicReference<String> outLinkNext); /** * @param fullUrl Full url - null for first page, not null for next page. * @param outLinkNext Out link for return next page full url. */ public List<GitHubBranchShort> getBranchesPage(@Nullable String fullUrl, @Nonnull AtomicReference<String> outLinkNext); /** * @return PR id from string "pull/XXXX/head" */ @Nullable public static Integer convertBranchToPrId(String branchForTc) { Integer res = null; if (Objects.isNull(branchForTc)) return res; String id = null; for (int i = 5; i < branchForTc.length(); i++) { char c = branchForTc.charAt(i); if (!Character.isDigit(c)) { id = branchForTc.substring(5, i); break; } } return Strings.isNullOrEmpty(id) ? null : Integer.parseInt(id); } /** * */ public IGitHubConfig config(); }
32.213483
123
0.681549
4f91da2f1852c0755dc22b2f004af20a0b0e67fa
16,139
package com.CMS.CentralParam.KKBSK.controller; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import javax.validation.constraints.NotNull; import com.CMS.CentralParam.KKBSK.config.HelperConf; import com.CMS.CentralParam.KKBSK.excel.RateBungaExcelExporter; import com.CMS.CentralParam.KKBSK.model.data.RateBunga; import com.CMS.CentralParam.KKBSK.model.form.RateBungaForm; import com.CMS.CentralParam.KKBSK.model.request.RequestMassSubmit; import com.CMS.CentralParam.KKBSK.model.response.ResponCekToken; import com.CMS.CentralParam.KKBSK.model.response.ResponCluster; import com.CMS.CentralParam.KKBSK.model.response.ResponJenisKendaraan; import com.CMS.CentralParam.KKBSK.model.response.ResponJenisPembiayaan; import com.CMS.CentralParam.KKBSK.model.response.ResponRateBunga; import com.CMS.CentralParam.KKBSK.view.vwRateBunga; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; 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.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.client.RestTemplate; @Controller public class RateBungaController { @Autowired RestTemplate restTemplate; @Value("${apiBaseUrl}") private String apiBaseUrl; ObjectMapper objectMapper = new ObjectMapper(); @RequestMapping(value = "/RateBunga/InputData", method = RequestMethod.GET) public String RateBungaInputData(Model model) { try { restTemplate.exchange(apiBaseUrl+"api/helper/cekToken",HttpMethod.POST, HelperConf.getHeader(), ResponCekToken.class); ResponseEntity<ResponJenisPembiayaan> responJenisPembiayaan = restTemplate.exchange( apiBaseUrl+"api/jenispembiayaan/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponJenisPembiayaan.class); model.addAttribute("listJenisPembiayaan",responJenisPembiayaan.getBody().getDataJenisPembiayaan()); ResponseEntity<ResponJenisKendaraan> responJenisKendaraan = restTemplate.exchange( apiBaseUrl+"api/jeniskendaraan/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponJenisKendaraan.class); model.addAttribute("listJenisKendaraan",responJenisKendaraan.getBody().getDataJenisKendaraan()); ResponseEntity<ResponCluster> responCluster = restTemplate.exchange( apiBaseUrl+"api/cluster/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponCluster.class); model.addAttribute("listCluster",responCluster.getBody().getDataCluster()); RateBungaForm rateBungaForm = new RateBungaForm(); rateBungaForm.setLoanType(0); rateBungaForm.setJenisKendaraan(0); model.addAttribute("rateBunga", rateBungaForm); return "pages/MasterParameter/RateBunga/InputData"; } catch (Exception e) { System.out.println("Error : "+e.toString()); SecurityContextHolder.getContext().setAuthentication(null); } return "pages/expired/token"; } @GetMapping("/RateBunga/Export/Excel") public void exportToExcel(HttpServletResponse response) throws IOException { response.setContentType("application/octet-stream"); DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); String currentDateTime = dateFormatter.format(new Date()); String headerKey = "Content-Disposition"; String headerValue = "attachment; filename=RateBunga_" + currentDateTime + ".xlsx"; response.setHeader(headerKey, headerValue); ResponseEntity<ResponRateBunga> respon = restTemplate.exchange( apiBaseUrl+"api/ratebunga/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponRateBunga.class); List<vwRateBunga> listRateBunga = respon.getBody().getDataRateBunga(); RateBungaExcelExporter excelExporter = new RateBungaExcelExporter(listRateBunga); excelExporter.export(response); } @PostMapping(value = "/RateBunga/ActionInputData") public String RateBungaActionInputData(@Valid RateBungaForm rateBunga, BindingResult result,String action,Model model) { if(!result.hasErrors()) { if(rateBunga.getEndBerlaku().before(rateBunga.getStartBerlaku())) { result.rejectValue("endBerlaku", "error.rateBunga", "End date must be greater than start date"); } if(rateBunga.getCluster().size() == 0) { result.rejectValue("cluster", "error.rateBunga", "You must choose Cluster"); } if(rateBunga.getJenisPembiayaan().size() == 0) { result.rejectValue("jenisPembiayaan", "error.rateBunga", "You must choose Jenis Pembiayaan"); } } if (result.hasErrors()) { ResponseEntity<ResponJenisPembiayaan> responJenisPembiayaan = restTemplate.exchange( apiBaseUrl+"api/jenispembiayaan/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponJenisPembiayaan.class); model.addAttribute("listJenisPembiayaan",responJenisPembiayaan.getBody().getDataJenisPembiayaan()); ResponseEntity<ResponJenisKendaraan> responJenisKendaraan = restTemplate.exchange( apiBaseUrl+"api/jeniskendaraan/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponJenisKendaraan.class); model.addAttribute("listJenisKendaraan",responJenisKendaraan.getBody().getDataJenisKendaraan()); ResponseEntity<ResponCluster> responCluster = restTemplate.exchange( apiBaseUrl+"api/cluster/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponCluster.class); model.addAttribute("listCluster",responCluster.getBody().getDataCluster()); model.addAttribute("rateBunga", rateBunga); return "pages/MasterParameter/RateBunga/InputData"; } try { rateBunga.getCluster().forEach((cluster) -> { rateBunga.getJenisPembiayaan().forEach((jenisPembiayaan) -> { RateBunga temp = new RateBunga(null, rateBunga.getNamaSkema(), rateBunga.getLoanType(), rateBunga.getJenisKendaraan(), jenisPembiayaan, cluster, rateBunga.getStartTahunKendaraan(), rateBunga.getEndTahun(), rateBunga.getTenor1(), rateBunga.getTenor2(), rateBunga.getTenor3(), rateBunga.getTenor4(), rateBunga.getTenor5Periode1(), rateBunga.getTenor5Periode2(), rateBunga.getTenor5Rate1(), rateBunga.getTenor5Rate2(), rateBunga.getTenor6Periode1(), rateBunga.getTenor6Periode2(), rateBunga.getTenor6Rate1(), rateBunga.getTenor6Rate2(), rateBunga.getTenor7Periode1(), rateBunga.getTenor7Periode2(), rateBunga.getTenor7Rate1(), rateBunga.getTenor7Rate2(), rateBunga.getTenor8Periode1(), rateBunga.getTenor8Periode2(), rateBunga.getTenor8Rate1(), rateBunga.getTenor8Rate2(), rateBunga.getTenor9Periode1(), rateBunga.getTenor9Periode2(), rateBunga.getTenor9Rate1(), rateBunga.getTenor9Rate2(), rateBunga.getTenor10Periode1(), rateBunga.getTenor10Periode2(), rateBunga.getTenor10Rate1(), rateBunga.getTenor10Rate2(), rateBunga.getStartBerlaku(), rateBunga.getEndBerlaku(), null, null, null, null, null, null, null, null); try { restTemplate.exchange( apiBaseUrl+"/api/ratebunga/"+HelperConf.getAction(action), HttpMethod.POST, HelperConf.getHeader(objectMapper.writeValueAsString(temp)), String.class ); } catch (Exception e) { } }); }); return "redirect:/RateBunga/Data"; } catch (Exception e) { System.out.println("Error : "+e.toString()); SecurityContextHolder.getContext().setAuthentication(null); } return "pages/expired/token"; } @PostMapping(value = "/RateBunga/ActionEditData") public String RateBungaActionEditData(@Valid RateBunga rateBunga, BindingResult result,String action,Model model) { if(!result.hasErrors()) { if(rateBunga.getEndBerlaku().before(rateBunga.getStartBerlaku())) { result.rejectValue("endBerlaku", "error.rateBunga", "End date must be greater than start date"); } } if (result.hasErrors()) { ResponseEntity<ResponJenisPembiayaan> responJenisPembiayaan = restTemplate.exchange( apiBaseUrl+"api/jenispembiayaan/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponJenisPembiayaan.class); model.addAttribute("listJenisPembiayaan",responJenisPembiayaan.getBody().getDataJenisPembiayaan()); ResponseEntity<ResponJenisKendaraan> responJenisKendaraan = restTemplate.exchange( apiBaseUrl+"api/jeniskendaraan/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponJenisKendaraan.class); model.addAttribute("listJenisKendaraan",responJenisKendaraan.getBody().getDataJenisKendaraan()); ResponseEntity<ResponCluster> responCluster = restTemplate.exchange( apiBaseUrl+"api/cluster/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponCluster.class); model.addAttribute("listCluster",responCluster.getBody().getDataCluster()); model.addAttribute("rateBunga", rateBunga); return "pages/MasterParameter/RateBunga/EditData"; } try { restTemplate.exchange( apiBaseUrl+"/api/ratebunga/"+HelperConf.getAction(action), HttpMethod.POST, HelperConf.getHeader(objectMapper.writeValueAsString(rateBunga)), String.class ); return "redirect:/RateBunga/Data"; } catch (Exception e) { System.out.println("Error : "+e.toString()); SecurityContextHolder.getContext().setAuthentication(null); } return "pages/expired/token"; } @PostMapping(value = "/RateBunga/ActionApprovalData") public String RateBungaActionApprovalData(RateBunga rateBunga, BindingResult result,String action) { try { restTemplate.exchange( apiBaseUrl+"/api/ratebunga/"+action+"Data", HttpMethod.POST, HelperConf.getHeader(objectMapper.writeValueAsString(rateBunga)), String.class ); return "redirect:/RateBunga/ApprovalData"; } catch (Exception e) { System.out.println("Error : "+e.toString()); SecurityContextHolder.getContext().setAuthentication(null); } return "pages/expired/token"; } @PostMapping(value = "/RateBunga/ActionData") public String RateBungaActionData(@RequestParam("ids") String ids,String action) { try { RequestMassSubmit requestMassSubmit = new RequestMassSubmit(ids); restTemplate.exchange( apiBaseUrl+"/api/ratebunga/"+action, HttpMethod.POST, HelperConf.getHeader(objectMapper.writeValueAsString(requestMassSubmit)), String.class ); return "redirect:/RateBunga/Data"; } catch (Exception e) { System.out.println("Error : "+e.toString()); SecurityContextHolder.getContext().setAuthentication(null); } return "pages/expired/token"; } @PostMapping(value = "/RateBunga/ActionApproval") public String RateBungaActionApproval(@RequestParam("ids") String ids,String action) { try { RequestMassSubmit requestMassSubmit = new RequestMassSubmit(ids); restTemplate.exchange( apiBaseUrl+"/api/ratebunga/"+action, HttpMethod.POST, HelperConf.getHeader(objectMapper.writeValueAsString(requestMassSubmit)), String.class ); return "redirect:/RateBunga/ApprovalData"; } catch (Exception e) { System.out.println("Error : "+e.toString()); SecurityContextHolder.getContext().setAuthentication(null); } return "pages/expired/token"; } @RequestMapping(value = "/RateBunga/EditData/{id}", method = RequestMethod.GET) public String RateBungaEditData(@PathVariable @NotNull Integer id,Model model) { try { ResponseEntity<ResponRateBunga> respon = restTemplate.exchange( apiBaseUrl+"/api/ratebunga/"+id, HttpMethod.GET, HelperConf.getHeader(), ResponRateBunga.class ); model.addAttribute("rateBunga",respon.getBody().getRateBunga()); ResponseEntity<ResponJenisPembiayaan> responJenisPembiayaan = restTemplate.exchange( apiBaseUrl+"api/jenispembiayaan/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponJenisPembiayaan.class); model.addAttribute("listJenisPembiayaan",responJenisPembiayaan.getBody().getDataJenisPembiayaan()); ResponseEntity<ResponJenisKendaraan> responJenisKendaraan = restTemplate.exchange( apiBaseUrl+"api/jeniskendaraan/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponJenisKendaraan.class); model.addAttribute("listJenisKendaraan",responJenisKendaraan.getBody().getDataJenisKendaraan()); ResponseEntity<ResponCluster> responCluster = restTemplate.exchange( apiBaseUrl+"api/cluster/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponCluster.class); model.addAttribute("listCluster",responCluster.getBody().getDataCluster()); return "pages/MasterParameter/RateBunga/EditData"; } catch (Exception e) { System.out.println("Error : "+e.toString()); SecurityContextHolder.getContext().setAuthentication(null); } return "pages/expired/token"; } @GetMapping(value = { "/RateBunga/Data" }) public String getListRateBunga(Model model) { try { ResponseEntity<ResponRateBunga> respon = restTemplate.exchange( apiBaseUrl+"api/ratebunga/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponRateBunga.class); model.addAttribute("listRateBunga", respon.getBody().getDataRateBunga()); return "pages/MasterParameter/RateBunga/Data"; } catch (Exception e) { System.out.println("Error : "+e.toString()); SecurityContextHolder.getContext().setAuthentication(null); } return "pages/expired/token"; } @GetMapping(value = { "/RateBunga/ApprovalData" }) public String getListApprovalRateBunga(Model model) { try { ResponseEntity<ResponRateBunga> respon = restTemplate.exchange( apiBaseUrl+"api/ratebunga/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponRateBunga.class); model.addAttribute("listRateBunga", respon.getBody().getDataRateBunga()); return "pages/MasterParameter/RateBunga/ApprovalData"; } catch (Exception e) { System.out.println("Error : "+e.toString()); SecurityContextHolder.getContext().setAuthentication(null); } return "pages/expired/token"; } @RequestMapping(value = "/RateBunga/FormApprovalData/{id}", method = RequestMethod.GET) public String RateBungaFormApprovalData(@PathVariable @NotNull Integer id,Model model) { try { ResponseEntity<ResponRateBunga> respon = restTemplate.exchange( apiBaseUrl+"/api/ratebunga/"+id, HttpMethod.GET, HelperConf.getHeader(), ResponRateBunga.class ); model.addAttribute("rateBunga",respon.getBody().getRateBunga()); ResponseEntity<ResponJenisPembiayaan> responJenisPembiayaan = restTemplate.exchange( apiBaseUrl+"api/jenispembiayaan/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponJenisPembiayaan.class); model.addAttribute("listJenisPembiayaan",responJenisPembiayaan.getBody().getDataJenisPembiayaan()); ResponseEntity<ResponJenisKendaraan> responJenisKendaraan = restTemplate.exchange( apiBaseUrl+"api/jeniskendaraan/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponJenisKendaraan.class); model.addAttribute("listJenisKendaraan",responJenisKendaraan.getBody().getDataJenisKendaraan()); ResponseEntity<ResponCluster> responCluster = restTemplate.exchange( apiBaseUrl+"api/cluster/getalldata", HttpMethod.POST, HelperConf.getHeader(), ResponCluster.class); model.addAttribute("listCluster",responCluster.getBody().getDataCluster()); return "pages/MasterParameter/RateBunga/FormApprovalData"; } catch (Exception e) { System.out.println("Error : "+e.toString()); SecurityContextHolder.getContext().setAuthentication(null); } return "pages/expired/token"; } }
41.276215
127
0.76089
724cb74fc759b1f1c7ce4722716ea087b981e7f8
446
package com.eu.habbo.plugin.events.users; import com.eu.habbo.habbohotel.users.Habbo; public class UserSavedSettingsEvent extends UserEvent { /** * Fired when a user changes it settings regarding: * - Volumes * - Camera following * - Ignoring room invites * - Chat mode. * @param habbo The Habbo this event applies to. */ public UserSavedSettingsEvent(Habbo habbo) { super(habbo); } }
22.3
55
0.654709
d821c623cb6bd690bd6eda84a030a3e6f13a262b
121
%OPTION_NAME%.setArgs(%ARGS_COUNT%); %OPTION_NAME%.setOptionalArg(false); %OPTION_NAME%.setArgName("%ARG_DESCRIPTION%");
30.25
46
0.77686
f1cfda83ed7d366db54bc8567d25f23b818e79e9
4,746
/* * Copyright 2015-2017 EntIT Software LLC, a Micro Focus company. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.cafdataprocessing.worker.policy.converters; import com.github.cafdataprocessing.corepolicy.common.Document; import com.github.cafdataprocessing.corepolicy.common.DocumentImpl; import com.github.cafdataprocessing.corepolicy.multimap.utils.CaseInsensitiveMultimap; import com.github.cafdataprocessing.worker.policy.common.DataStoreAwareInputStream; import com.hpe.caf.api.worker.DataStoreSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.Map; import java.util.stream.Collectors; /** * Logic for converting between Core Policy Document and worker-policy-shared Document types */ public class DocumentConverter { private static Logger logger = LoggerFactory.getLogger(DocumentConverter.class); public Document convert(com.github.cafdataprocessing.worker.policy.shared.Document document, DataStoreSource dataStoreSource) { DocumentImpl newDocument = new DocumentImpl(); CaseInsensitiveMultimap<String> metadata = newDocument.getMetadata(); // add all metadata. if (document.getMetadata() != null) { document.getMetadata().entries().stream() .filter(entry -> entry.getValue() != null) .forEach(entry -> metadata.put(entry.getKey(), entry.getValue())); } // add all doc references, as inputStreams to the target document. if (document.getMetadataReferences() != null) { document.getMetadataReferences().entries().stream() .filter(entry -> entry.getValue() != null) .forEach(entry -> { // create the lazy initialized stream using the unique reference for the DataStore. DataStoreAwareInputStream smartStream = new DataStoreAwareInputStream(entry.getValue(), dataStoreSource); newDocument.getStreams().put(entry.getKey(), smartStream); }); } newDocument.setFullMetadata(true); if (document.getDocuments() != null) { newDocument.getDocuments().addAll(document.getDocuments().stream().map(u -> convert(u, dataStoreSource)).collect(Collectors.toList())); } newDocument.setReference(document.getReference()); return newDocument; } /** * Converts the core policy document provided to a worker policy representation, copying metadata and streams to * metadata and metadata reference fields and converting any sub-documents also. * @param document Core policy document to convert * @return Converted version of passed document. */ public com.github.cafdataprocessing.worker.policy.shared.Document convert(Document document) { com.github.cafdataprocessing.worker.policy.shared.Document newDocument = new com.github.cafdataprocessing.worker.policy.shared.Document(); newDocument.setReference(document.getReference()); if (document.getMetadata() != null) { for (Map.Entry<String, String> entry : document.getMetadata().entries()) { newDocument.getMetadata().put(entry.getKey(), entry.getValue()); } } //copy the ReferenceData of any DataStoreAwareInputStreams as metadata references on new document if(document.getStreams() != null) { for (Map.Entry<String, InputStream> streamEntry : document.getStreams().entries()){ if(streamEntry.getValue() == null || !(streamEntry.getValue() instanceof DataStoreAwareInputStream)){ continue; } DataStoreAwareInputStream asDataStoreStreamEntry = (DataStoreAwareInputStream) streamEntry.getValue(); newDocument.getMetadataReferences().put(streamEntry.getKey(), asDataStoreStreamEntry.getReferencedData()); } } if (document.getDocuments() != null) { newDocument.setDocuments(document.getDocuments().stream().map(this::convert).collect(Collectors.toList())); } return newDocument; } }
45.634615
147
0.684366
0357470543eac905f300c3f55cc293e12e36e7ed
376
package com.Algorithm.Bubble_Sort; import org.junit.jupiter.api.Test; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.*; class Bubble_SortTest { @Test void bubbleSort() { int[] testArray={1042,33,4,67,5,89,123,456,777,3456,121,0,961127,-1,-122}; System.out.print(Arrays.toString(Bubble_Sort.BubbleSort(testArray))); } }
23.5
82
0.704787
515704c92421d1dbb2f1ec85ef20ae2575944719
1,937
/* * This file is part of dependency-check-core. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) 2015 The OWASP Foundatio. All Rights Reserved. */ package org.owasp.dependencycheck; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author jeremy */ public class AppTest { public AppTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of ensureCanonicalPath method, of class App. */ @Test public void testEnsureCanonicalPath() { String file = "../*.jar"; App instance = new App(); String result = instance.ensureCanonicalPath(file); assertFalse(result.contains("..")); assertTrue(result.endsWith("*.jar")); } /** * Test of ensureCanonicalPath method, of class App. */ @Test public void testEnsureCanonicalPath2() { String file = "../some/skip/../path/file.txt"; App instance = new App(); String expResult = "/some/path/file.txt"; String result = instance.ensureCanonicalPath(file); assertTrue("result=" + result, result.endsWith(expResult)); } }
25.486842
75
0.655653
d33cf9dcd4ec31c8d3c98ee5eec4acd8bcf629ae
7,012
package com.project.convertedCode.globalNamespace.classes; import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs; import com.runtimeconverter.runtime.classes.StaticBaseClass; import com.runtimeconverter.runtime.classes.RuntimeClassBase; import com.runtimeconverter.runtime.RuntimeEnv; import com.runtimeconverter.runtime.ZVal; import com.runtimeconverter.runtime.reflection.ReflectionClassData; import com.runtimeconverter.runtime.annotations.ConvertedParameter; import com.runtimeconverter.runtime.arrays.ZPair; import com.project.convertedCode.globalNamespace.classes.Swift_KeyCache; import java.lang.invoke.MethodHandles; import com.runtimeconverter.runtime.classes.NoConstructor; import com.project.convertedCode.globalNamespace.classes.Swift_KeyCache_KeyCacheInputStream; import com.runtimeconverter.runtime.annotations.ConvertedMethod; import static com.runtimeconverter.runtime.ZVal.assignParameter; /* Converted with The Runtime Converter (runtimeconverter.com) vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php */ public class Swift_KeyCache_SimpleKeyCacheInputStream extends RuntimeClassBase implements Swift_KeyCache_KeyCacheInputStream { public Object keyCache = null; public Object nsKey = null; public Object itemKey = null; public Object writeThrough = ZVal.getNull(); public Swift_KeyCache_SimpleKeyCacheInputStream(RuntimeEnv env, Object... args) { super(env); } public Swift_KeyCache_SimpleKeyCacheInputStream(NoConstructor n) { super(n); } @ConvertedMethod @ConvertedParameter(index = 0, name = "keyCache", typeHint = "Swift_KeyCache") public Object setKeyCache(RuntimeEnv env, Object... args) { Object keyCache = assignParameter(args, 0, false); this.keyCache = keyCache; return null; } @ConvertedMethod @ConvertedParameter(index = 0, name = "is", typeHint = "Swift_InputByteStream") public Object setWriteThroughStream(RuntimeEnv env, Object... args) { Object is = assignParameter(args, 0, false); this.writeThrough = is; return null; } @ConvertedMethod @ConvertedParameter(index = 0, name = "bytes") @ConvertedParameter( index = 1, name = "is", typeHint = "Swift_InputByteStream", defaultValue = "NULL", defaultValueType = "constant" ) public Object write(RuntimeEnv env, Object... args) { Object bytes = assignParameter(args, 0, false); Object is = assignParameter(args, 1, true); if (null == is) { is = ZVal.getNull(); } env.callMethod( this.keyCache, "setString", Swift_KeyCache_SimpleKeyCacheInputStream.class, this.nsKey, this.itemKey, bytes, Swift_KeyCache.CONST_MODE_APPEND); if (ZVal.isset(is)) { env.callMethod(is, "write", Swift_KeyCache_SimpleKeyCacheInputStream.class, bytes); } if (ZVal.isset(this.writeThrough)) { env.callMethod( this.writeThrough, "write", Swift_KeyCache_SimpleKeyCacheInputStream.class, bytes); } return null; } @ConvertedMethod public Object commit(RuntimeEnv env, Object... args) { return null; } @ConvertedMethod @ConvertedParameter(index = 0, name = "is", typeHint = "Swift_InputByteStream") public Object bind(RuntimeEnv env, Object... args) { Object is = assignParameter(args, 0, false); return null; } @ConvertedMethod @ConvertedParameter(index = 0, name = "is", typeHint = "Swift_InputByteStream") public Object unbind(RuntimeEnv env, Object... args) { Object is = assignParameter(args, 0, false); return null; } @ConvertedMethod public Object flushBuffers(RuntimeEnv env, Object... args) { env.callMethod( this.keyCache, "clearKey", Swift_KeyCache_SimpleKeyCacheInputStream.class, this.nsKey, this.itemKey); return null; } @ConvertedMethod @ConvertedParameter(index = 0, name = "nsKey") public Object setNsKey(RuntimeEnv env, Object... args) { Object nsKey = assignParameter(args, 0, false); this.nsKey = nsKey; return null; } @ConvertedMethod @ConvertedParameter(index = 0, name = "itemKey") public Object setItemKey(RuntimeEnv env, Object... args) { Object itemKey = assignParameter(args, 0, false); this.itemKey = itemKey; return null; } @ConvertedMethod public Object __clone(RuntimeEnv env, Object... args) { this.writeThrough = ZVal.getNull(); return null; } public static final Object CONST_class = "Swift_KeyCache_SimpleKeyCacheInputStream"; // Runtime Converter Internals // RuntimeStaticCompanion contains static methods // RequestStaticProperties contains static (per-request) properties // ReflectionClassData contains php reflection data used by the runtime library public static class RuntimeStaticCompanion extends StaticBaseClass { private static final MethodHandles.Lookup staticCompanionLookup = MethodHandles.lookup(); } public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion(); private static final ReflectionClassData runtimeConverterReflectionData = ReflectionClassData.builder() .setName("Swift_KeyCache_SimpleKeyCacheInputStream") .setLookup( Swift_KeyCache_SimpleKeyCacheInputStream.class, MethodHandles.lookup(), RuntimeStaticCompanion.staticCompanionLookup) .setLocalProperties("itemKey", "keyCache", "nsKey", "writeThrough") .setFilename( "vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php") .addInterface("Swift_KeyCache_KeyCacheInputStream") .addInterface("Swift_InputByteStream") .get(); @Override public ReflectionClassData getRuntimeConverterReflectionData() { return runtimeConverterReflectionData; } @Override public Object converterRuntimeCallExtended( RuntimeEnv env, String method, Class<?> caller, PassByReferenceArgs passByReferenceArgs, Object... args) { return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic( this, runtimeConverterReflectionData, env, method, caller, passByReferenceArgs, args); } }
34.885572
118
0.655876
81c460912b877b3d7dca94e5c0367bca32f8f77d
4,870
package com.ironoid.fdsquiz; import android.content.Intent; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.RatingBar; import android.widget.TextView; public class DeldResultActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Button btnres; //restart button setContentView(R.layout.activity_deld_result); //get rating bar object RatingBar bar=(RatingBar)findViewById(R.id.ratingBar1); bar.setNumStars(5); bar.setStepSize(0.5f); //get text view TextView o=(TextView)findViewById(R.id.textResult); TextView t=(TextView)findViewById(R.id.textView); //get score Animation bounce = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce_anim); final Animation rotate = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate); Animation zoomout = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.zoomout); bar.startAnimation(bounce); o.startAnimation(rotate); t.startAnimation(rotate); Bundle b = getIntent().getExtras(); final int score= b.getInt("score"); final int qid=b.getInt("qid"); //display score o.setText("Your Score is " + score + " out of " + qid ); switch (score) {case 0:t.setText("Need Improvement...");break; case 1:case 2:case 3: case 4:case 5: case 6: case 7:case 8:case 9:case 10: t.setText("Oopsie! Better Luck Next Time!"); bar.setRating(1); ;break; case 11:case 12:case 13:case 14:case 15: case 16:case 17:case 18:case 19:case 20: t.setText("You Can Do Better....."); bar.setRating(2); break; case 21:case 22:case 23:case 24:case 25: case 26:case 27:case 28:case 29: t.setText("Good but need improvement"); bar.setRating(3); break; case 30:case 31:case 32:case 33:case 34: case 35:case 36:case 37:case 38:case 39: t.setText("Good job...."); bar.setRating(4); break; case 40:case 41:case 42:case 43:case 45: case 44:case 46:case 47:case 48:case 50: t.setText("Excellent...!!!"); bar.setRating(5); break; } btnres=(Button)findViewById(R.id.btnres); //id to restart btn btnres.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(DeldResultActivity.this, DeldActivity.class); startActivity(intent); finish(); } }); Button btnhome=(Button)findViewById(R.id.btnhome); //id to restart btn btnhome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent home = new Intent(DeldResultActivity.this, MainActivity.class); startActivity(home); finish(); } }); final Button sharebtn=(Button)findViewById(R.id.sharebtn); //id to restart btn sharebtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick (View v){ sharebtn.startAnimation(rotate); String shareBody = "Hey , I just Scored "+ score +" out of "+ qid +" in this wonderfull app F.A.Q.\nYou can Revise Your MCQ's and " + "Frequently Asked Questions asked in Online Exam and Viva Using your Phone.\nJust Download the App From Here www.FAQ.com"; Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "FAQ App:"); sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_using))); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_result, menu); return true; } @Override public void onBackPressed() { Intent back = new Intent(DeldResultActivity.this, MainActivity.class); startActivity(back); finish(); } }
35.547445
149
0.609651
3d8cb7750f86365b07257d2c160ed26fe194a7f7
462
package ghissues; import act.controller.annotation.UrlContext; import act.util.PropertySpec; import org.osgl.mvc.annotation.GetAction; import org.osgl.util.*; @UrlContext("866") public class Gh866 extends BaseController { public static class Foo { public String name = S.random(); public int number = N.randInt(); } @GetAction @PropertySpec("name") public Iterable<Foo> list() { return C.list(new Foo()); } }
20.086957
44
0.670996
4bed1c5950964088499b78d2ca97f0e60346aa29
1,973
package org.qianyan.prescriptionmanager.controller; import org.qianyan.prescriptionmanager.domain.Prescription; import org.qianyan.prescriptionmanager.domain.User; import org.qianyan.prescriptionmanager.service.impl.PrescriptionServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * @author dyj123 2020/11/19 * @Company Qianyan Studio * 创建处方笺记录 Servlet */ @WebServlet(name = "prescriptionCreate", urlPatterns = "/prescriptionCreate") public class PrescriptionCreateServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 创建病人对象并从会话中接收参数 User user = (User) req.getSession().getAttribute("user"); // 创建该病人的处方笺对象并赋予参数 Prescription prescription = new Prescription(); prescription.setRecipe_id(Integer.parseInt(req.getParameter("recipe_id"))); prescription.setUser_id(user.getUser_id()); prescription.setPrescription_date(new SimpleDateFormat("yyyy-MM-dd").format(new Date())); try { // 保存到数据库 int result = new PrescriptionServiceImpl().doInsert(prescription); if (result != 0) { // 若保存成功,重定向至创建处方笺页面 resp.getWriter().print("<script>alert(\"处方笺创建成功!\");window.location.href = 'prescriptioncreate.jsp';</script>"); } } catch (Exception e) { req.setAttribute("error", e); req.getRequestDispatcher("error.jsp").forward(req, resp); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } }
32.344262
128
0.707552
7a7c8c6c2771f3dd2ea93a2104204927bd4cc3a8
251
package samplr.domain; public final class EventIds { public final static String DATA_IN_MONGO_COMPLETED = "DATA_IN_MONGO_COMPLETED"; public final static String SAVE_IN_ORACLE_ERROR = "DATA_IN_ORACLE_FAILED"; private EventIds() { } }
25.1
83
0.760956
43aceefbf22c12a984a85a07d32a66c3781148b1
12,911
package com.planet_ink.coffee_mud.WebMacros.grinder; import com.planet_ink.coffee_mud.WebMacros.RoomData; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2010 Bo Zimmerman 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. */ @SuppressWarnings("unchecked") public class GrinderClasses { public String name() {return this.getClass().getName().substring(this.getClass().getName().lastIndexOf('.')+1);} public static DVector cabilities(ExternalHTTPRequests httpReq) { DVector theclasses=new DVector(9); if(httpReq.isRequestParameter("CABLES1")) { int num=1; String behav=httpReq.getRequestParameter("CABLES"+num); while(behav!=null) { if(behav.length()>0) { String prof=httpReq.getRequestParameter("CABPOF"+num); if(prof==null) prof="0"; String qual=httpReq.getRequestParameter("CABQUA"+num); if(qual==null) qual="";// null means unchecked String levl=httpReq.getRequestParameter("CABLVL"+num); if(levl==null) levl="0"; String secr=httpReq.getRequestParameter("CABSCR"+num); if(secr==null) secr="";// null means unchecked Object parm=httpReq.getRequestParameter("CABPRM"+num); if(parm==null) parm=""; Object prereq=httpReq.getRequestParameter("CABPRE"+num); if(prereq==null) prereq=""; Object mask=httpReq.getRequestParameter("CABMSK"+num); if(mask==null) mask=""; String maxp=httpReq.getRequestParameter("CABMPOF"+num); if(maxp==null) maxp="100"; theclasses.addElement(behav,levl,prof,qual,secr,parm,prereq,mask,maxp); } num++; behav=httpReq.getRequestParameter("CABLES"+num); } } return theclasses; } public static String modifyCharClass(ExternalHTTPRequests httpReq, Hashtable parms, CharClass oldC, CharClass C) { String replaceCommand=httpReq.getRequestParameter("REPLACE"); if((replaceCommand != null) && (replaceCommand.length()>0) && (replaceCommand.indexOf('=')>0)) { int eq=replaceCommand.indexOf('='); String field=replaceCommand.substring(0,eq); String value=replaceCommand.substring(eq+1); httpReq.addRequestParameters(field, value); httpReq.addRequestParameters("REPLACE",""); } String old; // names are numerous DVector DV=new DVector(2); int num=0; while(httpReq.isRequestParameter("NAME"+(++num))) if(CMath.isInteger(httpReq.getRequestParameter("NAMELEVEL"+(num)))) { int minLevel = CMath.s_int(httpReq.getRequestParameter("NAMELEVEL"+(num))); String name=httpReq.getRequestParameter("NAME"+(num)); if((name!=null)&&(name.length()>0)) { if(DV.size()==0) DV.addElement(Integer.valueOf(minLevel),name); else { boolean added=false; for(int n=0;n<DV.size();n++) if(minLevel<((Integer)DV.elementAt(n,1)).intValue()) { DV.insertElementAt(n,Integer.valueOf(minLevel),name); added=true; break; } else if(minLevel==((Integer)DV.elementAt(n,1)).intValue()) { added=true; break; } if(!added) DV.addElement(Integer.valueOf(minLevel),name); } } } if(DV.size()==0) DV.addElement(Integer.valueOf(0),C.ID()); C.setStat("NUMNAME",""+DV.size()); for(int l=0;l<DV.size();l++) { C.setStat("NAME"+l, (String)DV.elementAt(l,2)); C.setStat("NAMELEVEL"+l, ((Integer)DV.elementAt(l,1)).toString()); } old=httpReq.getRequestParameter(""); C.setStat("",(old==null)?"":old); old=httpReq.getRequestParameter("BASE"); C.setStat("BASE",(old==null)?"BASECLASS":old); old=httpReq.getRequestParameter("HPDIV"); C.setStat("HPDIV",(old==null)?"1":old); old=httpReq.getRequestParameter("HPDICE"); C.setStat("HPDICE",(old==null)?"1":old); old=httpReq.getRequestParameter("HPDIE"); C.setStat("HPDIE",(old==null)?"6":old); old=httpReq.getRequestParameter("MANADIV"); C.setStat("MANADIV",(old==null)?"1":old); old=httpReq.getRequestParameter("MANADICE"); C.setStat("MANADICE",(old==null)?"1":old); old=httpReq.getRequestParameter("MANADIE"); C.setStat("MANADIE",(old==null)?"6":old); old=httpReq.getRequestParameter("LVLPRAC"); C.setStat("LVLPRAC",(old==null)?"0":old); old=httpReq.getRequestParameter("LVLATT"); C.setStat("LVLATT",(old==null)?"0":old); old=httpReq.getRequestParameter("FSTTRAN"); C.setStat("FSTTRAN",(old==null)?"0":old); old=httpReq.getRequestParameter("FSTPRAC"); C.setStat("FSTPRAC",(old==null)?"0":old); old=httpReq.getRequestParameter("LVLDAM"); C.setStat("LVLDAM",(old==null)?"10":old); old=httpReq.getRequestParameter("MAXNCS"); C.setStat("MAXNCS",(old==null)?"0":old); old=httpReq.getRequestParameter("MAXCRS"); C.setStat("MAXCRS",(old==null)?"0":old); old=httpReq.getRequestParameter("MAXCMS"); C.setStat("MAXCMS",(old==null)?"0":old); old=httpReq.getRequestParameter("MAXLGS"); C.setStat("MAXLGS",(old==null)?"0":old); old=httpReq.getRequestParameter("LEVELCAP"); C.setStat("LEVELCAP",(old==null)?"-1":old); old=httpReq.getRequestParameter("LVLMOVE"); C.setStat("LVLMOVE",(old==null)?"1":old); old=httpReq.getRequestParameter("ARMOR"); C.setStat("ARMOR",(old==null)?"0":old); old=httpReq.getRequestParameter("STRLMT"); C.setStat("STRLMT",(old==null)?"STRLMT":old); old=httpReq.getRequestParameter("STRBON"); C.setStat("STRBON",(old==null)?"STRBON":old); old=httpReq.getRequestParameter("QUAL"); C.setStat("QUAL",(old==null)?"":old); old=httpReq.getRequestParameter("PLAYER"); C.setStat("PLAYER",(old==null)?"0":old); C.setStat("ESTATS",GrinderRaces.getEStats('E',httpReq)); C.setStat("CSTATS",GrinderRaces.getCStats('S',httpReq)); C.setStat("ASTATS",GrinderRaces.getCStats('A',httpReq)); C.setStat("ASTATE",GrinderRaces.getCState('A',httpReq)); C.setStat("STARTASTATE",GrinderRaces.getCState('S',httpReq)); old=httpReq.getRequestParameter("GENHELP"); C.setStat("HELP", ((old==null)?"":old)); String id=""; Vector V=new Vector(); for(int i=0;httpReq.isRequestParameter("NOWEAPS"+id);id=""+(++i)) V.addElement(httpReq.getRequestParameter("NOWEAPS"+id)); C.setStat("GETWEP",CMParms.toStringList(V)); Vector Ivs=GrinderRaces.itemList(oldC.outfit(null),'O',httpReq,false); C.setStat("NUMOFT",""+Ivs.size()); for(int l=0;l<Ivs.size();l++) { C.setStat("GETOFTID"+l,((Environmental)Ivs.elementAt(l)).ID()); C.setStat("GETOFTPARM"+l,((Environmental)Ivs.elementAt(l)).text()); } C.setStat("DISFLAGS",""+CMath.s_long(httpReq.getRequestParameter("DISFLAGS"))); num=0; DV.clear(); while(httpReq.isRequestParameter("SSET"+(++num))) if(CMath.isInteger(httpReq.getRequestParameter("SSETLEVEL"+(num)))) { int minLevel = CMath.s_int(httpReq.getRequestParameter("SSETLEVEL"+(num))); String name=httpReq.getRequestParameter("SSET"+(num)); if((name!=null)&&(name.length()>0)) { if(DV.size()==0) DV.addElement(Integer.valueOf(minLevel),name); else { boolean added=false; for(int n=0;n<DV.size();n++) if(minLevel<((Integer)DV.elementAt(n,1)).intValue()) { DV.insertElementAt(n,Integer.valueOf(minLevel),name); added=true; break; } else if(minLevel==((Integer)DV.elementAt(n,1)).intValue()) { added=true; break; } if(!added) DV.addElement(Integer.valueOf(minLevel),name); } } } C.setStat("NUMSSET",""+DV.size()); for(int l=0;l<DV.size();l++) { String sec=(String)DV.elementAt(l,2); V=CMParms.parseCommas(sec, true); C.setStat("SSET"+l, CMParms.combineWithQuotes(V,0)); C.setStat("SSETLEVEL"+l, ((Integer)DV.elementAt(l,1)).toString()); } id=""; V=new Vector(); for(int i=0;httpReq.isRequestParameter("WEAPMATS"+id);id=""+(++i)) if(CMath.isInteger(httpReq.getRequestParameter("WEAPMATS"+id))) V.addElement(httpReq.getRequestParameter("WEAPMATS"+id)); C.setStat("NUMWMAT",""+V.size()); C.setStat("GETWMAT",CMParms.toStringList(V)); old=httpReq.getRequestParameter("ARMORMINOR"); C.setStat("ARMORMINOR",(old==null)?"-1":old); old=httpReq.getRequestParameter("STATCLASS"); C.setStat("STATCLASS",(old==null)?"":old); old=httpReq.getRequestParameter("EVENTCLASS"); C.setStat("EVENTCLASS",(old==null)?"":old); DV=cabilities(httpReq); C.setStat("NUMCABLE", ""+DV.size()); for(int i=0;i<DV.size();i++) { C.setStat("GETCABLELVL"+i, (String)DV.elementAt(i,2)); C.setStat("GETCABLEPROF"+i, (String)DV.elementAt(i,3)); C.setStat("GETCABLEGAIN"+i, ((String)DV.elementAt(i,4)).equalsIgnoreCase("on")?"false":"true"); C.setStat("GETCABLESECR"+i, ((String)DV.elementAt(i,5)).equalsIgnoreCase("on")?"true":"false"); if(DV.elementAt(i,6) instanceof String) C.setStat("GETCABLEPARM"+i, (String)DV.elementAt(i,6)); if(DV.elementAt(i,7) instanceof String) C.setStat("GETCABLEPREQ"+i, (String)DV.elementAt(i,7)); if(DV.elementAt(i,8) instanceof String) C.setStat("GETCABLEMASK"+i, (String)DV.elementAt(i,8)); C.setStat("GETCABLEMAXP"+i, (String)DV.elementAt(i,9)); // CABLE MUST BE LAST C.setStat("GETCABLE"+i, (String)DV.elementAt(i,1)); } return ""; } }
46.949091
120
0.540934
3531721eb120b8cfaa042697b5285bff8881040f
12,008
package com.baokaicong.android.bmusic.ui.activity; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.FragmentTransaction; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ListAdapter; import android.widget.ListView; import com.baokaicong.android.bmusic.BMContext; import com.baokaicong.android.bmusic.R; import com.baokaicong.android.bmusic.bean.Music; import com.baokaicong.android.bmusic.consts.Permission; import com.baokaicong.android.bmusic.consts.PropertyField; import com.baokaicong.android.bmusic.service.UserService; import com.baokaicong.android.bmusic.service.remoter.command.NextCommand; import com.baokaicong.android.bmusic.service.remoter.command.OpenCommand; import com.baokaicong.android.bmusic.service.remoter.command.PauseCommand; import com.baokaicong.android.bmusic.service.remoter.command.PlayCommand; import com.baokaicong.android.bmusic.service.remoter.command.ShutdownCommand; import com.baokaicong.android.bmusic.util.BEAUtil; import com.baokaicong.android.bmusic.util.PermissionUtil; import com.baokaicong.android.bmusic.service.MusicPlayService; import com.baokaicong.android.bmusic.service.remoter.MediaRemoter; import com.baokaicong.android.bmusic.ui.fragment.BFragment; import com.baokaicong.android.bmusic.ui.fragment.HomeFragment; import com.baokaicong.android.bmusic.ui.fragment.MStoreFragment; import com.baokaicong.android.bmusic.ui.view.BottomMusicView; import com.baokaicong.android.bmusic.ui.view.MainToolbar; import com.baokaicong.android.bmusic.util.sql.PropertySQLUtil; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private static final String NAME="main"; private DrawerLayout drawerLayout; private MainToolbar toolbar; private static long DOUBLE_CLICK_TIME = 0L; private Map<Integer, BFragment> fragmentMap; private int currentFragment=0; private BottomMusicView bottomMusicView; private MediaRemoter mediaRemoter; private Map<String,Integer> navMap; private ServiceConnection musicPlayCon; private ServiceConnection userCon; private UserService userService; private Button logoutButton; private PropertySQLUtil propertySQLUtil; private ImageButton searchButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BMContext.instance().addActivity(NAME,this); // 请求权限 PermissionUtil.Instance() .request(this, Permission.permissions); propertySQLUtil =new PropertySQLUtil(this); init(); } /** * 初始化 */ private void init(){ navMap=new HashMap<>(); navMap.put("首页",R.id.fragment_home); navMap.put("乐库",R.id.fragment_news); toolbar=findViewById(R.id.main_toolbar); toolbar.addListener(new MainToolbar.MainToolbarListener() { @Override public void onMenuClick() { openDrawer(); } @Override public void onNavClick(String last, String target) { switchFragment(navMap.get(last),navMap.get(target)); } }); logoutButton=findViewById(R.id.drawer_quit_button); logoutButton.setOnClickListener((v)->{logout();}); searchButton=findViewById(R.id.search); searchButton.setOnClickListener((v)->{ Intent intent=new Intent(MainActivity.this,SearchActivity.class); startActivity(intent); }); // 播放服务 musicPlayCon=new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mediaRemoter=((MusicPlayService.MusicBinder)service).getRemoter(); mediaRemoter.command(new OpenCommand(),null); BMContext.instance().setRemoter(mediaRemoter); } @Override public void onServiceDisconnected(ComponentName name) { } }; Intent intent=new Intent(this,MusicPlayService.class); bindService(intent, musicPlayCon,BIND_AUTO_CREATE); bottomMusicView=findViewById(R.id.bottom_music_view); bottomMusicView.addBottomMusciListener(new BottomMusicView.BottomMusicListener() { @Override public void onPlay() { if(mediaRemoter!=null){ mediaRemoter.command(new PlayCommand(),null); } } @Override public void onPause() { if(mediaRemoter!=null){ mediaRemoter.command(new PauseCommand(),null); } } @Override public void onJump(int rate) { } @Override public void onSwitch(Music music) { if(mediaRemoter!=null){ mediaRemoter.command(new NextCommand(),null); } } }); initFragment(); initActionBarAndDrawer(); initDrawerView(); // initNotification(); } /** * 初始化侧滑面板 */ private void initDrawerView(){ String[] names={"我的信息","设置","网络"}; ListView list=findViewById(R.id.drawer_nav_list); ListAdapter adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,names); list.setAdapter(adapter); } /** * 初始化Fragment */ private void initFragment() { fragmentMap = new HashMap<>(); fragmentMap.put(R.id.fragment_home, new HomeFragment()); fragmentMap.put(R.id.fragment_news, new MStoreFragment()); currentFragment = R.id.fragment_home; getSupportFragmentManager().beginTransaction() .replace(R.id.main_container, fragmentMap.get(currentFragment)) .show(fragmentMap.get(R.id.fragment_home)).commit(); } /** * 初始化标题栏和侧滑面板 */ private void initActionBarAndDrawer() { drawerLayout = findViewById(R.id.main_drawer); //创建返回键,并实现打开关/闭监听 ActionBarDrawerToggle barDrawerToggle = new ActionBarDrawerToggerAdapter(this, drawerLayout, R.string.open, R.string.close); barDrawerToggle.syncState(); drawerLayout.addDrawerListener(barDrawerToggle); } @Override protected void onResume() { super.onResume(); for(BFragment f:fragmentMap.values()){ f.resume(); } } /** * 切换Fragment * * @param last * @param target */ private void switchFragment(int last, int target) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.hide(fragmentMap.get(last));//隐藏上个Fragment if (fragmentMap.get(target).isAdded() == false) { transaction.add(R.id.main_container, fragmentMap.get(target)); } fragmentMap.get(target).resume(); transaction.show(fragmentMap.get(target)).commitAllowingStateLoss(); } /** * 响应按键 * * @param keyCode * @param event * @return */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(fragmentMap.get(currentFragment).keyDown(keyCode,event)){ return true; } switch (event.getKeyCode()){ case KeyEvent.KEYCODE_MENU: if (drawerLayout != null) { if (!closeDrawer()) { openDrawer(); } return true; } break; case KeyEvent.KEYCODE_BACK: if (!closeDrawer()) { // 设置两秒内连续两次back则退出 if ((System.currentTimeMillis() - DOUBLE_CLICK_TIME) > 2000) { DOUBLE_CLICK_TIME = System.currentTimeMillis(); } else { moveTaskToBack(true); return true; } } return true; // case KeyEvent.KEYCODE_MEDIA_PLAY: // BMContext.instance().getRemoter().command(new PlayCommand(),null); // return true; // case KeyEvent.KEYCODE_MEDIA_PAUSE: // BMContext.instance().getRemoter().command(new PauseCommand(),null); // return true; // case KeyEvent.KEYCODE_MEDIA_PREVIOUS: // BMContext.instance().getRemoter().command(new PreCommand(),null); // return true; // // case KeyEvent.KEYCODE_MEDIA_NEXT: // BMContext.instance().getRemoter().command(new NextCommand(),null); // return true; } return super.onKeyDown(keyCode, event); } /** * 标题栏拖拽响应 */ private class ActionBarDrawerToggerAdapter extends ActionBarDrawerToggle { public ActionBarDrawerToggerAdapter(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes) { super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes); } public ActionBarDrawerToggerAdapter(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes) { super(activity, drawerLayout, openDrawerContentDescRes, closeDrawerContentDescRes); } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); } } /** * 打开侧滑面板 * @return */ private boolean openDrawer(){ if (!drawerLayout.isDrawerOpen(Gravity.LEFT)) { drawerLayout.openDrawer(Gravity.LEFT); return true; } return false; } /** * 关闭侧滑面板 * @return */ private boolean closeDrawer(){ if (drawerLayout.isDrawerOpen(Gravity.LEFT)) { drawerLayout.closeDrawer(Gravity.LEFT); return true; } return false; } /** * 注销登录 */ private void logout(){ String username= propertySQLUtil.getProperty(PropertyField.USER_NAME); String password= propertySQLUtil.getProperty(PropertyField.USER_PASSWORD); propertySQLUtil.deleteProperty(PropertyField.USER_NAME); propertySQLUtil.deleteProperty(PropertyField.USER_PASSWORD); BMContext.instance().setCurrentUser(null); BMContext.instance().getRemoter().command(new ShutdownCommand(),null); Intent intent=new Intent(this,LoginActivity.class); intent.putExtra(PropertyField.USER_NAME,username); if(password!=null && password.length()>0){ password= BEAUtil.DBEA(password,username); } intent.putExtra(PropertyField.USER_PASSWORD,password); startActivity(intent); this.finish(); } @Override protected void onDestroy() { super.onDestroy(); if(musicPlayCon!=null){ unbindService(musicPlayCon); } if(userCon!=null){ unbindService(userCon); } if(propertySQLUtil !=null){ propertySQLUtil.close(); } mediaRemoter.command(new ShutdownCommand(),null); mediaRemoter=null; } }
34.016997
169
0.638408
4c93b744ea37b92b8849205219eee71cec4c29da
1,463
package br.com.mackenzie.appgamesvr.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "configuracaoJogo", schema = "appGamesVR") public class ConfiguracaoJogo implements Serializable { private static final long serialVersionUID = -936196861870606987L; @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "native") @GenericGenerator(name = "native", strategy = "native") @Column(name = "idConfiguracaoJogo", columnDefinition = "INT") private int idConfiguracaoJogo; @Column(name = "isModoImersivo", columnDefinition = "BIT") private int isModoImersivo; @Column(name = "observacao", columnDefinition = "VARCHAR(255)") private String observacao; public int getIdConfiguracaoJogo() { return idConfiguracaoJogo; } public void setIdConfiguracaoJogo(int idConfiguracaoJogo) { this.idConfiguracaoJogo = idConfiguracaoJogo; } public int getIsModoImersivo() { return isModoImersivo; } public void setIsModoImersivo(int isModoImersivo) { this.isModoImersivo = isModoImersivo; } public String getObservacao() { return observacao; } public void setObservacao(String observacao) { this.observacao = observacao; } }
26.6
71
0.764183
10876fd93916dd25dba2f1c1c7ebad1b0344c050
3,797
package uk.gov.hmcts.ccd.integrations; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.jupiter.api.DisplayName; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import uk.gov.hmcts.ccd.ApplicationParams; import uk.gov.hmcts.ccd.data.caseaccess.DefaultCaseRoleRepository; import java.util.HashSet; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static java.util.Collections.singletonList; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureWireMock(port = 0) @TestPropertySource(locations = "classpath:test.properties") public class CaseRoleDefinitionCachingIT { @Autowired private ApplicationParams applicationParams; @SpyBean private DefaultCaseRoleRepository caseRoleRepository; private final String caseTypeId1 = "caseTypeId1"; private final String caseTypeId2 = "caseTypeId2"; @Before public void setup() { doReturn(new HashSet<>(singletonList("role1"))) .when(this.caseRoleRepository) .getCaseRoles(DefaultCaseRoleRepository.DEFAULT_USER_ID, DefaultCaseRoleRepository.DEFAULT_JURISDICTION_ID, caseTypeId1); doReturn(new HashSet<>()) .when(this.caseRoleRepository) .getCaseRoles(DefaultCaseRoleRepository.DEFAULT_USER_ID, DefaultCaseRoleRepository.DEFAULT_JURISDICTION_ID, caseTypeId2); } @Test @DisplayName("return case roles from cache and repository after cache eviction") public void returnCaseRolesForCaseTypeFromCacheAndRepositoryAfterCacheEviction() throws InterruptedException { Assert.assertEquals(3, applicationParams.getLatestVersionTTLSecs()); verify(caseRoleRepository, times(0)).getCaseRoles(caseTypeId1); caseRoleRepository.getCaseRoles(caseTypeId1); caseRoleRepository.getCaseRoles(caseTypeId1); caseRoleRepository.getCaseRoles(caseTypeId1); verify(caseRoleRepository, times(1)).getCaseRoles(caseTypeId1); caseRoleRepository.getCaseRoles(caseTypeId1); caseRoleRepository.getCaseRoles(caseTypeId1); verify(caseRoleRepository, times(1)).getCaseRoles(caseTypeId1); TimeUnit.SECONDS.sleep(3); caseRoleRepository.getCaseRoles(caseTypeId1); caseRoleRepository.getCaseRoles(caseTypeId1); caseRoleRepository.getCaseRoles(caseTypeId1); caseRoleRepository.getCaseRoles(caseTypeId1); verify(caseRoleRepository, times(2)).getCaseRoles(caseTypeId1); } @Test @DisplayName("return empty case roles but do not cache the result") public void returnEmptyCaseRolesForCaseTypeButDoNotCache() throws InterruptedException { Assert.assertEquals(3, applicationParams.getLatestVersionTTLSecs()); verify(caseRoleRepository, times(0)).getCaseRoles(caseTypeId2); caseRoleRepository.getCaseRoles(caseTypeId2); caseRoleRepository.getCaseRoles(caseTypeId2); caseRoleRepository.getCaseRoles(caseTypeId2); verify(caseRoleRepository, times(3)).getCaseRoles(caseTypeId2); TimeUnit.SECONDS.sleep(3); caseRoleRepository.getCaseRoles(caseTypeId2); caseRoleRepository.getCaseRoles(caseTypeId2); verify(caseRoleRepository, times(5)).getCaseRoles(caseTypeId2); } }
38.353535
114
0.758757
bd3616738fbcad11008c66b2d5baea7b76a853a1
746
package de.adorsys.opba.protocol.facade.config.encryption; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class EncryptionProviderConfig { @Bean ConsentAuthorizationEncryptionServiceProvider consentAuthEncryptionProvider(ConsentSpecSecretKeyConfig specSecretKeyConfig) { return new ConsentAuthorizationEncryptionServiceProvider( new EncryptionWithInitVectorOper(specSecretKeyConfig) ); } @Bean PsuConsentEncryptionServiceProvider psuConsentEncryptionProvider(PsuKeyPairConfig psuKeyPairConfig) { return new PsuConsentEncryptionServiceProvider(new CmsEncryptionOper(psuKeyPairConfig)); } }
33.909091
129
0.808311
864e82180a1cb2b7bdeea17151bcd673183c1232
7,694
package org.valid4j; import org.hamcrest.Matcher; import org.valid4j.provider.AssertiveInstance; import org.valid4j.provider.AssertiveProvider; import static org.valid4j.BooleanContractCondition.booleanContract; import static org.valid4j.MatcherContractCondition.matcherContract; import static org.valid4j.Message.describing; /** * Entry point for the global assertive policy. * <p> * Violations indicate the presence of a programming error. * Never try to catch and recover from a programming error. Rather * a reasonable global approach would be to return a HTTP 500 response, * restart the application or similar. * </p> * Make use of hamcrest matchers to conveniently express conditions and get clear error messages. * Example: * <pre> * {@code * require(i, greaterThan(0)); * } * </pre> * <p> * All error messages are {@link java.lang.String#format format strings} as defined by {@link java.lang.String}. * </p> * Example: * <pre> * {@code * require(i > 0, "The value must be greater than zero: %d", i); * } * </pre> */ public class Assertive { private static final String NULL_MESSAGE = null; private static final Throwable NO_CAUSE = null; private static final Error DEFAULT_ERROR = null; private Assertive() { throw neverGetHereError("Prevent instantiation"); } /** * Precondition that clients are required to fulfill. * Violations are considered to be programming errors, * on the clients part. * * @param condition the condition to check */ public static void require(boolean condition) { getProvider().requirePolicy().check(booleanContract(condition, NULL_MESSAGE)); } /** * Precondition that clients are required to fulfill. * Violations are considered to be programming errors, * on the clients part. * * @param <T> type of object to check * @param o the object to check * @param matcher the matcher that the given object must satisfy * @return the validated object */ public static <T> T require(T o, Matcher<?> matcher) { getProvider().requirePolicy().check(matcherContract(o, matcher)); return o; } /** * Precondition that clients are required to fulfill. * Violations are considered to be programming errors, * on the clients part. * * @param condition the condition to check * @param msg message {@link java.lang.String#format format string} * @param values values passed into the msg format string */ public static void require(boolean condition, String msg, Object... values) { getProvider().requirePolicy().check(booleanContract(condition, describing(msg, values))); } /** * Postcondition that supplier are supposed to ensure. * Violations are considered to be a programming error, * on the suppliers part. * * @param condition the condition to check */ public static void ensure(boolean condition) { getProvider().ensurePolicy().check(booleanContract(condition, NULL_MESSAGE)); } /** * Postcondition that supplier are supposed to ensure. * Violations are considered to be programming errors, * on the suppliers part. * * @param <T> type of object to check * @param o the object to check * @param matcher the matcher that the given object must satisfy * @return the validated object */ public static <T> T ensure(T o, Matcher<?> matcher) { getProvider().ensurePolicy().check(matcherContract(o, matcher)); return o; } /** * Postcondition that supplier are supposed to ensure. * Violations are considered to be programming errors, * on the suppliers part. * * @param condition the condition to check * @param msg message {@link java.lang.String#format format string} * @param values values passed into the msg format string */ public static void ensure(boolean condition, String msg, Object... values) { getProvider().ensurePolicy().check(booleanContract(condition, describing(msg, values))); } /** * Unreachable code have been reached. * This is considered to be a programming error. */ public static void neverGetHere() { getProvider().neverGetHerePolicy().neverGetHere(NO_CAUSE, NULL_MESSAGE); } /** * Unreachable code have been reached. This is * considered to be a programming error. * * @param msg descriptive message */ public static void neverGetHere(String msg) { getProvider().neverGetHerePolicy().neverGetHere(NO_CAUSE, msg); } /** * Unreachable code have been reached. This is * considered to be a programming error. * * @param msg message {@link java.lang.String#format format string} * @param values values passed into the msg format string */ public static void neverGetHere(String msg, Object... values) { getProvider().neverGetHerePolicy().neverGetHere(NO_CAUSE, describing(msg, values)); } /** * Unexpected exception have been caught. This is considered * to be a programming error. * * @param t the throwable being unexpectedly caught. */ public static void neverGetHere(Throwable t) { getProvider().neverGetHerePolicy().neverGetHere(t, NULL_MESSAGE); } /** * Unexpected exception have been caught. This is considered * to be a programming error. * * @param t the throwable being unexpectedly caught. * @param msg message {@link java.lang.String#format format string} * @param values values passed into the msg format string */ public static void neverGetHere(Throwable t, String msg, Object... values) { getProvider().neverGetHerePolicy().neverGetHere(t, describing(msg, values)); } /** * Unreachable code have been reached. * This is considered to be a programming error. * @return an error */ public static Error neverGetHereError() { getProvider().neverGetHerePolicy().neverGetHere(NO_CAUSE, NULL_MESSAGE); return DEFAULT_ERROR; } /** * Unreachable code have been reached. This is * considered to be a programming error. * * @param msg descriptive message * @return an error */ public static Error neverGetHereError(String msg) { getProvider().neverGetHerePolicy().neverGetHere(NO_CAUSE, msg); return DEFAULT_ERROR; } /** * Unreachable code have been reached. This is * considered to be a programming error. * * @param msg message {@link java.lang.String#format format string} * @param values values passed into the msg format string * @return an error */ public static Error neverGetHereError(String msg, Object... values) { getProvider().neverGetHerePolicy().neverGetHere(NO_CAUSE, describing(msg, values)); return DEFAULT_ERROR; } /** * Unexpected exception have been caught. This is considered * to be a programming error. * * @param t the throwable being unexpectedly caught. * @return an error */ public static Error neverGetHereError(Throwable t) { getProvider().neverGetHerePolicy().neverGetHere(t, NULL_MESSAGE); return DEFAULT_ERROR; } /** * Unexpected exception have been caught. This is considered * to be a programming error. * * @param t the throwable being unexpectedly caught. * @param msg message {@link java.lang.String#format format string} * @param values values passed into the msg format string * @return an error */ public static Error neverGetHereError(Throwable t, String msg, Object... values) { getProvider().neverGetHerePolicy().neverGetHere(t, describing(msg, values)); return DEFAULT_ERROR; } private static AssertiveProvider getProvider() { return AssertiveInstance.getInstance(); } }
32.058333
112
0.699376
f826394fd0034a0f1a63edcc6e16bb11198b6c31
4,127
package me.geek.tom.fallfest; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.fabricmc.fabric.api.client.particle.v1.ParticleFactoryRegistry; import net.fabricmc.fabric.api.network.ClientSidePacketRegistry; import net.fabricmc.fabric.api.particle.v1.FabricParticleTypes; import net.minecraft.client.particle.FlameParticle; import net.minecraft.client.render.RenderLayer; import net.minecraft.particle.DefaultParticleType; import net.minecraft.particle.ParticleTypes; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.util.registry.Registry; import net.minecraft.world.World; public class FallFestClient implements ClientModInitializer { public static final DefaultParticleType EERIE_FLAME_PARTICLE = Registration.modRegister(Registry.PARTICLE_TYPE, FabricParticleTypes.simple(), "eerie_flame"); @Override public void onInitializeClient() { FallFest.LOGGER.info("Initialise client!"); BlockRenderLayerMap.INSTANCE.putBlock(Registration.EERIE_TORCH_BLOCK, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(Registration.EERIE_WALL_TORCH_BLOCK, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(Registration.CURSED_SPAWNER_BLOCK, RenderLayer.getCutout()); // Register particles ParticleFactoryRegistry.getInstance().register(EERIE_FLAME_PARTICLE, FlameParticle.Factory::new); ClientSidePacketRegistry.INSTANCE.register(FallFest.SPAWNER_EFFECT_PACKET_ID, (ctx, data) -> { BlockPos pos = data.readBlockPos(); int effect = data.readInt(); ctx.getTaskQueue().execute(() -> { World world = ctx.getPlayer().getEntityWorld(); switch (effect) { case 0: // BEGIN CHARGING world.playSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.BLOCK_BEACON_ACTIVATE, SoundCategory.BLOCKS, 1.0f, 1.0f, false); for (int i = 0; i < 32; i++) { world.addParticle(ParticleTypes.PORTAL, false, pos.getX() + 0.5, pos.getY() + world.random.nextDouble() * 2, pos.getZ() + 0.5, world.random.nextGaussian(), 0, world.random.nextGaussian()); } break; case 1: // BEGIN break; case 2: // SPAWN MOB world.playSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.ENTITY_ENDERMAN_TELEPORT, SoundCategory.HOSTILE, 1.0f, 1.0f, false); for (int i = 0; i < 32; i++) { world.addParticle(ParticleTypes.PORTAL, false, pos.getX() + 0.5, pos.getY() + world.random.nextDouble() * 2, pos.getZ() + 0.5, world.random.nextGaussian(), 0, world.random.nextGaussian()); } break; case 3: // COMPLETE world.playSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.UI_TOAST_CHALLENGE_COMPLETE, SoundCategory.MASTER, 1.0f, 1.0f, false); for (int i = 0; i < 250; i++) { world.addParticle(EERIE_FLAME_PARTICLE, false, pos.getX() + 0.5, pos.getY() + 1.5, pos.getZ() + 0.5, world.random.nextGaussian(), 0, world.random.nextGaussian()); } break; } }); }); } }
50.329268
161
0.55464
72e683cc7063bf831501d9f475d0f968f9b4b272
11,322
package Spiellogik; import GUIServer.IGUIServerCallback; import KommunikationServer.IKommunikationServerCallback; import Spieldaten.*; public class Spiellogik implements ISpiellogik, ISpielkontrolle{ ISpieldaten daten = null; public void setSpieldaten(ISpieldaten daten){ this.daten = daten; } //Hält die aktuelle Phase - 1,2,3 Integer aktivePhase = 0; private Integer[] A = {10,11,12,13,14,15,16}; private Integer[] B = {1,2,3,4,5,6,7,8,9}; private Integer[] C = {23,24,25,26,27,28,29,30}; private Integer[] D = {17,18,19,20,21,22}; private Integer[] AERO = {31,32,33}; private Missionskarte missionskarte = null; private Integer zuVerteilendeErsties = 0; boolean hatGetauscht = false; IKommunikationServerCallback beobachterMerkerKom = null; IGUIServerCallback beobachterMerkerServer = null; boolean istSpielGeladen(){ return true; } boolean alleSpielerBereit(){ boolean [] spielerBereit; spielerBereit = daten.spielerBereit(); for(boolean b : spielerBereit) if(!b) return false; return true; } boolean phase1Verstaerken(String nameSpieler){ zuVerteilendeErsties = 0; hatGetauscht = false; zuVerteilendeErsties = daten.anzahlGebaeudeSpieler(nameSpieler) / 3; if(zuVerteilendeErsties < 3){ zuVerteilendeErsties = 3; } zuVerteilendeErsties += fachbereichPruefen(nameSpieler); daten.anzahlZuVerteilendeErstiesAnpassen(nameSpieler, zuVerteilendeErsties); missionskarte = daten.missionskarteSpieler(nameSpieler); if(vergleicheMissionskarte(missionskarte, nameSpieler)){ return true; //Sieg } return false; } boolean fachbereichArrayPruefen(Integer[] fachbereiche, Integer[]gebaeudeSpieler){ for(int i = 0; i < fachbereiche.length; i++){ boolean istgefunden = false; for(int j = 0; j < gebaeudeSpieler.length; j++){ if(fachbereiche[i].equals(gebaeudeSpieler[j])){ istgefunden = true; break; } } if(istgefunden == false) return false; } beobachterMerkerServer.aktualisierung(); beobachterMerkerKom.aktualisierenKarte(); return true; } Integer fachbereichPruefen(String nameSpieler){ Integer[]gebaeudeSpieler = daten.eigeneGebaeude(nameSpieler); Integer anzahlErsties = 0; if(fachbereichArrayPruefen(A, gebaeudeSpieler)) anzahlErsties += 1; if(fachbereichArrayPruefen(B, gebaeudeSpieler)) anzahlErsties += 1; if (fachbereichArrayPruefen(C, gebaeudeSpieler)) anzahlErsties += 1; if(fachbereichArrayPruefen(D, gebaeudeSpieler)) anzahlErsties += 1; if(fachbereichArrayPruefen(AERO, gebaeudeSpieler)) anzahlErsties += 1; return anzahlErsties; } boolean phase2Angriff(String nameSpieler){ Missionskarte missionskarte = daten.missionskarteSpieler(nameSpieler); if(vergleicheMissionskarte(missionskarte, nameSpieler)){ //Sieg } return false; } //Prüft ob Zielgebäude im möglichen Ziel-Array enthalten ist boolean verschiebenAngreifenVonNach(Integer [] gebaeudeNach, Integer gebaeudeZiel){ for(int i = 0; i < gebaeudeNach.length; i++){ if(gebaeudeNach[i].equals(gebaeudeZiel)) return true; } return false; } boolean mindEinErstieGebaeude(Integer gebaeude, Integer anzahlErsties){ return (daten.anzahlErstiesGebaeude(gebaeude) - anzahlErsties) >= 1; } boolean vergleicheMissionskarte(Missionskarte missionskarte, String nameSpieler){ //[0]=null - [1]=etti - [2]=spo - [3]=wow - [4]=aero - [5]=bau String spielerNamen[] = daten.spielerNamen(); switch (missionskarte){ case BefreienVonStudiengangETTI: return (daten.anzahlGebaeudeSpieler(spielerNamen[1]) == 0); case BefreienVonStudiengangSPO: return (daten.anzahlGebaeudeSpieler(spielerNamen[2]) == 0); case BefreienVonStudiengangWOW: return (daten.anzahlGebaeudeSpieler(spielerNamen[3]) == 0); case BefreienVonStudiengangBAU: return (daten.anzahlGebaeudeSpieler(spielerNamen[4]) == 0); case BefreienVonStudiengangAero: return (daten.anzahlGebaeudeSpieler(spielerNamen[5]) == 0); case ZweiFachbereicheEinnehmen: return (daten.anzahlFachbereicheSpieler(nameSpieler) >= 2); case FuenfzehnGebaeudeEinnehmen: return (daten.anzahlGebaeudeSpieler(nameSpieler) >= 15); case ZehnGebaeudeEinnehmenUndZweiEinheitenJeweils: Integer [] eigGebaeude; Integer einheitenGebaeude = 0; Integer zaehler = 0; if(daten.anzahlGebaeudeSpieler(nameSpieler) >= 10){ eigGebaeude = daten.eigeneGebaeude(nameSpieler); for(int i = 0; i < eigGebaeude.length; i++){ einheitenGebaeude = daten.anzahlErstiesGebaeude(eigGebaeude[i]); if(einheitenGebaeude >= 2) zaehler++; } return (zaehler == eigGebaeude.length); } return false; default: return false; } } @Override public boolean spielerAnmelden(String nameSpieler, String passwort) { if(daten.spielerAnmelden(nameSpieler, passwort)) { beobachterMerkerServer.aktualisierung(); beobachterMerkerKom.aktualisierenLobby(); return true; } return false; } @Override public boolean spielAnlegen(int spielerAnzahl) { if(spielerAnzahl>=3 && spielerAnzahl<=5) { return daten.spielAnlegen(spielerAnzahl); } return false; } @Override public boolean spielLaden(String dateipfad) { return daten.spielLaden(dateipfad); } @Override public boolean spielerAusgestiegen(String nameSpieler) { beobachterMerkerServer.aktualisierung(); beobachterMerkerKom.aktualisierenLobby(); return daten.spielerAusgestiegen(nameSpieler); } @Override public boolean spielerBereitMelden(String nameSpieler) { beobachterMerkerServer.aktualisierung(); beobachterMerkerKom.aktualisierenLobby(); return daten.spielerBereitMelden(nameSpieler); } @Override public boolean spielStarten() { if(alleSpielerBereit()) { return true; } return false; } @Override public boolean spielBeenden() { return false; //return daten.spielBeenden(); } @Override public boolean spielSpeichern(String dateipfad) { return false; //return daten.spielStarten(dateipfad); } @Override public boolean erstiesAnzahlErhoehen(Integer gebaeude, String nameSpieler) { zuVerteilendeErsties = daten.anzahlZuVerteilendeErsties(nameSpieler); if(zuVerteilendeErsties > 0){ if (daten.besitzerGebaeude(gebaeude).equals(nameSpieler)) { daten.anzahlZuVerteilendeErstiesAnpassen(nameSpieler,zuVerteilendeErsties - 1); daten.anzahlErstiesAnpassen(gebaeude, 1); missionskarte = daten.missionskarteSpieler(nameSpieler); if(vergleicheMissionskarte(missionskarte, nameSpieler)) return true; //Sieg return true; } } return false; } @Override public boolean tauschBonuskarten(String nameSpieler, Integer[] bonuskarten) { Integer zusetzendeErsties = daten.anzahlZuVerteilendeErsties(nameSpieler); //daten.anzahlDerBonuskarten(nameSpieler,Bonuskarte.Ersties) if(!hatGetauscht) { if (bonuskarten.length > 3) return false; if (bonuskarten[0] == 3) { daten.anzahlZuVerteilendeErstiesAnpassen(nameSpieler, zusetzendeErsties + 4); hatGetauscht = true; } if (bonuskarten[1] == 3) { daten.anzahlZuVerteilendeErstiesAnpassen(nameSpieler, zusetzendeErsties + 6); hatGetauscht = true; } if (bonuskarten[2] == 3) { daten.anzahlZuVerteilendeErstiesAnpassen(nameSpieler, zusetzendeErsties + 8); hatGetauscht = true; } if (bonuskarten[0] == 1 && bonuskarten[1] == 1 && bonuskarten[2] == 1) { daten.anzahlZuVerteilendeErstiesAnpassen(nameSpieler, zusetzendeErsties + 10); hatGetauscht = true; } beobachterMerkerServer.aktualisierung(); beobachterMerkerKom.aktualisierenKarte(); return true; } return false; } @Override public boolean angriffVonNach(Integer gebaeudeUrsprung, Integer anzahlUrsprung, Integer gebaeudeZiel, String nameSpieler) { Integer [] angreibareNachbarGebaeude = daten.angreifbareNachbarGebaeude(gebaeudeUrsprung, nameSpieler); if(verschiebenAngreifenVonNach(angreibareNachbarGebaeude, gebaeudeZiel)){ //Angreifen missionskarte = daten.missionskarteSpieler(nameSpieler); if(vergleicheMissionskarte(missionskarte, nameSpieler)) return true; //Sieg return true; } return false; } @Override public boolean versetzenVonNach(Integer gebaeudeUrsprung, Integer anzahlUrsprung, Integer gebaeudeZiel, String nameSpieler) { Integer [] eigeneNachbarGebaeude = daten.eigeneNachbarGebaeude(gebaeudeUrsprung, nameSpieler); if(verschiebenAngreifenVonNach(eigeneNachbarGebaeude, gebaeudeZiel)){ if(mindEinErstieGebaeude(gebaeudeUrsprung, anzahlUrsprung)){ daten.anzahlErstiesAnpassen(gebaeudeUrsprung, daten.anzahlErstiesGebaeude(gebaeudeUrsprung) - anzahlUrsprung); daten.anzahlErstiesAnpassen(gebaeudeZiel, daten.anzahlErstiesGebaeude(gebaeudeZiel) + anzahlUrsprung); missionskarte = daten.missionskarteSpieler(nameSpieler); if(vergleicheMissionskarte(missionskarte, nameSpieler)) return true; //Sieg beobachterMerkerServer.aktualisierung(); beobachterMerkerKom.aktualisierenKarte(); return true; } } return false; } @Override public boolean gewuerfelt(String nameSpieler) { return false; } @Override public boolean zugBeendet(String nameSpieler) { return daten.naechsterSpieler(); } @Override public boolean beobachterHinzufuegen(IKommunikationServerCallback beobachter) { beobachterMerkerKom = beobachter; return true; } @Override public boolean beobachterHinzufuegen(IGUIServerCallback beobachter) { beobachterMerkerServer = beobachter; return true; } }
33.696429
129
0.628511
e44f57b30706c2e70eee616c965bcc19db62433a
993
package marubinotto.piggydb.ui.page.partial; import marubinotto.piggydb.model.Fragment; import marubinotto.piggydb.model.Tag; public class AddTag extends AbstractPartial { public Long fragmentId; public Long tagId; public Fragment fragment; @Override protected void setModels() throws Exception { super.setModels(); // fragment setFragment(); if (this.fragment == null) return; // tag Tag tag = getTag(); if (tag == null) return; // tagging this.fragment.addTagByUser(tag, getUser()); try { getDomain().saveFragment(this.fragment, getUser()); } catch (Exception e) { setFragment(); // restore the original data throw e; } } private void setFragment() throws Exception { if (this.fragmentId == null) return; this.fragment = getDomain().getFragmentRepository().get(this.fragmentId); } private Tag getTag() throws Exception { if (this.tagId == null) return null; return getDomain().getTagRepository().get(this.tagId); } }
21.586957
75
0.698892
1c8722a8de22b8591b973a7c31d0fac1064395e3
604
package app.com.cn.album.dao; import java.util.List; /** * 作者:ArMn on 2016/3/6 * 邮箱:859686819@qq.com */ public class Category { public String suffix; public List<String> lists; public Category(String suffix, List<String> lists) { this.suffix = suffix; this.lists = lists; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public List<String> getLists() { return lists; } public void setLists(List<String> lists) { this.lists = lists; } }
17.764706
56
0.599338
1e3ad98cd14d6635943b8aba89fb1e274d3dcf85
4,244
/* * Copyright 2002-2006,2009 The Apache Software Foundation. * * 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.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.util.TextParseUtil; import com.opensymphony.xwork2.util.logging.Logger; import com.opensymphony.xwork2.util.logging.LoggerFactory; import java.util.Collections; import java.util.Set; import java.io.Serializable; /** * <!-- START SNIPPET: javadoc --> * * MethodFilterInterceptor is an abstract <code>Interceptor</code> used as * a base class for interceptors that will filter execution based on method * names according to specified included/excluded method lists. * * <p/> * * Settable parameters are as follows: * * <ul> * <li>excludeMethods - method names to be excluded from interceptor processing</li> * <li>includeMethods - method names to be included in interceptor processing</li> * </ul> * * <p/> * * <b>NOTE:</b> If method name are available in both includeMethods and * excludeMethods, it will be considered as an included method: * includeMethods takes precedence over excludeMethods. * * <p/> * * Interceptors that extends this capability include: * * <ul> * <li>TokenInterceptor</li> * <li>TokenSessionStoreInterceptor</li> * <li>DefaultWorkflowInterceptor</li> * <li>ValidationInterceptor</li> * </ul> * * <!-- END SNIPPET: javadoc --> * * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a> * @author Rainer Hermanns * * @see org.apache.struts2.interceptor.TokenInterceptor * @see org.apache.struts2.interceptor.TokenSessionStoreInterceptor * @see com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor * @see com.opensymphony.xwork2.validator.ValidationInterceptor * * @version $Date: 2009-12-27 19:18:29 +0100 (Sun, 27 Dec 2009) $ $Id: MethodFilterInterceptor.java 894090 2009-12-27 18:18:29Z martinc $ */ public abstract class MethodFilterInterceptor extends AbstractInterceptor implements Serializable { protected transient Logger log = LoggerFactory.getLogger(getClass()); protected Set<String> excludeMethods = Collections.emptySet(); protected Set<String> includeMethods = Collections.emptySet(); public void setExcludeMethods(String excludeMethods) { this.excludeMethods = TextParseUtil.commaDelimitedStringToSet(excludeMethods); } public Set<String> getExcludeMethodsSet() { return excludeMethods; } public void setIncludeMethods(String includeMethods) { this.includeMethods = TextParseUtil.commaDelimitedStringToSet(includeMethods); } public Set<String> getIncludeMethodsSet() { return includeMethods; } @Override public String intercept(ActionInvocation invocation) throws Exception { if (applyInterceptor(invocation)) { return doIntercept(invocation); } return invocation.invoke(); } protected boolean applyInterceptor(ActionInvocation invocation) { String method = invocation.getProxy().getMethod(); // ValidationInterceptor boolean applyMethod = MethodFilterInterceptorUtil.applyMethod(excludeMethods, includeMethods, method); if (log.isDebugEnabled()) { if (!applyMethod) { log.debug("Skipping Interceptor... Method [" + method + "] found in exclude list."); } } return applyMethod; } /** * Subclasses must override to implement the interceptor logic. * * @param invocation the action invocation * @return the result of invocation * @throws Exception */ protected abstract String doIntercept(ActionInvocation invocation) throws Exception; }
33.952
137
0.727144
169d7eea810ecb667a4b8396c467e578c30dc825
1,218
package net.chrisrichardson.eventstore.javaexamples.banking.backend.common.transactions; /* case class TransferDetails(fromAccountId : EntityIdentifier, toAccountId : EntityIdentifier, amount : BigDecimal) */ import java.math.BigDecimal; import java.util.Date; public class TransferDetails { private String fromAccountId; private String toAccountId; private BigDecimal amount; private Date date; private String description; private TransferDetails() { } public TransferDetails(String fromAccountId, String toAccountId, BigDecimal amount) { this(fromAccountId, toAccountId, amount, new Date(), ""); } public TransferDetails(String fromAccountId, String toAccountId, BigDecimal amount, Date date, String description) { this.fromAccountId = fromAccountId; this.toAccountId = toAccountId; this.amount = amount; this.date = date; this.description = description; } public String getFromAccountId() { return fromAccountId; } public String getToAccountId() { return toAccountId; } public BigDecimal getAmount() { return amount; } public Date getDate() { return date; } public String getDescription() { return description; } }
22.555556
118
0.735632
f488c99e8511dae802e7ed36e925d1634f944794
594
/* * Copyright (c) Tarek Hosni El Alaoui 2017 */ package de.dytanic.cloudnet.bridge.internal.serverselectors.packet.out; import de.dytanic.cloudnet.lib.network.protocol.packet.Packet; import de.dytanic.cloudnet.lib.network.protocol.packet.PacketRC; import de.dytanic.cloudnet.lib.serverselectors.sign.Sign; import de.dytanic.cloudnet.lib.utility.document.Document; /** * Created by Tareko on 23.08.2017. */ public class PacketOutRemoveSign extends Packet { public PacketOutRemoveSign(Sign sign) { super(PacketRC.SERVER_SELECTORS + 2, new Document("sign", sign)); } }
28.285714
73
0.757576
546a8fbc9dfc929a136a8a792f6f6eea1da9efb6
998
package com.ku.seoultrace.ranking; public class MyItem { String imgUrl; String name; int drawPoint; int placeNumber; MyItem() { } MyItem(String imgUrl, String name, int drawPoint, int placeNumber) { this.imgUrl = imgUrl; this.name = name; this.drawPoint = drawPoint; this.placeNumber = placeNumber; } public int getPlaceNumber() { return placeNumber; } public void setPlaceNumber(int placeNumber) { this.placeNumber = placeNumber; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getDrawPoint() { return drawPoint; } public void setDrawPoint(int drawPoint) { this.drawPoint = drawPoint; } @Override public String toString() { return "MyItem [imgUrl=" + imgUrl + ", name=" + name + ", drawPoint=" + drawPoint + ", placeNumber=" + placeNumber + "]"; } }
16.096774
71
0.675351
c7e63ed34f4c4c6c6c0136eb9703949cf99db34c
1,633
/*- * #%L * Coffee * %% * Copyright (C) 2020 i-Cell Mobilsoft Zrt. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package hu.icellmobilsoft.roaster.tm4j.common.api.reporter; import java.util.Optional; /** * Common interface for reporting test cases run statuses. * * @author martin.nagy * @since 0.2.0 */ public interface TestResultReporter { /** * Reports that the test run was successful. * * @param record data describing the test case and run parameters */ void reportSuccess(TestCaseData record); /** * Reports that the test run failed. * * @param record data describing the test case and run parameters * @param cause the error cause why the test failed */ void reportFail(TestCaseData record, Throwable cause); /** * Reports that the test case has not run. * * @param record data describing the test case and run parameters * @param reason {@code Optional} {@code String} for giving the reason why the test is disabled */ void reportDisabled(TestCaseData record, Optional<String> reason); }
29.160714
99
0.690141
f11c84fbb2c196cb6873fbb448541422a77d5924
1,755
package com.miotech.kun.metadata.databuilder.model; import com.miotech.kun.metadata.core.model.dataset.DataStore; import com.miotech.kun.workflow.core.model.lineage.*; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; public class DataStoreTest { private static final String URL = "test_url"; private static final String HOST = "host"; private static final int PORT = 7890; private static final String DATABASE = "test_database"; private static final String SCHEMA = "test_schema"; private static final String TABLE = "test_table"; @Test public void testGetDatabaseName_arango() { DataStore dataStore = new ArangoCollectionStore(HOST, PORT, DATABASE, TABLE); assertThat(dataStore.getDatabaseName(), is(DATABASE)); } @Test public void testGetDatabaseName_es() { DataStore dataStore = new ElasticSearchIndexStore(HOST, PORT, TABLE); assertThat(dataStore.getDatabaseName(), nullValue()); } @Test public void testGetDatabaseName_hive() { DataStore dataStore = new HiveTableStore(URL, DATABASE, TABLE); assertThat(dataStore.getDatabaseName(), is(DATABASE)); } @Test public void testGetDatabaseName_mongo() { DataStore dataStore = new MongoDataStore(HOST, PORT, DATABASE, TABLE); assertThat(dataStore.getDatabaseName(), is(DATABASE)); } @Test public void testGetDatabaseName_postgres() { DataStore dataStore = new PostgresDataStore(HOST, PORT, DATABASE, SCHEMA, TABLE); assertThat(dataStore.getDatabaseName(), is(String.format("%s.%s", DATABASE, SCHEMA))); } }
33.75
94
0.716239
e1b7169203503ea0919717cec0c9787e182935a6
473
/** */ package COSEM.COSEMObjects; import COSEM.InterfaceClasses.S_FSKMACsynctimeouts; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>SFSKMAC Synchronization Timeouts</b></em>'. * <!-- end-user-doc --> * * * @see COSEM.COSEMObjects.COSEMObjectsPackage#getS_FSKMACSynchronizationTimeouts() * @model * @generated */ public interface S_FSKMACSynchronizationTimeouts extends S_FSKMACsynctimeouts { } // S_FSKMACSynchronizationTimeouts
24.894737
91
0.742072
feb12f1bfc5b1a87d241349593bb8ca61ce5b884
1,191
package me.ienze.twoDimMap.io; import me.ienze.twoDimMap.MapLayer; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public abstract class MapImageWriter<T extends MapLayer> { private String format = "PNG"; public void write(T layer, File file) throws IOException { try (OutputStream out = new FileOutputStream(file)) { write(layer, out); } } public void write(T layer, OutputStream out) throws IOException { ImageIO.write(generateImage(layer), format, out); } public BufferedImage generateImage(T layer) { BufferedImage image = new BufferedImage(layer.getWidth(), layer.getHeight(), BufferedImage.TYPE_INT_RGB); for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { image.setRGB(x, y, layer.getColor(x, y).getRGB()); } } return image; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } }
26.466667
113
0.638959
94115ad05937dd1123b87342b9aa16969e2355af
10,012
/******************************************************************************* * Copyright (C) 2016 Black Duck Software, Inc. * http://www.blackducksoftware.com/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ package com.blackducksoftware.integration.email.mock; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.UUID; import org.mockito.Mockito; import com.blackducksoftware.integration.hub.api.item.MetaService; import com.blackducksoftware.integration.hub.api.notification.NotificationRequestService; import com.blackducksoftware.integration.hub.api.policy.PolicyRequestService; import com.blackducksoftware.integration.hub.api.project.version.ProjectVersionRequestService; import com.blackducksoftware.integration.hub.dataservice.model.ProjectVersionModel; import com.blackducksoftware.integration.hub.dataservice.notification.NotificationDataService; import com.blackducksoftware.integration.hub.dataservice.notification.NotificationResults; import com.blackducksoftware.integration.hub.dataservice.notification.model.NotificationContentItem; import com.blackducksoftware.integration.hub.dataservice.notification.model.PolicyOverrideContentItem; import com.blackducksoftware.integration.hub.dataservice.notification.model.PolicyViolationClearedContentItem; import com.blackducksoftware.integration.hub.dataservice.notification.model.PolicyViolationContentItem; import com.blackducksoftware.integration.hub.dataservice.notification.model.VulnerabilityContentItem; import com.blackducksoftware.integration.hub.model.view.ComponentVersionView; import com.blackducksoftware.integration.hub.model.view.PolicyRuleView; import com.blackducksoftware.integration.hub.model.view.components.VulnerabilitySourceQualifiedId; import com.blackducksoftware.integration.hub.service.HubResponseService; import com.blackducksoftware.integration.log.IntLogger; public class MockNotificationDataService extends NotificationDataService { public MockNotificationDataService(final IntLogger logger, final HubResponseService hubResponseService, final NotificationRequestService notificationRequestService, final ProjectVersionRequestService projectVersionRequestService, final PolicyRequestService policyRequestService, final MetaService metaService) { super(logger, hubResponseService, notificationRequestService, projectVersionRequestService, policyRequestService, null, metaService); } @Override public NotificationResults getAllNotifications(final Date startDate, final Date endDate) { try { return createNotificationList(); } catch (final URISyntaxException e) { throw new RuntimeException(e); } } private NotificationResults createNotificationList() throws URISyntaxException { final SortedSet<NotificationContentItem> contentList = new TreeSet<>(); contentList.addAll(createPolicyViolations()); contentList.addAll(createPolicyOverrides()); contentList.addAll(createVulnerabilities()); contentList.addAll(createPolicyViolationsCleared()); final NotificationResults results = new NotificationResults(contentList, Collections.emptyList()); return results; } private List<PolicyViolationContentItem> createPolicyViolations() throws URISyntaxException { final List<PolicyViolationContentItem> itemList = new ArrayList<>(); for (int index = 0; index < 5; index++) { final ProjectVersionModel projectVersion = new ProjectVersionModel(); final String componentName = "Component" + index; final String versionName = "Version" + index; final ComponentVersionView componentVersion = Mockito.mock(ComponentVersionView.class); componentVersion.versionName = versionName; final UUID componentId = UUID.randomUUID(); final UUID componentVersionId = UUID.randomUUID(); final String componentUrl = "http://localhost/api/components/" + componentId; final String componentVersionUrl = "http://localhost/api/components/" + componentId + "/versions/" + componentVersionId; final List<PolicyRuleView> policyRuleList = new ArrayList<>(); final PolicyViolationContentItem item = new PolicyViolationContentItem(new Date(), projectVersion, componentName, componentVersion, componentUrl, componentVersionUrl, policyRuleList, ""); itemList.add(item); } return itemList; } private List<PolicyOverrideContentItem> createPolicyOverrides() throws URISyntaxException { final List<PolicyOverrideContentItem> itemList = new ArrayList<>(); for (int index = 0; index < 5; index++) { final ProjectVersionModel projectVersion = new ProjectVersionModel(); final String componentName = "Component" + index; final String versionName = "Version" + index; final ComponentVersionView componentVersion = Mockito.mock(ComponentVersionView.class); componentVersion.versionName = versionName; final UUID componentId = UUID.randomUUID(); final UUID componentVersionId = UUID.randomUUID(); final String componentUrl = "http://localhost/api/components/" + componentId; final String componentVersionUrl = "http://localhost/api/components/" + componentId + "/versions/" + componentVersionId; final String firstName = "firstName"; final String lastName = "lastName"; final List<PolicyRuleView> policyRuleList = new ArrayList<>(); final PolicyOverrideContentItem item = new PolicyOverrideContentItem(new Date(), projectVersion, componentName, componentVersion, componentUrl, componentVersionUrl, policyRuleList, firstName, lastName, ""); itemList.add(item); } return itemList; } private List<VulnerabilityContentItem> createVulnerabilities() throws URISyntaxException { final List<VulnerabilityContentItem> itemList = new ArrayList<>(); for (int index = 0; index < 5; index++) { final ProjectVersionModel projectVersion = new ProjectVersionModel(); final String componentName = "Component" + index; final String versionName = "Version" + index; final ComponentVersionView componentVersion = Mockito.mock(ComponentVersionView.class); componentVersion.versionName = versionName; final UUID componentId = UUID.randomUUID(); final UUID componentVersionId = UUID.randomUUID(); final String componentVersionUrl = "http://localhost/api/components/" + componentId + "/versions/" + componentVersionId; final VulnerabilityContentItem item = new VulnerabilityContentItem(new Date(), projectVersion, componentName, componentVersion, componentVersionUrl, createVulnSourceIds(), createVulnSourceIds(), createVulnSourceIds(), ""); itemList.add(item); } return itemList; } private List<VulnerabilitySourceQualifiedId> createVulnSourceIds() { final List<VulnerabilitySourceQualifiedId> sourceIdList = new ArrayList<>(); for (int index = 0; index < 2; index++) { final VulnerabilitySourceQualifiedId sourceId = new VulnerabilitySourceQualifiedId(); sourceId.source = "source"; sourceId.vulnerabilityId = "id"; sourceIdList.add(sourceId); } return sourceIdList; } private List<PolicyViolationClearedContentItem> createPolicyViolationsCleared() throws URISyntaxException { final List<PolicyViolationClearedContentItem> itemList = new ArrayList<>(); for (int index = 0; index < 5; index++) { final ProjectVersionModel projectVersion = new ProjectVersionModel(); final String componentName = "Component" + index; final String versionName = "Version" + index; final ComponentVersionView componentVersion = Mockito.mock(ComponentVersionView.class); componentVersion.versionName = versionName; final UUID componentId = UUID.randomUUID(); final UUID componentVersionId = UUID.randomUUID(); final String componentUrl = "http://localhost/api/components/" + componentId; final String componentVersionUrl = "http://localhost/api/components/" + componentId + "/versions/" + componentVersionId; final List<PolicyRuleView> policyRuleList = new ArrayList<>(); final PolicyViolationClearedContentItem item = new PolicyViolationClearedContentItem(new Date(), projectVersion, componentName, componentVersion, componentUrl, componentVersionUrl, policyRuleList, ""); itemList.add(item); } return itemList; } }
56.247191
141
0.709349
71a9bc68ecaf74e848b74b241352dbb0fd615b58
2,052
package com.brusic.elasticsearch.ingest.comprehend; import com.brusic.aws.comprehend.service.DominantLanguageService; import org.apache.lucene.util.LuceneTestCase; import org.elasticsearch.ingest.IngestDocument; import org.mockito.Mockito; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Unit tests for {@link DominantLanguageProcessor} */ public class DominantLanguageProcessorTests extends LuceneTestCase { public void testExecute() throws Exception { DominantLanguageService mockService = Mockito.mock(DominantLanguageService.class); Mockito.when(mockService.getDominantLanguages("foo", 0f)).thenReturn(Collections.singletonList("en")); DominantLanguageProcessor processor = new DominantLanguageProcessor("tag", "source", "target", 0f, 0, false, mockService); IngestDocument ingestDocument = TestUtils.createTestDocument(); processor.execute(ingestDocument); List<?> values = ingestDocument.getFieldValue("target", List.class); assertEquals(1, values.size()); assertEquals("en", values.get(0)); } public void testExecuteWithSingleMaxValue() throws Exception { DominantLanguageService mockService = Mockito.mock(DominantLanguageService.class); Mockito.when(mockService.getDominantLanguages("foo", 0f)).thenReturn(Collections.singletonList("en")); DominantLanguageProcessor processor = new DominantLanguageProcessor("tag", "source", "target", 0f, 1, false, mockService); IngestDocument ingestDocument = TestUtils.createTestDocument(); processor.execute(ingestDocument); String value = ingestDocument.getFieldValue("target", String.class); assertEquals("en", value); } public void testType() throws Exception { DominantLanguageProcessor processor = new DominantLanguageProcessor("tag", "source", "target", 0f, 0, false, null); assertEquals(DominantLanguageProcessor.TYPE, processor.getType()); } }
42.75
110
0.725634
42665c7ae2b5b7b0480a0af636953673eb9338b7
106,118
// $ANTLR 3.5.1 /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g 2015-01-30 16:39:44 package grammar; import ui.cli.UI; import org.antlr.runtime.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; @SuppressWarnings("all") public class CliParser extends Parser { public static final String[] tokenNames = new String[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "Character", "Comment", "Decimal", "Digit", "EscapeSpace", "Hex", "HexDigit", "Identifier", "NewLine", "Register", "String", "WS", "'+'", "'-'", "':'", "'='", "'=='", "'a'", "'assert'", "'b'", "'break'", "'clear'", "'cpu'", "'dat'", "'e'", "'e/x'", "'examine'", "'examine/x'", "'g'", "'goto'", "'help'", "'i'", "'i/x'", "'info'", "'info/x'", "'ins'", "'l'", "'load'", "'m'", "'mem'", "'nob'", "'nobreak'", "'not'", "'notrace'", "'prog'", "'quit'", "'r'", "'reg'", "'run'", "'s'", "'step'", "'t'", "'test'", "'trace'", "'w'", "'where'", "'x'" }; public static final int EOF=-1; public static final int T__16=16; public static final int T__17=17; public static final int T__18=18; public static final int T__19=19; public static final int T__20=20; public static final int T__21=21; public static final int T__22=22; public static final int T__23=23; public static final int T__24=24; public static final int T__25=25; public static final int T__26=26; public static final int T__27=27; public static final int T__28=28; public static final int T__29=29; public static final int T__30=30; public static final int T__31=31; public static final int T__32=32; public static final int T__33=33; public static final int T__34=34; public static final int T__35=35; public static final int T__36=36; public static final int T__37=37; public static final int T__38=38; public static final int T__39=39; public static final int T__40=40; public static final int T__41=41; public static final int T__42=42; public static final int T__43=43; public static final int T__44=44; public static final int T__45=45; public static final int T__46=46; public static final int T__47=47; public static final int T__48=48; public static final int T__49=49; public static final int T__50=50; public static final int T__51=51; public static final int T__52=52; public static final int T__53=53; public static final int T__54=54; public static final int T__55=55; public static final int T__56=56; public static final int T__57=57; public static final int T__58=58; public static final int T__59=59; public static final int T__60=60; public static final int Character=4; public static final int Comment=5; public static final int Decimal=6; public static final int Digit=7; public static final int EscapeSpace=8; public static final int Hex=9; public static final int HexDigit=10; public static final int Identifier=11; public static final int NewLine=12; public static final int Register=13; public static final int String=14; public static final int WS=15; // delegates public Parser[] getDelegates() { return new Parser[] {}; } // delegators public CliParser(TokenStream input) { this(input, new RecognizerSharedState()); } public CliParser(TokenStream input, RecognizerSharedState state) { super(input, state); } @Override public String[] getTokenNames() { return CliParser.tokenNames; } @Override public String getGrammarFileName() { return "/Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g"; } public class QuitException extends RuntimeException {} public class SyntaxErrorException extends RuntimeException {} @Override public void reportError (RecognitionException re) { throw new SyntaxErrorException (); } public interface CommandHandler { public enum MemFormat {ASM,HEX}; public enum MemRegion {INS, DAT, ALL}; public enum InsOper {REPLACE,INSERT,DELETE}; public enum DebugType {BREAK,TRACE}; public enum DebugPoint {INSTRUCTION, MEMORY_READ, MEMORY_WRITE, MEMORY_ACCESS, REGISTER_READ, REGISTER_WRITE, REGISTER_ACCESS}; void load (String filename); void test (String filename, String bnchArch, String bnchVariant); void run (); void step (); void showWhere (); void gotoPC (int pc); void examineMem (int count, MemFormat format, int addr); void examineReg (int count, int addr); void examineMemAll (MemFormat format, MemRegion region); void examineRegAll (); void examineProc (String state); void assertReg (int regNum, int value, String desc); void assertMem (int addr, int value, String desc); void assertDesc (String desc); void setReg (int regNum, int value); void setMem (int addr, int value); void setIns (int addr, InsOper oper, String value); void debugPoint (DebugType type, DebugPoint point, boolean isEnabled, int value); void traceProg (boolean isEnabled); void clearDebugPoints (DebugType type); void showDebugPoints (DebugType type); void help (); int getRegisterNumber (String registerName); int getLabelValue (String label); } CommandHandler cmd; public void setCommandHandler (CommandHandler aCmd) { cmd = aCmd; } boolean dpIsEnabled; // $ANTLR start "command" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:1: command : ( load | test | run | step | where | gotoPC | examine | assertCmd | info | set | debug | infoDebug | quit | help ) EOF ; public final void command() throws RecognitionException { try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:9: ( ( load | test | run | step | where | gotoPC | examine | assertCmd | info | set | debug | infoDebug | quit | help ) EOF ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:11: ( load | test | run | step | where | gotoPC | examine | assertCmd | info | set | debug | infoDebug | quit | help ) EOF { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:11: ( load | test | run | step | where | gotoPC | examine | assertCmd | info | set | debug | infoDebug | quit | help ) int alt1=14; switch ( input.LA(1) ) { case 40: case 41: { alt1=1; } break; case 56: { alt1=2; } break; case 50: case 52: { alt1=3; } break; case 53: case 54: { alt1=4; } break; case 58: case 59: { alt1=5; } break; case 32: case 33: { alt1=6; } break; case 28: case 29: case 30: case 31: { alt1=7; } break; case 21: case 22: { alt1=8; } break; case 35: { switch ( input.LA(2) ) { case 43: { int LA1_16 = input.LA(3); if ( (LA1_16==EOF) ) { alt1=9; } else if ( ((LA1_16 >= 16 && LA1_16 <= 17)||LA1_16==19) ) { alt1=10; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 1, 16, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 39: { int LA1_17 = input.LA(3); if ( (LA1_17==EOF) ) { alt1=9; } else if ( ((LA1_17 >= 16 && LA1_17 <= 17)||LA1_17==19) ) { alt1=10; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 1, 17, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 27: { int LA1_18 = input.LA(3); if ( (LA1_18==EOF) ) { alt1=9; } else if ( ((LA1_18 >= 16 && LA1_18 <= 17)||LA1_18==19) ) { alt1=10; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 1, 18, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 51: { int LA1_19 = input.LA(3); if ( (LA1_19==EOF) ) { alt1=9; } else if ( ((LA1_19 >= 16 && LA1_19 <= 17)||LA1_19==19) ) { alt1=10; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 1, 19, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 26: { int LA1_20 = input.LA(3); if ( (LA1_20==EOF||LA1_20==Identifier||LA1_20==21||(LA1_20 >= 23 && LA1_20 <= 28)||LA1_20==30||(LA1_20 >= 32 && LA1_20 <= 35)||LA1_20==37||(LA1_20 >= 39 && LA1_20 <= 43)||(LA1_20 >= 48 && LA1_20 <= 60)) ) { alt1=9; } else if ( ((LA1_20 >= 16 && LA1_20 <= 17)||LA1_20==19) ) { alt1=10; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 1, 20, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case Decimal: case Hex: case Identifier: case 21: case 25: case 28: case 30: case 32: case 33: case 34: case 35: case 37: case 40: case 41: case 42: case 48: case 49: case 50: case 52: case 53: case 54: case 56: case 58: case 59: case 60: { alt1=10; } break; case 23: case 24: { int LA1_21 = input.LA(3); if ( ((LA1_21 >= 16 && LA1_21 <= 17)||LA1_21==19) ) { alt1=10; } else if ( (LA1_21==EOF) ) { alt1=12; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 1, 21, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 55: case 57: { int LA1_22 = input.LA(3); if ( ((LA1_22 >= 16 && LA1_22 <= 17)||LA1_22==19) ) { alt1=10; } else if ( (LA1_22==EOF) ) { alt1=12; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 1, 22, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; default: int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 1, 9, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 37: { int LA1_10 = input.LA(2); if ( ((LA1_10 >= 26 && LA1_10 <= 27)||LA1_10==39||LA1_10==43||LA1_10==51) ) { alt1=9; } else if ( ((LA1_10 >= 23 && LA1_10 <= 24)||LA1_10==55||LA1_10==57) ) { alt1=12; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 1, 10, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 36: case 38: { alt1=9; } break; case Register: case 42: { alt1=10; } break; case 23: case 24: case 25: case 44: case 45: case 46: case 47: case 55: case 57: { alt1=11; } break; case 49: { alt1=13; } break; case 34: { alt1=14; } break; default: NoViableAltException nvae = new NoViableAltException("", 1, 0, input); throw nvae; } switch (alt1) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:12: load { pushFollow(FOLLOW_load_in_command41); load(); state._fsp--; } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:19: test { pushFollow(FOLLOW_test_in_command45); test(); state._fsp--; } break; case 3 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:26: run { pushFollow(FOLLOW_run_in_command49); run(); state._fsp--; } break; case 4 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:32: step { pushFollow(FOLLOW_step_in_command53); step(); state._fsp--; } break; case 5 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:39: where { pushFollow(FOLLOW_where_in_command57); where(); state._fsp--; } break; case 6 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:47: gotoPC { pushFollow(FOLLOW_gotoPC_in_command61); gotoPC(); state._fsp--; } break; case 7 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:56: examine { pushFollow(FOLLOW_examine_in_command65); examine(); state._fsp--; } break; case 8 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:66: assertCmd { pushFollow(FOLLOW_assertCmd_in_command69); assertCmd(); state._fsp--; } break; case 9 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:78: info { pushFollow(FOLLOW_info_in_command73); info(); state._fsp--; } break; case 10 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:85: set { pushFollow(FOLLOW_set_in_command77); set(); state._fsp--; } break; case 11 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:91: debug { pushFollow(FOLLOW_debug_in_command81); debug(); state._fsp--; } break; case 12 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:99: infoDebug { pushFollow(FOLLOW_infoDebug_in_command85); infoDebug(); state._fsp--; } break; case 13 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:111: quit { pushFollow(FOLLOW_quit_in_command89); quit(); state._fsp--; } break; case 14 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:72:118: help { pushFollow(FOLLOW_help_in_command93); help(); state._fsp--; } break; } match(input,EOF,FOLLOW_EOF_in_command96); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "command" // $ANTLR start "keyword" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:74:1: keyword : ( 'a' | 'm' | 'i' | 'l' | 'x' | 'load' | 'test' | 'e' | 'examine' | 'r' | 'run' | 's' | 'step' | 'w' | 'where' | 'g' | 'goto' | 't' | 'trace' | 'b' | 'break' | 'info' | 'help' | 'quit' | 'mem' | 'ins' | 'dat' | 'reg' | 'cpu' | 'clear' | 'prog' ) ; public final void keyword() throws RecognitionException { try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:74:9: ( ( 'a' | 'm' | 'i' | 'l' | 'x' | 'load' | 'test' | 'e' | 'examine' | 'r' | 'run' | 's' | 'step' | 'w' | 'where' | 'g' | 'goto' | 't' | 'trace' | 'b' | 'break' | 'info' | 'help' | 'quit' | 'mem' | 'ins' | 'dat' | 'reg' | 'cpu' | 'clear' | 'prog' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g: { if ( input.LA(1)==21||(input.LA(1) >= 23 && input.LA(1) <= 28)||input.LA(1)==30||(input.LA(1) >= 32 && input.LA(1) <= 35)||input.LA(1)==37||(input.LA(1) >= 39 && input.LA(1) <= 43)||(input.LA(1) >= 48 && input.LA(1) <= 60) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "keyword" // $ANTLR start "load" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:76:1: load : ( 'l' | 'load' ) f= filename ; public final void load() throws RecognitionException { ParserRuleReturnScope f =null; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:76:6: ( ( 'l' | 'load' ) f= filename ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:76:8: ( 'l' | 'load' ) f= filename { if ( (input.LA(1) >= 40 && input.LA(1) <= 41) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } pushFollow(FOLLOW_filename_in_load182); f=filename(); state._fsp--; cmd.load ((f!=null?((CliParser.filename_return)f).value:null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "load" // $ANTLR start "test" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:78:1: test : ( 'test' ) filename (arch= identifier (variant= identifier )? )? ; public final void test() throws RecognitionException { ParserRuleReturnScope arch =null; ParserRuleReturnScope variant =null; ParserRuleReturnScope filename1 =null; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:78:9: ( ( 'test' ) filename (arch= identifier (variant= identifier )? )? ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:78:17: ( 'test' ) filename (arch= identifier (variant= identifier )? )? { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:78:17: ( 'test' ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:78:18: 'test' { match(input,56,FOLLOW_56_in_test205); } pushFollow(FOLLOW_filename_in_test208); filename1=filename(); state._fsp--; // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:78:35: (arch= identifier (variant= identifier )? )? int alt3=2; int LA3_0 = input.LA(1); if ( (LA3_0==Identifier||LA3_0==21||(LA3_0 >= 23 && LA3_0 <= 28)||LA3_0==30||(LA3_0 >= 32 && LA3_0 <= 35)||LA3_0==37||(LA3_0 >= 39 && LA3_0 <= 43)||(LA3_0 >= 48 && LA3_0 <= 60)) ) { alt3=1; } switch (alt3) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:78:36: arch= identifier (variant= identifier )? { pushFollow(FOLLOW_identifier_in_test213); arch=identifier(); state._fsp--; // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:78:59: (variant= identifier )? int alt2=2; int LA2_0 = input.LA(1); if ( (LA2_0==Identifier||LA2_0==21||(LA2_0 >= 23 && LA2_0 <= 28)||LA2_0==30||(LA2_0 >= 32 && LA2_0 <= 35)||LA2_0==37||(LA2_0 >= 39 && LA2_0 <= 43)||(LA2_0 >= 48 && LA2_0 <= 60)) ) { alt2=1; } switch (alt2) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:78:59: variant= identifier { pushFollow(FOLLOW_identifier_in_test217); variant=identifier(); state._fsp--; } break; } } break; } cmd.test ((filename1!=null?input.toString(filename1.start,filename1.stop):null), (arch!=null?input.toString(arch.start,arch.stop):null), (variant!=null?input.toString(variant.start,variant.stop):null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "test" // $ANTLR start "run" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:80:1: run : ( 'r' | 'run' ) ; public final void run() throws RecognitionException { try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:80:5: ( ( 'r' | 'run' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:80:7: ( 'r' | 'run' ) { if ( input.LA(1)==50||input.LA(1)==52 ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } cmd.run (); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "run" // $ANTLR start "step" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:82:1: step : ( 's' | 'step' ) ; public final void step() throws RecognitionException { try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:82:6: ( ( 's' | 'step' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:82:8: ( 's' | 'step' ) { if ( (input.LA(1) >= 53 && input.LA(1) <= 54) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } cmd.step (); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "step" // $ANTLR start "where" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:84:1: where : ( 'w' | 'where' ) ; public final void where() throws RecognitionException { try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:84:8: ( ( 'w' | 'where' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:84:10: ( 'w' | 'where' ) { if ( (input.LA(1) >= 58 && input.LA(1) <= 59) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } cmd.showWhere (); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "where" // $ANTLR start "gotoPC" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:86:1: gotoPC : ( 'g' | 'goto' ) pc= address ; public final void gotoPC() throws RecognitionException { int pc =0; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:86:8: ( ( 'g' | 'goto' ) pc= address ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:86:10: ( 'g' | 'goto' ) pc= address { if ( (input.LA(1) >= 32 && input.LA(1) <= 33) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } pushFollow(FOLLOW_address_in_gotoPC316); pc=address(); state._fsp--; cmd.gotoPC (pc); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "gotoPC" // $ANTLR start "examine" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:88:1: examine : ( ( ( 'e' | 'examine' | ( ( 'e/x' | 'examine/x' ) ) ) ( (addr= address ( ':' count= number )? ) ) ) | ( ( 'e' | 'examine' ) ( ( register ( ':' count= number )? ) ) ) ); public final void examine() throws RecognitionException { int addr =0; int count =0; int register2 =0; CommandHandler.MemFormat format=CommandHandler.MemFormat.ASM; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:89:9: ( ( ( 'e' | 'examine' | ( ( 'e/x' | 'examine/x' ) ) ) ( (addr= address ( ':' count= number )? ) ) ) | ( ( 'e' | 'examine' ) ( ( register ( ':' count= number )? ) ) ) ) int alt7=2; switch ( input.LA(1) ) { case 28: { int LA7_1 = input.LA(2); if ( (LA7_1==Decimal||LA7_1==Hex||LA7_1==Identifier||LA7_1==21||(LA7_1 >= 23 && LA7_1 <= 28)||LA7_1==30||(LA7_1 >= 32 && LA7_1 <= 35)||LA7_1==37||(LA7_1 >= 39 && LA7_1 <= 43)||(LA7_1 >= 48 && LA7_1 <= 60)) ) { alt7=1; } else if ( (LA7_1==Register) ) { alt7=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 7, 1, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 30: { int LA7_2 = input.LA(2); if ( (LA7_2==Decimal||LA7_2==Hex||LA7_2==Identifier||LA7_2==21||(LA7_2 >= 23 && LA7_2 <= 28)||LA7_2==30||(LA7_2 >= 32 && LA7_2 <= 35)||LA7_2==37||(LA7_2 >= 39 && LA7_2 <= 43)||(LA7_2 >= 48 && LA7_2 <= 60)) ) { alt7=1; } else if ( (LA7_2==Register) ) { alt7=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 7, 2, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 29: case 31: { alt7=1; } break; default: NoViableAltException nvae = new NoViableAltException("", 7, 0, input); throw nvae; } switch (alt7) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:89:11: ( ( 'e' | 'examine' | ( ( 'e/x' | 'examine/x' ) ) ) ( (addr= address ( ':' count= number )? ) ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:89:11: ( ( 'e' | 'examine' | ( ( 'e/x' | 'examine/x' ) ) ) ( (addr= address ( ':' count= number )? ) ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:89:12: ( 'e' | 'examine' | ( ( 'e/x' | 'examine/x' ) ) ) ( (addr= address ( ':' count= number )? ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:89:12: ( 'e' | 'examine' | ( ( 'e/x' | 'examine/x' ) ) ) int alt4=3; switch ( input.LA(1) ) { case 28: { alt4=1; } break; case 30: { alt4=2; } break; case 29: case 31: { alt4=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 4, 0, input); throw nvae; } switch (alt4) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:89:13: 'e' { match(input,28,FOLLOW_28_in_examine354); } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:89:17: 'examine' { match(input,30,FOLLOW_30_in_examine356); } break; case 3 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:89:27: ( ( 'e/x' | 'examine/x' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:89:27: ( ( 'e/x' | 'examine/x' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:89:28: ( 'e/x' | 'examine/x' ) { if ( input.LA(1)==29||input.LA(1)==31 ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } format=CommandHandler.MemFormat.HEX; } } break; } // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:90:19: ( (addr= address ( ':' count= number )? ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:90:20: (addr= address ( ':' count= number )? ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:90:20: (addr= address ( ':' count= number )? ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:90:21: addr= address ( ':' count= number )? { pushFollow(FOLLOW_address_in_examine392); addr=address(); state._fsp--; // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:90:34: ( ':' count= number )? int alt5=2; int LA5_0 = input.LA(1); if ( (LA5_0==18) ) { alt5=1; } switch (alt5) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:90:35: ':' count= number { match(input,18,FOLLOW_18_in_examine395); pushFollow(FOLLOW_number_in_examine399); count=number(); state._fsp--; } break; } cmd.examineMem (count, format, addr); } } } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:92:17: ( ( 'e' | 'examine' ) ( ( register ( ':' count= number )? ) ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:92:17: ( ( 'e' | 'examine' ) ( ( register ( ':' count= number )? ) ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:92:18: ( 'e' | 'examine' ) ( ( register ( ':' count= number )? ) ) { if ( input.LA(1)==28||input.LA(1)==30 ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:93:19: ( ( register ( ':' count= number )? ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:93:20: ( register ( ':' count= number )? ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:93:20: ( register ( ':' count= number )? ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:93:21: register ( ':' count= number )? { pushFollow(FOLLOW_register_in_examine456); register2=register(); state._fsp--; // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:93:30: ( ':' count= number )? int alt6=2; int LA6_0 = input.LA(1); if ( (LA6_0==18) ) { alt6=1; } switch (alt6) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:93:31: ':' count= number { match(input,18,FOLLOW_18_in_examine459); pushFollow(FOLLOW_number_in_examine463); count=number(); state._fsp--; } break; } cmd.examineReg (count, register2); } } } } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "examine" // $ANTLR start "assertCmd" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:95:1: assertCmd : ( ( ( 'a' | 'assert' ) addr= address '==' value= address (desc= string )? ) | ( ( 'a' | 'assert' ) register '==' value= address (desc= string )? ) | ( ( 'a' | 'assert' ) desc= string ) ); public final void assertCmd() throws RecognitionException { int addr =0; int value =0; String desc =null; int register3 =0; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:96:2: ( ( ( 'a' | 'assert' ) addr= address '==' value= address (desc= string )? ) | ( ( 'a' | 'assert' ) register '==' value= address (desc= string )? ) | ( ( 'a' | 'assert' ) desc= string ) ) int alt10=3; int LA10_0 = input.LA(1); if ( ((LA10_0 >= 21 && LA10_0 <= 22)) ) { switch ( input.LA(2) ) { case Decimal: case Hex: case Identifier: case 21: case 23: case 24: case 25: case 26: case 27: case 28: case 30: case 32: case 33: case 34: case 35: case 37: case 39: case 40: case 41: case 42: case 43: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: { alt10=1; } break; case Register: { alt10=2; } break; case String: { alt10=3; } break; default: int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 10, 1, input); throw nvae; } finally { input.rewind(nvaeMark); } } } else { NoViableAltException nvae = new NoViableAltException("", 10, 0, input); throw nvae; } switch (alt10) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:96:4: ( ( 'a' | 'assert' ) addr= address '==' value= address (desc= string )? ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:96:4: ( ( 'a' | 'assert' ) addr= address '==' value= address (desc= string )? ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:96:5: ( 'a' | 'assert' ) addr= address '==' value= address (desc= string )? { if ( (input.LA(1) >= 21 && input.LA(1) <= 22) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } pushFollow(FOLLOW_address_in_assertCmd492); addr=address(); state._fsp--; match(input,20,FOLLOW_20_in_assertCmd494); pushFollow(FOLLOW_address_in_assertCmd498); value=address(); state._fsp--; // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:96:58: (desc= string )? int alt8=2; int LA8_0 = input.LA(1); if ( (LA8_0==String) ) { alt8=1; } switch (alt8) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:96:58: desc= string { pushFollow(FOLLOW_string_in_assertCmd502); desc=string(); state._fsp--; } break; } } cmd.assertMem (addr, value, desc); } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:97:17: ( ( 'a' | 'assert' ) register '==' value= address (desc= string )? ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:97:17: ( ( 'a' | 'assert' ) register '==' value= address (desc= string )? ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:97:18: ( 'a' | 'assert' ) register '==' value= address (desc= string )? { if ( (input.LA(1) >= 21 && input.LA(1) <= 22) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } pushFollow(FOLLOW_register_in_assertCmd535); register3=register(); state._fsp--; match(input,20,FOLLOW_20_in_assertCmd537); pushFollow(FOLLOW_address_in_assertCmd541); value=address(); state._fsp--; // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:97:67: (desc= string )? int alt9=2; int LA9_0 = input.LA(1); if ( (LA9_0==String) ) { alt9=1; } switch (alt9) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:97:67: desc= string { pushFollow(FOLLOW_string_in_assertCmd545); desc=string(); state._fsp--; } break; } } cmd.assertReg (register3, value, desc); } break; case 3 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:98:17: ( ( 'a' | 'assert' ) desc= string ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:98:17: ( ( 'a' | 'assert' ) desc= string ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:98:18: ( 'a' | 'assert' ) desc= string { if ( (input.LA(1) >= 21 && input.LA(1) <= 22) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } pushFollow(FOLLOW_string_in_assertCmd580); desc=string(); state._fsp--; } cmd.assertDesc (desc); } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "assertCmd" // $ANTLR start "info" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:99:1: info : ( ( ( 'i' | 'info' | ( ( 'i/x' | 'info/x' ) ) ) ( ( 'mem' ) | ( 'ins' ) | ( 'dat' ) ) ) | ( ( 'i' | 'info' ) ( ( 'reg' ) | ( 'cpu' (ps= identifier )? ) ) ) ); public final void info() throws RecognitionException { ParserRuleReturnScope ps =null; CommandHandler.MemFormat format=CommandHandler.MemFormat.ASM; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:100:9: ( ( ( 'i' | 'info' | ( ( 'i/x' | 'info/x' ) ) ) ( ( 'mem' ) | ( 'ins' ) | ( 'dat' ) ) ) | ( ( 'i' | 'info' ) ( ( 'reg' ) | ( 'cpu' (ps= identifier )? ) ) ) ) int alt15=2; switch ( input.LA(1) ) { case 35: { int LA15_1 = input.LA(2); if ( (LA15_1==27||LA15_1==39||LA15_1==43) ) { alt15=1; } else if ( (LA15_1==26||LA15_1==51) ) { alt15=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 15, 1, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 37: { int LA15_2 = input.LA(2); if ( (LA15_2==27||LA15_2==39||LA15_2==43) ) { alt15=1; } else if ( (LA15_2==26||LA15_2==51) ) { alt15=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 15, 2, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 36: case 38: { alt15=1; } break; default: NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:100:11: ( ( 'i' | 'info' | ( ( 'i/x' | 'info/x' ) ) ) ( ( 'mem' ) | ( 'ins' ) | ( 'dat' ) ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:100:11: ( ( 'i' | 'info' | ( ( 'i/x' | 'info/x' ) ) ) ( ( 'mem' ) | ( 'ins' ) | ( 'dat' ) ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:100:12: ( 'i' | 'info' | ( ( 'i/x' | 'info/x' ) ) ) ( ( 'mem' ) | ( 'ins' ) | ( 'dat' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:100:12: ( 'i' | 'info' | ( ( 'i/x' | 'info/x' ) ) ) int alt11=3; switch ( input.LA(1) ) { case 35: { alt11=1; } break; case 37: { alt11=2; } break; case 36: case 38: { alt11=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 11, 0, input); throw nvae; } switch (alt11) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:100:13: 'i' { match(input,35,FOLLOW_35_in_info615); } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:100:17: 'info' { match(input,37,FOLLOW_37_in_info617); } break; case 3 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:100:24: ( ( 'i/x' | 'info/x' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:100:24: ( ( 'i/x' | 'info/x' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:100:25: ( 'i/x' | 'info/x' ) { if ( input.LA(1)==36||input.LA(1)==38 ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } format=CommandHandler.MemFormat.HEX; } } break; } // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:101:19: ( ( 'mem' ) | ( 'ins' ) | ( 'dat' ) ) int alt12=3; switch ( input.LA(1) ) { case 43: { alt12=1; } break; case 39: { alt12=2; } break; case 27: { alt12=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 12, 0, input); throw nvae; } switch (alt12) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:101:20: ( 'mem' ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:101:20: ( 'mem' ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:101:21: 'mem' { match(input,43,FOLLOW_43_in_info651); cmd.examineMemAll (format, CommandHandler.MemRegion.ALL); } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:103:20: ( 'ins' ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:103:20: ( 'ins' ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:103:21: 'ins' { match(input,39,FOLLOW_39_in_info703); cmd.examineMemAll (format, CommandHandler.MemRegion.INS); } } break; case 3 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:105:20: ( 'dat' ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:105:20: ( 'dat' ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:105:21: 'dat' { match(input,27,FOLLOW_27_in_info754); cmd.examineMemAll (format, CommandHandler.MemRegion.DAT); } } break; } } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:107:17: ( ( 'i' | 'info' ) ( ( 'reg' ) | ( 'cpu' (ps= identifier )? ) ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:107:17: ( ( 'i' | 'info' ) ( ( 'reg' ) | ( 'cpu' (ps= identifier )? ) ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:107:18: ( 'i' | 'info' ) ( ( 'reg' ) | ( 'cpu' (ps= identifier )? ) ) { if ( input.LA(1)==35||input.LA(1)==37 ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:108:19: ( ( 'reg' ) | ( 'cpu' (ps= identifier )? ) ) int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0==51) ) { alt14=1; } else if ( (LA14_0==26) ) { alt14=2; } else { NoViableAltException nvae = new NoViableAltException("", 14, 0, input); throw nvae; } switch (alt14) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:108:20: ( 'reg' ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:108:20: ( 'reg' ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:108:21: 'reg' { match(input,51,FOLLOW_51_in_info830); cmd.examineRegAll (); } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:109:20: ( 'cpu' (ps= identifier )? ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:109:20: ( 'cpu' (ps= identifier )? ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:109:21: 'cpu' (ps= identifier )? { match(input,26,FOLLOW_26_in_info857); // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:109:29: (ps= identifier )? int alt13=2; int LA13_0 = input.LA(1); if ( (LA13_0==Identifier||LA13_0==21||(LA13_0 >= 23 && LA13_0 <= 28)||LA13_0==30||(LA13_0 >= 32 && LA13_0 <= 35)||LA13_0==37||(LA13_0 >= 39 && LA13_0 <= 43)||(LA13_0 >= 48 && LA13_0 <= 60)) ) { alt13=1; } switch (alt13) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:109:29: ps= identifier { pushFollow(FOLLOW_identifier_in_info861); ps=identifier(); state._fsp--; } break; } cmd.examineProc ((ps!=null?input.toString(ps.start,ps.stop):null)); } } break; } } } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "info" // $ANTLR start "set" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:110:1: set : ( ( register '=' val= address ) | ( 'm' addr= address '=' val= address ) | ( ( 'i' addr= address ) ( ( '=' instr0= instr ) | ( '+' instr1= instr ) | ( '-' ) ) ) ); public final void set() throws RecognitionException { int val =0; int addr =0; String instr0 =null; String instr1 =null; int register4 =0; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:110:5: ( ( register '=' val= address ) | ( 'm' addr= address '=' val= address ) | ( ( 'i' addr= address ) ( ( '=' instr0= instr ) | ( '+' instr1= instr ) | ( '-' ) ) ) ) int alt17=3; switch ( input.LA(1) ) { case Register: { alt17=1; } break; case 42: { alt17=2; } break; case 35: { alt17=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 17, 0, input); throw nvae; } switch (alt17) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:110:7: ( register '=' val= address ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:110:7: ( register '=' val= address ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:110:8: register '=' val= address { pushFollow(FOLLOW_register_in_set875); register4=register(); state._fsp--; match(input,19,FOLLOW_19_in_set877); pushFollow(FOLLOW_address_in_set881); val=address(); state._fsp--; } cmd.setReg (register4, val); } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:112:3: ( 'm' addr= address '=' val= address ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:112:3: ( 'm' addr= address '=' val= address ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:112:4: 'm' addr= address '=' val= address { match(input,42,FOLLOW_42_in_set895); pushFollow(FOLLOW_address_in_set899); addr=address(); state._fsp--; match(input,19,FOLLOW_19_in_set901); pushFollow(FOLLOW_address_in_set905); val=address(); state._fsp--; } cmd.setMem (addr, val); } break; case 3 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:114:3: ( ( 'i' addr= address ) ( ( '=' instr0= instr ) | ( '+' instr1= instr ) | ( '-' ) ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:114:3: ( ( 'i' addr= address ) ( ( '=' instr0= instr ) | ( '+' instr1= instr ) | ( '-' ) ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:114:4: ( 'i' addr= address ) ( ( '=' instr0= instr ) | ( '+' instr1= instr ) | ( '-' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:114:4: ( 'i' addr= address ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:114:5: 'i' addr= address { match(input,35,FOLLOW_35_in_set920); pushFollow(FOLLOW_address_in_set924); addr=address(); state._fsp--; } // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:115:19: ( ( '=' instr0= instr ) | ( '+' instr1= instr ) | ( '-' ) ) int alt16=3; switch ( input.LA(1) ) { case 19: { alt16=1; } break; case 16: { alt16=2; } break; case 17: { alt16=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 16, 0, input); throw nvae; } switch (alt16) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:115:20: ( '=' instr0= instr ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:115:20: ( '=' instr0= instr ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:115:21: '=' instr0= instr { match(input,19,FOLLOW_19_in_set948); pushFollow(FOLLOW_instr_in_set952); instr0=instr(); state._fsp--; cmd.setIns (addr, CommandHandler.InsOper.REPLACE, instr0); } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:117:20: ( '+' instr1= instr ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:117:20: ( '+' instr1= instr ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:117:21: '+' instr1= instr { match(input,16,FOLLOW_16_in_set1003); pushFollow(FOLLOW_instr_in_set1007); instr1=instr(); state._fsp--; cmd.setIns (addr, CommandHandler.InsOper.INSERT, instr1); } } break; case 3 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:119:20: ( '-' ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:119:20: ( '-' ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:119:21: '-' { match(input,17,FOLLOW_17_in_set1058); cmd.setIns (addr, CommandHandler.InsOper.DELETE, ""); } } break; } } } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "set" // $ANTLR start "debug" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:121:1: debug : ( debugPoint | traceProg | clear ); public final void debug() throws RecognitionException { try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:121:9: ( debugPoint | traceProg | clear ) int alt18=3; switch ( input.LA(1) ) { case 23: case 24: case 44: case 45: { alt18=1; } break; case 55: case 57: { int LA18_2 = input.LA(2); if ( (LA18_2==21||LA18_2==50||LA18_2==58||LA18_2==60) ) { alt18=1; } else if ( (LA18_2==48) ) { alt18=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 18, 2, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 46: { int LA18_3 = input.LA(2); if ( (LA18_3==21||LA18_3==50||LA18_3==58||LA18_3==60) ) { alt18=1; } else if ( (LA18_3==48) ) { alt18=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 18, 3, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 47: { int LA18_4 = input.LA(2); if ( (LA18_4==21||LA18_4==50||LA18_4==58||LA18_4==60) ) { alt18=1; } else if ( (LA18_4==48) ) { alt18=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 18, 4, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 25: { alt18=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 18, 0, input); throw nvae; } switch (alt18) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:121:17: debugPoint { pushFollow(FOLLOW_debugPoint_in_debug1103); debugPoint(); state._fsp--; } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:121:30: traceProg { pushFollow(FOLLOW_traceProg_in_debug1107); traceProg(); state._fsp--; } break; case 3 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:121:42: clear { pushFollow(FOLLOW_clear_in_debug1111); clear(); state._fsp--; } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "debug" // $ANTLR start "debugPoint" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:122:1: debugPoint : ( ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) | ( ( ( 'nob' | 'nobreak' ) ) | ( ( 'not' | 'notrace' ) ) ) ) ( 'x' (a0= address ) | ( ( ( ( 'r' | 'w' | 'a' ) (a1= address ) ) | ( ( 'r' | 'w' | 'a' ) ( register ) ) ) ) ) ; public final void debugPoint() throws RecognitionException { int a0 =0; int a1 =0; int register5 =0; boolean isEnabled=false; CommandHandler.DebugType type=null; CommandHandler.DebugPoint point=null; int value=0; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:126:9: ( ( ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) | ( ( ( 'nob' | 'nobreak' ) ) | ( ( 'not' | 'notrace' ) ) ) ) ( 'x' (a0= address ) | ( ( ( ( 'r' | 'w' | 'a' ) (a1= address ) ) | ( ( 'r' | 'w' | 'a' ) ( register ) ) ) ) ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:126:17: ( ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) | ( ( ( 'nob' | 'nobreak' ) ) | ( ( 'not' | 'notrace' ) ) ) ) ( 'x' (a0= address ) | ( ( ( ( 'r' | 'w' | 'a' ) (a1= address ) ) | ( ( 'r' | 'w' | 'a' ) ( register ) ) ) ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:126:17: ( ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) | ( ( ( 'nob' | 'nobreak' ) ) | ( ( 'not' | 'notrace' ) ) ) ) int alt21=2; int LA21_0 = input.LA(1); if ( ((LA21_0 >= 23 && LA21_0 <= 24)||LA21_0==55||LA21_0==57) ) { alt21=1; } else if ( ((LA21_0 >= 44 && LA21_0 <= 47)) ) { alt21=2; } else { NoViableAltException nvae = new NoViableAltException("", 21, 0, input); throw nvae; } switch (alt21) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:126:18: ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:126:18: ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) int alt19=2; int LA19_0 = input.LA(1); if ( ((LA19_0 >= 23 && LA19_0 <= 24)) ) { alt19=1; } else if ( (LA19_0==55||LA19_0==57) ) { alt19=2; } else { NoViableAltException nvae = new NoViableAltException("", 19, 0, input); throw nvae; } switch (alt19) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:126:19: ( ( 'b' | 'break' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:126:19: ( ( 'b' | 'break' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:126:20: ( 'b' | 'break' ) { if ( (input.LA(1) >= 23 && input.LA(1) <= 24) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } type=CommandHandler.DebugType.BREAK; } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:127:18: ( ( 't' | 'trace' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:127:18: ( ( 't' | 'trace' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:127:19: ( 't' | 'trace' ) { if ( input.LA(1)==55||input.LA(1)==57 ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } type=CommandHandler.DebugType.TRACE; } } break; } isEnabled=true; } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:128:17: ( ( ( 'nob' | 'nobreak' ) ) | ( ( 'not' | 'notrace' ) ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:128:17: ( ( ( 'nob' | 'nobreak' ) ) | ( ( 'not' | 'notrace' ) ) ) int alt20=2; int LA20_0 = input.LA(1); if ( ((LA20_0 >= 44 && LA20_0 <= 45)) ) { alt20=1; } else if ( ((LA20_0 >= 46 && LA20_0 <= 47)) ) { alt20=2; } else { NoViableAltException nvae = new NoViableAltException("", 20, 0, input); throw nvae; } switch (alt20) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:128:18: ( ( 'nob' | 'nobreak' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:128:18: ( ( 'nob' | 'nobreak' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:128:19: ( 'nob' | 'nobreak' ) { if ( (input.LA(1) >= 44 && input.LA(1) <= 45) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } type=CommandHandler.DebugType.BREAK; } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:129:18: ( ( 'not' | 'notrace' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:129:18: ( ( 'not' | 'notrace' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:129:19: ( 'not' | 'notrace' ) { if ( (input.LA(1) >= 46 && input.LA(1) <= 47) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } type=CommandHandler.DebugType.TRACE; } } break; } isEnabled=false; } break; } // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:130:17: ( 'x' (a0= address ) | ( ( ( ( 'r' | 'w' | 'a' ) (a1= address ) ) | ( ( 'r' | 'w' | 'a' ) ( register ) ) ) ) ) int alt25=2; int LA25_0 = input.LA(1); if ( (LA25_0==60) ) { alt25=1; } else if ( (LA25_0==21||LA25_0==50||LA25_0==58) ) { alt25=2; } else { NoViableAltException nvae = new NoViableAltException("", 25, 0, input); throw nvae; } switch (alt25) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:130:18: 'x' (a0= address ) { match(input,60,FOLLOW_60_in_debugPoint1272); // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:130:22: (a0= address ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:130:23: a0= address { pushFollow(FOLLOW_address_in_debugPoint1277); a0=address(); state._fsp--; cmd.debugPoint (type, CommandHandler.DebugPoint.INSTRUCTION, isEnabled, a0); } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:132:17: ( ( ( ( 'r' | 'w' | 'a' ) (a1= address ) ) | ( ( 'r' | 'w' | 'a' ) ( register ) ) ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:132:17: ( ( ( ( 'r' | 'w' | 'a' ) (a1= address ) ) | ( ( 'r' | 'w' | 'a' ) ( register ) ) ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:132:18: ( ( ( 'r' | 'w' | 'a' ) (a1= address ) ) | ( ( 'r' | 'w' | 'a' ) ( register ) ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:132:18: ( ( ( 'r' | 'w' | 'a' ) (a1= address ) ) | ( ( 'r' | 'w' | 'a' ) ( register ) ) ) int alt24=2; switch ( input.LA(1) ) { case 50: { int LA24_1 = input.LA(2); if ( (LA24_1==Decimal||LA24_1==Hex||LA24_1==Identifier||LA24_1==21||(LA24_1 >= 23 && LA24_1 <= 28)||LA24_1==30||(LA24_1 >= 32 && LA24_1 <= 35)||LA24_1==37||(LA24_1 >= 39 && LA24_1 <= 43)||(LA24_1 >= 48 && LA24_1 <= 60)) ) { alt24=1; } else if ( (LA24_1==Register) ) { alt24=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 24, 1, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 58: { int LA24_2 = input.LA(2); if ( (LA24_2==Decimal||LA24_2==Hex||LA24_2==Identifier||LA24_2==21||(LA24_2 >= 23 && LA24_2 <= 28)||LA24_2==30||(LA24_2 >= 32 && LA24_2 <= 35)||LA24_2==37||(LA24_2 >= 39 && LA24_2 <= 43)||(LA24_2 >= 48 && LA24_2 <= 60)) ) { alt24=1; } else if ( (LA24_2==Register) ) { alt24=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 24, 2, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 21: { int LA24_3 = input.LA(2); if ( (LA24_3==Decimal||LA24_3==Hex||LA24_3==Identifier||LA24_3==21||(LA24_3 >= 23 && LA24_3 <= 28)||LA24_3==30||(LA24_3 >= 32 && LA24_3 <= 35)||LA24_3==37||(LA24_3 >= 39 && LA24_3 <= 43)||(LA24_3 >= 48 && LA24_3 <= 60)) ) { alt24=1; } else if ( (LA24_3==Register) ) { alt24=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 24, 3, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; default: NoViableAltException nvae = new NoViableAltException("", 24, 0, input); throw nvae; } switch (alt24) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:132:19: ( ( 'r' | 'w' | 'a' ) (a1= address ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:132:19: ( ( 'r' | 'w' | 'a' ) (a1= address ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:132:20: ( 'r' | 'w' | 'a' ) (a1= address ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:132:20: ( 'r' | 'w' | 'a' ) int alt22=3; switch ( input.LA(1) ) { case 50: { alt22=1; } break; case 58: { alt22=2; } break; case 21: { alt22=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 22, 0, input); throw nvae; } switch (alt22) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:132:21: 'r' { match(input,50,FOLLOW_50_in_debugPoint1323); point=CommandHandler.DebugPoint.MEMORY_READ; } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:133:21: 'w' { match(input,58,FOLLOW_58_in_debugPoint1350); point=CommandHandler.DebugPoint.MEMORY_WRITE; } break; case 3 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:134:21: 'a' { match(input,21,FOLLOW_21_in_debugPoint1377); point=CommandHandler.DebugPoint.MEMORY_ACCESS; } break; } // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:134:76: (a1= address ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:134:77: a1= address { pushFollow(FOLLOW_address_in_debugPoint1386); a1=address(); state._fsp--; value=a1; } } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:135:19: ( ( 'r' | 'w' | 'a' ) ( register ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:135:19: ( ( 'r' | 'w' | 'a' ) ( register ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:135:20: ( 'r' | 'w' | 'a' ) ( register ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:135:20: ( 'r' | 'w' | 'a' ) int alt23=3; switch ( input.LA(1) ) { case 50: { alt23=1; } break; case 58: { alt23=2; } break; case 21: { alt23=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 23, 0, input); throw nvae; } switch (alt23) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:135:21: 'r' { match(input,50,FOLLOW_50_in_debugPoint1416); point=CommandHandler.DebugPoint.REGISTER_READ; } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:136:21: 'w' { match(input,58,FOLLOW_58_in_debugPoint1443); point=CommandHandler.DebugPoint.REGISTER_WRITE; } break; case 3 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:137:21: 'a' { match(input,21,FOLLOW_21_in_debugPoint1470); point=CommandHandler.DebugPoint.REGISTER_ACCESS; } break; } // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:137:77: ( register ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:137:78: register { pushFollow(FOLLOW_register_in_debugPoint1476); register5=register(); state._fsp--; value=register5; } } } break; } cmd.debugPoint (type, point, isEnabled, value); } } break; } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "debugPoint" // $ANTLR start "traceProg" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:139:1: traceProg : ( ( ( 't' | 'trace' ) ) | ( 'not' | 'notrace' ) ) 'prog' ; public final void traceProg() throws RecognitionException { boolean isEnabled=false; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:140:9: ( ( ( ( 't' | 'trace' ) ) | ( 'not' | 'notrace' ) ) 'prog' ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:140:17: ( ( ( 't' | 'trace' ) ) | ( 'not' | 'notrace' ) ) 'prog' { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:140:17: ( ( ( 't' | 'trace' ) ) | ( 'not' | 'notrace' ) ) int alt27=2; int LA27_0 = input.LA(1); if ( (LA27_0==55||LA27_0==57) ) { alt27=1; } else if ( ((LA27_0 >= 46 && LA27_0 <= 47)) ) { alt27=2; } else { NoViableAltException nvae = new NoViableAltException("", 27, 0, input); throw nvae; } switch (alt27) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:140:18: ( ( 't' | 'trace' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:140:18: ( ( 't' | 'trace' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:140:19: ( 't' | 'trace' ) { if ( input.LA(1)==55||input.LA(1)==57 ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } isEnabled=true; } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:140:54: ( 'not' | 'notrace' ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:140:54: ( 'not' | 'notrace' ) int alt26=2; int LA26_0 = input.LA(1); if ( (LA26_0==46) ) { alt26=1; } else if ( (LA26_0==47) ) { alt26=2; } else { NoViableAltException nvae = new NoViableAltException("", 26, 0, input); throw nvae; } switch (alt26) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:140:55: 'not' { match(input,46,FOLLOW_46_in_traceProg1548); } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:140:61: 'notrace' { match(input,47,FOLLOW_47_in_traceProg1550); isEnabled=false; } break; } } break; } match(input,48,FOLLOW_48_in_traceProg1556); cmd.traceProg (isEnabled); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "traceProg" // $ANTLR start "clear" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:142:1: clear : 'clear' ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) ; public final void clear() throws RecognitionException { CommandHandler.DebugType type=null; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:143:9: ( 'clear' ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:143:17: 'clear' ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) { match(input,25,FOLLOW_25_in_clear1611); // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:144:17: ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) int alt28=2; int LA28_0 = input.LA(1); if ( ((LA28_0 >= 23 && LA28_0 <= 24)) ) { alt28=1; } else if ( (LA28_0==55||LA28_0==57) ) { alt28=2; } else { NoViableAltException nvae = new NoViableAltException("", 28, 0, input); throw nvae; } switch (alt28) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:144:18: ( ( 'b' | 'break' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:144:18: ( ( 'b' | 'break' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:144:19: ( 'b' | 'break' ) { if ( (input.LA(1) >= 23 && input.LA(1) <= 24) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } type=CommandHandler.DebugType.BREAK; } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:145:18: ( ( 't' | 'trace' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:145:18: ( ( 't' | 'trace' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:145:19: ( 't' | 'trace' ) { if ( input.LA(1)==55||input.LA(1)==57 ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } type=CommandHandler.DebugType.TRACE; } } break; } cmd.clearDebugPoints (type); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "clear" // $ANTLR start "infoDebug" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:147:1: infoDebug : ( 'i' | 'info' ) ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) ; public final void infoDebug() throws RecognitionException { CommandHandler.DebugType type=null; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:148:9: ( ( 'i' | 'info' ) ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:148:17: ( 'i' | 'info' ) ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) { if ( input.LA(1)==35||input.LA(1)==37 ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:149:10: ( ( ( 'b' | 'break' ) ) | ( ( 't' | 'trace' ) ) ) int alt29=2; int LA29_0 = input.LA(1); if ( ((LA29_0 >= 23 && LA29_0 <= 24)) ) { alt29=1; } else if ( (LA29_0==55||LA29_0==57) ) { alt29=2; } else { NoViableAltException nvae = new NoViableAltException("", 29, 0, input); throw nvae; } switch (alt29) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:149:11: ( ( 'b' | 'break' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:149:11: ( ( 'b' | 'break' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:149:12: ( 'b' | 'break' ) { if ( (input.LA(1) >= 23 && input.LA(1) <= 24) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } type=CommandHandler.DebugType.BREAK; } } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:150:18: ( ( 't' | 'trace' ) ) { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:150:18: ( ( 't' | 'trace' ) ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:150:19: ( 't' | 'trace' ) { if ( input.LA(1)==55||input.LA(1)==57 ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } type=CommandHandler.DebugType.TRACE; } } break; } cmd.showDebugPoints (type); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "infoDebug" // $ANTLR start "help" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:152:1: help : 'help' ; public final void help() throws RecognitionException { try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:152:7: ( 'help' ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:152:9: 'help' { match(input,34,FOLLOW_34_in_help1793); cmd.help (); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "help" // $ANTLR start "quit" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:153:1: quit : 'quit' ; public final void quit() throws RecognitionException { try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:153:6: ( 'quit' ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:153:8: 'quit' { match(input,49,FOLLOW_49_in_quit1803); throw new QuitException (); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } } // $ANTLR end "quit" // $ANTLR start "address" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:154:1: address returns [int value] : (a= adrAtm |b= adrAtm '+' c= address ); public final int address() throws RecognitionException { int value = 0; int a =0; int b =0; int c =0; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:155:9: (a= adrAtm |b= adrAtm '+' c= address ) int alt30=2; switch ( input.LA(1) ) { case Hex: { int LA30_1 = input.LA(2); if ( (LA30_1==EOF||LA30_1==String||(LA30_1 >= 17 && LA30_1 <= 20)) ) { alt30=1; } else if ( (LA30_1==16) ) { int LA30_6 = input.LA(3); if ( (LA30_6==String) ) { alt30=1; } else if ( (LA30_6==Decimal||LA30_6==Hex||LA30_6==Identifier||LA30_6==21||(LA30_6 >= 23 && LA30_6 <= 28)||LA30_6==30||(LA30_6 >= 32 && LA30_6 <= 35)||LA30_6==37||(LA30_6 >= 39 && LA30_6 <= 43)||(LA30_6 >= 48 && LA30_6 <= 60)) ) { alt30=2; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 30, 6, input); throw nvae; } finally { input.rewind(nvaeMark); } } } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 30, 1, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case Decimal: { int LA30_2 = input.LA(2); if ( (LA30_2==EOF||LA30_2==String||(LA30_2 >= 17 && LA30_2 <= 20)) ) { alt30=1; } else if ( (LA30_2==16) ) { int LA30_6 = input.LA(3); if ( (LA30_6==String) ) { alt30=1; } else if ( (LA30_6==Decimal||LA30_6==Hex||LA30_6==Identifier||LA30_6==21||(LA30_6 >= 23 && LA30_6 <= 28)||LA30_6==30||(LA30_6 >= 32 && LA30_6 <= 35)||LA30_6==37||(LA30_6 >= 39 && LA30_6 <= 43)||(LA30_6 >= 48 && LA30_6 <= 60)) ) { alt30=2; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 30, 6, input); throw nvae; } finally { input.rewind(nvaeMark); } } } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 30, 2, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case Identifier: { int LA30_3 = input.LA(2); if ( (LA30_3==EOF||LA30_3==String||(LA30_3 >= 17 && LA30_3 <= 20)) ) { alt30=1; } else if ( (LA30_3==16) ) { int LA30_6 = input.LA(3); if ( (LA30_6==String) ) { alt30=1; } else if ( (LA30_6==Decimal||LA30_6==Hex||LA30_6==Identifier||LA30_6==21||(LA30_6 >= 23 && LA30_6 <= 28)||LA30_6==30||(LA30_6 >= 32 && LA30_6 <= 35)||LA30_6==37||(LA30_6 >= 39 && LA30_6 <= 43)||(LA30_6 >= 48 && LA30_6 <= 60)) ) { alt30=2; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 30, 6, input); throw nvae; } finally { input.rewind(nvaeMark); } } } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 30, 3, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 21: case 23: case 24: case 25: case 26: case 27: case 28: case 30: case 32: case 33: case 34: case 35: case 37: case 39: case 40: case 41: case 42: case 43: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: { int LA30_4 = input.LA(2); if ( (LA30_4==EOF||LA30_4==String||(LA30_4 >= 17 && LA30_4 <= 20)) ) { alt30=1; } else if ( (LA30_4==16) ) { int LA30_6 = input.LA(3); if ( (LA30_6==String) ) { alt30=1; } else if ( (LA30_6==Decimal||LA30_6==Hex||LA30_6==Identifier||LA30_6==21||(LA30_6 >= 23 && LA30_6 <= 28)||LA30_6==30||(LA30_6 >= 32 && LA30_6 <= 35)||LA30_6==37||(LA30_6 >= 39 && LA30_6 <= 43)||(LA30_6 >= 48 && LA30_6 <= 60)) ) { alt30=2; } else { int nvaeMark = input.mark(); try { for (int nvaeConsume = 0; nvaeConsume < 3 - 1; nvaeConsume++) { input.consume(); } NoViableAltException nvae = new NoViableAltException("", 30, 6, input); throw nvae; } finally { input.rewind(nvaeMark); } } } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 30, 4, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; default: NoViableAltException nvae = new NoViableAltException("", 30, 0, input); throw nvae; } switch (alt30) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:155:15: a= adrAtm { pushFollow(FOLLOW_adrAtm_in_address1831); a=adrAtm(); state._fsp--; value =a; } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:157:15: b= adrAtm '+' c= address { pushFollow(FOLLOW_adrAtm_in_address1879); b=adrAtm(); state._fsp--; match(input,16,FOLLOW_16_in_address1881); pushFollow(FOLLOW_address_in_address1885); c=address(); state._fsp--; value =b+c; } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "address" // $ANTLR start "adrAtm" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:159:1: adrAtm returns [int value] : ( number | identifier ); public final int adrAtm() throws RecognitionException { int value = 0; int number6 =0; ParserRuleReturnScope identifier7 =null; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:160:9: ( number | identifier ) int alt31=2; int LA31_0 = input.LA(1); if ( (LA31_0==Decimal||LA31_0==Hex) ) { alt31=1; } else if ( (LA31_0==Identifier||LA31_0==21||(LA31_0 >= 23 && LA31_0 <= 28)||LA31_0==30||(LA31_0 >= 32 && LA31_0 <= 35)||LA31_0==37||(LA31_0 >= 39 && LA31_0 <= 43)||(LA31_0 >= 48 && LA31_0 <= 60)) ) { alt31=2; } else { NoViableAltException nvae = new NoViableAltException("", 31, 0, input); throw nvae; } switch (alt31) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:160:17: number { pushFollow(FOLLOW_number_in_adrAtm1937); number6=number(); state._fsp--; value =number6; } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:160:50: identifier { pushFollow(FOLLOW_identifier_in_adrAtm1943); identifier7=identifier(); state._fsp--; value =cmd.getLabelValue ((identifier7!=null?input.toString(identifier7.start,identifier7.stop):null)); } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "adrAtm" // $ANTLR start "number" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:161:1: number returns [int value] : ( Hex | Decimal ); public final int number() throws RecognitionException { int value = 0; Token Hex8=null; Token Decimal9=null; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:162:2: ( Hex | Decimal ) int alt32=2; int LA32_0 = input.LA(1); if ( (LA32_0==Hex) ) { alt32=1; } else if ( (LA32_0==Decimal) ) { alt32=2; } else { NoViableAltException nvae = new NoViableAltException("", 32, 0, input); throw nvae; } switch (alt32) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:162:4: Hex { Hex8=(Token)match(input,Hex,FOLLOW_Hex_in_number1957); value =(int)(Long.parseLong((Hex8!=null?Hex8.getText():null).substring(2),16)); } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:164:3: Decimal { Decimal9=(Token)match(input,Decimal,FOLLOW_Decimal_in_number1970); value =Integer.parseInt((Decimal9!=null?Decimal9.getText():null)); } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "number" // $ANTLR start "instr" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:166:1: instr returns [String value] : string ; public final String instr() throws RecognitionException { String value = null; String string10 =null; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:167:9: ( string ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:167:11: string { pushFollow(FOLLOW_string_in_instr1995); string10=string(); state._fsp--; value =string10; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "instr" // $ANTLR start "register" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:169:1: register returns [int value] : r= Register ; public final int register() throws RecognitionException { int value = 0; Token r=null; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:170:2: (r= Register ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:170:4: r= Register { r=(Token)match(input,Register,FOLLOW_Register_in_register2035); value = cmd.getRegisterNumber ((r!=null?r.getText():null)!=null?(r!=null?r.getText():null).substring(1,(r!=null?r.getText():null).length()):null); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "register" public static class filename_return extends ParserRuleReturnScope { public String value; }; // $ANTLR start "filename" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:171:1: filename returns [String value] : (a= string |b= identifier ); public final CliParser.filename_return filename() throws RecognitionException { CliParser.filename_return retval = new CliParser.filename_return(); retval.start = input.LT(1); String a =null; ParserRuleReturnScope b =null; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:172:2: (a= string |b= identifier ) int alt33=2; int LA33_0 = input.LA(1); if ( (LA33_0==String) ) { alt33=1; } else if ( (LA33_0==Identifier||LA33_0==21||(LA33_0 >= 23 && LA33_0 <= 28)||LA33_0==30||(LA33_0 >= 32 && LA33_0 <= 35)||LA33_0==37||(LA33_0 >= 39 && LA33_0 <= 43)||(LA33_0 >= 48 && LA33_0 <= 60)) ) { alt33=2; } else { NoViableAltException nvae = new NoViableAltException("", 33, 0, input); throw nvae; } switch (alt33) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:172:4: a= string { pushFollow(FOLLOW_string_in_filename2051); a=string(); state._fsp--; retval.value =a; } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:172:34: b= identifier { pushFollow(FOLLOW_identifier_in_filename2059); b=identifier(); state._fsp--; retval.value =(b!=null?input.toString(b.start,b.stop):null); } break; } retval.stop = input.LT(-1); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "filename" public static class identifier_return extends ParserRuleReturnScope { }; // $ANTLR start "identifier" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:173:1: identifier : ( Identifier | keyword ); public final CliParser.identifier_return identifier() throws RecognitionException { CliParser.identifier_return retval = new CliParser.identifier_return(); retval.start = input.LT(1); try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:174:2: ( Identifier | keyword ) int alt34=2; int LA34_0 = input.LA(1); if ( (LA34_0==Identifier) ) { alt34=1; } else if ( (LA34_0==21||(LA34_0 >= 23 && LA34_0 <= 28)||LA34_0==30||(LA34_0 >= 32 && LA34_0 <= 35)||LA34_0==37||(LA34_0 >= 39 && LA34_0 <= 43)||(LA34_0 >= 48 && LA34_0 <= 60)) ) { alt34=2; } else { NoViableAltException nvae = new NoViableAltException("", 34, 0, input); throw nvae; } switch (alt34) { case 1 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:174:4: Identifier { match(input,Identifier,FOLLOW_Identifier_in_identifier2069); } break; case 2 : // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:174:17: keyword { pushFollow(FOLLOW_keyword_in_identifier2073); keyword(); state._fsp--; } break; } retval.stop = input.LT(-1); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "identifier" // $ANTLR start "string" // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:175:1: string returns [String value] : String ; public final String string() throws RecognitionException { String value = null; Token String11=null; try { // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:176:9: ( String ) // /Users/feeley/Documents/Work/Teaching/SimpleMachine/Grammar/Source/Cli.g:176:17: String { String11=(Token)match(input,String,FOLLOW_String_in_string2098); value =(String11!=null?String11.getText():null).substring (1, (String11!=null?String11.getText():null).length()-1); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "string" // Delegated rules public static final BitSet FOLLOW_load_in_command41 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_test_in_command45 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_run_in_command49 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_step_in_command53 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_where_in_command57 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_gotoPC_in_command61 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_examine_in_command65 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_assertCmd_in_command69 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_info_in_command73 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_set_in_command77 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_debug_in_command81 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_infoDebug_in_command85 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_quit_in_command89 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_help_in_command93 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_EOF_in_command96 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_load174 = new BitSet(new long[]{0x1FFF0FAF5FA04800L}); public static final BitSet FOLLOW_filename_in_load182 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_56_in_test205 = new BitSet(new long[]{0x1FFF0FAF5FA04800L}); public static final BitSet FOLLOW_filename_in_test208 = new BitSet(new long[]{0x1FFF0FAF5FA00802L}); public static final BitSet FOLLOW_identifier_in_test213 = new BitSet(new long[]{0x1FFF0FAF5FA00802L}); public static final BitSet FOLLOW_identifier_in_test217 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_run253 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_step270 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_where290 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_gotoPC308 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_gotoPC316 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_28_in_examine354 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_30_in_examine356 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_set_in_examine359 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_examine392 = new BitSet(new long[]{0x0000000000040002L}); public static final BitSet FOLLOW_18_in_examine395 = new BitSet(new long[]{0x0000000000000240L}); public static final BitSet FOLLOW_number_in_examine399 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_examine430 = new BitSet(new long[]{0x0000000000002000L}); public static final BitSet FOLLOW_register_in_examine456 = new BitSet(new long[]{0x0000000000040002L}); public static final BitSet FOLLOW_18_in_examine459 = new BitSet(new long[]{0x0000000000000240L}); public static final BitSet FOLLOW_number_in_examine463 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_assertCmd482 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_assertCmd492 = new BitSet(new long[]{0x0000000000100000L}); public static final BitSet FOLLOW_20_in_assertCmd494 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_assertCmd498 = new BitSet(new long[]{0x0000000000004002L}); public static final BitSet FOLLOW_string_in_assertCmd502 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_assertCmd527 = new BitSet(new long[]{0x0000000000002000L}); public static final BitSet FOLLOW_register_in_assertCmd535 = new BitSet(new long[]{0x0000000000100000L}); public static final BitSet FOLLOW_20_in_assertCmd537 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_assertCmd541 = new BitSet(new long[]{0x0000000000004002L}); public static final BitSet FOLLOW_string_in_assertCmd545 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_assertCmd570 = new BitSet(new long[]{0x0000000000004000L}); public static final BitSet FOLLOW_string_in_assertCmd580 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_35_in_info615 = new BitSet(new long[]{0x0000088008000000L}); public static final BitSet FOLLOW_37_in_info617 = new BitSet(new long[]{0x0000088008000000L}); public static final BitSet FOLLOW_set_in_info620 = new BitSet(new long[]{0x0000088008000000L}); public static final BitSet FOLLOW_43_in_info651 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_39_in_info703 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_27_in_info754 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_info804 = new BitSet(new long[]{0x0008000004000000L}); public static final BitSet FOLLOW_51_in_info830 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_26_in_info857 = new BitSet(new long[]{0x1FFF0FAF5FA00802L}); public static final BitSet FOLLOW_identifier_in_info861 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_register_in_set875 = new BitSet(new long[]{0x0000000000080000L}); public static final BitSet FOLLOW_19_in_set877 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_set881 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_42_in_set895 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_set899 = new BitSet(new long[]{0x0000000000080000L}); public static final BitSet FOLLOW_19_in_set901 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_set905 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_35_in_set920 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_set924 = new BitSet(new long[]{0x00000000000B0000L}); public static final BitSet FOLLOW_19_in_set948 = new BitSet(new long[]{0x0000000000004000L}); public static final BitSet FOLLOW_instr_in_set952 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_16_in_set1003 = new BitSet(new long[]{0x0000000000004000L}); public static final BitSet FOLLOW_instr_in_set1007 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_17_in_set1058 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_debugPoint_in_debug1103 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_traceProg_in_debug1107 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_clear_in_debug1111 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_debugPoint1145 = new BitSet(new long[]{0x1404000000200000L}); public static final BitSet FOLLOW_set_in_debugPoint1177 = new BitSet(new long[]{0x1404000000200000L}); public static final BitSet FOLLOW_set_in_debugPoint1213 = new BitSet(new long[]{0x1404000000200000L}); public static final BitSet FOLLOW_set_in_debugPoint1242 = new BitSet(new long[]{0x1404000000200000L}); public static final BitSet FOLLOW_60_in_debugPoint1272 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_debugPoint1277 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_50_in_debugPoint1323 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_58_in_debugPoint1350 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_21_in_debugPoint1377 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_debugPoint1386 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_50_in_debugPoint1416 = new BitSet(new long[]{0x0000000000002000L}); public static final BitSet FOLLOW_58_in_debugPoint1443 = new BitSet(new long[]{0x0000000000002000L}); public static final BitSet FOLLOW_21_in_debugPoint1470 = new BitSet(new long[]{0x0000000000002000L}); public static final BitSet FOLLOW_register_in_debugPoint1476 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_traceProg1536 = new BitSet(new long[]{0x0001000000000000L}); public static final BitSet FOLLOW_46_in_traceProg1548 = new BitSet(new long[]{0x0001000000000000L}); public static final BitSet FOLLOW_47_in_traceProg1550 = new BitSet(new long[]{0x0001000000000000L}); public static final BitSet FOLLOW_48_in_traceProg1556 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_25_in_clear1611 = new BitSet(new long[]{0x0280000001800000L}); public static final BitSet FOLLOW_set_in_clear1632 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_clear1660 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_infoDebug1713 = new BitSet(new long[]{0x0280000001800000L}); public static final BitSet FOLLOW_set_in_infoDebug1730 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_infoDebug1759 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_34_in_help1793 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_49_in_quit1803 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_adrAtm_in_address1831 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_adrAtm_in_address1879 = new BitSet(new long[]{0x0000000000010000L}); public static final BitSet FOLLOW_16_in_address1881 = new BitSet(new long[]{0x1FFF0FAF5FA00A40L}); public static final BitSet FOLLOW_address_in_address1885 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_number_in_adrAtm1937 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_identifier_in_adrAtm1943 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_Hex_in_number1957 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_Decimal_in_number1970 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_string_in_instr1995 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_Register_in_register2035 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_string_in_filename2051 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_identifier_in_filename2059 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_Identifier_in_identifier2069 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_keyword_in_identifier2073 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_String_in_string2098 = new BitSet(new long[]{0x0000000000000002L}); }
30.310768
340
0.606221
ccf3c0790f85763729d2a9fc561084950fe6076d
7,748
/* * Copyright (c) 2019. http://devonline.academy * * 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.revenat.javamm.compiler.component.impl; import com.revenat.javamm.code.fragment.Lexeme; import com.revenat.javamm.code.fragment.Operator; import com.revenat.javamm.code.fragment.SourceLine; import com.revenat.javamm.compiler.component.OperatorPrecedenceResolver; import com.revenat.javamm.compiler.component.error.JavammLineSyntaxError; import java.util.List; import static com.revenat.javamm.code.util.LexemeUtils.isBinaryAssignmentOperator; import static com.revenat.javamm.code.util.LexemeUtils.isBinaryOperator; import static com.revenat.javamm.code.util.LexemeUtils.isClosingParenthesis; import static com.revenat.javamm.code.util.LexemeUtils.isExpression; import static com.revenat.javamm.code.util.LexemeUtils.isOpeningParenthesis; import static com.revenat.javamm.code.util.LexemeUtils.isOperator; import static com.revenat.javamm.code.util.LexemeUtils.isUnaryOperator; import static com.revenat.javamm.compiler.component.impl.util.SyntaxValidationUtils.requireVariableExpression; /** * Validates that specified lexemes are in valid order * * @author Vitaliy Dragun */ final class LexemesOrderValidator { private final OperatorPrecedenceResolver operatorPrecedenceResolver; private final List<Lexeme> lexemes; private final SourceLine sourceLine; private Lexeme expressionWithoutBinary; private Lexeme lastCheckedExpression; private Lexeme lastValidatedLexeme; private LexemesOrderValidator(final OperatorPrecedenceResolver operatorPrecedenceResolver, final List<Lexeme> lexemes, final SourceLine sourceLine) { this.operatorPrecedenceResolver = operatorPrecedenceResolver; this.lexemes = lexemes; this.sourceLine = sourceLine; this.expressionWithoutBinary = null; this.lastCheckedExpression = null; this.lastValidatedLexeme = null; } static LexemesOrderValidator validator(final OperatorPrecedenceResolver operatorPrecedenceResolver, final List<Lexeme> lexemes, final SourceLine sourceLine) { return new LexemesOrderValidator(operatorPrecedenceResolver, lexemes, sourceLine); } public void validate() { validateFirstLexemeNotBinaryOperator(); validateLastLexemeNotOperator(); validateLexemesOrder(); } private void validateFirstLexemeNotBinaryOperator() { final Lexeme firstLexeme = lexemes.get(0); if (isBinaryOperator(firstLexeme)) { throw syntaxError("Expression can not start with binary operator: '%s'", firstLexeme); } } private void validateLastLexemeNotOperator() { final Lexeme lastLexeme = lexemes.get(lexemes.size() - 1); if (isOperator(lastLexeme)) { final Operator operator = (Operator) lastLexeme; throw syntaxError("Expression can not end with %s operator: '%s'", operator.getType(), operator); } } private void validateLexemesOrder() { final Lexeme firstLexeme = lexemes.get(0); expressionWithoutBinary = isExpression(firstLexeme) ? firstLexeme : expressionWithoutBinary; for (int i = 0; i < lexemes.size() - 1; i++) { final Lexeme current = lexemes.get(i); final Lexeme next = lexemes.get(i + 1); assertNoExpressionsWithoutBinaryInBetween(next); assertNoSequentialBinaryOperators(current, next); assertNoOperatorWithoutExpression(current, next); assertCorrectlyPlacedParentheses(current, next); requireVariableExpressionForBinaryAssignmentOperator(current, next); lastValidatedLexeme = current; } } private void requireVariableExpressionForBinaryAssignmentOperator(final Lexeme current, final Lexeme next) { lastCheckedExpression = isExpression(current) ? current : lastCheckedExpression; if (isBinaryAssignmentOperator(next) && isPreviousLexemeNotOperatorWithHigherPrecedence(next)) { requireVariableExpression(lastCheckedExpression, (Operator) next, sourceLine); } else if (isBinaryAssignmentOperator(next)) { throw syntaxError("A variable expression is expected for binary operator: '%s'", next); } } private boolean isPreviousLexemeNotOperatorWithHigherPrecedence(final Lexeme operator) { return !isPreviousLexemeIsOperatorWithHigherPrecedence(operator); } private boolean isPreviousLexemeIsOperatorWithHigherPrecedence(final Lexeme operator) { return lastValidatedLexeme != null && isOperator(lastValidatedLexeme) && operatorPrecedenceResolver.hasLowerPrecedence((Operator) operator, (Operator) lastValidatedLexeme); } private void assertNoExpressionsWithoutBinaryInBetween(final Lexeme lexemeToCheck) { if (isExpression(lexemeToCheck) && expressionWithoutBinary != null) { throw syntaxError("A binary operator is expected between expressions: '%s' and '%s'", expressionWithoutBinary, lexemeToCheck); } else if (isExpression(lexemeToCheck)) { expressionWithoutBinary = lexemeToCheck; } else if (isBinaryOperator(lexemeToCheck)) { expressionWithoutBinary = null; } } private void assertCorrectlyPlacedParentheses(final Lexeme current, final Lexeme next) { if (isOpeningParenthesis(current) && isClosingParenthesis(next)) { throw syntaxError("Parentheses are incorrectly placed"); } if (isClosingParenthesis(current) && isOpeningParenthesis(next)) { throw syntaxError("Parentheses are incorrectly placed"); } } private void assertNoOperatorWithoutExpression(final Lexeme current, final Lexeme next) { if (isOpeningParenthesis(current) && isBinaryOperator(next)) { throw syntaxError("An expression is expected for binary operator: '%s'", next); } if (isUnaryOperator(current) && isBinaryOperator(next)) { throw syntaxError("An expression is expected for binary operator: '%s'", next); } if (isOperator(current) && isClosingParenthesis(next)) { throw syntaxError("An expression is expected for %s operator: '%s'", ((Operator) current).getType(), current); } } private void assertNoSequentialBinaryOperators(final Lexeme current, final Lexeme next) { if (isBinaryOperator(current) && isBinaryOperator(next)) { throw syntaxError("An expression is expected between binary operators: '%s' and '%s'", current, next); } } private JavammLineSyntaxError syntaxError(final String msgTemplate, final Object... args) { return new JavammLineSyntaxError(sourceLine, msgTemplate, args); } }
42.338798
112
0.684951
4c06fb2629a1e3b530ca6282a3083caa339ab810
805
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.hal; import org.junit.Test; public class MatchInfoDataTest { @Test public void matchInfoDataDoesNotThrow() { HAL.initialize(500, 0); MatchInfoData data = new MatchInfoData(); HAL.getMatchInfo(data); // Nothing we can assert, so just make sure it didn't throw. } }
38.333333
80
0.489441
5b1fdf20233315005531882ec7193a9edae78f69
619
/* * This code is free of charge and may be edited, distributed and executed in any form but it must be marked as being developed by BABautzen_WI16. * This code is developed to not do any harm but the author is not responsible for any action done to the executing system. */ package org.wi16.counter; import org.wi16.gui.Hauptfenster; /** * * @author Tim Trense */ public class Haupt { public static void main(final String... args) { final Counter counter = new Counter(30); final Hauptfenster hf = new Hauptfenster(counter); hf.setVisible(true); } }
28.136364
147
0.672052
b406e4b931feba1caf08e3750e3c44403f185d79
506
package com.yisu.starter.sample.controller; import com.yisu.starter.sample.autoconfigure.service.SampleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @Autowired private SampleService sampleService; @GetMapping("/test") public String test(){ return sampleService.sayHello(); } }
24.095238
67
0.780632
a67600227df80a0e8209c28f52ea6b5ee4a3c9b3
2,054
/* * Copyright 2014-2016 Media for Mobile * * 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.m4m.domain; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MultipleMediaSourceTest extends TestBase { @Test public void getSegmentsDurationForTwoFiles() throws RuntimeException { MediaSource trackWithAudioDuration100 = create.mediaSource().with( create.audioFormat().withDuration(100).construct()) .construct(); MediaSource trackWithAudioDuration200 = create.mediaSource().with( create.audioFormat().withDuration(200).construct()) .construct(); MultipleMediaSource multipleMediaSource=create.multipleMediaSource() .with(trackWithAudioDuration100) .with(trackWithAudioDuration200) .construct(); assertEquals(300, multipleMediaSource.getSegmentsDurationInMicroSec()); } @Test(expected = RuntimeException.class) public void add_FilesWithoutAudioTrackIfFirstTrackHasAudioTrack_ThrowsRuntimeException() throws RuntimeException { MediaSource firstTrackWithVideoAndAudio = create.mediaSource() .withVideoTrack(0) .with(create.audioFormat().withBitRate(100).construct()).construct(); MediaSource trackWithVideoOnly = create.mediaSource().withVideoTrack(0).construct(); create.multipleMediaSource() .with(firstTrackWithVideoAndAudio) .with(trackWithVideoOnly) .construct(); } }
38.037037
118
0.712269
5223b87f39798bd978f032ca433276f328cec770
18,972
/// * // * Copyright (c) 2017. California Community Colleges Technology Center // * // * 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.pesc.cds.web; // // import com.google.common.base.Preconditions; // import com.google.common.collect.Lists; // import com.google.common.collect.Maps; // import io.swagger.annotations.Api; // import org.apache.commons.lang3.StringUtils; // import org.apache.commons.logging.Log; // import org.apache.commons.logging.LogFactory; // import org.json.JSONArray; // import org.json.JSONException; // import org.json.JSONObject; // import org.pesc.cds.domain.Transaction; // import org.pesc.cds.model.*; // import org.pesc.cds.repository.TransactionService; // import org.pesc.cds.service.OrganizationService; // import org.pesc.cds.service.PKIService; // import org.pesc.cds.utils.ErrorUtils; // import org.pesc.sdk.core.coremain.v1_14.DocumentTypeCodeType; // import org.pesc.sdk.core.coremain.v1_14.StateProvinceCodeType; // import org.pesc.sdk.core.coremain.v1_14.TransmissionTypeType; // import org.pesc.sdk.message.documentinfo.v1_0.DocumentTypeCode; // import org.pesc.sdk.message.transcriptrequest.v1_4.TranscriptRequest; // import org.pesc.sdk.sector.academicrecord.v1_9.PhoneType; // import org.pesc.sdk.sector.academicrecord.v1_9.ReleaseAuthorizedMethodType; // import org.springframework.beans.factory.annotation.Autowired; // import org.springframework.beans.factory.annotation.Qualifier; // import org.springframework.beans.factory.annotation.Value; // import org.springframework.core.io.ByteArrayResource; // import org.springframework.core.io.FileSystemResource; // import org.springframework.http.HttpMethod; // import org.springframework.http.HttpStatus; // import org.springframework.http.ResponseEntity; // import org.springframework.oxm.Marshaller; // import org.springframework.security.oauth2.client.OAuth2RestTemplate; // import org.springframework.util.LinkedMultiValueMap; // import org.springframework.web.bind.annotation.*; // import org.springframework.web.client.ResourceAccessException; // // import javax.annotation.Resource; // import javax.servlet.http.HttpServletResponse; // import javax.xml.transform.stream.StreamResult; // import java.io.File; // import java.io.FileInputStream; // import java.io.IOException; // import java.sql.Timestamp; // import java.text.DateFormat; // import java.text.SimpleDateFormat; // import java.util.*; // /// ** // * Created by james on 9/12/16. // */ // @RestController // @RequestMapping(value="api/v1/transcript-requests") // @Api(tags = "Transcript Requests", description = "Manage transcript /// requests.") // public class TranscriptRequestController { // // private static final Log log = /// LogFactory.getLog(TranscriptRequestController.class); // // @Autowired // private PKIService pkiService; // // @Resource(name="transcriptRequestMarshaller") // private Marshaller transcriptRequestMarshaller; // // @Resource(name="documentInfoMarshaller") // private Marshaller documentInfoMarshaller; // // @Value("${networkServer.outbox.path}") // private String localServerOutboxPath; // // @Value("${networkServer.id}") // private String localServerId; // // @Value("${networkServer.webServiceURL}") // private String localServerWebServiceURL; // // @Autowired // private TransactionService transactionService; // // // @Autowired // private OrganizationService organizationService; // // @Autowired // @Qualifier("myRestTemplate") // private OAuth2RestTemplate restTemplate; // // private String getEmailAddress(final JSONObject edexOrganization) throws /// JSONException { // JSONArray contacts = edexOrganization.getJSONArray("contacts"); // if(contacts.length()>0){ // JSONObject contact = contacts.getJSONObject(0); // return contact.getString("email"); // } // // return null; // } // // /** // * The source school indicates the school that is requesting the transcript. // * // * @param builder // * @param schoolDTO // * @throws JSONException // */ // private void constructTranscriptRequestSource(final TranscriptRequestBuilder /// builder, final RequestingSchoolDTO schoolDTO, final JSONObject /// edexOrganization) // throws JSONException { // // Map<SchoolCodeType, String> schoolCodes = Maps.newHashMap(); // // SchoolCodeType srcSchoolCodeType = /// SchoolCodeType.valueOf(schoolDTO.getSchoolCodeType()); // schoolCodes.put(srcSchoolCodeType, schoolDTO.getSchoolCode()); // // // List<String> organizationNames = /// Arrays.asList(edexOrganization.getString("name")); // List<String> addresses = Arrays.asList(edexOrganization.getString("street")); // String city = edexOrganization.getString("city"); // StateProvinceCodeType stateProvinceCode = /// StateProvinceCodeType.valueOf(edexOrganization.getString("state")); // String postalCode = edexOrganization.getString("zip"); // org.pesc.sdk.sector.academicrecord.v1_9.ObjectFactory /// academicRecordObjectFactory = new /// org.pesc.sdk.sector.academicrecord.v1_9.ObjectFactory(); // PhoneType phone = createPhone(edexOrganization.optString("telephone", "")); // // builder.sourceSchoolCodes(schoolCodes) // .sendersEmail(getEmailAddress(edexOrganization)) // .sendersPhone(phone) // .sourceOrganizationNames(organizationNames) // .sourceOrganizationAddressLines(addresses) // .sourceOrganizationCity(city) // .sourceOrganizationStateProvinceCode(stateProvinceCode) // .sourceOrganizationPostalCode(postalCode); // // // } // // // private PhoneType createPhone(String phoneNumber){ // org.pesc.sdk.sector.academicrecord.v1_9.ObjectFactory /// academicRecordObjectFactory = new /// org.pesc.sdk.sector.academicrecord.v1_9.ObjectFactory(); // PhoneType phone = academicRecordObjectFactory.createPhoneType();//Provided by /// Source Institution - optional // if(StringUtils.isNotBlank(phoneNumber)) { // int extensionIndex = StringUtils.indexOfIgnoreCase(phoneNumber, "x");//has /// extension? // if(extensionIndex!=-1) { // if((phoneNumber.length()-1)>extensionIndex) { // String extension = phoneNumber.substring(extensionIndex + 1); // phone.setPhoneNumberExtension(extension); // } // phoneNumber = phoneNumber.substring(0, extensionIndex - 1); // } // phoneNumber = phoneNumber.replaceAll("\\D", ""); // if(phoneNumber.length()>7){ // String basePhoneNumber = phoneNumber.substring(phoneNumber.length()-7); // phone.setPhoneNumber(basePhoneNumber); // String areaCode = /// phoneNumber.length()>10?phoneNumber.substring(phoneNumber.length()-10, /// phoneNumber.length()-7):phoneNumber.substring(0, phoneNumber.length()-7); // phone.setAreaCityCode(areaCode); // if(phoneNumber.length()>10){ // String countryCode = phoneNumber.substring(0, phoneNumber.length()-10); // phone.setCountryPrefixCode(countryCode); // } // } // } // return phone; // } // // private TranscriptRequestBuilder constructStudent(final /// TranscriptRequestBuilder builder, final TranscriptRequestDTO /// transcriptRequestDTO, final RecordHolderDTO schoolDTO, final JSONObject /// edexOrganization) { // Map<SchoolCodeType, String> currentlyAttendedSchoolCodes = Maps.newHashMap(); // // // Boolean trStudentRelease = transcriptRequestDTO.isStudentRelease(); // String trStudentReleasedMethod = /// transcriptRequestDTO.getStudentReleasedMethod(); // String studentBirthDate = transcriptRequestDTO.getStudentBirthDate(); // String trStudentFirstName = transcriptRequestDTO.getStudentFirstName(); // String trStudentLastName = transcriptRequestDTO.getStudentLastName() ; // String trStudentMiddleName = transcriptRequestDTO.getStudentMiddleName(); // String trStudentEmail = transcriptRequestDTO.getStudentEmail(); // String trStudentPartialSsn = transcriptRequestDTO.getStudentPartialSSN(); // // DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); // Date trStudentDOB = null; // try { // if (studentBirthDate != null) { // trStudentDOB = dateFormat.parse(studentBirthDate); // } // } catch (Exception e) { // log.error(e); // // } // // SchoolCodeType srcSchoolCodeType = /// SchoolCodeType.valueOf(schoolDTO.getSchoolCodeType()); // if (schoolDTO.isStudentCurrentlyEnrolled() == true) { // currentlyAttendedSchoolCodes.put(srcSchoolCodeType, /// schoolDTO.getSchoolCode()); // } // // builder.studentRelease(trStudentRelease) // .studentReleasedMethod(ReleaseAuthorizedMethodType.valueOf(trStudentReleasedMethod)) // .studentBirthDate(trStudentDOB) // .studentFirstName(trStudentFirstName) // .studentLastName(trStudentLastName) // .studentEmail(trStudentEmail) // .studentPartialSsn(trStudentPartialSsn) // .studentSchoolCodes(currentlyAttendedSchoolCodes) // .studentSchoolName(edexOrganization.optString("name", "")) // .studentCurrentlyEnrolled(schoolDTO.isStudentCurrentlyEnrolled()); // // if (StringUtils.isNotEmpty(trStudentMiddleName)) { // builder.studentMiddleNames(Arrays.asList(trStudentMiddleName)); // } // // return builder; // } // // /** // * The destination is the record holder's school. // * // * @param builder // * @param schoolDTO // * @throws JSONException // */ // private void constructTranscriptRequestDestination(final /// TranscriptRequestBuilder builder, final RecordHolderDTO schoolDTO, final /// JSONObject edexOrganization) // throws JSONException { // // Map<SchoolCodeType, String> schoolCodes = Maps.newHashMap(); // // SchoolCodeType srcSchoolCodeType = /// SchoolCodeType.valueOf(schoolDTO.getSchoolCodeType()); // schoolCodes.put(srcSchoolCodeType, schoolDTO.getSchoolCode()); // // // List<String> organizationNames = /// Arrays.asList(edexOrganization.getString("name")); // List<String> addresses = Arrays.asList(edexOrganization.getString("street")); // String city = edexOrganization.getString("city"); // StateProvinceCodeType stateProvinceCode = /// StateProvinceCodeType.valueOf(edexOrganization.getString("state")); // String postalCode = edexOrganization.getString("zip"); // PhoneType phone = createPhone(edexOrganization.optString("telephone", "")); // // builder.destinationSchoolCodes(schoolCodes) // .receiversEmail(getEmailAddress(edexOrganization)) // .receiversPhone(phone) // .destinationOrganizationNames(organizationNames) // .destinationOrganizationAddressLines(addresses) // .destinationCity(city) // .destinationOrganizationStateProvinceCode(stateProvinceCode) // .destinationOrganizationPostalCode(postalCode); // // } // // private JSONObject getEDExOrg(final SchoolDTO schoolDTO){ // //get the EDExchange organization object from the directory server... // Preconditions.checkArgument(StringUtils.isNotBlank(schoolDTO.getSchoolCode()), /// "School Code is required"); // Preconditions.checkArgument(StringUtils.isNotBlank(schoolDTO.getSchoolCodeType()), /// "School Code Type is required"); // // if (schoolDTO.getSchoolCodeType().equals(SchoolCodeType.EDEXCHANGE.name())) { // return /// organizationService.getOrganization(Integer.valueOf(schoolDTO.getSchoolCode())); // } // return organizationService.getOrganization(schoolDTO.getSchoolCode(), /// schoolDTO.getSchoolCodeType()); // // } // // @RequestMapping(method= RequestMethod.POST) // @ResponseBody // public List<Transaction> transcriptRequest( @RequestBody final /// TranscriptRequestDTO transcriptRequestDTO // ) throws JSONException { // // Preconditions.checkArgument(transcriptRequestDTO.getDestinationInstitutions().size() /// == 1) ; // Preconditions.checkArgument(transcriptRequestDTO.getSourceInstitutions().size() /// == 1); // // String fileFormat = DocumentFormat.PESCXML.getFormatName(); // String documentType = DocumentType.TRANSCRIPT_REQUEST.getDocumentName(); // String department = "Administration"; // // List<Transaction> transactions = new ArrayList<Transaction>(); // // //The receiving institution information in terms of the transcript. For the /// transcript request, // //this will be the opposite---it will be the sending/originating institution. // RequestingSchoolDTO transcriptRequestor = /// transcriptRequestDTO.getDestinationInstitutions().get(0); // RecordHolderDTO recordHolderInstitution = /// transcriptRequestDTO.getSourceInstitutions().get(0); // // List<String> transcriptRequestRecordHolderNames = /// Lists.newArrayList();//Provided by Source Institution // // //Create a transaction to track the transcript request. // // Transaction tx = new Transaction(); // // //Get the endpoint for the record holder. This is where the transcript /// request will be sent. // String endpointURI = /// organizationService.getEndpointURIForSchool(recordHolderInstitution.getSchoolCode(), /// recordHolderInstitution.getSchoolCodeType(), fileFormat, // documentType, department, tx, transcriptRequestRecordHolderNames, /// transcriptRequestDTO.getMode()); // // // if (endpointURI == null) { // String error = ErrorUtils.getNoEndpointFoundMessage(tx.getRecipientId(), // fileFormat, // documentType, // department); // log.warn(error); // throw new IllegalArgumentException(error); // } // // JSONObject requestorOrg = getEDExOrg(transcriptRequestor); // JSONObject recordHolderOrg = getEDExOrg(recordHolderInstitution); // //Create // File outboxDirectory = new File(localServerOutboxPath); // outboxDirectory.mkdirs(); // UUID uuid = UUID.randomUUID(); // String ext = "xml"; // String trFileName = uuid.toString()+"_document."+ext; // File requestFile = new File(outboxDirectory, trFileName); // // // tx.setSenderId(requestorOrg.getInt("id")); // tx.setRecipientId(recordHolderOrg.getInt("id")); // tx.setFileFormat(fileFormat); // tx.setFilePath(requestFile.getAbsolutePath()); // tx.setDocumentType(documentType); // tx.setDepartment(department); // tx.setAckURL(localServerWebServiceURL); // tx.setSignerId(Integer.valueOf(localServerId)); // tx.setOperation("SEND"); // tx.setOccurredAt(new Timestamp(Calendar.getInstance().getTimeInMillis())); // // tx = transactionService.create(tx); // String trDocumentID = tx.getId() + ""; // DocumentTypeCodeType trDocumentTypeCode = /// DocumentTypeCodeType.STUDENT_REQUEST; // TransmissionTypeType trTransmissionType = TransmissionTypeType.ORIGINAL; // String trRequestTrackingID = tx.getId() + ""; // // // //destination // // //trDestinationSchoolCodes.put(SchoolCodeType.MutuallyDefined, /// String.valueOf(tx.getSenderId())); // //document // DocumentTypeCode trDocumentType = DocumentTypeCode.TRANSCRIPT; // // //student // // TranscriptRequestBuilder builder = new TranscriptRequestBuilder() // .documentInfoMarshaller(documentInfoMarshaller) // .documentID(trDocumentID) // .documentTypeCode(trDocumentTypeCode) // .documentFormat(transcriptRequestDTO.getFileFormat()) // .transmissionType(trTransmissionType) // .requestTrackingID(trRequestTrackingID) // .parchmentDocumentTypeCode(trDocumentType) // .fileName(trFileName); // // // constructStudent(builder,transcriptRequestDTO, /// recordHolderInstitution,recordHolderOrg); // // constructTranscriptRequestDestination(builder, recordHolderInstitution, /// recordHolderOrg); // // constructTranscriptRequestSource(builder,transcriptRequestor, requestorOrg); // // TranscriptRequest transcriptRequest = builder.build(); // // try { // if(!requestFile.createNewFile()){ // String message = tx.getError()!=null?tx.getError():""; // tx.setError(message + ". " + String.format("file %s already exists", /// trFileName)); // }else { // //File gets saved to file system here. // transcriptRequestMarshaller.marshal(transcriptRequest, new /// StreamResult(requestFile)); // } // } // catch (Exception e) { // log.error("Failed to save transcript request document.", e); // // tx.setError(e.getLocalizedMessage()); // tx.setStatus(TransactionStatus.FAILURE); // } // // tx.setFileSize(requestFile.length()); // // transactionService.update(tx); // // transactions.add(tx); // // try { // if (StringUtils.isEmpty(tx.getError())) { // sendDocument(requestFile, endpointURI, tx, fileFormat,documentType, /// department); // } // } catch (Exception e) { // // tx.setError(e.getMessage()); // transactionService.update(tx); // // log.error("Failed to send transcript request.", e); // // throw new IllegalArgumentException(e.getMessage()); // } // // //Now send the transcript request document to the destination school // // // // // return transactions; // } // // // private void sendDocument(final File outboxFile, final String endpointURI, /// final Transaction tx, final String fileFormat, final String documentType, /// final String department) throws IOException { // // byte[] fileSignature = pkiService.createDigitalSignature(new /// FileInputStream(outboxFile), pkiService.getSigningKeys().getPrivate()); // try { // // LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); // map.add("recipient_id", tx.getRecipientId()); // map.add("sender_id", tx.getSenderId()); // map.add("signer_id", localServerId); // map.add("file_format", fileFormat); // map.add("document_type", documentType); // map.add("department", department); // map.add("transaction_id", tx.getId()); // map.add("ack_url", localServerWebServiceURL); // map.add("file", new FileSystemResource(outboxFile)); // map.add("signature", new ByteArrayResource(fileSignature){ // @Override // public String getFilename(){ // return "signature.dat"; // } // }); // // // org.springframework.http.HttpHeaders headers = new /// org.springframework.http.HttpHeaders(); // headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA); // // // ResponseEntity<String> response = restTemplate.exchange // (endpointURI, HttpMethod.POST, new /// org.springframework.http.HttpEntity<Object>(map, headers), String.class); // // // if (response.getStatusCode() != HttpStatus.OK) { // throw new IllegalArgumentException("Failed to send document. Reason: " + /// response.getStatusCode().getReasonPhrase()); // } // // log.info(response.getStatusCode().getReasonPhrase()); // // // } catch(ResourceAccessException e) { // // //Force the OAuth client to retrieve the token again whenever it is used /// again. // // restTemplate.getOAuth2ClientContext().setAccessToken(null); // // tx.setError(e.getMessage()); // transactionService.update(tx); // // log.error(e); // throw new IllegalArgumentException(e); // // } catch (Exception e) { // // tx.setError(e.getMessage()); // transactionService.update(tx); // // log.error(e); // // throw new IllegalArgumentException(e); // // } // // } // // @ExceptionHandler // void handleIllegalArgumentException(final IllegalArgumentException e, final /// HttpServletResponse response) throws IOException { // response.sendError(HttpStatus.BAD_REQUEST.value()); // } // // // }
35.133333
88
0.752952
236267537437242afc984f915bb0c014e5f640f1
1,742
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.file.config; import org.w3c.dom.Element; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.integration.config.xml.AbstractOutboundChannelAdapterParser; /** * Parser for the &lt;outbound-channel-adapter/&gt; element of the 'file' * namespace. * * @author Mark Fisher * @author Iwein Fuld * @author Oleg Zhurakousky * @author Artem Bilan */ public class FileOutboundChannelAdapterParser extends AbstractOutboundChannelAdapterParser { @Override protected AbstractBeanDefinition parseConsumer(Element element, ParserContext parserContext) { BeanDefinitionBuilder handlerBuilder = FileWritingMessageHandlerBeanDefinitionBuilder.configure(element, false, parserContext); return handlerBuilder.getBeanDefinition(); } @Override protected boolean isUsingReplyProducer() { // cannot be automatically determined by superclass because we are using a factory bean. return true; } }
34.84
129
0.789897
123a9ac67264ee0f854cda468aa7896dbd7ed5cd
987
/* * MIT Licence * Copyright (c) 2021 Simon Frankenberger * * Please see LICENCE.md for complete licence text. */ package eu.fraho.spring.securityJwt.internal; import eu.fraho.spring.securityJwt.base.service.RefreshTokenStore; import eu.fraho.spring.securityJwt.base.ut.service.AbstractJwtTokenServiceWithRefreshTest; import eu.fraho.spring.securityJwt.internal.service.InternalTokenStore; public class AbstractJwtServiceRefreshInternalTest extends AbstractJwtTokenServiceWithRefreshTest { private final InternalTokenStore refreshTokenStore; public AbstractJwtServiceRefreshInternalTest() throws Exception { refreshTokenStore = new InternalTokenStore(); refreshTokenStore.setRefreshProperties(getRefreshProperties()); refreshTokenStore.setUserDetailsService(getUserdetailsService()); refreshTokenStore.afterPropertiesSet(); } @Override protected RefreshTokenStore getRefreshStore() { return refreshTokenStore; } }
35.25
99
0.7923
14a2b3aaf1716d3c5a61b84caa7e56813718b546
1,060
package com.chakans.elasticsearch.jamo.plugin; import java.util.HashMap; import java.util.Map; import org.elasticsearch.index.analysis.TokenFilterFactory; import org.elasticsearch.indices.analysis.AnalysisModule; import org.elasticsearch.indices.analysis.AnalysisModule.AnalysisProvider; import org.elasticsearch.plugins.AnalysisPlugin; import org.elasticsearch.plugins.Plugin; import com.chakans.elasticsearch.jamo.index.analysis.HangulChosungFilterFactory; import com.chakans.elasticsearch.jamo.index.analysis.HangulJamoTokenFilterFactory; /** * Created by chakannom on 17. 6. 30. * Modified by chakannom on 18. 8. 14. */ public class HangulJamoPlugin extends Plugin implements AnalysisPlugin { @Override public Map<String, AnalysisProvider<TokenFilterFactory>> getTokenFilters() { Map<String, AnalysisModule.AnalysisProvider<TokenFilterFactory>> extra = new HashMap<>(); extra.put("hangul_jamo", HangulJamoTokenFilterFactory::new); extra.put("hangul_chosung", HangulChosungFilterFactory::new); return extra; } }
35.333333
97
0.796226
48dad9362ab7bd6f32d9cddca4cc92005ecf753f
663
package cn.binarywang.wx.miniapp.api.impl; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.test.ApiTestModule; import com.google.inject.Inject; import org.testng.annotations.Guice; import org.testng.annotations.Test; import java.io.File; /** * @author <a href="https://github.com/binarywang">Binary Wang</a> */ @Test @Guice(modules = ApiTestModule.class) public class WxMaQrcodeServiceImplTest { @Inject protected WxMaService wxService; @Test public void testCreateQrCode() throws Exception { final File qrCode = this.wxService.getQrcodeService().createQrcode("111", 122); System.out.println(qrCode); } }
24.555556
83
0.760181
27f2bfe5ea6ce4456fbc4b79b3295ac58c96657e
7,982
package b.j.a.c.e0; import b.e.a.a.a; import b.j.a.a.k; import b.j.a.a.r; import b.j.a.c.a0.g; import b.j.a.c.b; import b.j.a.c.c; import b.j.a.c.i; import b.j.a.c.j0.j; import b.j.a.c.t; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; public class p extends c { /* renamed from: j reason: collision with root package name */ public static final Class<?>[] f1935j = new Class[0]; /* renamed from: b reason: collision with root package name */ public final z f1936b; public final g<?> c; public final b d; /* renamed from: e reason: collision with root package name */ public final b f1937e; public Class<?>[] f; /* renamed from: g reason: collision with root package name */ public boolean f1938g; /* renamed from: h reason: collision with root package name */ public List<r> f1939h; /* renamed from: i reason: collision with root package name */ public y f1940i; public p(g<?> gVar, i iVar, b bVar, List<r> list) { super(iVar); this.f1936b = null; this.c = gVar; if (gVar == null) { this.d = null; } else { this.d = gVar.e(); } this.f1937e = bVar; this.f1939h = list; } /* JADX WARNING: Illegal instructions before constructor call */ /* Code decompiled incorrectly, please refer to instructions dump. */ public p(b.j.a.c.e0.z r3) { /* r2 = this; b.j.a.c.i r0 = r3.d b.j.a.c.e0.b r1 = r3.f1961e r2.<init>(r0) r2.f1936b = r3 b.j.a.c.a0.g<?> r0 = r3.a r2.c = r0 if (r0 != 0) goto L_0x0011 r0 = 0 goto L_0x0015 L_0x0011: b.j.a.c.b r0 = r0.e() L_0x0015: r2.d = r0 r2.f1937e = r1 b.j.a.c.b r0 = r3.f1962g b.j.a.c.e0.b r1 = r3.f1961e b.j.a.c.e0.y r0 = r0.z(r1) if (r0 == 0) goto L_0x002b b.j.a.c.b r1 = r3.f1962g b.j.a.c.e0.b r3 = r3.f1961e b.j.a.c.e0.y r0 = r1.A(r3, r0) L_0x002b: r2.f1940i = r0 return */ throw new UnsupportedOperationException("Method not decompiled: b.j.a.c.e0.p.<init>(b.j.a.c.e0.z):void"); } public static p i(g<?> gVar, i iVar, b bVar) { return new p(gVar, iVar, bVar, Collections.emptyList()); } public Class<?>[] a() { if (!this.f1938g) { this.f1938g = true; b bVar = this.d; Class<?>[] b0 = bVar == null ? null : bVar.b0(this.f1937e); if (b0 == null && !this.c.o(b.j.a.c.p.DEFAULT_VIEW_INCLUSION)) { b0 = f1935j; } this.f = b0; } return this.f; } public k.d b(k.d dVar) { k.d dVar2; b bVar = this.d; if (bVar == null || (dVar2 = bVar.m(this.f1937e)) == null) { dVar2 = null; } k.d h2 = this.c.h(this.f1937e.f1887i); if (h2 != null) { return dVar2 == null ? h2 : dVar2.f(h2); } return dVar2; } public h c() { z zVar = this.f1936b; if (zVar == null) { return null; } if (!zVar.f1965j) { zVar.g(); } LinkedList<h> linkedList = zVar.f1971p; if (linkedList == null) { return null; } if (linkedList.size() <= 1) { return zVar.f1971p.get(0); } zVar.h("Multiple 'as-value' properties defined (%s vs %s)", zVar.f1971p.get(0), zVar.f1971p.get(1)); throw null; } public i d(String str, Class<?>[] clsArr) { Map<w, i> map = this.f1937e.h().f1922h; if (map == null) { return null; } return map.get(new w(str, clsArr)); } public r.b e(r.b bVar) { r.b K; b bVar2 = this.d; return (bVar2 == null || (K = bVar2.K(this.f1937e)) == null) ? bVar : bVar == null ? K : bVar.a(K); } public List<i> f() { List<i> k2 = this.f1937e.k(); if (k2.isEmpty()) { return k2; } ArrayList arrayList = null; for (i next : k2) { if (k(next)) { if (arrayList == null) { arrayList = new ArrayList(); } arrayList.add(next); } } return arrayList == null ? Collections.emptyList() : arrayList; } public j<Object, Object> g(Object obj) { if (obj == null) { return null; } if (obj instanceof j) { return (j) obj; } if (obj instanceof Class) { Class<j.a> cls = (Class) obj; if (cls == j.a.class || b.j.a.c.j0.g.t(cls)) { return null; } if (j.class.isAssignableFrom(cls)) { Objects.requireNonNull(this.c.f1609i); return (j) b.j.a.c.j0.g.h(cls, this.c.b()); } throw new IllegalStateException(a.e(cls, a.y("AnnotationIntrospector returned Class "), "; expected Class<Converter>")); } throw new IllegalStateException(a.f(obj, a.y("AnnotationIntrospector returned Converter definition of type "), "; expected type Converter or Class<Converter> instead")); } public List<r> h() { if (this.f1939h == null) { z zVar = this.f1936b; if (!zVar.f1965j) { zVar.g(); } this.f1939h = new ArrayList(zVar.f1966k.values()); } return this.f1939h; } public boolean j(t tVar) { r rVar; Iterator<r> it = h().iterator(); while (true) { if (!it.hasNext()) { rVar = null; break; } rVar = it.next(); if (rVar.H(tVar)) { break; } } return rVar != null; } /* JADX WARNING: Code restructure failed: missing block: B:17:0x0041, code lost: r5 = r5.v(0); */ /* Code decompiled incorrectly, please refer to instructions dump. */ public boolean k(b.j.a.c.e0.i r5) { /* r4 = this; java.lang.Class r0 = r5.w() b.j.a.c.i r1 = r4.a java.lang.Class<?> r1 = r1.f2152h boolean r0 = r1.isAssignableFrom(r0) r1 = 0 if (r0 != 0) goto L_0x0010 return r1 L_0x0010: b.j.a.c.b r0 = r4.d b.j.a.c.a0.g<?> r2 = r4.c b.j.a.a.h$a r0 = r0.e(r2, r5) r2 = 1 if (r0 == 0) goto L_0x0020 b.j.a.a.h$a r3 = b.j.a.a.h.a.DISABLED if (r0 == r3) goto L_0x0020 return r2 L_0x0020: java.lang.String r0 = r5.d() java.lang.String r3 = "valueOf" boolean r3 = r3.equals(r0) if (r3 == 0) goto L_0x0033 int r3 = r5.t() if (r3 != r2) goto L_0x0033 return r2 L_0x0033: java.lang.String r3 = "fromString" boolean r0 = r3.equals(r0) if (r0 == 0) goto L_0x0052 int r0 = r5.t() if (r0 != r2) goto L_0x0052 java.lang.Class r5 = r5.v(r1) java.lang.Class<java.lang.String> r0 = java.lang.String.class if (r5 == r0) goto L_0x0051 java.lang.Class<java.lang.CharSequence> r0 = java.lang.CharSequence.class boolean r5 = r0.isAssignableFrom(r5) if (r5 == 0) goto L_0x0052 L_0x0051: return r2 L_0x0052: return r1 */ throw new UnsupportedOperationException("Method not decompiled: b.j.a.c.e0.p.k(b.j.a.c.e0.i):boolean"); } }
29.783582
177
0.484089
93de57f7a47d8bc48d723c38ae938ff2c71c44bf
7,252
// tag::adocResource[] package io.quarkus.workshop.superheroes.villain; // end::adocResource[] import org.eclipse.microprofile.metrics.MetricUnits; import org.eclipse.microprofile.metrics.annotation.Counted; import org.eclipse.microprofile.metrics.annotation.Timed; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.enums.SchemaType; import org.eclipse.microprofile.openapi.annotations.media.Content; import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.eclipse.microprofile.openapi.annotations.parameters.Parameter; import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.jboss.logging.Logger; import javax.inject.Inject; import javax.validation.Valid; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.List; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.TEXT_PLAIN; // tag::adocResource[] @Path("/api/villains") @Produces(APPLICATION_JSON) public class VillainResource { private static final Logger LOGGER = Logger.getLogger(VillainResource.class); @Inject VillainService service; @Operation(summary = "Returns a random villain") @APIResponse(responseCode = "200", content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(implementation = Villain.class, required = true))) // tag::adocMetrics[] @Counted(name = "countGetRandomVillain", description = "Counts how many times the getRandomVillain method has been invoked") @Timed(name = "timeGetRandomVillain", description = "Times how long it takes to invoke the getRandomVillain method", unit = MetricUnits.MILLISECONDS) // end::adocMetrics[] @GET @Path("/random") public Response getRandomVillain() { Villain villain = service.findRandomVillain(); LOGGER.debug("Found random villain " + villain); return Response.ok(villain).build(); } @Operation(summary = "Returns all the villains from the database") @APIResponse(responseCode = "200", content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(implementation = Villain.class, type = SchemaType.ARRAY))) @APIResponse(responseCode = "204", description = "No villains") // tag::adocMetrics[] @Counted(name = "countGetAllVillains", description = "Counts how many times the getAllVillains method has been invoked") @Timed(name = "timeGetAllVillains", description = "Times how long it takes to invoke the getAllVillains method", unit = MetricUnits.MILLISECONDS) // end::adocMetrics[] @GET public Response getAllVillains() { List<Villain> villains = service.findAllVillains(); LOGGER.debug("Total number of villains " + villains); return Response.ok(villains).build(); } @Operation(summary = "Returns a villain for a given identifier") @APIResponse(responseCode = "200", content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(implementation = Villain.class))) @APIResponse(responseCode = "204", description = "The villain is not found for a given identifier") // tag::adocMetrics[] @Counted(name = "countGetVillain", description = "Counts how many times the getVillain method has been invoked") @Timed(name = "timeGetVillain", description = "Times how long it takes to invoke the getVillain method", unit = MetricUnits.MILLISECONDS) // end::adocMetrics[] @GET @Path("/{id}") public Response getVillain(@Parameter(description = "Villain identifier", required = true) @PathParam("id") Long id) { Villain villain = service.findVillainById(id); if (villain != null) { LOGGER.debug("Found villain " + villain); return Response.ok(villain).build(); } else { LOGGER.debug("No villain found with id " + id); return Response.noContent().build(); } } @Operation(summary = "Creates a valid villain") @APIResponse(responseCode = "201", description = "The URI of the created villain", content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(implementation = URI.class))) // tag::adocMetrics[] @Counted(name = "countCreateVillain", description = "Counts how many times the createVillain method has been invoked") @Timed(name = "timeCreateVillain", description = "Times how long it takes to invoke the createVillain method", unit = MetricUnits.MILLISECONDS) // end::adocMetrics[] @POST public Response createVillain(@RequestBody(required = true, content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(implementation = Villain.class))) @Valid Villain villain, @Context UriInfo uriInfo) { villain = service.persistVillain(villain); UriBuilder builder = uriInfo.getAbsolutePathBuilder().path(Long.toString(villain.id)); LOGGER.debug("New villain created with URI " + builder.build().toString()); return Response.created(builder.build()).build(); } @Operation(summary = "Updates an exiting villain") @APIResponse(responseCode = "200", description = "The updated villain", content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(implementation = Villain.class))) // tag::adocMetrics[] @Counted(name = "countUpdateVillain", description = "Counts how many times the updateVillain method has been invoked") @Timed(name = "timeUpdateVillain", description = "Times how long it takes to invoke the updateVillain method", unit = MetricUnits.MILLISECONDS) // end::adocMetrics[] @PUT public Response updateVillain(@RequestBody(required = true, content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(implementation = Villain.class))) @Valid Villain villain) { villain = service.updateVillain(villain); LOGGER.debug("Villain updated with new valued " + villain); return Response.ok(villain).build(); } @Operation(summary = "Deletes an exiting villain") @APIResponse(responseCode = "204", content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(implementation = Villain.class))) // tag::adocMetrics[] @Counted(name = "countDeleteVillain", description = "Counts how many times the deleteVillain method has been invoked") @Timed(name = "timeDeleteVillain", description = "Times how long it takes to invoke the deleteVillain method", unit = MetricUnits.MILLISECONDS) // end::adocMetrics[] @DELETE @Path("/{id}") public Response deleteVillain(@Parameter(description = "Villain identifier", required = true) @PathParam("id") Long id) { service.deleteVillain(id); LOGGER.debug("Villain deleted with " + id); return Response.noContent().build(); } @GET @Produces(TEXT_PLAIN) @Path("/hello") public String hello() { return "hello"; } } // end::adocResource[]
50.713287
216
0.719526
94c2510bf88af3a9a800c853e0cdd8a27e9b3d9f
829
package com.nowakArtur97.myMoments.feature.user.resource; import com.nowakArtur97.myMoments.feature.user.entity.UserProfile; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.*; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString @ApiModel(description = "Details about the User's Profile") public class UserProfileModel implements UserProfile { @ApiModelProperty(notes = "The user's information") private String about; @ApiModelProperty(notes = "The user's gender") private String gender; @ApiModelProperty(notes = "The user's interests") private String interests; @ApiModelProperty(notes = "The user's languages") private String languages; @ApiModelProperty(notes = "The user's location") private String location; }
26.741935
66
0.765983
6ccee509ccf1a536c85da007c4d834e2290cffa5
2,990
package org.opencb.oskar.analysis.variant.stats; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import org.opencb.biodata.models.variant.metadata.SampleVariantStats; import org.opencb.commons.datastore.core.ObjectMap; import org.opencb.oskar.analysis.OskarAnalysis; import org.opencb.oskar.analysis.exceptions.OskarAnalysisException; import java.nio.file.Path; import java.util.List; public abstract class SampleVariantStatsAnalysis extends OskarAnalysis { protected String study; protected List<String> sampleNames; protected String individualId; protected String familyId; private Path outputFile; public SampleVariantStatsAnalysis() { } public SampleVariantStatsAnalysis(ObjectMap executorParams, Path outDir) { super.setUp(executorParams, outDir); } @Override public String toString() { final StringBuilder sb = new StringBuilder("SampleVariantStatsAnalysis{"); sb.append("sampleNames=").append(sampleNames); sb.append(", individualId='").append(individualId).append('\''); sb.append(", familyId='").append(familyId).append('\''); sb.append(", params=").append(params); sb.append(", outDir=").append(outDir); sb.append('}'); return sb.toString(); } public String getStudy() { return study; } public SampleVariantStatsAnalysis setStudy(String study) { this.study = study; return this; } public List<String> getSampleNames() { return sampleNames; } public SampleVariantStatsAnalysis setSampleNames(List<String> sampleNames) { this.sampleNames = sampleNames; return this; } public String getIndividualId() { return individualId; } public SampleVariantStatsAnalysis setIndividualId(String individualId) { this.individualId = individualId; return this; } public String getFamilyId() { return familyId; } public SampleVariantStatsAnalysis setFamilyId(String familyId) { this.familyId = familyId; return this; } public Path getOutputFile() { return outputFile; } public SampleVariantStatsAnalysis setOutputFile(Path outputFile) { this.outputFile = outputFile; return this; } protected void writeStatsToFile(List<SampleVariantStats> stats) throws OskarAnalysisException { ObjectMapper objectMapper = new ObjectMapper().configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); ObjectWriter objectWriter = objectMapper.writer().withDefaultPrettyPrinter(); Path outFilename = getOutputFile(); try { objectWriter.writeValue(outFilename.toFile(), stats); } catch (Exception e) { throw new OskarAnalysisException("Error writing output file: " + outFilename, e); } } }
30.510204
114
0.693311
03e96f38285e1908420ae0704ab441be2c02c6b9
9,283
class wc3D { public static void ODx3 (String[] u1hMvYr) throws fUuiiC4J { ; int ndKxTYg9fXe; return; { if ( false[ 47273280.il1LGsNkiu()]) return; boolean SJSJ2u_; new XikP9G4WWy_().YLODyI0(); -CG[ true[ new boolean[ this.nXe9ZgX2hMwK][ -this.TONA3S]]]; tBLHk[] nvqEAKSjel0S; boolean D2; while ( this.kTPJuf) !---false.X6UeyyyVD; { return; } mcR3lzvlT stUAOrb0; while ( ( !true.VkY)[ !-new mtujv5xZiTB()[ -E6cVfWXzM()[ !!this[ !-!!IszljLG().vKcLyZ()]]]]) return; void iTu; boolean YT; void kr2YKP; false.u5QYjEO(); boolean CAeg6W5; int[][][] dosiaJGkqJzjuJ; JRHGFS DXPZJxBm_dN0n; } boolean[] uIijc2AhV_0x; boolean[][][] vG2vMPdf6Czx; return !true[ !!new int[ !iEdDLTEP_YacDu[ !!!-!true[ null.mw3]]].bNty3PlY()]; if ( -true.KfGF23c5) if ( Njo().TGGNPtG9PP()) return; -new kYbBm5vnAC0[ ( DP8qT5.hpdt())[ kHhgV().ot()]][ new nlOaLT2dVNJLcj().YysHz0Pej]; void[] Dxa8If; D[][] uWAzDByqBuSEp; boolean[] AWGH; return new NEeBSJyYlSdDW()[ new WNEw[ !new EvFjE[ -new tV91OpfFJ[ false.vuNUGK()].CNrsdi5osM].f8dqa2Y].KLmxa7Wydgmam]; } public int[][] ILcvG1f87 () throws oXc { int QpzlRzO = new YTvdk1e[ this.OOLcKvA5hTHh()].wXqZh6() = !!this[ new biixT83XSr_4r().RO3d]; while ( !!!-!this.GAWwPBxi4NBvHP()) ; void EbL3X0Grtf; return; if ( new boolean[ true.sQL_fp94ygV][ Lt5f3NbhC.Zx_d9BjJgcTD]) while ( !--false.Y05VOQ4KdzA0J()) if ( false[ !null[ -kT2tUQvi().R8QJTOJSi]]) 477228.T9O4Xp();else !this[ !!wfJ[ ( -this[ !b7CZ()[ -false.Pek25wCA]]).OdN4fM]]; boolean a; void[][] NajwhDV_chkk0A; if ( !-true.noDUO) if ( this[ !!new IcCIw[ false[ !!null.w630G7()]].J]) { ; }else { int PejY96Thw; } int[][][] AWE = -!dw733hMrt.ZMS_fPFOG(); boolean[] fh8Ri = MGh9CWOx().BrAusl_Kaj; { { int cWEt4N75Jf3; } boolean E76ZI5v5; while ( --gpzN51OPwReShq()[ -!-ZCEV7Q4uTF_y().B5aqt9b]) while ( !--!2170283.uXUOo()) ; z3_Xw h9B; Ho2mlF diW; int JNZh9Wy; while ( new cpLM1QS9().o8J0lnXAb8Q3E3) if ( 8719[ !this[ 7207[ -!!this.zT]]]) while ( false[ !3744[ -Pzb.GkW8gZm5Xe4()]]) -!-true[ false[ !this[ true[ this[ 421.wSktosZnyZ()]]]]]; boolean cuv0f54yhfFiI_; void a9; return; if ( -!-( ( -null.iNwxiMq).DtpnrMt()).jJnN3()) { boolean Dm2O6Ys9GUDjqo; } return; IdpKIihO[] N_ai9YDi; if ( ELyYQZw0Oo.k2I3AOFQiSt) if ( null[ ( !77.Wwmc7IH0wpoY)[ null.GjJoV()]]) return; return; int[] tjv5gTRNC; !new void[ tcqC91.YVelqG].VtGlLijMu; } if ( !new E().MZuvc) ; return !-null[ true.pJTc()]; ; if ( ( !-!w3F.AuqX_m1k0wPq).GND()) ; void[][] CodwHdau85 = new j0skO().tvJb = new void[ -this[ !1772035.v8pI]][ !true.v50LI()]; void X6R658k87K = this[ ( --!!( -this.VVzVI).uoQSZukvMo1Qt4).YdOj0Az()] = --!---!!!true._myizWgqlMlbUI; boolean[][] s4x0xj3Lt; boolean[] __Pz; } public void e9fBtOw0uq (int[] mxE, int[] pvG_Kb8dMwj6) { return; { K v1; if ( !h2mNVB().oSpci) while ( bQiJYC9FX8379x().VITRD) return; } ---false.f06Mk(); int[] cORhq_u; -true.FZzCDtf(); nWd Syx; if ( -true[ C().sB3Ju8PgFmeYnz]) return; } public static void lCpaS5iQWanz (String[] DjanSf) throws WM3 { JCwy[][] Z3D33; f7QXiQOXG tpjBmMmkL0f5s = -!false.blvNqhmKPs; boolean neCmzwTnmb73E = !false.Pv = ZSUY1DgP().rVBtHsT; } public boolean[] YxnxB3M; public static void alsY0d (String[] T76G) { if ( fRLS[ -!!null[ y_PEbu5LuXGsUd().pOC()]]) { void nWvOfe7H_Z7Bf; }else if ( !!!58739.RmtTT8NeS()) ; boolean Y3QMNo7HeizJ; boolean[][][] JHDi67JRNC9HH; int[] yxvIiZm; int ZRoDpjO3wZ = this.Jj84tj(); { -null.mFeczhJ8qrR; { -false.i6vR2W2G; } return; AR_wlT2z47_[ new Dv3jD().OdNJ0tBLRqpCS()]; void[][] aymA5Fynh; ; void[] km9d; boolean FJ74TB; int[] lmm6NGBQHHoP; N2ont[] s; e_fSn[][][][] cwyHbr5wPeM; while ( null._X6GMpJ) ; int[][] hhnml; return; { if ( new stmQxyKzA9k().A8ye()) false.Eo3FJO7(); } -this[ !-!-!!4.SpoR9upXBz1()]; int[] zR1LOEwCDF; } return; giXO[] I7bnIoRYb = null.Ce92NqYAf1(); false[ ( new TBrL()[ !!--true.VGfzH5()]).bW1fjVFG7fqp5M]; void TXnSP87; int[][][] bvV8xGVl1BB; null[ new void[ -_YT2uugfr().Lp()][ ( SaFkV8VV0zd.MoPnJsGtICvC6c)[ null[ --nbi[ new _QvDXtT9xJfYB6().qNM]]]]]; LSGqhcEQ_LTDh OsPiC; while ( !false[ -88111460.aU1ia6qj()]) { while ( 31268.QrRDn) { int[][] bgEhJVbF3n38C; } } } public static void rRe8naC_7CCkDy (String[] ybmJ2a5KGs8UU) { int[] CJUC1X = -new boolean[ !!-!new BT()[ -null.r2]].Um7hI = -!D27FT_0().z7XVvorYf2i(); return !ZQOm8nPOG.f; void[][][][][][] RARZfyhraJD = -!4146131[ !!true.sqs9CP] = new int[ -( !!!true.mxCiudJuqbGD_t()).OTcWc].t3Q6yKRvmaDx; clViHLZ[] ZKuqV; if ( 2341[ -Amj()[ !176771102.cWmTitlM]]) while ( ( -!-new kn2csbXanhl7y[ null[ GKE8pvOYa0Ut()._]].JtUstr())[ !MSgt().bo]) if ( -!yeA.IAbD3CWme()) while ( new JnD6GpGaBbQtK()._xMqjSVq4Q) return; ; } public boolean lP () throws ihRa { boolean[][][][][][] ObwsUntBQ8Ar = --this.c5fr; if ( -06695605.QIM) return; int[] xId2; !SOM0hNT0s1Ui()._Qh2C(); void[][] ZMpUMcBuUFwLri; while ( null[ this[ -!false.wMN6w()]]) { int lkVG5r; } while ( new boolean[ M[ ( -false[ !!null[ !!!new int[ --null.v2y()][ e__22Mk().fwBsZ]]]).U7iTrX9al2twx]].qLWUf()) return; int[][] bzongjngvLDH2; tFnMhgkbL1().nqnNBAoLfr; return !!this.DkIyESVyD2mEC(); geHhe2M_4Gv3 wcbG36Jmh85; } public int[] FxeypDb; public nWxu O3s5XTAUa8Zkr4 () { boolean CuVctiT; { vRgq jfnYFpYzXNj3e; -( ( false.aHyrVCNq3()).wi)[ null[ !!-!( 13517.SO8KfYA3())[ new NmPf6mRcCIU1F().xd85l()]]]; boolean[] R0vsMSC14YE23e; } { return; y6cNqn[][][][][] HCctJp4HnR5cE; { return; } !new AMkkR[ DdUO().x()][ null.FdOO0B()]; boolean Rdw; while ( true[ new void[ new AG().m8XAm()][ 64023724.Pu74dUNh]]) return; int ZqToDSVK; int F; int[][][] IRpV4Js; aKPAivHb nnholxYf; } while ( Pj.CYYVDWDZKDd()) !---this[ null.oqPja1ubytQb]; qIDMxPUC1 oOOBg9vDMW; TFUNNi8R9L[] k7xTjnPrDl; void JQzR1w = RTdB.pCbwQ3b; } public int q9PxS11Ywp; public ttiwS9svY mKGvijR; public static void h (String[] I41) throws xn8obQa { boolean y7ur7_uhB; while ( null.gA1FUYeCNO) if ( m().j) ; while ( --new SEOc()[ --new int[ new wsTzdZe26w5HSV()[ !!!false.HQoC4_g97o5Jx()]].bgH__bw]) !!-!!true[ this.bd3jD_Z1()]; int zE7R0MTfc = -new FyPmDplIp[ !-this[ !this.mwpiUXQEDjWuh()]].CMu2ygaI1(); vPaDKnLA Pu3VKJpXLifO; { df2BqI6tEHfYC h5MtHF4gepL; void[] xuy_f; bWCu_Olgg4E4ek[][] uPhtjyIWCeyG; boolean FdSAU5H; while ( true.WGDXsa4JKA()) ; zoQ[][][] WbP2IYrsRFs0; E g2ABs3fann4pf; int[][] z; void[] EFYX_Di; return; boolean U6j0ndDudc0b5a; return; void[] ianApiIblFGj; } boolean F8cAv; grT Rh; } public static void ziOJsr_t (String[] D) { boolean fQCD_S6; { Xlx0c[] Zof; boolean[][] ei; void[] sA97M; return; int[][] kB; int buLce9Ny; { boolean H1cKSvVLw; } --!!true[ -!!new siOdGBZ71Iue5().MuVVA_Eo1c]; { int XQTJJNp; } int[] hq; tHky[][][] EvKk; !--!34038.yo3YZRdJ; boolean[] Gem87; int[][][][][][] jlsR4cs5D; Q[] gtaEClDpKxwX; } while ( !this.BSMZAiszQUQ9Zx) while ( -!1752[ !true[ ( true.YJE).Dd8JKC]]) { void[][][][][][] N_; } PLkHXXN5[] UaEB1Kf06EtnsS; x[] QcliFSyQnV0; boolean ej; boolean _jgVmVxD; if ( new J().P58bpNepY7fzc()) ;else ; return; } }
36.261719
231
0.491975
7190e7c6b17412f87ed41b6c779dee26c76823ab
1,455
/* * Copyright 2018 the original author or authors. * Copyright 2018 SorcerSoft.org. * * 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 sorcer.service; import net.jini.core.transaction.Transaction; import net.jini.core.transaction.TransactionException; import java.rmi.RemoteException; import java.util.List; /** * Created by Mike Sobolewski on 08/14/18. * * Execute provided list of services as a service pipe. */ public interface Consumer extends Service, Client { Context consume(Context context, Arg[] args) throws ServiceException, RemoteException, TransactionException; List<Service> getService(String... args) throws ServiceException; Transaction getTransaction(); void preprocess(String... args) throws MogramException, ContextException; void process(String... args) throws MogramException, ContextException; void postprocess(String... args) throws MogramException, ContextException; }
31.630435
112
0.757388
c48b2800a1f843319d1365c71661398184f9a2fb
2,865
package org.testmonkeys; import com.gargoylesoftware.htmlunit.BrowserVersion; import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.remote.DesiredCapabilities; import static org.openqa.selenium.remote.BrowserType.CHROME; import static org.openqa.selenium.remote.BrowserType.PHANTOMJS; public class DriverFactory { public static WebDriver initDriver(String browser) { DesiredCapabilities cap; switch (browser.toLowerCase()) { case CHROME: cap = DesiredCapabilities.chrome(); return new ChromeDriver(cap); case PHANTOMJS: cap = DesiredCapabilities.phantomjs(); cap.setCapability("phantomjs.page.settings.userAgent", "chrome"); cap.setCapability("phantomjs.page.settings.resourceTimeout", 5000); PhantomJSDriver driver = new PhantomJSDriver(cap); driver.manage().window().setSize(new Dimension(1920, 1080)); return driver; case "htmlunit": cap = DesiredCapabilities.htmlUnit(); HtmlUnitDriver htmlUnitDriver = new HtmlUnitDriver(BrowserVersion.EDGE, true); htmlUnitDriver.setJavascriptEnabled(true); return htmlUnitDriver; case "firefox": cap = DesiredCapabilities.firefox(); cap.setCapability("binary", "/usr/bin/firefox"); cap.setCapability("marionette", false); return new FirefoxDriver(cap); default: throw new RuntimeException("Unsupported browser[" + browser + "]"); } } public static WebDriver initDriver(String browser, String mode, DesiredCapabilities caps) { switch (browser.toLowerCase()) { case CHROME: return initChromeDriver(mode, caps); case PHANTOMJS: caps = DesiredCapabilities.phantomjs(); return new PhantomJSDriver(caps); default: throw new RuntimeException("Unsupported browser[" + browser + "]"); } } public static WebDriver initChromeDriver(String mode, DesiredCapabilities capabilities) { if (mode != null && mode.equals("headless")) { ChromeOptions options = new ChromeOptions(); // options.addArguments("--headless"); capabilities.setCapability(ChromeOptions.CAPABILITY, options); } return new ChromeDriver(capabilities); } }
40.928571
95
0.647818
3f940b164a01bfce86d60ec3fed43479a771f362
297
package com.maxDeVos; import java.util.ArrayList; public class Division { //Week 1 = B3:H6 //Week 2 = B9:H12 //Week 3 = B15:H18 //Week 4 = B21:H24 //Week 5 = B27:H30 String divisionName; ArrayList<Team> teams = new ArrayList<Team>(); public void populateTeams(int week) { } }
14.142857
47
0.653199