repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Whoosh/schalarm
localdb/src/main/java/com/github/mikhailerofeev/scholarm/local/services/QuestionsManager.java
3530
package com.github.mikhailerofeev.scholarm.local.services; import android.app.Application; import com.github.mikhailerofeev.scholarm.api.entities.Question; import com.github.mikhailerofeev.scholarm.local.entities.QuestionImpl; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.inject.Inject; import java.io.*; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @author m-erofeev * @since 22.08.14 */ public class QuestionsManager { private final Application application; private List<QuestionImpl> questions; private Long maxId; @Inject public QuestionsManager(Application application) { this.application = application; } public List<Question> getQuestions(Set<String> questionThemesAndSubthemesNames) { List<Question> ret = new ArrayList<>(); for (QuestionImpl question : questions) { if (questionThemesAndSubthemesNames.contains(question.getThemeName())) { ret.add(question); } } return ret; } @Inject public synchronized void init() { System.out.println("init QuestionsManager"); System.out.println("our dir: " + application.getApplicationContext().getFilesDir()); maxId = 0L; File dataFile = getDataFile(); if (!dataFile.exists()) { System.out.println(dataFile.getAbsolutePath() + " not exists"); if (!tryToLoadAssets()) { questions = new ArrayList<>(); } return; } FileReader fileReader; try { fileReader = new FileReader(dataFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } readQuestions(fileReader); } private void readQuestions(Reader fileReader) { Type type = new TypeToken<List<QuestionImpl>>() { }.getType(); questions = new Gson().fromJson(fileReader, type); for (QuestionImpl question : questions) { if (maxId < question.getId()) { maxId = question.getId(); } } } private boolean tryToLoadAssets() { if (application.getAssets() == null) { return false; } try { Reader inputStreamReader = new InputStreamReader(application.getAssets().open("database.json")); readQuestions(inputStreamReader); } catch (IOException e) { e.printStackTrace(); return false; } return true; } public synchronized void addQuestions(List<QuestionImpl> questionsToAdd) { for (QuestionImpl question : questionsToAdd) { question.setId(maxId++); this.questions.add(question); } File dataFile = getDataFile(); dataFile.delete(); try { if (!dataFile.createNewFile()) { throw new RuntimeException("can't create file"); } String questionsStr = new Gson().toJson(this.questions); FileWriter writer = new FileWriter(dataFile); writer.append(questionsStr); writer.close(); } catch (IOException e) { throw new RuntimeException(e); } } private File getDataFile() { File filesDir = application.getApplicationContext().getFilesDir(); return new File(filesDir.getAbsolutePath() + "database.json"); } }
mit
jblindsay/jblindsay.github.io
ghrg/Whitebox/WhiteboxGAT-linux/resources/plugins/source_files/AverageSlopeToDivide.java
16874
/* * Copyright (C) 2011-2012 Dr. John Lindsay <jlindsay@uoguelph.ca> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package plugins; import java.util.Date; import whitebox.geospatialfiles.WhiteboxRaster; import whitebox.interfaces.WhiteboxPlugin; import whitebox.interfaces.WhiteboxPluginHost; /** * This tool calculates the average slope gradient (i.e., slope steepness in degrees) of the flowpaths that run through each grid cell in an input digital elevation model (DEM) to the upslope divide cells. * * @author Dr. John Lindsay email: jlindsay@uoguelph.ca */ public class AverageSlopeToDivide implements WhiteboxPlugin { private WhiteboxPluginHost myHost = null; private String[] args; // Constants private static final double LnOf2 = 0.693147180559945; /** * Used to retrieve the plugin tool's name. This is a short, unique name * containing no spaces. * * @return String containing plugin name. */ @Override public String getName() { return "AverageSlopeToDivide"; } /** * Used to retrieve the plugin tool's descriptive name. This can be a longer * name (containing spaces) and is used in the interface to list the tool. * * @return String containing the plugin descriptive name. */ @Override public String getDescriptiveName() { return "Average Flowpath Slope From Cell To Divide"; } /** * Used to retrieve a short description of what the plugin tool does. * * @return String containing the plugin's description. */ @Override public String getToolDescription() { return "Measures the average slope gradient from each grid cell to all " + "upslope divide cells."; } /** * Used to identify which toolboxes this plugin tool should be listed in. * * @return Array of Strings. */ @Override public String[] getToolbox() { String[] ret = {"FlowpathTAs"}; return ret; } /** * Sets the WhiteboxPluginHost to which the plugin tool is tied. This is the * class that the plugin will send all feedback messages, progress updates, * and return objects. * * @param host The WhiteboxPluginHost that called the plugin tool. */ @Override public void setPluginHost(WhiteboxPluginHost host) { myHost = host; } /** * Used to communicate feedback pop-up messages between a plugin tool and * the main Whitebox user-interface. * * @param feedback String containing the text to display. */ private void showFeedback(String message) { if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } } /** * Used to communicate a return object from a plugin tool to the main * Whitebox user-interface. * * @return Object, such as an output WhiteboxRaster. */ private void returnData(Object ret) { if (myHost != null) { myHost.returnData(ret); } } private int previousProgress = 0; private String previousProgressLabel = ""; /** * Used to communicate a progress update between a plugin tool and the main * Whitebox user interface. * * @param progressLabel A String to use for the progress label. * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(String progressLabel, int progress) { if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel, progress); } previousProgress = progress; previousProgressLabel = progressLabel; } /** * Used to communicate a progress update between a plugin tool and the main * Whitebox user interface. * * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(int progress) { if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress = progress; } /** * Sets the arguments (parameters) used by the plugin. * * @param args An array of string arguments. */ @Override public void setArgs(String[] args) { this.args = args.clone(); } private boolean cancelOp = false; /** * Used to communicate a cancel operation from the Whitebox GUI. * * @param cancel Set to true if the plugin should be canceled. */ @Override public void setCancelOp(boolean cancel) { cancelOp = cancel; } private void cancelOperation() { showFeedback("Operation cancelled."); updateProgress("Progress: ", 0); } private boolean amIActive = false; /** * Used by the Whitebox GUI to tell if this plugin is still running. * * @return a boolean describing whether or not the plugin is actively being * used. */ @Override public boolean isActive() { return amIActive; } /** * Used to execute this plugin tool. */ @Override public void run() { amIActive = true; String inputHeader = null; String outputHeader = null; String DEMHeader = null; int row, col, x, y; int progress = 0; double z, val, val2, val3; int i, c; int[] dX = new int[]{1, 1, 1, 0, -1, -1, -1, 0}; int[] dY = new int[]{-1, 0, 1, 1, 1, 0, -1, -1}; double[] inflowingVals = new double[]{16, 32, 64, 128, 1, 2, 4, 8}; boolean flag = false; double flowDir = 0; double flowLength = 0; double numUpslopeFlowpaths = 0; double flowpathLengthToAdd = 0; double conversionFactor = 1; double divideElevToAdd = 0; double radToDeg = 180 / Math.PI; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputHeader = args[0]; DEMHeader = args[1]; outputHeader = args[2]; conversionFactor = Double.parseDouble(args[3]); // check to see that the inputHeader and outputHeader are not null. if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster pntr = new WhiteboxRaster(inputHeader, "r"); int rows = pntr.getNumberRows(); int cols = pntr.getNumberColumns(); double noData = pntr.getNoDataValue(); double gridResX = pntr.getCellSizeX(); double gridResY = pntr.getCellSizeY(); double diagGridRes = Math.sqrt(gridResX * gridResX + gridResY * gridResY); double[] gridLengths = new double[]{diagGridRes, gridResX, diagGridRes, gridResY, diagGridRes, gridResX, diagGridRes, gridResY}; WhiteboxRaster DEM = new WhiteboxRaster(DEMHeader, "r"); if (DEM.getNumberRows() != rows || DEM.getNumberColumns() != cols) { showFeedback("The input files must have the same dimensions, i.e. number of " + "rows and columns."); return; } WhiteboxRaster output = new WhiteboxRaster(outputHeader, "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, -999); output.setPreferredPalette("blueyellow.pal"); output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS); output.setZUnits(pntr.getXYUnits()); WhiteboxRaster numInflowingNeighbours = new WhiteboxRaster(outputHeader.replace(".dep", "_temp1.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0); numInflowingNeighbours.isTemporaryFile = true; WhiteboxRaster numUpslopeDivideCells = new WhiteboxRaster(outputHeader.replace(".dep", "_temp2.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0); numUpslopeDivideCells.isTemporaryFile = true; WhiteboxRaster totalFlowpathLength = new WhiteboxRaster(outputHeader.replace(".dep", "_temp3.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0); totalFlowpathLength.isTemporaryFile = true; WhiteboxRaster totalUpslopeDivideElev = new WhiteboxRaster(outputHeader.replace(".dep", "_temp4.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0); totalUpslopeDivideElev.isTemporaryFile = true; updateProgress("Loop 1 of 3:", 0); for (row = 0; row < rows; row++) { for (col = 0; col < cols; col++) { if (pntr.getValue(row, col) != noData) { z = 0; for (i = 0; i < 8; i++) { if (pntr.getValue(row + dY[i], col + dX[i]) == inflowingVals[i]) { z++; } } if (z > 0) { numInflowingNeighbours.setValue(row, col, z); } else { numInflowingNeighbours.setValue(row, col, -1); } } else { output.setValue(row, col, noData); } } if (cancelOp) { cancelOperation(); return; } progress = (int) (100f * row / (rows - 1)); updateProgress("Loop 1 of 3:", progress); } updateProgress("Loop 2 of 3:", 0); for (row = 0; row < rows; row++) { for (col = 0; col < cols; col++) { val = numInflowingNeighbours.getValue(row, col); if (val <= 0 && val != noData) { flag = false; x = col; y = row; do { val = numInflowingNeighbours.getValue(y, x); if (val <= 0 && val != noData) { //there are no more inflowing neighbours to visit; carry on downslope if (val == -1) { //it's the start of a flowpath numUpslopeDivideCells.setValue(y, x, 0); numUpslopeFlowpaths = 1; divideElevToAdd = DEM.getValue(y, x); } else { numUpslopeFlowpaths = numUpslopeDivideCells.getValue(y, x); divideElevToAdd = totalUpslopeDivideElev.getValue(y, x); } numInflowingNeighbours.setValue(y, x, noData); // find it's downslope neighbour flowDir = pntr.getValue(y, x); if (flowDir > 0) { // what's the flow direction as an int? c = (int) (Math.log(flowDir) / LnOf2); flowLength = gridLengths[c]; val2 = totalFlowpathLength.getValue(y, x); flowpathLengthToAdd = val2 + numUpslopeFlowpaths * flowLength; //move x and y accordingly x += dX[c]; y += dY[c]; numUpslopeDivideCells.setValue(y, x, numUpslopeDivideCells.getValue(y, x) + numUpslopeFlowpaths); totalFlowpathLength.setValue(y, x, totalFlowpathLength.getValue(y, x) + flowpathLengthToAdd); totalUpslopeDivideElev.setValue(y, x, totalUpslopeDivideElev.getValue(y, x) + divideElevToAdd); numInflowingNeighbours.setValue(y, x, numInflowingNeighbours.getValue(y, x) - 1); } else { // you've hit the edge or a pit cell. flag = true; } } else { flag = true; } } while (!flag); } } if (cancelOp) { cancelOperation(); return; } progress = (int) (100f * row / (rows - 1)); updateProgress("Loop 2 of 3:", progress); } numUpslopeDivideCells.flush(); totalFlowpathLength.flush(); totalUpslopeDivideElev.flush(); numInflowingNeighbours.close(); updateProgress("Loop 3 of 3:", 0); double[] data1 = null; double[] data2 = null; double[] data3 = null; double[] data4 = null; double[] data5 = null; for (row = 0; row < rows; row++) { data1 = numUpslopeDivideCells.getRowValues(row); data2 = totalFlowpathLength.getRowValues(row); data3 = pntr.getRowValues(row); data4 = totalUpslopeDivideElev.getRowValues(row); data5 = DEM.getRowValues(row); for (col = 0; col < cols; col++) { if (data3[col] != noData) { if (data1[col] > 0) { val = data2[col] / data1[col]; val2 = (data4[col] / data1[col] - data5[col]) * conversionFactor; val3 = Math.atan(val2 / val) * radToDeg; output.setValue(row, col, val3); } else { output.setValue(row, col, 0); } } else { output.setValue(row, col, noData); } } if (cancelOp) { cancelOperation(); return; } progress = (int) (100f * row / (rows - 1)); updateProgress("Loop 3 of 3:", progress); } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); pntr.close(); DEM.close(); numUpslopeDivideCells.close(); totalFlowpathLength.close(); totalUpslopeDivideElev.close(); output.close(); // returning a header file string displays the image. returnData(outputHeader); } catch (OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch (Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(), e); } finally { updateProgress("Progress: ", 0); // tells the main application that this process is completed. amIActive = false; myHost.pluginComplete(); } } }
mit
remcomokveld/WearCast
library-app/src/main/java/nl/rmokveld/wearcast/phone/WearCastService.java
2916
package nl.rmokveld.wearcast.phone; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v7.app.NotificationCompat; import nl.rmokveld.wearcast.shared.C; public class WearCastService extends Service { private static final String ACTION_DISCOVERY = "discovery"; private static final String ACTION_START_CAST = "start_cast"; public static void startDiscovery(Context context) { context.startService(new Intent(context, WearCastService.class).setAction(ACTION_DISCOVERY).putExtra("start", true)); } public static void stopDiscovery(Context context) { context.startService(new Intent(context, WearCastService.class).setAction(ACTION_DISCOVERY).putExtra("start", false)); } public static void startCast(Context context, String requestNode, String deviceId, String mediaJson) { context.startService(new Intent(context, WearCastService.class) .setAction(ACTION_START_CAST) .putExtra(C.REQUEST_NODE_ID, requestNode) .putExtra(C.ARG_MEDIA_INFO, mediaJson) .putExtra(C.DEVICE_ID, deviceId)); } private WearCastDiscoveryHelper mCastDiscoveryHelper; private AbstractStartCastHelper mStartCastHelper; private Runnable mTimeout = new Runnable() { @Override public void run() { stopForeground(true); mCastDiscoveryHelper.stopDiscovery(); } }; @Override public void onCreate() { super.onCreate(); mCastDiscoveryHelper = new WearCastDiscoveryHelper(this); if (WearCastNotificationManager.getExtension() != null) mStartCastHelper = WearCastNotificationManager.getExtension().newStartCastHelper(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { if (ACTION_DISCOVERY.equals(intent.getAction())) { if (intent.getBooleanExtra("start", false)) { mCastDiscoveryHelper.startDiscovery(); } else { mCastDiscoveryHelper.stopDiscovery(); } } else if (ACTION_START_CAST.equals(intent.getAction())) { mStartCastHelper.startCastFromWear( intent.getStringExtra(C.DEVICE_ID), intent.getStringExtra(C.ARG_MEDIA_INFO), intent.getStringExtra(C.REQUEST_NODE_ID), null); } } return START_NOT_STICKY; } @Override public void onDestroy() { super.onDestroy(); mCastDiscoveryHelper.release(); mStartCastHelper.release(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
mit
sriki77/edgesh
src/main/java/org/github/sriki77/edgesh/command/CommandException.java
180
package org.github.sriki77.edgesh.command; public class CommandException extends RuntimeException { public CommandException(String message) { super(message); } }
mit
apetenchea/SpaceInvaders
src/main/java/spaceinvaders/command/client/FlushScreenCommand.java
771
package spaceinvaders.command.client; import static spaceinvaders.command.ProtocolEnum.UDP; import spaceinvaders.client.mvc.Controller; import spaceinvaders.client.mvc.View; import spaceinvaders.command.Command; /** Flush the screen. */ public class FlushScreenCommand extends Command { private transient Controller executor; public FlushScreenCommand() { super(FlushScreenCommand.class.getName(),UDP); } @Override public void execute() { for (View view : executor.getViews()) { view.flush(); } } @Override public void setExecutor(Object executor) { if (executor instanceof Controller) { this.executor = (Controller) executor; } else { // This should never happen. throw new AssertionError(); } } }
mit
bThink-BGU/BPjs
src/test/java/il/ac/bgu/cs/bp/bpjs/analysis/DfsBProgramVerifierTest.java
23981
/* * The MIT License * * Copyright 2017 michael. * * 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 il.ac.bgu.cs.bp.bpjs.analysis; import il.ac.bgu.cs.bp.bpjs.TestUtils; import static il.ac.bgu.cs.bp.bpjs.TestUtils.eventNamesString; import il.ac.bgu.cs.bp.bpjs.model.BProgram; import il.ac.bgu.cs.bp.bpjs.execution.BProgramRunner; import il.ac.bgu.cs.bp.bpjs.model.ResourceBProgram; import il.ac.bgu.cs.bp.bpjs.execution.listeners.InMemoryEventLoggingListener; import il.ac.bgu.cs.bp.bpjs.execution.listeners.PrintBProgramRunnerListener; import org.junit.Test; import static il.ac.bgu.cs.bp.bpjs.TestUtils.traceEventNamesString; import static org.junit.Assert.*; import il.ac.bgu.cs.bp.bpjs.model.StringBProgram; import il.ac.bgu.cs.bp.bpjs.analysis.listeners.PrintDfsVerifierListener; import il.ac.bgu.cs.bp.bpjs.analysis.violations.DeadlockViolation; import il.ac.bgu.cs.bp.bpjs.analysis.violations.DetectedSafetyViolation; import il.ac.bgu.cs.bp.bpjs.analysis.violations.JsErrorViolation; import il.ac.bgu.cs.bp.bpjs.analysis.violations.Violation; import il.ac.bgu.cs.bp.bpjs.model.BEvent; import java.util.Arrays; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static java.util.stream.Collectors.joining; /** * @author michael */ public class DfsBProgramVerifierTest { @Test public void sanity() throws Exception { BProgram program = new ResourceBProgram("DFSVerifierTests/AAABTrace.js"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setDebugMode(true); sut.setMaxTraceLength(3); sut.setIterationCountGap(1); sut.verify(program); assertEquals( ExecutionTraceInspections.DEFAULT_SET, sut.getInspections() ); } @Test public void simpleAAABTrace_forgetfulStore() throws Exception { BProgram program = new ResourceBProgram("DFSVerifierTests/AAABTrace.js"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setProgressListener(new PrintDfsVerifierListener()); program.appendSource(Requirements.eventNotSelected("B")); sut.setVisitedStateStore(new ForgetfulVisitedStateStore()); VerificationResult res = sut.verify(program); assertTrue(res.isViolationFound()); assertEquals("AAAB", traceEventNamesString(res, "")); } @Test public void simpleAAABTrace() throws Exception { BProgram program = new ResourceBProgram("DFSVerifierTests/AAABTrace.js"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setDebugMode(true); sut.setProgressListener(new PrintDfsVerifierListener()); program.appendSource(Requirements.eventNotSelected("B")); sut.setVisitedStateStore(new BThreadSnapshotVisitedStateStore()); VerificationResult res = sut.verify(program); assertTrue(res.isViolationFound()); assertEquals("AAAB", traceEventNamesString(res, "")); } @Test public void simpleAAABTrace_hashedNodeStore() throws Exception { BProgram program = new ResourceBProgram("DFSVerifierTests/AAABTrace.js"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setDebugMode(true); sut.setProgressListener(new PrintDfsVerifierListener()); program.appendSource(Requirements.eventNotSelected("B")); VisitedStateStore stateStore = new BProgramSnapshotVisitedStateStore(); sut.setVisitedStateStore(stateStore); VerificationResult res = sut.verify(program); assertTrue(res.isViolationFound()); assertEquals("AAAB", traceEventNamesString(res, "")); //Add trivial getter check VisitedStateStore retStore = sut.getVisitedStateStore(); assertSame(retStore, stateStore); } @Test public void testAAABRun() { BProgram program = new ResourceBProgram("DFSVerifierTests/AAABTrace.js"); BProgramRunner rnr = new BProgramRunner(program); rnr.addListener(new PrintBProgramRunnerListener()); InMemoryEventLoggingListener eventLogger = rnr.addListener(new InMemoryEventLoggingListener()); rnr.run(); eventLogger.getEvents().forEach(System.out::println); assertTrue(eventNamesString(eventLogger.getEvents(), "").matches("^(AAAB)+$")); } @Test public void deadlockTrace() throws Exception { BProgram program = new ResourceBProgram("DFSVerifierTests/deadlocking.js"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setVisitedStateStore(new ForgetfulVisitedStateStore()); VerificationResult res = sut.verify(program); assertTrue(res.isViolationFound()); assertTrue(res.getViolation().get() instanceof DeadlockViolation); assertEquals("A", traceEventNamesString(res, "")); } @Test public void testDeadlockSetting() throws Exception { BProgram program = new ResourceBProgram("DFSVerifierTests/deadlocking.js"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.addInspection(ExecutionTraceInspections.FAILED_ASSERTIONS); VerificationResult res = sut.verify(program); assertFalse(res.isViolationFound()); } @Test public void deadlockRun() { BProgram program = new ResourceBProgram("DFSVerifierTests/deadlocking.js"); BProgramRunner rnr = new BProgramRunner(program); rnr.addListener(new PrintBProgramRunnerListener()); InMemoryEventLoggingListener eventLogger = rnr.addListener(new InMemoryEventLoggingListener()); rnr.run(); eventLogger.getEvents().forEach(System.out::println); assertTrue(eventNamesString(eventLogger.getEvents(), "").matches("^A$")); } @Test public void testTwoSimpleBThreads() throws Exception { BProgram bprog = new StringBProgram( "bp.registerBThread('bt1', function(){bp.sync({ request:[ bp.Event(\"STAM1\") ] });});" + "bp.registerBThread('bt2', function(){bp.sync({ request:[ bp.Event(\"STAM2\") ] });});"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setIterationCountGap(1); sut.setProgressListener(new PrintDfsVerifierListener()); sut.addInspection(ExecutionTraceInspections.FAILED_ASSERTIONS); VerificationResult res = sut.verify(bprog); assertFalse(res.isViolationFound()); assertEquals(4, res.getScannedStatesCount()); assertEquals(4, res.getScannedEdgesCount()); } @Test(timeout = 2000) public void testTwoLoopingBThreads() throws Exception { BProgram bprog = new StringBProgram("bp.registerBThread('bt1', function(){" + " while(true){\n" + " bp.sync({ request:[ bp.Event(\"STAM1\") ] });\n" + "}});\n" + "bp.registerBThread('bt2', function(){" + " while(true){\n" + " bp.sync({ request:[ bp.Event(\"STAM2\") ] });\n" + "}});\n" + ""); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setIterationCountGap(1); sut.setProgressListener(new PrintDfsVerifierListener()); sut.setDebugMode(true); VerificationResult res = sut.verify(bprog); assertFalse(res.isViolationFound()); assertEquals(1, res.getScannedStatesCount()); } @Test(timeout = 2000) public void testVariablesInBT() throws Exception { BProgram bprog = new StringBProgram("bp.registerBThread('bt1', function(){" + // " for(var i=0; i<10; i++){\n" + // " bp.sync({ waitFor:[ bp.Event(\"X\") ] });\n" + // " }\n" + // " bp.sync({ block:[ bp.Event(\"X\") ] });\n" + // "});\n" + // "bp.registerBThread('bt2', function(){" + // " while(true){\n" + // " bp.sync({ request:[ bp.Event(\"X\") ] });\n" + // "}});\n" + // "" // ); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setIterationCountGap(1); sut.setProgressListener(new PrintDfsVerifierListener()); sut.setDebugMode(true); VerificationResult res = sut.verify(bprog); assertTrue(res.isViolationFound()); assertTrue(res.getViolation().get() instanceof DeadlockViolation); assertEquals(11, res.getScannedStatesCount()); } @Test(timeout = 2000) public void testVariablesEquailtyInBT() throws Exception { BProgram bprog = new StringBProgram( // "bp.registerBThread('bt1', function(){" + // " bp.sync({ waitFor:[ bp.Event(\"X\") ] });\n" + // 1 " bp.sync({ waitFor:[ bp.Event(\"X\") ] });\n" + // 2 " bp.sync({ waitFor:[ bp.Event(\"X\") ] });\n" + // 3 " bp.sync({ waitFor:[ bp.Event(\"X\") ] });\n" + // 4 "});\n" + "bp.registerBThread('bt2', function(){" + // " while(true){\n" + // " bp.sync({ request:[ bp.Event(\"X\") ] });\n" + // "}});\n"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setIterationCountGap(1); sut.setProgressListener(new PrintDfsVerifierListener()); sut.setDebugMode(true); VerificationResult res = sut.verify(bprog); assertFalse(res.isViolationFound()); // 10 syncs while bt1 is alive, 1 sync per bt2's infinite loop alone. assertEquals(5, res.getScannedStatesCount()); // in this case only one option per state assertEquals(5, res.getScannedEdgesCount()); } @Test(timeout = 2000) public void testMaxTraceLength() throws Exception { String source = "bp.registerBThread('bt1', function(){" + " bp.sync({ request:[ bp.Event(\"X\") ] });\n" + " bp.sync({ request:[ bp.Event(\"X\") ] });\n" + " bp.sync({ request:[ bp.Event(\"X\") ] });\n" + " bp.sync({ request:[ bp.Event(\"X\") ] });\n" + " bp.sync({ request:[ bp.Event(\"X\") ] });\n" + " bp.sync({ request:[ bp.Event(\"X\") ] });\n" + " bp.ASSERT(false, \"\");" + "});"; BProgram bprog = new StringBProgram(source); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setIterationCountGap(1); sut.setProgressListener(new PrintDfsVerifierListener()); sut.setDebugMode(true); VerificationResult res = sut.verify(bprog); assertTrue(res.isViolationFound()); sut.setMaxTraceLength(6); res = sut.verify(new StringBProgram(source)); assertFalse(res.isViolationFound()); } @Test(timeout = 6000) public void testJavaVariablesInBT() throws Exception { BProgram bprog = new StringBProgram( // "bp.registerBThread('bt1', function(){" + // " var sampleArray=[1,2,3,4,5];\n" + " while(true) \n" + // " for(var i=0; i<10; i++){\n" + // " bp.sync({ request:[ bp.Event(\"X\"+i) ] });\n" + // " if (i == 5) {bp.sync({ request:[ bp.Event(\"X\"+i) ] });}\n" + // " }\n" + // "});\n" + "var xs = bp.EventSet( \"X\", function(e){\r\n" + " return e.getName().startsWith(\"X\");\r\n" + "} );\r\n" + "" + "bp.registerBThread('bt2', function(){" + // " var lastE = {name:\"what\"};" + // " while(true) {\n" + // " var e = bp.sync({ waitFor: xs});\n" + // " lastE = e;" + // " if( e.name == lastE.name) { bp.ASSERT(false,\"Poof\");} " + // "}});\n" ); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setIterationCountGap(1); sut.setProgressListener(new PrintDfsVerifierListener()); sut.setDebugMode(true); VerificationResult res = sut.verify(bprog); assertTrue(res.isViolationFound()); assertTrue(res.getViolation().get() instanceof DetectedSafetyViolation); assertEquals(2, res.getScannedStatesCount()); assertEquals(1, res.getScannedEdgesCount()); } /** * Running this transition system. State 3 should be arrived at twice. * +-»B1»--+ * | | * -»1--»A»--2 3--»C»----+ * | | | | * | +-»B2»--+ | * +------------«------------+ * * event trace "AB1-" is the result of execution * * -»1-»A»-2-»B1»-3 * * Whose stack is: * * +---+----+---+ * |1,A|2,B1|3,-| * +---+----+---+ * * With C selected, we get to * * +---+----+---+ * |1,A|2,B1|3,C| + cycleTo 0 * +---+----+---+ * * @throws Exception */ @Test public void testDoublePathDiscovery() throws Exception { BProgram bprog = new StringBProgram( // "bp.registerBThread(\"round\", function(){\n" + " while( true ) {\n" + " bp.sync({request:bp.Event(\"A\")});\n" + " bp.sync({waitFor:[bp.Event(\"B1\"), bp.Event(\"B2\")]});\n" + " bp.sync({request:bp.Event(\"C\")});\n" + " }\n" + "});\n" + "\n" + "bp.registerBThread(\"round-s1\", function(){\n" + " while( true ) {\n" + " bp.sync({waitFor:bp.Event(\"A\")});\n" + " bp.sync({request:bp.Event(\"B1\"), waitFor:bp.Event(\"B2\")});\n" + " }\n" + "});\n" + "\n" + "bp.registerBThread(\"round-s2\", function(){\n" + " while( true ) {\n" + " bp.sync({waitFor:bp.Event(\"A\")});\n" + " bp.sync({request:bp.Event(\"B2\"), waitFor:bp.Event(\"B1\")});\n" + " }\n" + "});"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); final Set<String> foundTraces = new HashSet<>(); sut.addInspection( ExecutionTraceInspection.named("DFS trace captures", et->{ String eventTrace = et.getNodes().stream() .map( n->n.getEvent() ) .map( o->o.map(BEvent::getName).orElse("-") ) .collect( joining("") ); System.out.println("eventTrace = " + eventTrace); foundTraces.add(eventTrace); return Optional.empty(); })); sut.setProgressListener(new PrintDfsVerifierListener()); VerificationResult res = sut.verify(bprog); assertEquals(3, res.getScannedStatesCount()); assertEquals(4, res.getScannedEdgesCount()); Set<String> expected1 = new TreeSet<>(Arrays.asList("-","A-","AB1-","AB1C", "AB2-")); Set<String> expected2 = new TreeSet<>(Arrays.asList("-","A-","AB2-","AB2C", "AB1-")); String eventTraces = foundTraces.stream().sorted().collect( joining(", ") ); assertTrue("Traces don't match expected: " + eventTraces, foundTraces.equals(expected1) || foundTraces.equals(expected2) ); System.out.println("Event traces: " + eventTraces); } /** * Program graph is same as above, but state "3" is duplicated since a b-thread * holds the last event that happened in a variable. * * +------------«------------+ * | | * v +-»B1»--3'---»C»--+ * | | * -»1--»A»--2 * | | * ^ +-»B2»--3''--»C»--+ * | | * +------------«------------+ * * * * @throws Exception */ @Test public void testDoublePathWithVariablesDiscovery() throws Exception { BProgram bprog = new StringBProgram("doubleWithVar", // "bp.registerBThread(\"round\", function(){\n" + " var le=null;\n" + " while( true ) {\n" + " bp.sync({request:bp.Event(\"A\")});\n" + " le = bp.sync({waitFor:[bp.Event(\"B1\"), bp.Event(\"B2\")]});\n" + " bp.sync({request:bp.Event(\"C\")});\n" + " le=null;\n " + " }\n" + "});\n" + "\n" + "bp.registerBThread(\"round-s1\", function(){\n" + " while( true ) {\n" + " bp.sync({waitFor:bp.Event(\"A\")});\n" + " bp.sync({request:bp.Event(\"B1\"), waitFor:bp.Event(\"B2\")});\n" + " }\n" + "});\n" + "\n" + "bp.registerBThread(\"round-s2\", function(){\n" + " while( true ) {\n" + " bp.sync({waitFor:bp.Event(\"A\")});\n" + " bp.sync({request:bp.Event(\"B2\"), waitFor:bp.Event(\"B1\")});\n" + " }\n" + "});"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); final Set<String> foundTraces = new HashSet<>(); sut.addInspection( ExecutionTraceInspection.named("DFS trace captures", et->{ String eventTrace = et.getNodes().stream() .map( n->n.getEvent() ) .map( o->o.map(BEvent::getName).orElse("-") ) .collect( joining("") ); System.out.println("eventTrace = " + eventTrace); foundTraces.add(eventTrace); return Optional.empty(); })); sut.setVisitedStateStore( new BProgramSnapshotVisitedStateStore() ); sut.setProgressListener(new PrintDfsVerifierListener()); VerificationResult res = sut.verify(bprog); assertEquals(4, res.getScannedStatesCount()); assertEquals(5, res.getScannedEdgesCount()); Set<String> expectedTraces = new TreeSet<>(Arrays.asList("-","A-","AB1-","AB1C","AB2-","AB2C")); assertEquals("Traces don't match expected: " + foundTraces, expectedTraces, foundTraces ); } @Test public void testJavaScriptError() throws Exception { BProgram bprog = new StringBProgram( "bp.registerBThread( function(){\n" + " bp.sync({request:bp.Event(\"A\")});\n" + " bp.sync({request:bp.Event(\"A\")});\n" + " bp.sync({request:bp.Event(\"A\")});\n" + " var myNullVar;\n" + " myNullVar.isNullAndSoThisInvocationShouldCrash();\n" + " bp.sync({request:bp.Event(\"A\")});\n" + "});" ); final AtomicBoolean errorCalled = new AtomicBoolean(); final AtomicBoolean errorMadeSense = new AtomicBoolean(); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setProgressListener(new DfsBProgramVerifier.ProgressListener() { @Override public void started(DfsBProgramVerifier vfr) {} @Override public void iterationCount(long count, long statesHit, DfsBProgramVerifier vfr) {} @Override public void maxTraceLengthHit(ExecutionTrace aTrace, DfsBProgramVerifier vfr) {} @Override public void done(DfsBProgramVerifier vfr) {} @Override public boolean violationFound(Violation aViolation, DfsBProgramVerifier vfr) { errorCalled.set(aViolation instanceof JsErrorViolation ); JsErrorViolation jsev = (JsErrorViolation) aViolation; errorMadeSense.set(jsev.decsribe().contains("isNullAndSoThisInvocationShouldCrash")); System.out.println(jsev.getThrownException().getMessage()); return true; } }); sut.verify( bprog ); assertTrue( errorCalled.get() ); assertTrue( errorMadeSense.get() ); } /** * Test that even with forgetful storage, a circular trace does not get * use to an infinite run. * @throws java.lang.Exception */ @Test//(timeout=6000) public void testCircularTraceDetection_forgetfulStorage() throws Exception { String bprog = "bp.registerBThread(function(){\n" + "while (true) {\n" + " bp.sync({request:bp.Event(\"X\")});" + " bp.sync({request:bp.Event(\"Y\")});" + " bp.sync({request:bp.Event(\"Z\")});" + " bp.sync({request:bp.Event(\"W\")});" + " bp.sync({request:bp.Event(\"A\")});" + " bp.sync({request:bp.Event(\"B\")});" + "}" + "});"; DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setVisitedStateStore( new ForgetfulVisitedStateStore() ); final AtomicInteger cycleToIndex = new AtomicInteger(Integer.MAX_VALUE); final AtomicReference<String> lastEventName = new AtomicReference<>(); sut.addInspection(ExecutionTraceInspection.named("Cycle", t->{ if ( t.isCyclic() ) { cycleToIndex.set( t.getCycleToIndex() ); lastEventName.set( t.getLastEvent().get().getName() ); System.out.println(TestUtils.traceEventNamesString(t, ", ")); } return Optional.empty(); })); VerificationResult res = sut.verify(new StringBProgram(bprog)); System.out.println("states: " + res.getScannedStatesCount()); assertEquals( 0, cycleToIndex.get() ); assertEquals( "B", lastEventName.get() ); } @Test public void testThreadStorageEquality() throws Exception { BProgram program = new ResourceBProgram("hotColdThreadMonitor.js"); DfsBProgramVerifier sut = new DfsBProgramVerifier(); sut.setProgressListener(new PrintDfsVerifierListener()); VisitedStateStore stateStore = new BThreadSnapshotVisitedStateStore(); sut.setVisitedStateStore(stateStore); VerificationResult res = sut.verify(program); assertEquals( 9, res.getScannedStatesCount() ); assertEquals( 9, stateStore.getVisitedStateCount() ); } }
mit
sivasamyk/graylog2-plugin-input-httpmonitor
src/main/java/org/graylog2/plugin/httpmonitor/HttpMonitorInputModule.java
892
package org.graylog2.plugin.httpmonitor; import org.graylog2.plugin.PluginConfigBean; import org.graylog2.plugin.PluginModule; import java.util.Collections; import java.util.Set; /** * Extend the PluginModule abstract class here to add you plugin to the system. */ public class HttpMonitorInputModule extends PluginModule { /** * Returns all configuration beans required by this plugin. * * Implementing this method is optional. The default method returns an empty {@link Set}. */ // @Override // public Set<? extends PluginConfigBean> getConfigBeans() { // return Collections.emptySet(); // } @Override protected void configure() { installTransport(transportMapBinder(),"http-monitor-transport",HttpMonitorTransport.class); installInput(inputsMapBinder(), HttpMonitorInput.class, HttpMonitorInput.Factory.class); } }
mit
picopalette/event-me
app/src/main/java/io/picopalette/apps/event_me/Utils/ImageBehaviour.java
4149
package io.picopalette.apps.event_me.Utils; import android.annotation.SuppressLint; import android.content.Context; import android.support.design.widget.CoordinatorLayout; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.view.View; import com.facebook.drawee.view.SimpleDraweeView; import io.picopalette.apps.event_me.R; /** * Created by Aswin Sundar on 14-06-2017. */ public class ImageBehaviour extends CoordinatorLayout.Behavior<SimpleDraweeView> { private final static float MIN_AVATAR_PERCENTAGE_SIZE = 0.3f; private final static int EXTRA_FINAL_AVATAR_PADDING = 80; private final static String TAG = "behavior"; private final Context mContext; private float mAvatarMaxSize; private float mFinalLeftAvatarPadding; private float mStartPosition; private int mStartXPosition; private float mStartToolbarPosition; public ImageBehaviour(Context context, AttributeSet attrs) { mContext = context; init(); mFinalLeftAvatarPadding = context.getResources().getDimension(R.dimen.activity_horizontal_margin); } private void init() { bindDimensions(); } private void bindDimensions() { mAvatarMaxSize = mContext.getResources().getDimension(R.dimen.image_width); } private int mStartYPosition; private int mFinalYPosition; private int finalHeight; private int mStartHeight; private int mFinalXPosition; @Override public boolean layoutDependsOn(CoordinatorLayout parent, SimpleDraweeView child, View dependency) { return dependency instanceof Toolbar; } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, SimpleDraweeView child, View dependency) { maybeInitProperties(child, dependency); final int maxScrollDistance = (int) (mStartToolbarPosition - getStatusBarHeight()); float expandedPercentageFactor = dependency.getY() / maxScrollDistance; float distanceYToSubtract = ((mStartYPosition - mFinalYPosition) * (1f - expandedPercentageFactor)) + (child.getHeight()/2); float distanceXToSubtract = ((mStartXPosition - mFinalXPosition) * (1f - expandedPercentageFactor)) + (child.getWidth()/2); float heightToSubtract = ((mStartHeight - finalHeight) * (1f - expandedPercentageFactor)); child.setY(mStartYPosition - distanceYToSubtract); child.setX(mStartXPosition - distanceXToSubtract); int proportionalAvatarSize = (int) (mAvatarMaxSize * (expandedPercentageFactor)); CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams(); lp.width = (int) (mStartHeight - heightToSubtract); lp.height = (int) (mStartHeight - heightToSubtract); child.setLayoutParams(lp); return true; } @SuppressLint("PrivateResource") private void maybeInitProperties(SimpleDraweeView child, View dependency) { if (mStartYPosition == 0) mStartYPosition = (int) (dependency.getY()); if (mFinalYPosition == 0) mFinalYPosition = (dependency.getHeight() /2); if (mStartHeight == 0) mStartHeight = child.getHeight(); if (finalHeight == 0) finalHeight = mContext.getResources().getDimensionPixelOffset(R.dimen.image_small_width); if (mStartXPosition == 0) mStartXPosition = (int) (child.getX() + (child.getWidth() / 2)); if (mFinalXPosition == 0) mFinalXPosition = mContext.getResources().getDimensionPixelOffset(R.dimen.abc_action_bar_content_inset_material) + (finalHeight / 2); if (mStartToolbarPosition == 0) mStartToolbarPosition = dependency.getY() + (dependency.getHeight()/2); } public int getStatusBarHeight() { int result = 0; int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = mContext.getResources().getDimensionPixelSize(resourceId); } return result; } }
mit
acalvoa/GEA-FRAMEWORK
src/gea/api/Api.java
55
package gea.api; public class Api extends Thread{ }
mit
blinkboxbooks/android-app
app/src/main/java/com/blinkboxbooks/android/authentication/BBBAuthenticator.java
6858
// Copyright (c) 2014 blinkbox Entertainment Limited. All rights reserved. package com.blinkboxbooks.android.authentication; import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.accounts.NetworkErrorException; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import com.blinkboxbooks.android.api.BBBApiConstants; import com.blinkboxbooks.android.api.model.BBBTokenResponse; import com.blinkboxbooks.android.api.net.BBBRequest; import com.blinkboxbooks.android.api.net.BBBRequestFactory; import com.blinkboxbooks.android.api.net.BBBRequestManager; import com.blinkboxbooks.android.api.net.BBBResponse; import com.blinkboxbooks.android.controller.AccountController; import com.blinkboxbooks.android.ui.account.LoginActivity; import com.blinkboxbooks.android.util.LogUtils; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; /** * Implementation of AbstractAccountAuthenticator. Subclasses only need to override the getLaunchAuthenticatorActivityIntent() method to return an Intent which will launch * an Activity which is a subclass of AccountAuthenticatorActivity */ public class BBBAuthenticator extends AbstractAccountAuthenticator { private static final String TAG = BBBAuthenticator.class.getSimpleName(); private final Context mContext; public BBBAuthenticator(Context context) { super(context); mContext = context; } /** * {inheritDoc} */ public Bundle addAccount(AccountAuthenticatorResponse accountAuthenticatorResponse, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { Intent intent = new Intent(mContext, LoginActivity.class); intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse); Bundle bundle = new Bundle(); bundle.putParcelable(AccountManager.KEY_INTENT, intent); return bundle; } /** * {inheritDoc} */ public Bundle confirmCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, Bundle options) throws NetworkErrorException { return null; } /** * {inheritDoc} */ public Bundle editProperties(AccountAuthenticatorResponse accountAuthenticatorResponse, String accountType) { throw new UnsupportedOperationException(); } /** * {inheritDoc} */ public Bundle getAuthToken(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String authTokenType, Bundle options) throws NetworkErrorException { AccountManager am = AccountManager.get(mContext); //first check to see if we already have an access token in the AccountManager cache String accessToken = am.peekAuthToken(account, authTokenType); if (accessToken != null) { Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); result.putString(AccountManager.KEY_AUTHTOKEN, accessToken); return result; } //if we don't have a valid access token we try and get a new one with the refresh token String refreshToken = am.getUserData(account, BBBApiConstants.PARAM_REFRESH_TOKEN); String clientId = am.getUserData(account, BBBApiConstants.PARAM_CLIENT_ID); String clientSecret = am.getUserData(account, BBBApiConstants.PARAM_CLIENT_SECRET); if (!TextUtils.isEmpty(refreshToken)) { BBBRequest request = BBBRequestFactory.getInstance().createGetRefreshAuthTokenRequest(refreshToken, clientId, clientSecret); BBBResponse response = BBBRequestManager.getInstance().executeRequestSynchronously(request); if (response == null) { throw new NetworkErrorException("Could not get auth token with refresh token"); } String json = response.getResponseData(); BBBTokenResponse authenticationResponse = null; if (json != null) { try { authenticationResponse = new Gson().fromJson(json, BBBTokenResponse.class); } catch (JsonSyntaxException e) { LogUtils.d(TAG, e.getMessage(), e); } } if (authenticationResponse != null) { accessToken = authenticationResponse.access_token; refreshToken = authenticationResponse.refresh_token; if (!TextUtils.isEmpty(accessToken)) { Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, BBBApiConstants.AUTHTOKEN_TYPE); result.putString(AccountManager.KEY_AUTHTOKEN, authenticationResponse.access_token); AccountController.getInstance().setAccessToken(account, accessToken); AccountController.getInstance().setRefreshToken(account, refreshToken); return result; } } } //if we can't get an access token via the cache or by using the refresh token we must return an Intent which will launch an Activity allowing the user to perform manual authentication Intent intent = new Intent(mContext, LoginActivity.class); intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse); intent.putExtra(BBBApiConstants.PARAM_USERNAME, account.name); intent.putExtra(BBBApiConstants.PARAM_AUTHTOKEN_TYPE, authTokenType); Bundle bundle = new Bundle(); bundle.putParcelable(AccountManager.KEY_INTENT, intent); return bundle; } /** * {inheritDoc} */ public String getAuthTokenLabel(String authTokenType) { //we don't need to display the authTokenType in the account manager so we return null return null; } /** * {inheritDoc} */ public Bundle hasFeatures(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String[] features) throws NetworkErrorException { Bundle result = new Bundle(); result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false); return result; } /** * {inheritDoc} */ public Bundle updateCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String authTokenType, Bundle options) throws NetworkErrorException { return null; } }
mit
iseki-masaya/spongycastle
prov/src/test/java/org/spongycastle/pqc/jcajce/provider/test/McElieceKobaraImaiCipherTest.java
1060
package org.spongycastle.pqc.jcajce.provider.test; import java.security.KeyPairGenerator; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.Cipher; import org.spongycastle.pqc.jcajce.spec.ECCKeyGenParameterSpec; public class McElieceKobaraImaiCipherTest extends AsymmetricHybridCipherTest { protected void setUp() { super.setUp(); try { kpg = KeyPairGenerator.getInstance("McElieceKobaraImai"); cipher = Cipher.getInstance("McElieceKobaraImaiWithSHA256"); } catch (Exception e) { e.printStackTrace(); } } /** * Test encryption and decryption performance for SHA256 message digest and parameters * m=11, t=50. */ public void testEnDecryption_SHA256_11_50() throws Exception { // initialize key pair generator AlgorithmParameterSpec kpgParams = new ECCKeyGenParameterSpec(11, 50); kpg.initialize(kpgParams); performEnDecryptionTest(1, 10, 32, null); } }
mit
hinogi/eternalwinterwars
src/com/github/scaronthesky/eternalwinterwars/view/entities/IMeasureableEntity.java
160
package com.github.scaronthesky.eternalwinterwars.view.entities; public interface IMeasureableEntity { public float getWidth(); public float getHeight(); }
mit
daniel-beck/sorcerer
javac/src/main/java/com/sun/source/util/TaskEvent.java
3433
/* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.source.util; import com.sun.source.tree.CompilationUnitTree; import javax.lang.model.element.TypeElement; import javax.tools.JavaFileObject; /** * Provides details about work that has been done by the Sun Java Compiler, javac. * * @author Jonathan Gibbons * @since 1.6 */ public final class TaskEvent { /** * Kind of task event. * @since 1.6 */ public enum Kind { /** * For events related to the parsing of a file. */ PARSE, /** * For events relating to elements being entered. **/ ENTER, /** * For events relating to elements being analyzed for errors. **/ ANALYZE, /** * For events relating to class files being generated. **/ GENERATE, /** * For events relating to overall annotaion processing. **/ ANNOTATION_PROCESSING, /** * For events relating to an individual annotation processing round. **/ ANNOTATION_PROCESSING_ROUND }; public TaskEvent(Kind kind) { this(kind, null, null, null); } public TaskEvent(Kind kind, JavaFileObject sourceFile) { this(kind, sourceFile, null, null); } public TaskEvent(Kind kind, CompilationUnitTree unit) { this(kind, unit.getSourceFile(), unit, null); } public TaskEvent(Kind kind, CompilationUnitTree unit, TypeElement clazz) { this(kind, unit.getSourceFile(), unit, clazz); } private TaskEvent(Kind kind, JavaFileObject file, CompilationUnitTree unit, TypeElement clazz) { this.kind = kind; this.file = file; this.unit = unit; this.clazz = clazz; } public Kind getKind() { return kind; } public JavaFileObject getSourceFile() { return file; } public CompilationUnitTree getCompilationUnit() { return unit; } public TypeElement getTypeElement() { return clazz; } public String toString() { return "TaskEvent[" + kind + "," + file + "," // the compilation unit is identified by the file + clazz + "]"; } private Kind kind; private JavaFileObject file; private CompilationUnitTree unit; private TypeElement clazz; }
mit
way2muchnoise/refinedstorage
src/main/java/com/raoulvdberge/refinedstorage/block/enums/ControllerType.java
557
package com.raoulvdberge.refinedstorage.block.enums; import net.minecraft.util.IStringSerializable; public enum ControllerType implements IStringSerializable { NORMAL(0, "normal"), CREATIVE(1, "creative"); private int id; private String name; ControllerType(int id, String name) { this.id = id; this.name = name; } @Override public String getName() { return name; } public int getId() { return id; } @Override public String toString() { return name; } }
mit
nayan92/ic-hack
OpenOMR/openomr/omr_engine/XProjection.java
4106
/*************************************************************************** * Copyright (C) 2006 by Arnaud Desaedeleer * * arnaud@desaedeleer.com * * * * This file is part of OpenOMR * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ package openomr.omr_engine; import java.awt.image.BufferedImage; /** * The <code> XProjection </code> class will calculate the X-Projection of an image. The constructor * is given a <code> BufferedImage </code> and then the <code> calcXProjection </method> is invoked * to calculate the X-Projection of the <code> BufferedImage </code>. * <p> * The <code> XProjection </code> class is used as follows: * <p> * <code> * XProjection xProj = new XProjection(BufferedImage); <br> * xProj.calcXProjection(startH, endH, startW, endW); <br> * </code> * <p> * Calling the <code> calcXProjection </code> method will place the X-Projection of the <code> BufferedImage </code> * in a int[] array which can be obtained by calling the <code> getYProjection </code> method. * <p> * * @author Arnaud Desaedeleer * @version 1.0 */ public class XProjection { private int xProjection[]; private int size; private BufferedImage buffImage; public XProjection(BufferedImage buffImage) { this.buffImage = buffImage; } /** * Cacluate the X-Projection of the BufferedImage * @param startH Desired start Y-Coordinate of the BufferedImage * @param endH Desired end Y-Coordinate of the BufferedImage * @param startW Desired start X-Coordinate of the BufferedImage * @param endW Desired end X-Coordinate of the BufferedImage */ public void calcXProjection(int startH, int endH, int startW, int endW) { int size = Math.abs(endW - startW) + 1; //System.out.println("Size: " + size); this.size = size; xProjection = new int[size]; for (int i = startW; i < endW; i += 1) { for (int j = startH; j < endH; j += 1) { int color = 0; try { color = buffImage.getRGB(i, j); } catch (ArrayIndexOutOfBoundsException e) { } if (color != -1) //if black pixel { xProjection[i-startW] += 1; } } } } /** * Returns the resulting X-Projection of the BufferedImage * @return xProjection */ public int[] getXProjection() { return xProjection; } /** * Prints the X-Projection of the BufferedImage * */ public void printXProjection() { System.out.println("X Projection"); for (int i=0; i<size; i+=1) { System.out.println(xProjection[i]); } System.out.println("END X Projection"); } }
mit
selvasingh/azure-sdk-for-java
sdk/eventgrid/mgmt-v2020_04_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2020_04_01_preview/NumberGreaterThanOrEqualsAdvancedFilter.java
1359
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.eventgrid.v2020_04_01_preview; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * NumberGreaterThanOrEquals Advanced Filter. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "operatorType", defaultImpl = NumberGreaterThanOrEqualsAdvancedFilter.class) @JsonTypeName("NumberGreaterThanOrEquals") public class NumberGreaterThanOrEqualsAdvancedFilter extends AdvancedFilter { /** * The filter value. */ @JsonProperty(value = "value") private Double value; /** * Get the filter value. * * @return the value value */ public Double value() { return this.value; } /** * Set the filter value. * * @param value the value value to set * @return the NumberGreaterThanOrEqualsAdvancedFilter object itself. */ public NumberGreaterThanOrEqualsAdvancedFilter withValue(Double value) { this.value = value; return this; } }
mit
maesse/DerpStream
src/derpstream/ChunkInfo.java
5842
package derpstream; import java.io.FileOutputStream; import java.io.IOException; import java.util.PriorityQueue; import java.util.TimerTask; import java.util.concurrent.LinkedBlockingDeque; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Mads */ public final class ChunkInfo extends TimerTask { private static final Logger LOGGER = Logger.getLogger("derpstream"); private static final int BUFFER_PIECES = 3; private final StreamInfo streamInfo; private final DerpStream derpStream; // Template for generating chunk links private final String chunkPath; private final LinkedBlockingDeque<Piece> pieceQueue = new LinkedBlockingDeque<>(); private final PriorityQueue<Piece> bufferedPieces = new PriorityQueue<>(); private long nextPieceTime; // when next piece becomes available private int maxValidPiece; // maximum valid piece that can be requested private int writePiece; // next piece to be written to disk. private final Object waitObj = new Object(); ChunkInfo(DerpStream derpStream, StreamInfo streamInfo) throws IOException { this.streamInfo = streamInfo; this.derpStream = derpStream; // Download chunklist LOGGER.info("Getting latest chunklist..."); String chunkList = DerpStream.downloadString(streamInfo.getChunkInfoPath()); if(!DerpStream.isM3U(chunkList)) throw new IllegalStateException("Invalid chunklist: " + chunkList); // Parse current chunk index String search = "#EXT-X-MEDIA-SEQUENCE:"; int start = chunkList.indexOf(search) + search.length(); int end = chunkList.indexOf("\n", start); maxValidPiece = Integer.parseInt(chunkList.substring(start, end)); writePiece = maxValidPiece - BUFFER_PIECES; LOGGER.info("Ok. Stream is at piece " + maxValidPiece + "\n"); // Figure out chunkPath template String[] lines = chunkList.split("\n"); String chunkPath = null; for (String line : lines) { if(!line.startsWith("#")) { if(line.contains(""+maxValidPiece)) { chunkPath = line.replace("" + maxValidPiece, "%d"); LOGGER.info("Setting chunkpath: " + chunkPath); break; } } } if(chunkPath == null) throw new IllegalStateException("Couldn't find chunkPath"); this.chunkPath = chunkPath; // Enqueue valid pieces for (int i = 0; i < BUFFER_PIECES; i++) { pieceQueue.add(makePiece(writePiece+i)); } // 10 seconds to next piece becomes available nextPieceTime = System.currentTimeMillis() + 10000; } // Increments the piece counter for every 10 seconds since start. public void updatePiece() { long time = System.currentTimeMillis(); while(time >= nextPieceTime) { nextPieceTime += 10000; pieceQueue.add(makePiece(maxValidPiece)); DerpStreamCallbacks callbacks = derpStream.getCallbacks(); if(callbacks != null) { callbacks.pieceAvailable(maxValidPiece); } maxValidPiece++; } } public String getChunkPath() { return String.format(chunkPath, writePiece); } private Piece makePiece(int index) { return new Piece(index, String.format(chunkPath, index)); } @Override public void run() { // Update pieces updatePiece(); } void lostPiece(Piece p) { synchronized(bufferedPieces) { bufferedPieces.add(p); } synchronized(waitObj) { waitObj.notify(); } } public void registerPiece(Piece p) { synchronized(bufferedPieces) { bufferedPieces.add(p); } synchronized(waitObj) { waitObj.notify(); } } public Piece grabWork() throws InterruptedException { return pieceQueue.takeFirst(); } void startWriting(FileOutputStream fos) throws IOException { DerpStreamCallbacks callbacks = derpStream.getCallbacks(); while(derpStream.isRunning()) { // Write data to the file as it becomes available. synchronized(bufferedPieces) { while(bufferedPieces.size() > 0) { Piece topPiece = bufferedPieces.peek(); // Not what we're looking for? if(topPiece.pieceIndex != writePiece) break; // Grab it! Piece removedPiece = bufferedPieces.poll(); // Check it! if(removedPiece != topPiece) throw new RuntimeException("Huh?"); if(topPiece.data != null) { LOGGER.fine("Writing " + topPiece); // Write it! fos.getChannel().write(topPiece.data); if(callbacks != null) { callbacks.finishedWriting(topPiece.pieceIndex); } } else { LOGGER.warning("Skipping " + topPiece); if(callbacks != null) { callbacks.skippedWriting(topPiece.pieceIndex); } } writePiece++; } } synchronized(waitObj) { try { waitObj.wait(5000); } catch (InterruptedException ex) { } } } } }
mit
honjow/XDroidMvp_hzw
app/src/main/java/cn/honjow/leanc/ui/Fragment/ChoQueListFragment.java
1611
package cn.honjow.leanc.ui.Fragment; import cn.honjow.leanc.adapter.QuestionListAdapter; import cn.honjow.leanc.ui.Activice.ChoQueActivity; import cn.droidlover.xdroidmvp.base.SimpleRecAdapter; import cn.honjow.leanc.model.QuestionItem; import cn.honjow.leanc.ui.BaseLeancFragment; import cn.droidlover.xrecyclerview.RecyclerItemCallback; import cn.droidlover.xrecyclerview.XRecyclerView; /** * Created by honjow311 on 2017/5/17. */ public class ChoQueListFragment extends BaseLeancFragment { QuestionListAdapter adapter; @Override public SimpleRecAdapter getAdapter() { if (adapter == null) { adapter = new QuestionListAdapter(context); adapter.setRecItemClick(new RecyclerItemCallback<QuestionItem, QuestionListAdapter.ViewHolder>() { @Override public void onItemClick(int position, QuestionItem model, int tag, QuestionListAdapter.ViewHolder holder) { super.onItemClick(position, model, tag, holder); switch (tag) { case QuestionListAdapter.TAG_VIEW: ChoQueActivity.launch(context, model); break; } } }); } return adapter; } @Override public void setLayoutManager(XRecyclerView recyclerView) { recyclerView.verticalLayoutManager(context); } @Override public String getType() { return "1"; } public static ChoQueListFragment newInstance() { return new ChoQueListFragment(); } }
mit
joshiejack/Progression
src/main/java/joshie/progression/api/gui/ICustomDrawGuiDisplay.java
449
package joshie.progression.api.gui; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /** Implement this on rewards, triggers, filters, conditions, * if you wish to draw something special on them, other than default fields. */ public interface ICustomDrawGuiDisplay { @SideOnly(Side.CLIENT) public void drawDisplay(IDrawHelper helper, int renderX, int renderY, int mouseX, int mouseY); }
mit
i3l/NuTrack
src/edu/gatech/nutrack/Home.java
2842
package edu.gatech.nutrack; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.support.v4.app.NavUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class Home extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.home, menu); return true; } public void callScan(View view) { Intent callScanIntent = new Intent(this, NutritionixActivity.class); startActivity(callScanIntent); } public void callTrack(View view) { Intent callTrackIntent = new Intent(this, Track.class); startActivity(callTrackIntent); } public void callSync(View view) { Intent callSyncIntent = new Intent(this, Sync.class); startActivity(callSyncIntent); } public void callReco(View view) { Intent callRecoIntent = new Intent(this, Reco.class); startActivity(callRecoIntent); } public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpFromSameTask(this); return true; case R.id.action_scan: Intent callScanIntent = new Intent(this, NutritionixActivity.class); startActivity(callScanIntent); return true; case R.id.action_track: Intent callTrackIntent = new Intent(this, Track.class); startActivity(callTrackIntent); return true; case R.id.action_reco: Intent callReco = new Intent(this, Track.class); startActivity(callReco); return true; case R.id.action_nutrition_info: Intent callNutritionInfo = new Intent(this, Track.class); startActivity(callNutritionInfo); return true; case R.id.action_log_out: callLogout(item.getActionView()); return true; default: return super.onOptionsItemSelected(item); } } // log out. Every activity should have this method! public void callLogout(View view) { Intent callLoginIntent = new Intent(this, Login.class); startActivity(callLoginIntent); } }
mit
incentivetoken/offspring
com.dgex.offspring.nxtCore/src/com/dgex/offspring/nxtCore/service/IAccount.java
1085
package com.dgex.offspring.nxtCore.service; import java.util.List; import nxt.Account; import nxt.Alias; import nxt.Block; import nxt.Transaction; import com.dgex.offspring.nxtCore.core.TransactionHelper.IteratorAsList; public interface IAccount { public Account getNative(); public Long getId(); public String getStringId(); public long getBalance(); public long getUnconfirmedBalance(); public long getAssetBalance(Long assetId); public long getUnconfirmedAssetBalance(Long assetId); public String getPrivateKey(); public byte[] getPublicKey(); public List<ITransaction> getTransactions(); public List<Transaction> getNativeTransactions(); public List<Alias> getNativeAliases(); public List<Block> getForgedBlocks(); public List<IAlias> getAliases(); public List<IMessage> getMessages(); public List<IAsset> getIssuedAssets(); public int getForgedFee(); public boolean startForging(); public boolean stopForging(); public boolean isForging(); public boolean isReadOnly(); IteratorAsList getUserTransactions(); }
mit
fvasquezjatar/fermat-unused
fermat-api/src/main/java/com/bitdubai/fermat_api/layer/dmp_basic_wallet/common/enums/BalanceType.java
574
package com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.enums; /** * Created by natalia on 06/07/15. */ public enum BalanceType { AVAILABLE("AVAILABLE"), BOOK("BOOK"); private final String code; BalanceType(String code) { this.code = code; } public String getCode() { return this.code ; } public static BalanceType getByCode(String code) { switch (code) { case "BOOK": return BOOK; case "AVAILABLE": return AVAILABLE; default: return AVAILABLE; } } }
mit
jgnan/edu
android/AndroidTutorial/app/src/main/java/org/shenit/tutorial/android/HelloWorldActivity.java
353
package org.shenit.tutorial.android; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class HelloWorldActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hello_world); } }
mit
open-sinovoice/sinovoice-pathfinder
Pathfinder/src/com/sinovoice/pathfinder/hcicloud/hwr/HciCloudHwrHelper.java
1907
package com.sinovoice.pathfinder.hcicloud.hwr; import android.content.Context; import android.util.Log; import com.sinovoice.hcicloudsdk.api.hwr.HciCloudHwr; import com.sinovoice.hcicloudsdk.common.hwr.HwrInitParam; import com.sinovoice.pathfinder.hcicloud.sys.SysConfig; public class HciCloudHwrHelper { private static final String TAG = HciCloudHwrHelper.class.getSimpleName(); private static HciCloudHwrHelper mInstance; private HciCloudHwrHelper() { } public static HciCloudHwrHelper getInstance() { if (mInstance == null) { mInstance = new HciCloudHwrHelper(); } return mInstance; } /** * HWRÊÖдʶ±ðÄÜÁ¦³õʼ»¯£¬·µ»ØµÄ´íÎóÂë¿ÉÒÔÔÚAPIÖÐHciErrorCode²é¿´ * * @param context * @return ´íÎóÂë, return 0 ±íʾ³É¹¦ */ public int init(Context context) { int initResult = 0; // ¹¹ÔìHwr³õʼ»¯µÄ²ÎÊýÀàµÄʵÀý HwrInitParam hwrInitParam = new HwrInitParam(); // »ñÈ¡AppÓ¦ÓÃÖеÄlibµÄ·¾¶,Èç¹ûʹÓÃ/data/data/pkgName/libϵÄ×ÊÔ´Îļþ,ÐèÒªÌí¼Óandroid_soµÄ±ê¼Ç String hwrDirPath = context.getFilesDir().getAbsolutePath() .replace("files", "lib"); hwrInitParam.addParam(HwrInitParam.PARAM_KEY_DATA_PATH, hwrDirPath); hwrInitParam.addParam(HwrInitParam.PARAM_KEY_FILE_FLAG, "android_so"); hwrInitParam.addParam(HwrInitParam.PARAM_KEY_INIT_CAP_KEYS, SysConfig.CAPKEY_HWR); Log.d(TAG, "hwr init config: " + hwrInitParam.getStringConfig()); // HWR ³õʼ»¯ initResult = HciCloudHwr.hciHwrInit(hwrInitParam.getStringConfig()); return initResult; } /** * HWRÊÖдʶ±ðÄÜÁ¦·´³õʼ»¯£¬·µ»ØµÄ´íÎóÂë¿ÉÒÔÔÚAPIÖÐHciErrorCode²é¿´ * * @return ´íÎóÂë, return 0 ±íʾ³É¹¦ */ public int release() { int result = HciCloudHwr.hciHwrRelease(); return result; } }
mit
javagl/Flow
flow-gui/src/main/java/de/javagl/flow/gui/Shapes.java
4028
/* * www.javagl.de - Flow * * Copyright (c) 2012-2017 Marco Hutter - http://www.javagl.de * * 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 de.javagl.flow.gui; import java.awt.Shape; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.util.ArrayList; import java.util.List; /** * Utility methods related to shapes */ class Shapes { /** * Create a list containing line segments that approximate the given * shape. * * NOTE: Copied from https://github.com/javagl/Geom/blob/master/ * src/main/java/de/javagl/geom/Shapes.java * * @param shape The shape * @param flatness The allowed flatness * @return The list of line segments */ public static List<Line2D> computeLineSegments( Shape shape, double flatness) { List<Line2D> result = new ArrayList<Line2D>(); PathIterator pi = shape.getPathIterator(null, flatness); double[] coords = new double[6]; double previous[] = new double[2]; double first[] = new double[2]; while (!pi.isDone()) { int segment = pi.currentSegment(coords); switch (segment) { case PathIterator.SEG_MOVETO: previous[0] = coords[0]; previous[1] = coords[1]; first[0] = coords[0]; first[1] = coords[1]; break; case PathIterator.SEG_CLOSE: result.add(new Line2D.Double( previous[0], previous[1], first[0], first[1])); previous[0] = first[0]; previous[1] = first[1]; break; case PathIterator.SEG_LINETO: result.add(new Line2D.Double( previous[0], previous[1], coords[0], coords[1])); previous[0] = coords[0]; previous[1] = coords[1]; break; case PathIterator.SEG_QUADTO: // Should never occur throw new AssertionError( "SEG_QUADTO in flattened path!"); case PathIterator.SEG_CUBICTO: // Should never occur throw new AssertionError( "SEG_CUBICTO in flattened path!"); default: // Should never occur throw new AssertionError( "Invalid segment in flattened path!"); } pi.next(); } return result; } /** * Private constructor to prevent instantiation */ private Shapes() { // Private constructor to prevent instantiation } }
mit
fluted0g/Mr.Fartman
core/src/net/ausiasmarch/fartman/util/AudioManager.java
1784
package net.ausiasmarch.fartman.util; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; /** * AudioManager.java * Gestiona la musica y sonidos * @author Luis * */ public class AudioManager { /** Administrador de audio */ public static final AudioManager instance = new AudioManager(); /** Musica reproduciendose*/ private Music playingMusic; /** singleton: previene la instanciacion desde otras clases */ private AudioManager () { } /** Reproduce sonido */ public void play (Sound sound) { play(sound, 1); } /** Reproduce sonido */ public void play (Sound sound, float volume) { play(sound, volume, 1); } /** Reproduce sonido */ public void play (Sound sound, float volume, float pitch) { play(sound, volume, pitch, 0); } /** Reproduce sonido */ public void play (Sound sound, float volume, float pitch, float pan) { if (!GamePreferences.instance.sound) return; sound.play(volume, pitch, pan); } /** Reproduce musica */ public void play(Music music){ play(music, 1); } /** Reproduce musica */ public void play (Music music, float volume) { stopMusic(); playingMusic = music; if (GamePreferences.instance.music) { music.setLooping(true); music.setVolume(volume); music.play(); } } /** Para la musica */ public void stopMusic () { if (playingMusic != null) playingMusic.stop(); } /** Obtiene la musica que se esta reproduciendo */ public Music getPlayingMusic () { return playingMusic; } /** Reproduce/pausa la musica segun el archivo de preferencias */ public void onSettingsUpdated () { if (playingMusic == null) return; if (GamePreferences.instance.music) { if (!playingMusic.isPlaying()) playingMusic.play(); } else { playingMusic.pause(); } } }
mit
ajil/Java-Patterns
src/main/java/creationalPattern/builder/ColdDrink.java
192
package creationalPattern.builder; public abstract class ColdDrink implements Item { public Packing packing() { return new Bottle(); } public abstract float price(); }
mit
lfmendivelso10/GescoFinal
DSL/co.edu.uniandes.mono.gesco.ui/src-gen/co/edu/uniandes/mono/gesco/ui/contentassist/antlr/PartialDSLContentAssistParser.java
1288
/* * generated by Xtext */ package co.edu.uniandes.mono.gesco.ui.contentassist.antlr; import java.util.Collection; import java.util.Collections; import org.eclipse.xtext.AbstractRule; import org.eclipse.xtext.ui.codetemplates.ui.partialEditing.IPartialContentAssistParser; import org.eclipse.xtext.ui.editor.contentassist.antlr.FollowElement; import org.eclipse.xtext.ui.editor.contentassist.antlr.internal.AbstractInternalContentAssistParser; import org.eclipse.xtext.util.PolymorphicDispatcher; /** * @author Sebastian Zarnekow - Initial contribution and API */ @SuppressWarnings("restriction") public class PartialDSLContentAssistParser extends DSLParser implements IPartialContentAssistParser { private AbstractRule rule; public void initializeFor(AbstractRule rule) { this.rule = rule; } @Override protected Collection<FollowElement> getFollowElements(AbstractInternalContentAssistParser parser) { if (rule == null || rule.eIsProxy()) return Collections.emptyList(); String methodName = "entryRule" + rule.getName(); PolymorphicDispatcher<Collection<FollowElement>> dispatcher = new PolymorphicDispatcher<Collection<FollowElement>>(methodName, 0, 0, Collections.singletonList(parser)); dispatcher.invoke(); return parser.getFollowElements(); } }
mit
Thaenor/magnetic-and-electric-forces-study
src/selector/Barra.java
659
package selector; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.util.EventObject; class Barra implements AdjustmentListener { SelectorApplet applet; public Barra(SelectorApplet applet) { this.applet = applet; } public void adjustmentValueChanged(AdjustmentEvent e) { Object obj = e.getSource(); if (obj == this.applet.sbElectrico) this.applet.sbElectrico_adjustmentValueChanged(e); else if (obj == this.applet.sbMagnetico) this.applet.sbMagnetico_adjustmentValueChanged(e); else this.applet.sbVelocidad_adjustmentValueChanged(e); } }
mit
dwing4g/luaj
src/org/luaj/vm2/Print.java
10612
package org.luaj.vm2; import java.io.ByteArrayOutputStream; import java.io.PrintStream; /** * Debug helper class to pretty-print lua bytecodes. * @see Prototype * @see LuaClosure */ public class Print extends Lua { /** opcode names */ private static final String STRING_FOR_NULL = "null"; private static final String[] OPNAMES = { "MOVE", "LOADK", "LOADBOOL", "LOADNIL", "GETUPVAL", "GETGLOBAL", "GETTABLE", "SETGLOBAL", "SETUPVAL", "SETTABLE", "NEWTABLE", "SELF", "ADD", "SUB", "MUL", "DIV", "MOD", "POW", "UNM", "NOT", "LEN", "CONCAT", "JMP", "EQ", "LT", "LE", "TEST", "TESTSET", "CALL", "TAILCALL", "RETURN", "FORLOOP", "FORPREP", "TFORLOOP", "SETLIST", "CLOSE", "CLOSURE", "VARARG", }; static void printString(PrintStream ps, LuaString s) { ps.print('"'); for(int i = 0, n = s._length; i < n; i++) { int c = s._bytes[s._offset + i]; if(c >= ' ' && c <= '~' && c != '\"' && c != '\\') ps.print((char)c); else { switch(c) { case '"': ps.print("\\\""); break; case '\\': ps.print("\\\\"); break; case 0x0007: /* bell */ ps.print("\\a"); break; case '\b': /* backspace */ ps.print("\\b"); break; case '\f': /* form feed */ ps.print("\\f"); break; case '\t': /* tab */ ps.print("\\t"); break; case '\r': /* carriage return */ ps.print("\\r"); break; case '\n': /* newline */ ps.print("\\n"); break; case 0x000B: /* vertical tab */ ps.print("\\v"); break; default: ps.print('\\'); ps.print(Integer.toString(1000 + 0xff & c).substring(1)); break; } } } ps.print('"'); } static void printValue(PrintStream ps, LuaValue v) { switch(v.type()) { case LuaValue.TSTRING: printString(ps, (LuaString)v); break; default: ps.print(v.tojstring()); } } static void printConstant(PrintStream ps, Prototype f, int i) { printValue(ps, f.k[i]); } /** * Print the code in a prototype * @param f the {@link Prototype} */ public static void printCode(PrintStream ps, Prototype f) { int[] code = f.code; int pc, n = code.length; for(pc = 0; pc < n; pc++) { printOpCode(ps, f, pc); ps.println(); } } /** * Print an opcode in a prototype * @param ps the {@link PrintStream} to print to * @param f the {@link Prototype} * @param pc the program counter to look up and print */ public static void printOpCode(PrintStream ps, Prototype f, int pc) { int[] code = f.code; int i = code[pc]; int o = GET_OPCODE(i); int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); int bx = GETARG_Bx(i); int sbx = GETARG_sBx(i); int line = getline(f, pc); ps.print(" " + (pc + 1) + " "); if(line > 0) ps.print("[" + line + "] "); else ps.print("[-] "); ps.print(OPNAMES[o] + " "); switch(getOpMode(o)) { case iABC: ps.print(a); if(getBMode(o) != OpArgN) ps.print(" " + (ISK(b) ? (-1 - INDEXK(b)) : b)); if(getCMode(o) != OpArgN) ps.print(" " + (ISK(c) ? (-1 - INDEXK(c)) : c)); break; case iABx: if(getBMode(o) == OpArgK) { ps.print(a + " " + (-1 - bx)); } else { ps.print(a + " " + (bx)); } break; case iAsBx: if(o == OP_JMP) ps.print(sbx); else ps.print(a + " " + sbx); break; } switch(o) { case OP_LOADK: ps.print(" ; "); printConstant(ps, f, bx); break; case OP_GETUPVAL: case OP_SETUPVAL: ps.print(" ; "); if(f.upvalues.length > b) printValue(ps, f.upvalues[b]); else ps.print("-"); break; case OP_GETGLOBAL: case OP_SETGLOBAL: ps.print(" ; "); printConstant(ps, f, bx); break; case OP_GETTABLE: case OP_SELF: if(ISK(c)) { ps.print(" ; "); printConstant(ps, f, INDEXK(c)); } break; case OP_SETTABLE: case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_POW: case OP_EQ: case OP_LT: case OP_LE: if(ISK(b) || ISK(c)) { ps.print(" ; "); if(ISK(b)) printConstant(ps, f, INDEXK(b)); else ps.print("-"); ps.print(" "); if(ISK(c)) printConstant(ps, f, INDEXK(c)); else ps.print("-"); } break; case OP_JMP: case OP_FORLOOP: case OP_FORPREP: ps.print(" ; to " + (sbx + pc + 2)); break; case OP_CLOSURE: ps.print(" ; " + f.p[bx].getClass().getName()); break; case OP_SETLIST: if(c == 0) ps.print(" ; " + code[++pc]); else ps.print(" ; " + c); break; case OP_VARARG: ps.print(" ; is_vararg=" + f.is_vararg); break; default: break; } } private static int getline(Prototype f, int pc) { return pc > 0 && f.lineinfo != null && pc < f.lineinfo.length ? f.lineinfo[pc] : -1; } static void printHeader(PrintStream ps, Prototype f) { String s = String.valueOf(f.source); if(s.startsWith("@") || s.startsWith("=")) s = s.substring(1); else if("\033Lua".equals(s)) s = "(bstring)"; else s = "(string)"; String a = (f.linedefined == 0) ? "main" : "function"; ps.print("\n%" + a + " <" + s + ":" + f.linedefined + "," + f.lastlinedefined + "> (" + f.code.length + " instructions, " + f.code.length * 4 + " bytes at " + id() + ")\n"); ps.print(f.numparams + " param, " + f.maxstacksize + " slot, " + f.upvalues.length + " upvalue, "); ps.print(f.locvars.length + " local, " + f.k.length + " constant, " + f.p.length + " function\n"); } static void printConstants(PrintStream ps, Prototype f) { int i, n = f.k.length; ps.print("constants (" + n + ") for " + id() + ":\n"); for(i = 0; i < n; i++) { ps.print(" " + (i + 1) + " "); printValue(ps, f.k[i]); ps.print("\n"); } } static void printLocals(PrintStream ps, Prototype f) { int i, n = f.locvars.length; ps.print("locals (" + n + ") for " + id() + ":\n"); for(i = 0; i < n; i++) { ps.println(" " + i + " " + f.locvars[i]._varname + " " + (f.locvars[i]._startpc + 1) + " " + (f.locvars[i]._endpc + 1)); } } static void printUpValues(PrintStream ps, Prototype f) { int i, n = f.upvalues.length; ps.print("upvalues (" + n + ") for " + id() + ":\n"); for(i = 0; i < n; i++) { ps.print(" " + i + " " + f.upvalues[i] + "\n"); } } public static void print(PrintStream ps, Prototype p) { printFunction(ps, p, true); } public static void printFunction(PrintStream ps, Prototype f, boolean full) { int i, n = f.p.length; printHeader(ps, f); printCode(ps, f); if(full) { printConstants(ps, f); printLocals(ps, f); printUpValues(ps, f); } for(i = 0; i < n; i++) printFunction(ps, f.p[i], full); } private static void format(PrintStream ps, String s, int maxcols) { int n = s.length(); if(n > maxcols) ps.print(s.substring(0, maxcols)); else { ps.print(s); for(int i = maxcols - n; --i >= 0;) ps.print(' '); } } private static String id() { return "Proto"; } /** * Print the state of a {@link LuaClosure} that is being executed * @param cl the {@link LuaClosure} * @param pc the program counter * @param stack the stack of {@link LuaValue} * @param top the top of the stack * @param varargs any {@link Varargs} value that may apply */ public static void printState(LuaClosure cl, int pc, LuaValue[] stack, int top, Varargs varargs) { // print opcode into buffer ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); printOpCode(ps, cl._p, pc); ps.flush(); ps.close(); ps = System.out; format(ps, baos.toString(), 50); // print stack ps.print('['); for(int i = 0; i < stack.length; i++) { LuaValue v = stack[i]; if(v == null) ps.print(STRING_FOR_NULL); else switch(v.type()) { case LuaValue.TSTRING: LuaString s = v.checkstring(); ps.print(s.length() < 48 ? s.tojstring() : s.substring(0, 32).tojstring() + "...+" + (s.length() - 32) + "b"); break; case LuaValue.TFUNCTION: ps.print((v instanceof LuaClosure) ? ((LuaClosure)v)._p.toString() : v.tojstring()); break; case LuaValue.TUSERDATA: Object o = v.touserdata(); if(o != null) { String n = o.getClass().getName(); n = n.substring(n.lastIndexOf('.') + 1); ps.print(n + ": " + Integer.toHexString(o.hashCode())); } else { ps.print(v.toString()); } break; default: ps.print(v.tojstring()); } if(i + 1 == top) ps.print(']'); ps.print(" | "); } ps.print(varargs); ps.println(); } }
mit
WiQuery/wiquery
wiquery-jquery-ui/src/test/java/org/odlabs/wiquery/ui/resizable/ResizableBehaviorTestCase.java
10375
/* * Copyright (c) 2009 WiQuery team * * 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 org.odlabs.wiquery.ui.resizable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.Panel; import org.junit.Before; import org.junit.Test; import org.odlabs.wiquery.core.options.LiteralOption; import org.odlabs.wiquery.tester.WiQueryTestCase; import org.odlabs.wiquery.ui.DivTestPanel; import org.odlabs.wiquery.ui.resizable.ResizableContainment.ElementEnum; /** * Test on {@link ResizableBehavior} * * @author Julien Roche */ public class ResizableBehaviorTestCase extends WiQueryTestCase { // Properties private ResizableBehavior resizableBehavior; @Override @Before public void setUp() { super.setUp(); resizableBehavior = new ResizableBehavior(); Panel panel = new DivTestPanel("panelId"); WebMarkupContainer component = new WebMarkupContainer("anId"); component.setMarkupId("anId"); component.add(resizableBehavior); panel.add(component); tester.startComponentInPage(panel); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#destroy()} * . */ @Test public void testDestroy() { assertNotNull(resizableBehavior.destroy()); assertEquals(resizableBehavior.destroy().render().toString(), "$('#anId').resizable('destroy');"); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#disable()} * . */ @Test public void testDisable() { assertNotNull(resizableBehavior.disable()); assertEquals(resizableBehavior.disable().render().toString(), "$('#anId').resizable('disable');"); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#enable()}. */ @Test public void testEnable() { assertNotNull(resizableBehavior.enable()); assertEquals(resizableBehavior.enable().render().toString(), "$('#anId').resizable('enable');"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getAlsoResizeComplex()} . */ @Test public void testGetAlsoResizeComplex() { assertNull(resizableBehavior.getAlsoResizeComplex()); resizableBehavior.setAlsoResize(new ResizableAlsoResize(new LiteralOption("div"))); assertNotNull(resizableBehavior.getAlsoResizeComplex()); assertEquals(resizableBehavior.getAlsoResizeComplex().getJavascriptOption().toString(), "'div'"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getAnimateEasing()} . */ @Test public void testGetAnimateEasing() { assertEquals(resizableBehavior.getAnimateEasing(), "swing"); resizableBehavior.setAnimateEasing("slide"); assertEquals(resizableBehavior.getAnimateEasing(), "slide"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getAnimateDuration()} . */ @Test public void testGetAnimateDuration() { assertNotNull(resizableBehavior.getAnimateDuration()); assertEquals(resizableBehavior.getAnimateDuration().getJavascriptOption().toString(), "'slow'"); resizableBehavior.setAnimateDuration(new ResizableAnimeDuration(1000)); assertEquals(resizableBehavior.getAnimateDuration().getJavascriptOption().toString(), "1000"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getAspectRatio()} . */ @Test public void testGetAspectRatio() { assertNull(resizableBehavior.getAspectRatio()); resizableBehavior.setAspectRatio(new ResizableAspectRatio(true)); assertNotNull(resizableBehavior.getAspectRatio()); assertEquals(resizableBehavior.getAspectRatio().getJavascriptOption().toString(), "true"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getCancel()}. */ @Test public void testGetCancel() { assertEquals(resizableBehavior.getCancel(), "input,option"); resizableBehavior.setCancel("input"); assertEquals(resizableBehavior.getCancel(), "input"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getContainment()} . */ @Test public void testGetContainment() { assertNull(resizableBehavior.getContainment()); resizableBehavior.setContainment(new ResizableContainment(ElementEnum.PARENT)); assertNotNull(resizableBehavior.getContainment()); assertEquals(resizableBehavior.getContainment().getJavascriptOption().toString(), "'parent'"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getDelay()}. */ @Test public void testGetDelay() { assertEquals(resizableBehavior.getDelay(), 0); resizableBehavior.setDelay(5); assertEquals(resizableBehavior.getDelay(), 5); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getDistance()}. */ @Test public void testGetDistance() { assertEquals(resizableBehavior.getDistance(), 1); resizableBehavior.setDistance(5); assertEquals(resizableBehavior.getDistance(), 5); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getGrid()} * . */ @Test public void testGetGrid() { assertNull(resizableBehavior.getGrid()); resizableBehavior.setGrid(5, 6); assertNotNull(resizableBehavior.getGrid()); assertEquals(resizableBehavior.getGrid().getJavascriptOption().toString(), "[5,6]"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getHandles()}. */ @Test public void testGetHandles() { assertNotNull(resizableBehavior.getHandles()); assertEquals(resizableBehavior.getHandles().getJavascriptOption().toString(), "'e,s,se'"); resizableBehavior.setHandles(new ResizableHandles(new LiteralOption("e,s"))); assertEquals(resizableBehavior.getHandles().getJavascriptOption().toString(), "'e,s'"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getHelper()}. */ @Test public void testGetHelper() { assertNull(resizableBehavior.getHelper()); resizableBehavior.setHelper(".aClass"); assertEquals(resizableBehavior.getHelper(), ".aClass"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getMaxHeight()}. */ @Test public void testGetMaxHeight() { assertEquals(resizableBehavior.getMaxHeight(), 0); resizableBehavior.setMaxHeight(100); assertEquals(resizableBehavior.getMaxHeight(), 100); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getMaxWidth()}. */ @Test public void testGetMaxWidth() { assertEquals(resizableBehavior.getMaxWidth(), 0); resizableBehavior.setMaxWidth(100); assertEquals(resizableBehavior.getMaxWidth(), 100); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getMinHeight()}. */ @Test public void testGetMinHeight() { assertEquals(resizableBehavior.getMinHeight(), 10); resizableBehavior.setMinHeight(100); assertEquals(resizableBehavior.getMinHeight(), 100); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getMinWidth()}. */ @Test public void testGetMinWidth() { assertEquals(resizableBehavior.getMinWidth(), 10); resizableBehavior.setMinWidth(100); assertEquals(resizableBehavior.getMinWidth(), 100); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getOptions()}. */ @Test public void testGetOptions() { assertNotNull(resizableBehavior.getOptions()); assertEquals(resizableBehavior.getOptions().getJavaScriptOptions().toString(), "{}"); resizableBehavior.setAnimate(true); assertEquals(resizableBehavior.getOptions().getJavaScriptOptions().toString(), "{animate: true}"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#isAnimate()}. */ @Test public void testIsAnimate() { assertFalse(resizableBehavior.isAnimate()); resizableBehavior.setAnimate(true); assertTrue(resizableBehavior.isAnimate()); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#isAutoHide()}. */ @Test public void testIsAutoHide() { assertFalse(resizableBehavior.isAutoHide()); resizableBehavior.setAutoHide(true); assertTrue(resizableBehavior.isAutoHide()); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#isDisabled()}. */ @Test public void testIsDisabled() { assertFalse(resizableBehavior.isDisabled()); resizableBehavior.setDisabled(true); assertTrue(resizableBehavior.isDisabled()); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#isGhost()} * . */ @Test public void testIsGhost() { assertFalse(resizableBehavior.isGhost()); resizableBehavior.setGhost(true); assertTrue(resizableBehavior.isGhost()); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#widget()}. */ @Test public void testWidget() { assertNotNull(resizableBehavior.widget()); assertEquals(resizableBehavior.widget().render().toString(), "$('#anId').resizable('widget');"); } }
mit
sherxon/AlgoDS
src/contests/Solution2.java
639
package contests; /** * Created by sherxon on 2/27/17. */ public class Solution2 { public static void main(String[] args) { } static public String shortestPalindrome(String s) { if (s.length() <= 1) return s; char[] a = s.toCharArray(); StringBuilder sb = new StringBuilder(); int i = 0; int j = a.length - 1; while (i < j) { if (a[j] == a[i]) { j--; i++; } else { i = 0; } } System.out.println(s.substring(0, i)); return sb.toString() + s.substring(i); } }
mit
adamjcook/cs27500
exam1/problem15/Sequence.java
646
import java.lang.IndexOutOfBoundsException; public interface Sequence { public int size(); // Return number of elements in sequence. public void addFirst(int e); // Insert e at the front of the sequence. public void addLast(int e); // Insert e at the back of the sequence. // Inserts an element e to be at index i. public void add(int i, int e) throws IndexOutOfBoundsException; // Returns the element at index i, without removing it. public int get(int i) throws IndexOutOfBoundsException; // Removes and returns the element at index i. public int remove(int i) throws IndexOutOfBoundsException; }
mit
ticketmaster-api/ticketmaster-api.github.io
tests/serenity/src/test/java/com/tkmdpa/taf/definitions/pantheon/UserAccountDefinition.java
1145
package com.tkmdpa.taf.definitions.pantheon; import com.tkmdpa.taf.steps.pantheon.UserAccountSteps; import net.thucydides.core.annotations.Steps; import org.jbehave.core.annotations.Given; import org.jbehave.core.annotations.Then; import org.jbehave.core.annotations.When; public class UserAccountDefinition { @Steps UserAccountSteps userAccountPage; @When("navigate to Pantheon Edit Profile page from User Account page") public void navigateToEditProfile(){ userAccountPage.navigateToEditProfilePage(); } @Given("navigate to Pantheon Add New App page from User Account page") @When("navigate to Pantheon Add New App page from User Account page") public void navigateToAddNewApp(){ userAccountPage.navigateToAddNewAppPage(); } @Given("all the applications were deleted") public void allAppsWereDeleted(){ userAccountPage.deleteAllApps(); } @Then("check general page elements for Pantheon User Account page") public void checkGeneralPageElements(){ userAccountPage.checkIfTitleIsCorrect(); userAccountPage.checkGeneralPageElements(); } }
mit
blnz/palomar
src/main/java/com/blnz/xsl/expr/CurrentFunction.java
874
// $Id: CurrentFunction.java 96 2005-02-28 21:07:29Z blindsey $ package com.blnz.xsl.expr; import com.blnz.xsl.om.*; /** * Represents the XSLT Function: node-set current() * * The current function returns a node-set that has the * current node as its only member. For an outermost * expression (an expression not occurring within * another expression), the current node is always the same * as the context node. Thus, */ class CurrentFunction extends Function0 { ConvertibleExpr makeCallExpr() { return new ConvertibleNodeSetExpr() { public NodeIterator eval(Node node, ExprContext context) throws XSLException { return new SingleNodeIterator(context.getCurrent(node)); } }; } }
mit
CMPUT301F17T20/Habitivity
app/src/main/java/main/habitivity/services/ConnectivityService.java
1916
package main.habitivity.services; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * Created by Shally on 2017-12-01. */ public class ConnectivityService implements IConnectivityService { private Context context; private OnConnectivityChangedListener onConnectivityChangedListener; /** * Instantiates a new Android connectivity service. * * @param context the context */ public ConnectivityService(Context context) { this.context = context; registerConnectivityListener(); } @Override public boolean isInternetAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } @Override public void setOnConnectivityChangedListener(OnConnectivityChangedListener onConnectivityChangedListener) { this.onConnectivityChangedListener = onConnectivityChangedListener; dispatchConnectivityChange(); } private void registerConnectivityListener() { context.registerReceiver(new ConnectivityListener(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } private void dispatchConnectivityChange() { if (onConnectivityChangedListener != null) { onConnectivityChangedListener.onConnectivityChanged(isInternetAvailable()); } } private class ConnectivityListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { dispatchConnectivityChange(); } } }
mit
Haehnchen/idea-php-shopware-plugin
src/main/java/de/espend/idea/shopware/reference/provider/StringReferenceProvider.java
1454
package de.espend.idea.shopware.reference.provider; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiPolyVariantReferenceBase; import com.intellij.psi.ResolveResult; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import de.espend.idea.shopware.ShopwarePluginIcons; import de.espend.idea.shopware.util.ShopwareUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public class StringReferenceProvider extends PsiPolyVariantReferenceBase<PsiElement> { final private String[] values; public StringReferenceProvider(StringLiteralExpression stringLiteralExpression, String... values) { super(stringLiteralExpression); this.values = values; } @NotNull @Override public ResolveResult[] multiResolve(boolean b) { return new ResolveResult[0]; } @NotNull @Override public Object[] getVariants() { final List<LookupElement> lookupElements = new ArrayList<>(); for(String value: values) { lookupElements.add(LookupElementBuilder.create(ShopwareUtil.toCamelCase(value, true)) .withIcon(ShopwarePluginIcons.SHOPWARE) ); } return lookupElements.toArray(); } }
mit
SkullTech/algorithms-princeton
Algorithms/src/sorting/MergeBU.java
1193
package com.algorithms.sorting; public class MergeBU { public static void sort(Comparable[] a) { Comparable[] aux = new Comparable[a.length]; int N = a.length; for (int size = 1; size < N; size = size*2) { for (int i = 0; i < N; i = i + size) merge(a, aux, i, i+size-1, Math.min(i+size+size-1, N-1)); } } private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) { assert isSorted(a, lo, mid); assert isSorted(a, mid+1, hi); for (int i = lo; i < hi; i++) aux[i] = a[i]; int i = lo, j = mid + 1; for (int k = lo; k < hi; k ++) { if (i > mid) a[k] = aux[j++]; else if (j > hi) a[k] = aux[i++]; if (less(aux[j], aux[i])) a[k] = aux[j++]; else a[k] = aux[i++]; } assert isSorted(a, lo, hi); } private static boolean isSorted(Comparable[] a, int lo, int hi) { for (int i = lo; i < hi; i ++) { if (less(a[i+1], a[i])) return false; } return true; } }
mit
saipjayanthi23/Fundoo-Tots
app/src/main/java/projects/oss2015/cs/fundookid/Colors.java
3586
/* Copyright (c) 2015 Sai Jayanthi This source file is licensed under the "MIT license". Please see the file COPYING in this distribution for license terms. */ /* This program provides the functionality to implement sound and swipe features for Colors activity */ package projects.oss2015.cs.fundookid; import android.content.Intent; import android.media.MediaPlayer; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.Toast; public class Colors extends ActionBarActivity { public static MediaPlayer mpCheer,mpAww,mpBlueHat; float x1,x2,y1,y2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_colors); mpCheer= MediaPlayer.create(this, R.raw.cheering); mpAww= MediaPlayer.create(this, R.raw.aww); mpBlueHat=MediaPlayer.create(this,R.raw.bluehat); mpBlueHat.start(); } public boolean onTouchEvent(MotionEvent touchevent) { switch (touchevent.getAction()) { case MotionEvent.ACTION_DOWN: { x1 = touchevent.getX(); y1 = touchevent.getY(); break; } case MotionEvent.ACTION_UP: { x2 = touchevent.getX(); y2 = touchevent.getY(); //if left to right swipe event on screen if (x1 < x2) { if(mpCheer.isPlaying()) mpCheer.stop(); Intent i = new Intent(this,MainActivity.class); startActivity(i); } //if right to left swipe event on screen if (x1 > x2) { if(mpCheer.isPlaying()) mpCheer.stop(); Intent i = new Intent(this,Shoes.class); startActivity(i); } break; } } return false; } public void onClickBlueHat(View view){ if(mpAww.isPlaying() || mpAww.isLooping()) { mpAww.stop(); mpAww= MediaPlayer.create(this, R.raw.aww); } mpCheer.start(); } public void onClickRedHat(View view){ if(mpCheer.isPlaying() || mpCheer.isLooping()) { mpCheer.stop(); mpCheer= MediaPlayer.create(this, R.raw.cheering); } mpAww.start(); } public void onClickYellowHat(View view){ if(mpCheer.isPlaying() || mpCheer.isLooping()) { mpCheer.stop(); mpCheer= MediaPlayer.create(this, R.raw.cheering); } mpAww.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_colors, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
mit
EDACC/edacc_api
src/edacc/parameterspace/domain/IntegerDomain.java
3522
package edacc.parameterspace.domain; import java.util.LinkedList; import java.util.List; import java.util.Random; @SuppressWarnings("serial") public class IntegerDomain extends Domain { protected Integer low, high; public static final String name = "Integer"; @SuppressWarnings("unused") private IntegerDomain() { } public IntegerDomain(Integer low, Integer high) { this.low = low; this.high = high; } @Override public boolean contains(Object value) { if (!(value instanceof Number)) return false; double d = ((Number)value).doubleValue(); if (d != Math.round(d)) return false; return d >= this.low && d <= this.high; } @Override public Object randomValue(Random rng) { return rng.nextInt(this.high - this.low + 1) + this.low; } @Override public String toString() { return "[" + this.low + "," + this.high + "]"; } public Integer getLow() { return low; } public void setLow(Integer low) { this.low = low; } public Integer getHigh() { return high; } public void setHigh(Integer high) { this.high = high; } @Override public Object mutatedValue(Random rng, Object value) { return mutatedValue(rng, value, 0.1f); } @Override public Object mutatedValue(Random rng, Object value, float stdDevFactor) { if (!contains(value)) return value; double r = rng.nextGaussian() * ((high - low) * stdDevFactor); return (int) Math.min(Math.max(this.low, Math.round(((Number)value).doubleValue() + r)), this.high); } @Override public List<Object> getDiscreteValues() { List<Object> values = new LinkedList<Object>(); for (int i = this.low; i <= this.high; i++) { values.add(i); } return values; } @Override public String getName() { return name; } @Override public List<Object> getGaussianDiscreteValues(Random rng, Object value, float stdDevFactor, int numberSamples) { if (numberSamples == 1) { List<Object> singleVals = new LinkedList<Object>(); singleVals.add(mutatedValue(rng, value, stdDevFactor)); return singleVals; } if (numberSamples >= (high - low + 1)) { return getDiscreteValues(); } List<Object> vals = new LinkedList<Object>(); for (int i = 0; i < numberSamples; i++) { if (vals.size() == high - low + 1) break; // sampled all possible values Object val = null; int tries = 0; while ((val == null || vals.contains(val)) && tries++ < (high - low + 1)) { val = mutatedValue(rng, value, stdDevFactor); } vals.add(mutatedValue(rng, value, stdDevFactor)); } return vals; } @Override public List<Object> getUniformDistributedValues(int numberSamples) { if (numberSamples >= (high - low + 1)) { return getDiscreteValues(); } List<Object> vals = new LinkedList<Object>(); double dist = (high - low) / (double) (numberSamples-1); double cur = low; for (int i = 0; i < numberSamples; i++) { if (vals.size() == high - low + 1) break; vals.add(new Integer((int) Math.round(cur))); cur += dist; } return vals; } @Override public Object getMidValueOrNull(Object o1, Object o2) { if (!(o1 instanceof Integer) || !(o2 instanceof Integer)) { return null; } Integer i1 = (Integer)o1; Integer i2 = (Integer)o2; Integer mid = (i1 + i2) / 2; if (i1.equals(mid) || i2.equals(mid)) { return null; } return mid; } }
mit
marmotka/Java-Exercises-Basics
Tests/src/TestSea6Task1.java
831
public class TestSea6Task1 { public static void main(String[] args) { String text = "Sun is shining. Today is a good day for test. Sun is shining. The students are happy. The birds are blue."; int indexSent = -1; int lengthSen = 0; int counterSen = 0; int indexLast = 0; int maxLengthSen = 0; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) >= 'A' && text.charAt(i) <= 'Z') { counterSen++; lengthSen = i - indexLast; indexLast = i; } if (i == text.length() - 1) { lengthSen = text.length() - 1 - indexLast; } if (maxLengthSen < lengthSen) { maxLengthSen = lengthSen; indexSent = indexLast - maxLengthSen; } } String sentence = text.substring(indexSent, indexSent + maxLengthSen); System.out.println(sentence); System.out.println(counterSen); } }
mit
guwek/HuGS
hugs/support/ScoreParameter.java
451
package hugs.support; import hugs.*; public class ScoreParameter extends Parameter { public Score value; public ScoreParameter (String name) { this(name,null);} public ScoreParameter (String name, Score value) { super(name); this.value = value; } public Object getValue () {return value;} public Parameter copy () { return new ScoreParameter(name, (value == null ? null : value.copy())); } }
mit
riteshakya037/Subs
presentation/src/main/java/com/riteshakya/subs/views/screens/login/LoginPresenter.java
859
package com.riteshakya.subs.views.screens.login; import android.content.Intent; import android.support.v4.app.FragmentActivity; import com.google.android.gms.common.api.GoogleApiClient; import com.riteshakya.subs.mvp.FlowListener; import com.riteshakya.subs.mvp.IPresenter; import com.riteshakya.subs.mvp.IView; import com.riteshakya.subs.mvp.FlowListener; import com.riteshakya.subs.mvp.IPresenter; import com.riteshakya.subs.mvp.IView; /** * @author Ritesh Shakya */ public interface LoginPresenter extends IPresenter { void setView(LoginView loginView); void initialize(); void validateResult(Intent data); GoogleApiClient getGoogleApiClient(); interface LoginFlowListener extends FlowListener { void openMainActivity(); } interface LoginView extends IView { FragmentActivity getActivity(); } }
mit
EricHyh/FileDownloader
lib-common/src/main/java/com/hyh/common/picasso/PicassoExecutorService.java
4271
/* * Copyright (C) 2013 Square, 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.hyh.common.picasso; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * The default {@link java.util.concurrent.ExecutorService} used for new {@link NativePicasso} instances. * <p> * Exists as a custom type so that we can differentiate the use of defaults versus a user-supplied * instance. */ class PicassoExecutorService extends ThreadPoolExecutor { private static final int DEFAULT_THREAD_COUNT = 3; PicassoExecutorService() { super(DEFAULT_THREAD_COUNT, DEFAULT_THREAD_COUNT, 0, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), new Utils.PicassoThreadFactory()); } void adjustThreadCount(NetworkInfo info) { if (info == null || !info.isConnectedOrConnecting()) { setThreadCount(DEFAULT_THREAD_COUNT); return; } switch (info.getType()) { case ConnectivityManager.TYPE_WIFI: case ConnectivityManager.TYPE_WIMAX: case ConnectivityManager.TYPE_ETHERNET: setThreadCount(4); break; case ConnectivityManager.TYPE_MOBILE: switch (info.getSubtype()) { case TelephonyManager.NETWORK_TYPE_LTE: // 4G case TelephonyManager.NETWORK_TYPE_HSPAP: case TelephonyManager.NETWORK_TYPE_EHRPD: setThreadCount(3); break; case TelephonyManager.NETWORK_TYPE_UMTS: // 3G case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_EVDO_B: setThreadCount(2); break; case TelephonyManager.NETWORK_TYPE_GPRS: // 2G case TelephonyManager.NETWORK_TYPE_EDGE: setThreadCount(1); break; default: setThreadCount(DEFAULT_THREAD_COUNT); } break; default: setThreadCount(DEFAULT_THREAD_COUNT); } } private void setThreadCount(int threadCount) { setCorePoolSize(threadCount); setMaximumPoolSize(threadCount); } @Override public Future<?> submit(Runnable task) { PicassoFutureTask ftask = new PicassoFutureTask((BitmapHunter) task); execute(ftask); return ftask; } private static final class PicassoFutureTask extends FutureTask<BitmapHunter> implements Comparable<PicassoFutureTask> { private final BitmapHunter hunter; public PicassoFutureTask(BitmapHunter hunter) { super(hunter, null); this.hunter = hunter; } @Override public int compareTo(PicassoFutureTask other) { NativePicasso.Priority p1 = hunter.getPriority(); NativePicasso.Priority p2 = other.hunter.getPriority(); // High-priority requests are "lesser" so they are sorted to the front. // Equal priorities are sorted by sequence number to provide FIFO ordering. return (p1 == p2 ? hunter.sequence - other.hunter.sequence : p2.ordinal() - p1.ordinal()); } } }
mit
bcvsolutions/CzechIdMng
Realization/backend/core/core-impl/src/test/java/eu/bcvsolutions/idm/core/bulk/action/impl/IdentityDisableBulkActionTest.java
9528
package eu.bcvsolutions.idm.core.bulk.action.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.List; import java.util.Set; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.google.common.collect.Sets; import eu.bcvsolutions.idm.core.api.bulk.action.dto.IdmBulkActionDto; import eu.bcvsolutions.idm.core.api.domain.IdentityState; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto; import eu.bcvsolutions.idm.core.api.dto.IdmRoleDto; import eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityFilter; import eu.bcvsolutions.idm.core.api.exception.ForbiddenEntityException; import eu.bcvsolutions.idm.core.api.service.IdmIdentityService; import eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission; import eu.bcvsolutions.idm.core.model.entity.IdmIdentity; import eu.bcvsolutions.idm.core.notification.api.dto.IdmNotificationLogDto; import eu.bcvsolutions.idm.core.notification.api.dto.filter.IdmNotificationFilter; import eu.bcvsolutions.idm.core.notification.api.service.IdmNotificationLogService; import eu.bcvsolutions.idm.core.notification.entity.IdmEmailLog; import eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto; import eu.bcvsolutions.idm.core.scheduler.entity.IdmLongRunningTask; import eu.bcvsolutions.idm.core.security.api.domain.IdentityBasePermission; import eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission; import eu.bcvsolutions.idm.core.security.evaluator.task.SelfLongRunningTaskEvaluator; import eu.bcvsolutions.idm.test.api.AbstractBulkActionTest; /** * Integration test for {@link IdentityDisableBulkAction} * * @author Ondrej Kopr <kopr@xyxy.cz> * */ public class IdentityDisableBulkActionTest extends AbstractBulkActionTest { @Autowired private IdmIdentityService identityService; @Autowired private IdmNotificationLogService notificationLogService; private IdmIdentityDto loginIdentity; @Before public void login() { loginIdentity = this.createUserWithAuthorities(IdentityBasePermission.MANUALLYDISABLE, IdmBasePermission.READ); loginAsNoAdmin(loginIdentity.getUsername()); } @After public void logout() { super.logout(); } @Test public void processBulkActionByIds() { List<IdmIdentityDto> identities = this.createIdentities(5); for (IdmIdentityDto identity : identities) { assertTrue(identity.getState() != IdentityState.DISABLED_MANUALLY); } IdmBulkActionDto bulkAction = this.findBulkAction(IdmIdentity.class, IdentityDisableBulkAction.NAME); Set<UUID> ids = this.getIdFromList(identities); bulkAction.setIdentifiers(ids); IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, 5l, null, null); for (UUID id : ids) { IdmIdentityDto identityDto = identityService.get(id); assertNotNull(identityDto); assertTrue(identityDto.getState() == IdentityState.DISABLED_MANUALLY); } } @Test public void processBulkActionByFilter() { String testFirstName = "bulkActionFirstName" + System.currentTimeMillis(); List<IdmIdentityDto> identities = this.createIdentities(5); for (IdmIdentityDto identity : identities) { identity.setFirstName(testFirstName); identity = identityService.save(identity); assertTrue(identity.getState() != IdentityState.DISABLED_MANUALLY); } IdmIdentityFilter filter = new IdmIdentityFilter(); filter.setFirstName(testFirstName); List<IdmIdentityDto> checkIdentities = identityService.find(filter, null).getContent(); assertEquals(5, checkIdentities.size()); IdmBulkActionDto bulkAction = this.findBulkAction(IdmIdentity.class, IdentityDisableBulkAction.NAME); bulkAction.setTransformedFilter(filter); bulkAction.setFilter(toMap(filter)); IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, 5l, null, null); for (IdmIdentityDto identity : identities) { IdmIdentityDto dto = identityService.get(identity.getId()); assertNotNull(dto); assertTrue(dto.getState() == IdentityState.DISABLED_MANUALLY); } } @Test public void processBulkActionByFilterWithRemove() { String testLastName = "bulkActionLastName" + System.currentTimeMillis(); List<IdmIdentityDto> identities = this.createIdentities(5); IdmIdentityDto removedIdentity = identities.get(0); IdmIdentityDto removedIdentity2 = identities.get(1); for (IdmIdentityDto identity : identities) { identity.setLastName(testLastName); identity = identityService.save(identity); assertTrue(identity.getState() != IdentityState.DISABLED_MANUALLY); } IdmIdentityFilter filter = new IdmIdentityFilter(); filter.setLastName(testLastName); IdmBulkActionDto bulkAction = this.findBulkAction(IdmIdentity.class, IdentityDisableBulkAction.NAME); bulkAction.setTransformedFilter(filter); bulkAction.setFilter(toMap(filter)); bulkAction.setRemoveIdentifiers(Sets.newHashSet(removedIdentity.getId(), removedIdentity2.getId())); IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, 3l, null, null); for (IdmIdentityDto identity : identities) { IdmIdentityDto dto = identityService.get(identity.getId()); assertNotNull(dto); if (dto.getId().equals(removedIdentity.getId()) || dto.getId().equals(removedIdentity2.getId())) { assertTrue(dto.getState() != IdentityState.DISABLED_MANUALLY); continue; } assertTrue(dto.getState() == IdentityState.DISABLED_MANUALLY); } } @Test public void processBulkActionWithoutPermission() { // user hasn't permission for update identity IdmIdentityDto adminIdentity = this.createUserWithAuthorities(IdmBasePermission.READ); loginAsNoAdmin(adminIdentity.getUsername()); List<IdmIdentityDto> identities = this.createIdentities(5); for (IdmIdentityDto identity : identities) { assertTrue(identity.getState() != IdentityState.DISABLED_MANUALLY); } IdmBulkActionDto bulkAction = this.findBulkAction(IdmIdentity.class, IdentityDisableBulkAction.NAME); Set<UUID> ids = this.getIdFromList(identities); bulkAction.setIdentifiers(this.getIdFromList(identities)); IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, 0l, 0l, 5l); for (UUID id : ids) { IdmIdentityDto identityDto = identityService.get(id); assertNotNull(identityDto); assertTrue(identityDto.getState() != IdentityState.DISABLED_MANUALLY); } } @Test public void checkNotification() { List<IdmIdentityDto> identities = this.createIdentities(5); IdmBulkActionDto bulkAction = this.findBulkAction(IdmIdentity.class, IdentityDisableBulkAction.NAME); Set<UUID> ids = this.getIdFromList(identities); bulkAction.setIdentifiers(ids); IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, 5l, null, null); IdmNotificationFilter filter = new IdmNotificationFilter(); filter.setRecipient(loginIdentity.getUsername()); filter.setNotificationType(IdmEmailLog.class); List<IdmNotificationLogDto> notifications = notificationLogService.find(filter, null).getContent(); assertEquals(1, notifications.size()); IdmNotificationLogDto notificationLogDto = notifications.get(0); assertEquals(IdmEmailLog.NOTIFICATION_TYPE, notificationLogDto.getType()); assertTrue(notificationLogDto.getMessage().getHtmlMessage().contains(bulkAction.getName())); } @Test public void checkEvaluatorForLrt() { IdmIdentityDto identity = getHelper().createIdentity(); IdmRoleDto createRole = getHelper().createRole(); getHelper().createBasePolicy(createRole.getId(), CoreGroupPermission.IDENTITY, IdmIdentity.class, IdmBasePermission.READ, IdentityBasePermission.MANUALLYDISABLE); getHelper().createIdentityRole(identity, createRole); loginAsNoAdmin(identity.getUsername()); IdmBulkActionDto bulkAction = this.findBulkAction(IdmIdentity.class, IdentityDisableBulkAction.NAME); Set<UUID> ids = this.getIdFromList(this.createIdentities(5)); bulkAction.setIdentifiers(ids); IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); IdmLongRunningTaskDto lrt = checkResultLrt(processAction, 5l, null, null); try { longRunningTaskService.get(lrt.getId(), IdmBasePermission.READ); fail("User hasn't permission for read the long running task."); } catch (ForbiddenEntityException ex) { assertTrue(ex.getMessage().contains(lrt.getId().toString())); assertTrue(ex.getMessage().contains(IdmBasePermission.READ.toString())); } catch (Exception ex) { fail("Bad exception: " + ex.getMessage()); } // create authorization with SelfLongRunningTaskEvaluator getHelper().createAuthorizationPolicy(createRole.getId(), CoreGroupPermission.SCHEDULER, IdmLongRunningTask.class, SelfLongRunningTaskEvaluator.class, IdmBasePermission.READ); try { IdmLongRunningTaskDto longRunningTaskDto = longRunningTaskService.get(lrt.getId(), IdmBasePermission.READ); assertNotNull(longRunningTaskDto); assertEquals(lrt, longRunningTaskDto); } catch (ForbiddenEntityException ex) { fail("User has permission for read the long running task. " + ex.getMessage()); } catch (Exception ex) { fail("Bad exception: " + ex.getMessage()); } } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanagerhybrid/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/fluent/models/GalleryProperties.java
3142
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.compute.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.compute.models.GalleryIdentifier; import com.azure.resourcemanager.compute.models.GalleryPropertiesProvisioningState; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Describes the properties of a Shared Image Gallery. */ @Fluent public final class GalleryProperties { @JsonIgnore private final ClientLogger logger = new ClientLogger(GalleryProperties.class); /* * The description of this Shared Image Gallery resource. This property is * updatable. */ @JsonProperty(value = "description") private String description; /* * Describes the gallery unique name. */ @JsonProperty(value = "identifier") private GalleryIdentifier identifier; /* * The current state of the gallery. The provisioning state, which only * appears in the response. */ @JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY) private GalleryPropertiesProvisioningState provisioningState; /** * Get the description property: The description of this Shared Image Gallery resource. This property is updatable. * * @return the description value. */ public String description() { return this.description; } /** * Set the description property: The description of this Shared Image Gallery resource. This property is updatable. * * @param description the description value to set. * @return the GalleryProperties object itself. */ public GalleryProperties withDescription(String description) { this.description = description; return this; } /** * Get the identifier property: Describes the gallery unique name. * * @return the identifier value. */ public GalleryIdentifier identifier() { return this.identifier; } /** * Set the identifier property: Describes the gallery unique name. * * @param identifier the identifier value to set. * @return the GalleryProperties object itself. */ public GalleryProperties withIdentifier(GalleryIdentifier identifier) { this.identifier = identifier; return this; } /** * Get the provisioningState property: The current state of the gallery. The provisioning state, which only appears * in the response. * * @return the provisioningState value. */ public GalleryPropertiesProvisioningState provisioningState() { return this.provisioningState; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (identifier() != null) { identifier().validate(); } } }
mit
Azure/azure-sdk-for-java
sdk/avs/azure-resourcemanager-avs/src/main/java/com/azure/resourcemanager/avs/models/VirtualMachineRestrictMovementState.java
1489
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.avs.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for VirtualMachineRestrictMovementState. */ public final class VirtualMachineRestrictMovementState extends ExpandableStringEnum<VirtualMachineRestrictMovementState> { /** Static value Enabled for VirtualMachineRestrictMovementState. */ public static final VirtualMachineRestrictMovementState ENABLED = fromString("Enabled"); /** Static value Disabled for VirtualMachineRestrictMovementState. */ public static final VirtualMachineRestrictMovementState DISABLED = fromString("Disabled"); /** * Creates or finds a VirtualMachineRestrictMovementState from its string representation. * * @param name a name to look for. * @return the corresponding VirtualMachineRestrictMovementState. */ @JsonCreator public static VirtualMachineRestrictMovementState fromString(String name) { return fromString(name, VirtualMachineRestrictMovementState.class); } /** @return known VirtualMachineRestrictMovementState values. */ public static Collection<VirtualMachineRestrictMovementState> values() { return values(VirtualMachineRestrictMovementState.class); } }
mit
przodownikR1/hibernateKata
src/test/java/pl/java/scalatech/basic/SimpleBetterSpringSolutionDaoTest.java
2249
package pl.java.scalatech.basic; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.runners.MethodSorters.NAME_ASCENDING; import java.util.List; import java.util.Map; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.jdbc.JdbcTestUtils; import lombok.extern.slf4j.Slf4j; import pl.java.scalatech.config.JdbcConfig; import pl.java.scalatech.domain.basic.SimpleMessage; import pl.java.scalatech.repository.spring_jdbc.JdbcSimpleMessageDao; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { JdbcConfig.class, SimpleBetterSpringSolutionDaoTest.DaoConfig.class }) @FixMethodOrder(NAME_ASCENDING) @SqlDataAccount @ActiveProfiles("test") @Slf4j public class SimpleBetterSpringSolutionDaoTest { @Configuration @ComponentScan(basePackageClasses = JdbcSimpleMessageDao.class) static class DaoConfig {} @Autowired private JdbcSimpleMessageDao simpleDao; @Autowired private JdbcTemplate jdbcTemplate; private void retrieveObjects() { String selectQuery = "SELECT * from SimpleMessages"; List<Map<String, Object>> resultSet = jdbcTemplate.queryForList(selectQuery); resultSet.stream().forEach(record -> log.info("{}", record)); } private int countRowsInTable(String tableName) { return JdbcTestUtils.countRowsInTable(jdbcTemplate, tableName); } @Test public void shouldAutowiredDao(){ assertThat(simpleDao).isNotNull(); assertThat(jdbcTemplate).isNotNull(); } @Test public void shouldAddSomeRecord(){ simpleDao.add(SimpleMessage.builder().text("convenient way added record").build()); retrieveObjects(); assertThat(countRowsInTable("SimpleMessages")).isEqualTo(4); } }
mit
prl-tokyo/MAPE-controller
src/main/java/jp/ac/nii/prl/mape/controller/service/KnowledgeBaseService.java
277
package jp.ac.nii.prl.mape.controller.service; import jp.ac.nii.prl.mape.controller.model.MAPEKComponent; public interface KnowledgeBaseService { void put(MAPEKComponent kb, String bx, String view, String param); String get(MAPEKComponent kb, String bx, String param); }
mit
simonetripodi/shs
core/src/main/java/org/nnsoft/shs/core/http/parse/ParserTrigger.java
1894
package org.nnsoft.shs.core.http.parse; /* * Copyright (c) 2012 Simone Tripodi (simonetripodi@apache.org) * * 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. */ import org.nnsoft.shs.core.http.MutableRequest; import org.nnsoft.shs.core.http.RequestParseException; /** * ParserTrigger instances are invoked depending on the {@link ParserStatus}. */ interface ParserTrigger { /** * Performs an parse action on the input token, adding data to the request, depending on the parser status. * * @param status the current parser status. * @param token the consumed token. * @param request the request that the parser is currently building * @throws RequestParseException if any syntax error occurs */ ParserStatus onToken( ParserStatus status, String token, MutableRequest request ) throws RequestParseException; }
mit
ismailBsd/cdc
src/helper/CorpDetatHelper.java
1011
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package helper; import bean.CorpDetat; import java.util.List; import javax.swing.JTable; /** * * @author kamal */ public class CorpDetatHelper extends AbstractViewHelper<CorpDetat>{ public CorpDetatHelper(JTable jTable, List<CorpDetat> corpDetats) { super(new String[]{ "Corp Detat"}); this.jTable = jTable; this.list = corpDetats; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (rowIndex < list.size()) { switch (columnIndex) { case 0: return list.get(rowIndex).getTitre(); case 1: return null; default: return null; } } return null; } }
mit
fieldenms/tg
platform-pojo-bl/src/main/java/ua/com/fielden/platform/sample/domain/TgOrgUnit3.java
1556
package ua.com.fielden.platform.sample.domain; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.DynamicEntityKey; import ua.com.fielden.platform.entity.annotation.CompanionObject; import ua.com.fielden.platform.entity.annotation.CompositeKeyMember; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.annotation.KeyType; import ua.com.fielden.platform.entity.annotation.MapEntityTo; import ua.com.fielden.platform.entity.annotation.MapTo; import ua.com.fielden.platform.entity.annotation.Observable; import ua.com.fielden.platform.entity.annotation.Required; import ua.com.fielden.platform.entity.annotation.Title; @KeyType(DynamicEntityKey.class) @MapEntityTo @CompanionObject(ITgOrgUnit3.class) public class TgOrgUnit3 extends AbstractEntity<DynamicEntityKey> { private static final long serialVersionUID = 1L; @IsProperty @Required @MapTo @Title(value = "Parent", desc = "Parent") @CompositeKeyMember(1) private TgOrgUnit2 parent; @IsProperty @MapTo @Title(value = "Name", desc = "Desc") @CompositeKeyMember(2) private String name; @Observable public TgOrgUnit3 setName(final String name) { this.name = name; return this; } public String getName() { return name; } @Observable public TgOrgUnit3 setParent(final TgOrgUnit2 parent) { this.parent = parent; return this; } public TgOrgUnit2 getParent() { return parent; } }
mit
blay09/BetterMinecraftChat
src/main/java/net/blay09/mods/bmc/chat/RandomNameColors.java
1064
package net.blay09.mods.bmc.chat; import com.google.common.collect.Maps; import net.minecraft.util.text.TextFormatting; import java.util.Map; import java.util.Random; public class RandomNameColors { private static final Random random = new Random(); private static final TextFormatting[] VALID_COLORS = new TextFormatting[] { TextFormatting.DARK_BLUE, TextFormatting.DARK_GREEN, TextFormatting.DARK_AQUA, TextFormatting.DARK_RED, TextFormatting.DARK_PURPLE, TextFormatting.GOLD, TextFormatting.GRAY, TextFormatting.BLUE, TextFormatting.GREEN, TextFormatting.AQUA, TextFormatting.RED, TextFormatting.LIGHT_PURPLE, TextFormatting.YELLOW, TextFormatting.WHITE }; private static Map<String, TextFormatting> nameColorMap = Maps.newHashMap(); public static TextFormatting getRandomNameColor(String senderName) { TextFormatting color = nameColorMap.get(senderName); if(color == null) { color = VALID_COLORS[random.nextInt(VALID_COLORS.length)]; nameColorMap.put(senderName, color); } return color; } }
mit
yangra/SoftUni
DataStructures/BinaryHeap/src/main/java/Heap.java
1445
public class Heap { public static <E extends Comparable<E>> void sort(E[] array) { constructHeap(array); sortHeap(array); String debug = ""; } private static <E extends Comparable<E>> void sortHeap(E[] array) { for (int i = array.length - 1; i >= 1; i--) { swap(array, 0, i); heapifyDown(array, 0, i); } } private static <E extends Comparable<E>> void constructHeap(E[] array) { for (int i = array.length / 2; i >= 0; i--) { heapifyDown(array, i, array.length); } } private static <E extends Comparable<E>> void heapifyDown(E[] array, int index, int limit) { while (index < array.length / 2) { int childIndex = (2 * index) + 1; if(childIndex >= limit){ break; } if (childIndex + 1 < limit && array[childIndex].compareTo(array[childIndex + 1]) < 0) { childIndex += 1; } int compare = array[index].compareTo(array[childIndex]); if (compare > 0) { break; } swap(array, index, childIndex); index = childIndex; } } private static <E extends Comparable<E>> void swap(E[] array, int index, int childIndex) { E element = array[index]; array[index] = array[childIndex]; array[childIndex] = element; } }
mit
stalayhan/OOP
cse241hw09/Family.java
3888
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package HW09_101044044; /** * CSE241_HW09 Samet Sait Talayhan 101044044 */ /** * @author talayhan * */ public class Family { // Data fields private Person father = null; private Person mother = null; private Person [] children; /** The current size of the children array */ private int size = 0; /** The current size of the array */ private final static int INITIAL_CAPACITY = 10; /** T */ private int capacity = INITIAL_CAPACITY; public static int numberOfFamilies = 0; /** * No parameter constructor. */ public Family(){ ++numberOfFamilies; //increase family number children = new Person [INITIAL_CAPACITY]; } /** * Two paramater constructor. */ public Family(Person father, Person mother){ if(father.getGender().equals(mother.getGender())){ throw new IllegalArgumentException("Father and Mother should have different" + " gender!"); } this.father = father; this.mother = mother; children = new Person [INITIAL_CAPACITY]; ++numberOfFamilies; } /** * Allocate a new array to hold */ private void reallocate(){ capacity = capacity * 2; Person[] newArray = new Person[capacity]; System.arraycopy(children, 0, newArray, 0, children.length); children = newArray; } /** * Method at() returns the child at the given index. * @param int index * @return Person at the given index. */ public Person at(int index){ // Validty check if(index < 0 || index >= size){ throw new IndexOutOfBoundsException("Invalid index!"); } return children[index]; } /** * Method add() that adds the Person as a child * to the family. * @param Person as a child. */ public void add(Person child){ if (size >= capacity) { reallocate(); } children[size] = child; ++size; } /* * Method compareTo() comparing two families, and * returns true if two families are equal. * @return boolean * @param Family object * **/ public boolean compareTo(Family other){ if(this.hashCode() == other.hashCode()){ return true; } return false; } /** * Override method toString() * @return String * */ public String toString(){ String s = "\t\tFamily Informations\n"; s += "Father: \n" + father.toString(); s += "Mother: \n" + mother.toString(); for (int i = 0; i < size; i++) { s += "Child" + i + ":\n" + children[i].toString(); } return s; } /** * Method isRelative() returns true if one of the persons is a * relative of the other by equals sirname the family array list. * @param get two person objects and family objects array * @return boolean type, true or false. * */ public static boolean isRelative(Person one, Person two, Family[] families){ if(one.getLastName() == two.getLastName()) return true; for (int i = 0; i < families.length; i++) { String comp = families[i].father.getLastName(); if(comp == one.getLastName() || comp == two.getLastName()){ return true; } } return false; } //Gettters and setters methods. public Person getFather() { return father; } public void setFather(Person father) { this.father = father; } public Person getMother() { return mother; } public void setMother(Person mother) { this.mother = mother; } public Person[] getChildren() { return children; } public void setChildren(Person[] children) { this.children = children; } public static int getNumberOfFamilies() { return numberOfFamilies; } // Actually, Java take cares of all clean up resources, // But we should decrease number of families in destructor, protected void finalize(){ --numberOfFamilies; } }
mit
AnanthaRajuC/Core-Java-Concepts
Selection Statements/src/io/github/anantharajuc/IfStatement.java
198
package io.github.anantharajuc; public class IfStatement { public static void main(String[] args) { int age = 19; if (age > 18) { System.out.println("Eligible to Vote"); } } }
mit
pcalouche/spat
spat-services/src/main/java/com/pcalouche/spat/config/WebConfig.java
1424
package com.pcalouche.spat.config; import com.pcalouche.spat.interceptors.LoggerInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { private final SpatProperties spatProperties; private final LoggerInterceptor loggerInterceptor; public WebConfig(SpatProperties spatProperties, LoggerInterceptor loggerInterceptor) { this.spatProperties = spatProperties; this.loggerInterceptor = loggerInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loggerInterceptor); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns(spatProperties.getCorsAllowedOrigins()) .allowCredentials(true) .allowedHeaders("*") .allowedMethods( "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE" ); } }
mit
LynnOwens/starlite
src/test/java/net/tofweb/starlite/CellSpaceTest.java
5440
package net.tofweb.starlite; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.LinkedList; import org.junit.Before; import org.junit.Test; public class CellSpaceTest { CellSpace space; // Test values double costA = 1.0; double gA = 12.12435565298214; double rhsA = 12.12435565298214; double gB = 17.320508075688775; double gC = 8.774964387392123; Double costPlusHeuristicA = 26.302685732130897; double costB = 3.7416573867739413; double gD = 3.7416573867739413; double rhsD = 4.0; double gE = 3.7416573867739413; @Before public void setup() { space = new CellSpace(); space.setGoalCell(10, 10, 10); space.setStartCell(-5, -5, -5); } @Test public void testGetInfo() { // Happy path Cell cell = space.makeNewCell(3, 3, 3); CellInfo returnedInfo = space.getInfo(cell); assertNotNull(returnedInfo); assertTrue(costA == returnedInfo.getCost()); assertTrue(gA == returnedInfo.getG()); assertTrue(rhsA == returnedInfo.getRhs()); // Null condition assertNull(space.getInfo(null)); /* * Illegal argument case - CellSpace managed cells should be made with * makeCell */ Cell illegalCell = new Cell(); assertNull(space.getInfo(illegalCell)); illegalCell.setX(100); illegalCell.setY(100); illegalCell.setZ(100); assertNull(space.getInfo(illegalCell)); } @Test public void testUpdateCellCost() { Cell cell = space.makeNewCell(3, 3, 3); CellInfo returnedInfo = space.getInfo(cell); // Existing state, cost = 1 assertNotNull(returnedInfo); assertTrue(1 == returnedInfo.getCost()); // Happy path, set cost = 2 space.updateCellCost(cell, 2); returnedInfo = space.getInfo(cell); assertNotNull(returnedInfo); assertTrue(2 == returnedInfo.getCost()); // Null condition A space.updateCellCost(null, 3); returnedInfo = space.getInfo(cell); assertNotNull(returnedInfo); assertTrue(2 == returnedInfo.getCost()); } @Test public void testGetG() { Cell cell = space.makeNewCell(3, 3, 3); // Existing state assertTrue(gA == space.getG(cell)); // Null conditions assertTrue(0.0 == space.getG(null)); assertTrue(0.0 == space.getG(new Cell())); Cell illegalCell = new Cell(); illegalCell.setX(100); illegalCell.setY(100); illegalCell.setZ(100); assertNull(space.getInfo(illegalCell)); } @Test public void testMakeNewCellIntIntInt() { Cell cell = space.makeNewCell(5, 4, 6); assertNotNull(cell); CellInfo info = space.getInfo(cell); assertNotNull(info); assertTrue(gC == info.getG()); assertTrue(gC == info.getRhs()); assertTrue(costA == info.getCost()); } @Test public void testMakeNewCellIntIntIntCosts() { Costs k = new Costs(3.14, 21.0); Cell cell = space.makeNewCell(7, 8, 9, k); assertNotNull(cell); assertEquals(costPlusHeuristicA, cell.getKey().getCostPlusHeuristic()); assertTrue(costB == cell.getKey().getCost()); CellInfo info = space.getInfo(cell); assertNotNull(info); assertTrue(gD == info.getG()); assertTrue(rhsD == info.getRhs()); assertTrue(costA == info.getCost()); } @Test public void testSetStartCell() { space.setStartCell(7, 8, 9); Cell startCell = space.getStartCell(); assertNotNull(startCell); assertEquals(7, startCell.getX()); assertEquals(8, startCell.getY()); assertEquals(9, startCell.getZ()); CellInfo info = space.getInfo(startCell); assertNotNull(info); assertTrue(gE == info.getG()); assertTrue(gE == info.getRhs()); assertTrue(costA == info.getCost()); } @Test public void testSetGoalCell() { space.setGoalCell(10, 11, 12); Cell goalCell = space.getGoalCell(); assertNotNull(goalCell); assertEquals(10, goalCell.getX()); assertEquals(11, goalCell.getY()); assertEquals(12, goalCell.getZ()); CellInfo info = space.getInfo(goalCell); assertNotNull(info); assertTrue(0.0 == info.getG()); assertTrue(0.0 == info.getRhs()); assertTrue(costA == info.getCost()); } @Test public void testIsClose() { assertTrue(space.isClose(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)); assertFalse(space.isClose(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY)); assertFalse(space.isClose(1.0, 2.0)); assertTrue(space.isClose(1.0, 1.000009)); assertFalse(space.isClose(1.0, 1.00001)); } @Test public void testGetSuccessors() { Cell cell = space.makeNewCell(20, 20, 20); LinkedList<Cell> neighbors = space.getPredecessors(cell); assertNotNull(neighbors); assertTrue(6 == neighbors.size()); assertEquals(20, neighbors.getFirst().getX()); assertEquals(20, neighbors.getFirst().getY()); assertEquals(19, neighbors.getFirst().getZ()); assertEquals(21, neighbors.getLast().getX()); assertEquals(20, neighbors.getLast().getY()); assertEquals(20, neighbors.getLast().getZ()); } @Test public void testGetPredecessors() { Cell cell = space.makeNewCell(20, 20, 20); LinkedList<Cell> neighbors = space.getPredecessors(cell); assertNotNull(neighbors); assertTrue(6 == neighbors.size()); assertEquals(20, neighbors.getFirst().getX()); assertEquals(20, neighbors.getFirst().getY()); assertEquals(19, neighbors.getFirst().getZ()); assertEquals(21, neighbors.getLast().getX()); assertEquals(20, neighbors.getLast().getY()); assertEquals(20, neighbors.getLast().getZ()); } }
mit
juqian/Slithice
Slithice/src/jqian/sootex/location/GlobalLocation.java
558
package jqian.sootex.location; import soot.SootField; import soot.Type; /** Model a static class field */ public class GlobalLocation extends Location{ protected final SootField _field; GlobalLocation(SootField field){ this._field=field; } public SootField getSootField(){ return _field; } public String toString(){ return _field.getDeclaringClass().getShortName()+"."+_field.getName(); } public Type getType(){ return _field.getType(); } }
mit
enkara/ta4j
ta4j/src/main/java/eu/verdelhan/ta4j/indicators/trackers/DirectionalMovementIndicator.java
2472
/** * The MIT License (MIT) * * Copyright (c) 2014-2017 Marc de Verdelhan & respective authors (see AUTHORS) * * 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 eu.verdelhan.ta4j.indicators.trackers; import eu.verdelhan.ta4j.Decimal; import eu.verdelhan.ta4j.TimeSeries; import eu.verdelhan.ta4j.indicators.CachedIndicator; import eu.verdelhan.ta4j.indicators.helpers.DirectionalDownIndicator; import eu.verdelhan.ta4j.indicators.helpers.DirectionalUpIndicator; /** * Directional movement indicator. * <p> */ public class DirectionalMovementIndicator extends CachedIndicator<Decimal>{ private final int timeFrame; private final DirectionalUpIndicator dup; private final DirectionalDownIndicator ddown; public DirectionalMovementIndicator(TimeSeries series, int timeFrame) { super(series); this.timeFrame = timeFrame; dup = new DirectionalUpIndicator(series, timeFrame); ddown = new DirectionalDownIndicator(series, timeFrame); } @Override protected Decimal calculate(int index) { Decimal dupValue = dup.getValue(index); Decimal ddownValue = ddown.getValue(index); Decimal difference = dupValue.minus(ddownValue); return difference.abs().dividedBy(dupValue.plus(ddownValue)).multipliedBy(Decimal.HUNDRED); } @Override public String toString() { return getClass().getSimpleName() + " timeFrame: " + timeFrame; } }
mit
angcyo/jsoup
src/test/java/org/jsoup/integration/TestServer.java
1758
package org.jsoup.integration; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletHandler; import org.jsoup.integration.servlets.BaseServlet; import java.util.concurrent.atomic.AtomicInteger; public class TestServer { private static final Server jetty = new Server(0); private static final ServletHandler handler = new ServletHandler(); private static AtomicInteger latch = new AtomicInteger(0); static { jetty.setHandler(handler); } private TestServer() { } public static void start() { synchronized (jetty) { int count = latch.getAndIncrement(); if (count == 0) { try { jetty.start(); } catch (Exception e) { throw new IllegalStateException(e); } } } } public static void stop() { synchronized (jetty) { int count = latch.decrementAndGet(); if (count == 0) { try { jetty.stop(); } catch (Exception e) { throw new IllegalStateException(e); } } } } public static String map(Class<? extends BaseServlet> servletClass) { synchronized (jetty) { if (!jetty.isStarted()) start(); // if running out of the test cases String path = "/" + servletClass.getSimpleName(); handler.addServletWithMapping(servletClass, path + "/*"); int port = ((ServerConnector) jetty.getConnectors()[0]).getLocalPort(); return "http://localhost:" + port + path; } } }
mit
XDrake99/WarpPI
teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPlatform.java
6772
package it.cavallium.warppi.teavm; import java.io.PrintWriter; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.teavm.jso.browser.Window; import org.teavm.jso.dom.html.HTMLDocument; import it.cavallium.warppi.Platform; import it.cavallium.warppi.gui.graphicengine.GraphicEngine; import it.cavallium.warppi.gui.graphicengine.html.HtmlEngine; import it.cavallium.warppi.math.rules.RulesManager; import it.cavallium.warppi.util.Error; public class TeaVMPlatform implements Platform { private final TeaVMConsoleUtils cu; private final TeaVMGpio gi; private final TeaVMStorageUtils su; private final String on; private final Map<String, GraphicEngine> el; private final TeaVMImageUtils pu; private final TeaVMSettings settings; private Boolean runningOnRaspberryOverride = null; public TeaVMPlatform() { cu = new TeaVMConsoleUtils(); gi = new TeaVMGpio(); su = new TeaVMStorageUtils(); pu = new TeaVMImageUtils(); on = "JavaScript"; el = new HashMap<>(); el.put("HTML5 engine", new HtmlEngine()); settings = new TeaVMSettings(); } @Override public ConsoleUtils getConsoleUtils() { return cu; } @Override public Gpio getGpio() { return gi; } @Override public StorageUtils getStorageUtils() { return su; } @Override public ImageUtils getImageUtils() { return pu; } @Override public TeaVMSettings getSettings() { return settings; } @Override public void setThreadName(final Thread t, final String name) {} @Override public void setThreadDaemon(final Thread t) {} @Override public void setThreadDaemon(final Thread t, final boolean value) {} @Override public void exit(final int value) { System.err.println("====================PROGRAM END===================="); } @Override public void gc() { } @Override public boolean isJavascript() { return true; } @Override public String getOsName() { return on; } private boolean shift, alpha; @Override public void alphaChanged(final boolean alpha) { this.alpha = alpha; final HTMLDocument doc = Window.current().getDocument(); doc.getBody().setClassName((shift ? "shift " : "") + (alpha ? "alpha" : "")); } @Override public void shiftChanged(final boolean shift) { this.shift = shift; final HTMLDocument doc = Window.current().getDocument(); doc.getBody().setClassName((shift ? "shift " : "") + (alpha ? "alpha" : "")); } @Override public Semaphore newSemaphore() { return new TeaVMSemaphore(0); } @Override public Semaphore newSemaphore(final int i) { return new TeaVMSemaphore(i); } @Override public URLClassLoader newURLClassLoader(final URL[] urls) { return new TeaVMURLClassLoader(urls); } @Override public Map<String, GraphicEngine> getEnginesList() { return el; } @Override public GraphicEngine getEngine(final String string) throws NullPointerException { return el.get(string); } @Override public void throwNewExceptionInInitializerError(final String text) { throw new NullPointerException(); } @Override public String[] stacktraceToString(final Error e) { return e.getMessage().toUpperCase().replace("\r", "").split("\n"); } @Override public void loadPlatformRules() { RulesManager.addRule(new rules.functions.DivisionRule()); RulesManager.addRule(new rules.functions.EmptyNumberRule()); RulesManager.addRule(new rules.functions.ExpressionRule()); RulesManager.addRule(new rules.functions.JokeRule()); RulesManager.addRule(new rules.functions.MultiplicationRule()); RulesManager.addRule(new rules.functions.NegativeRule()); RulesManager.addRule(new rules.functions.NumberRule()); RulesManager.addRule(new rules.functions.PowerRule()); RulesManager.addRule(new rules.functions.RootRule()); RulesManager.addRule(new rules.functions.SubtractionRule()); RulesManager.addRule(new rules.functions.SumRule()); RulesManager.addRule(new rules.functions.SumSubtractionRule()); RulesManager.addRule(new rules.functions.VariableRule()); RulesManager.addRule(new rules.ExpandRule1()); RulesManager.addRule(new rules.ExpandRule2()); RulesManager.addRule(new rules.ExpandRule5()); RulesManager.addRule(new rules.ExponentRule1()); RulesManager.addRule(new rules.ExponentRule2()); RulesManager.addRule(new rules.ExponentRule3()); RulesManager.addRule(new rules.ExponentRule4()); RulesManager.addRule(new rules.ExponentRule8()); RulesManager.addRule(new rules.ExponentRule9()); RulesManager.addRule(new rules.ExponentRule15()); RulesManager.addRule(new rules.ExponentRule16()); RulesManager.addRule(new rules.ExponentRule17()); RulesManager.addRule(new rules.FractionsRule1()); RulesManager.addRule(new rules.FractionsRule2()); RulesManager.addRule(new rules.FractionsRule3()); RulesManager.addRule(new rules.FractionsRule4()); RulesManager.addRule(new rules.FractionsRule5()); RulesManager.addRule(new rules.FractionsRule6()); RulesManager.addRule(new rules.FractionsRule7()); RulesManager.addRule(new rules.FractionsRule8()); RulesManager.addRule(new rules.FractionsRule9()); RulesManager.addRule(new rules.FractionsRule10()); RulesManager.addRule(new rules.FractionsRule11()); RulesManager.addRule(new rules.FractionsRule12()); RulesManager.addRule(new rules.FractionsRule14()); RulesManager.addRule(new rules.NumberRule1()); RulesManager.addRule(new rules.NumberRule2()); RulesManager.addRule(new rules.NumberRule3()); RulesManager.addRule(new rules.NumberRule4()); RulesManager.addRule(new rules.NumberRule5()); RulesManager.addRule(new rules.NumberRule7()); RulesManager.addRule(new rules.UndefinedRule1()); RulesManager.addRule(new rules.UndefinedRule2()); RulesManager.addRule(new rules.VariableRule1()); RulesManager.addRule(new rules.VariableRule2()); RulesManager.addRule(new rules.VariableRule3()); } @Override public void zip(final String targetPath, final String destinationFilePath, final String password) { throw new java.lang.UnsupportedOperationException("Not implemented."); } @Override public void unzip(final String targetZipFilePath, final String destinationFolderPath, final String password) { throw new java.lang.UnsupportedOperationException("Not implemented."); } @Override public boolean compile(final String[] command, final PrintWriter printWriter, final PrintWriter errors) { throw new java.lang.UnsupportedOperationException("Not implemented."); } @Override public void setRunningOnRaspberry(boolean b) { } @Override public boolean isRunningOnRaspberry() { return false; } }
mit
eduardodaluz/xfire
xfire-aegis/src/test/org/codehaus/xfire/aegis/example/CustomTypeTest.java
4341
package org.codehaus.xfire.aegis.example; import javax.xml.namespace.QName; import org.codehaus.xfire.aegis.AbstractXFireAegisTest; import org.codehaus.xfire.aegis.AegisBindingProvider; import org.codehaus.xfire.aegis.type.TypeMapping; import org.codehaus.xfire.aegis.type.basic.BeanType; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.binding.ObjectServiceFactory; import org.codehaus.xfire.services.BeanService; import org.codehaus.xfire.services.SimpleBean; import org.codehaus.xfire.soap.SoapConstants; import org.codehaus.xfire.wsdl.WSDLWriter; import org.jdom.Document; /** * @author <a href="mailto:peter.royal@pobox.com">peter royal</a> */ public class CustomTypeTest extends AbstractXFireAegisTest { public void testBeanService() throws Exception { // START SNIPPET: types ObjectServiceFactory osf = (ObjectServiceFactory) getServiceFactory(); AegisBindingProvider provider = (AegisBindingProvider) osf.getBindingProvider(); TypeMapping tm = provider.getTypeMappingRegistry().getDefaultTypeMapping(); // Create your custom type BeanType type = new BeanType(); type.setTypeClass(SimpleBean.class); type.setSchemaType(new QName("urn:ReallyNotSoSimpleBean", "SimpleBean")); // register the type tm.register(type); Service service = getServiceFactory().create(BeanService.class); getServiceRegistry().register(service); // END SNIPPET: types final Document response = invokeService("BeanService", "/org/codehaus/xfire/message/wrapped/WrappedCustomTypeTest.bean11.xml"); addNamespace("sb", "http://services.xfire.codehaus.org"); assertValid("/s:Envelope/s:Body/sb:getSubmitBeanResponse", response); assertValid("//sb:getSubmitBeanResponse/sb:out", response); assertValid("//sb:getSubmitBeanResponse/sb:out[text()=\"blah\"]", response); final Document doc = getWSDLDocument("BeanService"); addNamespace("wsdl", WSDLWriter.WSDL11_NS); addNamespace("wsdlsoap", WSDLWriter.WSDL11_SOAP_NS); addNamespace("xsd", SoapConstants.XSD); assertValid("/wsdl:definitions/wsdl:types", doc); assertValid("/wsdl:definitions/wsdl:types/xsd:schema", doc); assertValid("/wsdl:definitions/wsdl:types/xsd:schema[@targetNamespace='http://services.xfire.codehaus.org']", doc); assertValid( "//xsd:schema[@targetNamespace='http://services.xfire.codehaus.org']/xsd:element[@name='getSubmitBean']", doc); assertValid( "//xsd:element[@name='getSubmitBean']/xsd:complexType/xsd:sequence/xsd:element[@name='bleh'][@type='xsd:string']", doc); assertValid( "//xsd:element[@name='getSubmitBean']/xsd:complexType/xsd:sequence/xsd:element[@name='bean'][@type='ns1:SimpleBean']", doc); assertValid("/wsdl:definitions/wsdl:types" + "/xsd:schema[@targetNamespace='urn:ReallyNotSoSimpleBean']" + "/xsd:complexType", doc); assertValid("/wsdl:definitions/wsdl:types" + "/xsd:schema[@targetNamespace='urn:ReallyNotSoSimpleBean']" + "/xsd:complexType[@name=\"SimpleBean\"]", doc); assertValid("/wsdl:definitions/wsdl:types" + "/xsd:schema[@targetNamespace='urn:ReallyNotSoSimpleBean']" + "/xsd:complexType[@name=\"SimpleBean\"]/xsd:sequence/xsd:element[@name=\"bleh\"]", doc); assertValid("/wsdl:definitions/wsdl:types" + "/xsd:schema[@targetNamespace='urn:ReallyNotSoSimpleBean']" + "/xsd:complexType[@name=\"SimpleBean\"]/xsd:sequence/xsd:element[@name=\"howdy\"]", doc); assertValid("/wsdl:definitions/wsdl:types" + "/xsd:schema[@targetNamespace='urn:ReallyNotSoSimpleBean']" + "/xsd:complexType[@name=\"SimpleBean\"]/xsd:sequence/xsd:element[@type=\"xsd:string\"]", doc); assertValid( "/wsdl:definitions/wsdl:service/wsdl:port/wsdlsoap:address[@location='http://localhost/services/BeanService']", doc); } }
mit
andylyao/ImageTextView
app/src/main/java/com/dodola/animview/ImageTextView.java
3082
package com.dodola.animview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.text.Html; import android.util.AttributeSet; import android.widget.TextView; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; /** * Created by Yaoll * Time on 2015/10/23. * Description text里插入图片实现 */ public class ImageTextView extends TextView { public ImageTextView(Context context) { super(context); } public ImageTextView(Context context, AttributeSet attrs) { super(context, attrs); } public ImageTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setImageText(CharSequence text, String... imageUrls) { StringBuffer stringBuffer = new StringBuffer(); if(imageUrls != null) { for(String imageUrl : imageUrls) { stringBuffer.append("<img src='"); stringBuffer.append(imageUrl); stringBuffer.append("'/>"); } } stringBuffer.append(text); new ImageAsyncTask().execute(stringBuffer.toString()); } private class ImageAsyncTask extends AsyncTask<String, Void, CharSequence> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected CharSequence doInBackground(String... params) { Html.ImageGetter imageGetter = new Html.ImageGetter() { @Override public Drawable getDrawable(String source) { Bitmap bitmap = getImageLoader().loadImageSync(source); Drawable drawable = new BitmapDrawable(getResources(), bitmap); int width = drawable.getMinimumWidth(); int height = drawable.getMinimumHeight(); int outHeight = (int) (getPaint().descent() - getPaint().ascent()); int outWidth = (width * outHeight) / height; drawable.setBounds(0, 0, outWidth, outHeight); drawable.setLevel(1); return drawable; } }; CharSequence charSequence = Html.fromHtml(params[0].toString(), imageGetter, null); return charSequence; } @Override protected void onPostExecute(CharSequence charSequence) { super.onPostExecute(charSequence); ImageTextView.super.setText(charSequence); } } private ImageLoader mImageLoader; private ImageLoader getImageLoader() { if(mImageLoader == null) { ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext())// .threadPriority(Thread.NORM_PRIORITY - 2) .memoryCache(new WeakMemoryCache())// .diskCacheFileNameGenerator(new Md5FileNameGenerator())// .tasksProcessingOrder(QueueProcessingType.LIFO)// .build(); mImageLoader = ImageLoader.getInstance(); mImageLoader.init(config); } return mImageLoader; } }
mit
darthsitthiander/DP2-Duckhunt
Assesment/src/view/WelcomePanel.java
5249
package view; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Observable; import java.util.Observer; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import model.BouncingProjectile; import model.FriendlyShip; import model.Projectile; import controler.GameControler; @SuppressWarnings("serial") public class WelcomePanel extends JPanel implements Observer { //Panel used to show the title and sends you to the gamepanel after you pressed enter. private MainFrame mainFrame; private GameControler controler; private boolean loadingCompleted, reloading; private JLabel loadingLabel; private Image friendlyShipImage; public WelcomePanel(MainFrame newMainFrame, GameControler newControler){ mainFrame = newMainFrame; controler = newControler; loadingCompleted = false; reloading = false; setPreferredSize(new Dimension(500,630)); setLayout(new FlowLayout()); setBackground(Color.black); JLabel titleLabel = new JLabel("WELCOME TO SPACE WARS!", JLabel.CENTER); titleLabel.setPreferredSize(new Dimension(480,60)); titleLabel.setFont(new Font("Ariel", Font.BOLD, 33)); titleLabel.setForeground(Color.red); JLabel instructionsLabel = new JLabel("<html>Fight with your battleships against the battleships of the enemy! " + "Move your ship by selecting it and move it to a location by click with the left mouse button. If you get close enaugh to an enemy, " + "then it will automaticly fire a projectile towards him. If you press with your right mouse button, " + "then a bouncing projectile will be fired. It is twice as big, bounces 3 times against the walls " + "and will stay longer in the battlefield then a regular projectile. If a ship is above the moon and fires a projectile, " + "then 8 projectiles will be shot as a bonus. You can change the speed of the game by moving the slider, " + "and enable or disable the sounds with the checkbox. You win the level if you defeat the ships of the enemy " + "before they defeat yours. If you get defeated, then you can reset the level. If you make it through all the levels, " + "then you have completed the game.</html>", JLabel.CENTER); instructionsLabel.setPreferredSize(new Dimension(480,480)); instructionsLabel.setFont(new Font("Ariel", Font.BOLD, 20)); instructionsLabel.setForeground(Color.gray); loadingLabel = new JLabel("Loading the levels...", JLabel.CENTER); loadingLabel.setPreferredSize(new Dimension(480,50)); loadingLabel.setFont(new Font("Ariel", Font.BOLD, 30)); loadingLabel.setForeground(Color.green); add(titleLabel); add(instructionsLabel); add(loadingLabel); //load friendlyShipImage friendlyShipImage = new ImageIcon("resources/chaser.png").getImage(); //start the game when the player presses enter and the loading is completed. addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent evt){ if(evt.getKeyCode() == KeyEvent.VK_ENTER && loadingCompleted){ mainFrame.startGame(); } } }); setFocusable(true); } /*Called from mainFrame after the welcomePanel is set to visible.*/ public void startLoading(){ controler.loadLevelData(); } /*To reload te levels, some changes are needed. the reloading is used so the gamePanel * doesn;t get re-intialized again, and a different text is nicer.*/ public void prepaireReloadingLevels(){ loadingCompleted = false; reloading = true; loadingLabel.setText("Reloading the levels..."); } /*Paint the background and the ship and bouncing projectiles.*/ public void paintComponent(Graphics g){ super.paintComponent(g); try{ Projectile moon = controler.getBackgroundMoonFromBattleField(); if(moon != null){ g.setColor(moon.getProjectileColor()); g.fillOval(moon.x, moon.y, moon.width, moon.height); } for(Projectile star:controler.getBackgroundStarsFromBattleField()){ g.setColor(star.getProjectileColor()); g.fillRect(star.x, star.y, star.width, star.height); } for(BouncingProjectile shot:controler.getWelcomeAnimationBouncingProjectiles()){ g.setColor(shot.getProjectileColor()); g.fillOval(shot.x, shot.y, shot.width, shot.height); } }catch(Exception e){} FriendlyShip friendlyShip = controler.getWelcomeAnimationFriendlyShip(); g.drawImage(friendlyShipImage, friendlyShip.getLocation().x, friendlyShip.getLocation().y, null); } /*Gets called in the welcomeanimationloop and backgroundloop to repaint after a changehappened. * Also used by the controler f the battlefield has loaded the levels so the player can press enter and begin.*/ @Override public void update(Observable arg0, Object arg1) { String command = (String) arg1; if(command!=null && command.equals("levelsLoaded")){ //this panel will be reloading if the user visits the panel for the 2nd time. if(!reloading){ mainFrame.setGamePanel(controler.getAndIntializeGamePanel()); } loadingCompleted = true; reloading = false; loadingLabel.setText("Press ENTER to start the game."); } repaint(); } }
mit
androididentification/android
servlet/src/com/tum/ident/fastdtw/matrix/Array2D.java
3000
/* * Array2D.java Jul 14, 2004 * * Copyright (c) 2004 Stan Salvador * stansalvador@hotmail.com */ package com.tum.ident.fastdtw.matrix; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class Array2D { // PRIVATE DATA final private ArrayList<ArrayList<Object>> rows; // ArrayList of ArrayList (an array of rows in the array) private int numOfElements; // CONSTRUCTOR public Array2D() { rows = new ArrayList<ArrayList<Object>>(); numOfElements = 0; } public Array2D(Array2D array) { this.rows = new ArrayList<ArrayList<Object>>(array.rows); this.numOfElements = array.numOfElements; } // PUBLIC FU?NCTIONS public void clear() { rows.clear(); numOfElements = 0; } public int size() { return numOfElements; } public int numOfRows() { return rows.size(); } public int getSizeOfRow(int row) { return rows.get(row).size(); } public Object get(int row, int col) { return rows.get(row).get(col); } public void set(int row, int col, Object newVal) { rows.get(row).set(col, newVal); } public void addToEndOfRow(int row, Object value) { rows.get(row).add(value); numOfElements++; } public void addAllToEndOfRow(int row, Collection<?> objects) { final Iterator<?> i = objects.iterator(); while (i.hasNext()) { rows.get(row).add(i.next()); numOfElements++; } } public void addToNewFirstRow(Object value) { final ArrayList<Object> newFirstRow = new ArrayList<Object>(1); newFirstRow.add(value); rows.add(0, newFirstRow); numOfElements++; } public void addToNewLastRow(Object value) { final ArrayList<Object> newLastRow = new ArrayList<Object>(1); newLastRow.add(value); rows.add(newLastRow); numOfElements++; } public void addAllToNewLastRow(Collection<?> objects) { final Iterator<?> i = objects.iterator(); final ArrayList<Object> newLastRow = new ArrayList<Object>(1); while (i.hasNext()) { newLastRow.add(i.next()); numOfElements++; } rows.add(newLastRow); } public void removeFirstRow() { numOfElements -= rows.get(0).size(); rows.remove(0); } public void removeLastRow() { numOfElements -= rows.get(rows.size()-1).size(); rows.remove(rows.size()-1); } public String toString() { String outStr = ""; for (int r=0; r<rows.size(); r++) { final ArrayList<?> currentRow = rows.get(r); for (int c=0; c<currentRow.size(); c++) { outStr += currentRow.get(c); if (c == currentRow.size()-1) outStr += "\n"; else outStr += ","; } } // end for return outStr; } } // end class matrix.Array2D
mit
SpongePowered/SpongeForge
src/main/java/org/spongepowered/mod/mixin/core/client/gui/GuiOptionsMixin_Forge.java
3185
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.mod.mixin.core.client.gui; import net.minecraft.client.gui.GuiOptions; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.storage.WorldInfo; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.world.WorldManager; /** * In Sponge's Multi-World implementation, we give each world its own {@link WorldInfo}. While this is a great idea all around (allows us to * make things world-specific), it has some unintended consequences, such as breaking being able to change your difficulty in SinglePlayer. While * most people would tell us to not worry about it as Sponge isn't really client-side oriented, I have no tolerance for breaking Vanilla * functionality (barring some exceptions) so this cannot stand. */ @Mixin(GuiOptions.class) public abstract class GuiOptionsMixin_Forge { @Redirect(method = "actionPerformed", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/storage/WorldInfo;setDifficulty(Lnet/minecraft/world/EnumDifficulty;)V")) private void syncDifficulty(final WorldInfo worldInfo, final EnumDifficulty newDifficulty) { // Sync server WorldManager.getWorlds().forEach(worldServer -> WorldManager.adjustWorldForDifficulty(worldServer, newDifficulty, true)); // Sync client worldInfo.setDifficulty(newDifficulty); } @Redirect(method = "confirmClicked", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/storage/WorldInfo;setDifficultyLocked(Z)V")) private void syncDifficultyLocked(final WorldInfo worldInfo, final boolean locked) { // Sync server WorldManager.getWorlds().forEach(worldServer -> worldServer.getWorldInfo().setDifficultyLocked(locked)); // Sync client worldInfo.setDifficultyLocked(locked); } }
mit
kmcloutier/synapse
src/com/integpg/synapse/actions/CompositeAction.java
998
package com.integpg.synapse.actions; import com.integpg.logger.FileLogger; import java.io.IOException; import java.util.Json; public class CompositeAction extends Action { private String[] _actions; public CompositeAction(Json json) { _actions = (String[]) json.get("Actions"); ActionHash.put((String) json.get("ID"), this); } public void execute() throws IOException { Thread thd = new Thread(new Runnable() { public void run() { FileLogger.debug("Executing Composite Action in " + Thread.currentThread().getName()); for (int i = 0; i < _actions.length; i++) { try { Action.execute(_actions[i]); } catch (Exception ex) { FileLogger.error("Error executing action: " + ex.getMessage()); } } } }); thd.setDaemon(true); thd.start(); } }
mit
Idoneus/buildbot
buildbot-core/src/main/java/be/idoneus/hipchat/buildbot/hipchat/server/Paths.java
305
package be.idoneus.hipchat.buildbot.hipchat.server; public class Paths { public static String PATH_CAPABILITIES = ""; public static String PATH_INSTALL = "install"; public static String PATH_WEBHOOK_ROOM_MESSAGE = "webhooks/room_message"; public static String PATH_GLANCES = "glances"; }
mit
clayfish/printful4j
client/src/main/java/in/clayfish/printful/models/ShippingRequest.java
1115
package in.clayfish.printful.models; import java.io.Serializable; import java.util.List; import in.clayfish.printful.models.info.AddressInfo; import in.clayfish.printful.models.info.ItemInfo; /** * @author shuklaalok7 * @since 24/12/2016 */ public class ShippingRequest implements Serializable { /** * Recipient location information */ private AddressInfo recipient; /** * List of order items */ private List<ItemInfo> items; /** * 3 letter currency code (optional), required if the rates need to be converted to another currency instead of USD */ private String currency; public AddressInfo getRecipient() { return recipient; } public void setRecipient(AddressInfo recipient) { this.recipient = recipient; } public List<ItemInfo> getItems() { return items; } public void setItems(List<ItemInfo> items) { this.items = items; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } }
mit
pgorecki/visearch
projects/clustering/src/pl/edu/uwm/wmii/visearch/clustering/KMeans.java
12415
package pl.edu.uwm.wmii.visearch.clustering; /* * * Z linii poleceń * /usr/local/mahout/bin/mahout kmeans -i kmeans/data1/in -c kmeans/data1/cl -o kmeans/data1/out -x 10 -k 2 -ow -cl * opcja -ow nadpisuje katalog wyjściowy (nie trzeba ręcznie kasować) * opcja -cl generuje katalog clusteredPoints, zawierający informację o tym który punt do którego klastra * /usr/local/mahout/bin/mahout clusterdump -i kmeans/data1/out/clusters-*-final * * */ import java.io.File; import java.io.IOException; import java.security.InvalidKeyException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.StringTokenizer; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.mahout.clustering.Cluster; import org.apache.mahout.clustering.conversion.InputDriver; import org.apache.mahout.clustering.iterator.ClusterWritable; import org.apache.mahout.clustering.kmeans.KMeansDriver; import org.apache.mahout.clustering.kmeans.RandomSeedGenerator; import org.apache.mahout.common.HadoopUtil; import org.apache.mahout.common.Pair; import org.apache.mahout.common.distance.DistanceMeasure; import org.apache.mahout.common.distance.EuclideanDistanceMeasure; import org.apache.mahout.common.iterator.sequencefile.PathFilters; import org.apache.mahout.common.iterator.sequencefile.PathType; import org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterable; import org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterator; import org.apache.mahout.common.iterator.sequencefile.SequenceFileDirValueIterable; import org.apache.mahout.math.DenseVector; import org.apache.mahout.math.NamedVector; import org.apache.mahout.math.RandomAccessSparseVector; import org.apache.mahout.math.SequentialAccessSparseVector; import org.apache.mahout.math.VectorWritable; import org.apache.mahout.math.Vector; import org.apache.mahout.utils.clustering.ClusterDumper; import org.apache.mahout.vectorizer.SparseVectorsFromSequenceFiles; import org.apache.mahout.clustering.classify.ClusterClassificationDriver; import org.apache.mahout.clustering.classify.WeightedVectorWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import pl.edu.uwm.wmii.visearch.core.ConfigFile; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class KMeans { private static final Logger log = LoggerFactory.getLogger(KMeans.class); private static final Path BASE_DIR = new Path("visearch"); private static final Path DESCRIPTORS_DIR = new Path("visearch/descriptors"); private static final Path DICTIONARY_DIR = new Path("visearch/dictionary"); private static final Path VISUAL_WORDS_DIR = new Path( "visearch/visualwords"); private static final Path REPRESENTATIONS_DIR = new Path( "visearch/representations"); private static void createInput(Configuration conf, ConfigFile configFile, Path outputDir) throws Exception { String descriptorsDir = configFile.get("descriptorsDir") + "/SIFT"; File files = new File(descriptorsDir); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // wyczysc katalog z deskryptorami FileSystem fs = outputDir.getFileSystem(conf); fs.delete(outputDir, true); fs.mkdirs(outputDir); Path outputFile = new Path(outputDir, "all-descriptors"); SequenceFile.Writer writer = new SequenceFile.Writer(fs, conf, outputFile, Text.class, VectorWritable.class); // key:value pair for output file Text key = new Text(); VectorWritable val = new VectorWritable(); // procedura tworzaca pojedynczy duzy plik z deskryptorami dla kazdego // obrazka // k: [hash obrazka]:[kolejny numer deskryptora] // v: [deskryptor, 128 elementow dla SIFT'a] int totalFiles = 0; int badFiles = 0; for (File f : files.listFiles()) { totalFiles++; String docId = f.getName().split("\\.")[0]; log.info(String.valueOf(totalFiles)); try { Document doc = dBuilder.parse(f); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("desc"); for (int i = 0; i < nList.getLength(); i++) { String csv = nList.item(i).getTextContent(); String[] csvParts = csv.split(","); double[] data = new double[csvParts.length]; for (int j = 0; j < csvParts.length; j++) { data[j] = Integer.parseInt(csvParts[j].trim()); } StringBuilder sb = new StringBuilder(); sb.append(docId).append(":").append(i); key.set(sb.toString()); val.set(new DenseVector(data)); writer.append(key, val); } } catch (Exception e) { badFiles++; System.out.println(badFiles+"/"+totalFiles+" "+e); } } writer.close(); System.out.println("Done making a bigfile, #files: "+(totalFiles-badFiles)); } private static void runClustering(Configuration conf, ConfigFile configFile) throws IOException, ClassNotFoundException, InterruptedException { FileSystem fs = FileSystem.get(conf); Path clusters = new Path(BASE_DIR, new Path("initial-clusters")); fs.delete(DICTIONARY_DIR, true); fs.mkdirs(DICTIONARY_DIR); DistanceMeasure measure = new EuclideanDistanceMeasure(); int k = configFile.get("dictionarySize",100); double convergenceDelta = configFile.get("dictionaryConvergenceDelta",0.001); int maxIterations = configFile.get("dictionaryMaxIterations",10); // Random clusters clusters = RandomSeedGenerator.buildRandom(conf, DESCRIPTORS_DIR, clusters, k, measure); log.info("Random clusters generated, running K-Means, k="+k+" maxIter="+maxIterations); log.info("KMeansDriver.run(..."); log.info(DESCRIPTORS_DIR.toString()); log.info(clusters.toString()); log.info(DICTIONARY_DIR.toString()); log.info("....)"); KMeansDriver.run(conf, DESCRIPTORS_DIR, clusters, DICTIONARY_DIR, measure, convergenceDelta, maxIterations, true, 0.0, VM.RunSequential()); log.info("KMeans done"); } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); /* * TODO: musze jakos ustawic sciezki dla jar'a do /usr/local/hadoop/conf * bo KMeansDriver nie widzi ustawien hdfs i zapisuje wyniki klasteryzacji * do lokalnego katalogu * File files = new File("/usr/local/hadoop/conf"); for (File f : files.listFiles()) { System.out.println(f.getAbsolutePath()); conf.addResource(f.getAbsolutePath()); }*/ log.info("Configuration: "+conf.toString()); log.info("fs.default.name: "+conf.get("fs.default.name")); FileSystem fs = FileSystem.get(conf); ConfigFile configFile = new ConfigFile("settings.cfg"); boolean skipCreatingDictionary = false; try { List<String> largs = Arrays.asList(args); if (largs.contains("skipdict")) { skipCreatingDictionary = true; } } catch (Exception e) { } if (!skipCreatingDictionary) { if (VM.RunSequential()) { System.out.println("Running as SEQ"); } else { System.out.println("Running as MR"); } // stworz pliki z deskryptorami na podstawie xml'i // TODO: najlepiej zeby Anazyler zapisywal pliki od razu do hdfs (daily basis?) createInput(conf, configFile, DESCRIPTORS_DIR); // uruchom K-Means dla deskryptorow runClustering(conf, configFile); } else { log.info("Skipped creating dictionary"); } ImageToTextDriver.run(conf, DESCRIPTORS_DIR, DICTIONARY_DIR, VISUAL_WORDS_DIR, VM.RunSequential()); String dbUrl = configFile.get("dbUrl"); String dbUser = configFile.get("dbUser"); String dbPass = configFile.get("dbPass"); Connection dbConnection = DriverManager.getConnection("jdbc:" + dbUrl, dbUser, dbPass); log.info("Connected to {}", dbUrl); Statement statement = dbConnection.createStatement(); statement.executeUpdate("DELETE FROM ImageRepresentations"); statement.executeUpdate("DELETE FROM IFS"); for (Pair<Text, Text> entry : new SequenceFileDirIterable<Text, Text>( VISUAL_WORDS_DIR, PathType.LIST, conf)) { String docId = entry.getFirst().toString(); String line = entry.getSecond().toString(); StringTokenizer tokenizer = new StringTokenizer(line); Map<Integer, Integer> termFreq = new TreeMap<Integer, Integer>(); while (tokenizer.hasMoreTokens()) { int key = Integer.parseInt(tokenizer.nextToken()); if (termFreq.containsKey(key)) { termFreq.put(key, termFreq.get(key) + 1); } else { termFreq.put(key, 1); } } saveToDb(docId, termFreq, dbConnection); } dbConnection.close(); /* * MyClusterClassificationDriver .run(conf, DESCRIPTORS_DIR, * DICTIONARY_DIR, VISUAL_WORDS_DIR, 0.0, true, VM.RunSequential()); */ /* * Albo stworze wlasny map-reduce, ktory utworzy histogramy TF * * Albo zapisze obrazki jako tekst, i zapuszce na nich narzedzia * dostepne w Mahout org.apache.mahout.text.SequenceFilesFromDirectory * org.apache.mahout.vectorizer.SparseVectorsFromSequenceFiles */ // BagOfWordsDriver.run(conf, VISUAL_WORDS_DIR, REPRESENTATIONS_DIR, // VM.RunSequential()); /* * Path representationsFile = new Path(REPRESENTATIONS_DIR, "part-0"); * SequenceFile.Writer writer = new SequenceFile.Writer(fs, conf, * representationsFile, Text.class, VectorWritable.class); Text key = * new Text(); VectorWritable val = new VectorWritable(); * * RandomAccessSparseVector freq = new RandomAccessSparseVector(10); for * (Pair<IntWritable, Text> entry : new * SequenceFileDirIterable<IntWritable, Text>( VISUAL_WORDS_DIR, * PathType.LIST, conf)) { int idx = entry.getFirst().get(); * freq.incrementQuick(idx, 1); } */ /* * // stworzenie histogramu i zapisanie do pliku jako sparse vector for * (FileStatus f : fs.listStatus(VISUAL_WORDS_DIR)) { if (f.isDir()) { * RandomAccessSparseVector freq = new RandomAccessSparseVector(10); for * (Pair<IntWritable, WeightedVectorWritable> entry : new * SequenceFileDirIterable<IntWritable, WeightedVectorWritable>( new * Path(f.getPath(), "part-*"), PathType.GLOB, conf)) { int idx = * entry.getFirst().get(); freq.incrementQuick(idx, 1); } * key.set(f.getPath().getName()); val.set(freq); writer.append(key, * val); * * log.info("REP: {}",key); } } writer.close(); */ // saveToDb(conf, configFile); log.info("Done"); } private static void saveToDb(String docId, Map<Integer, Integer> termFreq, Connection dbConnection) throws InvalidKeyException, SQLException, IOException { String sql; PreparedStatement ps; // build json string and IFS Iterator<Entry<Integer, Integer>> it = termFreq.entrySet().iterator(); Map.Entry<Integer, Integer> e; String json = "{"; while (it.hasNext()) { e = it.next(); json += "\"" + e.getKey() + "\":\"" + e.getValue() + "\""; if (it.hasNext()) { json += ", "; } // save to IFS as well sql = "INSERT INTO IFS SELECT ?, ImageId FROM Images WHERE FileName LIKE ?"; ps = dbConnection.prepareStatement(sql); ps.setInt(1, e.getKey()); ps.setString(2, docId + "%"); ps.executeUpdate(); } json += "}"; System.out.println(termFreq); System.out.println(json); sql = "INSERT INTO ImageRepresentations SELECT ImageId, ? FROM Images WHERE FileName LIKE ?"; ps = dbConnection.prepareStatement(sql); ps.setString(1, json); ps.setString(2, docId.toString() + "%"); ps.executeUpdate(); } }
mit
SabreOSS/conf4j
conf4j-core/src/test/java/com/sabre/oss/conf4j/converter/OffsetDateTimeConverterTest.java
8201
/* * MIT License * * Copyright 2017-2018 Sabre GLBL Inc. * * 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.sabre.oss.conf4j.converter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.lang.reflect.Type; import java.time.*; import java.util.Map; import static com.sabre.oss.conf4j.converter.AbstractNumberConverter.FORMAT; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class OffsetDateTimeConverterTest { private OffsetDateTimeConverter offsetDateTimeConverter; @BeforeEach public void setUp() { offsetDateTimeConverter = new OffsetDateTimeConverter(); } @Test public void shouldBeApplicableWhenOffsetDateTimeType() { // given Type type = OffsetDateTime.class; // when boolean applicable = offsetDateTimeConverter.isApplicable(type, emptyMap()); // then assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotOffsetDateTimeType() { // given Type type = Boolean.class; // when boolean applicable = offsetDateTimeConverter.isApplicable(type, emptyMap()); // then assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { // then assertThatThrownBy(() -> offsetDateTimeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } @Test public void shouldConvertToStringWhenFormatNotSpecified() { // given Clock clock = Clock.fixed(Instant.EPOCH, ZoneId.of("Z")); OffsetDateTime toConvert = OffsetDateTime.now(clock); // when String converted = offsetDateTimeConverter.toString(OffsetDateTime.class, toConvert, emptyMap()); // then assertThat(converted).isEqualTo("1970-01-01T00:00Z"); } @Test public void shouldConvertToStringWhenFormatSpecified() { // given Clock clock = Clock.fixed(Instant.EPOCH, ZoneId.of("Z")); OffsetDateTime toConvert = OffsetDateTime.now(clock); String format = "yyyy-MM-dd HH:mm x"; Map<String, String> attributes = singletonMap(FORMAT, format); // when String converted = offsetDateTimeConverter.toString(OffsetDateTime.class, toConvert, attributes); // then assertThat(converted).isEqualTo("1970-01-01 00:00 +00"); } @Test public void shouldReturnNullWhenConvertingToStringAndValueToConvertIsNull() { // when String converted = offsetDateTimeConverter.toString(OffsetDateTime.class, null, emptyMap()); // then assertThat(converted).isNull(); } @Test public void shouldThrowExceptionWhenConvertingToStringAndWrongFormat() { // given Clock clock = Clock.fixed(Instant.EPOCH, ZoneId.of("Z")); OffsetDateTime toConvert = OffsetDateTime.now(clock); String format = "invalid format"; Map<String, String> attributes = singletonMap(FORMAT, format); // then assertThatThrownBy(() -> offsetDateTimeConverter.toString(OffsetDateTime.class, toConvert, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert OffsetDateTime to String. Invalid format: 'invalid format'"); } @Test public void shouldThrowExceptionWhenConvertingToStringAndTypeIsNull() { // given Clock clock = Clock.fixed(Instant.EPOCH, ZoneId.of("Z")); OffsetDateTime toConvert = OffsetDateTime.now(clock); // then assertThatThrownBy(() -> offsetDateTimeConverter.toString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } @Test public void shouldConvertFromStringWhenFormatNotSpecified() { // given String dateInString = "1970-01-01T00:00Z"; // when OffsetDateTime fromConversion = offsetDateTimeConverter.fromString(OffsetDateTime.class, dateInString, emptyMap()); // then Clock clock = Clock.fixed(Instant.EPOCH, ZoneId.of("Z")); OffsetDateTime expected = OffsetDateTime.now(clock); assertThat(fromConversion).isEqualTo(expected); } @Test public void shouldConvertFromStringWhenFormatSpecified() { // given String dateInString = "1970 01 01 00:00 +00"; String format = "yyyy MM dd HH:mm x"; Map<String, String> attributes = singletonMap(FORMAT, format); // when OffsetDateTime fromConversion = offsetDateTimeConverter.fromString(OffsetDateTime.class, dateInString, attributes); // then LocalDateTime localDateTime = LocalDateTime.of(1970, 1, 1, 0, 0); ZoneOffset zoneOffset = ZoneOffset.of("+00"); OffsetDateTime expected = OffsetDateTime.of(localDateTime, zoneOffset); assertThat(fromConversion).isEqualTo(expected); } @Test public void shouldReturnNullWhenConvertingFromStringAndValueToConvertIsNull() { // when OffsetDateTime fromConversion = offsetDateTimeConverter.fromString(OffsetDateTime.class, null, emptyMap()); // then assertThat(fromConversion).isNull(); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValueString() { // given String dateInString = "invalid value string"; // then assertThatThrownBy(() -> offsetDateTimeConverter.fromString(OffsetDateTime.class, dateInString, emptyMap())) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert to OffsetDateTime: invalid value string. The value doesn't match specified format null."); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongFormat() { // given String dateInString = "1970 01 01 00:00 +00"; String format = "invalid format"; Map<String, String> attributes = singletonMap(FORMAT, format); // then assertThatThrownBy(() -> offsetDateTimeConverter.fromString(OffsetDateTime.class, dateInString, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert to OffsetDateTime: 1970 01 01 00:00 +00. Invalid format: 'invalid format'"); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndTypeIsNull() { // given Clock clock = Clock.fixed(Instant.EPOCH, ZoneId.of("Z")); OffsetDateTime toConvert = OffsetDateTime.now(clock); // then assertThatThrownBy(() -> offsetDateTimeConverter.toString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } }
mit
Feng-Zihao/protox-webapp-archetype
jersey-ext/src/main/java/me/protox/archetype/jersey/ext/config_property/ConfigPropertyFeature.java
1271
package me.protox.archetype.jersey.ext.config_property; import org.glassfish.hk2.api.InjectionResolver; import org.glassfish.hk2.api.TypeLiteral; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Singleton; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Feature; import javax.ws.rs.core.FeatureContext; public class ConfigPropertyFeature implements Feature { static final Logger LOGGER = LoggerFactory.getLogger(ConfigPropertyFeature.class); @Override public boolean configure(FeatureContext context) { Configuration configuration = context.getConfiguration(); if (!configuration.isRegistered(ConfigPropertyResolver.class)) { LOGGER.debug("Register ConfigPropertyFeature"); context.register(ConfigPropertyResolver.class); context.register(new AbstractBinder() { @Override protected void configure() { bind(ConfigPropertyResolver.class) .to(new TypeLiteral<InjectionResolver<ConfigProperty>>() {}) .in(Singleton.class); } }); } return true; } }
mit
SamSix/s6-db
src/main/java/net/crowmagnumb/database/SqlColumn.java
4933
package net.crowmagnumb.database; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; public class SqlColumn implements SqlComponent { private final String _name; private final SqlColumnType _type; private SqlTable _table; private final String _alias; private String _properName; private String _constraints; // // Used for char and varchars // private Integer _charMaxLength; private String _prefix = null; private String _suffix = null; public SqlColumn(final SqlTable table, final String name) { this(table, name, SqlColumnType.OTHER, null); } public SqlColumn(final SqlTable table, final String name, final String alias) { this(table, name, SqlColumnType.OTHER, alias); } public SqlColumn(final String name, final SqlColumnType type) { this(null, name, type, null); } public SqlColumn(final SqlTable table, final String name, final SqlColumnType type) { this(table, name, type, null); } public SqlColumn(final SqlTable table, final String name, final String properName, final SqlColumnType type) { this(table, name, type, null); _properName = properName; } public SqlColumn(final SqlTable table, final String name, final SqlColumnType type, final String alias) { _table = table; _name = name; _type = type; _alias = alias; } public SqlTable getTable() { return _table; } public void setTable( final SqlTable table) { _table = table; } public String getName() { return _name; } public SqlColumnType getType() { return _type; } public String getProperName() { if (_properName == null) { return _name; } return _properName; } public void setCharMaxLength(final Integer charMaxLength) { _charMaxLength = charMaxLength; } public Integer getCharMaxLength() { return _charMaxLength; } public void setConstraints(final String constraints) { _constraints = constraints; } public String getConstraints() { return _constraints; } /** * The prefix and suffix are simply mechanisms to cheat * in case you have an usual column (like a function * call that you need to shoehorn into this structure. * When the column is formatted for output the prefix * and suffix are tacked on. * * @param prefix value */ public void setPrefix(final String prefix) { _prefix = prefix; } public String getPrefix() { return _prefix; } public void setSuffix(final String suffix) { _suffix = suffix; } public String formatValue(final String value) { if (_type == SqlColumnType.TEXT) { // // TODO: Fix this so that we can search on question marks if need be. // To fix a problem I had trying to use this to make parameterized queries I // check for a question mark and if so do not wrap quotes. I guess we // need to pass in that it is a parameterized query in which case we don't // even specify the value. // if (value == "?") { return "?"; } return DbUtils.wrapQuotes(value); } return value; } public String getSqlReference() { String value; if (! StringUtils.isBlank(_alias)) { value = _alias; } else { value = getStandardSqlReference(); } if (_prefix != null) { value = _prefix + value; } if (_suffix != null) { value += _suffix; } return value; } private String getStandardSqlReference() { if (_table == null) { return _name; } return DbUtils.buildDbRef(_table.getSqlReference(), _name); } @Override public void appendToSqlBuffer(final StringBuilder buffer) { buffer.append(getStandardSqlReference()); if (! StringUtils.isBlank(_alias)) { buffer.append(" AS ").append(_alias); } } //======================================== // // Standard common methods // //======================================== @Override public String toString() { return new ToStringBuilder(this).append("table", _table) .append("name", _name) .append("alias", _alias) .append("type", _type) .append("charMaxLength", _charMaxLength) .toString(); } }
mit
kikoseijo/AndroidPopularMovies
app/src/main/java/com/sunnyface/popularmovies/MainActivity.java
3149
package com.sunnyface.popularmovies; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.util.Pair; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.sunnyface.popularmovies.databinding.ActivityMainBinding; import com.sunnyface.popularmovies.libs.Constants; import com.sunnyface.popularmovies.models.Movie; /** * Root Activity. * Loads */ public class MainActivity extends AppCompatActivity implements MainActivityFragment.Callback { private boolean isTableLayout; private FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main); Toolbar toolbar = binding.actionBar.toolbar; setSupportActionBar(toolbar); fragmentManager = getSupportFragmentManager(); isTableLayout = binding.movieDetailContainer != null; } @Override public void onItemSelected(Movie movie, View view) { if (isTableLayout) { Bundle args = new Bundle(); args.putBoolean("isTabletLayout", true); args.putParcelable("movie", movie); DetailFragment fragment = new DetailFragment(); fragment.setArguments(args); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.movie_detail_container, fragment, Constants.MOVIE_DETAIL_FRAGMENT_TAG); //Replace its key. fragmentTransaction.commit(); } else { Intent intent = new Intent(this, DetailActivity.class); intent.putExtra("movie", movie); String movieID = "" + movie.getId(); Log.i("movieID: ", movieID); // Doing some view transitions with style, // But, we must check if we're running on Android 5.0 or higher to work. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //KK Bind this to remove findViewByID?????? ImageView thumbnailImageView = (ImageView) view.findViewById(R.id.thumbnail); TextView titleTextView = (TextView) view.findViewById(R.id.title); Pair<View, String> transition_a = Pair.create((View) thumbnailImageView, "movie_cover"); Pair<View, String> transition_b = Pair.create((View) titleTextView, "movie_title"); ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, transition_a, transition_b); startActivity(intent, options.toBundle()); } else { startActivity(intent); } } } }
mit
GenSolutionRep/Note
src/main/java/com/dasa/approval/service/ApprovalService.java
3931
package com.dasa.approval.service; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.beans.factory.annotation.Autowired; import com.dasa.approval.dao.ApprovalDao; import com.dasa.approval.vo.ApprovalVo; import com.dasa.communication.vo.BusinessOrderVo; import com.dasa.communication.vo.Notification; import com.dasa.communication.vo.SendNotification; import com.vertexid.vo.NaviVo; public class ApprovalService extends SqlSessionDaoSupport implements ApprovalDao { @Autowired private SendNotification sendNotification; @Override public NaviVo selectApprovalListCount(NaviVo naviVo) throws SQLException { naviVo.setTotRow( (Integer) getSqlSession().selectOne("approval.selectApprovalListCount", naviVo) ); return naviVo; } @Override public List<ApprovalVo> selectApprovalList(NaviVo naviVo) throws SQLException { return getSqlSession().selectList("approval.selectApprovalList", naviVo); } @Override public List<ApprovalVo> selectRejectList(String am_code) throws SQLException { return getSqlSession().selectList("approval.selectRejectList", am_code); } @Override public ApprovalVo selectApprovalRow(ApprovalVo vo) throws SQLException { return getSqlSession().selectOne("approval.selectApprovalRow", vo); } @Override public int getCheckCount(ApprovalVo vo) throws SQLException { int checkCount = (Integer) getSqlSession().selectOne("approval.dupCheckCount", vo); return checkCount; } @Override public void saveApproval(ApprovalVo p_vo) throws SQLException { getSqlSession().update("approval.SP_SAVE_30100", p_vo); System.out.println("p_vo.getAm_code() : " + p_vo.getAm_code()); System.out.println("p_vo.getRes_code() : " + p_vo.getRes_code()); System.out.println("p_vo.getRes_am_code() : " + p_vo.getRes_am_code()); System.out.println("p_vo.getFlag() : " + p_vo.getFlag()); System.out.println("p_vo.getRes_msg : " + p_vo.getRes_msg()); if(p_vo.getRes_code().equals("0") && (p_vo.getFlag().equals("INSERT") || p_vo.getFlag().equals("UPDATE")) ){ //상신 ApprovalVo resVo = new ApprovalVo(); List<Notification> bizNoti1 = new ArrayList<Notification>(); List<Notification> bizNoti2 = new ArrayList<Notification>(); Notification noti1 = new Notification(); Notification noti2 = new Notification(); resVo = getSqlSession().selectOne("approval.selectPushList", p_vo); if(resVo !=null && resVo.getEm_push_id().trim() != ""){ String em_push_id = resVo.getEm_push_id(); String em_device_type = resVo.getEm_device_type(); String subject = "[전자결재] " + resVo.getEm_nm() + " 상신" ; System.out.println("em_device_type:" +em_device_type ); if(em_device_type.equals("A")){ System.out.println("em_push_id:" +em_push_id ); System.out.println("em_device_type:" +em_device_type ); System.out.println("vo.getEm_nm:" +resVo.getEm_nm() ); System.out.println("subject:" +subject); noti1.setStringPropRegId(em_push_id); noti1.setDeviceType(em_device_type); bizNoti1.add(noti1); }else if(em_device_type.equals("I")){ noti2.setStringPropRegId(em_push_id); noti2.setDeviceType(em_device_type); noti2.setRunMode("REAL"); noti2.setCertificatePath("C:\\DASA\\iphone_rel.p12"); noti2.setCertificatePassword("vertexid"); bizNoti2.add(noti2); } try { sendNotification.sendPushMessage(bizNoti1, bizNoti2, subject); } catch (Exception e) { e.printStackTrace(); } } } } @Override public int amNoUpdate(ApprovalVo vo) throws SQLException { return getSqlSession().update("approval.amNoUpdate", vo); } }
mit
programmerr47/guitar-chords
app/src/main/java/com/github/programmerr47/chords/representation/adapter/item/SelectionModeAdapterItem.java
1102
package com.github.programmerr47.chords.representation.adapter.item; /** * Simple expansion of interface {@link AdapterItem} for organization of * "selection mode". * * @author Michael Spitsin * @since 2014-10-08 */ public abstract class SelectionModeAdapterItem implements AdapterItem { protected boolean isSelected; /** * Selects/deselects element. It is needed for selection mode to keep the "selection" * state in element. * * @param isSelected true if need to select element, false if need to deselect element */ public final void setElementSelected(boolean isSelected) { this.isSelected = isSelected; // setViewSelected(); } /** * Retrieves "selection" state of concrete element. * * @return true if element is selected and false if elements is deselected */ public final boolean isElementSelected() { return isSelected; } // /** // * Changes view when calls {@link SelectionModeAdapterItem#setElementSelected(boolean)}. // */ // protected abstract void setViewSelected(); }
mit
trust-wenderson/super-dao-demo
src/main/java/br/com/trustsystems/demo/provider/DatabasePersistenceProvider.java
1812
package br.com.trustsystems.demo.provider; import br.com.trustsystems.persistence.Persistent; import br.com.trustsystems.persistence.dao.IUnitOfWork; import br.com.trustsystems.persistence.provider.jpa.JpaPersistenceProvider; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.Collection; import java.util.List; @Service public class DatabasePersistenceProvider extends JpaPersistenceProvider { @PersistenceContext private EntityManager em; @Override public EntityManager entityManager() { return em; } @Transactional(propagation = Propagation.REQUIRED) public <D extends Persistent<?>> D persist(Class<D> domainClass, D domainObject) { return super.persist(domainClass, domainObject); } @Transactional(propagation = Propagation.REQUIRED) public <D extends Persistent<?>> List<D> persistAll(Class<D> domainClass, List<D> domainObjects) { return super.persistAll(domainClass, domainObjects); } @Transactional(propagation = Propagation.REQUIRED) public <D extends Persistent<?>> boolean deleteAll(Class<D> domainClass, Collection<D> domainObjects) { return super.deleteAll(domainClass, domainObjects); } @Transactional(propagation = Propagation.REQUIRED) public <D extends Persistent<?>> boolean delete(Class<D> domainClass, D domainObject) { return super.delete(domainClass, domainObject); } @Transactional(propagation = Propagation.REQUIRES_NEW) public void runInTransaction(IUnitOfWork t) { super.runInTransaction(t); } }
mit
konradxyz/cloudatlas
src/pl/edu/mimuw/cloudatlas/agent/modules/network/SendDatagramMessage.java
518
package pl.edu.mimuw.cloudatlas.agent.modules.network; import java.net.InetAddress; import pl.edu.mimuw.cloudatlas.agent.modules.framework.SimpleMessage; public final class SendDatagramMessage extends SimpleMessage<byte[]> { private InetAddress target; private int port; public SendDatagramMessage(byte[] content, InetAddress target, int port) { super(content); this.target = target; this.port = port; } public InetAddress getTarget() { return target; } public int getPort() { return port; } }
mit
dude719/JetBrains-NASM-Language
src/com/nasmlanguage/NASMCommenter.java
1389
/*++ NASM Assembly Language Plugin Copyright (c) 2017-2019 Aidan Khoury. All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --*/ package com.nasmlanguage; import com.intellij.lang.Commenter; import org.jetbrains.annotations.Nullable; public class NASMCommenter implements Commenter { @Nullable @Override public String getLineCommentPrefix() { return ";"; } @Nullable @Override public String getBlockCommentPrefix() { return null; } @Nullable @Override public String getBlockCommentSuffix() { return null; } @Nullable @Override public String getCommentedBlockCommentPrefix() { return null; } @Nullable @Override public String getCommentedBlockCommentSuffix() { return null; } }
mit
OreCruncher/ThermalRecycling
src/main/java/org/blockartistry/mod/ThermalRecycling/support/recipe/accessor/ForestryFabricatorRecipeAccessor.java
1809
/* * This file is part of ThermalRecycling, licensed under the MIT License (MIT). * * Copyright (c) OreCruncher * * 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 org.blockartistry.mod.ThermalRecycling.support.recipe.accessor; import java.util.List; import forestry.api.recipes.IFabricatorRecipe; import net.minecraft.item.ItemStack; public class ForestryFabricatorRecipeAccessor extends RecipeAccessorBase { @Override public ItemStack getInput(final Object recipe) { final IFabricatorRecipe r = (IFabricatorRecipe) recipe; return r.getRecipeOutput().copy(); } @Override public List<ItemStack> getOutput(final Object recipe) { final IFabricatorRecipe r = (IFabricatorRecipe) recipe; return RecipeUtil.projectForgeRecipeList(r.getIngredients()); } }
mit
udger/udger-java
src/test/java/org/udger/parser/UdgerParserTest.java
3881
package org.udger.parser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.net.URL; import java.net.UnknownHostException; import java.sql.SQLException; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CyclicBarrier; import org.junit.After; import org.junit.Before; import org.junit.Test; public class UdgerParserTest { private UdgerParser parser; private UdgerParser inMemoryParser; private UdgerParser.ParserDbData parserDbData; @Before public void initialize() throws SQLException { URL resource = this.getClass().getClassLoader().getResource("udgerdb_test_v3.dat"); parserDbData = new UdgerParser.ParserDbData(resource.getFile()); parser = new UdgerParser(parserDbData); inMemoryParser = new UdgerParser(parserDbData, true, 0); // no cache } @After public void close() throws IOException { parser.close(); } @Test public void testUaString1() throws SQLException { String uaQuery = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"; UdgerUaResult qr = parser.parseUa(uaQuery); assertEquals(qr.getUa(), "Firefox 40.0"); assertEquals(qr.getOs(), "Windows 10"); assertEquals(qr.getUaFamily(), "Firefox"); } @Test public void testIp() throws SQLException, UnknownHostException { String ipQuery = "108.61.199.93"; UdgerIpResult qr = parser.parseIp(ipQuery); assertEquals(qr.getIpClassificationCode(), "crawler"); } @Test public void testUaStringInMemoryParser() throws SQLException { String uaQuery = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"; UdgerUaResult qr = inMemoryParser.parseUa(uaQuery); assertEquals(qr.getUa(), "Firefox 40.0"); assertEquals(qr.getOs(), "Windows 10"); assertEquals(qr.getUaFamily(), "Firefox"); } @Test public void testIpInMemoryParser() throws SQLException, UnknownHostException { String ipQuery = "108.61.199.93"; UdgerIpResult qr = inMemoryParser.parseIp(ipQuery); assertEquals(qr.getIpClassificationCode(), "crawler"); } @Test public void testParserDbDataThreadSafety() throws Throwable { final int numThreads = 500; final String uaQuery = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"; final CyclicBarrier gate = new CyclicBarrier(numThreads); final ConcurrentLinkedQueue<Throwable> failures = new ConcurrentLinkedQueue<>(); Thread[] threads = new Thread[numThreads]; for (int i = 0; i < numThreads; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { UdgerParser threadParser = new UdgerParser(parserDbData); try { gate.await(); for (int j = 0; j < 100; j++) { UdgerUaResult qr = threadParser.parseUa(uaQuery); assertEquals(qr.getUa(), "Firefox 40.0"); assertEquals(qr.getOs(), "Windows 10"); assertEquals(qr.getUaFamily(), "Firefox"); } } catch (Throwable t) { failures.add(t); } } }); threads[i].start(); } for (int i = 0; i < numThreads; i++) { threads[i].join(); } if (!failures.isEmpty()) { for (Throwable throwable : failures) { throwable.printStackTrace(); } fail("Parsing threads failed, see printed exceptions"); } } }
mit
Fumaloko92/MSc-Thesis
17-05-2017/neuralturingmachines-master/src/dk/itu/ejuuragr/tests/MinimalTuringMachineTest.java
3649
package dk.itu.ejuuragr.tests; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.anji.util.Properties; import dk.itu.ejuuragr.turing.MinimalTuringMachine; public class MinimalTuringMachineTest { MinimalTuringMachine tm; @Before public void before(){ Properties props = new Properties(); props.setProperty("tm.m", "2"); props.setProperty("tm.shift.length", "3"); tm = new MinimalTuringMachine(props); } @Test public void testShift(){ double[] tmstim = new double[]{ 0, 1, //Write 1, //Write interpolation 0, //Content jump 1, 0, 0 //Shift }; double[] result = tm.processInput(tmstim)[0]; Assert.assertArrayEquals(new double[]{0, 0}, result, 0.0); tmstim = new double[]{ 0, 0, //Write 0, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; Assert.assertArrayEquals(new double[]{0, 1}, result, 0.0); } @Test public void testContentBasedJump(){ //Write jump target double[] tmstim = new double[]{ 0, 1, //Write 1, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; double[] result = tm.processInput(tmstim)[0]; //Write jump result tmstim = new double[]{ 1, 0, //Write 1, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; //Jump, shift, and read tmstim = new double[]{ 0, 1, //Write 0, //Write interpolation 1, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; Assert.assertArrayEquals(new double[]{1, 0}, result, 0.0); } @Test public void testContentBasedJumpLonger(){ //Write jump target double[] tmstim = new double[]{ 0, 1, //Write 1, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; double[] result = tm.processInput(tmstim)[0]; //Write jump result tmstim = new double[]{ 1, 0, //Write 1, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; //Move right for (int k = 0; k < 10; k++){ tmstim = new double[]{ 0, 0, //Write 0, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; } //Jump, shift, and read tmstim = new double[]{ 0, 1, //Write 0, //Write interpolation 1, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; Assert.assertArrayEquals(new double[]{1, 0}, result, 0.0); } @Test public void testCopyTaskSimple(){ double[][] seq = new double[][]{ {0,1,0}, //Start {1,0,0}, //Data {0,0,0}, //Data {0,0,0}, //Data {1,0,0}, //Data {1,0,0}, //Data {0,0,1}, //End {0,0,0}, //Poll {0,0,0}, //Poll {0,0,0}, //Poll {0,0,0}, //Poll {0,0,0}, //Poll }; double[] lastRoundRead = new double[]{0,0}; for (int round = 0; round < seq.length; round++){ double d = seq[round][0]; double s = seq[round][1]; double b = seq[round][2]; lastRoundRead = act(d + lastRoundRead[0],s + b + lastRoundRead[1], 1-b, b, 0, b ,1-b); double roundResult = lastRoundRead[0]; if (round > 6){ double verify = seq[round-6][0]; Assert.assertEquals(verify, roundResult, 0.00); } } } private double[] act(double d1, double d2, double write, double jump, double shiftLeft, double shiftStay, double shiftRight){ return tm.processInput(new double[]{ d1, d2, //Write write, //Write interpolation jump, //Content jump shiftLeft, shiftStay, shiftRight //Shift })[0]; } }
mit
Azure/azure-sdk-for-java
sdk/datalakestore/azure-resourcemanager-datalakestore/src/main/java/com/azure/resourcemanager/datalakestore/models/EncryptionIdentity.java
2508
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datalakestore.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; /** The encryption identity properties. */ @Fluent public class EncryptionIdentity { @JsonIgnore private final ClientLogger logger = new ClientLogger(EncryptionIdentity.class); /* * The type of encryption being used. Currently the only supported type is * 'SystemAssigned'. */ @JsonProperty(value = "type", required = true) private String type; /* * The principal identifier associated with the encryption. */ @JsonProperty(value = "principalId", access = JsonProperty.Access.WRITE_ONLY) private UUID principalId; /* * The tenant identifier associated with the encryption. */ @JsonProperty(value = "tenantId", access = JsonProperty.Access.WRITE_ONLY) private UUID tenantId; /** Creates an instance of EncryptionIdentity class. */ public EncryptionIdentity() { type = "SystemAssigned"; } /** * Get the type property: The type of encryption being used. Currently the only supported type is 'SystemAssigned'. * * @return the type value. */ public String type() { return this.type; } /** * Set the type property: The type of encryption being used. Currently the only supported type is 'SystemAssigned'. * * @param type the type value to set. * @return the EncryptionIdentity object itself. */ public EncryptionIdentity withType(String type) { this.type = type; return this; } /** * Get the principalId property: The principal identifier associated with the encryption. * * @return the principalId value. */ public UUID principalId() { return this.principalId; } /** * Get the tenantId property: The tenant identifier associated with the encryption. * * @return the tenantId value. */ public UUID tenantId() { return this.tenantId; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
mit
metaluna/magefortress
test/magefortress/jobs/subtasks/MFGotoLocationSubtaskTest.java
8185
/* * Copyright (c) 2010 Simon Hardijanto * * 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 magefortress.jobs.subtasks; import magefortress.core.MFEDirection; import magefortress.core.MFLocation; import magefortress.core.MFUnexpectedStateException; import magefortress.creatures.behavior.movable.MFCapability; import magefortress.creatures.behavior.movable.MFIMovable; import magefortress.map.MFPath; import magefortress.map.MFPathFinder; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class MFGotoLocationSubtaskTest { private MFGotoLocationSubtask gotoTask; private MFIMovable mockOwner; private MFPathFinder mockPathFinder; @Before public void setUp() { this.mockOwner = mock(MFIMovable.class); this.mockPathFinder = mock(MFPathFinder.class); this.gotoTask = new MFGotoLocationSubtask(this.mockOwner, this.mockPathFinder); MFLocation start = new MFLocation(4,4,4); MFLocation goal = new MFLocation(2,2,2); when(this.mockOwner.getLocation()).thenReturn(start); when(this.mockOwner.getCurrentHeading()).thenReturn(goal); } @Test public void shouldStartPathSearchFirstThing() throws MFSubtaskCanceledException { gotoTask.update(); verify(mockPathFinder).enqueuePathSearch(any(MFLocation.class), any(MFLocation.class), anyInt(), any(MFCapability.class), eq(gotoTask)); } @Test public void shouldStartPathSearchIfPathIsInvalid() throws MFSubtaskCanceledException { // path that's first valid and then invalid MFPath path = mock(MFPath.class); when(path.isPathValid()).thenReturn(true).thenReturn(false); gotoTask.update(); gotoTask.pathSearchFinished(path); gotoTask.update(); verify(mockPathFinder).enqueuePathSearch(any(MFLocation.class), any(MFLocation.class), anyInt(), any(MFCapability.class), eq(gotoTask)); gotoTask.update(); verify(mockPathFinder, times(2)).enqueuePathSearch(any(MFLocation.class), any(MFLocation.class), anyInt(), any(MFCapability.class), eq(gotoTask)); } @Test(expected=MFNoPathFoundException.class) public void shouldCancelIfNoPathWasFound() throws MFSubtaskCanceledException { gotoTask.update(); gotoTask.pathSearchFinished(null); gotoTask.update(); } @Test public void shouldBeginToMoveOwnerWhenPathWasFound() throws MFSubtaskCanceledException { // never-ending path northwards MFPath path = mock(MFPath.class); when(path.isPathValid()).thenReturn(true); when(path.hasNext()).thenReturn(true); when(path.next()).thenReturn(MFEDirection.N); gotoTask.update(); gotoTask.pathSearchFinished(path); gotoTask.update(); verify(mockOwner).move(any(MFEDirection.class)); } @Test public void shouldMoveOwnerAccordingToHisSpeed() throws MFSubtaskCanceledException { // never-ending path northwards MFPath path = mock(MFPath.class); when(path.isPathValid()).thenReturn(true); when(path.hasNext()).thenReturn(true); when(path.next()).thenReturn(MFEDirection.N); when(mockOwner.getSpeed()).thenReturn(3); gotoTask.update(); gotoTask.pathSearchFinished(path); gotoTask.update(); verify(mockOwner).move(any(MFEDirection.class)); gotoTask.update(); verify(mockOwner).move(any(MFEDirection.class)); gotoTask.update(); verify(mockOwner).move(any(MFEDirection.class)); gotoTask.update(); verify(mockOwner, times(2)).move(any(MFEDirection.class)); } @Test public void shouldBeDoneWhenGoalWasReached() throws MFSubtaskCanceledException { MFLocation goal = new MFLocation(1, 2, 3); // 2-tile path northwards MFPath path = mock(MFPath.class); when(path.isPathValid()).thenReturn(true); when(path.hasNext()).thenReturn(true); when(path.next()).thenReturn(MFEDirection.N); when(mockOwner.getSpeed()).thenReturn(3); when(mockOwner.getCurrentHeading()).thenReturn(goal); boolean done = true; done = gotoTask.update(); assertFalse(done); gotoTask.pathSearchFinished(path); // 1st move done = gotoTask.update(); assertFalse(done); done = gotoTask.update(); assertFalse(done); done = gotoTask.update(); assertFalse(done); // 2nd move when(mockOwner.getLocation()).thenReturn(goal); when(path.hasNext()).thenReturn(true).thenReturn(false); done = gotoTask.update(); assertTrue(done); } @Test(expected=MFUnexpectedStateException.class) public void shouldThrowExceptionWhenPathEndsNotAtGoal() throws MFSubtaskCanceledException { MFLocation goal = new MFLocation(1, 2, 3); // 2-tile path northwards MFPath path = mock(MFPath.class); when(path.isPathValid()).thenReturn(true); when(path.hasNext()).thenReturn(true); when(path.next()).thenReturn(MFEDirection.N); when(mockOwner.getSpeed()).thenReturn(3); when(mockOwner.getCurrentHeading()).thenReturn(goal); gotoTask.update(); gotoTask.pathSearchFinished(path); // 1st move gotoTask.update(); gotoTask.update(); gotoTask.update(); // 2nd move when(mockOwner.getLocation()).thenReturn(new MFLocation(1,1,3)); when(path.hasNext()).thenReturn(true).thenReturn(false); gotoTask.update(); } @Test(expected=MFUnexpectedStateException.class) public void shouldThrowExceptionAfterGoalWasReached() throws MFSubtaskCanceledException { MFLocation goal = new MFLocation(1, 2, 3); // 2-tile path northwards MFPath path = mock(MFPath.class); when(path.isPathValid()).thenReturn(true); when(path.hasNext()).thenReturn(true); when(path.next()).thenReturn(MFEDirection.N); when(mockOwner.getSpeed()).thenReturn(3); when(mockOwner.getCurrentHeading()).thenReturn(goal); gotoTask.update(); gotoTask.pathSearchFinished(path); // 1st move gotoTask.update(); gotoTask.update(); gotoTask.update(); // 2nd move when(mockOwner.getLocation()).thenReturn(goal); when(path.hasNext()).thenReturn(true).thenReturn(false); boolean done = gotoTask.update(); assertTrue(done); gotoTask.update(); } @Test public void shouldSetHeadingWhenSearchingForAPath() throws MFSubtaskCanceledException { MFLocation goal = new MFLocation(1,2,3); gotoTask = new MFGotoLocationSubtask(mockOwner, goal, mockPathFinder); MFLocation prevGoal = new MFLocation (3,2,1); when(mockOwner.getCurrentHeading()).thenReturn(prevGoal); gotoTask.update(); verify(mockOwner).setCurrentHeading(goal); } @Test public void shouldNotSearchPathIfAlreadyThere() throws MFSubtaskCanceledException { MFLocation goal = new MFLocation(1,2,3); when(this.mockOwner.getCurrentHeading()).thenReturn(goal); when(this.mockOwner.getLocation()).thenReturn(goal); this.gotoTask = new MFGotoLocationSubtask(this.mockOwner, this.mockPathFinder); this.gotoTask.update(); verify(this.mockPathFinder, never()).enqueuePathSearch(any(MFLocation.class), any(MFLocation.class), anyInt(), any(MFCapability.class), eq(gotoTask)); } }
mit
openregister/register
test/uk/gov/openregister/JsonObjectMapperTest.java
548
package uk.gov.openregister; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class JsonObjectMapperTest { @Test public void convertToString_Map_convertsMapToCononicalJson() { Map<String, Object> jsonMap = new HashMap<>(); jsonMap.put("key1", "value1"); jsonMap.put("akey", "value2"); String result = JsonObjectMapper.convertToString(jsonMap); assertEquals("{\"akey\":\"value2\",\"key1\":\"value1\"}", result); } }
mit
fahadadeel/Aspose.Cells-for-Java
Showcases/Html5_Spreadsheet_Editor_by_Aspose.Cells_for_Java/src/main/java/com/aspose/spreadsheeteditor/MessageService.java
952
package com.aspose.spreadsheeteditor; import java.util.logging.Logger; import javax.enterprise.context.ApplicationScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Named; import org.primefaces.context.RequestContext; /** * * @author Saqib Masood */ @Named(value = "msg") @ApplicationScoped public class MessageService { private static final Logger LOGGER = Logger.getLogger(MessageService.class.getName()); public void sendMessage(String summary, String details) { LOGGER.info(String.format("%s: %s", summary, details)); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(summary, details)); } public void sendMessageDialog(String summary, String details) { LOGGER.info(String.format("%s: %s", summary, details)); RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(summary, details)); } }
mit
SpongeHistory/SpongeAPI-History
src/main/java/org/spongepowered/api/item/properties/DoubleProperty.java
4824
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.api.item.properties; import org.spongepowered.api.util.Coerce; /** * Represents an item property that has an integer value. Examples may include * {@link FoodRestorationProperty}, {@link SaturationProperty} etc. */ public class DoubleProperty extends AbstractItemProperty<String, Double> { /** * Create a new integer property with the specified value. * * @param value value to match */ public DoubleProperty(double value) { super(Coerce.toDouble(value)); } /** * Create a new integer property with the specified value and logical * operator. * * @param value value to match * @param operator logical operator to use when comparing to other * properties */ public DoubleProperty(double value, Operator operator) { super(value, operator); } /** * Create a new integer property with the specified value and logical * operator. * * @param value value to match * @param operator logical operator to use when comparing to other * properties */ public DoubleProperty(Object value, Operator operator) { super(Coerce.toDouble(value), operator); } @Override public int compareTo(ItemProperty<?, ?> other) { return this.getValue().compareTo(other == null ? 1 : Coerce.toDouble(other.getValue())); } /** * Create an DoubleProperty property which matches DoubleProperty properties with * equal value. * * @param value value to match * @return new property */ public static DoubleProperty of(Object value) { return new DoubleProperty(value, Operator.EQUAL); } /** * Create an DoubleProperty property which matches DoubleProperty properties with * unequal value. * * @param value value to match * @return new property */ public static DoubleProperty not(Object value) { return new DoubleProperty(value, Operator.NOTEQUAL); } /** * Create an DoubleProperty property which matches DoubleProperty properties with * value greater than this value. * * @param value value to match * @return new property */ public static DoubleProperty greaterThan(Object value) { return new DoubleProperty(value, Operator.GREATER); } /** * Create an DoubleProperty property which matches DoubleProperty properties with * value greater than or equal to this value. * * @param value value to match * @return new property */ public static DoubleProperty greaterThanOrEqual(Object value) { return new DoubleProperty(value, Operator.GEQUAL); } /** * Create an DoubleProperty property which matches DoubleProperty properties with * value less than this value. * * @param value value to match * @return new property */ public static DoubleProperty lessThan(Object value) { return new DoubleProperty(value, Operator.LESS); } /** * Create an DoubleProperty property which matches DoubleProperty properties with * value less than or equal to this value. * * @param value value to match * @return new property */ public static DoubleProperty lessThanOrEqual(Object value) { return new DoubleProperty(value, Operator.LEQUAL); } /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ public boolean isFlowerPot() { return false; } }
mit
OpenMods/OpenPeripheral
src/main/java/openperipheral/adapter/IMethodCall.java
180
package openperipheral.adapter; public interface IMethodCall { public IMethodCall setEnv(String name, Object value); public Object[] call(Object... args) throws Exception; }
mit
messenger4j/messenger4j
src/main/java/com/github/messenger4j/send/message/template/receipt/Item.java
1752
package com.github.messenger4j.send.message.template.receipt; import static java.util.Optional.empty; import java.net.URL; import java.util.Optional; import lombok.EqualsAndHashCode; import lombok.NonNull; import lombok.ToString; /** * @author Max Grabenhorst * @since 1.0.0 */ @ToString @EqualsAndHashCode public final class Item { private final String title; private final float price; private final Optional<String> subtitle; private final Optional<Integer> quantity; private final Optional<String> currency; private final Optional<URL> imageUrl; private Item( String title, float price, Optional<String> subtitle, Optional<Integer> quantity, Optional<String> currency, Optional<URL> imageUrl) { this.title = title; this.price = price; this.subtitle = subtitle; this.quantity = quantity; this.currency = currency; this.imageUrl = imageUrl; } public static Item create(@NonNull String title, float price) { return create(title, price, empty(), empty(), empty(), empty()); } public static Item create( @NonNull String title, float price, @NonNull Optional<String> subtitle, @NonNull Optional<Integer> quantity, @NonNull Optional<String> currency, @NonNull Optional<URL> imageUrl) { return new Item(title, price, subtitle, quantity, currency, imageUrl); } public String title() { return title; } public float price() { return price; } public Optional<String> subtitle() { return subtitle; } public Optional<Integer> quantity() { return quantity; } public Optional<String> currency() { return currency; } public Optional<URL> imageUrl() { return imageUrl; } }
mit
FelipeAvila/hallejava
HalleEJB/ejbModule/com/halle/facade/FriendFacade.java
410
package com.halle.facade; import java.util.List; import javax.ejb.Local; import com.halle.exception.ApplicationException; import com.halle.model.Friend; @Local public interface FriendFacade { void inviteByPhone(final String token, final String name, final String phoneFriend) throws ApplicationException; List<Friend> findAllFriend(final String token, String status) throws ApplicationException; }
mit
imie-source/CDPN-N-05-SHARE
tests/testTennisRule/TennisRule/test/fr/imie/TennisRuleTest.java
2597
package fr.imie; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import fr.imie.Jeu; public class TennisRuleTest { private Jeu jeu; @Before public void initJeux(){ ISerialiser serialiser = new StateLessMockedSerialiser(); jeu = new Jeu(); jeu.setSerialiser(serialiser); } @Test public void testNewJeuxForSuccessCreatedClass() { } @Test public void testInitJeuxForSuccess0_0() { assertEquals("0-0",jeu.getScore()); } @Test public void testFirstPointJeuxForSuccess15_0() { //Arrange //Act jeu.marquerJoueur1(); //Assert assertEquals("15-0",jeu.getScore()); } @Test public void testSecondPointJeuxForSuccess30_0() { //Arrange jeu.marquerJoueur1(); //Act jeu.marquerJoueur1(); //Assert assertEquals("30-0",jeu.getScore()); } @Test public void testThirdPointJeuxForSuccess40_0() { //Arrange + Act joueur1To40(); //Assert assertEquals("40-0",jeu.getScore()); } @Test public void testFirstOpenentPointJeuxForSuccess40_15() { //Arrange joueur1To40(); //Act jeu.marquerJoueur2(); //Assert assertEquals("40-15",jeu.getScore()); } @Test public void testSecondOpenentPointJeuxForSuccess40_30() { //Arrange joueur1To40(); jeu.marquerJoueur2(); //Act jeu.marquerJoueur2(); //Assert assertEquals("40-30",jeu.getScore()); } @Test public void testEqualityForSuccessEgalite() { //Arrange+Act joueursToEquality(); //Assert assertEquals("égalité",jeu.getScore()); } @Test public void testJ1AvantageForSuccessAvantageJ1() { //Arrange joueursToEquality(); //Act jeu.marquerJoueur1(); //Assert assertEquals("av J1",jeu.getScore()); } @Test public void testResetForSuccessEgalite(){ //Arrange joueursToEquality(); //Act jeu.reset(); //Assert assertEquals("0-0",jeu.getScore()); } @Test public void testSaveAndLoadForSuccessEgalite(){ //Arrange joueursToEquality(); jeu.saveJeu(); jeu.reset(); //Act jeu.loadJeu(); //Assert assertEquals("égalité",jeu.getScore()); } @Test public void testSaveAndLoadTwiceForSuccess40_0(){ //Arrange joueursToEquality(); jeu.saveJeu(); jeu.reset(); jeu.loadJeu(); jeu.reset(); joueur1To40(); jeu.saveJeu(); jeu.reset(); //Act jeu.loadJeu(); //Assert assertEquals("40-0",jeu.getScore()); } private void joueursToEquality() { joueur1To40(); jeu.marquerJoueur2(); jeu.marquerJoueur2(); jeu.marquerJoueur2(); } private void joueur1To40() { jeu.marquerJoueur1(); jeu.marquerJoueur1(); jeu.marquerJoueur1(); } }
mit
mjurinic/AndroidWorkshop
app/src/main/java/org/foi/androidworkshop/adapters/PokemonAdapter.java
1685
package org.foi.androidworkshop.adapters; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import org.foi.androidworkshop.R; import org.foi.androidworkshop.models.Pokemon; import java.util.List; public class PokemonAdapter extends RecyclerView.Adapter<PokemonAdapter.ViewHolder> { private List<Pokemon> pokemons; public PokemonAdapter(List<Pokemon> pokemons) { this.pokemons = pokemons; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.pokemon_item, parent, false)); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.ivPokemonThumbnail.setImageResource(R.mipmap.ic_launcher); holder.tvPokeName.setText(pokemons.get(position).getName()); holder.tvPokeUrl.setText(pokemons.get(position).getUrl()); } @Override public int getItemCount() { return pokemons.size(); } public class ViewHolder extends RecyclerView.ViewHolder { private ImageView ivPokemonThumbnail; private TextView tvPokeName; private TextView tvPokeUrl; public ViewHolder(View itemView) { super(itemView); ivPokemonThumbnail = (ImageView) itemView.findViewById(R.id.ivPokeThumbnail); tvPokeName = (TextView) itemView.findViewById(R.id.tvPokeName); tvPokeUrl = (TextView) itemView.findViewById(R.id.tvPokeUrl); } } }
mit
catedrasaes-umu/NoSQLDataEngineering
projects/es.um.nosql.streaminginference/src/es/um/nosql/streaminginference/NoSQLSchema/impl/PrimitiveTypeImpl.java
3672
/** */ package es.um.nosql.streaminginference.NoSQLSchema.impl; import es.um.nosql.streaminginference.NoSQLSchema.NoSQLSchemaPackage; import es.um.nosql.streaminginference.NoSQLSchema.PrimitiveType; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Primitive Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link es.um.nosql.streaminginference.NoSQLSchema.impl.PrimitiveTypeImpl#getName <em>Name</em>}</li> * </ul> * * @generated */ public class PrimitiveTypeImpl extends TypeImpl implements PrimitiveType { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final long serialVersionUID = 6870693875L; /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected PrimitiveTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return NoSQLSchemaPackage.Literals.PRIMITIVE_TYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (name: "); result.append(name); result.append(')'); return result.toString(); } } //PrimitiveTypeImpl
mit
mikemey01/Markets
app/src/main/java/com/chariotinstruments/markets/CalcRSI.java
2899
package com.chariotinstruments.markets; import java.util.ArrayList; /** * Created by user on 1/30/16. */ public class CalcRSI { private MarketDay marketDay; private ArrayList<MarketCandle> marketCandles; private double gainAverage; private double lossAverage; public CalcRSI(MarketDay marDay){ this.marketDay = marDay; marketCandles = new ArrayList<MarketCandle>(); marketCandles = this.marketDay.getMarketCandles(); } public double getGainAverage(){ return gainAverage; } public double getLossAverage(){ return lossAverage; } public double getCurrentRSI(){ double RSI = 0.0; if(marketCandles.size()>1) { getFirstAverages(); RSI = getRSI(gainAverage, lossAverage); } return RSI; } public void getFirstAverages(){ double curAmount = 0.0; double prevAmount = 0.0; double sum = 0.0; double lastAmount = 0.0; for(int i = 1; i < 15; i++) { //start from the beginning to get the first SMA curAmount = marketCandles.get(i).getClose(); prevAmount = marketCandles.get(i-1).getClose(); sum = curAmount - prevAmount; if(sum < 0){ lossAverage += (sum * -1); }else{ gainAverage += sum; } } lossAverage = lossAverage / 14; gainAverage = gainAverage / 14; getSmoothAverages(lossAverage, gainAverage); } public void getSmoothAverages(double lossAvg, double gainAvg){ double curAmount = 0.0; double prevAmount = 0.0; double lastAmount = 0.0; //loop through the remaining amounts in the marketDay and calc the smoothed avgs for(int i = 15; i < marketCandles.size(); i++){ curAmount = marketCandles.get(i).getClose(); prevAmount = marketCandles.get(i-1).getClose(); lastAmount = curAmount - prevAmount; if(lastAmount < 0) { lossAvg = ((lossAvg * 13) + (lastAmount * -1)) / 14; gainAvg = ((gainAvg * 13) + 0) / 14; }else{ lossAvg = ((lossAvg * 13) + 0) / 14; gainAvg = ((gainAvg * 13) + lastAmount) / 14; } } lossAverage = lossAvg; gainAverage = gainAvg; } private double getRSI(double avgGain, double avgLoss){ double RS = avgGain/avgLoss; double RSI = 0; if(avgLoss > 0) { RSI = (100 - (100 / (1 + RS))); }else{ RSI = 100; } return RSI; } public String tester(){ String output = ""; for(int i = 0; i < marketCandles.size(); i++){ output = output + "\n" + Double.toString(marketCandles.get(i).getClose()); } return output; } }
mit
borrob/Meterstanden
src/main/java/meterstanden/domain/JaaroverzichtDomain.java
1867
package main.java.meterstanden.domain; import java.io.IOException; import java.util.List; import javax.persistence.Query; 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 org.apache.log4j.Logger; import org.hibernate.Session; import com.google.gson.Gson; import main.java.meterstanden.hibernate.HibernateUtil; /** * Servlet implementation class JaaroverzichtDomain */ @WebServlet( description = "Get the yearly overview", urlPatterns = { "/Jaaroverzicht", "/JAAROVERZICHT", "/jaaroverzicht" } ) public class JaaroverzichtDomain extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger log = Logger.getLogger(JaaroverzichtDomain.class); /** * @see HttpServlet#HttpServlet() */ public JaaroverzichtDomain() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Getting the jaarverbruik."); Session session = HibernateUtil.getSessionFactory().openSession(); StringBuilder hql = new StringBuilder(); hql.append("from Jaarverbruik"); Query q = session.createQuery(hql.toString()); List<?> rl = q.getResultList(); Gson gson = new Gson(); response.getWriter().append(gson.toJson(rl)); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
mit
G43riko/Java
PathFinder/src/PathFinder_2/Main.java
1742
package PathFinder_2; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import javax.swing.JFrame; public class Main extends JFrame{ private static final long serialVersionUID = 1L; private final String TITLE = "ArenaGame"; private MouseEvents mouseEvent = new MouseEvents(); private KeyEvents keyEvent = new KeyEvents(); public static Display display; public static int WIDTH,HEIGHT,gameIs; public static boolean isRunning; public static boolean fullScreen=true; public static Mapa[][] map; public static int block=40; public static boolean onlyGoal,findGoal,removedPossibles; public static int[] goal = null; public static int[] start = null; public static void main(String[] args) { Main game = new Main(); game.init(); display.start(); Main.newGame(); }; private void init(){ Main.WIDTH =800; Main.HEIGHT =600; this.setResizable(true); if(Main.fullScreen){ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Main.WIDTH = (int)screenSize.getWidth(); Main.HEIGHT = (int)screenSize.getHeight(); this.setResizable(false); this.setExtendedState(Frame.MAXIMIZED_BOTH); this.setUndecorated(true); } display=new Display(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.add(display); this.pack(); this.setTitle(TITLE); this.setVisible(true); display.addMouseListener(mouseEvent); display.addKeyListener(keyEvent); }; public static void newGame(){ Main.goal=Main.start=null; Main.onlyGoal=Main.findGoal=removedPossibles=true; Mapa.create((int)Main.HEIGHT/Main.block,(int)Main.WIDTH/Main.block); //Mapa.create(5,5); } }
mit
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/ActivityBasedTimeoutPolicyRequest.java
6648
// Template Source: BaseEntityRequest.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.models.ActivityBasedTimeoutPolicy; import com.microsoft.graph.models.DirectoryObject; import com.microsoft.graph.models.ExtensionProperty; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequest; import com.microsoft.graph.http.HttpMethod; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Activity Based Timeout Policy Request. */ public class ActivityBasedTimeoutPolicyRequest extends BaseRequest<ActivityBasedTimeoutPolicy> { /** * The request for the ActivityBasedTimeoutPolicy * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public ActivityBasedTimeoutPolicyRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions, ActivityBasedTimeoutPolicy.class); } /** * Gets the ActivityBasedTimeoutPolicy from the service * * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<ActivityBasedTimeoutPolicy> getAsync() { return sendAsync(HttpMethod.GET, null); } /** * Gets the ActivityBasedTimeoutPolicy from the service * * @return the ActivityBasedTimeoutPolicy from the request * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public ActivityBasedTimeoutPolicy get() throws ClientException { return send(HttpMethod.GET, null); } /** * Delete this item from the service * * @return a future with the deletion result */ @Nonnull public java.util.concurrent.CompletableFuture<ActivityBasedTimeoutPolicy> deleteAsync() { return sendAsync(HttpMethod.DELETE, null); } /** * Delete this item from the service * @return the resulting response if the service returns anything on deletion * * @throws ClientException if there was an exception during the delete operation */ @Nullable public ActivityBasedTimeoutPolicy delete() throws ClientException { return send(HttpMethod.DELETE, null); } /** * Patches this ActivityBasedTimeoutPolicy with a source * * @param sourceActivityBasedTimeoutPolicy the source object with updates * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<ActivityBasedTimeoutPolicy> patchAsync(@Nonnull final ActivityBasedTimeoutPolicy sourceActivityBasedTimeoutPolicy) { return sendAsync(HttpMethod.PATCH, sourceActivityBasedTimeoutPolicy); } /** * Patches this ActivityBasedTimeoutPolicy with a source * * @param sourceActivityBasedTimeoutPolicy the source object with updates * @return the updated ActivityBasedTimeoutPolicy * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public ActivityBasedTimeoutPolicy patch(@Nonnull final ActivityBasedTimeoutPolicy sourceActivityBasedTimeoutPolicy) throws ClientException { return send(HttpMethod.PATCH, sourceActivityBasedTimeoutPolicy); } /** * Creates a ActivityBasedTimeoutPolicy with a new object * * @param newActivityBasedTimeoutPolicy the new object to create * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<ActivityBasedTimeoutPolicy> postAsync(@Nonnull final ActivityBasedTimeoutPolicy newActivityBasedTimeoutPolicy) { return sendAsync(HttpMethod.POST, newActivityBasedTimeoutPolicy); } /** * Creates a ActivityBasedTimeoutPolicy with a new object * * @param newActivityBasedTimeoutPolicy the new object to create * @return the created ActivityBasedTimeoutPolicy * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public ActivityBasedTimeoutPolicy post(@Nonnull final ActivityBasedTimeoutPolicy newActivityBasedTimeoutPolicy) throws ClientException { return send(HttpMethod.POST, newActivityBasedTimeoutPolicy); } /** * Creates a ActivityBasedTimeoutPolicy with a new object * * @param newActivityBasedTimeoutPolicy the object to create/update * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<ActivityBasedTimeoutPolicy> putAsync(@Nonnull final ActivityBasedTimeoutPolicy newActivityBasedTimeoutPolicy) { return sendAsync(HttpMethod.PUT, newActivityBasedTimeoutPolicy); } /** * Creates a ActivityBasedTimeoutPolicy with a new object * * @param newActivityBasedTimeoutPolicy the object to create/update * @return the created ActivityBasedTimeoutPolicy * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public ActivityBasedTimeoutPolicy put(@Nonnull final ActivityBasedTimeoutPolicy newActivityBasedTimeoutPolicy) throws ClientException { return send(HttpMethod.PUT, newActivityBasedTimeoutPolicy); } /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ @Nonnull public ActivityBasedTimeoutPolicyRequest select(@Nonnull final String value) { addSelectOption(value); return this; } /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ @Nonnull public ActivityBasedTimeoutPolicyRequest expand(@Nonnull final String value) { addExpandOption(value); return this; } }
mit
rentianhua/tsf_android
houseAd/HouseGo/src/com/dumu/housego/presenter/LoginUserInfoPresenter.java
902
package com.dumu.housego.presenter; import com.dumu.housego.entity.UserInfo; import com.dumu.housego.model.ILoginUserInfoModel; import com.dumu.housego.model.IModel.AsycnCallBack; import com.dumu.housego.model.LoginUserInfoModel; import com.dumu.housego.view.ILoginUserInfoView; public class LoginUserInfoPresenter implements ILoginUserInfoPresenter { private ILoginUserInfoModel model; private ILoginUserInfoView view; public LoginUserInfoPresenter(ILoginUserInfoView view) { super(); this.view = view; model = new LoginUserInfoModel(); } @Override public void login(String userid) { model.login(userid, new AsycnCallBack() { @Override public void onSuccess(Object success) { UserInfo userinfo = (UserInfo) success; view.loginUserInfoSuccess(); } @Override public void onError(Object error) { view.loginUserInfoFail(error.toString()); } }); } }
mit
arnaudroger/SimpleFlatMapper
sfm-poi/src/main/java/org/simpleflatmapper/poi/impl/JoinSheetMapper.java
3746
package org.simpleflatmapper.poi.impl; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.simpleflatmapper.map.ConsumerErrorHandler; import org.simpleflatmapper.map.ContextualSourceFieldMapper; import org.simpleflatmapper.map.SourceFieldMapper; import org.simpleflatmapper.map.MappingContext; import org.simpleflatmapper.map.MappingException; import org.simpleflatmapper.map.context.MappingContextFactory; import org.simpleflatmapper.map.mapper.JoinMapperEnumerable; import org.simpleflatmapper.poi.RowMapper; import org.simpleflatmapper.util.CheckedConsumer; import java.util.Iterator; import org.simpleflatmapper.util.Enumerable; import org.simpleflatmapper.util.EnumerableIterator; //IFJAVA8_START import org.simpleflatmapper.util.EnumerableSpliterator; import java.util.stream.Stream; import java.util.stream.StreamSupport; //IFJAVA8_END public class JoinSheetMapper<T> implements RowMapper<T> { private final ContextualSourceFieldMapper<Row, T> mapper; private final int startRow = 0; private final ConsumerErrorHandler consumerErrorHandler; private final MappingContextFactory<? super Row> mappingContextFactory; public JoinSheetMapper(ContextualSourceFieldMapper<Row, T> mapper, ConsumerErrorHandler consumerErrorHandler, MappingContextFactory<? super Row> mappingContextFactory) { this.mapper = mapper; this.consumerErrorHandler = consumerErrorHandler; this.mappingContextFactory = mappingContextFactory; } @Override public Iterator<T> iterator(Sheet sheet) { return iterator(startRow, sheet); } @Override public Iterator<T> iterator(int startRow, Sheet sheet) { return new EnumerableIterator<T>(enumerable(startRow, sheet, newMappingContext())); } @Override public Enumerable<T> enumerate(Sheet sheet) { return enumerate(startRow, sheet); } @Override public Enumerable<T> enumerate(int startRow, Sheet sheet) { return enumerable(startRow, sheet, newMappingContext()); } private Enumerable<T> enumerable(int startRow, Sheet sheet, MappingContext<? super Row> mappingContext) { return new JoinMapperEnumerable<Row, T>(mapper, mappingContext, new RowEnumerable(startRow, sheet)); } @Override public <RH extends CheckedConsumer<? super T>> RH forEach(Sheet sheet, RH consumer) { return forEach(startRow, sheet, consumer); } @Override public <RH extends CheckedConsumer<? super T>> RH forEach(int startRow, Sheet sheet, RH consumer) { MappingContext<? super Row> mappingContext = newMappingContext(); Enumerable<T> enumarable = enumerable(startRow, sheet, mappingContext); while(enumarable.next()) { try { consumer.accept(enumarable.currentValue()); } catch(Exception e) { consumerErrorHandler.handlerError(e, enumarable.currentValue()); } } return consumer; } //IFJAVA8_START @Override public Stream<T> stream(Sheet sheet) { return stream(startRow, sheet); } @Override public Stream<T> stream(int startRow, Sheet sheet) { return StreamSupport.stream(new EnumerableSpliterator<T>(enumerable(startRow, sheet, newMappingContext())), false); } //IFJAVA8_END @Override public T map(Row source) throws MappingException { return mapper.map(source); } @Override public T map(Row source, MappingContext<? super Row> context) throws MappingException { return mapper.map(source, context); } private MappingContext<? super Row> newMappingContext() { return mappingContextFactory.newContext(); } }
mit