repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
wizzardo/epoll
src/test/java/com/wizzardo/epoll/sized/SizedDataServerTest.java
1584
package com.wizzardo.epoll.sized; import com.wizzardo.tools.io.BlockSizeType; import com.wizzardo.tools.io.SizedBlockInputStream; import com.wizzardo.tools.io.SizedBlockOutputStream; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.net.Socket; /** * @author: wizzardo * Date: 2/27/14 */ public class SizedDataServerTest { @Test public void test() throws InterruptedException, IOException { int port = 8080; SizedDataServer server = new SizedDataServer(port) { @Override public void handleData(SizedDataServerConnection connection, byte[] data) { System.out.println(new String(data)); connection.write(new ReadableByteArrayWithSize(new String(data).toUpperCase().getBytes()), this); } }; server.setIoThreadsCount(1); server.start(); Socket socket = new Socket("localhost", port); String string = "some test data"; byte[] data = string.getBytes(); SizedBlockOutputStream out = new SizedBlockOutputStream(socket.getOutputStream(), BlockSizeType.INTEGER); out.setBlockLength(data.length); out.write(data); out.flush(); SizedBlockInputStream in = new SizedBlockInputStream(socket.getInputStream(), BlockSizeType.INTEGER); Assert.assertTrue(in.hasNext()); in.read(data); Assert.assertEquals(string.toUpperCase(), new String(data)); // Thread.sleep(5 * 60 * 1000); Thread.sleep(1 * 1000); server.close(); } }
mit
tectronics/wiki-to-speech
src/com/jgraves/WikiToSpeech/InputView.java
2022
package com.jgraves.WikiToSpeech; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.widget.Button; import android.widget.EditText; public class InputView extends Activity { private EditText mInputEditText; private Button mGoButton; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.inputview); // mTts.setLanguage(Locale.UK); // print("UK available: " + mTts.isLanguageAvailable(Locale.UK)); mInputEditText = (EditText) findViewById(R.id.input_edittext); mGoButton = (Button) findViewById(R.id.go_button); String extra = getIntent().getStringExtra(Constants.EXTRA_INPUT_STRING); if(null!=extra){ mInputEditText.setText(extra); } mGoButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Intent i = new Intent(InputView.this,QuestionView.class); i.putExtra(Constants.EXTRA_INPUT_STRING, mInputEditText.getText().toString()); i.putExtra(Constants.EXTRA_INPUT_TYPE, State.getDestinationType(mInputEditText.getText().toString())); startActivity(i); } }); mInputEditText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { return true; } return false; } }); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } }
mit
BrassGoggledCoders/SlimeFusion
src/main/java/xyz/brassgoggledcoders/slimefusion/modules/grasses/ModuleGrasses.java
920
package xyz.brassgoggledcoders.slimefusion.modules.grasses; import com.teamacronymcoders.base.modulesystem.Module; import com.teamacronymcoders.base.modulesystem.ModuleBase; import com.teamacronymcoders.base.registry.BlockRegistry; import com.teamacronymcoders.base.registry.config.ConfigRegistry; import xyz.brassgoggledcoders.slimefusion.modules.grasses.blocks.BlockStakteroGrass; import xyz.brassgoggledcoders.slimefusion.modules.grasses.blocks.BlockStakteroTallGrass; import static xyz.brassgoggledcoders.slimefusion.SlimeFusion.MOD_ID; @Module(MOD_ID) public class ModuleGrasses extends ModuleBase { @Override public String getName() { return "Grasses"; } @Override public void registerBlocks(ConfigRegistry configRegistry, BlockRegistry blockRegistry) { blockRegistry.register(new BlockStakteroGrass()); blockRegistry.register(new BlockStakteroTallGrass()); } }
mit
enrichman/cloudatcost
cloudatcost/src/main/java/cloudatcost/response/ListTemplatesResponse.java
257
package cloudatcost.response; import cloudatcost.model.Template; import java.util.List; /** * Copyright (c) 2015 Enrico Candino * <p> * Distributed under the MIT License. */ public class ListTemplatesResponse extends CACResponse<List<Template>> { }
mit
evarga/se-tutorials
jta_distributed_transactions/example/src/test/java/rs/exproit/jta_distributed_transactions/RNGServiceIntegrationTest.java
5819
package rs.exproit.jta_distributed_transactions; import static org.junit.Assert.*; import java.net.URISyntaxException; import java.util.concurrent.Callable; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * This is the integration test class that simulates a client sending commands and receiving results. * This test sets up the whole embedded infrastructure: ActiveMQ broker, transaction manager and Java DB. * The logic of the test is very simple, as it just ensures that the numbers generated by a service are correctly * received by a client. However, it illustrates the full transaction processing cycle. * * @author Ervin Varga */ public class RNGServiceIntegrationTest { static final String BROKER_URL = "tcp://localhost:" + BrokerService.DEFAULT_PORT; private static BrokerService broker; private static RNGService rngService; @BeforeClass public static void startJMSBroker() throws URISyntaxException, Exception { broker = new BrokerService(); broker.addConnector(BROKER_URL); // For an embedded broker the persistent mode doesn't mean too much. Of course, for an external // broker you would set this to true. broker.setPersistent(false); broker.setUseJmx(false); broker.start(); System.out.println("Embedded ActiveMQ broker is started"); rngService = new RNGService(BROKER_URL); rngService.start(); System.out.println("RNG Service is started"); } @AfterClass public static void stopJMSBroker() throws Exception { rngService.stop(); System.out.println("RNG Service is stopped"); broker.stop(); System.out.println("Embedded ActiveMQ broker is stopped"); } /** * This method performs full cycles with valid command messages. The test client * will receive the random numbers as specified. * * @throws Exception if some error happens in the test client. */ @Test public void executeValidClientServerInteractions() throws Exception { for (int i = 2; i < 10; i++) { String result = new RNGClient(i + "/52").call(); assertNotNull(result); String[] randomNumbers = result.split(","); assertEquals(i, randomNumbers.length); } } /** * This method triggers an intentional exception inside the RNG micro-service by * sending a special "poison" message GENERATE 1/1 (this is a confusing message for a service as * the response cannot be random). In this case, the test client will never receive a response. * Take a look into the RNG service, and you will notice that due to nested transactions neither a message * sending action nor the database update will succeed if the top transaction rolls back. * * @throws Exception if some error happens in the test client. */ @Test(expected = NullPointerException.class) public void executeInvalidClientServerInteraction() throws Exception { new RNGClient("1/1").call(); } } // This is our simple pure JMS 1.1 test client that triggers the RNG micro-service. // It sends a command and performs a blocking wait on the response. We don't use here // correlation identifiers, since we only have a single client. In production you // will need to filter messages based upon this ID. Temporary reply queues cannot be transacted. class RNGClient implements Callable<String> { private final String commandArguments; RNGClient(String commandArguments) { this.commandArguments = commandArguments; } void sendCommandMessage(String commandMessage, Session session) throws JMSException { Queue reqQueue = session.createQueue(RNGService.COMMAND_REQUEST_QUEUE); MessageProducer sender = session.createProducer(reqQueue); TextMessage msg = session.createTextMessage(commandMessage); sender.send(msg); System.out.println("Command to generate random numebrs is sent, message = " + commandMessage); } // How long should we wait for the response. private static final int MAX_WAIT_TIME = 7000; String receiveRandomNumbers(Session session) throws JMSException { Queue resQueue = session.createQueue(RNGService.COMMAND_RESPONSE_QUEUE); MessageConsumer receiver = session.createConsumer(resQueue); // In case of a time-out we will receive here a NullPointerException exception due to an // unsuccessful type cast. Naturally, you must explicitly protect yourself in production against this. return ((TextMessage) receiver.receive(MAX_WAIT_TIME)).getText(); } // In production you will need to ensure that sessions/connections are properly closed even in the case // of an exception. public String call() throws Exception { Connection connection = new ActiveMQConnectionFactory(RNGServiceIntegrationTest.BROKER_URL).createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); sendCommandMessage(RNGService.GENERATE_COMMAND + " " + commandArguments, session); session.close(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); String randomNumbers = receiveRandomNumbers(session); session.close(); connection.close(); return randomNumbers; } }
mit
ONSdigital/tredegar
src/main/java/com/github/onsdigital/search/bean/CollectionSearchResult.java
2731
package com.github.onsdigital.search.bean; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.github.davidcarboni.restolino.json.Serialiser; import com.github.onsdigital.json.collection.CollectionItem; /** * Holds the details for a collection of content types */ public class CollectionSearchResult { private static final String INDEX_VALUE = "latest"; private static final String INDEX_KEY = "indexNumber"; private static final String RELEASE_DATE = "releaseDate"; private static final String URL = "url"; private static final String DATA_JSON = "data.json"; private static final String PATH_ROOT = "taxonomy"; private static final String TITLE = "title"; private long numberOfResults; private List<Map<String, String>> results; private int page; /** * ctor that parses the files and stores information about these files into * a map * * @param files * collection of files representing the content types * @param page * indicates which page number, needed to help identify latest * bulletin */ public CollectionSearchResult(List<File> files, int page) { results = new ArrayList<Map<String, String>>(); this.numberOfResults = files.size(); this.page = page; init(files); } /** * @return number of files found during the search */ public long getNumberOfResults() { return numberOfResults; } /** * @param numberOfHits * number of files stored */ public void setNumberOfResults(long numberOfHits) { this.numberOfResults = numberOfHits; } /** * @return collection of key,value pairs that detail a content type */ public List<Map<String, String>> getResults() { return results; } private void init(List<File> files) { for (File file : files) { Map<String, String> item = new HashMap<String, String>(); CollectionItem collectionItemJson = getCollectionItem(file); item.put(TITLE, collectionItemJson.title); item.put(RELEASE_DATE, collectionItemJson.releaseDate); String[] urlWithoutJson = getUrl(file); item.put(URL, urlWithoutJson[0]); if ((page == 1) && (files.indexOf(file) == 0)) { item.put(INDEX_KEY, INDEX_VALUE); } results.add(item); } } private String[] getUrl(File file) { String[] url = file.getPath().split(PATH_ROOT); String[] urlWithoutJson = url[1].split(DATA_JSON); return urlWithoutJson; } private CollectionItem getCollectionItem(File file) { try { return Serialiser.deserialise(new FileInputStream(file), CollectionItem.class); } catch (IOException e) { throw new RuntimeException(e); } } }
mit
dfsisinni/enum-generator-from-csv-java
src/com/danesisinni/CSVEnumGenerator.java
6160
package com.danesisinni; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import lombok.AllArgsConstructor; import lombok.Data; import lombok.val; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord; import org.apache.commons.lang3.StringUtils; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; public class CSVEnumGenerator { private static final String ENUM_INITIALIZATION_VALUE = "VALUE"; private static final ImmutableSet<String> NON_QUOTE_DATA_TYPES = new ImmutableSet.Builder<String>() .add("int") .add("Integer") .add("long") .add("Long") .add("double") .add("Double") .add("Float") .add("float") .build(); private final String CSV_FILE; private final String ENUM_NAME; public CSVEnumGenerator(String CSV_FILE, String ENUM_NAME) { this.CSV_FILE = CSV_FILE; this.ENUM_NAME = ENUM_NAME; } public String getEnum() { val enumWrapper = getDataFromCSVFile(); val enumBuilder = new StringBuilder(); enumBuilder.append("public enum "); enumBuilder.append(ENUM_NAME); enumBuilder.append(" { \n\n"); val arguments = enumWrapper.getDataTypes(); val argumentOrder = arguments.keySet().asList(); val initializationList = new ArrayList<String>(); for (EnumData entry : enumWrapper.getEnumData()) { val instanceBuilder = new StringBuilder(); instanceBuilder.append(entry.getName()); instanceBuilder.append("("); val paramsList = new ArrayList<String>(); for (String argument : argumentOrder) { val arg = entry.getInitializationValues().get(argument); if (needsQuotes(arguments.get(argument), arg)) { paramsList.add("\"" + arg + "\""); } else { paramsList.add(arg); } } instanceBuilder.append(Joiner.on(",").join(paramsList)); instanceBuilder.append(")"); initializationList.add(instanceBuilder.toString()); } enumBuilder.append(Joiner.on(",\n").join(initializationList)); enumBuilder.append(";\n\n"); for (String argument : argumentOrder) { enumBuilder.append("private final "); enumBuilder.append(arguments.get(argument)); enumBuilder.append(" "); enumBuilder.append(argument); enumBuilder.append(";\n"); } enumBuilder.append("\n\n"); enumBuilder.append(ENUM_NAME); enumBuilder.append("("); val parameters = new ArrayList<String>(); for (String argument : argumentOrder) { parameters.add(arguments.get(argument) + " " + argument); } enumBuilder.append(Joiner.on(",").join(parameters)); enumBuilder.append(") {\n"); val initialize = new ArrayList<String>(); for (String argument : argumentOrder) { initialize.add("this." + argument + " = " + argument + ";"); } enumBuilder.append(Joiner.on("\n").join(initialize)); enumBuilder.append("\n}\n\n"); for (String argument : argumentOrder) { enumBuilder.append("public "); enumBuilder.append(arguments.get(argument)); enumBuilder.append(" get"); enumBuilder.append(StringUtils.capitalize(argument)); enumBuilder.append("() {\n"); enumBuilder.append("return this."); enumBuilder.append(argument); enumBuilder.append(";\n}\n\n"); } enumBuilder.append("}"); return enumBuilder.toString(); } private boolean needsQuotes(String dataType, String value) { return !(value.equals("null") || NON_QUOTE_DATA_TYPES.contains(dataType)); } private EnumWrapper getDataFromCSVFile() { final EnumWrapper data; try { data = getDataFromCSVFileThrowsException(); } catch (IOException ex) { throw new IllegalStateException(String.format("Unable to parse file: %s", CSV_FILE), ex); } return data; } private EnumWrapper getDataFromCSVFileThrowsException() throws IOException { val data = new ArrayList<EnumData>(); val fileReader = new FileReader(CSV_FILE); val records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(fileReader); val headerDataTypes = new HashMap<String, String>(); val headerMap = records.getHeaderMap(); for (String header : headerMap.keySet()) { if (!header.trim().equals(ENUM_INITIALIZATION_VALUE)) { val split = header.trim().split(" "); if (split.length != 2) { throw new IllegalStateException(String.format("Invalid header: %s", header)); } headerDataTypes.put(split[1], split[0]); } } for (CSVRecord record : records) { val entry = new HashMap<String, String>(); for (String header : headerMap.keySet()) { if (!header.trim().equals(ENUM_INITIALIZATION_VALUE)) { entry.put(header.trim().split(" ")[1], record.get(headerMap.get(header))); } } data.add(new EnumData(record.get(headerMap.get(ENUM_INITIALIZATION_VALUE)), ImmutableMap.copyOf(entry))); } return new EnumWrapper(ImmutableList.copyOf(data), ImmutableMap.copyOf(headerDataTypes)); } @Data @AllArgsConstructor static class EnumWrapper { private ImmutableList<EnumData> enumData; private ImmutableMap<String, String> dataTypes; } @Data @AllArgsConstructor static class EnumData { private String name; private ImmutableMap<String, String> initializationValues; } }
mit
arvast/317refactor
src/com/jagex/runescape/DrawingArea.java
7047
package com.jagex.runescape; /* * This file is part of the RuneScape client * revision 317, which was publicly released * on the 13th of June 2005. * * This file has been refactored in order to * restore readability to the codebase for * educational purposes, primarility to those * with an interest in game development. * * It may be a criminal offence to run this * file. This file is the intellectual property * of Jagex Ltd. */ /* * This file was renamed as part of the 317refactor project. */ public class DrawingArea extends QueueLink { public static int pixels[]; public static int width; public static int height; public static int topY; public static int bottomY; public static int topX; public static int bottomX; public static int centerX; public static int viewportCentreX; public static int viewportCentreY; DrawingArea() { } public static void clear() { int i = width * height; for (int j = 0; j < i; j++) pixels[j] = 0; } public static void defaultDrawingAreaSize() { topX = 0; topY = 0; bottomX = width; bottomY = height; centerX = bottomX - 1; viewportCentreX = bottomX / 2; } public static void drawFilledCircle(int x, int y, int radius, int colour) { for (int _y = -radius; _y <= radius; _y++) for (int _x = -radius; _x <= radius; _x++) if (_x * _x + _y * _y <= radius * radius) drawHorizontalLine(_x + x, _y + y, 1, colour); } public static void drawFilledCircleAlpha(int x, int y, int radius, int colour, int alpha) { for (int _y = -radius; _y <= radius; _y++) for (int _x = -radius; _x <= radius; _x++) if (_x * _x + _y * _y <= radius * radius) drawHorizontalLineAlpha(_x + x, _y + y, 1, colour, alpha); } public static void drawFilledRectangle(int x, int y, int width, int height, int colour) { if (x < topX) { width -= topX - x; x = topX; } if (y < topY) { height -= topY - y; y = topY; } if (x + width > bottomX) width = bottomX - x; if (y + height > bottomY) height = bottomY - y; int increment = DrawingArea.width - width; int pointer = x + y * DrawingArea.width; for (int row = -height; row < 0; row++) { for (int column = -width; column < 0; column++) pixels[pointer++] = colour; pointer += increment; } } public static void drawFilledRectangleAlpha(int colour, int y, int width, int height, int alpha, int x) { if (x < topX) { width -= topX - x; x = topX; } if (y < topY) { height -= topY - y; y = topY; } if (x + width > bottomX) width = bottomX - x; if (y + height > bottomY) height = bottomY - y; int l1 = 256 - alpha; int i2 = (colour >> 16 & 0xff) * alpha; int j2 = (colour >> 8 & 0xff) * alpha; int k2 = (colour & 0xff) * alpha; int k3 = DrawingArea.width - width; int l3 = x + y * DrawingArea.width; for (int i4 = 0; i4 < height; i4++) { for (int j4 = -width; j4 < 0; j4++) { int l2 = (pixels[l3] >> 16 & 0xff) * l1; int i3 = (pixels[l3] >> 8 & 0xff) * l1; int j3 = (pixels[l3] & 0xff) * l1; int packedRGB = ((i2 + l2 >> 8) << 16) + ((j2 + i3 >> 8) << 8) + (k2 + j3 >> 8); pixels[l3++] = packedRGB; } l3 += k3; } } public static void drawHorizontalLine(int x, int y, int width, int colour) { if (x < topY || x >= bottomY) return; if (y < topX) { width -= topX - y; y = topX; } if (y + width > bottomX) width = bottomX - y; int pointer = y + x * DrawingArea.width; for (int column = 0; column < width; column++) pixels[pointer + column] = colour; } public static void drawHorizontalLineAlpha(int x, int y, int width, int colour, int alpha) { if (x < topY || x >= bottomY) return; if (y < topX) { width -= topX - y; y = topX; } if (y + width > bottomX) width = bottomX - y; int opacity = 256 - alpha; int r = (colour >> 16 & 0xff) * alpha; int g = (colour >> 8 & 0xff) * alpha; int b = (colour & 0xff) * alpha; int pointer = y + x * DrawingArea.width; for (int column = 0; column < width; column++) { int rAlpha = (pixels[pointer + column] >> 16 & 0xff) * opacity; int gAlpha = (pixels[pointer + column] >> 8 & 0xff) * opacity; int bAlpha = (pixels[pointer + column] & 0xff) * opacity; int packedRGB = ((r + rAlpha >> 8) << 16) + ((g + gAlpha >> 8) << 8) + (b + bAlpha >> 8); pixels[pointer + column] = packedRGB; } } public static void drawUnfilledRectangle(int i, int j, int k, int l, int i1) { drawHorizontalLine(i1, i, j, l); drawHorizontalLine((i1 + k) - 1, i, j, l); drawVerticalLine(i, i1, k, l); drawVerticalLine((i + j) - 1, i1, k, l); } public static void drawUnfilledRectangleAlpha(int i, int j, int k, int l, int i1, int j1) { method340(l, i1, i, k, j1); method340(l, i1, (i + j) - 1, k, j1); if (j >= 3) { method342(l, j1, k, i + 1, j - 2); method342(l, (j1 + i1) - 1, k, i + 1, j - 2); } } public static void drawVerticalLine(int x, int y, int height, int colour) { if (x < topX || x >= bottomX) return; if (y < topY) { height -= topY - y; y = topY; } if (y + height > bottomY) height = bottomY - y; int pointer = x + y * DrawingArea.width; for (int row = 0; row < height; row++) pixels[pointer + row * DrawingArea.width] = colour; } public static void initDrawingArea(int height, int width, int pixels[]) { DrawingArea.pixels = pixels; DrawingArea.width = width; DrawingArea.height = height; setDrawingArea(height, 0, width, 0); } public static void setDrawingArea(int h, int j, int w, int l) { if (j < 0) j = 0; if (l < 0) l = 0; if (w > width) w = width; if (h > height) h = height; topX = j; topY = l; bottomX = w; bottomY = h; centerX = bottomX - 1; viewportCentreX = bottomX / 2; viewportCentreY = bottomY / 2; } private static void method340(int i, int j, int k, int l, int i1) { if (k < topY || k >= bottomY) return; if (i1 < topX) { j -= topX - i1; i1 = topX; } if (i1 + j > bottomX) j = bottomX - i1; int j1 = 256 - l; int k1 = (i >> 16 & 0xff) * l; int l1 = (i >> 8 & 0xff) * l; int i2 = (i & 0xff) * l; int i3 = i1 + k * width; for (int j3 = 0; j3 < j; j3++) { int j2 = (pixels[i3] >> 16 & 0xff) * j1; int k2 = (pixels[i3] >> 8 & 0xff) * j1; int l2 = (pixels[i3] & 0xff) * j1; int k3 = ((k1 + j2 >> 8) << 16) + ((l1 + k2 >> 8) << 8) + (i2 + l2 >> 8); pixels[i3++] = k3; } } private static void method342(int i, int j, int k, int l, int i1) { if (j < topX || j >= bottomX) return; if (l < topY) { i1 -= topY - l; l = topY; } if (l + i1 > bottomY) i1 = bottomY - l; int j1 = 256 - k; int k1 = (i >> 16 & 0xff) * k; int l1 = (i >> 8 & 0xff) * k; int i2 = (i & 0xff) * k; int i3 = j + l * width; for (int j3 = 0; j3 < i1; j3++) { int j2 = (pixels[i3] >> 16 & 0xff) * j1; int k2 = (pixels[i3] >> 8 & 0xff) * j1; int l2 = (pixels[i3] & 0xff) * j1; int k3 = ((k1 + j2 >> 8) << 16) + ((l1 + k2 >> 8) << 8) + (i2 + l2 >> 8); pixels[i3] = k3; i3 += width; } } }
mit
PeterCappello/cs290bHw2
Cs290bHw2/src/system/ComputerImpl.java
2901
/* * The MIT License * * Copyright 2015 peter. * * 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 system; import api.*; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.logging.Level; import java.util.logging.Logger; /** * An implementation of the Remote Computer interface. * @author Peter Cappello */ public class ComputerImpl extends UnicastRemoteObject implements Computer { public int numTasks = 0; public ComputerImpl() throws RemoteException {} /** * Execute a Task. * @param <T> type of return value. * @param task to be executed. * @return the return-value of the Task call method. * @throws RemoteException */ @Override public <T> Result<T> execute( Task<T> task ) throws RemoteException { numTasks++; final long startTime = System.nanoTime(); final T value = task.call(); final long runTime = ( System.nanoTime() - startTime ) / 1000000; // milliseconds return new Result<>( value, runTime ); } public static void main( String[] args ) throws Exception { System.setSecurityManager( new SecurityManager() ); final String domainName = "localhost"; final String url = "rmi://" + domainName + ":" + Space.PORT + "/" + Space.SERVICE_NAME; final Space space = (Space) Naming.lookup( url ); space.register( new ComputerImpl() ); System.out.println( "Computer running." ); } /** * Terminate the JVM. * @throws RemoteException - always! */ @Override public void exit() throws RemoteException { Logger.getLogger( this.getClass().getName() ) .log(Level.INFO, "Computer: on exit, # completed [0] tasks:", numTasks ); System.exit( 0 ); } }
mit
cinjoff/XChange-1
xchange-core/src/main/java/com/xeiam/xchange/currency/CurrencyPair.java
13564
package com.xeiam.xchange.currency; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * <p> * Value object to provide the following to API: * </p> * <ul> * <li>Provision of major currency symbol pairs (EUR/USD, GBP/USD etc)</li> * <li>Provision of arbitrary symbol pairs for exchange index trading, notional currencies etc</li> * </ul> * <p> * Symbol pairs are quoted, for example, as EUR/USD 1.25 such that 1 EUR can be purchased with 1.25 USD * </p> */ @JsonSerialize(using = CustomCurrencyPairSerializer.class) public class CurrencyPair { // Provide some standard major symbols public static final CurrencyPair EUR_USD = new CurrencyPair(Currencies.EUR, Currencies.USD); public static final CurrencyPair GBP_USD = new CurrencyPair(Currencies.GBP, Currencies.USD); public static final CurrencyPair USD_JPY = new CurrencyPair(Currencies.USD, Currencies.JPY); public static final CurrencyPair JPY_USD = new CurrencyPair(Currencies.JPY, Currencies.USD); public static final CurrencyPair USD_CHF = new CurrencyPair(Currencies.USD, Currencies.CHF); public static final CurrencyPair USD_AUD = new CurrencyPair(Currencies.USD, Currencies.AUD); public static final CurrencyPair USD_CAD = new CurrencyPair(Currencies.USD, Currencies.CAD); public static final CurrencyPair USD_RUR = new CurrencyPair(Currencies.USD, Currencies.RUR); public static final CurrencyPair EUR_RUR = new CurrencyPair(Currencies.EUR, Currencies.RUR); public static final CurrencyPair USD_XRP = new CurrencyPair(Currencies.USD, Currencies.XRP); public static final CurrencyPair EUR_XRP = new CurrencyPair(Currencies.EUR, Currencies.XRP); public static final CurrencyPair USD_XVN = new CurrencyPair(Currencies.USD, Currencies.XVN); public static final CurrencyPair EUR_XVN = new CurrencyPair(Currencies.EUR, Currencies.XVN); public static final CurrencyPair KRW_XRP = new CurrencyPair(Currencies.KRW, Currencies.XRP); // Provide some courtesy BTC major symbols public static final CurrencyPair BTC_USD = new CurrencyPair(Currencies.BTC, Currencies.USD); public static final CurrencyPair BTC_GBP = new CurrencyPair(Currencies.BTC, Currencies.GBP); public static final CurrencyPair BTC_EUR = new CurrencyPair(Currencies.BTC, Currencies.EUR); public static final CurrencyPair BTC_JPY = new CurrencyPair(Currencies.BTC, Currencies.JPY); public static final CurrencyPair BTC_CHF = new CurrencyPair(Currencies.BTC, Currencies.CHF); public static final CurrencyPair BTC_AUD = new CurrencyPair(Currencies.BTC, Currencies.AUD); public static final CurrencyPair BTC_CAD = new CurrencyPair(Currencies.BTC, Currencies.CAD); public static final CurrencyPair BTC_CNY = new CurrencyPair(Currencies.BTC, Currencies.CNY); public static final CurrencyPair BTC_DKK = new CurrencyPair(Currencies.BTC, Currencies.DKK); public static final CurrencyPair BTC_HKD = new CurrencyPair(Currencies.BTC, Currencies.HKD); public static final CurrencyPair BTC_MXN = new CurrencyPair(Currencies.BTC, Currencies.MXN); public static final CurrencyPair BTC_NZD = new CurrencyPair(Currencies.BTC, Currencies.NZD); public static final CurrencyPair BTC_PLN = new CurrencyPair(Currencies.BTC, Currencies.PLN); public static final CurrencyPair BTC_RUB = new CurrencyPair(Currencies.BTC, Currencies.RUB); public static final CurrencyPair BTC_SEK = new CurrencyPair(Currencies.BTC, Currencies.SEK); public static final CurrencyPair BTC_SGD = new CurrencyPair(Currencies.BTC, Currencies.SGD); public static final CurrencyPair BTC_NOK = new CurrencyPair(Currencies.BTC, Currencies.NOK); public static final CurrencyPair BTC_THB = new CurrencyPair(Currencies.BTC, Currencies.THB); public static final CurrencyPair BTC_RUR = new CurrencyPair(Currencies.BTC, Currencies.RUR); public static final CurrencyPair BTC_ZAR = new CurrencyPair(Currencies.BTC, Currencies.ZAR); public static final CurrencyPair BTC_BRL = new CurrencyPair(Currencies.BTC, Currencies.BRL); public static final CurrencyPair BTC_CZK = new CurrencyPair(Currencies.BTC, Currencies.CZK); public static final CurrencyPair BTC_ILS = new CurrencyPair(Currencies.BTC, Currencies.ILS); public static final CurrencyPair BTC_KRW = new CurrencyPair(Currencies.BTC, Currencies.KRW); public static final CurrencyPair BTC_LTC = new CurrencyPair(Currencies.BTC, Currencies.LTC); public static final CurrencyPair BTC_XRP = new CurrencyPair(Currencies.BTC, Currencies.XRP); public static final CurrencyPair BTC_NMC = new CurrencyPair(Currencies.BTC, Currencies.NMC); public static final CurrencyPair BTC_XVN = new CurrencyPair(Currencies.BTC, Currencies.XVN); public static final CurrencyPair BTC_IDR = new CurrencyPair(Currencies.BTC, Currencies.IDR); public static final CurrencyPair BTC_PHP = new CurrencyPair(Currencies.BTC, Currencies.PHP); public static final CurrencyPair BTC_STR = new CurrencyPair(Currencies.BTC, Currencies.STR); public static final CurrencyPair XDC_BTC = new CurrencyPair(Currencies.XDC, Currencies.BTC); public static final CurrencyPair XRP_BTC = new CurrencyPair(Currencies.XRP, Currencies.BTC); public static final CurrencyPair LTC_USD = new CurrencyPair(Currencies.LTC, Currencies.USD); public static final CurrencyPair LTC_KRW = new CurrencyPair(Currencies.LTC, Currencies.KRW); public static final CurrencyPair LTC_CNY = new CurrencyPair(Currencies.LTC, Currencies.CNY); public static final CurrencyPair LTC_RUR = new CurrencyPair(Currencies.LTC, Currencies.RUR); public static final CurrencyPair LTC_EUR = new CurrencyPair(Currencies.LTC, Currencies.EUR); public static final CurrencyPair LTC_BTC = new CurrencyPair(Currencies.LTC, Currencies.BTC); public static final CurrencyPair LTC_XRP = new CurrencyPair(Currencies.LTC, Currencies.XRP); public static final CurrencyPair NMC_USD = new CurrencyPair(Currencies.NMC, Currencies.USD); public static final CurrencyPair NMC_CNY = new CurrencyPair(Currencies.NMC, Currencies.CNY); public static final CurrencyPair NMC_EUR = new CurrencyPair(Currencies.NMC, Currencies.EUR); public static final CurrencyPair NMC_KRW = new CurrencyPair(Currencies.NMC, Currencies.KRW); public static final CurrencyPair NMC_BTC = new CurrencyPair(Currencies.NMC, Currencies.BTC); public static final CurrencyPair NMC_LTC = new CurrencyPair(Currencies.NMC, Currencies.LTC); public static final CurrencyPair NMC_XRP = new CurrencyPair(Currencies.NMC, Currencies.XRP); public static final CurrencyPair NVC_USD = new CurrencyPair(Currencies.NVC, Currencies.USD); public static final CurrencyPair NVC_BTC = new CurrencyPair(Currencies.NVC, Currencies.BTC); public static final CurrencyPair TRC_BTC = new CurrencyPair(Currencies.TRC, Currencies.BTC); public static final CurrencyPair PPC_USD = new CurrencyPair(Currencies.PPC, Currencies.USD); public static final CurrencyPair PPC_BTC = new CurrencyPair(Currencies.PPC, Currencies.BTC); public static final CurrencyPair PPC_LTC = new CurrencyPair(Currencies.PPC, Currencies.LTC); public static final CurrencyPair FTC_USD = new CurrencyPair(Currencies.FTC, Currencies.USD); public static final CurrencyPair FTC_CNY = new CurrencyPair(Currencies.FTC, Currencies.CNY); public static final CurrencyPair FTC_BTC = new CurrencyPair(Currencies.FTC, Currencies.BTC); public static final CurrencyPair FTC_LTC = new CurrencyPair(Currencies.FTC, Currencies.LTC); public static final CurrencyPair XPM_USD = new CurrencyPair(Currencies.XPM, Currencies.USD); public static final CurrencyPair XPM_CNY = new CurrencyPair(Currencies.XPM, Currencies.CNY); public static final CurrencyPair XPM_BTC = new CurrencyPair(Currencies.XPM, Currencies.BTC); public static final CurrencyPair XPM_LTC = new CurrencyPair(Currencies.XPM, Currencies.LTC); public static final CurrencyPair XPM_PPC = new CurrencyPair(Currencies.XPM, Currencies.PPC); public static final CurrencyPair XVN_XRP = new CurrencyPair(Currencies.XVN, Currencies.XRP); // start of extra ANX supported pair // BTC public static final CurrencyPair BTC_XDC = new CurrencyPair(Currencies.BTC, Currencies.XDC); public static final CurrencyPair BTC_PPC = new CurrencyPair(Currencies.BTC, Currencies.PPC); // LTC public static final CurrencyPair LTC_HKD = new CurrencyPair(Currencies.LTC, Currencies.HKD); public static final CurrencyPair LTC_XDC = new CurrencyPair(Currencies.LTC, Currencies.XDC); public static final CurrencyPair LTC_NMC = new CurrencyPair(Currencies.LTC, Currencies.NMC); public static final CurrencyPair LTC_PPC = new CurrencyPair(Currencies.LTC, Currencies.PPC); // DOGE public static final CurrencyPair DOGE_HKD = new CurrencyPair(Currencies.DOGE, Currencies.HKD); public static final CurrencyPair DOGE_BTC = new CurrencyPair(Currencies.DOGE, Currencies.BTC); public static final CurrencyPair DOGE_LTC = new CurrencyPair(Currencies.DOGE, Currencies.LTC); public static final CurrencyPair DOGE_NMC = new CurrencyPair(Currencies.DOGE, Currencies.NMC); public static final CurrencyPair DOGE_PPC = new CurrencyPair(Currencies.DOGE, Currencies.PPC); public static final CurrencyPair DOGE_USD = new CurrencyPair(Currencies.DOGE, Currencies.USD); public static final CurrencyPair XDC_HKD = new CurrencyPair(Currencies.XDC, Currencies.HKD); public static final CurrencyPair XDC_LTC = new CurrencyPair(Currencies.XDC, Currencies.LTC); public static final CurrencyPair XDC_NMC = new CurrencyPair(Currencies.XDC, Currencies.NMC); public static final CurrencyPair XDC_PPC = new CurrencyPair(Currencies.XDC, Currencies.PPC); public static final CurrencyPair XDC_USD = new CurrencyPair(Currencies.XDC, Currencies.USD); // NMC public static final CurrencyPair NMC_HKD = new CurrencyPair(Currencies.NMC, Currencies.HKD); public static final CurrencyPair NMC_XDC = new CurrencyPair(Currencies.NMC, Currencies.XDC); public static final CurrencyPair NMC_PPC = new CurrencyPair(Currencies.NMC, Currencies.PPC); // PPC public static final CurrencyPair PPC_HKD = new CurrencyPair(Currencies.PPC, Currencies.HKD); public static final CurrencyPair PPC_XDC = new CurrencyPair(Currencies.PPC, Currencies.XDC); public static final CurrencyPair PPC_NMC = new CurrencyPair(Currencies.PPC, Currencies.NMC); // end // not real currencies, but tradable commodities (GH/s) public static final CurrencyPair GHs_BTC = new CurrencyPair(Currencies.GHs, Currencies.BTC); public static final CurrencyPair GHs_NMC = new CurrencyPair(Currencies.GHs, Currencies.NMC); public static final CurrencyPair CNC_BTC = new CurrencyPair(Currencies.CNC, Currencies.BTC); public static final CurrencyPair WDC_USD = new CurrencyPair(Currencies.WDC, Currencies.USD); public static final CurrencyPair WDC_BTC = new CurrencyPair(Currencies.WDC, Currencies.BTC); public static final CurrencyPair DVC_BTC = new CurrencyPair(Currencies.DVC, Currencies.BTC); public static final CurrencyPair DGC_BTC = new CurrencyPair(Currencies.DGC, Currencies.BTC); public static final CurrencyPair UTC_USD = new CurrencyPair(Currencies.UTC, Currencies.USD); public static final CurrencyPair UTC_EUR = new CurrencyPair(Currencies.UTC, Currencies.EUR); public static final CurrencyPair UTC_BTC = new CurrencyPair(Currencies.UTC, Currencies.BTC); public static final CurrencyPair UTC_LTC = new CurrencyPair(Currencies.UTC, Currencies.LTC); public final String baseSymbol; public final String counterSymbol; /** * <p> * Full constructor * </p> * In general the CurrencyPair.base is what you're wanting to buy/sell. The CurrencyPair.counter is what currency you want to use to pay/receive for * your purchase/sale. * * @param baseSymbol The base symbol is what you're wanting to buy/sell * @param counterSymbol The counter symbol is what currency you want to use to pay/receive for your purchase/sale. */ public CurrencyPair(String baseSymbol, String counterSymbol) { this.baseSymbol = baseSymbol; this.counterSymbol = counterSymbol; } /** * Parse currency pair from a string in the same format as returned by toString() method - ABC/XYZ */ public CurrencyPair(String currencyPair) { int split = currencyPair.indexOf("/"); if (split < 1) { throw new IllegalArgumentException("Could not parse currency pair from '" + currencyPair + "'"); } String base = currencyPair.substring(0, split); String counter = currencyPair.substring(split + 1); this.baseSymbol = base; this.counterSymbol = counter; } @Override public String toString() { return baseSymbol + "/" + counterSymbol; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((baseSymbol == null) ? 0 : baseSymbol.hashCode()); result = prime * result + ((counterSymbol == null) ? 0 : counterSymbol.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CurrencyPair other = (CurrencyPair) obj; if (baseSymbol == null) { if (other.baseSymbol != null) { return false; } } else if (!baseSymbol.equals(other.baseSymbol)) { return false; } if (counterSymbol == null) { if (other.counterSymbol != null) { return false; } } else if (!counterSymbol.equals(other.counterSymbol)) { return false; } return true; } }
mit
mattgillooly/logscale-agent
src/test/java/com/logscale/agent/MainTest.java
494
package com.logscale.agent; import org.junit.*; import org.junit.contrib.java.lang.system.ExpectedSystemExit; public class MainTest { @Rule public final ExpectedSystemExit exit = ExpectedSystemExit.none(); @Test public void testUsage() { exit.expectSystemExitWithStatus(Main.EXIT_CODE_USAGE); Main.main(); } @Test public void testBadUrl() { exit.expectSystemExitWithStatus(Main.EXIT_CODE_BAD_URL); Main.main("not a url"); } }
mit
martin-lizner/trezor-ssh-agent
src/main/java/com/trezoragent/exception/DeviceTimeoutException.java
131
package com.trezoragent.exception; /** * * @author martin.lizner */ public class DeviceTimeoutException extends Exception { }
mit
Aarronmc/WallpaperCraft
1.7.10/src/main/java/com/Aarron/WallpaperCraft/items/PressAuraLamp.java
827
package com.Aarron.WallpaperCraft.items; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import com.Aarron.WallpaperCraft.creativeTab.Tab; public class PressAuraLamp extends Item { public PressAuraLamp() { setUnlocalizedName("pressauralamp"); setTextureName("wp:pressauralamp"); setContainerItem(this); setCreativeTab(Tab.WPtab); } @Override public void addInformation(ItemStack itemStack, EntityPlayer player, List tooltipLines, boolean advancedTooltips) { tooltipLines.add("Combine this with any solid colored block to apply the Aura pattern and make it glow!"); } @Override public boolean doesContainerItemLeaveCraftingGrid(ItemStack itemstack) { return false; } }
mit
geekmj/course-management
src/main/java/com/geekmj/seedgs/domain/User.java
1078
package com.geekmj.seedgs.domain; import java.io.Serializable; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email; public class User implements Serializable { private static final long serialVersionUID = 1L; private Long userId; /*Only Alphabets allowed in name*/ @NotNull @Size(min=2, max=255, message="{Size.User.Name}") private String name; @NotNull @Min(value = 13, message="Minimum age required is 13, you passed: ${validatedValue}") private Integer age; @NotNull @Email private String email; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
mit
alexandre-normand/blood-shepherd
dexcom-receiver/src/main/java/org/glukit/dexcom/sync/model/UserEventRecord.java
3081
package org.glukit.dexcom.sync.model; import lombok.EqualsAndHashCode; import lombok.ToString; import java.util.Map; import static com.google.common.collect.Maps.newHashMap; /** * Represents a record of {@link RecordType#UserEventData}. * * @author alexandre.normand */ @ToString @EqualsAndHashCode public class UserEventRecord { public static final int RECORD_LENGTH = 20; private long internalSecondsSinceDexcomEpoch; private long localSecondsSinceDexcomEpoch; private UserEventType eventType; private byte eventSubType; private long eventSecondsSinceDexcomEpoch; private long eventValue; public UserEventRecord(long internalSecondsSinceDexcomEpoch, long localSecondsSinceDexcomEpoch, long eventSecondsSinceDexcomEpoch, UserEventType eventType, byte eventSubType, long eventValue) { this.internalSecondsSinceDexcomEpoch = internalSecondsSinceDexcomEpoch; this.localSecondsSinceDexcomEpoch = localSecondsSinceDexcomEpoch; this.eventType = eventType; this.eventSubType = eventSubType; this.eventSecondsSinceDexcomEpoch = eventSecondsSinceDexcomEpoch; this.eventValue = eventValue; } public long getInternalSecondsSinceDexcomEpoch() { return internalSecondsSinceDexcomEpoch; } public long getLocalSecondsSinceDexcomEpoch() { return localSecondsSinceDexcomEpoch; } public UserEventType getEventType() { return eventType; } public byte getEventSubType() { return eventSubType; } public long getEventSecondsSinceDexcomEpoch() { return eventSecondsSinceDexcomEpoch; } public long getEventValue() { return eventValue; } public static enum UserEventType { CARBS((byte) 1), EXERCISE((byte) 4), HEALTH((byte) 3), INSULIN((byte) 2), MaxValue((byte) 5), NullType((byte) 0); private byte id; private static Map<Byte, UserEventType> mappings; private UserEventType(byte id) { this.id = id; addMapping(id, this); } private static void addMapping(byte id, UserEventType recordType) { if (mappings == null) { mappings = newHashMap(); } mappings.put(id, recordType); } public static UserEventType fromId(byte id) { return mappings.get(id); } public byte getId() { return id; } } public static enum ExerciseIntensity { HEAVY((byte) 3), LIGHT((byte) 1), MaxValue((byte) 4), MEDIUM((byte) 2), Null((byte) 0); private byte id; private static Map<Byte, ExerciseIntensity> mappings; private ExerciseIntensity(byte id) { this.id = id; addMapping(id, this); } private static void addMapping(byte id, ExerciseIntensity recordType) { if (mappings == null) { mappings = newHashMap(); } mappings.put(id, recordType); } public static ExerciseIntensity fromId(byte id) { return mappings.get(id); } public byte getId() { return id; } } }
mit
shunjikonishi/hypdf4j
src/main/java/jp/co/flect/hypdf/json/JsonByGson.java
637
package jp.co.flect.hypdf.json; import java.util.List; import java.util.Map; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class JsonByGson implements Json { public List<Map<String, Object>> parseArray(String str) { Type type = new TypeToken<List<Map<String, Object>>>() {}.getType(); return new Gson().fromJson(str, type); } public Map<String, Object> parse(String str) { Type type = new TypeToken<Map<String, Object>>() {}.getType(); return new Gson().fromJson(str, type); } public String serialize(Object obj) { return new Gson().toJson(obj); } }
mit
enhorse/FUDS
src/main/java/xyz/enhorse/utils/DateFolder.java
1715
package xyz.enhorse.utils; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Date; /** * 07.10.2015. */ public class DateFolder { private static final String TEMPLATE = File.separator + "YEAR" + File.separator + "MONTH" + File.separator + "DAY" + File.separator; private Date date; public DateFolder(Date date) { setDate(date); } public Date getDate() { return date; } public void setDate(Date value) { date = value; } public Path createIn(Path root) throws IllegalArgumentException { Path result; if (isExistingFolder(root)) { String path = root.toFile().getAbsolutePath(); path = path + generatePathString(date); try { result = Files.createDirectories(Paths.get(path)); } catch (IOException e) { result = null; } } else { throw new IllegalArgumentException(root + "is not a valid directory!"); } return result; } private String generatePathString(Date date) { String year = (new SimpleDateFormat("YY")).format(date.getTime()); String month = (new SimpleDateFormat("MM")).format(date.getTime()); String day = (new SimpleDateFormat("dd")).format(date.getTime()); return TEMPLATE.replaceAll("YEAR", year).replaceAll("MONTH", month).replaceAll("DAY", day); } private boolean isExistingFolder(Path path) { return (path != null) && (path.toFile().isDirectory()); } }
mit
kcsl/immutability-benchmark
benchmark-applications/reiminfer-oopsla-2012/source/JdbF/src/org/jdbf/engine/configuration/ConfigurationException.java
3294
/* * 04/04/2002 - 23:12:27 * * $RCSfile: ConfigurationException.java,v $ - JDBF Object Relational mapping system * Copyright (C) 2002 JDBF Development Team * * http://jdbf.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * $Id: ConfigurationException.java,v 1.4 2004/05/20 22:36:38 gmartone Exp $ */ package org.jdbf.engine.configuration; import org.jdbf.engine.JDBFException; import org.jdbf.castor.Messages; /** * <code>ConfigurationException</code> handles exception that occur * during parsing configuration process.<br> * * @author Giovanni Martone<br> * @version $Revision: 1.4 $<br> * last changed by $Author: gmartone $ * */ public class ConfigurationException extends JDBFException { /** * Nested Exception */ private Exception except; /** * Creates exception with message * * @param message */ public ConfigurationException (String message){ super(Messages.message(message)); } /** * Creates exception with message and Integer parameter * * @param message * @param type */ public ConfigurationException (String message, Integer type){ super(Messages.format(message, type)); } /** * Creates exception with message and int param * * @param message * @param type */ public ConfigurationException (String message, int type){ this(message, new Integer(type)); } /** * Creates exception with message and String parameter * * @param message * @param type */ public ConfigurationException (String message, String type){ super(Messages.format(message, type)); } /** * Creates exception with message and two String parameters * * Message is parsed with two parameter to create error message * * @param message * @param type1 * @param type2 */ public ConfigurationException (String message, String type1, String type2){ super(Messages.format(message, type1, type2)); } /** * Creates exception with a nested exception * * @param except */ public ConfigurationException(Exception except){ super(Messages.format("config.nested", except.toString())); this.except = except; } /** * Return nested exception * * @return Exception * */ public Exception getException() { return except; } } /* * $Log: ConfigurationException.java,v $ * Revision 1.4 2004/05/20 22:36:38 gmartone * Changed for task 99073 (Coverage Javadocs) * */
mit
Naftoreiclag/Minecraft-Face-Recognition
java/naftoreiclag/mcfacerecog/MainPanel.java
991
package naftoreiclag.mcfacerecog; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.swing.JPanel; @SuppressWarnings("serial") public class MainPanel extends JPanel { BufferedImage helloWorld; BufferedImage[] yes; public MainPanel() { this.setSize(300, 200); helloWorld = FaceGetter.getSkin("Reiclag"); //System.out.println(ColorCompare.similarity(helloWorld.getRGB(0, 0), helloWorld.getRGB(0, 1))); //System.out.println(ColorCompare.similarity(helloWorld.getRGB(0, 0), helloWorld.getRGB(0, 3))); yes = ShapeDetector.detectShapes(helloWorld); System.out.println(yes.length); } @Override public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; g2.drawImage(helloWorld, 10, 10, 64, 64, null); for(int x = 0; x < yes.length; ++ x) { //g2.drawImage(helloWorld, (x * 74) + 84, 10, 64, 64, null); g2.drawImage(yes[x], (x * 74) + 84, 10, 64, 64, null); } } }
mit
tunefish/simplify
simplify/Obfuscated/app/src/main/java/org/cf/obfuscated/DESCrypt.java
1991
package org.cf.obfuscated; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.security.spec.KeySpec; public class DESCrypt { private static Cipher cipher = null; private static SecretKeyFactory mySecretKeyFactory = null; static { try { cipher = Cipher.getInstance("DES"); mySecretKeyFactory = SecretKeyFactory.getInstance("DES"); } catch (Exception e) { } } public static byte[] encrypt(String string, String keyString) { try { byte[] encryptionKey = keyString.getBytes("UTF8"); KeySpec myKeySpec = new DESKeySpec(encryptionKey); SecretKey key = mySecretKeyFactory.generateSecret(myKeySpec); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] stringBytes = string.getBytes("UTF8"); byte[] encryptedBytes = cipher.doFinal(stringBytes); return encryptedBytes; } catch (Exception e) { e.printStackTrace(); return new byte[0]; } } public static String decrypt(byte[] encrypted, String keyString) { String decrypted = null; try { byte[] encryptionKey = keyString.getBytes("UTF8"); KeySpec myKeySpec = new DESKeySpec(encryptionKey); SecretKey key = mySecretKeyFactory.generateSecret(myKeySpec); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decryptedBytes = cipher.doFinal(encrypted); return new String(decryptedBytes); } catch (Exception e) { e.printStackTrace(); return ""; } } public static void main(String[] argv) throws Exception { // DESCrypt dc = new DESCrypt(StringHolder.desKey); // byte[] encrypt = dc.encrypt("secretMethod2"); // System.out.println(Arrays.toString(encrypt)); // System.out.println(dc.decrypt(encrypt)); } }
mit
GeneralizedLearningUtilities/SuperGLU
java_maven/src/main/java/edu/usc/ict/superglu/ipc/HintServiceIPCRunner.java
10737
package edu.usc.ict.superglu.ipc; import static edu.usc.ict.superglu.core.Message.CONTEXT_CONVERSATION_ID_KEY; import static edu.usc.ict.superglu.core.Message.CONTEXT_IN_REPLY_TO_KEY; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author rthaker * */ import org.zeromq.ZMQ; import com.google.common.base.Predicate; import edu.usc.ict.superglu.core.BaseMessage; import edu.usc.ict.superglu.core.BaseMessagingNode; import edu.usc.ict.superglu.core.BaseService; import edu.usc.ict.superglu.core.ExternalMessagingHandler; import edu.usc.ict.superglu.core.Message; import edu.usc.ict.superglu.core.MessagingGateway; import edu.usc.ict.superglu.core.SpeechActEnum; import edu.usc.ict.superglu.core.config.ServiceConfiguration; import edu.usc.ict.superglu.util.SerializationConvenience; import edu.usc.ict.superglu.util.SerializationFormatEnum; import edu.usc.ict.superglu.util.SuperGlu_Serializable; public class HintServiceIPCRunner { final String ZERO_MQ_SENDER = "tcp://localhost:5558"; final String ZERO_MQ_SINK = "tcp://localhost:5557"; protected Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); private List<BaseMessage> testMessages; private static HintService hintService; private MessagingGateway gateway; class HintService extends BaseService { private Map<String, Message> proposalsAccepted = new HashMap<>(); //replying conversation-id, propose msg private List<Message> proposalsConfirmReceived = new ArrayList<>(); //replying conversation-id, propose msg private Map<String, Set<String>> proposalsConfirmedToServ = new HashMap<>(); private Queue<String> proposedMsgRequests = new LinkedList<>(); private Map<String, String> auditOfProposedMsgReq = new HashMap<>(); private boolean respondToProposedMessage = false; private boolean respondToProposal = false; private boolean maintainACountForResponse = false; private int counterForResponse = 0; public HintService(String id) { super(id, null); } @Override public boolean receiveMessage(BaseMessage msg) { super.receiveMessage(msg); logger.info("============================================================================"); logger.info("Message received by " + this.getId() + " : " + this.getClass().getName()); if (msg instanceof Message) { logger.info("SpeechAct : " + ((Message) msg).getSpeechAct()); if (((Message) msg).getSpeechAct() == SpeechActEnum.PROPOSE_ACT && respondToProposal) { String conversationId = (String) msg.getContextValue(Message.CONTEXT_CONVERSATION_ID_KEY); String replyingConversationId = "conversation_accept_proposal_" + this.getId() + "_" + System.currentTimeMillis(); proposalsAccepted.put(replyingConversationId, (Message) msg); Message msg2 = (Message) testMessages.get(1).clone(false); msg2.setContextValue(BaseMessagingNode.ORIGINATING_SERVICE_ID_KEY, this.getId()); msg2.setContextValue(CONTEXT_CONVERSATION_ID_KEY, replyingConversationId); msg2.setContextValue(Message.PROPOSAL_KEY, (String) msg.getContextValue(Message.PROPOSAL_KEY)); msg2.setContextValue(CONTEXT_IN_REPLY_TO_KEY, conversationId); this.sendMessage(msg2); } else if (((Message) msg).getSpeechAct() == SpeechActEnum.CONFIRM_PROPOSAL_ACT) { String originalConversationId = (String) msg.getContextValue(Message.CONTEXT_IN_REPLY_TO_KEY); if (proposalsAccepted.get(originalConversationId) != null) { //confirm proposals only for which this service accepted proposalsConfirmReceived.add((Message) msg); String hintPresenter = msg.getContext().get(BaseMessagingNode.ORIGINATING_SERVICE_ID_KEY).toString(); String proposalId = msg.getContext().get(Message.PROPOSAL_KEY).toString(); if(!proposalsConfirmedToServ.containsKey(hintPresenter)) { proposalsConfirmedToServ.put(hintPresenter, new HashSet<>(Arrays.asList(proposalId))); } else { Set<String> proposalsAccepted = proposalsConfirmedToServ.get(hintPresenter); proposalsAccepted.add(proposalId); proposalsConfirmedToServ.put(hintPresenter, proposalsAccepted); } } } else if (((Message) msg).getSpeechAct() == SpeechActEnum.PROPOSED_MESSAGE && (msg.getContextValue("toBeServicedBy").toString().equals(this.getId())) && respondToProposedMessage) { String originalConversationId = (String) msg.getContextValue(Message.PROPOSAL_KEY); String hinterPresenterId = (String) msg.getContextValue(BaseMessagingNode.ORIGINATING_SERVICE_ID_KEY); boolean flag = maintainACountForResponse && (counterForResponse < 2) ? true : !maintainACountForResponse ? true : false; if(flag && proposalsConfirmedToServ.containsKey(hinterPresenterId) && proposalsConfirmedToServ.get(hinterPresenterId).contains(originalConversationId)) { String MessageId = msg.getId(); proposedMsgRequests.add(msg.getId()); auditOfProposedMsgReq.put(msg.getId(), originalConversationId); String proposalMessageRespose = proposedMsgRequests.poll(); if(proposalMessageRespose != null) { Message msgAck = (Message) testMessages.get(1).clone(false); msgAck.setSpeechAct(SpeechActEnum.PROPOSED_MESSAGE_ACKNOWLEDGMENT); msgAck.setContextValue(BaseMessagingNode.ORIGINATING_SERVICE_ID_KEY, this.getId()); msgAck.setContextValue(Message.CONTEXT_CONVERSATION_ID_KEY, "conversation_accept_proposal_" + this.getId() + "_" + System.currentTimeMillis()); msgAck.setContextValue("proposedMessageId", proposalMessageRespose); msgAck.setContextValue(Message.PROPOSAL_KEY, auditOfProposedMsgReq.get(proposalMessageRespose)); msgAck.setContextValue(Message.CONTEXT_IN_REPLY_TO_MESSAGE, MessageId); this.sendMessage(msgAck); } } else { logger.info("My Service name is : "+ this.id + "I am Not Answering Right Now. "); } counterForResponse++; } } logger.info("============================================================================"); return true; } } class ServiceGateway extends MessagingGateway { private ZMQ.Socket requester; public ServiceGateway(String anId, Map<String, Object> scope, Collection<BaseMessagingNode> nodes, Predicate<BaseMessage> conditions, List<ExternalMessagingHandler> handlers, ServiceConfiguration config) { super(anId, scope, nodes, conditions, handlers, config); ZMQ.Context context = ZMQ.context(1); // Socket to talk to server requester = context.socket(ZMQ.PUSH); requester.bind(ZERO_MQ_SENDER); } @Override public void distributeMessage(BaseMessage msg, String senderId) { // TODO Auto-generated method stub super.distributeMessage(msg, senderId); if (((Message) msg).getSpeechAct() != SpeechActEnum.PROPOSE_ACT) { try { String json = SerializationConvenience.serializeObject(msg, SerializationFormatEnum.JSON_FORMAT); System.out.println("launch and connect client."); requester.send(json); } catch (Exception e) { System.out.println("Something Wrong"); } } } } public void run() { ZMQ.Context context = ZMQ.context(1); ZMQ.Socket receiver = context.socket(ZMQ.PULL); receiver.connect(ZERO_MQ_SINK); List<BaseMessagingNode> nodes = new ArrayList<>(); hintService = new HintService("HintService"); hintService.respondToProposal = true; hintService.respondToProposedMessage = true; nodes.add(hintService); ServiceConfiguration config = new ServiceConfiguration("mockConfiguration", null, new HashMap<>(), null, null, null); gateway = new ServiceGateway("GatewayNode", null, nodes, null, null, config); testMessages = buildMessages(); startReception(receiver); } private void startReception(ZMQ.Socket receiver) { ExecutorService receiverService = Executors.newSingleThreadExecutor(); receiverService.submit(() -> { while (!Thread.currentThread().isInterrupted()) { String receptionString = null; if((receptionString = new String(receiver.recv(0)).trim()) != null) { System.out.println(receptionString); System.out.println("CONVERTInG MESSAGE"); SuperGlu_Serializable message = SerializationConvenience.nativeizeObject(receptionString, SerializationFormatEnum.JSON_FORMAT); BaseMessage msgRcd = (BaseMessage) message; System.out.println("CONVERTED MESSAGE!!! BINGO!!"); new Thread(new Runnable() { public void run() { gateway.sendMessage(msgRcd); } }).start(); System.out.print(receptionString + '.'); } } }); } private List<BaseMessage> buildMessages() { List<BaseMessage> result = new ArrayList<>(); Message msg1 = new Message("penguin", "eats", "fish", "Sending Proposal", SpeechActEnum.PROPOSE_ACT, null, new HashMap<>(), "msg1"); result.add(msg1); Message msg2 = new Message("penguin", "eats", "fish", "Accepting Proposal", SpeechActEnum.ACCEPT_PROPOSAL_ACT, null, new HashMap<>(), "msg2"); result.add(msg2); Message msg3 = new Message("penguin", "eats", "fish", "Confirming Proposal", SpeechActEnum.CONFIRM_PROPOSAL_ACT, null, new HashMap<>(), "msg3"); result.add(msg3); return result; } public static void main(String[] args) { HintServiceIPCRunner server = new HintServiceIPCRunner(); server.run(); } }
mit
flyzsd/java-code-snippets
ibm.jdk8/src/javax/sound/midi/ShortMessage.java
17356
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 1998, 2013. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.sound.midi; /** * A <code>ShortMessage</code> contains a MIDI message that has at most * two data bytes following its status byte. The types of MIDI message * that satisfy this criterion are channel voice, channel mode, system common, * and system real-time--in other words, everything except system exclusive * and meta-events. The <code>ShortMessage</code> class provides methods * for getting and setting the contents of the MIDI message. * <p> * A number of <code>ShortMessage</code> methods have integer parameters by which * you specify a MIDI status or data byte. If you know the numeric value, you * can express it directly. For system common and system real-time messages, * you can often use the corresponding fields of <code>ShortMessage</code>, such as * {@link #SYSTEM_RESET SYSTEM_RESET}. For channel messages, * the upper four bits of the status byte are specified by a command value and * the lower four bits are specified by a MIDI channel number. To * convert incoming MIDI data bytes that are in the form of Java's signed bytes, * you can use the <A HREF="MidiMessage.html#integersVsBytes">conversion code</A> * given in the <code>{@link MidiMessage}</code> class description. * * @see SysexMessage * @see MetaMessage * * @author David Rivas * @author Kara Kytle * @author Florian Bomers */ public class ShortMessage extends MidiMessage { // Status byte defines // System common messages /** * Status byte for MIDI Time Code Quarter Frame message (0xF1, or 241). * @see MidiMessage#getStatus */ public static final int MIDI_TIME_CODE = 0xF1; // 241 /** * Status byte for Song Position Pointer message (0xF2, or 242). * @see MidiMessage#getStatus */ public static final int SONG_POSITION_POINTER = 0xF2; // 242 /** * Status byte for MIDI Song Select message (0xF3, or 243). * @see MidiMessage#getStatus */ public static final int SONG_SELECT = 0xF3; // 243 /** * Status byte for Tune Request message (0xF6, or 246). * @see MidiMessage#getStatus */ public static final int TUNE_REQUEST = 0xF6; // 246 /** * Status byte for End of System Exclusive message (0xF7, or 247). * @see MidiMessage#getStatus */ public static final int END_OF_EXCLUSIVE = 0xF7; // 247 // System real-time messages /** * Status byte for Timing Clock message (0xF8, or 248). * @see MidiMessage#getStatus */ public static final int TIMING_CLOCK = 0xF8; // 248 /** * Status byte for Start message (0xFA, or 250). * @see MidiMessage#getStatus */ public static final int START = 0xFA; // 250 /** * Status byte for Continue message (0xFB, or 251). * @see MidiMessage#getStatus */ public static final int CONTINUE = 0xFB; // 251 /** * Status byte for Stop message (0xFC, or 252). * @see MidiMessage#getStatus */ public static final int STOP = 0xFC; //252 /** * Status byte for Active Sensing message (0xFE, or 254). * @see MidiMessage#getStatus */ public static final int ACTIVE_SENSING = 0xFE; // 254 /** * Status byte for System Reset message (0xFF, or 255). * @see MidiMessage#getStatus */ public static final int SYSTEM_RESET = 0xFF; // 255 // Channel voice message upper nibble defines /** * Command value for Note Off message (0x80, or 128) */ public static final int NOTE_OFF = 0x80; // 128 /** * Command value for Note On message (0x90, or 144) */ public static final int NOTE_ON = 0x90; // 144 /** * Command value for Polyphonic Key Pressure (Aftertouch) message (0xA0, or 160) */ public static final int POLY_PRESSURE = 0xA0; // 160 /** * Command value for Control Change message (0xB0, or 176) */ public static final int CONTROL_CHANGE = 0xB0; // 176 /** * Command value for Program Change message (0xC0, or 192) */ public static final int PROGRAM_CHANGE = 0xC0; // 192 /** * Command value for Channel Pressure (Aftertouch) message (0xD0, or 208) */ public static final int CHANNEL_PRESSURE = 0xD0; // 208 /** * Command value for Pitch Bend message (0xE0, or 224) */ public static final int PITCH_BEND = 0xE0; // 224 // Instance variables /** * Constructs a new <code>ShortMessage</code>. The * contents of the new message are guaranteed to specify * a valid MIDI message. Subsequently, you may set the * contents of the message using one of the <code>setMessage</code> * methods. * @see #setMessage */ public ShortMessage() { this(new byte[3]); // Default message data: NOTE_ON on Channel 0 with max volume data[0] = (byte) (NOTE_ON & 0xFF); data[1] = (byte) 64; data[2] = (byte) 127; length = 3; } /** * Constructs a new {@code ShortMessage} which represents a MIDI * message that takes no data bytes. * The contents of the message can be changed by using one of * the {@code setMessage} methods. * * @param status the MIDI status byte * @throws InvalidMidiDataException if {@code status} does not specify * a valid MIDI status byte for a message that requires no data bytes * @see #setMessage(int) * @see #setMessage(int, int, int) * @see #setMessage(int, int, int, int) * @see #getStatus() * @since 1.7 */ public ShortMessage(int status) throws InvalidMidiDataException { super(null); setMessage(status); // can throw InvalidMidiDataException } /** * Constructs a new {@code ShortMessage} which represents a MIDI message * that takes up to two data bytes. If the message only takes one data byte, * the second data byte is ignored. If the message does not take * any data bytes, both data bytes are ignored. * The contents of the message can be changed by using one of * the {@code setMessage} methods. * * @param status the MIDI status byte * @param data1 the first data byte * @param data2 the second data byte * @throws InvalidMidiDataException if the status byte or all data bytes * belonging to the message do not specify a valid MIDI message * @see #setMessage(int) * @see #setMessage(int, int, int) * @see #setMessage(int, int, int, int) * @see #getStatus() * @see #getData1() * @see #getData2() * @since 1.7 */ public ShortMessage(int status, int data1, int data2) throws InvalidMidiDataException { super(null); setMessage(status, data1, data2); // can throw InvalidMidiDataException } /** * Constructs a new {@code ShortMessage} which represents a channel * MIDI message that takes up to two data bytes. If the message only takes * one data byte, the second data byte is ignored. If the message does not * take any data bytes, both data bytes are ignored. * The contents of the message can be changed by using one of * the {@code setMessage} methods. * * @param command the MIDI command represented by this message * @param channel the channel associated with the message * @param data1 the first data byte * @param data2 the second data byte * @throws InvalidMidiDataException if the command value, channel value * or all data bytes belonging to the message do not specify * a valid MIDI message * @see #setMessage(int) * @see #setMessage(int, int, int) * @see #setMessage(int, int, int, int) * @see #getCommand() * @see #getChannel() * @see #getData1() * @see #getData2() * @since 1.7 */ public ShortMessage(int command, int channel, int data1, int data2) throws InvalidMidiDataException { super(null); setMessage(command, channel, data1, data2); } /** * Constructs a new <code>ShortMessage</code>. * @param data an array of bytes containing the complete message. * The message data may be changed using the <code>setMessage</code> * method. * @see #setMessage */ // $$fb this should throw an Exception in case of an illegal message! protected ShortMessage(byte[] data) { // $$fb this may set an invalid message. // Can't correct without compromising compatibility super(data); } /** * Sets the parameters for a MIDI message that takes no data bytes. * @param status the MIDI status byte * @throws InvalidMidiDataException if <code>status</code> does not * specify a valid MIDI status byte for a message that requires no data bytes. * @see #setMessage(int, int, int) * @see #setMessage(int, int, int, int) */ public void setMessage(int status) throws InvalidMidiDataException { // check for valid values int dataLength = getDataLength(status); // can throw InvalidMidiDataException if (dataLength != 0) { throw new InvalidMidiDataException("Status byte; " + status + " requires " + dataLength + " data bytes"); } setMessage(status, 0, 0); } /** * Sets the parameters for a MIDI message that takes one or two data * bytes. If the message takes only one data byte, the second data * byte is ignored; if the message does not take any data bytes, both * data bytes are ignored. * * @param status the MIDI status byte * @param data1 the first data byte * @param data2 the second data byte * @throws InvalidMidiDataException if the * the status byte, or all data bytes belonging to the message, do * not specify a valid MIDI message. * @see #setMessage(int, int, int, int) * @see #setMessage(int) */ public void setMessage(int status, int data1, int data2) throws InvalidMidiDataException { // check for valid values int dataLength = getDataLength(status); // can throw InvalidMidiDataException if (dataLength > 0) { if (data1 < 0 || data1 > 127) { throw new InvalidMidiDataException("data1 out of range: " + data1); } if (dataLength > 1) { if (data2 < 0 || data2 > 127) { throw new InvalidMidiDataException("data2 out of range: " + data2); } } } // set the length length = dataLength + 1; // re-allocate array if ShortMessage(byte[]) constructor gave array with fewer elements if (data == null || data.length < length) { data = new byte[3]; } // set the data data[0] = (byte) (status & 0xFF); if (length > 1) { data[1] = (byte) (data1 & 0xFF); if (length > 2) { data[2] = (byte) (data2 & 0xFF); } } } /** * Sets the short message parameters for a channel message * which takes up to two data bytes. If the message only * takes one data byte, the second data byte is ignored; if * the message does not take any data bytes, both data bytes * are ignored. * * @param command the MIDI command represented by this message * @param channel the channel associated with the message * @param data1 the first data byte * @param data2 the second data byte * @throws InvalidMidiDataException if the * status byte or all data bytes belonging to the message, do * not specify a valid MIDI message * * @see #setMessage(int, int, int) * @see #setMessage(int) * @see #getCommand * @see #getChannel * @see #getData1 * @see #getData2 */ public void setMessage(int command, int channel, int data1, int data2) throws InvalidMidiDataException { // check for valid values if (command >= 0xF0 || command < 0x80) { throw new InvalidMidiDataException("command out of range: 0x" + Integer.toHexString(command)); } if ((channel & 0xFFFFFFF0) != 0) { // <=> (channel<0 || channel>15) throw new InvalidMidiDataException("channel out of range: " + channel); } setMessage((command & 0xF0) | (channel & 0x0F), data1, data2); } /** * Obtains the MIDI channel associated with this event. This method * assumes that the event is a MIDI channel message; if not, the return * value will not be meaningful. * @return MIDI channel associated with the message. * @see #setMessage(int, int, int, int) */ public int getChannel() { // this returns 0 if an invalid message is set return (getStatus() & 0x0F); } /** * Obtains the MIDI command associated with this event. This method * assumes that the event is a MIDI channel message; if not, the return * value will not be meaningful. * @return the MIDI command associated with this event * @see #setMessage(int, int, int, int) */ public int getCommand() { // this returns 0 if an invalid message is set return (getStatus() & 0xF0); } /** * Obtains the first data byte in the message. * @return the value of the <code>data1</code> field * @see #setMessage(int, int, int) */ public int getData1() { if (length > 1) { return (data[1] & 0xFF); } return 0; } /** * Obtains the second data byte in the message. * @return the value of the <code>data2</code> field * @see #setMessage(int, int, int) */ public int getData2() { if (length > 2) { return (data[2] & 0xFF); } return 0; } /** * Creates a new object of the same class and with the same contents * as this object. * @return a clone of this instance. */ public Object clone() { byte[] newData = new byte[length]; System.arraycopy(data, 0, newData, 0, newData.length); ShortMessage msg = new ShortMessage(newData); return msg; } /** * Retrieves the number of data bytes associated with a particular * status byte value. * @param status status byte value, which must represent a short MIDI message * @return data length in bytes (0, 1, or 2) * @throws InvalidMidiDataException if the * <code>status</code> argument does not represent the status byte for any * short message */ protected final int getDataLength(int status) throws InvalidMidiDataException { // system common and system real-time messages switch(status) { case 0xF6: // Tune Request case 0xF7: // EOX // System real-time messages case 0xF8: // Timing Clock case 0xF9: // Undefined case 0xFA: // Start case 0xFB: // Continue case 0xFC: // Stop case 0xFD: // Undefined case 0xFE: // Active Sensing case 0xFF: // System Reset return 0; case 0xF1: // MTC Quarter Frame case 0xF3: // Song Select return 1; case 0xF2: // Song Position Pointer return 2; default: } // channel voice and mode messages switch(status & 0xF0) { case 0x80: case 0x90: case 0xA0: case 0xB0: case 0xE0: return 2; case 0xC0: case 0xD0: return 1; default: throw new InvalidMidiDataException("Invalid status byte: " + status); } } }
mit
teacurran/wirelust-bitbucket-api
client/src/main/java/com/wirelust/bitbucket/client/representations/Update.java
1836
package com.wirelust.bitbucket.client.representations; import java.io.Serializable; import java.util.Date; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonFormat; import com.wirelust.bitbucket.client.Constants; /** * Date: 12-Oct-2015 * * @author T. Curran */ public class Update implements Serializable { private static final long serialVersionUID = 6410285719035915746L; public enum State { OPEN, DECLINED, MERGED; @JsonCreator public static State fromString(String key) { return key == null ? null : State.valueOf(key.toUpperCase()); } } String description; String title; CommitSource destination; CommitSource source; String reason; State state; User author; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = Constants.DATE_TIME_FORMAT) Date date; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public CommitSource getDestination() { return destination; } public void setDestination(CommitSource destination) { this.destination = destination; } public CommitSource getSource() { return source; } public void setSource(CommitSource source) { this.source = source; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public State getState() { return state; } public void setState(State state) { this.state = state; } public User getAuthor() { return author; } public void setAuthor(User author) { this.author = author; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
mit
Alex-BusNet/InfiniteStratos
src/main/java/com/sparta/is/proxy/IProxy.java
433
package com.sparta.is.proxy; import net.minecraftforge.fml.common.event.*; public interface IProxy { default ClientProxy getClientProxy() { return null; } void onPreInit(FMLPreInitializationEvent event); void onInit(FMLInitializationEvent event); void onPostInit(FMLPostInitializationEvent event); void onServerStarting(FMLServerStartingEvent event); void onServerStopping(FMLServerStoppingEvent event); }
mit
jarheadSLO/ProteusCompiler
src/compiler/abstr/tree/AbsVarDef.java
784
package compiler.abstr.tree; import compiler.Position; import compiler.abstr.Visitor; /** * Definicija spremenljivke. * * @author sliva */ public class AbsVarDef extends AbsDef { /** * Ime spremenljivke. */ public final String name; /** * Opis tipa spremenljivke. */ public final AbsType type; /** * Ustvari novo definicijo spremenljivke. * * @param pos Polozaj stavcne oblike tega drevesa. * @param name Ime spremenljivke. * @param type Opis tipa spremenljivke. */ public AbsVarDef(Position pos, String name, AbsType type) { super(pos); this.name = name; this.type = type; } @Override public void accept(Visitor visitor) { visitor.visit(this); } }
mit
ssando/crawl4neo
src/test/java/org/scrumbucket/crawler4neo/GrabPageTest.java
1731
package org.scrumbucket.crawler4neo; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.scrumbucket.crawler4neo.services.GrabPage; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.eq; import static org.powermock.api.mockito.PowerMockito.mockStatic; @RunWith(PowerMockRunner.class) @PrepareForTest(Jsoup.class) public class GrabPageTest { @Test public void testGrabbing() throws Exception { /// create a real jsoup document using a test file String simpleHTML = new String(Files.readAllBytes(Paths.get(getClass().getResource("/simple.html").toURI()))); Document document = Jsoup.parse(simpleHTML); // This is our pretend url. URL fakeUrl = new URL("http://example.com/dir1/page1"); // Invoke powermock to take care of our static Jsoup.parse mockStatic(Jsoup.class); PowerMockito.when(Jsoup.parse(eq(fakeUrl), anyInt())).thenReturn(document); // Run the code to be tested GrabPage grabPage = new GrabPage(fakeUrl, 1); grabPage.call(); // check the results. Set<URL> urls = grabPage.getUrlList(); assertEquals(3, urls.size()); assertTrue(urls.contains(new URL("http://example.com/dir1/link1"))); assertTrue(urls.contains(new URL("http://example.com/link2"))); assertTrue(urls.contains(new URL("http://example.com/relative"))); } }
mit
archimatetool/archi
org.eclipse.gef/src/org/eclipse/gef/tools/CreationTool.java
13626
/******************************************************************************* * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.gef.tools; import org.eclipse.swt.graphics.Cursor; import org.eclipse.draw2d.Cursors; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.PositionConstants; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.PrecisionRectangle; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPartViewer; import org.eclipse.gef.GraphicalEditPart; import org.eclipse.gef.Request; import org.eclipse.gef.SharedCursors; import org.eclipse.gef.SnapToHelper; import org.eclipse.gef.requests.CreateRequest; import org.eclipse.gef.requests.CreationFactory; /** * The CreationTool creates new {@link EditPart EditParts} via a * {@link CreationFactory}. If the user simply clicks on the viewer, the default * sized EditPart will be created at that point. If the user clicks and drags, * the created EditPart will be sized based on where the user clicked and * dragged. */ public class CreationTool extends TargetingTool { /** * Property to be used in {@link AbstractTool#setProperties(java.util.Map)} * for {@link #setFactory(CreationFactory)}. */ public static final Object PROPERTY_CREATION_FACTORY = "factory"; //$NON-NLS-1$ private CreationFactory factory; private SnapToHelper helper; /** * Default constructor. Sets the default and disabled cursors. */ public CreationTool() { setDefaultCursor(SharedCursors.CURSOR_TREE_ADD); setDisabledCursor(Cursors.NO); } /** * Constructs a new CreationTool with the given factory. * * @param aFactory * the creation factory */ public CreationTool(CreationFactory aFactory) { this(); setFactory(aFactory); } /** * @see org.eclipse.gef.tools.AbstractTool#applyProperty(java.lang.Object, * java.lang.Object) */ @Override protected void applyProperty(Object key, Object value) { if (PROPERTY_CREATION_FACTORY.equals(key)) { if (value instanceof CreationFactory) setFactory((CreationFactory) value); return; } super.applyProperty(key, value); } /** * @see org.eclipse.gef.tools.AbstractTool#calculateCursor() */ @Override protected Cursor calculateCursor() { /* * Fix for Bug# 66010 The following two lines of code were added for the * case where a tool is activated via the keyboard (that code hasn't * been released yet). However, they were causing a problem as described * in 66010. Since the keyboard activation code is not being released * for 3.0, the following lines are being commented out. */ // if (isInState(STATE_INITIAL)) // return getDefaultCursor(); return super.calculateCursor(); } /** * Creates a {@link CreateRequest} and sets this tool's factory on the * request. * * @see org.eclipse.gef.tools.TargetingTool#createTargetRequest() */ @Override protected Request createTargetRequest() { CreateRequest request = new CreateRequest(); request.setFactory(getFactory()); return request; } /** * @see org.eclipse.gef.Tool#deactivate() */ @Override public void deactivate() { super.deactivate(); helper = null; } /** * @see org.eclipse.gef.tools.AbstractTool#getCommandName() */ @Override protected String getCommandName() { return REQ_CREATE; } /** * Cast the target request to a CreateRequest and returns it. * * @return the target request as a CreateRequest * @see TargetingTool#getTargetRequest() */ protected CreateRequest getCreateRequest() { return (CreateRequest) getTargetRequest(); } /** * @see org.eclipse.gef.tools.AbstractTool#getDebugName() */ @Override protected String getDebugName() { return "Creation Tool";//$NON-NLS-1$ } /** * Returns the creation factory used to create the new EditParts. * * @return the creation factory */ protected CreationFactory getFactory() { return factory; } /** * The creation tool only works by clicking mouse button 1 (the left mouse * button in a right-handed world). If any other button is pressed, the tool * goes into an invalid state. Otherwise, it goes into the drag state, * updates the request's location and calls * {@link TargetingTool#lockTargetEditPart(EditPart)} with the edit part * that was just clicked on. * * @see org.eclipse.gef.tools.AbstractTool#handleButtonDown(int) */ @Override protected boolean handleButtonDown(int button) { if (button != 1) { setState(STATE_INVALID); handleInvalidInput(); return true; } if (stateTransition(STATE_INITIAL, STATE_DRAG)) { getCreateRequest().setLocation(getLocation()); lockTargetEditPart(getTargetEditPart()); // Snap only when size on drop is employed if (getTargetEditPart() != null) helper = getTargetEditPart().getAdapter( SnapToHelper.class); } return true; } /** * If the tool is currently in a drag or drag-in-progress state, it goes * into the terminal state, performs some cleanup (erasing feedback, * unlocking target edit part), and then calls {@link #performCreation(int)} * . * * @see org.eclipse.gef.tools.AbstractTool#handleButtonUp(int) */ @Override protected boolean handleButtonUp(int button) { if (stateTransition(STATE_DRAG | STATE_DRAG_IN_PROGRESS, STATE_TERMINAL)) { eraseTargetFeedback(); unlockTargetEditPart(); performCreation(button); } setState(STATE_TERMINAL); handleFinished(); return true; } /** * Updates the request, sets the current command, and asks to show feedback. * * @see org.eclipse.gef.tools.AbstractTool#handleDragInProgress() */ @Override protected boolean handleDragInProgress() { if (isInState(STATE_DRAG_IN_PROGRESS)) { updateTargetRequest(); setCurrentCommand(getCommand()); showTargetFeedback(); } return true; } /** * @see org.eclipse.gef.tools.AbstractTool#handleDragStarted() */ @Override protected boolean handleDragStarted() { return stateTransition(STATE_DRAG, STATE_DRAG_IN_PROGRESS); } /** * If the user is in the middle of creating a new edit part, the tool erases * feedback and goes into the invalid state when focus is lost. * * @see org.eclipse.gef.tools.AbstractTool#handleFocusLost() */ @Override protected boolean handleFocusLost() { if (isInState(STATE_DRAG | STATE_DRAG_IN_PROGRESS)) { eraseTargetFeedback(); setState(STATE_INVALID); handleFinished(); return true; } return false; } /** * @see org.eclipse.gef.tools.TargetingTool#handleHover() */ @Override protected boolean handleHover() { if (isInState(STATE_INITIAL)) updateAutoexposeHelper(); return true; } /** * Updates the request and mouse target, gets the current command and asks * to show feedback. * * @see org.eclipse.gef.tools.AbstractTool#handleMove() */ @Override protected boolean handleMove() { updateTargetRequest(); updateTargetUnderMouse(); setCurrentCommand(getCommand()); showTargetFeedback(); return true; } /** * Executes the current command and selects the newly created object. The * button that was released to cause this creation is passed in, but since * {@link #handleButtonDown(int)} goes into the invalid state if the button * pressed is not button 1, this will always be button 1. * * @param button * the button that was pressed */ protected void performCreation(int button) { EditPartViewer viewer = getCurrentViewer(); executeCurrentCommand(); selectAddedObject(viewer); } /* * Add the newly created object to the viewer's selected objects. */ private void selectAddedObject(EditPartViewer viewer) { final Object model = getCreateRequest().getNewObject(); if (model == null || viewer == null) return; Object editpart = viewer.getEditPartRegistry().get(model); viewer.flush(); if (editpart != null && editpart instanceof EditPart && ((EditPart) editpart).isSelectable()) { // Force the new object to get positioned in the viewer. viewer.select((EditPart) editpart); } } /** * Sets the creation factory used to create the new edit parts. * * @param factory * the factory */ public void setFactory(CreationFactory factory) { this.factory = factory; } /** * Sets the location (and size if the user is performing size-on-drop) of * the request. * * @see org.eclipse.gef.tools.TargetingTool#updateTargetRequest() */ @Override protected void updateTargetRequest() { CreateRequest createRequest = getCreateRequest(); if (isInState(STATE_DRAG_IN_PROGRESS)) { Point loq = getStartLocation(); Rectangle bounds = new Rectangle(loq, loq); bounds.union(loq.getTranslated(getDragMoveDelta())); createRequest.setSize(bounds.getSize()); createRequest.setLocation(bounds.getLocation()); createRequest.getExtendedData().clear(); createRequest.setSnapToEnabled(!getCurrentInput().isModKeyDown( MODIFIER_NO_SNAPPING)); if (helper != null && createRequest.isSnapToEnabled()) { PrecisionRectangle baseRect = new PrecisionRectangle(bounds); PrecisionRectangle result = baseRect.getPreciseCopy(); helper.snapRectangle(createRequest, PositionConstants.NSEW, baseRect, result); createRequest.setLocation(result.getLocation()); createRequest.setSize(result.getSize()); } enforceConstraintsForSizeOnDropCreate(createRequest); } else { createRequest.setSize(null); createRequest.setLocation(getLocation()); createRequest.setSnapToEnabled(false); } } /** * Ensures size constraints (by default minimum and maximum) are respected * by the given request. May be overwritten by clients to enforce additional * constraints. * * @since 3.7 */ protected void enforceConstraintsForSizeOnDropCreate(CreateRequest request) { CreateRequest createRequest = (CreateRequest) getTargetRequest(); if (createRequest.getSize() != null) { // ensure create request respects minimum and maximum size // constraints PrecisionRectangle constraint = new PrecisionRectangle( createRequest.getLocation(), createRequest.getSize()); ((GraphicalEditPart) getTargetEditPart()).getContentPane() .translateToRelative(constraint); constraint.setSize(Dimension.max(constraint.getSize(), getMinimumSizeFor(createRequest))); constraint.setSize(Dimension.min(constraint.getSize(), getMaximumSizeFor(createRequest))); ((GraphicalEditPart) getTargetEditPart()).getContentPane() .translateToAbsolute(constraint); createRequest.setSize(constraint.getSize()); } } /** * Determines the <em>maximum</em> size for CreateRequest's size on drop. It * is called from * {@link #enforceConstraintsForSizeOnDropCreate(CreateRequest)} during * creation. By default, a large <code>Dimension</code> is returned. * * @param request * the request. * @return the minimum size * @since 3.7 */ protected Dimension getMaximumSizeFor(CreateRequest request) { return IFigure.MAX_DIMENSION; } /** * Determines the <em>minimum</em> size for CreateRequest's size on drop. It * is called from * {@link #enforceConstraintsForSizeOnDropCreate(CreateRequest)} during * creation. By default, a small <code>Dimension</code> is returned. * * @param request * the request. * @return the minimum size * @since 3.7 */ protected Dimension getMinimumSizeFor(CreateRequest request) { return IFigure.MIN_DIMENSION; } }
mit
Cuhey3/my-orchestrator
src/main/java/com/heroku/myapp/myorchestrator/consumers/snapshot/amiami/SnapshotAmiamiItemConsumer.java
2025
package com.heroku.myapp.myorchestrator.consumers.snapshot.amiami; import com.heroku.myapp.commons.consumers.SnapshotQueueConsumer; import com.heroku.myapp.commons.util.content.DocumentUtil; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.apache.camel.Exchange; import org.bson.Document; import org.jsoup.Jsoup; import org.springframework.stereotype.Component; @Component public class SnapshotAmiamiItemConsumer extends SnapshotQueueConsumer { @Override protected Optional<Document> doSnapshot(Exchange exchange) { try { String amiamiUrl = "http://www.amiami.jp/top/page/cal/goods.html"; org.jsoup.nodes.Document doc = Jsoup.connect(amiamiUrl) .maxBodySize(Integer.MAX_VALUE).timeout(Integer.MAX_VALUE) .get(); doc.select(".listitem:has(.originaltitle:matches(^$))").remove(); List<Map<String, Object>> collect = doc.select(".listitem") .stream().map((e) -> { Map<String, Object> map = new HashMap<>(); String title = e.select(".originaltitle").text(); map.put("img", e.select("img").attr("src") .replace("thumbnail", "main")); map.put("url", e.select(".name a").attr("href")); map.put("name", e.select("ul li").text()); map.put("release", e.select(".releasedatetext").text()); map.put("price", e.select(".price").text()); map.put("orig", title); return map; }).collect(Collectors.toList()); return new DocumentUtil(collect).createPrefix("img", "url") .nullable(); } catch (Exception ex) { util().sendError("doSnapshot", ex); return Optional.empty(); } } }
mit
matthewshim-ms/Recognizers-Text
Java/libraries/recognizers-text-number-with-unit/src/main/java/com/microsoft/recognizers/text/numberwithunit/chinese/extractors/CurrencyExtractorConfiguration.java
1308
package com.microsoft.recognizers.text.numberwithunit.chinese.extractors; import com.microsoft.recognizers.text.Culture; import com.microsoft.recognizers.text.CultureInfo; import com.microsoft.recognizers.text.numberwithunit.Constants; import com.microsoft.recognizers.text.numberwithunit.resources.ChineseNumericWithUnit; import java.util.List; import java.util.Map; public class CurrencyExtractorConfiguration extends ChineseNumberWithUnitExtractorConfiguration { public CurrencyExtractorConfiguration() { this(new CultureInfo(Culture.Chinese)); } public CurrencyExtractorConfiguration(CultureInfo ci) { super(ci); } @Override public String getExtractType() { return Constants.SYS_UNIT_CURRENCY; } @Override public List<String> getAmbiguousUnitList() { return ChineseNumericWithUnit.CurrencyAmbiguousValues; } @Override public Map<String, String> getSuffixList() { return CurrencySuffixList; } @Override public Map<String, String> getPrefixList() { return CurrencyPrefixList; } public static Map<String, String> CurrencySuffixList = ChineseNumericWithUnit.CurrencySuffixList; public static Map<String, String> CurrencyPrefixList = ChineseNumericWithUnit.CurrencyPrefixList; }
mit
koneksys/Git4RDF
RDFVersionControl/src/main/java/mainPackage/CommandLineHandler.java
18752
package mainPackage; import visualization.*; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import com.google.common.base.Objects; public class CommandLineHandler { public static void executeCommand(String commandStr){ String[] command = {null, null, null, null, null}; //Make sure that command array has at least length 5 String[] commandInput = parseCommand(commandStr); int number = commandInput.length; if(number<5){ for(int i=0;i<number;i++){ command[i]=commandInput[i]; } }else{ command = commandInput; } if(Objects.equal(command[0],null)){ System.out.println("This is not a valid command. Please insert a different one."); }else{ switch(command[0]){ case "help": System.out.print(Scripts.help); break; case "config": if((number<2)||(Objects.equal(command[1], null))){ System.out.println("The command elements are not sufficient for a config operation"); }else{ String inputString = new String(); switch(command[1]){ case "user.name": try { inputString = command[2].substring(command[2].indexOf("\"")+1, command[2].lastIndexOf("\"")); Settings.authorID = inputString; System.out.println("Author ID: " + Settings.authorID); } catch (Exception e) { System.out.println("Please insert the argument within \"quotation marks\"."); } break; case "rdfFormat": //TODO robust error try { inputString = command[2].substring(command[2].indexOf("\"")+1, command[2].lastIndexOf("\"")); if(Settings.formats.contains(inputString)){ Settings.FILEFORMAT = inputString; System.out.println("File format: " + Settings.FILEFORMAT); }else{ System.out.println("This format is not supported."); } } catch (Exception e) { System.out.println("Please insert the argument within \"quotation marks\"."); } break; case "QVF": try { inputString = command[2].substring(command[2].indexOf("\"")+1, command[2].lastIndexOf("\"")); if((Objects.equal(inputString, "true"))||(Objects.equal(inputString, "false"))){ Settings.QVF = Boolean.parseBoolean(inputString); System.out.println("QVF: " + Settings.QVF); }else{ System.out.println("This is not a valid assignment for the configuration of quarter visualization"); } } catch (Exception e) { System.out.println("Please insert the argument within \"quotation marks\"."); } break; default: System.out.println("The config operation could not be executed, please insert different arguments"); break; } } break; case "C": String temp = new String(); if(Objects.equal(command[1], null)){ temp = new File("").getAbsolutePath() + File.separator + "Workspace"; }else{ try { temp = command[1].substring(command[1].indexOf("<")+1, command[1].lastIndexOf(">")); } catch (Exception e) { System.out.println("Please enter file name in <angle brackets>"); return; } } File file = new File(temp + File.separator + "versionModel"); if(file.exists()){ try { Model tempModel = ModelFactory.createDefaultModel().read(file.getAbsolutePath(),Settings.FILEFORMAT); KVC.dirWorkspace = temp; if(Objects.equal(KVC.workspaceModel, null)){ KVC.workspaceModel = new VersionModel(KVC.dirWorkspace); } KVC.workspaceModel.getVersionModel().removeAll(); KVC.workspaceModel.getVersionModel().add(tempModel.listStatements()); System.out.println("Workspace adopted: " + KVC.dirWorkspace); KVC.initWorkspace = true; } catch (Exception e) { System.out.println("Can not read file"); } }else{ if(temp.endsWith(File.separator)){ temp = temp + "Workspace"; }else{ temp = temp + File.separator + "Workspace"; } KVC.initializeWorkspace(temp); } if(!(KVC.dirLocalRep.endsWith(File.separator))){ KVC.dirLocalRep = KVC.dirLocalRep + File.separator; } if(!(KVC.dirWorkspace.endsWith(File.separator))){ KVC.dirWorkspace = KVC.dirWorkspace + File.separator; } break; case "init": temp = new String(); if(Objects.equal(command[1], null)){ temp = new File("").getAbsolutePath() + File.separator + "Workspace"; }else{ try { temp = command[1].substring(command[1].indexOf("<")+1, command[1].lastIndexOf(">")); } catch (Exception e) { System.out.println("Please enter file name in <angle brackets>."); return; } } if(new File(temp).isDirectory()){ if(temp.endsWith(File.separator)){ temp = temp + "LocalRepository"; }else{ temp = temp + File.separator + "LocalRepository"; } file = new File(temp); if(file.exists()){ System.out.println("A Local Repository folder already exists in this directory."); System.out.println("Do you want to overwrite the folder?\n(y)\n(n)"); String decider = KVC.scanner.nextLine(); if(Objects.equal(decider, "y")){ try { FileUtils.deleteDirectory(file); file = new File(temp); KVC.initializeLocalRepository(temp); } catch (IOException e) { e.printStackTrace(); } }else{ System.out.println("Init command could not be executed."); } }else{ KVC.initializeLocalRepository(temp); } }else{ System.out.println("The directory path does not exist."); } if(!(KVC.dirLocalRep.endsWith(File.separator))){ KVC.dirLocalRep = KVC.dirLocalRep + File.separator; } if(!(KVC.dirWorkspace.endsWith(File.separator))){ KVC.dirWorkspace = KVC.dirWorkspace + File.separator; } break; case "load": if(!KVC.initWorkspace){ System.out.println("Workspace is not set up properly"); }else{ if(Objects.equal(command[1], null)){ System.out.println("This is not a valid command. Please insert a different one."); }else if(Objects.equal(command[1], "local")){ TransferFunctions.loadLocalRepoData(); }else{ String inputString = new String(); try { if(Objects.equal(command[1], "example")){ inputString = System.getProperty("user.dir") + File.separator + "src" + File.separator + "additional" + File.separator + "RDFdocuments" + File.separator + "ExampleDataset.txt"; }else{ inputString = command[1].substring(command[1].indexOf("<")+1, command[1].lastIndexOf(">")); } file = new File(inputString); if(file.exists()){ boolean success = false; Model addedModel = ModelFactory.createDefaultModel(); if(file.getAbsolutePath().endsWith(".txt")){ try { addedModel.read(file.getAbsolutePath(),Settings.FILEFORMAT); success = true; } catch (Exception e) { System.out.println("Could not import file content into RDF dataset."); } }else if(file.getAbsolutePath().endsWith(".rdf")){ try { addedModel.read(file.getAbsolutePath()); success = true; } catch (Exception e) { System.out.println("Could not import file content into RDF dataset."); } } if(success){ Model currentApplicationModel = KVC.workspaceModel.getApplicationModel(KVC.workspaceModel.getCurrentCommit()); currentApplicationModel.add(addedModel.listStatements()); SparqlUtils.model2File(currentApplicationModel, KVC.dirWorkspace + KVC.workspaceModel.checkModelAttachment(KVC.workspaceModel.getCurrentCommit())); SparqlUtils.parseModel(currentApplicationModel); System.out.println("Model loaded into workspace:"); Visualizer.printModel(currentApplicationModel); } }else{ System.out.println("This file does not exist."); } } catch (Exception e) { System.out.println("Please enter file name in <angle brackets>"); } } } break; case "clone": System.out.println("Not implemented yet."); // TransferFunctions.cloneDirectories(KVC.dirLocalRep, KVC.dirWorkspace); break; case "dir": if(Objects.equal(command[1], null)){ System.out.println("This is not a valid command. Please insert a different one."); }else{ try { String inputString = command[1].substring(command[1].indexOf("<")+1, command[1].lastIndexOf(">")); file = new File(inputString + File.separator + "versionModel"); if(file.exists()){ if(Objects.equal(KVC.localRepModel, null)){ KVC.localRepModel = new VersionModel(inputString); } if(KVC.localRepModel.loadModel(file)){ String repoDir = KVC.localRepModel.getFilename(); if(repoDir.endsWith(File.separator)){ KVC.dirLocalRep = repoDir.substring(0,repoDir.lastIndexOf(File.separator)); KVC.dirLocalRep = repoDir.substring(0,repoDir.lastIndexOf(File.separator)); }else{ KVC.dirLocalRep = repoDir.substring(0,repoDir.lastIndexOf(File.separator)); } KVC.initLocalRepo = true; System.out.println("Changed repository directory: " + KVC.dirLocalRep); } }else{ System.out.println("The inserted file name does not point to a KLD repository"); } } catch (Exception e) { System.out.println("Please enter file name in <angle brackets>"); } } if(!(KVC.dirLocalRep.endsWith(File.separator))){ KVC.dirLocalRep = KVC.dirLocalRep + File.separator; } if(!(KVC.dirWorkspace.endsWith(File.separator))){ KVC.dirWorkspace = KVC.dirWorkspace + File.separator; } break; case "pwd": String currentDirectory = new File("").getAbsolutePath(); System.out.println(currentDirectory); break; case "gui": if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ System.out.println("Working environment is not set up properly"); }else{ if(number<2){ if(Settings.QVF){ Visualizer.visualizationTool(KVC.workspaceModel, KVC.workspaceModel.getCurrentCommit(),KVC.localRepModel, KVC.localRepModel.getCurrentCommit()); }else{ System.out.println("Please select, if you want to see the \"workspace\" or the \"localrepo\"."); } }else if(number<3){ if(Objects.equal(command[1], null)){ System.out.println("Please select, if you want to see the \"workspace\" or the \"localrepo\"."); }else{ if(Objects.equal(command[1], "workspace")){ Settings.QVF = false; Visualizer.visualizationTool(KVC.workspaceModel, KVC.workspaceModel.getCurrentCommit()); }else if(Objects.equal(command[1], "localrepo")){ Settings.QVF = false; Visualizer.visualizationTool(KVC.localRepModel, KVC.localRepModel.getCurrentCommit()); }else{ System.out.println("Please select, if you want to see the \"workspace\" or the \"localrepo\"."); } } }else{ System.out.println("Incorrect command!"); } } break; case "index": Visualizer.displayIndexScript(); break; case "add": if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ System.out.println("The local repository has not been initialized yet."); }else{ if((number<2)||(Objects.equal(command[1], null))){ System.out.println("This is not a valid command. Please insert a different one."); }else if(Objects.equal(command[1],"a")){ File file1 = new File(KVC.dirLocalRep + KVC.localRepModel.checkModelAttachment(KVC.localRepModel.getCurrentCommit())); //specified version of the dataset in the workspace File file2 = new File(KVC.dirWorkspace + KVC.workspaceModel.checkModelAttachment(KVC.workspaceModel.getCurrentCommit())); if(file1.exists() && file2.exists()){ KVC.indexScript = SparqlUtils.diff(file1, file2); } }else{ try { int tripleNumber = Integer.parseInt(command[1]); TransferFunctions.addData(tripleNumber); } catch (NumberFormatException e) { System.out.println("This is not a valid command. Please insert a different one."); } } } break; case "rm": if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ System.out.println("The local repository has not been initialized yet."); }else{ if((KVC.indexScript.getDeleteTriples().size()+KVC.indexScript.getInsertTriples().size())<0){ System.out.println("Index is empty"); }else{ if((number<2)||(Objects.equal(command[1], null))){ System.out.println("This is not a valid command. Please insert a different one."); }else if(Objects.equal(command[1],"a")){ KVC.indexScript = new SparqlScript(); System.out.println("Index repository is emptied."); }else{ try { int tripleNumber = Integer.parseInt(command[1]); TransferFunctions.removeData(tripleNumber); } catch (NumberFormatException e) { System.out.println("This is not a valid command. Please insert a different one."); } } } } break; case "reset": System.out.println("Not implemented yet."); break; case "tag": if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ System.out.println("The dataset has not been initialized yet."); }else{ KVC.tagCommit(KVC.localRepModel); } break; case "branch": if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ System.out.println("The dataset has not been initialized yet."); }else{ Visualizer.listBranches(); } break; case "merge": if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ System.out.println("The dataset has not been initialized yet."); }else if((number<2)||(Objects.equal(command[1], null))){ KVC.mergeModels(KVC.localRepModel); }else{ String mergeCommit = command[1].substring(command[1].indexOf("[")+1,command[1].lastIndexOf("]")); if(KVC.localRepModel.getCommitNumbers().contains(mergeCommit)){ KVC.mergeModels(KVC.localRepModel,KVC.localRepModel.getCurrentCommit(),mergeCommit); }else{ System.out.println("Commit is not included in repository model"); } } break; case "push": System.out.println("Not implemented yet."); // if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ // System.out.println("The dataset has not been initialized yet."); // }else{ // TransferFunctions.pushData(); // } break; case "pull": System.out.println("Not implemented yet."); // if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ // System.out.println("The dataset has not been initialized yet."); // }else{ // TransferFunctions.pullData(); // } break; case "commit": if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ System.out.println("Working environment is not set up properly."); }else{ if((number<2)||(Objects.equal(command[1], null))){ TransferFunctions.commitData(); }else if(Objects.equal(command[1],"a")){ TransferFunctions.commitAllData(); }else{ System.out.println("This is not a valid command. Please insert a different one."); } } break; case "checkout": if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ System.out.println("Working environment is not set up properly."); }else{ if((number<2)||(Objects.equal(command[1], null))){ System.out.println("Not implemented yet."); }else if(Objects.equal(command[1], "b")){ KVC.createBranch(KVC.localRepModel); }else if((command[1].contains("["))&&(command[1].contains("]"))){ String commitNumber = command[1].substring(command[1].indexOf("[")+1,command[1].lastIndexOf("]")); if(KVC.localRepModel.getCommitNumbers().contains(commitNumber)){ if(Objects.equal(commitNumber,KVC.localRepModel.getLatestCommit(commitNumber))){ KVC.localRepModel.setCurrentCommit(commitNumber); }else{ System.out.println("This commit does not conform to the end of a branch"); System.out.println("Show all branch ends with: \"branch\""); } }else{ System.out.println("This commit number is not included in the model"); } }else{ System.out.println("Please enter branch end commit in [square brackets]"); } } break; case "fetch": System.out.println("Not implemented yet."); // if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ // System.out.println("The dataset has not been initialized yet."); // }else{ // TransferFunctions.fetchData(); // } break; case "change": if((number<2)||(Objects.equal(command[1], null))){ System.out.println(Scripts.change); }else{ if(!KVC.initWorkspace){ System.out.println("The workspace has not been set up properly."); }else{ KVC.updateAction(command[1]); } } break; case "show": if((number<2)||(Objects.equal(command[1], null))){ System.out.println(Scripts.show); }else{ if(!KVC.initWorkspace){ System.out.println("The workspace has not been set up properly."); }else{ KVC.overlookProject(command[1]); } } break; case "log": Settings.printSettings(); System.out.println("Workspace directory:\t\t" + KVC.dirWorkspace); System.out.println("Local repository directory:\t" + KVC.dirLocalRep); System.out.println("Workspace initialized:\t\t" + KVC.initWorkspace); if(KVC.initWorkspace){ System.out.println("Current branch workspace:\t" + KVC.workspaceModel.getLatestCommit(KVC.workspaceModel.getCurrentCommit())); } System.out.println("Local repository directory:\t" + KVC.initLocalRepo); if(KVC.initLocalRepo){ System.out.println("Current branch local repo:\t" + KVC.localRepModel.getLatestCommit(KVC.localRepModel.getCurrentCommit())); } break; case "status": if((!KVC.initWorkspace)||(!KVC.initLocalRepo)){ System.out.println("The dataset has not been initialized yet."); }else{ TransferFunctions.statusOutput(); } break; case "exit": KVC.exitFunction(); break; default: System.out.println("This is not a valid command. Please insert a different one."); break; } } } private static String[] parseCommand(String command){ String[] elements = command.split(" |-"); String[] elements2 = new String[elements.length]; int j=0; for(int i=0;i<elements.length;i++){ if(!(Objects.equal(elements[i], ""))){ elements2[j]=elements[i]; j++; } } return elements2; } }
mit
hockeyhurd/ExtraTools-
com/hockeyhurd/worldgen/OreFermiteWorldgen.java
947
package com.hockeyhurd.worldgen; import net.minecraft.block.Block; public class OreFermiteWorldgen extends AbstractWorldGen { /** * Init chance of spawn. NOTE: set int to -1 if not spawning in said dimension, likewise the said block can be set to null. * @param blockSpawn = Block to spawn. * @param blockSpawnNether = block to spawn in nether. * @param chanceofSpawn = Chance of spawning rate. * @param chanceOfSpawn_nether = Chance of spawning rate. * @param minVeinSize = min. size of given vein. * @param maxVeinSize = max. size of given vein. * @param minY = min. y-level. * @param maxY = max. y-level. */ public OreFermiteWorldgen(Block blockSpawn, Block blockSpawnNether, int chanceofSpawn, int chanceOfSpawn_nether, int minVeinSize, int maxVeinSize, int minY, int maxY) { super(blockSpawn, blockSpawnNether, chanceofSpawn, chanceOfSpawn_nether, minVeinSize, maxVeinSize, minY, maxY); } }
mit
elect86/oglDevTutorials
oglDevTutorials/src/ogldevtutorials/tut04_shaders/Tutorial04.java
5347
/* * 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 ogldevtutorials.tut04_shaders; import com.jogamp.newt.Display; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; import com.jogamp.newt.opengl.GLWindow; import static com.jogamp.opengl.GL.GL_ARRAY_BUFFER; import static com.jogamp.opengl.GL.GL_FLOAT; import static com.jogamp.opengl.GL.GL_STATIC_DRAW; import static com.jogamp.opengl.GL.GL_TRIANGLES; import static com.jogamp.opengl.GL.GL_VERSION; import static com.jogamp.opengl.GL2ES2.GL_FRAGMENT_SHADER; import static com.jogamp.opengl.GL2ES2.GL_VERTEX_SHADER; import static com.jogamp.opengl.GL2ES3.GL_COLOR; import com.jogamp.opengl.GL3; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.GLCapabilities; import com.jogamp.opengl.GLContext; import com.jogamp.opengl.GLEventListener; import com.jogamp.opengl.GLProfile; import com.jogamp.opengl.util.Animator; import com.jogamp.opengl.util.GLBuffers; import com.jogamp.opengl.util.glsl.ShaderCode; import com.jogamp.opengl.util.glsl.ShaderProgram; import glm.vec._3.Vec3; import glutil.BufferUtils; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import ogldevtutorials.framework.Semantic; /** * * @author elect */ public class Tutorial04 implements GLEventListener { public static GLWindow glWindow; public static Animator animator; private final String SHADERS_ROOT = "src/ogldevtutorials/tut04_shaders/shaders"; private final String SHADERS_NAME = "shader"; public static void main(String[] args) { Display display = NewtFactory.createDisplay(null); Screen screen = NewtFactory.createScreen(display, 0); GLProfile glProfile = GLProfile.get(GLProfile.GL3); GLCapabilities glCapabilities = new GLCapabilities(glProfile); glWindow = GLWindow.create(screen, glCapabilities); glWindow.setSize(1044, 768); glWindow.setPosition(100, 50); glWindow.setUndecorated(false); glWindow.setAlwaysOnTop(false); glWindow.setFullscreen(false); glWindow.setPointerVisible(true); glWindow.confinePointer(false); glWindow.setTitle("Tutorial 04 - Shaders"); glWindow.setContextCreationFlags(GLContext.CTX_OPTION_DEBUG); glWindow.setVisible(true); Tutorial04 tutorial04 = new Tutorial04(); glWindow.addGLEventListener(tutorial04); animator = new Animator(glWindow); animator.start(); } private FloatBuffer clearColor = GLBuffers.newDirectFloatBuffer(4); private IntBuffer vbo = GLBuffers.newDirectIntBuffer(1); private int programName; @Override public void init(GLAutoDrawable drawable) { GL3 gl3 = drawable.getGL().getGL3(); System.out.println("GL version: " + gl3.glGetString(GL_VERSION)); clearColor.put(0, 0.0f).put(1, 0.0f).put(2, 0.0f).put(3, 0.0f); createVertexBuffer(gl3); compileShaders(gl3); } private void createVertexBuffer(GL3 gl3) { Vec3 vertices[] = { new Vec3(-1.0f, -1.0f, 0.0f), new Vec3(+1.0f, -1.0f, 0.0f), new Vec3(+0.0f, +1.0f, 0.0f)}; ByteBuffer verticesBuffer = GLBuffers.newDirectByteBuffer(Vec3.SIZE * vertices.length); for (int i = 0; i < vertices.length; i++) { vertices[i].toDbb(verticesBuffer, i * Vec3.SIZE); } gl3.glGenBuffers(1, vbo); gl3.glBindBuffer(GL_ARRAY_BUFFER, vbo.get(0)); gl3.glBufferData(GL_ARRAY_BUFFER, verticesBuffer.capacity(), verticesBuffer, GL_STATIC_DRAW); BufferUtils.destroyDirectBuffer(verticesBuffer); } private void compileShaders(GL3 gl3) { ShaderCode vertShader = ShaderCode.create(gl3, GL_VERTEX_SHADER, this.getClass(), SHADERS_ROOT, null, SHADERS_NAME, "vert", null, true); ShaderCode fragShader = ShaderCode.create(gl3, GL_FRAGMENT_SHADER, this.getClass(), SHADERS_ROOT, null, SHADERS_NAME, "frag", null, true); ShaderProgram program = new ShaderProgram(); program.add(vertShader); program.add(fragShader); program.link(gl3, System.out); programName = program.program(); gl3.glUseProgram(programName); } @Override public void display(GLAutoDrawable drawable) { GL3 gl3 = drawable.getGL().getGL3(); gl3.glClearBufferfv(GL_COLOR, 0, clearColor); gl3.glEnableVertexAttribArray(Semantic.Attr.POSITION); gl3.glBindBuffer(GL_ARRAY_BUFFER, vbo.get(0)); gl3.glVertexAttribPointer(Semantic.Attr.POSITION, 3, GL_FLOAT, false, Vec3.SIZE, 0); gl3.glDrawArrays(GL_TRIANGLES, 0, 3); gl3.glDisableVertexAttribArray(Semantic.Attr.POSITION); } @Override public void reshape(GLAutoDrawable drawable, int i, int i1, int i2, int i3) { } @Override public void dispose(GLAutoDrawable drawable) { GL3 gl3 = drawable.getGL().getGL3(); gl3.glDeleteBuffers(1, vbo); gl3.glDeleteProgram(programName); BufferUtils.destroyDirectBuffer(clearColor); BufferUtils.destroyDirectBuffer(vbo); System.exit(0); } }
mit
Markonis/JCrypt
test/encryption/algorithm/BlockEncryptorTest.java
1284
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package encryption.algorithm; import encryption.Configuration; import encryption.algorithm.blockEncryptor.BlockEncryptor; import org.junit.Assert; import org.junit.Test; /** * * @author marko */ public class BlockEncryptorTest { public BlockEncryptorTest() { } @Test public void testImplodeExplodeLong() { System.out.println("implode/explode"); Configuration config = new Configuration(); config.set("blockLength", "8"); BlockEncryptor instance = new BlockEncryptor(config); int[] bytes = new int[4]; int imploded, imploded2; int[] exploded; for(int i = 0; i < 1024; i++){ // Setup random bytes to implode for(int j = 0; j < bytes.length; j++) bytes[0] = (int) Math.floor(Math.random() * 256); imploded = instance.implodeInt(bytes); exploded = instance.explodeInt(imploded, 4); Assert.assertArrayEquals(bytes, exploded); imploded2 = instance.implodeInt(exploded); Assert.assertEquals(imploded, imploded2); } } }
mit
ArturWisniewski/ToDoApp-Spring
src/main/java/aw2079/todoapp/Configuration/HibernateConfig.java
3299
/* * MIT License */ package aw2079.todoapp.Configuration; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.hibernate.cfg.AvailableSettings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.jdbc.datasource. DriverManagerDataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * * @author Artur Wiśniewski */ @Configuration @EnableTransactionManagement @PropertySource({"classpath:persistance.properties"}) public class HibernateConfig { @Autowired private Environment env; @Bean("dataSource") public DataSource getDataSource() { // BasicDataSource dataSource = new BasicDataSource(); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getRequiredProperty("datasource.driverClassName")); dataSource.setUrl(env.getRequiredProperty("datasource.url")); dataSource.setUsername(env.getRequiredProperty("datasource.user")); dataSource.setPassword(env.getRequiredProperty("datasource.password")); return dataSource; } Properties getHibernateProperties() { return new Properties() { { setProperty(AvailableSettings.DIALECT, env.getRequiredProperty("hibernate.dialect")); setProperty(AvailableSettings.SHOW_SQL, env.getRequiredProperty("hibernate.show_sql")); setProperty(AvailableSettings.HBM2DDL_AUTO, env.getRequiredProperty("hibernate.hbm2ddl.auto")); setProperty(AvailableSettings.STATEMENT_BATCH_SIZE, env.getRequiredProperty("hibernate.batch.size")); setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, env.getRequiredProperty("hibernate.current.session.context.class")); } }; } @Bean("sessionFactory") public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(getDataSource()); sessionFactory.setPackagesToScan(new String[]{"aw2079.todoapp.Model.Entities"}); sessionFactory.setHibernateProperties(getHibernateProperties()); return sessionFactory; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) { System.out.println(sessionFactory); HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(sessionFactory); return txManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } }
mit
Pankiev/MMORPG_Prototype
Server/core/src/pl/mmorpg/prototype/server/packetshandling/characteractions/ItemRemovedFromQuickAccessBarPacketHandler.java
1177
package pl.mmorpg.prototype.server.packetshandling.characteractions; import com.esotericsoftware.kryonet.Connection; import pl.mmorpg.prototype.clientservercommon.packets.playeractions.ItemRemovedFromQuickAccessBarPacket; import pl.mmorpg.prototype.server.objects.PlayerCharacter; import pl.mmorpg.prototype.server.packetshandling.GameDataRetriever; import pl.mmorpg.prototype.server.packetshandling.PacketHandlerBase; import pl.mmorpg.prototype.server.states.PlayState; public class ItemRemovedFromQuickAccessBarPacketHandler extends PacketHandlerBase<ItemRemovedFromQuickAccessBarPacket> { private GameDataRetriever gameData; private PlayState playState; public ItemRemovedFromQuickAccessBarPacketHandler(PlayState playState, GameDataRetriever gameData) { this.playState = playState; this.gameData = gameData; } @Override public void handle(Connection connection, ItemRemovedFromQuickAccessBarPacket packet) { int characterId = gameData.getCharacterIdByConnectionId(connection.getID()); PlayerCharacter character = (PlayerCharacter)playState.getObject(characterId); character.removeConfigElementFromItemQuickAccessBar(packet.getCellPosition()); } }
mit
guixiaoyuan/workspace
ShanbayTest/app/src/main/java/gxy/shanbaytest/View/SquareRelativeLayout.java
1535
package gxy.shanbaytest.View; import android.content.Context; import android.util.AttributeSet; import android.widget.RelativeLayout; /** * Created by Administrator on 2015/8/25. * 长宽相等的正方形RelativeLayout */ public class SquareRelativeLayout extends RelativeLayout { public SquareRelativeLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public SquareRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); } public SquareRelativeLayout(Context context) { super(context); } @SuppressWarnings("unused") @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // For simple implementation, or internal size is always 0. // We depend on the container to specify the layout size of // our view. We can't really know what it is since we will be // adding and removing different arbitrary views and do not // want the layout to change as this happens. setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); // Children are just made to fill our space. int childWidthSize = getMeasuredWidth(); int childHeightSize = getMeasuredHeight(); //高度和宽度一样 heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
mit
CyclopsMC/IntegratedDynamics
src/main/java/org/cyclops/integrateddynamics/tileentity/TileProxyConfig.java
742
package org.cyclops.integrateddynamics.tileentity; import com.google.common.collect.Sets; import net.minecraft.tileentity.TileEntityType; import org.cyclops.cyclopscore.config.extendedconfig.TileEntityConfig; import org.cyclops.integrateddynamics.IntegratedDynamics; import org.cyclops.integrateddynamics.RegistryEntries; /** * Config for the {@link TileProxy}. * @author rubensworks * */ public class TileProxyConfig extends TileEntityConfig<TileProxy> { public TileProxyConfig() { super( IntegratedDynamics._instance, "proxy", (eConfig) -> new TileEntityType<>(TileProxy::new, Sets.newHashSet(RegistryEntries.BLOCK_PROXY), null) ); } }
mit
Alex-Diez/Java-TDD-Katas
old-katas/string-calculator-kata/string-calculator-kata-day-7/src/test/java/kata/java/StringCalcTest.java
1210
package kata.java; import org.junit.Test; import org.junit.internal.Classes; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class StringCalcTest { @Test public void calculateOneDigitNumber() throws Exception { assertThat(Calculator.calculate("2"), is(2.0)); } @Test public void calculateManyDigitNumber() throws Exception { assertThat(Calculator.calculate("2453"), is(2453.0)); } @Test public void calculateAddition() throws Exception { assertThat(Calculator.calculate("324+64"), is(388.0)); } @Test public void calculateSubtraction() throws Exception { assertThat(Calculator.calculate("345-23"), is(345 - 23.0)); } @Test public void calculateMultiplication() throws Exception { assertThat(Calculator.calculate("34*23"), is(34.0 * 23)); } @Test public void calculateDivision() throws Exception { assertThat(Calculator.calculate("245/5"), is(245 / 5.0)); } @Test public void calculateManyOperations() throws Exception { assertThat(Calculator.calculate("354+54/4-13+2*4-23"), is(354+54/4.0-13+2*4.0-23)); } }
mit
swayzetrain/InvServices
inventory-common/src/main/java/com/swayzetrain/inventory/common/repository/InstanceRepository.java
425
package com.swayzetrain.inventory.common.repository; import java.util.ArrayList; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.swayzetrain.inventory.common.model.Instance; public interface InstanceRepository extends JpaRepository<Instance,Long> { Instance findByInstanceid(Integer instanceid); List<Instance> findByInstanceidIn(ArrayList<Integer> instanceidList); }
mit
nyrkovalex/deploy.me
src/main/java/com/github/nyrkovalex/deploy/me/descriptor/Script.java
2148
/* * The MIT License * * Copyright 2015 Alexander Nyrkov. * * 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.github.nyrkovalex.deploy.me.descriptor; import com.google.common.collect.ImmutableSet; import java.util.Objects; import java.util.Set; public class Script { private final String source; private final Set<String> targets; public Script(String source, Iterable<String> targets) { this.source = source; this.targets = ImmutableSet.copyOf(targets); } public String source() { return source; } public Set<String> targets() { return targets; } @Override public int hashCode() { return Objects.hash(this.source(), this.targets()); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Script other = (Script) obj; return Objects.equals(this.source(), other.source()) && Objects.equals(this.targets(), other.targets()); } }
mit
yuelu/algorithms
src/test/java/org/luyue/examples/datastructure/ArrayStackTest.java
1200
package org.luyue.examples.datastructure; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.EmptyStackException; import java.util.List; import org.junit.Test; public class ArrayStackTest { /** * <pre> * input: 5 4 3 2 - - 1 - - - * output: 2 3 1 4 5 */ @Test public void test() { ArrayStack<Integer> stack = new ArrayStack<>(); assertThat(stack.isEmpty(), is(true)); List<Integer> actual = new ArrayList<>(); stack.push(5); stack.push(4); stack.push(3); stack.push(2); assertThat(stack.isEmpty(), is(false)); actual.add(stack.pop()); actual.add(stack.pop()); stack.push(1); actual.add(stack.pop()); actual.add(stack.pop()); actual.add(stack.pop()); assertThat(stack.isEmpty(), is(true)); assertThat(actual.toString(), is("[2, 3, 1, 4, 5]")); try { actual.add(stack.pop()); fail("Should throw stack empty exception"); } catch (EmptyStackException e) { } } }
mit
allotory/glaucis
LeetCode/P70_ClimbingStairs.java
1199
/* 70. Climbing Stairs Easy You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step Constraints: 1 <= n <= 45 */ class Solution { // Time Limit Exceeded: 45 /*public int climbStairs(int n) { if (n == 1) { return 1; } if (n == 2) { return 2; } return climbStairs(n - 1) + climbStairs(n - 2); }*/ public int climbStairs(int n) { int[] dp = new int[n + 1]; if (n == 1) { return 1; } if (n == 2) { return 2; } dp[0] = 0; dp[1] = 1; dp[2] = 2; for (int i = 3; i < n + 1; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[n]; } }
mit
tgame14/Modjam4
src/main/scala/com/tgame/modjam4/api/SpellRegistry.java
1625
package com.tgame.modjam4.api; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.tgame.modjam4.spells.ISpell; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.LoaderState; /** * @since 15/05/14 * @author tgame14 */ public class SpellRegistry { public static SpellRegistry INSTANCE = new SpellRegistry(); private SpellRegistry() {} protected ImmutableList<String> spellList; protected ImmutableBiMap<String, ISpell> spellMap; private ImmutableList.Builder<String> listBuilder = new ImmutableList.Builder<String>(); private ImmutableBiMap.Builder<String, ISpell> mapBuilder = new ImmutableBiMap.Builder<String, ISpell>(); public void addSpell(ISpell spell, String key) { if (Loader.instance().hasReachedState(LoaderState.POSTINITIALIZATION)) { throw new UnsupportedOperationException("Must register spells before postinit!"); } listBuilder.add(key); mapBuilder.put(key, spell); } public void onPost() { this.spellList = listBuilder.build(); this.spellMap = mapBuilder.build(); listBuilder = null; mapBuilder = null; } public ISpell getSpell(String key) { return spellMap.get(key); } public String getFirst() { return spellList.get(0); } public String getNext(String key) { if (spellList.contains(key)) { return spellList.get(spellList.indexOf(key)); } return null; } }
mit
teiler/api.teiler.io
src/main/java/io/teiler/server/util/exceptions/PayerInactiveException.java
366
package io.teiler.server.util.exceptions; /** * Exception denoting that a person has not been found (and presumably doesn't exist). * * @author lroellin */ public class PayerInactiveException extends PersonInactiveException { private static final long serialVersionUID = 1L; public PayerInactiveException() { super("PAYER_INACTIVE"); } }
mit
berry-cs/big-data-cse
big-data-java/src/easy/data/DataSourceIterator.java
621
package easy.data; /** * Interface for iterators over data sources * * @author Nadeem Abdul Hamid * */ public interface DataSourceIterator { public boolean hasData(); public DataSourceIterator loadNext(); public <T> T fetch(String clsName, String... keys); public <T> T fetch(Class<T> cls, String... keys); public boolean fetchBoolean(String key); public byte fetchByte(String key); public char fetchChar(String key); public double fetchDouble(String key); public float fetchFloat(String key); public int fetchInt(String key); public String fetchString(String key); public String usageString(); }
mit
martindilling/idea-php-laravel-plugin
src/de/espend/idea/laravel/stub/processor/ArrayKeyVisitor.java
262
package de.espend.idea.laravel.stub.processor; import com.intellij.psi.PsiElement; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public interface ArrayKeyVisitor { public void visit(String key, PsiElement psiKey, boolean isRootElement); }
mit
servicosgovbr/editor-de-servicos
src/main/java/br/gov/servicos/editor/security/GerenciadorPermissoes.java
1739
package br.gov.servicos.editor.security; import br.gov.servicos.editor.usuarios.Usuario; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import lombok.AccessLevel; import lombok.experimental.FieldDefaults; import lombok.experimental.NonFinal; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.stereotype.Component; import java.util.Collection; @Component @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) public class GerenciadorPermissoes implements InitializingBean { @NonFinal Multimap<String, Permissao> map; YamlPropertiesFactoryBean properties; @Autowired public GerenciadorPermissoes(YamlPropertiesFactoryBean properties) { this.properties = properties; } @Override public void afterPropertiesSet() { map = HashMultimap.create(); properties.getObject().forEach((papel, permissao) -> map.put(parsePapel(papel), new Permissao(permissao.toString().toUpperCase()))); Usuario.setGerenciadorPermissoes(this); // necessário porque Usuario não é uma classe Spring } private String parsePapel(Object papelObj) { String papel = (String) papelObj; if (!papel.matches("[\\w\\s]+\\[\\d+\\]")) { throw new RuntimeException("Formato incorreto do arquivo de permissões. Problema com o papel: " + papel); } return papel.split("\\[")[0].toUpperCase(); } public Collection<Permissao> getPermissoes(String editor) { return map.get(editor.toUpperCase()); } }
mit
friendlyted/mvnsh
mvnsh-core/src/main/java/pro/friendlyted/mvnsh/core/processor/MavenMsDownload.java
1287
package pro.friendlyted.mvnsh.core.processor; import java.util.Collections; import java.util.List; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; import pro.friendlyted.mvnsh.core.api.MsDownload; import pro.friendlyted.mvnsh.core.tools.ArtifactTools; import pro.friendlyted.mvnsh.core.tools.DownloadTools; /** * * @author frekade */ public class MavenMsDownload implements MsDownload { private List<RemoteRepository> remoteRepos; private RepositorySystem repoSystem; private RepositorySystemSession repoSession; @Override public void download(String artifact) { Collections.singletonList(artifact).stream() .map(ArtifactTools::parseArtifact) .map(a -> DownloadTools.getRemoteArtifact(a, remoteRepos, repoSystem, repoSession)); } @Override public void setRemoteRepos(List<RemoteRepository> remoteRepos) { this.remoteRepos = remoteRepos; } @Override public void setRepoSession(RepositorySystemSession repoSession) { this.repoSession = repoSession; } @Override public void setRepoSystem(RepositorySystem repoSystem) { this.repoSystem = repoSystem; } }
mit
OKtoshi/ROKOS
clients-nodes/flavors/rokos-flavors-Pi2-Pi3/horizon/src/java/nxt/http/GetECBlock.java
2393
/****************************************************************************** * Copyright © 2013-2015 The Nxt Core Developers. * * * * See the AUTHORS.txt, DEVELOPER-AGREEMENT.txt and LICENSE.txt files at * * the top-level directory of this distribution for the individual copyright * * holder information and the developer policies on copyright and licensing. * * * * Unless otherwise agreed in a custom licensing agreement, no part of the * * Nxt software, including this file, may be copied, modified, propagated, * * or distributed except according to the terms contained in the LICENSE.txt * * file. * * * * Removal or modification of this copyright notice is prohibited. * * * ******************************************************************************/ package nxt.http; import nxt.Block; import nxt.Constants; import nxt.EconomicClustering; import nxt.Nxt; import nxt.NxtException; import org.json.simple.JSONObject; import org.json.simple.JSONStreamAware; import javax.servlet.http.HttpServletRequest; public final class GetECBlock extends APIServlet.APIRequestHandler { static final GetECBlock instance = new GetECBlock(); private GetECBlock() { super(new APITag[] {APITag.BLOCKS}, "timestamp"); } @Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { int timestamp = ParameterParser.getTimestamp(req); if (timestamp == 0) { timestamp = Nxt.getEpochTime(); } if (timestamp < Nxt.getBlockchain().getLastBlock().getTimestamp() - Constants.MAX_TIMEDRIFT) { return JSONResponses.INCORRECT_TIMESTAMP; } Block ecBlock = EconomicClustering.getECBlock(timestamp); JSONObject response = new JSONObject(); response.put("ecBlockId", ecBlock.getStringId()); response.put("ecBlockHeight", ecBlock.getHeight()); response.put("timestamp", timestamp); return response; } }
mit
misthupper/CreditApp
source/main/Main.java
3728
package source.main; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.*; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage stage) throws Exception{ stage.setTitle("Ha28"); BorderPane borderPane = new BorderPane(); HBox toolbarBox = new HBox(); toolbarBox.setPadding(new Insets(15, 12, 15, 12)); toolbarBox.setSpacing(10); toolbarBox.setStyle("-fx-background-color: #336699;"); VBox navigationBox = new VBox(); navigationBox.setPadding(new Insets(15, 12, 15, 12)); //navigationBox.setStyle("-fx-background-color: #FF1111;"); final CategoryAxis xAxis = new CategoryAxis(); final NumberAxis yAxis = new NumberAxis(); final LineChart<String,Number> lineChart = new LineChart<String, Number>(xAxis,yAxis); xAxis.setLabel("Monat"); lineChart.setTitle("Kredit-Monitoring Ha28"); XYChart.Series series1 = new XYChart.Series(); series1.setName("Kredit"); series1.getData().add(new XYChart.Data("Jul 15", 230000)); series1.getData().add(new XYChart.Data("Dez 15", 228000)); series1.getData().add(new XYChart.Data("Dez 16", 213000)); series1.getData().add(new XYChart.Data("Apr 17", 199000)); XYChart.Series series2 = new XYChart.Series(); series2.setName("Bausparer 2"); series2.getData().add(new XYChart.Data("Jul 15", 0)); series2.getData().add(new XYChart.Data("Dez 15", 500)); series2.getData().add(new XYChart.Data("Dez 16", 3000)); series2.getData().add(new XYChart.Data("Apr 17", 9800)); XYChart.Series series3 = new XYChart.Series(); series3.setName("Bausparer inkl. Kredit"); series3.getData().add(new XYChart.Data("Jul 15", 0)); series3.getData().add(new XYChart.Data("Dez 15", getBausparerMitKredit(500))); series3.getData().add(new XYChart.Data("Dez 16", getBausparerMitKredit(3000))); series3.getData().add(new XYChart.Data("Apr 17", getBausparerMitKredit(9800))); Pane centerPane = new Pane(); centerPane.getChildren().addAll(lineChart); Label label = new Label(); //String.valueOf(getDifferenzGuthabenKredit(199000, getBausparerMitKredit(9800)))); label.setText("HALLO HBOX!"); label.setPrefSize(100, 20); toolbarBox.getChildren().addAll(label); Button scene1 = new Button(); scene1.setText("LineChart"); scene1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { borderPane.setCenter(centerPane); } }); navigationBox.getChildren().add(scene1); borderPane.setTop(toolbarBox); borderPane.setLeft(navigationBox); //borderPane.setCenter(centerPane); Scene scene = new Scene(borderPane, 800, 600); lineChart.getData().addAll(series1, series2, series3); stage.setScene(scene); stage.show(); } private double getBausparerMitKredit(double guthaben) { return guthaben/0.4; } private double getDifferenzGuthabenKredit(double Kredit, double Guthaben) { return Kredit - Guthaben; } public static void main(String[] args) { launch(args); } }
mit
rubenlagus/TelegramBots
telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaAnimation.java
2816
package org.telegram.telegrambots.meta.api.objects.media; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.File; import java.io.InputStream; import java.util.List; /** * @author Ruben Bermudez * @version 4.0.0 * * Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent. */ @SuppressWarnings("unused") @JsonDeserialize @EqualsAndHashCode(callSuper = true) @Getter @Setter @ToString public class InputMediaAnimation extends InputMedia { private static final String TYPE = "animation"; public static final String WIDTH_FIELD = "width"; public static final String HEIGHT_FIELD = "height"; public static final String DURATION_FIELD = "duration"; public static final String THUMB_FIELD = "thumb"; @JsonProperty(WIDTH_FIELD) private Integer width; ///< Optional. Animation width @JsonProperty(HEIGHT_FIELD) private Integer height; ///< Optional. Animation height @JsonProperty(DURATION_FIELD) private Integer duration; ///< Optional. Animation duration /** * Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size. * A thumbnail’s width and height should not exceed 320. * Ignored if the file is not uploaded using multipart/form-data. * Thumbnails can’t be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” * if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. */ private InputFile thumb; public InputMediaAnimation() { super(); } public InputMediaAnimation(@NonNull String media) { super(media); } @Builder public InputMediaAnimation(@NonNull String media, String caption, String parseMode, List<MessageEntity> entities, boolean isNewMedia, String mediaName, File newMediaFile, InputStream newMediaStream, Integer width, Integer height, Integer duration, InputFile thumb) { super(media, caption, parseMode, entities, isNewMedia, mediaName, newMediaFile, newMediaStream); this.width = width; this.height = height; this.duration = duration; this.thumb = thumb; } @Override public String getType() { return TYPE; } @Override public void validate() throws TelegramApiValidationException { super.validate(); } }
mit
moccaplusplus/LightweightCDI
src/main/java/com/moccaplusplus/cdi/TypeInfoProvider.java
649
package com.moccaplusplus.cdi; import java.util.HashMap; import java.util.Map; public class TypeInfoProvider { private final Map<Class<?>, TypeInfo<?>> map; public TypeInfoProvider() { map = new HashMap<Class<?>, TypeInfo<?>>(); } public <T> TypeInfo<T> getTypeInfo(Class<T> c) { if (c == null) { return null; } @SuppressWarnings("unchecked") TypeInfo<T> typeInfo = (TypeInfo<T>) map.get(c); if (typeInfo == null) { typeInfo = new TypeInfo<T>(c, getTypeInfo(c.getSuperclass())); map.put(c, typeInfo); } return typeInfo; } }
mit
ErikVerheul/jenkins
core/src/main/java/hudson/slaves/DelegatingComputerLauncher.java
4561
/* * The MIT License * * Copyright (c) 2010, InfraDNA, 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 hudson.slaves; import hudson.RestrictedSince; import hudson.model.Descriptor; import hudson.model.Slave; import hudson.model.TaskListener; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import jenkins.model.Jenkins; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.DoNotUse; /** * Base implementation of {@link ComputerLauncher} that to be used by launchers that * perform some initialization (typically something cloud/v12n related * to power up the machine), and then delegate to another {@link ComputerLauncher} * to connect. * * <strong>If you are delegating to another {@link ComputerLauncher} you must extend this base class</strong> * * @author Kohsuke Kawaguchi * @since 1.382 */ public abstract class DelegatingComputerLauncher extends ComputerLauncher { protected ComputerLauncher launcher; protected DelegatingComputerLauncher(ComputerLauncher launcher) { this.launcher = launcher; } public ComputerLauncher getLauncher() { return launcher; } @Override public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException { getLauncher().launch(computer, listener); } @Override public void afterDisconnect(SlaveComputer computer, TaskListener listener) { getLauncher().afterDisconnect(computer, listener); } @Override public void beforeDisconnect(SlaveComputer computer, TaskListener listener) { getLauncher().beforeDisconnect(computer, listener); } public static abstract class DescriptorImpl extends Descriptor<ComputerLauncher> { /** * Returns the applicable nested computer launcher types. * The default implementation avoids all delegating descriptors, as that creates infinite recursion. * @since 2.12 */ public List<Descriptor<ComputerLauncher>> applicableDescriptors(@CheckForNull Slave it, @Nonnull Slave.SlaveDescriptor itDescriptor) { List<Descriptor<ComputerLauncher>> r = new ArrayList<>(); for (Descriptor<ComputerLauncher> d : itDescriptor.computerLauncherDescriptors(it)) { if (DelegatingComputerLauncher.class.isAssignableFrom(d.getKlass().toJavaClass())) continue; r.add(d); } return r; } /** * Returns the applicable nested computer launcher types. * The default implementation avoids all delegating descriptors, as that creates infinite recursion. * @deprecated use {@link #applicableDescriptors(Slave, Slave.SlaveDescriptor)} */ @Deprecated @Restricted(DoNotUse.class) @RestrictedSince("2.12") public List<Descriptor<ComputerLauncher>> getApplicableDescriptors() { List<Descriptor<ComputerLauncher>> r = new ArrayList<>(); for (Descriptor<ComputerLauncher> d : Jenkins.get().<ComputerLauncher, Descriptor<ComputerLauncher>>getDescriptorList(ComputerLauncher.class)) { if (DelegatingComputerLauncher.class.isAssignableFrom(d.getKlass().toJavaClass())) continue; r.add(d); } return r; } } }
mit
digero/maestro
src/com/digero/abcplayer/AbcPlayer.java
53043
package com.digero.abcplayer; import info.clearthought.layout.TableLayout; import info.clearthought.layout.TableLayoutConstants; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Image; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.prefs.Preferences; import javax.imageio.ImageIO; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiUnavailableException; import javax.sound.midi.Sequence; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.filechooser.FileFilter; import com.digero.abcplayer.view.HighlightAbcNotesFrame; import com.digero.abcplayer.view.TrackListPanel; import com.digero.abcplayer.view.TrackListPanelCallback; import com.digero.common.abc.LotroInstrument; import com.digero.common.abctomidi.AbcInfo; import com.digero.common.abctomidi.AbcToMidi; import com.digero.common.abctomidi.FileAndData; import com.digero.common.icons.IconLoader; import com.digero.common.midi.MidiConstants; import com.digero.common.midi.LotroSequencerWrapper; import com.digero.common.midi.SequencerEvent; import com.digero.common.midi.SequencerEvent.SequencerProperty; import com.digero.common.midi.SequencerWrapper; import com.digero.common.midi.VolumeTransceiver; import com.digero.common.util.ExtensionFileFilter; import com.digero.common.util.FileFilterDropListener; import com.digero.common.util.Listener; import com.digero.common.util.LotroParseException; import com.digero.common.util.ParseException; import com.digero.common.util.Util; import com.digero.common.util.Version; import com.digero.common.view.AboutDialog; import com.digero.common.view.BarNumberLabel; import com.digero.common.view.NativeVolumeBar; import com.digero.common.view.SongPositionBar; import com.digero.common.view.SongPositionLabel; import com.digero.common.view.TempoBar; public class AbcPlayer extends JFrame implements TableLayoutConstants, MidiConstants, TrackListPanelCallback { private static final ExtensionFileFilter ABC_FILE_FILTER = new ExtensionFileFilter("ABC Files", "abc", "txt"); public static final String APP_NAME = "ABC Player"; private static final String APP_NAME_LONG = APP_NAME + " for The Lord of the Rings Online"; private static final String APP_URL = "https://github.com/digero/maestro/"; private static final String LAME_URL = "http://lame.sourceforge.net/"; private static Version APP_VERSION = new Version(0, 0, 0); private static AbcPlayer mainWindow = null; public static void main(String[] args) { try { Properties props = new Properties(); props.load(AbcPlayer.class.getResourceAsStream("version.txt")); String versionString = props.getProperty("version.AbcPlayer"); if (versionString != null) APP_VERSION = Version.parseVersion(versionString); } catch (IOException ex) { } System.setProperty("sun.sound.useNewAudioEngine", "true"); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } mainWindow = new AbcPlayer(); mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainWindow.setVisible(true); mainWindow.openSongFromCommandLine(args); try { ready(); } catch (UnsatisfiedLinkError err) { // Ignore (we weren't started via WinRun4j) } } public static native boolean isVolumeSupported(); private static boolean isVolumeSupportedSafe() { try { return isVolumeSupported(); } catch (UnsatisfiedLinkError err) { return false; } } public static native float getVolume(); public static native void setVolume(float volume); public static void onVolumeChanged() { if (mainWindow != null && mainWindow.volumeBar != null) mainWindow.volumeBar.repaint(); } /** Tells the WinRun4J launcher that we're ready to accept activate() calls. */ public static native void ready(); /** A new activation (a.k.a. a file was opened) */ public static void activate(String[] args) { mainWindow.openSongFromCommandLine(args); } public static void execute(String cmdLine) { mainWindow.openSongFromCommandLine(new String[] { cmdLine }); } private final SequencerWrapper sequencer; private boolean useLotroInstruments = true; private FileFilterDropListener dropListener; private JPanel content; private JLabel titleLabel; private TrackListPanel trackListPanel; private SongPositionBar songPositionBar; private SongPositionLabel songPositionLabel; private BarNumberLabel barNumberLabel; private JLabel tempoLabel; private TempoBar tempoBar; private NativeVolumeBar volumeBar; private VolumeTransceiver volumeTransceiver; private ImageIcon playIcon, pauseIcon, stopIcon; private ImageIcon playIconDisabled, pauseIconDisabled, stopIconDisabled; private JButton playButton, stopButton; private JCheckBoxMenuItem lotroErrorsMenuItem; private JCheckBoxMenuItem stereoMenuItem; private JCheckBoxMenuItem showFullPartNameMenuItem; private JCheckBoxMenuItem showAbcViewMenuItem; private JFileChooser openFileDialog; private JFileChooser saveFileDialog; private JFileChooser exportFileDialog; private HighlightAbcNotesFrame abcViewFrame; private final Map<Integer, LotroInstrument> instrumentOverrideMap = new HashMap<Integer, LotroInstrument>(); private List<FileAndData> abcData; private AbcInfo abcInfo = new AbcInfo(); private Preferences prefs = Preferences.userNodeForPackage(AbcPlayer.class); private boolean isExporting = false; public AbcPlayer() { super(APP_NAME); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (sequencer != null) sequencer.close(); } }); try { List<Image> icons = new ArrayList<Image>(); icons.add(ImageIO.read(IconLoader.class.getResourceAsStream("abcplayer_16.png"))); icons.add(ImageIO.read(IconLoader.class.getResourceAsStream("abcplayer_32.png"))); setIconImages(icons); } catch (Exception ex) { // Ignore } dropListener = new FileFilterDropListener(true, "abc", "txt"); dropListener.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { FileFilterDropListener l = (FileFilterDropListener) e.getSource(); boolean append = (l.getDropEvent().getDropAction() == DnDConstants.ACTION_COPY); SwingUtilities.invokeLater(new OpenSongRunnable(append, l.getDroppedFiles().toArray(new File[0]))); } }); new DropTarget(this, dropListener); if (isVolumeSupportedSafe()) { volumeTransceiver = null; } else { volumeTransceiver = new VolumeTransceiver(); volumeTransceiver.setVolume(prefs.getInt("volumizer", VolumeTransceiver.MAX_VOLUME)); } volumeBar = new NativeVolumeBar(new NativeVolumeBar.Callback() { @Override public void setVolume(int volume) { if (volumeTransceiver == null) AbcPlayer.setVolume((float) volume / NativeVolumeBar.MAX_VOLUME); else { volumeTransceiver.setVolume(volume); prefs.putInt("volumizer", volume); } } @Override public int getVolume() { if (volumeTransceiver == null) return (int) (AbcPlayer.getVolume() * NativeVolumeBar.MAX_VOLUME); else return volumeTransceiver.getVolume(); } }); try { if (useLotroInstruments) { sequencer = new LotroSequencerWrapper(); if (LotroSequencerWrapper.getLoadLotroSynthError() != null) { Version requredJavaVersion = new Version(1, 7, 0, 0); Version recommendedJavaVersion = new Version(1, 7, 0, 25); JPanel errorMessage = new JPanel(new BorderLayout(0, 12)); errorMessage.add(new JLabel( "<html><b>There was an error loading the LOTRO instrument sounds</b><br>" + "Playback will use standard MIDI instruments instead<br>" + "(drums do not sound good in this mode).</html>"), BorderLayout.NORTH); final String JAVA_URL = "http://www.java.com"; if (requredJavaVersion.compareTo(Version.parseVersion(System.getProperty("java.version"))) > 0) { JLabel update = new JLabel("<html>It is recommended that you install Java " + recommendedJavaVersion.getMinor() + " update " + recommendedJavaVersion.getRevision() + " or later.<br>" + "Get the latest version from <a href='" + JAVA_URL + "'>" + JAVA_URL + "</a>.</html>"); update.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); update.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { Util.openURL(JAVA_URL); } } }); errorMessage.add(update, BorderLayout.CENTER); } errorMessage.add( new JLabel("<html>Error details:<br>" + LotroSequencerWrapper.getLoadLotroSynthError() + "</html>"), BorderLayout.SOUTH); JOptionPane.showMessageDialog(this, errorMessage, APP_NAME + " failed to load LOTRO instruments", JOptionPane.ERROR_MESSAGE); useLotroInstruments = false; } } else { sequencer = new SequencerWrapper(); } if (volumeTransceiver != null) sequencer.addTransceiver(volumeTransceiver); } catch (MidiUnavailableException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "MIDI error", JOptionPane.ERROR_MESSAGE); System.exit(1); // This will never be hit, but convinces the compiler that // the sequencer field will never be uninitialized throw new RuntimeException(); } content = new JPanel(new TableLayout(// new double[] { 4, FILL, 4 },// new double[] { PREFERRED, 0, FILL, 8, PREFERRED })); setContentPane(content); titleLabel = new JLabel(" "); Font f = titleLabel.getFont(); titleLabel.setFont(f.deriveFont(Font.BOLD, 16)); titleLabel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); trackListPanel = new TrackListPanel(sequencer, this); JScrollPane trackListScroller = new JScrollPane(trackListPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); trackListScroller.getVerticalScrollBar().setUnitIncrement(TrackListPanel.TRACKLIST_ROWHEIGHT); trackListScroller.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.GRAY)); JPanel controlPanel = new JPanel(new TableLayout(// new double[] { 4, SongPositionBar.SIDE_PAD, 0.5, 4, PREFERRED, 4, PREFERRED, 4, 0.5, SongPositionBar.SIDE_PAD, 4, PREFERRED, 4 },// new double[] { 4, PREFERRED, 4, PREFERRED, 4 })); songPositionBar = new SongPositionBar(sequencer); songPositionLabel = new SongPositionLabel(sequencer); barNumberLabel = new BarNumberLabel(sequencer, null); barNumberLabel.setToolTipText("Bar number"); playIcon = IconLoader.getImageIcon("play.png"); playIconDisabled = IconLoader.getDisabledIcon("play.png"); pauseIcon = IconLoader.getImageIcon("pause.png"); pauseIconDisabled = IconLoader.getDisabledIcon("pause.png"); stopIcon = IconLoader.getImageIcon("stop.png"); stopIconDisabled = IconLoader.getDisabledIcon("stop.png"); playButton = new JButton(playIcon); playButton.setDisabledIcon(playIconDisabled); playButton.setEnabled(false); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { playPause(); } }); stopButton = new JButton(stopIcon); stopButton.setDisabledIcon(stopIconDisabled); stopButton.setEnabled(false); stopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stop(); } }); tempoBar = new TempoBar(sequencer); tempoLabel = new JLabel(); tempoLabel.setHorizontalAlignment(SwingConstants.CENTER); updateTempoLabel(); JPanel tempoPanel = new JPanel(new BorderLayout()); tempoPanel.add(tempoLabel, BorderLayout.NORTH); tempoPanel.add(tempoBar, BorderLayout.CENTER); JPanel volumePanel = new JPanel(new BorderLayout()); JLabel volumeLabel = new JLabel("Volume"); volumeLabel.setHorizontalAlignment(SwingConstants.CENTER); volumePanel.add(volumeLabel, BorderLayout.NORTH); volumePanel.add(volumeBar, BorderLayout.CENTER); controlPanel.add(songPositionBar, "1, 1, 9, 1"); controlPanel.add(songPositionLabel, "11, 1"); controlPanel.add(playButton, "4, 3"); controlPanel.add(stopButton, "6, 3"); controlPanel.add(tempoPanel, "2, 3, c, c"); controlPanel.add(volumePanel, "8, 3, c, c"); controlPanel.add(barNumberLabel, "9, 3, 11, 3, r, t"); sequencer.addChangeListener(new Listener<SequencerEvent>() { @Override public void onEvent(SequencerEvent evt) { SequencerProperty p = evt.getProperty(); if (!p.isInMask(SequencerProperty.THUMB_POSITION_MASK)) { updateButtonStates(); } if (p.isInMask(SequencerProperty.TEMPO.mask | SequencerProperty.SEQUENCE.mask)) { updateTempoLabel(); } } }); add(titleLabel, "0, 0, 2, 0"); add(trackListScroller, "0, 2, 2, 2"); add(controlPanel, "1, 4"); initMenu(); updateButtonStates(); setMinimumSize(new Dimension(320, 168)); Util.initWinBounds(this, prefs.node("window"), 450, 282); } @Override public void setTrackInstrumentOverride(int trackIndex, LotroInstrument instrument) { instrumentOverrideMap.put(trackIndex, instrument); refreshSequence(); } @Override public void showHighlightPanelForTrack(int trackIndex) { updateAbcView(/* showIfHidden = */true, /* retainScrollPosition = */false); abcViewFrame.scrollToLineNumber(abcInfo.getPartStartLine(trackIndex)); abcViewFrame.setFollowedTrackNumber(trackIndex); } private void updateAbcView(boolean showIfHidden, boolean retainScrollPosition) { boolean hasAbcData = (abcData != null && abcInfo != null); if (showAbcViewMenuItem != null) showAbcViewMenuItem.setEnabled(hasAbcData); boolean isVisible = (abcViewFrame != null && abcViewFrame.isVisible()); if (!isVisible && !showIfHidden) return; if (abcViewFrame == null) { abcViewFrame = new HighlightAbcNotesFrame(sequencer); abcViewFrame.setTitle(getTitle()); abcViewFrame.setIconImages(getIconImages()); abcViewFrame.addDropListener(dropListener); abcViewFrame.setShowFullPartName(showFullPartNameMenuItem.isSelected()); abcViewFrame.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { if (showAbcViewMenuItem != null) { showAbcViewMenuItem.setSelected(true); prefs.putBoolean("showAbcViewMenuItem", true); } } @Override public void windowClosed(WindowEvent e) { if (showAbcViewMenuItem != null) { showAbcViewMenuItem.setSelected(false); prefs.putBoolean("showAbcViewMenuItem", false); } } }); } if (!hasAbcData) { abcViewFrame.setFollowedTrackNumber(-1); abcViewFrame.clearLinesAndRegions(); } else { List<String> lines = new ArrayList<String>(); for (FileAndData entry : abcData) lines.addAll(entry.lines); final int startLine = 0; abcViewFrame.setLinesAndRegions(lines, startLine, abcInfo); if (!retainScrollPosition) abcViewFrame.scrollToLineNumber(startLine); } if (showIfHidden) { if (!isVisible) abcViewFrame.setVisible(true); abcViewFrame.toFront(); } } private void updateTitleLabel() { String title = abcInfo.getTitle(); String artist = abcInfo.getComposer_MaybeNull(); if (artist != null) { titleLabel.setText("<html>" + title + "&ensp;<span style='font-size:12pt; font-weight:normal'>" + artist + "</span></html>"); } else { titleLabel.setText(title); } String tooltip = title; if (artist != null) tooltip += " - " + artist; titleLabel.setToolTipText(tooltip); } private void updateTempoLabel() { float tempo = sequencer.getTempoFactor(); int t = Math.round(tempo * 100); tempoLabel.setText("Tempo: " + t + "%"); } private void initMenu() { JMenuBar mainMenu = new JMenuBar(); setJMenuBar(mainMenu); JMenu fileMenu = mainMenu.add(new JMenu(" File ")); fileMenu.setMnemonic(KeyEvent.VK_F); JMenuItem open = fileMenu.add(new JMenuItem("Open ABC file(s)...")); open.setMnemonic(KeyEvent.VK_O); open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)); open.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { openSongDialog(); } }); JMenuItem openAppend = fileMenu.add(new JMenuItem("Append ABC file(s)...")); openAppend.setMnemonic(KeyEvent.VK_D); openAppend.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); openAppend.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { appendSongDialog(); } }); final JMenuItem pasteMenuItem = fileMenu.add(new JMenuItem("Open from clipboard")); pasteMenuItem.setMnemonic(KeyEvent.VK_P); pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_DOWN_MASK)); pasteMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ArrayList<File> files = new ArrayList<File>(); if (getFileListFromClipboard(files)) { openSong(files.toArray(new File[files.size()])); return; } ArrayList<String> lines = new ArrayList<String>(); if (getAbcDataFromClipboard(lines, false)) { List<FileAndData> filesData = new ArrayList<FileAndData>(); filesData.add(new FileAndData(new File("[Clipboard]"), lines)); openSong(filesData); return; } Toolkit.getDefaultToolkit().beep(); } }); final JMenuItem pasteAppendMenuItem = fileMenu.add(new JMenuItem("Append from clipboard")); pasteAppendMenuItem.setMnemonic(KeyEvent.VK_N); pasteAppendMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); pasteAppendMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ArrayList<File> files = new ArrayList<File>(); if (getFileListFromClipboard(files)) { appendSong(files.toArray(new File[files.size()])); return; } ArrayList<String> lines = new ArrayList<String>(); if (getAbcDataFromClipboard(lines, true)) { List<FileAndData> data = new ArrayList<FileAndData>(); data.add(new FileAndData(new File("[Clipboard]"), lines)); appendSong(data); return; } Toolkit.getDefaultToolkit().beep(); } }); fileMenu.addSeparator(); final JMenuItem saveMenuItem = fileMenu.add(new JMenuItem("Save a copy as ABC...")); saveMenuItem.setMnemonic(KeyEvent.VK_S); saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); saveMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!sequencer.isLoaded()) { Toolkit.getDefaultToolkit().beep(); return; } saveSongDialog(); } }); final JMenuItem exportMp3MenuItem = fileMenu.add(new JMenuItem("Save as MP3 file...")); exportMp3MenuItem.setMnemonic(KeyEvent.VK_M); exportMp3MenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK)); exportMp3MenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!sequencer.isLoaded() || isExporting) { Toolkit.getDefaultToolkit().beep(); return; } exportMp3(); } }); final JMenuItem exportWavMenuItem = fileMenu.add(new JMenuItem("Save as Wave file...")); exportWavMenuItem.setMnemonic(KeyEvent.VK_E); exportWavMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); exportWavMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!sequencer.isLoaded() || isExporting) { Toolkit.getDefaultToolkit().beep(); return; } exportWav(); } }); fileMenu.addSeparator(); JMenuItem exit = fileMenu.add(new JMenuItem("Exit")); exit.setMnemonic(KeyEvent.VK_X); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_DOWN_MASK)); exit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); fileMenu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { boolean pasteEnabled = getFileListFromClipboard(null); pasteMenuItem.setEnabled(pasteEnabled || getAbcDataFromClipboard(null, false)); pasteAppendMenuItem.setEnabled(pasteEnabled || getAbcDataFromClipboard(null, true)); boolean saveEnabled = sequencer.isLoaded(); saveMenuItem.setEnabled(saveEnabled); exportWavMenuItem.setEnabled(saveEnabled && !isExporting); exportMp3MenuItem.setEnabled(saveEnabled && !isExporting); } @Override public void menuDeselected(MenuEvent e) { menuCanceled(e); } @Override public void menuCanceled(MenuEvent e) { pasteMenuItem.setEnabled(true); pasteAppendMenuItem.setEnabled(true); saveMenuItem.setEnabled(true); exportWavMenuItem.setEnabled(true); exportMp3MenuItem.setEnabled(true); } }); JMenu toolsMenu = mainMenu.add(new JMenu(" Tools ")); toolsMenu.setMnemonic(KeyEvent.VK_T); toolsMenu.add(lotroErrorsMenuItem = new JCheckBoxMenuItem("Ignore LOTRO-specific errors")); lotroErrorsMenuItem.setSelected(prefs.getBoolean("ignoreLotroErrors", false)); lotroErrorsMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { prefs.putBoolean("ignoreLotroErrors", lotroErrorsMenuItem.isSelected()); } }); toolsMenu.add(stereoMenuItem = new JCheckBoxMenuItem("Stereo pan in multi-part songs")); stereoMenuItem.setToolTipText("<html>Separates the parts of a multi-part song by <br>" + "panning them towards the left or right speaker.</html>"); stereoMenuItem.setSelected(prefs.getBoolean("stereoMenuItem", true)); stereoMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { prefs.putBoolean("stereoMenuItem", stereoMenuItem.isSelected()); refreshSequence(); } }); toolsMenu.addSeparator(); toolsMenu.add(showFullPartNameMenuItem = new JCheckBoxMenuItem("Show full part names")); showFullPartNameMenuItem.setSelected(prefs.getBoolean("showFullPartNameMenuItem", false)); trackListPanel.setShowFullPartName(showFullPartNameMenuItem.isSelected()); if (abcViewFrame != null) abcViewFrame.setShowFullPartName(showFullPartNameMenuItem.isSelected()); showFullPartNameMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { prefs.putBoolean("showFullPartNameMenuItem", showFullPartNameMenuItem.isSelected()); trackListPanel.setShowFullPartName(showFullPartNameMenuItem.isSelected()); if (abcViewFrame != null) abcViewFrame.setShowFullPartName(showFullPartNameMenuItem.isSelected()); } }); final JCheckBoxMenuItem showLineNumbersMenuItem = new JCheckBoxMenuItem("Show line numbers"); toolsMenu.add(showLineNumbersMenuItem); showLineNumbersMenuItem.setSelected(prefs.getBoolean("showLineNumbersMenuItem", true)); trackListPanel.setShowLineNumbers(showLineNumbersMenuItem.isSelected()); showLineNumbersMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { prefs.putBoolean("showLineNumbersMenuItem", showLineNumbersMenuItem.isSelected()); trackListPanel.setShowLineNumbers(showLineNumbersMenuItem.isSelected()); } }); final JCheckBoxMenuItem showSoloButtonsMenuItem = new JCheckBoxMenuItem("Show track solo buttons"); toolsMenu.add(showSoloButtonsMenuItem); showSoloButtonsMenuItem.setSelected(prefs.getBoolean("showSoloButtonsMenuItem", true)); trackListPanel.setShowSoloButtons(showSoloButtonsMenuItem.isSelected()); showSoloButtonsMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { prefs.putBoolean("showSoloButtonsMenuItem", showSoloButtonsMenuItem.isSelected()); trackListPanel.setShowSoloButtons(showSoloButtonsMenuItem.isSelected()); } }); final JCheckBoxMenuItem showInstrumentComboBoxesMenuItem = new JCheckBoxMenuItem("Show instrument pickers"); toolsMenu.add(showInstrumentComboBoxesMenuItem); showInstrumentComboBoxesMenuItem.setSelected(prefs.getBoolean("showInstrumentComboBoxesMenuItem", true)); trackListPanel.setShowInstrumentComboBoxes(showInstrumentComboBoxesMenuItem.isSelected()); showInstrumentComboBoxesMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { prefs.putBoolean("showInstrumentComboBoxesMenuItem", showInstrumentComboBoxesMenuItem.isSelected()); trackListPanel.setShowInstrumentComboBoxes(showInstrumentComboBoxesMenuItem.isSelected()); } }); toolsMenu.addSeparator(); JMenuItem about = toolsMenu.add(new JMenuItem("About " + APP_NAME + "...")); about.setMnemonic(KeyEvent.VK_A); about.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AboutDialog.show(AbcPlayer.this, APP_NAME_LONG, APP_VERSION, APP_URL, "abcplayer_64.png"); } }); JMenu abcViewMenu = mainMenu.add(new JMenu(" ABC View ")); abcViewMenu.setMnemonic(KeyEvent.VK_A); abcViewMenu.add(showAbcViewMenuItem = new JCheckBoxMenuItem("Show ABC text")); showAbcViewMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (showAbcViewMenuItem.isSelected()) { updateAbcView(/* showIfHidden = */true, /* retainScrollPosition = */false); } else if (abcViewFrame != null) { abcViewFrame.setVisible(false); } } }); } private boolean getAbcDataFromClipboard(ArrayList<String> data, boolean checkContents) { if (data != null) data.clear(); Transferable xfer = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); if (xfer == null || !xfer.isDataFlavorSupported(DataFlavor.stringFlavor)) return false; String text; try { text = (String) xfer.getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException e) { return false; } catch (IOException e) { return false; } if (!checkContents && data == null) return true; StringTokenizer tok = new StringTokenizer(text, "\r\n"); int i = 0; boolean isValid = !checkContents; while (tok.hasMoreTokens()) { String line = tok.nextToken(); if (!isValid) { if (line.startsWith("X:") || line.startsWith("x:")) { isValid = true; if (data == null) break; } else { String lineTrim = line.trim(); // If we find a line that's not a comment before the // X: line, then this isn't an ABC file if (lineTrim.length() > 0 && !lineTrim.startsWith("%")) { isValid = false; break; } } } if (data != null) data.add(line); else if (i >= 100) break; i++; } if (!isValid && data != null) data.clear(); return isValid; } @SuppressWarnings("unchecked")// private boolean getFileListFromClipboard(ArrayList<File> data) { if (data != null) data.clear(); Transferable xfer = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); if (xfer == null || !xfer.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) return false; List<File> fileList; try { fileList = (List<File>) xfer.getTransferData(DataFlavor.javaFileListFlavor); } catch (UnsupportedFlavorException e) { return false; } catch (IOException e) { return false; } if (fileList.size() == 0) return false; for (File file : fileList) { if (!ABC_FILE_FILTER.accept(file)) { if (data != null) data.clear(); return false; } if (data != null) data.add(file); } return true; } private void initOpenFileDialog() { if (openFileDialog == null) { openFileDialog = new JFileChooser(prefs.get("openFileDialog.currentDirectory", Util .getLotroMusicPath(false).getAbsolutePath())); openFileDialog.setMultiSelectionEnabled(true); openFileDialog.setFileFilter(ABC_FILE_FILTER); } } private void openSongDialog() { initOpenFileDialog(); int result = openFileDialog.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { prefs.put("openFileDialog.currentDirectory", openFileDialog.getCurrentDirectory().getAbsolutePath()); openSong(openFileDialog.getSelectedFiles()); } } private void appendSongDialog() { if (this.abcData == null || this.abcData.size() == 0) { openSongDialog(); return; } initOpenFileDialog(); int result = openFileDialog.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { prefs.put("openFileDialog.currentDirectory", openFileDialog.getCurrentDirectory().getAbsolutePath()); appendSong(openFileDialog.getSelectedFiles()); } } private void saveSongDialog() { if (this.abcData == null || this.abcData.size() == 0) { Toolkit.getDefaultToolkit().beep(); return; } if (saveFileDialog == null) { saveFileDialog = new JFileChooser(prefs.get("saveFileDialog.currentDirectory", Util .getLotroMusicPath(false).getAbsolutePath())); saveFileDialog.setFileFilter(ABC_FILE_FILTER); } int result = saveFileDialog.showSaveDialog(this); if (result == JFileChooser.APPROVE_OPTION) { prefs.put("saveFileDialog.currentDirectory", saveFileDialog.getCurrentDirectory().getAbsolutePath()); String fileName = saveFileDialog.getSelectedFile().getName(); int dot = fileName.lastIndexOf('.'); if (dot <= 0 || !fileName.substring(dot).equalsIgnoreCase(".abc")) fileName += ".abc"; File saveFileTmp = new File(saveFileDialog.getSelectedFile().getParent(), fileName); if (saveFileTmp.exists()) { int res = JOptionPane.showConfirmDialog(this, "File " + fileName + " already exists. Overwrite?", "Confirm Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (res != JOptionPane.YES_OPTION) return; } saveFileDialog.setSelectedFile(saveFileTmp); saveSong(saveFileTmp); } } private boolean openSongFromCommandLine(String[] args) { mainWindow.setExtendedState(mainWindow.getExtendedState() & ~JFrame.ICONIFIED); if (args.length > 0) { File[] argFiles = new File[args.length]; for (int i = 0; i < args.length; i++) { argFiles[i] = new File(args[i]); } return openSong(argFiles); } return false; } private class OpenSongRunnable implements Runnable { private File[] abcFiles; private boolean append; public OpenSongRunnable(boolean append, File... abcFiles) { this.append = append; this.abcFiles = abcFiles; } @Override public void run() { if (append) appendSong(abcFiles); else openSong(abcFiles); } } private boolean openSong(File[] abcFiles) { List<FileAndData> data = new ArrayList<FileAndData>(); try { for (File abcFile : abcFiles) { data.add(new FileAndData(abcFile, AbcToMidi.readLines(abcFile))); } } catch (IOException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Failed to open file", JOptionPane.ERROR_MESSAGE); return false; } return openSong(data); } private boolean appendSong(File[] abcFiles) { List<FileAndData> data = new ArrayList<FileAndData>(); try { for (File abcFile : abcFiles) { data.add(new FileAndData(abcFile, AbcToMidi.readLines(abcFile))); } } catch (IOException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Failed to open file", JOptionPane.ERROR_MESSAGE); return false; } return appendSong(data); } private boolean onLotroParseError(LotroParseException lpe) { JCheckBox checkBox = new JCheckBox("Ignore LOTRO-specific errors"); Object[] message = new Object[] { lpe.getMessage(), checkBox }; JOptionPane.showMessageDialog(this, message, "Error reading ABC file", JOptionPane.WARNING_MESSAGE); prefs.putBoolean("ignoreLotroErrors", checkBox.isSelected()); lotroErrorsMenuItem.setSelected(checkBox.isSelected()); return checkBox.isSelected(); } private boolean openSong(List<FileAndData> data) { boolean isSameFile = false; if (abcData != null && abcData.size() == data.size()) { isSameFile = true; for (int i = 0; i < abcData.size(); i++) { if (!abcData.get(i).file.equals(data.get(i).file)) { isSameFile = false; break; } } } sequencer.stop(); // pause updateButtonStates(); Sequence song = null; AbcInfo info = new AbcInfo(); boolean retry; do { retry = false; try { AbcToMidi.Params params = new AbcToMidi.Params(data); params.useLotroInstruments = useLotroInstruments; params.abcInfo = info; params.enableLotroErrors = !lotroErrorsMenuItem.isSelected(); params.stereo = stereoMenuItem.isSelected(); params.generateRegions = true; song = AbcToMidi.convert(params); } catch (LotroParseException e) { if (onLotroParseError(e)) { retry = lotroErrorsMenuItem.isSelected(); } else { return false; } } catch (ParseException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Error reading ABC", JOptionPane.ERROR_MESSAGE); return false; } } while (retry); this.exportFileDialog = null; this.saveFileDialog = null; this.abcData = data; this.abcInfo = info; this.instrumentOverrideMap.clear(); if (abcViewFrame != null) abcViewFrame.clearLinesAndRegions(); stop(); try { sequencer.setSequence(song); } catch (InvalidMidiDataException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "MIDI error", JOptionPane.ERROR_MESSAGE); return false; } sequencer.setTempoFactor(1.0f); for (int i = 0; i < CHANNEL_COUNT; i++) { sequencer.setTrackMute(i, false); sequencer.setTrackSolo(i, false); } updateWindowTitle(); trackListPanel.songChanged(abcInfo); updateButtonStates(); updateTitleLabel(); barNumberLabel.setBarNumberCache(abcInfo); barNumberLabel.setVisible(abcInfo.getBarCount() > 0); updateAbcView(/* showIfHidden = */false, /* retainScrollPosition = */isSameFile); sequencer.start(); return true; } private boolean appendSong(List<FileAndData> appendData) { if (this.abcData == null || this.abcData.size() == 0) { return openSong(appendData); } boolean running = sequencer.isRunning() || !sequencer.isLoaded(); long position = sequencer.getPosition(); sequencer.stop(); // pause List<FileAndData> data = new ArrayList<FileAndData>(abcData); data.addAll(appendData); Sequence song = null; AbcInfo info = new AbcInfo(); boolean retry; do { retry = false; try { AbcToMidi.Params params = new AbcToMidi.Params(data); params.useLotroInstruments = useLotroInstruments; params.instrumentOverrideMap = instrumentOverrideMap; params.abcInfo = info; params.enableLotroErrors = !lotroErrorsMenuItem.isSelected(); params.stereo = stereoMenuItem.isSelected(); params.generateRegions = true; song = AbcToMidi.convert(params); } catch (LotroParseException e) { if (onLotroParseError(e)) { retry = lotroErrorsMenuItem.isSelected(); } else { return false; } } catch (ParseException e) { String thisFile = appendData.size() == 1 ? "this file" : "these files"; String msg = e.getMessage() + "\n\nWould you like to close the current song and retry opening " + thisFile + "?"; int result = JOptionPane.showConfirmDialog(this, msg, "Error appending ABC", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE); if (result == JOptionPane.YES_OPTION) { boolean success = openSong(appendData); sequencer.setRunning(success && running); return success; } else { return false; } } } while (retry); this.abcData = data; this.abcInfo = info; int oldTrackCount = sequencer.getSequence().getTracks().length; try { sequencer.reset(false); sequencer.setSequence(song); sequencer.setPosition(position); sequencer.setRunning(running); } catch (InvalidMidiDataException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "MIDI error", JOptionPane.ERROR_MESSAGE); return false; } // Make sure the new tracks are unmuted for (int i = oldTrackCount; i < CHANNEL_COUNT; i++) { sequencer.setTrackMute(i, false); sequencer.setTrackSolo(i, false); } updateWindowTitle(); trackListPanel.songChanged(abcInfo); updateButtonStates(); updateTitleLabel(); barNumberLabel.setBarNumberCache(abcInfo); barNumberLabel.setVisible(abcInfo.getBarCount() > 0); updateAbcView(/* showIfHidden = */false, /* retainScrollPosition = */true); return true; } private void updateWindowTitle() { String fileNames = ""; int c = 0; for (FileAndData fd : abcData) { File f = fd.file; if (++c > 1) fileNames += ", "; if (c > 2) { fileNames += "..."; break; } fileNames += f.getName(); } String title = APP_NAME; if (fileNames != "") title += " - " + fileNames; setTitle(title); if (abcViewFrame != null) abcViewFrame.setTitle(title); } private boolean saveSong(File file) { PrintStream out = null; try { out = new PrintStream(file); int i = 0; for (FileAndData fileData : abcData) { for (String line : fileData.lines) out.println(line); if (++i < abcData.size()) out.println(); } } catch (IOException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Failed to save file", JOptionPane.ERROR_MESSAGE); return false; } finally { if (out != null) out.close(); } return true; } private void playPause() { if (sequencer.isRunning()) sequencer.stop(); else sequencer.start(); } private void stop() { sequencer.stop(); sequencer.setPosition(0); updateButtonStates(); } private void updateButtonStates() { boolean loaded = (sequencer.getSequence() != null); playButton.setEnabled(loaded); playButton.setIcon(sequencer.isRunning() ? pauseIcon : playIcon); playButton.setDisabledIcon(sequencer.isRunning() ? pauseIconDisabled : playIconDisabled); stopButton.setEnabled(loaded && (sequencer.isRunning() || sequencer.getPosition() != 0)); } private class WaitDialog extends JDialog { public WaitDialog(JFrame owner, File saveFile) { super(owner, APP_NAME, false); JPanel waitContent = new JPanel(new BorderLayout(5, 5)); setContentPane(waitContent); waitContent.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); waitContent.add(new JLabel("Saving " + saveFile.getName() + ". Please wait..."), BorderLayout.CENTER); JProgressBar waitProgress = new JProgressBar(); waitProgress.setIndeterminate(true); waitContent.add(waitProgress, BorderLayout.SOUTH); pack(); setLocation(getOwner().getX() + (getOwner().getWidth() - getWidth()) / 2, getOwner().getY() + (getOwner().getHeight() - getHeight()) / 2); setResizable(false); setEnabled(false); setIconImages(AbcPlayer.this.getIconImages()); } } private void exportWav() { if (exportFileDialog == null) { exportFileDialog = new JFileChooser(prefs.get("exportFileDialog.currentDirectory", Util.getUserMusicPath() .getAbsolutePath())); File openedFile = null; if (abcData.size() > 0) openedFile = abcData.get(0).file; if (openedFile != null) { String openedName = openedFile.getName(); int dot = openedName.lastIndexOf('.'); if (dot >= 0) { openedName = openedName.substring(0, dot); } openedName += ".wav"; exportFileDialog.setSelectedFile(new File(exportFileDialog.getCurrentDirectory() + "/" + openedName)); } } exportFileDialog.setFileFilter(new ExtensionFileFilter("WAV Files", "wav")); int result = exportFileDialog.showSaveDialog(this); if (result == JFileChooser.APPROVE_OPTION) { prefs.put("exportFileDialog.currentDirectory", exportFileDialog.getCurrentDirectory().getAbsolutePath()); File saveFile = exportFileDialog.getSelectedFile(); if (saveFile.getName().indexOf('.') < 0) { saveFile = new File(saveFile.getParent() + "/" + saveFile.getName() + ".wav"); exportFileDialog.setSelectedFile(saveFile); } JDialog waitFrame = new WaitDialog(this, saveFile); waitFrame.setVisible(true); new Thread(new ExportWavTask(sequencer.getSequence(), saveFile, waitFrame)).start(); } } private class ExportWavTask implements Runnable { private Sequence sequence; private File file; private JDialog waitFrame; public ExportWavTask(Sequence sequence, File file, JDialog waitFrame) { this.sequence = sequence; this.file = file; this.waitFrame = waitFrame; } @Override public void run() { isExporting = true; Exception error = null; try { FileOutputStream fos = new FileOutputStream(file); try { MidiToWav.render(sequence, fos); } finally { fos.close(); } } catch (Exception e) { error = e; } finally { isExporting = false; SwingUtilities.invokeLater(new ExportWavFinishedTask(error, waitFrame)); } } } private class ExportWavFinishedTask implements Runnable { private Exception error; private JDialog waitFrame; public ExportWavFinishedTask(Exception error, JDialog waitFrame) { this.error = error; this.waitFrame = waitFrame; } @Override public void run() { if (error != null) { JOptionPane.showMessageDialog(AbcPlayer.this, error.getMessage(), "Error saving WAV file", JOptionPane.ERROR_MESSAGE); } waitFrame.setVisible(false); } } // Cached result of isLame() private static File notLameExe = null; private boolean isLame(File lameExe) { if (!lameExe.exists() || lameExe.equals(notLameExe)) return false; LameChecker checker = new LameChecker(lameExe); checker.start(); try { // Wait up to 3 seconds for the program to respond checker.join(3000); } catch (InterruptedException e) { } if (checker.isAlive()) checker.process.destroy(); if (!checker.isLame) { notLameExe = lameExe; return false; } return true; } private static class LameChecker extends Thread { private boolean isLame = false; private File lameExe; private Process process; public LameChecker(File lameExe) { this.lameExe = lameExe; } @Override public void run() { try { process = Runtime.getRuntime().exec(Util.quote(lameExe.getAbsolutePath()) + " -?"); BufferedReader rdr = new BufferedReader(new InputStreamReader(process.getErrorStream())); String line; while ((line = rdr.readLine()) != null) { if (line.contains("LAME")) { isLame = true; break; } } } catch (IOException e) { } } } private void exportMp3() { File openedFile = null; if (abcData.size() > 0) openedFile = abcData.get(0).file; Preferences mp3Prefs = prefs.node("mp3"); File lameExe = new File(mp3Prefs.get("lameExe", "./lame.exe")); if (!lameExe.exists()) { outerLoop: for (File dir : new File(".").listFiles()) { if (dir.isDirectory()) { for (File file : dir.listFiles()) { if (file.getName().toLowerCase().equals("lame.exe")) { lameExe = file; break outerLoop; } } } } } JLabel hyperlink = new JLabel("<html><a href='" + LAME_URL + "'>" + LAME_URL + "</a></html>"); hyperlink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); hyperlink.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1 && e.getButton() == MouseEvent.BUTTON1) { Util.openURL(LAME_URL); } } }); boolean overrideAndUseExe = false; for (int i = 0; (!overrideAndUseExe && !isLame(lameExe)) || !lameExe.exists(); i++) { if (i > 0) { JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().equals("lame.exe"); } @Override public String getDescription() { return "lame.exe"; } }); fc.setSelectedFile(lameExe); int result = fc.showOpenDialog(this); if (result == JFileChooser.ERROR_OPTION) continue; // Try again else if (result != JFileChooser.APPROVE_OPTION) return; lameExe = fc.getSelectedFile(); } if (!lameExe.exists()) { Object message; int icon; if (i == 0) { message = new Object[] { "Exporting to MP3 requires LAME, a free MP3 encoder.\n" + "To download LAME, visit: ", hyperlink, "\nAfter you download and unzip it, click OK to locate lame.exe", }; icon = JOptionPane.INFORMATION_MESSAGE; } else { message = "File does not exist:\n" + lameExe.getAbsolutePath(); icon = JOptionPane.ERROR_MESSAGE; } int result = JOptionPane.showConfirmDialog(this, message, "Export to MP3 requires LAME", JOptionPane.OK_CANCEL_OPTION, icon); if (result != JOptionPane.OK_OPTION) return; } else if (!isLame(lameExe)) { Object[] message = new Object[] { "The MP3 converter you selected \"" + lameExe.getName() + "\" doesn't appear to be LAME.\n" + "You can download LAME from: ", hyperlink, "\nWould you like to use \"" + lameExe.getName() + "\" anyways?\n" + "If you choose No, you'll be prompted to locate lame.exe" }; int result = JOptionPane.showConfirmDialog(this, message, "Export to MP3 requires LAME", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (result == JOptionPane.YES_OPTION) overrideAndUseExe = true; else if (result == JOptionPane.NO_OPTION) continue; // Try again else return; } mp3Prefs.put("lameExe", lameExe.getAbsolutePath()); } ExportMp3Dialog mp3Dialog = new ExportMp3Dialog(this, lameExe, mp3Prefs, openedFile, abcInfo.getTitle(), abcInfo.getComposer()); mp3Dialog.setIconImages(AbcPlayer.this.getIconImages()); mp3Dialog.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ExportMp3Dialog dialog = (ExportMp3Dialog) e.getSource(); JDialog waitFrame = new WaitDialog(AbcPlayer.this, dialog.getSaveFile()); waitFrame.setVisible(true); new Thread(new ExportMp3Task(sequencer.getSequence(), dialog, waitFrame)).start(); } }); mp3Dialog.setVisible(true); } private class ExportMp3Task implements Runnable { private Sequence sequence; private ExportMp3Dialog mp3Dialog; private JDialog waitFrame; public ExportMp3Task(Sequence sequence, ExportMp3Dialog mp3Dialog, JDialog waitFrame) { this.sequence = sequence; this.mp3Dialog = mp3Dialog; this.waitFrame = waitFrame; } @Override public void run() { isExporting = true; Exception error = null; String lameExeSav = null; Preferences mp3Prefs = mp3Dialog.getPreferencesNode(); try { lameExeSav = mp3Prefs.get("lameExe", null); mp3Prefs.put("lameExe", ""); File wavFile = File.createTempFile("AbcPlayer-", ".wav"); FileOutputStream fos = new FileOutputStream(wavFile); try { MidiToWav.render(sequence, fos); fos.close(); Process p = Runtime.getRuntime().exec(mp3Dialog.getCommandLine(wavFile)); if (p.waitFor() != 0) throw new Exception("LAME failed"); } finally { fos.close(); wavFile.delete(); } } catch (Exception e) { error = e; } finally { if (lameExeSav != null) { mp3Prefs.put("lameExe", lameExeSav); } isExporting = false; SwingUtilities.invokeLater(new ExportMp3FinishedTask(error, waitFrame)); } } } private class ExportMp3FinishedTask implements Runnable { private Exception error; private JDialog waitFrame; public ExportMp3FinishedTask(Exception error, JDialog waitFrame) { this.error = error; this.waitFrame = waitFrame; } @Override public void run() { if (error != null) { JOptionPane.showMessageDialog(AbcPlayer.this, error.getMessage(), "Error saving MP3 file", JOptionPane.ERROR_MESSAGE); } waitFrame.setVisible(false); } } private void refreshSequence() { long position = sequencer.getPosition(); Sequence song; try { AbcToMidi.Params params = new AbcToMidi.Params(abcData); params.useLotroInstruments = useLotroInstruments; params.instrumentOverrideMap = instrumentOverrideMap; params.abcInfo = abcInfo; params.enableLotroErrors = false; params.stereo = stereoMenuItem.isSelected(); song = AbcToMidi.convert(params); } catch (ParseException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Error changing instrument", JOptionPane.ERROR_MESSAGE); return; } try { boolean running = sequencer.isRunning(); sequencer.reset(false); sequencer.setSequence(song); sequencer.setPosition(position); sequencer.setRunning(running); } catch (InvalidMidiDataException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "MIDI error", JOptionPane.ERROR_MESSAGE); return; } } }
mit
Nylle/JavaFixture
src/main/java/com/github/nylle/javafixture/specimen/TimeSpecimen.java
3642
package com.github.nylle.javafixture.specimen; import com.github.nylle.javafixture.Context; import com.github.nylle.javafixture.CustomizationContext; import com.github.nylle.javafixture.ISpecimen; import com.github.nylle.javafixture.SpecimenException; import com.github.nylle.javafixture.SpecimenType; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.time.Clock; import java.time.Duration; import java.time.LocalDateTime; import java.time.MonthDay; import java.time.Period; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.chrono.JapaneseEra; import java.time.temporal.Temporal; import java.util.Random; import static com.github.nylle.javafixture.CustomizationContext.noContext; public class TimeSpecimen<T> implements ISpecimen<T> { private final SpecimenType<T> type; private final Random random; private final Context context; public TimeSpecimen(final SpecimenType<T> type, final Context context) { if (type == null) { throw new IllegalArgumentException("type: null"); } if (!type.isTimeType()) { throw new IllegalArgumentException("type: " + type.getName()); } if (context == null) { throw new IllegalArgumentException("context: null"); } this.type = type; this.random = new Random(); this.context = context; } @Override public T create(Annotation[] annotations) { return create(noContext(), annotations); } @Override public T create(final CustomizationContext customizationContext, Annotation[] annotations) { if (Temporal.class.isAssignableFrom(type.asClass())) { try { Method now = type.asClass().getMethod("now", Clock.class); return context.preDefined(type, (T) now.invoke(null, context.getConfiguration().getClock())); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new SpecimenException("Unsupported type: " + type.asClass()); } } if (type.asClass().equals(java.util.Date.class)) { return context.preDefined(type, (T) java.sql.Timestamp.valueOf(LocalDateTime.now(context.getConfiguration().getClock()))); } if (type.asClass().equals(java.sql.Date.class)) { return context.preDefined(type, (T) java.sql.Date.valueOf(LocalDateTime.now(context.getConfiguration().getClock()).toLocalDate())); } if (type.asClass().equals(MonthDay.class)) { return context.preDefined(type, (T) MonthDay.now(context.getConfiguration().getClock())); } if (type.asClass().equals(JapaneseEra.class)) { return context.preDefined(type, (T) JapaneseEra.values()[random.nextInt(JapaneseEra.values().length)]); } if (type.asClass().equals(ZoneOffset.class)) { return context.preDefined(type, (T) ZoneOffset.ofHours(new Random().nextInt(19))); } if (type.asClass().equals(Duration.class)) { return context.preDefined(type, (T) Duration.ofDays(random.nextInt())); } if (type.asClass().equals(Period.class)) { return context.preDefined(type, (T) Period.ofDays(random.nextInt())); } if (type.asClass().equals(ZoneId.class)) { return context.preDefined(type, (T) ZoneId.of(ZoneId.getAvailableZoneIds().iterator().next())); } throw new SpecimenException("Unsupported type: " + type.asClass()); } }
mit
SpongePowered/Sponge
src/mixins/java/org/spongepowered/common/mixin/api/minecraft/util/DamageSourceMixin_API.java
3569
/* * 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.common.mixin.api.minecraft.util; import org.spongepowered.api.event.cause.entity.damage.DamageType; import org.spongepowered.api.event.cause.entity.damage.source.DamageSource; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Interface.Remap; import org.spongepowered.asm.mixin.Intrinsic; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.bridge.world.damagesource.DamageSourceBridge; @Mixin(value = net.minecraft.world.damagesource.DamageSource.class) @Implements(@Interface(iface = DamageSource.class, prefix = "damageSource$", remap = Remap.NONE)) public abstract class DamageSourceMixin_API implements DamageSource { // @formatter:off @Shadow public abstract boolean shadow$isBypassArmor(); @Shadow public abstract boolean shadow$isBypassInvul(); @Shadow public abstract boolean shadow$isBypassMagic(); @Shadow public abstract boolean shadow$isMagic(); @Shadow public abstract float shadow$getFoodExhaustion(); @Shadow public abstract boolean shadow$scalesWithDifficulty(); @Shadow public abstract boolean shadow$isExplosion(); @Shadow public abstract boolean shadow$isFire(); @Shadow public abstract String shadow$getMsgId(); // @formatter:on @Override public boolean isExplosive() { return this.shadow$isExplosion(); } @Intrinsic public boolean damageSource$isMagic() { return this.shadow$isMagic(); } @Intrinsic public boolean damageSource$isFire() { return this.shadow$isFire(); } @Override public boolean doesAffectCreative() { return this.shadow$isBypassInvul(); } @Override public boolean isAbsolute() { return this.shadow$isBypassMagic(); } @Override public boolean isBypassingArmor() { return this.shadow$isBypassArmor(); } @Override public boolean isScaledByDifficulty() { return this.shadow$scalesWithDifficulty(); } @Override public double exhaustion() { return this.shadow$getFoodExhaustion(); } @Override public DamageType type() { return ((DamageSourceBridge) this).bridge$getDamageType(); } }
mit
branscha/lib-jsontools
src/test/java/com/sdicons/json/mapper/helper/impl/MapMapperTest.java
3349
/******************************************************************************* * Copyright (c) 2006-2013 Bruno Ranschaert * Released under the MIT License: http://opensource.org/licenses/MIT * Library "jsontools" ******************************************************************************/ package com.sdicons.json.mapper.helper.impl; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.sdicons.json.mapper.JSONMapper; import com.sdicons.json.mapper.MapperException; import com.sdicons.json.mapper.helper.ClassMapper; import com.sdicons.json.mapper.helper.MapMapper; import com.sdicons.json.mapper.helper.StringMapper; import com.sdicons.json.model.JSONObject; import com.sdicons.json.model.JSONString; import com.sdicons.json.model.JSONValue; public class MapMapperTest { private MapMapper helper; private JSONMapper mapper; @Before public void init() { helper = new MapMapper(); mapper = new JSONMapper(new ClassMapper[]{}); } @SuppressWarnings("rawtypes") @Test public void hashMaps() throws MapperException { mapper.addHelper(new StringMapper()); Map<String, String> map = new HashMap<String, String>(); map.put("uno" , "one"); map.put("duo", "two" ); map.put("tres", "three"); JSONValue json = helper.toJSON(mapper, map); Assert.assertNotNull(json); Assert.assertThat(json, is(instanceOf(JSONObject.class))); // // Back to HashMap. Object back = helper.toJava(mapper, json, HashMap.class); Assert.assertNotNull(back); Assert.assertThat(back, is(instanceOf(HashMap.class))); Assert.assertTrue(((Map)back).containsKey("uno")); Assert.assertEquals("one", ((Map)back).get("uno" )); // // Try a TreeMap. back = helper.toJava(mapper, json, TreeMap.class); Assert.assertNotNull(back); Assert.assertThat(back, is(instanceOf(TreeMap.class))); Assert.assertTrue(((Map)back).containsKey("uno")); Assert.assertEquals("one", ((Map)back).get("uno" )); // // Try to ask for an unmodifiable map that cannot be instantiated. // The helper should create some other map. back = helper.toJava(mapper, json, Collections.EMPTY_MAP.getClass()); Assert.assertNotNull(back); Assert.assertTrue(((Map)back).containsKey("uno")); Assert.assertEquals("one", ((Map)back).get("uno" )); } @Test(expected=MapperException.class) public void unhappy() throws MapperException { // The input JSON is not an object. The mapper cannot do this. helper.toJava(mapper, new JSONString("ai"), HashMap.class); } @Test(expected=MapperException.class) public void unhappy2() throws MapperException { // The requested class is not a map. helper.toJava(mapper, new JSONObject(), Integer.class); } @Test(expected=MapperException.class) public void unhappy3() throws MapperException { // You cannot map a string to a map. helper.toJSON(mapper, 3); } }
mit
xm-repo/java-web-app
src/main/java/cmc/ps/dao/BusinessDAO.java
403
package cmc.ps.dao; import cmc.ps.model.Business; import com.googlecode.genericdao.dao.hibernate.GenericDAO; /* * Interface for the Business DAO. This is created very simply by extending * GenericDAO and specifying the type for the entity class (Business) and the * type of its identifier (Integer). */ public interface BusinessDAO extends GenericDAO<Business, Integer> { }
mit
Yonaba/Java-samples
Algorithms/src/Equation2ndDeg.java
2170
/** Copyright (c) 2012 Roland Yonaba 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. **/ // Solves linear equations (ax^2+bx+c=0) import java.util.Scanner; public class Equation2ndDeg { static void resol(double a,double b, double c) { double d,x1,x2; if (a==0) { if (b==0) { if (c==0) System.out.println("R is solution."); else System.out.println("No solution"); } else { x1 = c/b; System.out.println("x = "+x1); } } else { d = Math.pow(b,2)-4*a*c; if (d==0) { x1 = -b/(2*a); System.out.println("Real double root x0 = "+x1); } else { x1 = (-b-Math.sqrt(d))/(2*a); x2 = (-b+Math.sqrt(d))/(2*a); System.out.println("x1 = "+x1+"\nx2 = "+x2); } } System.out.println(".........Program Closed........."); } public static void main(String[] args) { double a,b,c; Scanner sc = new Scanner(System.in); System.out.println("----Equation solver (ax^2+bx+c=0)-----"); System.out.println("Enter a, b, and c coefficient: "); a=sc.nextDouble(); b=sc.nextDouble(); c=sc.nextDouble(); System.out.println("Equation: "+a+"x^2 + "+b+" x + "+c); resol(a,b,c); } }
mit
localstorm/wordpress-to-livejournal-bridge
src/org/katkov/lj/http/Extractor.java
1727
/* * Copyright (c) 2006, Igor Katkov * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * The name of the author may not be used may not be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.katkov.lj.http; import org.htmlparser.util.ParserException; interface Extractor<E> { public E extract(String content) throws ParserException; }
mit
HbbTV-Association/ReferenceApplication
tools/java/src/org/hbbtv/refapp/LogWriter.java
1149
package org.hbbtv.refapp; import java.io.*; /** * Simple logging file writer. */ public class LogWriter { private FileOutputStream fos; private byte[] NLb; public LogWriter() {} /** * Open a logging file or use STDOUT. * @param file output file or NULL to use System.out. * @throws IOException */ public void openFile(File file) throws IOException { String NL=System.getProperty("line.separator", "\r\n"); NLb = NL.getBytes("ISO-8859-1"); if (file==null) { close(); } else { fos = new FileOutputStream(file); fos.write( new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF } ); // UTF8 BOM marker } } public void close() { try { if (fos!=null) fos.close(); fos=null; } catch (Exception ex) { } } public void println(String value) throws IOException { if (fos==null) { System.out.println(value); } else { fos.write(value.getBytes("UTF-8")); fos.write(NLb); } } public void print(String value) throws IOException { if (fos==null) { System.out.print(value); } else { fos.write(value.getBytes("UTF-8")); } } }
mit
emacslisp/Java
TomcatReading/src/org/apache/tomcat/InstanceManager.java
2107
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat; import java.lang.reflect.InvocationTargetException; import javax.naming.NamingException; public interface InstanceManager { Object newInstance(Class<?> clazz) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, IllegalArgumentException, NoSuchMethodException, SecurityException; Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException, IllegalArgumentException, NoSuchMethodException, SecurityException; Object newInstance(String fqcn, ClassLoader classLoader) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException, IllegalArgumentException, NoSuchMethodException, SecurityException; void newInstance(Object o) throws IllegalAccessException, InvocationTargetException, NamingException; void destroyInstance(Object o) throws IllegalAccessException, InvocationTargetException; /** * Called by the component using the InstanceManager periodically to perform * any regular maintenance that might be required. By default, this method * is a NO-OP. */ default void backgroundProcess() { // NO-OP by default } }
mit
xiongmaoshouzha/test
jeecg-p3-biz-qywx/src/main/java/com/jeecg/qywx/core/util/WeixinUtil.java
2142
package com.jeecg.qywx.core.util; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.ResourceBundle; import com.jeecg.qywx.base.entity.QywxGzuserinfo; import com.jeecg.qywx.core.weixin.model.resp.Article; import com.jeecg.qywx.core.weixin.model.resp.NewsMessageResp; import com.jeecg.qywx.core.weixin.model.resp.TextMessageResp; import com.jeecg.qywx.sucai.entity.QywxNewsitem; import com.jeecg.qywx.sucai.entity.QywxTexttemplate; /** * 公众平台通用接口工具类 * * @author zhoujf * @date 2016-04-06 */ public class WeixinUtil { // private static final ResourceBundle bundle = ResourceBundle.getBundle("weixin"); public static String wrapperTextMessage(QywxTexttemplate textTemplate,String fromUserName,String toUserName){ String content = textTemplate.getTemplateContent(); TextMessageResp textMessage = new TextMessageResp(); textMessage.setToUserName(fromUserName); textMessage.setFromUserName(toUserName); textMessage.setCreateTime(new Date().getTime()); textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT); textMessage.setContent(content); return MessageUtil.textMessageToXml(textMessage); } public static String wrapperNewsMessage(List<QywxNewsitem> newsList,String fromUserName,String toUserName,String accountId,String agentid){ List<Article> articleList = new ArrayList<Article>(); for(QywxNewsitem news:newsList){ Article article = new Article(); article.setTitle(news.getTitle()); article.setPicUrl(QywxResourceUtil.getDomain()+"/"+news.getImagePath()); article.setUrl(QywxResourceUtil.getDomain()+"/qywx/qywxNewsitem.do?goContent&id="+news.getId()); articleList.add(article); } NewsMessageResp newsResp = new NewsMessageResp(); newsResp.setCreateTime(new Date().getTime()); newsResp.setFromUserName(toUserName); newsResp.setToUserName(fromUserName); newsResp.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS); newsResp.setArticleCount(newsList.size()); newsResp.setArticles(articleList); return MessageUtil.newsMessageToXml(newsResp); } }
mit
SBPrime/MCPainter
MCPainter/src/main/java/org/primesoft/mcpainter/drawing/statue/StatueDescription.java
5120
/* * The MIT License * * Copyright 2013 SBPrime. * * 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.primesoft.mcpainter.drawing.statue; import java.util.List; import org.primesoft.mcpainter.drawing.blocks.BlockHelper; import org.primesoft.mcpainter.drawing.RawImage; import org.primesoft.mcpainter.utils.Pair; import org.primesoft.mcpainter.texture.TextureManager; import org.primesoft.mcpainter.utils.Vector; import org.bukkit.configuration.ConfigurationSection; /** * * @author SBPrime */ public class StatueDescription { private final Vector m_size; private final int[] m_textureRes; private final StatueBlock[] m_blocks; private final StatueFace[][] m_faces; private final int[] m_columns; private final int[] m_rows; private final String m_permissionNode; private final String m_name; private final RawImage[][] m_textures; public StatueDescription(TextureManager textureManager, ConfigurationSection bp) { m_name = bp.getName(); m_permissionNode = bp.getString("Permission"); m_size = BlockHelper.parseSize(bp.getIntegerList("Size")); int res = bp.getInt("TextureRes", -1); int[] mRes = BlockHelper.parseIntListEntry(bp.getIntegerList("TexturesRes")); if (res != -1) { m_textureRes = new int[]{res}; } else if (mRes != null && mRes.length > 0) { m_textureRes = mRes; } else { m_textureRes = new int[]{16}; } int variants = bp.getInt("Variants", -1); if (variants > 1) { m_textures = new RawImage[variants][]; for (int i = 0; i < variants; i++) { m_textures[i] = getTextures(bp, textureManager, i + 1); } } else { m_textures = new RawImage[][]{getTextures(bp, textureManager, -1)}; } m_columns = BlockHelper.parseIntListEntry(bp.getIntegerList("Columns")); m_rows = BlockHelper.parseIntListEntry(bp.getIntegerList("Rows")); Pair<StatueBlock, StatueFace[]>[] parts = BlockHelper.parseBlocks(bp.getConfigurationSection("Parts")); m_blocks = new StatueBlock[parts.length]; m_faces = new StatueFace[parts.length][]; for (int i = 0; i < parts.length; i++) { Pair<StatueBlock, StatueFace[]> part = parts[i]; m_blocks[i] = part.getFirst(); m_faces[i] = part.getSecond(); } } /** * Parse texture entry * * @param bp * @param textureManager * @param id * @return */ private static RawImage[] getTextures(ConfigurationSection bp, TextureManager textureManager, int id) { String simple; String multiple; if (id > 0) { simple = "Texture_" + id; multiple = "Textures_" + id; } else { simple = "Texture"; multiple = "Textures"; } List<String> textures = bp.getStringList(multiple); String texture = bp.getString(simple); RawImage[] tex = null; if (textures != null && textures.size() > 0) { tex = BlockHelper.parseTextures(textureManager, textures); } if (texture != null) { tex = new RawImage[]{BlockHelper.parseTexture(textureManager, texture)}; } return tex; } public RawImage[] getTextures(int id) { if (id == 0) { id = 1; } id = (id + m_textures.length - 1) % m_textures.length; return m_textures[id]; } public Vector getSize() { return m_size; } public int[] getTextureRes() { return m_textureRes; } public StatueBlock[] getBlocks() { return m_blocks; } public StatueFace[][] getFaces() { return m_faces; } public int[] getColumns() { return m_columns; } public int[] getRows() { return m_rows; } public String getName() { return m_name; } public String getPermission() { return m_permissionNode; } }
mit
kotovdv/RichValidation
core/src/main/java/com/jquartz/rich/validation/core/util/PrimitiveToWrapperConverter.java
1059
package com.jquartz.rich.validation.core.util; import com.google.common.collect.ImmutableMap; import com.jquartz.rich.validation.core.util.exception.NoWrapperForPrimitiveTypeFoundException; /** * @author Dmitriy Kotov */ public class PrimitiveToWrapperConverter { private final ImmutableMap<Class<?>, Class<?>> primitiveToWrapperMapping = ImmutableMap.<Class<?>, Class<?>>builder() .put(boolean.class, Boolean.class) .put(char.class, Character.class) .put(byte.class, Byte.class) .put(short.class, Short.class) .put(int.class, Integer.class) .put(float.class, Float.class) .put(long.class, Long.class) .put(double.class, Double.class) .build(); public Class<?> getWrapperFor(Class<?> primitiveType) { Class<?> wrapperType = primitiveToWrapperMapping.get(primitiveType); if (wrapperType == null) { throw new NoWrapperForPrimitiveTypeFoundException(primitiveType); } return wrapperType; } }
mit
przodownikR1/concurrency_java_kata
src/main/java/pl/java/scalatech/notification/MessageEvent.java
422
package pl.java.scalatech.notification; import lombok.Getter; import lombok.ToString; import org.springframework.context.ApplicationEvent; @ToString public class MessageEvent extends ApplicationEvent { private static final long serialVersionUID = 212813971454653731L; @Getter private String msg; public MessageEvent(Object source, String msg) { super(source); this.msg = msg; } }
mit
m0ep/master-thesis
source/apis/rdf2go/rdf2go-sioc-services-auth/src/main/java/de/m0ep/sioc/services/auth/Username.java
7839
/* * generated by http://RDFReactor.semweb4j.org ($Id: CodeGenerator.java 1895 2013-02-09 17:39:56Z max.at.xam.de@gmail.com $) on 8/8/13 12:01 PM */ package de.m0ep.sioc.services.auth; import org.ontoware.aifbcommons.collection.ClosableIterator; import org.ontoware.rdf2go.exception.ModelRuntimeException; import org.ontoware.rdf2go.model.Model; import org.ontoware.rdf2go.model.node.BlankNode; import org.ontoware.rdf2go.model.node.Resource; import org.ontoware.rdf2go.model.node.URI; import org.ontoware.rdf2go.model.node.impl.URIImpl; import org.ontoware.rdfreactor.runtime.Base; /** * * This class was generated by <a href="http://RDFReactor.semweb4j.org">RDFReactor</a> on 8/8/13 * 12:01 PM */ public class Username extends Credentials { private static final long serialVersionUID = -3432936095270094815L; /** http://purl.oclc.org/NET/WebApiAuthentication#Username */ public static final URI RDFS_CLASS = new URIImpl( "http://purl.oclc.org/NET/WebApiAuthentication#Username", false ); /** * All property-URIs with this class as domain. All properties of all super-classes are also * available. */ public static final URI[] MANAGED_URIS = { }; // protected constructors needed for inheritance /** * Returns a Java wrapper over an RDF object, identified by URI. Creating two wrappers for the * same instanceURI is legal. * * @param model * RDF2GO Model implementation, see http://rdf2go.semweb4j.org * @param classURI * URI of RDFS class * @param instanceIdentifier * Resource that identifies this instance * @param write * if true, the statement (this, rdf:type, TYPE) is written to the model * * [Generated from RDFReactor template rule #c1] */ protected Username( Model model, URI classURI, Resource instanceIdentifier, boolean write ) { super( model, classURI, instanceIdentifier, write ); } // public constructors /** * Returns a Java wrapper over an RDF object, identified by URI. Creating two wrappers for the * same instanceURI is legal. * * @param model * RDF2GO Model implementation, see http://rdf2go.ontoware.org * @param instanceIdentifier * an RDF2Go Resource identifying this instance * @param write * if true, the statement (this, rdf:type, TYPE) is written to the model * * [Generated from RDFReactor template rule #c2] */ public Username( Model model, Resource instanceIdentifier, boolean write ) { super( model, RDFS_CLASS, instanceIdentifier, write ); } /** * Returns a Java wrapper over an RDF object, identified by a URI, given as a String. Creating * two wrappers for the same URI is legal. * * @param model * RDF2GO Model implementation, see http://rdf2go.ontoware.org * @param uriString * a URI given as a String * @param write * if true, the statement (this, rdf:type, TYPE) is written to the model * @throws ModelRuntimeException * if URI syntax is wrong * * [Generated from RDFReactor template rule #c7] */ public Username( Model model, String uriString, boolean write ) throws ModelRuntimeException { super( model, RDFS_CLASS, new URIImpl( uriString, false ), write ); } /** * Returns a Java wrapper over an RDF object, identified by a blank node. Creating two wrappers * for the same blank node is legal. * * @param model * RDF2GO Model implementation, see http://rdf2go.ontoware.org * @param bnode * BlankNode of this instance * @param write * if true, the statement (this, rdf:type, TYPE) is written to the model * * [Generated from RDFReactor template rule #c8] */ public Username( Model model, BlankNode bnode, boolean write ) { super( model, RDFS_CLASS, bnode, write ); } /** * Returns a Java wrapper over an RDF object, identified by a randomly generated URI. Creating * two wrappers results in different URIs. * * @param model * RDF2GO Model implementation, see http://rdf2go.ontoware.org * @param write * if true, the statement (this, rdf:type, TYPE) is written to the model * * [Generated from RDFReactor template rule #c9] */ public Username( Model model, boolean write ) { super( model, RDFS_CLASS, model.newRandomUniqueURI(), write ); } /////////////////////////////////////////////////////////////////// // typing /** * Return an existing instance of this class in the model. No statements are written. * * @param model * an RDF2Go model * @param instanceResource * an RDF2Go resource * @return an instance of Username or null if none existst * * [Generated from RDFReactor template rule #class0] */ public static Username getInstance( Model model, Resource instanceResource ) { return Base.getInstance( model, instanceResource, Username.class ); } /** * Create a new instance of this class in the model. That is, create the statement * (instanceResource, RDF.type, http://purl.oclc.org/NET/WebApiAuthentication#Username). * * @param model * an RDF2Go model * @param instanceResource * an RDF2Go resource * * [Generated from RDFReactor template rule #class1] */ public static void createInstance( Model model, Resource instanceResource ) { Base.createInstance( model, RDFS_CLASS, instanceResource ); } /** * @param model * an RDF2Go model * @param instanceResource * an RDF2Go resource * @return true if instanceResource is an instance of this class in the model * * [Generated from RDFReactor template rule #class2] */ public static boolean hasInstance( Model model, Resource instanceResource ) { return Base.hasInstance( model, RDFS_CLASS, instanceResource ); } /** * @param model * an RDF2Go model * @return all instances of this class in Model 'model' as RDF resources * * [Generated from RDFReactor template rule #class3] */ public static ClosableIterator<Resource> getAllInstances( Model model ) { return Base.getAllInstances( model, RDFS_CLASS, Resource.class ); } /** * Remove triple {@code (this, rdf:type, Username)} from this instance. Other triples are not * affected. To delete more, use deleteAllProperties * * @param model * an RDF2Go model * @param instanceResource * an RDF2Go resource * * [Generated from RDFReactor template rule #class4] */ public static void deleteInstance( Model model, Resource instanceResource ) { Base.deleteInstance( model, RDFS_CLASS, instanceResource ); } /** * Delete all triples {@code (this, *, *)}, i.e. including {@code rdf:type}. * * @param model * an RDF2Go model * @param instanceResource * an RDF2Go resource * * [Generated from RDFReactor template rule #class5] */ public static void deleteAllProperties( Model model, Resource instanceResource ) { Base.deleteAllProperties( model, instanceResource ); } /////////////////////////////////////////////////////////////////// // property access methods }
mit
Azure/azure-sdk-for-java
sdk/apimanagement/azure-resourcemanager-apimanagement/src/main/java/com/azure/resourcemanager/apimanagement/implementation/GatewaysImpl.java
13044
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.apimanagement.implementation; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.apimanagement.fluent.GatewaysClient; import com.azure.resourcemanager.apimanagement.fluent.models.GatewayContractInner; import com.azure.resourcemanager.apimanagement.fluent.models.GatewayKeysContractInner; import com.azure.resourcemanager.apimanagement.fluent.models.GatewayTokenContractInner; import com.azure.resourcemanager.apimanagement.models.GatewayContract; import com.azure.resourcemanager.apimanagement.models.GatewayKeyRegenerationRequestContract; import com.azure.resourcemanager.apimanagement.models.GatewayKeysContract; import com.azure.resourcemanager.apimanagement.models.GatewayTokenContract; import com.azure.resourcemanager.apimanagement.models.GatewayTokenRequestContract; import com.azure.resourcemanager.apimanagement.models.Gateways; import com.azure.resourcemanager.apimanagement.models.GatewaysGetEntityTagResponse; import com.azure.resourcemanager.apimanagement.models.GatewaysGetResponse; import com.azure.resourcemanager.apimanagement.models.GatewaysListKeysResponse; import com.fasterxml.jackson.annotation.JsonIgnore; public final class GatewaysImpl implements Gateways { @JsonIgnore private final ClientLogger logger = new ClientLogger(GatewaysImpl.class); private final GatewaysClient innerClient; private final com.azure.resourcemanager.apimanagement.ApiManagementManager serviceManager; public GatewaysImpl( GatewaysClient innerClient, com.azure.resourcemanager.apimanagement.ApiManagementManager serviceManager) { this.innerClient = innerClient; this.serviceManager = serviceManager; } public PagedIterable<GatewayContract> listByService(String resourceGroupName, String serviceName) { PagedIterable<GatewayContractInner> inner = this.serviceClient().listByService(resourceGroupName, serviceName); return Utils.mapPage(inner, inner1 -> new GatewayContractImpl(inner1, this.manager())); } public PagedIterable<GatewayContract> listByService( String resourceGroupName, String serviceName, String filter, Integer top, Integer skip, Context context) { PagedIterable<GatewayContractInner> inner = this.serviceClient().listByService(resourceGroupName, serviceName, filter, top, skip, context); return Utils.mapPage(inner, inner1 -> new GatewayContractImpl(inner1, this.manager())); } public void getEntityTag(String resourceGroupName, String serviceName, String gatewayId) { this.serviceClient().getEntityTag(resourceGroupName, serviceName, gatewayId); } public GatewaysGetEntityTagResponse getEntityTagWithResponse( String resourceGroupName, String serviceName, String gatewayId, Context context) { return this.serviceClient().getEntityTagWithResponse(resourceGroupName, serviceName, gatewayId, context); } public GatewayContract get(String resourceGroupName, String serviceName, String gatewayId) { GatewayContractInner inner = this.serviceClient().get(resourceGroupName, serviceName, gatewayId); if (inner != null) { return new GatewayContractImpl(inner, this.manager()); } else { return null; } } public Response<GatewayContract> getWithResponse( String resourceGroupName, String serviceName, String gatewayId, Context context) { GatewaysGetResponse inner = this.serviceClient().getWithResponse(resourceGroupName, serviceName, gatewayId, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new GatewayContractImpl(inner.getValue(), this.manager())); } else { return null; } } public void delete(String resourceGroupName, String serviceName, String gatewayId, String ifMatch) { this.serviceClient().delete(resourceGroupName, serviceName, gatewayId, ifMatch); } public Response<Void> deleteWithResponse( String resourceGroupName, String serviceName, String gatewayId, String ifMatch, Context context) { return this.serviceClient().deleteWithResponse(resourceGroupName, serviceName, gatewayId, ifMatch, context); } public GatewayKeysContract listKeys(String resourceGroupName, String serviceName, String gatewayId) { GatewayKeysContractInner inner = this.serviceClient().listKeys(resourceGroupName, serviceName, gatewayId); if (inner != null) { return new GatewayKeysContractImpl(inner, this.manager()); } else { return null; } } public Response<GatewayKeysContract> listKeysWithResponse( String resourceGroupName, String serviceName, String gatewayId, Context context) { GatewaysListKeysResponse inner = this.serviceClient().listKeysWithResponse(resourceGroupName, serviceName, gatewayId, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new GatewayKeysContractImpl(inner.getValue(), this.manager())); } else { return null; } } public void regenerateKey( String resourceGroupName, String serviceName, String gatewayId, GatewayKeyRegenerationRequestContract parameters) { this.serviceClient().regenerateKey(resourceGroupName, serviceName, gatewayId, parameters); } public Response<Void> regenerateKeyWithResponse( String resourceGroupName, String serviceName, String gatewayId, GatewayKeyRegenerationRequestContract parameters, Context context) { return this .serviceClient() .regenerateKeyWithResponse(resourceGroupName, serviceName, gatewayId, parameters, context); } public GatewayTokenContract generateToken( String resourceGroupName, String serviceName, String gatewayId, GatewayTokenRequestContract parameters) { GatewayTokenContractInner inner = this.serviceClient().generateToken(resourceGroupName, serviceName, gatewayId, parameters); if (inner != null) { return new GatewayTokenContractImpl(inner, this.manager()); } else { return null; } } public Response<GatewayTokenContract> generateTokenWithResponse( String resourceGroupName, String serviceName, String gatewayId, GatewayTokenRequestContract parameters, Context context) { Response<GatewayTokenContractInner> inner = this .serviceClient() .generateTokenWithResponse(resourceGroupName, serviceName, gatewayId, parameters, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new GatewayTokenContractImpl(inner.getValue(), this.manager())); } else { return null; } } public GatewayContract getById(String id) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); } String serviceName = Utils.getValueFromIdByName(id, "service"); if (serviceName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'service'.", id))); } String gatewayId = Utils.getValueFromIdByName(id, "gateways"); if (gatewayId == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'gateways'.", id))); } return this.getWithResponse(resourceGroupName, serviceName, gatewayId, Context.NONE).getValue(); } public Response<GatewayContract> getByIdWithResponse(String id, Context context) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); } String serviceName = Utils.getValueFromIdByName(id, "service"); if (serviceName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'service'.", id))); } String gatewayId = Utils.getValueFromIdByName(id, "gateways"); if (gatewayId == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'gateways'.", id))); } return this.getWithResponse(resourceGroupName, serviceName, gatewayId, context); } public void deleteById(String id) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); } String serviceName = Utils.getValueFromIdByName(id, "service"); if (serviceName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'service'.", id))); } String gatewayId = Utils.getValueFromIdByName(id, "gateways"); if (gatewayId == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'gateways'.", id))); } String localIfMatch = null; this.deleteWithResponse(resourceGroupName, serviceName, gatewayId, localIfMatch, Context.NONE).getValue(); } public Response<Void> deleteByIdWithResponse(String id, String ifMatch, Context context) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); } String serviceName = Utils.getValueFromIdByName(id, "service"); if (serviceName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'service'.", id))); } String gatewayId = Utils.getValueFromIdByName(id, "gateways"); if (gatewayId == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'gateways'.", id))); } return this.deleteWithResponse(resourceGroupName, serviceName, gatewayId, ifMatch, context); } private GatewaysClient serviceClient() { return this.innerClient; } private com.azure.resourcemanager.apimanagement.ApiManagementManager manager() { return this.serviceManager; } public GatewayContractImpl define(String name) { return new GatewayContractImpl(name, this.manager()); } }
mit
oixhwotl/RecursoDeAndroidProgramming
REF/AndExam4_1/src/andexam/ver4_1/c37_appwidget/AppWidgetManagerTest.java
769
package andexam.ver4_1.c37_appwidget; import andexam.ver4_1.*; import java.util.*; import android.app.*; import android.appwidget.*; import android.os.*; import android.widget.*; public class AppWidgetManagerTest extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.appwidgetmanagertest); AppWidgetManager mAWM = AppWidgetManager.getInstance(this); List<AppWidgetProviderInfo> mList = mAWM.getInstalledProviders(); String result = "count = " + mList.size() + "\n"; for (AppWidgetProviderInfo info : mList) { result += info.toString() + "\n\n"; } TextView resulttxt = (TextView)findViewById(R.id.result); resulttxt.setText(result); } }
mit
sree93/Escritoire
app/src/main/java/com/sreemenon/protean/RichEditboxFragment.java
2497
package com.sreemenon.protean; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.sreemenon.escritoire.R; /** * A simple {@link Fragment} subclass. * Use the {@link RichEditboxFragment#newInstance} factory method to * create an instance of this fragment. */ public class RichEditboxFragment extends Fragment { private static final String ARG_RICHTEXT = "RICHTEXT"; private String richText; public RichEditboxFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param richText the formatted rich text or empty strings * for a new Editbox. * @return A new instance of fragment RichEditboxFragment. */ public static RichEditboxFragment newInstance(String richText) { RichEditboxFragment fragment = new RichEditboxFragment(); Bundle args = new Bundle(); args.putString(ARG_RICHTEXT, richText); fragment.setArguments(args); return fragment; } public static RichEditboxFragment newInstance() { return newInstance(""); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { refreshArgRichtext(); } } private String refreshArgRichtext(){ richText = getArguments().getString(ARG_RICHTEXT); return richText; } private void setArgRichtext(String richText){ this.richText = richText; getArguments().putString(ARG_RICHTEXT, richText); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setText(R.string.hello_blank_fragment); return textView; } // @Override // public void onAttach(Context context) { // super.onAttach(context); // if (context instanceof OnFragmentInteractionListener) { // mListener = (OnFragmentInteractionListener) context; // } else { // throw new RuntimeException(context.toString() // + " must implement OnFragmentInteractionListener"); // } // } }
mit
monicalzn/Super-Doctor-Medical-RobotI
src/com/brackeen/javagamebook/input/InputManager.java
13673
package com.brackeen.javagamebook.input; import java.awt.*; import java.awt.event.*; import java.util.List; import java.util.ArrayList; import javax.swing.SwingUtilities; /** * The InputManager manages input of key and mouse events. * Events are mapped to GameActions. */ public class InputManager implements KeyListener, MouseListener, MouseMotionListener, MouseWheelListener { /** * An invisible cursor. */ public static final Cursor INVISIBLE_CURSOR = Toolkit.getDefaultToolkit().createCustomCursor( Toolkit.getDefaultToolkit().getImage(""), new Point(0,0), "invisible"); // mouse codes public static final int MOUSE_MOVE_LEFT = 0; public static final int MOUSE_MOVE_RIGHT = 1; public static final int MOUSE_MOVE_UP = 2; public static final int MOUSE_MOVE_DOWN = 3; public static final int MOUSE_WHEEL_UP = 4; public static final int MOUSE_WHEEL_DOWN = 5; public static final int MOUSE_BUTTON_1 = 6; public static final int MOUSE_BUTTON_2 = 7; public static final int MOUSE_BUTTON_3 = 8; private static final int NUM_MOUSE_CODES = 9; // key codes are defined in java.awt.KeyEvent. // most of the codes (except for some rare ones like // "alt graph") are less than 600. private static final int NUM_KEY_CODES = 600; private GameAction[] keyActions = new GameAction[NUM_KEY_CODES]; private GameAction[] mouseActions = new GameAction[NUM_MOUSE_CODES]; private Point mouseLocation; private Point centerLocation; private Component comp; private Robot robot; private boolean isRecentering; /** * Creates a new InputManager that listens to input from the * specified component. * @param comp Component received to create the InputManager */ public InputManager(Component comp) { this.comp = comp; mouseLocation = new Point(); centerLocation = new Point(); // register key and mouse listeners comp.addKeyListener(this); comp.addMouseListener(this); comp.addMouseMotionListener(this); comp.addMouseWheelListener(this); // allow input of the TAB key and other keys normally // used for focus traversal comp.setFocusTraversalKeysEnabled(false); } /** * Sets the cursor on this InputManager's input component. * @param cursor the cursor of the mouse */ public void setCursor(Cursor cursor) { comp.setCursor(cursor); } /** * Sets whether relative mouse mode is on or not. For * relative mouse mode, the mouse is "locked" in the center * of the screen, and only the changed in mouse movement * is measured. In normal mode, the mouse is free to move * about the screen. * @param mode receives the mode of the mouse */ public void setRelativeMouseMode(boolean mode) { if (mode == isRelativeMouseMode()) { return; } if (mode) { try { robot = new Robot(); recenterMouse(); } catch (AWTException ex) { // couldn't create robot! robot = null; } } else { robot = null; } } /** * Returns whether or not relative mouse mode is on. * @return true if the mouse mode is relative, or false if it isn't */ public boolean isRelativeMouseMode() { return (robot != null); } /** * Maps a GameAction to a specific key. The key codes are * defined in java.awt.KeyEvent. If the key already has * a GameAction mapped to it, the new GameAction overwrites * it. * @param gameAction the current GameAction * @param keyCode the current key code */ public void mapToKey(GameAction gameAction, int keyCode) { keyActions[keyCode] = gameAction; } /** * Maps a GameAction to a specific mouse action. The mouse * codes are defined herer in InputManager (MOUSE_MOVE_LEFT, * MOUSE_BUTTON_1, etc). If the mouse action already has * a GameAction mapped to it, the new GameAction overwrites * it. * @param gameAction the current GameAction * @param mouseCode the current mouse code */ public void mapToMouse(GameAction gameAction, int mouseCode) { mouseActions[mouseCode] = gameAction; } /** * Clears all mapped keys and mouse actions to this * GameAction. * @param gameAction the current GameAction */ public void clearMap(GameAction gameAction) { for (int i=0; i<keyActions.length; i++) { if (keyActions[i] == gameAction) { keyActions[i] = null; } } for (int i=0; i<mouseActions.length; i++) { if (mouseActions[i] == gameAction) { mouseActions[i] = null; } } gameAction.reset(); } /** * Gets a List of names of the keys and mouse actions mapped * to this GameAction. Each entry in the List is a String. * @param gameCode the current GameAction * @return the list of the keys and mouse actions */ public List getMaps(GameAction gameCode) { ArrayList list = new ArrayList(); for (int i=0; i<keyActions.length; i++) { if (keyActions[i] == gameCode) { list.add(getKeyName(i)); } } for (int i=0; i<mouseActions.length; i++) { if (mouseActions[i] == gameCode) { list.add(getMouseName(i)); } } return list; } /** * Resets all GameActions so they appear like they haven't * been pressed. */ public void resetAllGameActions() { for (int i=0; i<keyActions.length; i++) { if (keyActions[i] != null) { keyActions[i].reset(); } } for (int i=0; i<mouseActions.length; i++) { if (mouseActions[i] != null) { mouseActions[i].reset(); } } } /** * Gets the name of a key code. * @param keyCode the number of key code * @return the string of the key code */ public static String getKeyName(int keyCode) { return KeyEvent.getKeyText(keyCode); } /** * Gets the name of a mouse code. * @param mouseCode the number of the mouse code * @return the string of the mouse code */ public static String getMouseName(int mouseCode) { switch (mouseCode) { case MOUSE_MOVE_LEFT: return "Mouse Left"; case MOUSE_MOVE_RIGHT: return "Mouse Right"; case MOUSE_MOVE_UP: return "Mouse Up"; case MOUSE_MOVE_DOWN: return "Mouse Down"; case MOUSE_WHEEL_UP: return "Mouse Wheel Up"; case MOUSE_WHEEL_DOWN: return "Mouse Wheel Down"; case MOUSE_BUTTON_1: return "Mouse Button 1"; case MOUSE_BUTTON_2: return "Mouse Button 2"; case MOUSE_BUTTON_3: return "Mouse Button 3"; default: return "Unknown mouse code " + mouseCode; } } /** * Gets the x position of the mouse. * @return position of the mouse in x */ public int getMouseX() { return mouseLocation.x; } /** * Gets the y position of the mouse. * @return position of the mouse in y */ public int getMouseY() { return mouseLocation.y; } /** * Uses the Robot class to try to position the mouse in the * center of the screen. * <p>Note that use of the Robot class may not be available * on all platforms. */ private synchronized void recenterMouse() { if (robot != null && comp.isShowing()) { centerLocation.x = comp.getWidth() / 2; centerLocation.y = comp.getHeight() / 2; SwingUtilities.convertPointToScreen(centerLocation, comp); isRecentering = true; robot.mouseMove(centerLocation.x, centerLocation.y); } } /** * Gets the action of the key. * @param e the event generated by the key * @return the code of the event */ private GameAction getKeyAction(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode < keyActions.length) { return keyActions[keyCode]; } else { return null; } } /** * Gets the mouse code for the button specified in this MouseEvent. * @param e the event generated by the mouse * @return the code of the event */ public static int getMouseButtonCode(MouseEvent e) { switch (e.getButton()) { case MouseEvent.BUTTON1: return MOUSE_BUTTON_1; case MouseEvent.BUTTON2: return MOUSE_BUTTON_2; case MouseEvent.BUTTON3: return MOUSE_BUTTON_3; default: return -1; } } /** * Gets the mouse action for the button specified in this MouseEvent. * @param e the event generated by the mouse * @return the code of the event */ private GameAction getMouseButtonAction(MouseEvent e) { int mouseCode = getMouseButtonCode(e); if (mouseCode != -1) { return mouseActions[mouseCode]; } else { return null; } } /** * Manages the event generated when a key is pressed. * From the KeyListener interface. * @param e the event generated by the pressed key */ public void keyPressed(KeyEvent e) { GameAction gameAction = getKeyAction(e); if (gameAction != null) { gameAction.press(); } // make sure the key isn't processed for anything else e.consume(); } /** * Manages the event generated when a key is released. * From the KeyListener interface. * @param e the event generated by the released key */ public void keyReleased(KeyEvent e) { GameAction gameAction = getKeyAction(e); if (gameAction != null) { gameAction.release(); } // make sure the key isn't processed for anything else e.consume(); } /** * Manages the event generated when a key is typed. * From the KeyListener interface. * @param e the event generated by the typed key */ public void keyTyped(KeyEvent e) { // make sure the key isn't processed for anything else e.consume(); } /** * Manages the event generated when the mouse is pressed. * From the MouseListener interface. * @param e the event generated by the pressed mouse */ public void mousePressed(MouseEvent e) { GameAction gameAction = getMouseButtonAction(e); if (gameAction != null) { gameAction.press(); } } /** * Manages the event generated when the mouse is released. * From the MouseListener interface. * @param e the event generated by the released mouse */ public void mouseReleased(MouseEvent e) { GameAction gameAction = getMouseButtonAction(e); if (gameAction != null) { gameAction.release(); } } /** * Manages the event generated when the mouse is clicked. * From the MouseListener interface. * @param e the event generated by the clicked mouse */ public void mouseClicked(MouseEvent e) { // do nothing } /** * Manages the event generated when the mouse is entered. * From the MouseListener interface. * @param e the event generated by the entered mouse */ public void mouseEntered(MouseEvent e) { mouseMoved(e); } /** * Manages the event generated when the mouse is pressed. * From the MouseListener interface. * @param e the event generated by the pressed mouse */ public void mouseExited(MouseEvent e) { mouseMoved(e); } /** * Manages the event generated when the mouse is dragged. * From the MouseMotionListener interface. * @param e the event generated by the dragged mouse */ public void mouseDragged(MouseEvent e) { mouseMoved(e); } /** * Manages the event generated when the mouse is moved. * From the MouseMotionListener interface. * @param e the event generated by the moved mouse */ public synchronized void mouseMoved(MouseEvent e) { // this event is from re-centering the mouse - ignore it if (isRecentering && centerLocation.x == e.getX() && centerLocation.y == e.getY()) { isRecentering = false; } else { int dx = e.getX() - mouseLocation.x; int dy = e.getY() - mouseLocation.y; mouseHelper(MOUSE_MOVE_LEFT, MOUSE_MOVE_RIGHT, dx); mouseHelper(MOUSE_MOVE_UP, MOUSE_MOVE_DOWN, dy); if (isRelativeMouseMode()) { recenterMouse(); } } mouseLocation.x = e.getX(); mouseLocation.y = e.getY(); } /** * Manages the event generated when the mouse is wheel moved. * From the MouseWheelListener interface. * @param e the event generated by the wheel moved mouse */ public void mouseWheelMoved(MouseWheelEvent e) { mouseHelper(MOUSE_WHEEL_UP, MOUSE_WHEEL_DOWN, e.getWheelRotation()); } /** * Gets the list of mouseActions depending on the amount of codes. * @param codeNeg the negative code of the mouse * @param codePos the positive code of the mouse * @param amount the amount of codes */ private void mouseHelper(int codeNeg, int codePos, int amount) { GameAction gameAction; if (amount < 0) { gameAction = mouseActions[codeNeg]; } else { gameAction = mouseActions[codePos]; } if (gameAction != null) { gameAction.press(Math.abs(amount)); gameAction.release(); } } }
mit
snucsne/CSNE-Course-Source-Code
CSNE2543-Intro-to-CS-II/src/edu/snu/csne/csne2543/methods/PassByValueExample.java
1866
/* * The MIT License (MIT) * * Copyright (c) 2015 Southern Nazarene University Computer Science/Network Engineering Department * * 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 edu.snu.csne.csne2543.methods; /** * @author Brent Eskridge */ public class PassByValueExample { public static void main( String[] args ) { int n = 1; System.out.println( "Before call n=[" + n + "]" ); increment( n ); System.out.println( "After call n=[" + n + "]" ); } public static void increment( int n ) { System.out.println( "Incrementing n=[" + n + "]..." ); n++; System.out.println( "Post increment n=[" + n + "]" ); } }
mit
DavidArayan/EzyRenderer
EzyRenderer/src/engine/util/InterleavedVertex.java
1702
package engine.util; public class InterleavedVertex { public static final int elementBytes = 4; public static final int positionElementCount = 4; public static final int colorElementCount = 4; public static final int texElementCount = 2; public static final int positionByteCount = positionElementCount * elementBytes; public static final int colorByteCount = colorElementCount * elementBytes; public static final int texByteCount = texElementCount * elementBytes; public static final int positionByteOffset = 0; public static final int colorByteOffset = positionByteOffset + positionByteCount; public static final int texByteOffset = colorByteOffset + colorByteCount; public static final int elementCount = positionElementCount + colorElementCount + texElementCount; public static final int stride = positionByteCount + colorByteCount + texByteCount; private static final float[] data = new float[elementCount]; private final float[] xyz = new float[4]; private final float[] rgba = new float[4]; private final float[] st = new float[2]; public void setPosition(final float x, final float y, final float z) { xyz[0] = x; xyz[1] = y; xyz[2] = z; xyz[3] = 1.0f; } public void setRGBA(final float r, final float g, final float b, final float a) { rgba[0] = r; rgba[1] = g; rgba[2] = b; rgba[3] = a; } public void setTex(final float u, final float v) { st[0] = u; st[1] = v; } public float[] getElements() { data[0] = xyz[0]; data[1] = xyz[1]; data[2] = xyz[2]; data[3] = xyz[3]; data[4] = rgba[0]; data[5] = rgba[1]; data[6] = rgba[2]; data[7] = rgba[3]; data[8] = st[0]; data[9] = st[1]; return data; } }
mit
Azure-Samples/Android-PieTalk
source/client/src/com/msdpe/pietalk/datamodels/PieFile.java
1515
package com.msdpe.pietalk.datamodels; import java.io.File; public class PieFile { @com.google.gson.annotations.SerializedName("isVideo") private boolean mIsVideo; @com.google.gson.annotations.SerializedName("isPicture") private boolean mIsPicture; @com.google.gson.annotations.SerializedName("ownerUsername") private String mOwnerUsername; @com.google.gson.annotations.SerializedName("sentMessageId") private int mSentMessageId; @com.google.gson.annotations.SerializedName("fileName") private String mFileName; @com.google.gson.annotations.SerializedName("blobPath") private String mBlobPath; @com.google.gson.annotations.SerializedName("id") private int mId; public PieFile() {} public void setIsVideo(boolean isVideo) { mIsVideo = isVideo; } public void setIsPicture(boolean isPicture) { mIsPicture = isPicture; } public void setOwnerUsername(String ownerUsername) { mOwnerUsername = ownerUsername; } public void setSentMessageId(int sentMessageId) { mSentMessageId = sentMessageId; } public PieFile(boolean isPicture, boolean isVideo, String ownerUsername, int sentMessageId, String filePath) { mIsVideo = isVideo; mIsPicture = isPicture; mOwnerUsername = ownerUsername; mSentMessageId = sentMessageId; File file = new File(filePath); mFileName = file.getName(); } public int getId() { return mId; } public String getBlobPath() { return mBlobPath; } @Override public boolean equals(Object o) { return o instanceof PieFile && ((PieFile) o).mId == mId; } }
mit
DocuWare/PlatformJavaClient
src/com/docuware/dev/schema/_public/services/platform/DocumentLinks.java
1751
package com.docuware.dev.schema._public.services.platform; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.net.URI; import com.docuware.dev.Extensions.*; import java.util.concurrent.CompletableFuture; import java.util.*; import com.docuware.dev.schema._public.services.Link; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DocumentLinks", propOrder = { "proxy", "items" }) public class DocumentLinks implements IHttpClientProxy { private HttpClientProxy proxy;//test @XmlElement(name = "Items") protected List<DocumentLink> items; /**ArrayList is required for the XML-Marshalling */ public void setItems(ArrayList<DocumentLink> value) { items=value; } /**Define specific document link of a document*/ public List<DocumentLink> getItems() { if (items == null) { items = new ArrayList<DocumentLink>(); } return this.items; } /** * Gets the proxy. * * @return The proxy */ @Extension public HttpClientProxy getProxy() { return this.proxy; } /** * Sets the HTTP Communication Proxy which is used in futher HTTP communication. * * @param proxy The new proxy */ @Extension public void setProxy(HttpClientProxy proxy) { this.proxy = proxy; if(this.items!=null) { for (int i = 0; (i < this.items.size()); i = (i + 1)) { this.items.get(i).setProxy(proxy); } } } }
mit
VladimirRadojcic/Master
BusinessProcessModelingTool/src/bp/details/LaneDetails.java
2533
package bp.details; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import bp.event.BPFocusListener; import bp.model.data.Lane; import bp.model.util.BPKeyWords; import bp.model.util.Controller; public class LaneDetails extends ElementDetails{ /** * */ private static final long serialVersionUID = -5480446616251138679L; public static final String PARENT_LABEL = "Parent:"; public static final String ACTOR_LABEL = "Actor:"; private Lane lane = (Lane) getElement(); private JLabel parentLb; private JLabel actorLb; private JTextField parentTf; private JTextArea actorTa; private JScrollPane actorScroll; public LaneDetails(Lane lane) { super(lane); } @Override protected void initComponents() { super.initComponents(); this.parentLb = new JLabel(PARENT_LABEL); this.actorLb = new JLabel(ACTOR_LABEL); this.parentTf = new JTextField(20); this.actorTa = new JTextArea(5, 20); this.actorScroll = new JScrollPane(this.actorTa); // Set the texts if available lane = (Lane) getElement(); if (lane.getParent() != null) parentTf.setText(lane.getParent().getUniqueName()); if (lane.getActor() != null) actorTa.setText(lane.getActor()); } @Override protected void layoutComponents() { super.layoutComponents(); createBasic(); getBasic().add(this.actorLb); getBasic().add(this.actorScroll); getBasic().add(this.parentLb); getBasic().add(this.parentTf); } @Override protected void addActions() { super.addActions(); this.actorTa.addFocusListener(new BPFocusListener() { @Override public void updateValue() { LaneDetails.this.lane.updateActor((String) getValue(), Controller.DETAILS); } @Override public Object getValue() { return LaneDetails.this.actorTa.getText(); } }); } @Override protected void dataAttributeChanged(final BPKeyWords keyWord, final Object value) { super.dataAttributeChanged(keyWord, value); if (value != null) { if (keyWord == BPKeyWords.PARENT) { // TODO } else if (keyWord == BPKeyWords.ACTOR) { this.actorTa.setText((String) value); } } } }
mit
RespectNetwork/csp-provisioning-application
src/main/java/net/respectnetwork/csp/application/model/InviteResponseModel.java
2802
package net.respectnetwork.csp.application.model; import java.util.Date; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; public class InviteResponseModel { private String responseId; private String inviteId; private String paymentId; private String cloudNameCreated; private Date timeCreated; public InviteResponseModel() { this.responseId = null; this.inviteId = null; this.paymentId = null; this.cloudNameCreated = null; this.timeCreated = null; } public String getResponseId() { return this.responseId; } public void setResponseId( String responseId ) { this.responseId = responseId; } public String getInviteId() { return this.inviteId; } public void setInviteId( String inviteId ) { this.inviteId = inviteId; } public String getPaymentId() { return this.paymentId; } public void setPaymentId( String paymentId ) { this.paymentId = paymentId; } public String getCloudNameCreated() { return this.cloudNameCreated; } public void setCloudNameCreated( String cloudNameCreated ) { this.cloudNameCreated = cloudNameCreated; } public Date getTimeCreated() { return this.timeCreated; } public void setTimeCreated( Date timeCreated ) { this.timeCreated = timeCreated; } public boolean equals( Object object ) { if( object == null ) { return false; } if( object == this ) { return true; } if( this.getClass().equals(object.getClass()) == false ) { return false; } InviteResponseModel other = (InviteResponseModel) object; return new EqualsBuilder() .appendSuper(super.equals(other)) .append(this.responseId, other.responseId) .append(this.inviteId, other.inviteId) .append(this.paymentId, other.paymentId) .append(this.cloudNameCreated, other.cloudNameCreated) .append(this.timeCreated, other.timeCreated) .isEquals(); } public int hashCode() { return new HashCodeBuilder(17, 37) .appendSuper(super.hashCode()) .append(this.responseId) .append(this.inviteId) .append(this.paymentId) .append(this.cloudNameCreated) .append(this.timeCreated) .toHashCode(); } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("InviteResponseModel "); builder.append("[responseId=") .append(this.responseId).append(']'); builder.append("[inviteId=") .append(this.inviteId).append(']'); builder.append("[paymentId=") .append(this.paymentId).append(']'); builder.append("[cloudNameCreated=") .append(this.cloudNameCreated).append(']'); builder.append("[timeCreated=") .append(this.timeCreated).append(']'); builder.append(' '); builder.append(super.toString()); return builder.toString(); } }
mit
Hexeption/Youtube-Hacked-Client-1.8
minecraft/net/minecraft/nbt/NBTTagEnd.java
765
package net.minecraft.nbt; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; public class NBTTagEnd extends NBTBase { private static final String __OBFID = "CL_00001219"; void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException {} /** * Write the actual data contents of the tag, implemented in NBT extension classes */ void write(DataOutput output) throws IOException {} /** * Gets the type byte for the tag. */ public byte getId() { return (byte)0; } public String toString() { return "END"; } /** * Creates a clone of the tag. */ public NBTBase copy() { return new NBTTagEnd(); } }
mit
CDSteer/cs235steera6
src/MenuGUI.java
20433
import javax.swing.*; import javax.swing.event.DocumentListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.util.ArrayList; import java.util.Random; import java.io.File; /** * @author Jamie I Davies * @date March 25, 2014 * @brief This class creates all the swing objects for the Splash Screen of the game * */ public class MenuGUI extends JFrame{ private Main m_splash; private Main m_options; private Main m_playerNames; private static final int SPLASH_JFRAME_WIDTH = 1110; private static final int SPLASH_JFRAME_HEIGHT = 285; private static final int PLAYER_JFRAME_WIDTH = 360; private static final int PLAYER_JFRAME_HEIGHT = 330; private static final int PLAYNAMES_JFRAME_WIDTH = 280; private static final int PLAYNAMES_JFRAME_HEIGHT = 300; private static final int SPLASH_GRID_COLS = 2; private static final int PLAYER_GRID_COLS = 1; private static final int PLAYER_GRID_ROWS = 2; private static final int OTH_LOOP_MAX = 8; private static final int LOOP_MAX_ONE = 7; private static final int LOOP_MAX_TWO = 10; private static final int PLAY_STATE_HARD = 2; private static final int NORMAL_BOARD_SIZE = 8; private static final double C_WEIGHT = 1.; private static final int WIDTH_VALUE = 2; private static final int Y_VALUE = 3; private static String player2Option; private static Boolean player2Human = false; private static int difficulty = 0; // 0 for easy, 1 for hard private static int gameChoice; private static int playState; // 0 for human, 1 for easy, 2 for hard private static String player1name; private static String player2name; private static boolean player1blank; private static boolean player2blank; private C4SaveManager c4SaveManager = new C4SaveManager(); private OthSaveManager othSaveManager = new OthSaveManager(); private int turn, time; private int m_UIState = 3; /** * Set splash screen to visible */ public MenuGUI(){ m_splash = new Main(); m_splash.setVisible(true); m_options = new Main(); m_playerNames = new Main(); m_splash.setResizable(false); } /** * method to initialise all the GUI Swing elements for the SplashScreen */ public void initSplash() { /** 2 cols 1 row JPanel */ JPanel panel = new JPanel(new GridLayout(1,SPLASH_GRID_COLS)); m_splash.getContentPane().add(panel); ImageIcon c4ButtonIMG = new ImageIcon("../Images/C4SplashScreenImage.png"); ImageIcon othButtonIMG = new ImageIcon("../Images/OthSplashScreenImage.png"); ImageIcon tttButtonIMG = new ImageIcon("../Images/TTTSplashScreenImage.png"); JButton c4Button = new JButton("", c4ButtonIMG); JButton othButton = new JButton("", othButtonIMG); JButton tttButton = new JButton("", tttButtonIMG); // action listener for the C4 button c4Button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { //call the options splash screen System.out.println("Play Connect 4..."); gameChoice = 0; m_splash.setVisible(false); initPlayerOptions(); m_UIState = 0; } }); // othello button action listener othButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { //call the options splash screen System.out.println("Play Othello..."); gameChoice = 1; m_splash.setVisible(false); initPlayerOptions(); m_UIState = 1; System.out.println("Othello: " + m_UIState); } }); // othello button action listener tttButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { //call the options splash screen System.out.println("Play TicTacToe^2..."); gameChoice = 2; m_splash.setVisible(false); initPlayerOptions(); m_UIState = 3; System.out.println("TicTacToe^2: " + m_UIState); } }); //add buttons to panel panel.add(c4Button); panel.add(othButton); panel.add(tttButton); //initialise JFrame m_splash.setTitle("A5 Complete Implementation : Connect 4 and Othello : Group 3 "); m_splash.setSize(SPLASH_JFRAME_WIDTH, SPLASH_JFRAME_HEIGHT); m_splash.setLocationRelativeTo(null); m_splash.setDefaultCloseOperation(EXIT_ON_CLOSE); } public void initPlayerOptions() { m_options.setVisible(true); /** 2 cols 2 rows JPanel */ JPanel playerOptionsPanel = new JPanel(new GridLayout(PLAYER_GRID_ROWS,PLAYER_GRID_COLS)); m_options.getContentPane().add(playerOptionsPanel); ImageIcon humanPlayerIMG = new ImageIcon("../Images/HumanImageWD.png"); ImageIcon easyAIButtonIMG = new ImageIcon("../Images/AIEasyImageWD.png"); ImageIcon hardAIButtonIMG = new ImageIcon("../Images/AIHardImageWD.png"); ImageIcon loadButtonIMG = new ImageIcon("../Images/LoadGameImage.png"); JButton humanButton = new JButton("", humanPlayerIMG); JButton easyAIButton = new JButton("", easyAIButtonIMG); JButton hardAIButton = new JButton("", hardAIButtonIMG); JButton loadButtonOth = new JButton("", loadButtonIMG); JButton loadButtonC4 = new JButton("", loadButtonIMG); // action listener for the human button humanButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { m_options.setVisible(true); m_options.setVisible(false); //change p2 label on name selection and set p2human state to false player2Option = "Player 2 Name: "; player2Human = true; playState = 0; initPlayerNaming(); } }); // action listener for the easy AI button easyAIButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { m_options.setVisible(false); //change p2 label on name selection and set p2human state to false player2Option = "Computer Name: "; player2Human = false; //set difficulty to easy difficulty = 0; playState = 1; initPlayerNaming(); } }); // action listener for the hard AI button hardAIButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { m_options.setVisible(false); //change p2 label on name selection and set p2human state to false player2Option = "Computer Name: "; player2Human = false; //set difficulty to hard difficulty = 1; playState = PLAY_STATE_HARD; initPlayerNaming(); } }); // action listener for the load button loadButtonOth.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Piece[][] newBoard = new Piece[NORMAL_BOARD_SIZE][NORMAL_BOARD_SIZE]; try{ othSaveManager.loadData(); } catch (IOException e){ JOptionPane.showMessageDialog(null, "Can't Load Data"); System.out.println("Can't Load Data"); e.printStackTrace(); } ProgramController controller = new ProgramController(); controller.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if (othSaveManager.getLoadGameType().equals("Oth")) { gameChoice = 1; if (othSaveManager.getLoadPlayerType2().equals("Human")){ playState = 0; } else if (othSaveManager.getLoadPlayerType2().equals("Easy")) { playState = 1; } else if (othSaveManager.getLoadPlayerType2().equals("Hard")) { playState = PLAY_STATE_HARD; } player1name = othSaveManager.getLoadName1(); player2name = othSaveManager.getLoadName2(); turn = othSaveManager.getLoadTurn(); time = othSaveManager.getLoadTime(); OthelloGameLogic othGameLogic = othSaveManager.getLoadGame(); Board board = othGameLogic.getBoard(); newBoard = board.getBoard(); for (int i = 0; i < OTH_LOOP_MAX; i++) { for (int j = 0; j < OTH_LOOP_MAX; j++) { System.out.println(newBoard[j][i].getColour()); } } } try { controller.ProgramController(gameChoice, playState, player1name, player2name, newBoard, turn, time); m_playerNames.setVisible(false); } catch (IOException e) { e.printStackTrace(); } } }); // action listener for the load button loadButtonC4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Piece[][] newBoard = new Piece[LOOP_MAX_TWO][LOOP_MAX_ONE]; try { if (c4SaveManager.loadData()){ System.out.println("Data loaded"); } else { System.out.println("Can't Load Data"); JOptionPane.showMessageDialog(null, "Can't Load Data"); } } catch (IOException e) { System.out.println("Can't Load Data"); JOptionPane.showMessageDialog(null, "Can't Load Data"); //e.printStackTrace(); } ProgramController controller = new ProgramController(); controller.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if (c4SaveManager.getLoadGameType().equals("C4")) { gameChoice = 0; if (c4SaveManager.getLoadPlayerType2().equals("Human")) { playState = 0; } else if (c4SaveManager.getLoadPlayerType2().equals("Easy")) { playState = 1; } else if (c4SaveManager.getLoadPlayerType2().equals("Hard")) { playState = PLAY_STATE_HARD; } player1name = c4SaveManager.getLoadName1(); player2name = c4SaveManager.getLoadName2(); turn = c4SaveManager.getLoadTurn(); time = c4SaveManager.getLoadTime(); Connect4GameLogic connect4GameLogic = c4SaveManager.getLoadGame(); Board board = connect4GameLogic.getBoard(); newBoard = board.getBoard(); for (int i = 0; i < LOOP_MAX_ONE; i++) { for (int j = 0; j < LOOP_MAX_TWO; j++) { System.out.println(newBoard[j][i].getColour()); } } } try { controller.ProgramController(gameChoice, playState, player1name, player2name, newBoard, turn, time); m_playerNames.setVisible(false); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); //add buttons to panel playerOptionsPanel.add(humanButton); playerOptionsPanel.add(easyAIButton); if (gameChoice == 0 || gameChoice == 1){ playerOptionsPanel.add(hardAIButton); } if (gameChoice == 0){ System.out.println("C4: "+m_UIState); playerOptionsPanel.add(loadButtonC4); } else if (gameChoice == 1){ System.out.println("Othello: "+m_UIState); playerOptionsPanel.add(loadButtonOth); } //initialise JFrame m_options.setTitle("Play Options"); m_options.setSize(PLAYER_JFRAME_WIDTH, PLAYER_JFRAME_HEIGHT); m_options.setLocationRelativeTo(null); m_options.setDefaultCloseOperation(EXIT_ON_CLOSE); m_options.setResizable(false); } public void initPlayerNaming() { /** 2 cols 2 rows JPanel */ m_playerNames.setVisible(true); JPanel playerNamesPanel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); m_playerNames.getContentPane().add(playerNamesPanel); JButton playButton = new JButton("Play "); final JTextField player1 = new JTextField(); final JTextField player2 = new JTextField(); JLabel label1 = new JLabel("Player 1 Name: "); JLabel label2 = new JLabel(player2Option); //create various grid references for the layout c.gridx = 0; c.gridy = 0; playerNamesPanel.add(label1, c); c.gridx = 0; c.gridy = 1; playerNamesPanel.add(label2, c); c.gridx = 1; c.gridy = 0; c.weightx = C_WEIGHT; c.fill=GridBagConstraints.HORIZONTAL; playerNamesPanel.add(player1, c); c.gridx = 1; c.gridy = 1; c.weightx = C_WEIGHT; c.fill=GridBagConstraints.HORIZONTAL; playerNamesPanel.add(player2, c); c.gridx = 0; c.gridy = Y_VALUE; c.gridwidth = WIDTH_VALUE; playerNamesPanel.add(playButton, c); //adjusts state of player2 label depending on play option if (player2Human == false) { player2.setEnabled(false); player2.setText(randomNameGen(difficulty)); } else { player2.setEnabled(true); } // action listener for the hard AI button playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { //store entered player names player1name = player1.getText(); player2name = player2.getText(); System.out.println("choice: " + gameChoice + " playstate: " + playState + " p1:" + player1name + " p2: " + player2name); if (player1name.equals("")) { player1blank = true; } else if (player2name.equals("")) { player2blank = true; } else { player1blank = false; player2blank = false; } System.out.println("p1blank?: " + player1blank + " p2blank?: " + player2blank); //checks the validation for the input player names if (player1blank == true | player2blank == true) { JOptionPane.showMessageDialog(m_playerNames, "Sorry, you haven't entered valid player name input!", "Player Name Input Error!", JOptionPane.WARNING_MESSAGE); } else { ProgramController controller = new ProgramController(); controller.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); m_playerNames.setVisible(false); try { controller.ProgramController(gameChoice, playState, player1name, player2name); } catch (IOException e) { e.printStackTrace(); } } } }); //initialise JFrame m_playerNames.setTitle("Set Player Names"); m_playerNames.setSize(PLAYNAMES_JFRAME_WIDTH, PLAYNAMES_JFRAME_HEIGHT); m_playerNames.setLocationRelativeTo(null); m_playerNames.setDefaultCloseOperation(EXIT_ON_CLOSE); m_playerNames.setResizable(false); } /** * method to get a random name for either the easy or hard computer player * This provides the option to have multiple possible names for AI, though currently * only 'Easy AI' and 'Hard AI' are used. * @param difficulty int representing AI difficulty * @return String representing player name */ public String randomNameGen(int difficulty) { ArrayList<String> easyNames = new ArrayList<String>(); ArrayList<String> hardNames = new ArrayList<String>(); // add elements to easy list easyNames.add("Easy AI"); //add elements to hard list hardNames.add("Hard AI"); //create two random generators Random easyRandomGen = new Random();Random hardRandomGen = new Random(); //set index to the random element to get from arraylist int easyIndex = easyRandomGen.nextInt(easyNames.size()); int hardIndex = hardRandomGen.nextInt(hardNames.size()); //get the value from the arraylist String easyName = easyNames.get(easyIndex); String hardName = hardNames.get(hardIndex); //if to determine if the game is being played in easy or hard ai mode String playerName; if (difficulty == 0 ) { playerName = easyName; } else { playerName = hardName; } return playerName; } /** * Main method for class tests on MenuGUI * Takes no arguments */ public static void main(String args[]) { /* * Test One * Calling the MenuGUI Constructor */ try { MenuGUI testScreen1 = new MenuGUI(); System.out.println("MenuGUI.constructor Evaluated: Correct"); } catch(Exception e) { System.out.println("MenuGUI.constructor Evaluated: Incorrect"); } /* * Test Two * Calling the MenuGUI.initSplash method */ try{ MenuGUI testScreen2 = new MenuGUI(); testScreen2.initSplash(); System.out.println("MenuGUI.initSplash Evaluated:: Correct"); } catch(Exception e) { System.out.println("MenuGUI.initSplash Evaluated:: Incorrect"); } /* * Test Three * Calling the MenuGUI.initPlayerOptions method */ try{ MenuGUI testScreen3 = new MenuGUI(); testScreen3.initPlayerOptions(); System.out.println("MenuGUI.initPlayerOptions Evaluated:: Correct"); } catch(Exception e) { System.out.println("MenuGUI.initPlayerOptions Evaluated:: Incorrect"); } /* * Test Four * Calling the MenuGUI.initPlayerNaming method */ try{ MenuGUI testScreen4 = new MenuGUI(); testScreen4.initPlayerNaming(); System.out.println("MenuGUI.initPlayerNaming Evaluated:: Correct"); } catch(Exception e) { System.out.println("MenuGUI.initPlayerNaming Evaluated: Incorrect"); } /* * Test Five * Calling the MenuGUI.randomNameGen method */ try{ MenuGUI testScreen5 = new MenuGUI(); String testName = testScreen5.randomNameGen(0); if(testName.equals("Easy AI")) { System.out.println("MenuGUI.randomNameGen Evaluated: Correct"); } else { System.out.println("MenuGUI.randomNameGen Evaluated: Correct"); } } catch(Exception e) { System.out.println("MenuGUI.randomNameGen: Error in MenuGUI constructor"); } } }
mit
shoken-tofi/shoken
identity-access-management-api-rest-adapter/src/main/java/com/bsuir/shoken/iam/AuthenticationRestController.java
504
package com.bsuir.shoken.iam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController; @RestController class AuthenticationRestController extends AuthenticationController { @Autowired AuthenticationRestController(UserConverter userConverter, UserService userService, SecurityContextService securityContextService) { super(userConverter, userService, securityContextService); } }
mit
BookFrank/CodePlay
codeplay-jvm/src/main/java/com/tazine/jvm/exception/CpuExhaustion.java
841
package com.tazine.jvm.exception; import java.util.concurrent.Executor; import java.util.concurrent.Executors; /** * CPU 使用率过高 * * @author frank * @date 2019/01/26 */ public class CpuExhaustion { private static Executor executor = Executors.newFixedThreadPool(4); private static Object lock = new Object(); public static void main(String[] args) { Task task1 = new Task(); Task task2 = new Task(); executor.execute(task1); executor.execute(task2); } private static class Task implements Runnable{ @Override public void run() { synchronized (lock){ doBusiness(); } } public void doBusiness(){ int i = 0; while (true){ i++; } } } }
mit
tom5454/Toms-Mod
src/main/java/com/tom/client/GuiButtonMatchMeta.java
2157
package com.tom.client; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import com.tom.api.gui.GuiTomsMod; @SideOnly(Side.CLIENT) public class GuiButtonMatchMeta extends GuiButton { private final GuiTomsMod gui; public boolean use; private static final ItemStack stack = new ItemStack(Items.DIAMOND_SWORD, 1, ((ItemSword) Items.DIAMOND_SWORD).getMaxDamage(new ItemStack(Items.DIAMOND_SWORD)) / 2); public GuiButtonMatchMeta(int buttonId, int x, int y, GuiTomsMod gui) { super(buttonId, x, y, 16, 16, ""); this.gui = gui; } /** * Draws this button to the screen. */ @Override public void drawButton(Minecraft mc, int mouseX, int mouseY, float partTicks) { if (this.visible) { mc.getTextureManager().bindTexture(GuiTomsMod.LIST_TEXTURE); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); this.drawTexturedModalRect(this.x, this.y, 175, 161, this.width, this.height); GlStateManager.pushMatrix(); float f = 0.85f; RenderHelper.enableGUIStandardItemLighting(); gui.renderItemInGui(stack, this.x + 1, this.y + 1, -200, -200, f); RenderHelper.disableStandardItemLighting(); GlStateManager.popMatrix(); mc.getTextureManager().bindTexture(GuiTomsMod.LIST_TEXTURE); if (!use) this.drawTexturedModalRect(this.x, this.y, 191, 161, this.width, this.height); this.mouseDragged(mc, mouseX, mouseY); } } }
mit
aidonggua/jarvis
src/main/java/jarvis/converter/CollectionConverter.java
1679
package jarvis.converter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.function.Function; /** * 一系列对bean的操作 * * @author yehao * @date 2019-09-24 */ public class CollectionConverter { /** * 将Collection转化为Map * * @param collection 需要转换成map的集合 * @param function 用于构造Map的key的函数 * @author yehao * @date 2019-09-24 */ public static <V, K> HashMap<K, V> toMap(Collection<V> collection, Function<V, K> function) { if (collection == null || collection.size() == 0) { return null; } HashMap<K, V> map = new HashMap<>(); for (V v : collection) { map.put(function.apply(v), v); } return map; } /** * 将Collection转化为元素为List的Map * * @param collection 需要转换成map的集合 * @param function 用于构造Map的key的函数 * @author yehao * @date 2019-09-24 */ public static <V, K> HashMap<K, List<V>> group(Collection<V> collection, Function<V, K> function) { if (collection == null || collection.size() == 0) { return null; } HashMap<K, List<V>> map = new HashMap<>(); for (V v : collection) { K key = function.apply(v); if (map.containsKey(key)) { map.get(key) .add(v); } else { List<V> list = new ArrayList<>(); list.add(v); map.put(key, list); } } return map; } }
mit
cng1985/scribejava
scribejava-core/src/main/java/com/github/scribejava/core/services/PlaintextSignatureService.java
1028
package com.github.scribejava.core.services; import com.github.scribejava.core.exceptions.OAuthSignatureException; import com.github.scribejava.core.utils.OAuthEncoder; import com.github.scribejava.core.utils.Preconditions; /** * plaintext implementation of {@link SignatureService} */ public class PlaintextSignatureService implements SignatureService { private static final String METHOD = "PLAINTEXT"; /** * {@inheritDoc} */ @Override public String getSignature(String baseString, String apiSecret, String tokenSecret) { try { Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string"); return OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret); } catch (Exception e) { throw new OAuthSignatureException(baseString, e); } } /** * {@inheritDoc} */ @Override public String getSignatureMethod() { return METHOD; } }
mit
yzhnasa/TASSEL-iRods
src/net/maizegenetics/analysis/gbs/ProductionPipeline.java
7681
/* * ProductionPipeline */ package net.maizegenetics.analysis.gbs; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.plugindef.PluginParameter; import net.maizegenetics.util.Utils; import net.maizegenetics.util.DirectoryCrawler; import net.maizegenetics.plugindef.AbstractPlugin; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; /** * * @author Terry Casstevens */ public class ProductionPipeline extends AbstractPlugin { private static final Logger myLogger = Logger.getLogger(ProductionPipeline.class); private static final SimpleDateFormat LOGGING_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); public enum PARAMETERS { inputDirectory, keyFile, enzyme, productionTOPM, outputGenotypeFile, archiveDirectory }; protected PluginParameter<String> myInputDirectory = new PluginParameter.Builder<String>(PARAMETERS.inputDirectory, null, String.class).required(true).inFile() .description("Input directory containing fastq AND/OR qseq files").build(); protected PluginParameter<String> myKeyFile = new PluginParameter.Builder<String>(PARAMETERS.keyFile, null, String.class).required(true).inFile() .description("Barcode Key File").build(); protected PluginParameter<String> myEnzyme = new PluginParameter.Builder<String>(PARAMETERS.enzyme, null, String.class).required(true) .description("Enzyme used to create the GBS library").build(); protected PluginParameter<String> myProductionTOPM = new PluginParameter.Builder<String>(PARAMETERS.productionTOPM, null, String.class).required(true).inFile() .description("Physical map file containing tags and corresponding variants (production TOPM)").build(); protected PluginParameter<String> myOutputGenotypeFile = new PluginParameter.Builder<String>(PARAMETERS.outputGenotypeFile, null, String.class).required(true).outFile() .description("Output (target) HDF5 genotypes file to add new genotypes to (new file created if it doesn't exist)").build(); protected PluginParameter<String> myArchiveDirectory = new PluginParameter.Builder<String>(PARAMETERS.archiveDirectory, null, String.class).required(true).outFile() .description("Archive directory where to move processed files").build(); private String myOutputDirectory; private PrintStream myPrintStreamToLog; public ProductionPipeline(Frame parentFrame, boolean isInteractive) { super(parentFrame, isInteractive); } @Override public DataSet performFunction(DataSet input) { if (myOutputGenotypeFile.value() != null) { myOutputDirectory = Utils.getDirectory(myOutputGenotypeFile.value()); setupLogfile(); } myLogger.info(getTimeStamp()); return super.performFunction(input); } @Override public DataSet processData(DataSet input) { try { String[] rawSeqFileNames = DirectoryCrawler.listFileNames(ProductionSNPCallerPlugin.rawSeqFileNameRegex, myInputDirectory.value()); if ((rawSeqFileNames == null) || (rawSeqFileNames.length == 0)) { return null; } myLogger.info("Raw Sequence Files: " + Arrays.deepToString(rawSeqFileNames)); myLogger.info("Parameters Passed to ProductionSNPCallerPlugin: " + Arrays.deepToString(getPluginArgs())); ProductionSNPCallerPlugin plugin = new ProductionSNPCallerPlugin(); plugin.setParameters(getPluginArgs()); printParameterValues(); plugin.performFunction(null); for (int i = 0; i < rawSeqFileNames.length; i++) { File currentLocation = new File(rawSeqFileNames[i]); File newLocation = new File(myArchiveDirectory.value() + Utils.getFilename(rawSeqFileNames[i])); currentLocation.renameTo(newLocation); myLogger.info("Moved : " + currentLocation.getAbsolutePath() + " to: " + newLocation.getAbsolutePath()); } return null; } finally { if (myPrintStreamToLog != null) { myPrintStreamToLog.close(); } } } private String[] getPluginArgs() { String[] args = { "-i", myInputDirectory.value(), "-k", myKeyFile.value(), "-e", myEnzyme.value(), "-o", myOutputGenotypeFile.value(), "-m", myProductionTOPM.value() }; return args; } private void setupLogfile() { String todayDate = new SimpleDateFormat("yyyyMMdd").format(new Date()); String logFileName = todayDate + "_" + "ProductionPipeline" + ".log"; File logFile = new File(myOutputDirectory + "/" + logFileName); myLogger.info("Log File: " + logFile.getAbsolutePath()); java.util.Properties props = new java.util.Properties(); props.setProperty("log4j.logger.net.maizegenetics", "DEBUG, FILE"); props.setProperty("log4j.appender.FILE", "org.apache.log4j.FileAppender"); props.setProperty("log4j.appender.FILE.File", logFile.getAbsolutePath()); props.setProperty("log4j.appender.FILE.ImmediateFlush", "true"); props.setProperty("log4j.appender.FILE.Threshold", "debug"); props.setProperty("log4j.appender.FILE.Append", "true"); props.setProperty("log4j.appender.FILE.layout", "org.apache.log4j.TTCCLayout"); PropertyConfigurator.configure(props); myPrintStreamToLog = new PrintStream(new ProductionPipelineOutputStream()); System.setOut(myPrintStreamToLog); System.setErr(myPrintStreamToLog); } /** * Convenience method to provide uniformly labeled timestamps */ private static String getTimeStamp() { return "Timestamp: " + LOGGING_DATE_FORMAT.format(new Date()) + ": "; } @Override public ImageIcon getIcon() { return null; } @Override public String getButtonName() { return "Production Pipeline"; } @Override public String getToolTipText() { return "Production Pipeline"; } private class ProductionPipelineOutputStream extends OutputStream { private static final int DEFAULT_BUFFER_LENGTH = 2048; private int bufferLength = DEFAULT_BUFFER_LENGTH; private byte[] myBuffer; private int myCounter; public ProductionPipelineOutputStream() { myBuffer = new byte[bufferLength]; myCounter = 0; } @Override public void write(final int b) throws IOException { if (b == 0) { return; } if (myCounter == bufferLength) { final int newBufferLength = bufferLength + DEFAULT_BUFFER_LENGTH; final byte[] temp = new byte[newBufferLength]; System.arraycopy(myBuffer, 0, temp, 0, bufferLength); myBuffer = temp; bufferLength = newBufferLength; } myBuffer[myCounter] = (byte) b; myCounter++; } @Override public void flush() { if (myCounter == 0) { return; } myLogger.info(new String(myBuffer, 0, myCounter)); myCounter = 0; } @Override public void close() { flush(); } } }
mit
KoKumagai/exercises
yukicoder/373_かけ算と割った余り/Main.java
353
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long A = sc.nextInt(); long B = sc.nextInt(); long C = sc.nextInt(); long D = sc.nextInt(); long answer = A * B % D * C % D; System.out.println(answer); } }
mit
IsaiasSantana/CarGame
core/src/com/cargame/game/Car.java
434
package com.cargame.game; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.cargame.helpers.AssetLoader; import com.cargame.screens.GameScreen; public class Car extends Game { @Override public void create () { Gdx.app.log("Car","Car started!"); AssetLoader.load(); setScreen(new GameScreen()); } @Override public void dispose () { super.dispose(); AssetLoader.dispose(); } }
mit
pokey/smartAutocomplete
src/features/Test2.java
1089
package smartAutocomplete; import fig.basic.*; public class Test2 extends FeatureDomain { @Option(gloss="Seed parameters") public static boolean seedParams = false; public Test2(Corpus corpus, Statistics statistics) {} private void putParam(Params params, int cluster, String feature, double val) { params.weights.put(toFeature(Main.clusterDecorators[cluster].decorate(feature)), val); } @Override protected void initParams(Params params) { if (seedParams) putParams(params); } void putParams(Params params) { putParam(params, 0, "feat", 10); putParam(params, 1, "feat", -10); } @Override void addFeatures(PredictionContext context, Candidate candidate) { SubList<String> candidate_ngram = CandidateNgram.get(context, candidate); FeatureVector features = candidate.clusterFeatures; // addFeature(features, "bias", 100); if (candidate.token == "w0") { if (candidate_ngram.get(0) == "a") addFeature(features, "feat", 1); else // b addFeature(features, "feat", -1); } } }
mit
vollov/jboss-lab
cdbooks/src/main/java/org/demo/books/domain/Book.java
1615
package org.demo.books.domain; public class Book { // ====================================== // = Attributes = // ====================================== private String title; private Float price; private String description; private String number; // ====================================== // = Constructors = // ====================================== public Book() { } public Book(String title, Float price, String description) { this.title = title; this.price = price; this.description = description; } // ====================================== // = Getters & Setters = // ====================================== public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } // ====================================== // = hash, equals, toString = // ====================================== @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Book{"); sb.append("title='").append(title).append('\''); sb.append(", price=").append(price); sb.append(", description='").append(description).append('\''); sb.append(", number='").append(number).append('\''); sb.append('}'); return sb.toString(); } }
mit
wu99lin/generator-syp-andy
generators/app/templates/_src/adapter/NotebookAdapter.java
5518
/* * Copyright (c) 2015, 张涛. * * 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 <%= packageName %>.adapter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import <%= packageName %>.AppContext; import <%= packageName %>.R; import <%= packageName %>.domain.NotebookData; import <%= packageName %>.ui.fragment.NoteEditFragment; import <%= packageName %>.ui.widget.KJDragGridView.DragGridBaseAdapter; import android.app.Activity; import android.text.Html; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; /** * 便签列表适配器 * * @author kymjs (https://www.kymjs.com/) * */ public class NotebookAdapter extends BaseAdapter implements DragGridBaseAdapter { private List<NotebookData> datas; private final Activity aty; private int currentHidePosition = -1; private final int width; private final int height; private boolean dataChange = false; public NotebookAdapter(Activity aty, List<NotebookData> datas) { super(); if (datas == null) { datas = new ArrayList<NotebookData>(1); } this.datas = datas; this.aty = aty; width = AppContext.screenW / 2; height = (int) aty.getResources().getDimension(R.dimen.space_35); } public void refurbishData(List<NotebookData> datas) { if (datas == null) { datas = new ArrayList<NotebookData>(1); } this.datas = datas; notifyDataSetChanged(); } @Override public int getCount() { return datas.size(); } @Override public Object getItem(int position) { return datas.get(position); } @Override public long getItemId(int position) { return 0; } public List<NotebookData> getDatas() { return datas; } /** * 数据是否发生了改变 * * @return */ public boolean getDataChange() { return dataChange; } static class ViewHolder { TextView date; ImageView state; ImageView thumbtack; View titleBar; TextView content; } @Override public View getView(int position, View v, ViewGroup parent) { NotebookData data = datas.get(position); ViewHolder holder = null; if (v == null) { holder = new ViewHolder(); v = View.inflate(aty, R.layout.item_notebook, null); holder.titleBar = v.findViewById(R.id.item_note_titlebar); holder.date = (TextView) v.findViewById(R.id.item_note_tv_date); holder.state = (ImageView) v.findViewById(R.id.item_note_img_state); holder.thumbtack = (ImageView) v .findViewById(R.id.item_note_img_thumbtack); holder.content = (TextView) v.findViewById(R.id.item_note_content); v.setTag(holder); } else { holder = (ViewHolder) v.getTag(); } RelativeLayout.LayoutParams params = (LayoutParams) holder.content .getLayoutParams(); params.width = width; params.height = (params.width - height); holder.content.setLayoutParams(params); holder.titleBar .setBackgroundColor(NoteEditFragment.sTitleBackGrounds[data .getColor()]); holder.date.setText(data.getDate()); if (data.getId() > 0) { holder.state.setVisibility(View.GONE); } else { holder.state.setVisibility(View.VISIBLE); } holder.thumbtack.setImageResource(NoteEditFragment.sThumbtackImgs[data .getColor()]); holder.content.setText(Html.fromHtml(data.getContent()).toString()); holder.content.setBackgroundColor(NoteEditFragment.sBackGrounds[data .getColor()]); if (position == currentHidePosition) { v.setVisibility(View.GONE); } else { v.setVisibility(View.VISIBLE); } return v; } @Override public void reorderItems(int oldPosition, int newPosition) { dataChange = true; if (oldPosition >= datas.size() || oldPosition < 0) { return; } NotebookData temp = datas.get(oldPosition); if (oldPosition < newPosition) { for (int i = oldPosition; i < newPosition; i++) { Collections.swap(datas, i, i + 1); } } else if (oldPosition > newPosition) { for (int i = oldPosition; i > newPosition; i--) { Collections.swap(datas, i, i - 1); } } datas.set(newPosition, temp); } @Override public void setHideItem(int hidePosition) { this.currentHidePosition = hidePosition; notifyDataSetChanged(); } }
mit
shashanksingh28/code-similarity
data/Java Cookbook 3rd Edition/javacooksrc/javacooksrc/main/java/threads/buzzin/BuzzInServlet.java
6835
package threads.buzzin; /* * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Ian F. Darwin. * 4. Neither the name of the author nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Java, the Duke mascot, and all variants of Sun's Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun's, and James Gosling's, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */ import javax.servlet.*; import javax.servlet.http.*; import java.io.*; /** A quiz-show "buzzer" servlet: the first respondant wins the chance * to answer the skill-testing question. * <p> * Previous versions of this code used shared static variables, but this * is not reliable, since most web engines now use custom class loaders * that may load a servlet class more than once. The "right" way is to * synchronize on an object stored in the Servlet Application Context. */ // BEGIN main public class BuzzInServlet extends HttpServlet { /** The attribute name used throughout. */ protected final static String WINNER = "buzzin.winner"; /** doGet is called from the contestants web page. * Uses a synchronized code block to ensure that * only one contestant can change the state of "buzzed". */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext application = getServletContext(); boolean iWon = false; String user = request.getRemoteHost() + '@' + request.getRemoteAddr(); // Do the synchronized stuff first, and all in one place. synchronized(application) { if (application.getAttribute(WINNER) == null) { application.setAttribute(WINNER, user); application.log("BuzzInServlet: WINNER " + user); iWon = true; } } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Thanks for playing</title></head>"); out.println("<body bgcolor=\"white\">"); if (iWon) { out.println("<b>YOU GOT IT</b>"); // TODO - output HTML to play a sound file :-) } else { out.println("Thanks for playing, " + request.getRemoteAddr()); out.println(", but " + application.getAttribute(WINNER) + " buzzed in first"); } out.println("</body></html>"); } /** The Post method is used from an Administrator page (which should * only be installed in the instructor/host's localweb directory). * Post is used for administrative functions: * 1) to display the winner; * 2) to reset the buzzer for the next question. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext application = getServletContext(); response.setContentType("text/html"); HttpSession session = request.getSession(); PrintWriter out = response.getWriter(); if (request.isUserInRole("host")) { out.println("<html><head><title>Welcome back, " + request.getUserPrincipal().getName() + "</title><head>"); out.println("<body bgcolor=\"white\">"); String command = request.getParameter("command"); if (command.equals("reset")) { // Synchronize what you need, no more, no less. synchronized(application) { application.setAttribute(WINNER, null); } session.setAttribute("buzzin.message", "RESET"); } else if (command.equals("show")) { String winner = null; synchronized(application) { winner = (String)application.getAttribute(WINNER); } if (winner == null) { session.setAttribute("buzzin.message", "<b>No winner yet!</b>"); } else { session.setAttribute("buzzin.message", "<b>Winner is: </b>" + winner); } } else { session.setAttribute("buzzin.message", "ERROR: Command " + command + " invalid."); } RequestDispatcher rd = application.getRequestDispatcher( "/hosts/index.jsp"); rd.forward(request, response); } else { out.println("<html><head><title>Nice try, but... </title><head>"); out.println("<body bgcolor=\"white\">"); out.println( "I'm sorry, Dave, but you know I can't allow you to do that."); out.println("Even if you are " + request.getUserPrincipal()); } out.println("</body></html>"); } } // END main
mit
aekazakov/GrowthDataUtils
lib/src/growthdatautils/GrowthDataUtilsServer.java
5727
package growthdatautils; import java.io.File; import us.kbase.auth.AuthToken; import us.kbase.common.service.JsonServerMethod; import us.kbase.common.service.JsonServerServlet; import us.kbase.common.service.JsonServerSyslog; import us.kbase.common.service.RpcContext; //BEGIN_HEADER import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import us.kbase.common.service.Tuple11; import us.kbase.common.service.UObject; import us.kbase.kbaseenigmametals.GrowthMatrix; import us.kbase.kbaseenigmametals.MetadataProperties; import us.kbase.workspace.ObjectIdentity; import us.kbase.workspace.ObjectSaveData; import us.kbase.workspace.ProvenanceAction; import us.kbase.workspace.SaveObjectsParams; import us.kbase.workspace.WorkspaceClient; //END_HEADER /** * <p>Original spec-file module name: GrowthDataUtils</p> * <pre> * A KBase module: GrowthDataUtils * Growth Data Utilites. * </pre> */ public class GrowthDataUtilsServer extends JsonServerServlet { private static final long serialVersionUID = 1L; //BEGIN_CLASS_HEADER private final String wsUrl; //END_CLASS_HEADER public GrowthDataUtilsServer() throws Exception { super("GrowthDataUtils"); //BEGIN_CONSTRUCTOR wsUrl = config.get("workspace-url"); //END_CONSTRUCTOR } /** * <p>Original spec-file function name: group_replicates</p> * <pre> * Group replicates by samples, calculate average and stderr * </pre> * @param params instance of type {@link growthdatautils.GroupReplicatesParams GroupReplicatesParams} * @return instance of original type "growthmatrix_id" (A string representing a GrowthMatrix id.) */ @JsonServerMethod(rpc = "GrowthDataUtils.group_replicates", async=true) public String groupReplicates(GroupReplicatesParams params, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { String returnVal = null; //BEGIN group_replicates MetadataProperties.startup(); if (params.getWorkspace() == null) throw new IllegalStateException("Parameter workspace is not set in input arguments"); String workspaceName = params.getWorkspace(); if (params.getInputGrowthmatrixId() == null) throw new IllegalStateException("Parameter input_growthmatrix_id is not set in input arguments"); String inputGrowthMatrixId = params.getInputGrowthmatrixId(); if (params.getResultId() == null) throw new IllegalStateException("Parameter result_id is not set in input arguments"); String outputGrowthMatrixId = params.getResultId(); if (params.getStdDev() == null) throw new IllegalStateException("Parameter std_dev is not set in input arguments"); long calculateStdDev = params.getStdDev(); if ((calculateStdDev < 0)||(calculateStdDev < 1)) throw new IllegalStateException("std_dev parameter should be either 0 or 1 (" + calculateStdDev + ")"); if (params.getStdDev() == null) throw new IllegalStateException("Parameter std_dev is not set in input arguments"); long calculateStdErr = params.getStdErr(); if ((calculateStdErr < 0)||(calculateStdErr < 1)) throw new IllegalStateException("std_err parameter should be either 0 or 1 (" + calculateStdErr + ")"); WorkspaceClient wc = new WorkspaceClient(new URL(this.wsUrl), authPart); wc.setAuthAllowedForHttp(true); GrowthMatrix matrix; try { matrix = wc.getObjects(Arrays.asList(new ObjectIdentity().withRef( workspaceName + "/" + inputGrowthMatrixId))).get(0).getData().asClassInstance(GrowthMatrix.class); } catch (Exception ex) { throw new IllegalStateException("Error loading input GrowthMatrix object from workspace", ex); } System.out.println("Got GrowthMatrix data."); matrix=GrowthDataUtilsImpl.createStatValuesMatrix(matrix, calculateStdDev, calculateStdErr); matrix.setName(outputGrowthMatrixId); //Save resulting matrix Tuple11<Long, String, String, String, Long, String, Long, String, String, Long, Map<String,String>> info; try { info = wc.saveObjects(new SaveObjectsParams().withWorkspace(workspaceName) .withObjects(Arrays.asList(new ObjectSaveData() .withType("KBaseEnigmaMetals.GrowthMatrix").withName(outputGrowthMatrixId) .withData(new UObject(matrix)) .withProvenance((List<ProvenanceAction>)jsonRpcContext.getProvenance())))).get(0); } catch (Exception ex) { throw new IllegalStateException("Error saving output GrowthMatrix object to workspace", ex); } System.out.println("saved:" + info); //returnVal = info.getE7() + "/" + info.getE1() + "/" + info.getE5(); returnVal = info.getE2(); //END group_replicates return returnVal; } public static void main(String[] args) throws Exception { if (args.length == 1) { new GrowthDataUtilsServer().startupServer(Integer.parseInt(args[0])); } else if (args.length == 3) { JsonServerSyslog.setStaticUseSyslog(false); JsonServerSyslog.setStaticMlogFile(args[1] + ".log"); new GrowthDataUtilsServer().processRpcCall(new File(args[0]), new File(args[1]), args[2]); } else { System.out.println("Usage: <program> <server_port>"); System.out.println(" or: <program> <context_json_file> <output_json_file> <token>"); return; } } }
mit
puntopepe/SfogliaFilm
app/src/main/java/com/example/fab/android/sfogliafilm/Utility.java
6837
/* * The MIT License (MIT) * * Copyright (c) 2015 Fabrizio. * * 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.example.fab.android.sfogliafilm; import android.content.Intent; import android.net.Uri; import android.provider.CalendarContract; import android.util.Log; import com.example.fab.android.sfogliafilm.data.JSONApiTmdbSfogliaMovie; import com.example.fab.android.sfogliafilm.data.SfogliaFilmContract; import org.json.JSONException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Utility { private static final String LOG_TAG=Utility.class.getSimpleName(); protected static String getDevKey(){ return "aa1e7261d9475e8fdd21de02ee2f334b"; } public static boolean canFetchImages=false; static String setupTMDBConfigurationURL(){ Uri.Builder bulderBase = Uri.parse(JSONApiTmdbSfogliaMovie.TMDB_API_URL).buildUpon(); return bulderBase.appendPath("configuration"). appendQueryParameter("api_key", getDevKey()). build().toString(); } static boolean setupImagesConfiguration() { String configurationURL = setupTMDBConfigurationURL(); HttpURLConnection urlConnection = null; BufferedReader reader = null; String jsonConfiguration = ""; try { URL url = new URL(configurationURL); //Log.d(Utility.LOG_TAG, "GET / " + configurationURL); //Connection request urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); if (inputStream == null) { // Nothing to do. return false; } StringBuffer buffer = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { //pretty for DEBUG buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty return false; } else { //Log.d(Utility.LOG_TAG, "GET / " + buffer.length() + " Chars!"); jsonConfiguration = buffer.toString(); //Log.d(Utility.LOG_TAG, "CONTENT \n" + jsonConfiguration + " "); } } catch (IOException e) { Log.e(Utility.LOG_TAG, e.getMessage(), e); return false; } finally { if (urlConnection != null) { //CLOSE connection urlConnection.disconnect(); } if (reader != null) { //CLOSE stream try { reader.close(); } catch (final IOException e) { Log.e(Utility.LOG_TAG, "Error closing stream", e); } } } try { //Log.d(Utility.LOG_TAG, "getGeneralConfigurationFromJson"); JSONApiTmdbSfogliaMovie.getGeneralConfigurationFromJson(jsonConfiguration); } catch (JSONException e) { //error parsing Log.e(Utility.LOG_TAG, e.getMessage(), e); return false; } return true; } static Intent createSaveTheDateIntent(VideoDetailFragment currentVDF) { Intent saveTDIntent = new Intent(Intent.ACTION_INSERT); saveTDIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); //ritorna nella tua applicazione invece che in quella chiamata saveTDIntent.setType("vnd.android.cursor.item/event"); String title=""; if (currentVDF!=null) title=currentVDF.getMovieTitle(); String date=""; if (currentVDF!=null) date=currentVDF.getMovieDate(); String tmdbID=""; if (currentVDF!=null) tmdbID=currentVDF.getMovieId(); saveTDIntent.putExtra(CalendarContract.Events.TITLE, "Upcoming movie: " + title); saveTDIntent.putExtra(CalendarContract.Events.EVENT_LOCATION, "on screen"); saveTDIntent.putExtra(CalendarContract.Events.DESCRIPTION, title + " https://www.themoviedb.org/search?query=" + title.replace(' ', '+')); Date alDate ; try { alDate =new SimpleDateFormat(SfogliaFilmContract.DATE_FORMAT).parse(date); } catch (ParseException e) { //e.printStackTrace(); alDate=new Date(); } Calendar cal = Calendar.getInstance(); cal.setTime(alDate); saveTDIntent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true); saveTDIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, cal.getTimeInMillis()); saveTDIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, cal.getTimeInMillis()); saveTDIntent.putExtra(CalendarContract.Events.ACCESS_LEVEL, CalendarContract.Events.ACCESS_PRIVATE); saveTDIntent.putExtra(CalendarContract.Events.HAS_ALARM, 1); return saveTDIntent; } public static String strJoin(String[] aArr, String sSep) { StringBuilder sbStr = new StringBuilder(); int c=0; for (int i = 0, il = aArr.length; i < il; i++) { if (null!= aArr[i]) { if (c > 0) { sbStr.append(sSep); } sbStr.append(aArr[i]); c++; } } return sbStr.toString(); } }
mit
kveskimae/eazyfill
positional-order/src/test/java/ee/pdfarve/common/posorder/CandidatesComparatorTest.java
1079
package ee.pdfarve.common.posorder; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; public class CandidatesComparatorTest { private Node root; private CandidatesComparator comparator; @Before public void setUp() throws Exception { root = NodeTest.getRootInitializedWithTrainingData(); comparator = new CandidatesComparator(root); } @Test public void test() { LocationPointWithText candidate1 = new LocationPointWithText(313, 689, "123"); LocationPointWithText candidate2 = new LocationPointWithText(502, 166, "456"); LocationPointWithText candidate3 = new LocationPointWithText(113, 147, "789"); List<LocationPointWithText> candidates = new ArrayList<>(); candidates.add(candidate1); candidates.add(candidate2); candidates.add(candidate3); Collections.sort(candidates, comparator); assertEquals(candidates.get(0), candidate2); assertEquals(candidates.get(1), candidate3); assertEquals(candidates.get(2), candidate1); } }
mit
DDTH/ddth-queue
ddth-queue-core/src/test/java/com/github/ddth/queue/test/universal/idstr/rocksdb/TestRocksDbQueueMT.java
1678
package com.github.ddth.queue.test.universal.idstr.rocksdb; import com.github.ddth.queue.IQueue; import com.github.ddth.queue.impl.RocksDbQueue; import com.github.ddth.queue.impl.universal.idstr.UniversalRocksDbQueue; import com.github.ddth.queue.test.universal.BaseQueueMultiThreadsTest; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.io.FileUtils; import java.io.File; /* * mvn test -DskipTests=false -Dtest=com.github.ddth.queue.test.universal.idstr.rocksdb.TestRocksDbQueueMT -DenableTestsRocksDb=true */ public class TestRocksDbQueueMT extends BaseQueueMultiThreadsTest<String> { public TestRocksDbQueueMT(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestRocksDbQueueMT.class); } @Override protected IQueue<String, byte[]> initQueueInstance() throws Exception { if (System.getProperty("enableTestsRocksDb") == null && System.getProperty("enableTestsRocksDB") == null) { return null; } File tempDir = FileUtils.getTempDirectory(); File testDir = new File(tempDir, String.valueOf(System.currentTimeMillis())); RocksDbQueue<String, byte[]> queue = new UniversalRocksDbQueue() { public void destroy() { try { super.destroy(); } finally { FileUtils.deleteQuietly(testDir); } } }; queue.setStorageDir(testDir.getAbsolutePath()).setEphemeralDisabled(false).init(); return queue; } protected int numTestMessages() { return 512 * 1024; } }
mit
sel-utils/java
src/main/java/sul/protocol/bedrock137/play/InventorySlot.java
1123
/* * This file was automatically generated by sel-utils and * released under the MIT License. * * License: https://github.com/sel-project/sel-utils/blob/master/LICENSE * Repository: https://github.com/sel-project/sel-utils * Generated from https://github.com/sel-project/sel-utils/blob/master/xml/protocol/bedrock137.xml */ package sul.protocol.bedrock137.play; import sul.utils.*; public class InventorySlot extends Packet { public static final int ID = (int)50; public static final boolean CLIENTBOUND = true; public static final boolean SERVERBOUND = false; @Override public int getId() { return ID; } @Override public int length() { return 1; } @Override public byte[] encode() { this._buffer = new byte[this.length()]; this.writeVaruint(ID); return this.getBuffer(); } @Override public void decode(byte[] buffer) { this._buffer = buffer; this.readVaruint(); } public static InventorySlot fromBuffer(byte[] buffer) { InventorySlot ret = new InventorySlot(); ret.decode(buffer); return ret; } @Override public String toString() { return "InventorySlot()"; } }
mit
LiangMaYong/android-apkbox
apkbox/src/main/java/com/liangmayong/apkbox/core/manager/orm/ApkOrmModel.java
5047
/** The MIT License (MIT) Copyright (c) 2017 LiangMaYong ( ibeam@qq.com ) 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.liangmayong.apkbox.core.manager.orm; import android.os.Parcel; import android.os.Parcelable; /** * Created by LiangMaYong on 2017/4/12. */ public class ApkOrmModel implements Parcelable { public ApkOrmModel() { } private long id = 0; private String apkPath; private String apkPackageName = ""; private int apkVersionCode = 0; private String apkVersionName = ""; private String apkDescription = ""; private String apkSignture = ""; private String apkSha1 = ""; private int apkStatus = 1; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getApkPath() { return apkPath; } public void setApkPath(String apkPath) { this.apkPath = apkPath; } public String getApkPackageName() { return apkPackageName; } public void setApkPackageName(String apkPackageName) { this.apkPackageName = apkPackageName; } public int getApkVersionCode() { return apkVersionCode; } public void setApkVersionCode(int apkVersionCode) { this.apkVersionCode = apkVersionCode; } public String getApkVersionName() { return apkVersionName; } public void setApkVersionName(String apkVersionName) { this.apkVersionName = apkVersionName; } public String getApkDescription() { return apkDescription; } public void setApkDescription(String apkDescription) { this.apkDescription = apkDescription; } public String getApkSignture() { return apkSignture; } public void setApkSignture(String apkSignture) { this.apkSignture = apkSignture; } public String getApkSha1() { return apkSha1; } public void setApkSha1(String apkSha1) { this.apkSha1 = apkSha1; } public int getApkStatus() { return apkStatus; } public void setApkStatus(int apkStatus) { this.apkStatus = apkStatus; } @Override public String toString() { return "ApkOrmModel{" + "id=" + id + ", apkPath='" + apkPath + '\'' + ", apkPackageName='" + apkPackageName + '\'' + ", apkVersionCode=" + apkVersionCode + ", apkVersionName='" + apkVersionName + '\'' + ", apkDescription='" + apkDescription + '\'' + ", apkSignture='" + apkSignture + '\'' + ", apkSha1='" + apkSha1 + '\'' + ", apkStatus=" + apkStatus + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(this.id); dest.writeString(this.apkPath); dest.writeString(this.apkPackageName); dest.writeInt(this.apkVersionCode); dest.writeString(this.apkVersionName); dest.writeString(this.apkDescription); dest.writeString(this.apkSignture); dest.writeString(this.apkSha1); dest.writeInt(this.apkStatus); } protected ApkOrmModel(Parcel in) { this.id = in.readLong(); this.apkPath = in.readString(); this.apkPackageName = in.readString(); this.apkVersionCode = in.readInt(); this.apkVersionName = in.readString(); this.apkDescription = in.readString(); this.apkSignture = in.readString(); this.apkSha1 = in.readString(); this.apkStatus = in.readInt(); } public static final Creator<ApkOrmModel> CREATOR = new Creator<ApkOrmModel>() { @Override public ApkOrmModel createFromParcel(Parcel source) { return new ApkOrmModel(source); } @Override public ApkOrmModel[] newArray(int size) { return new ApkOrmModel[size]; } }; }
mit
BotMill/kik-botmill
src/main/java/co/aurasphere/botmill/kik/incoming/model/ReadReceiptMessage.java
1417
/* * * MIT License * * Copyright (c) 2016 BotMill.io * * 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 co.aurasphere.botmill.kik.incoming.model; /** * The Class ReadReceiptMessage. * * @author Alvin P. Reyes */ public class ReadReceiptMessage extends IncomingMessage { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; }
mit
HxCKDMS/HxCIssueServer
src/main/java/hxckdms/hxcissueserver/server/HxCIssueServer.java
2910
package hxckdms.hxcissueserver.server; import hxckdms.hxccore.crash.CrashSerializer; import hxckdms.hxcissueserver.github.GitHubReporter; import hxckdms.hxcissueserver.logging.Logger; import hxckdms.hxcissueserver.streams.CustomSysErrStream; import hxckdms.hxcissueserver.streams.CustomSysOutStream; import java.io.IOException; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Arrays; public class HxCIssueServer { public static Logger logger = new Logger("HxCIssueServer Logger", "HxCIssueBot_log"); static volatile boolean running = true; private static ServerSocket serverSocket; private static Socket connection; private static ObjectInputStream input; static volatile boolean isReceiving = false; public static String githubAuthenticationKey; public static void main(String[] args) throws IOException, ClassNotFoundException { System.setOut(new CustomSysOutStream(System.out)); System.setErr(new CustomSysErrStream(System.err)); if(args.length != 2){ logger.severe("Program doesn't accept less and more than 2 arguments [port] [github key]"); System.exit(-1); } int port = Integer.parseInt(args[0]); githubAuthenticationKey = args[1]; try{ serverSocket = new ServerSocket(port, 100); } catch (IOException e) { logger.severe("Failed to bind to port: " + port + ".", e); running = false; System.exit(1); } while(running) { try { isReceiving = false; waitForConnection(); isReceiving = true; setupInputStream(); whileReceivingCrash(); closeConnections(); } catch (IOException e) { e.printStackTrace(); logger.warning("connection lost.", e); } } } private static void waitForConnection() throws IOException{ logger.info("waiting..."); connection = serverSocket.accept(); logger.info("Connected to: " + connection.getInetAddress().getHostName()); } private static void setupInputStream() throws IOException{ input = new ObjectInputStream(connection.getInputStream()); logger.info("setting up streams done"); } private static void whileReceivingCrash() throws IOException, ClassNotFoundException { CrashSerializer crash = (CrashSerializer) input.readObject(); new GitHubReporter(new ArrayList<>(Arrays.asList(crash.crashString.split("\n"))), GitHubReporter.class.getSimpleName()).start(); } private static void closeConnections() throws IOException{ input.close(); connection.close(); logger.info("Closed all incoming connections."); } }
mit
tornaia/hr2
hr2-java-parent/hr2-backend-impl/src/main/java/hu/interconnect/hr/module/reports/vacation/VacationRowCreator.java
5471
package hu.interconnect.hr.module.reports.vacation; import static hu.interconnect.hr.backend.api.enumeration.FelhasznaltSzabadnapJelleg.APA_SZABADSAG; import static hu.interconnect.hr.backend.api.enumeration.FelhasznaltSzabadnapJelleg.BETEGSZABADSAG; import static hu.interconnect.hr.backend.api.enumeration.FelhasznaltSzabadnapJelleg.SZABADSAG; import static hu.interconnect.hr.backend.api.enumeration.FelhasznaltSzabadnapJelleg.TANULMANYI_SZABADSAG; import static hu.interconnect.hr.backend.api.enumeration.FelhasznaltSzabadnapJelleg.TEMETESI_SZABADSAG; import static hu.interconnect.util.DateUtils.getCalendar; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiFunction; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; import hu.interconnect.hr.dao.EvesSzabadsagAdatDAO; import hu.interconnect.hr.dao.SzabadsagDAO; import hu.interconnect.hr.dao.SzemelyitorzsDAO; import hu.interconnect.hr.domain.EvesSzabadsagAdat; import hu.interconnect.hr.domain.Szabadsag; import hu.interconnect.hr.domain.Szemelyitorzs; import hu.interconnect.hr.module.reports.NullValueToEmptyStringMap; import hu.interconnect.hr.security.AuthorityConstants; @Component public class VacationRowCreator { @Autowired private SzemelyitorzsDAO szemelyitorzsDAO; @Autowired private SzabadsagDAO szabadsagDAO; @Autowired private EvesSzabadsagAdatDAO evesSzabadsagAdatDAO; @PreAuthorize(AuthorityConstants.HAS_ROLE_BETEKINTO) public List<Map<String, Object>> eloallit(Date honap) { List<Szemelyitorzs> szemelyitorzsek = szemelyitorzsDAO.findOsszes(); return szemelyitorzsek .stream() .map(szemelyitorzs -> szemelyitorzsAndHonapToRow.apply(szemelyitorzs, honap)) .collect(Collectors.toList()); } private BiFunction<Szemelyitorzs, Date, Map<String, Object>> szemelyitorzsAndHonapToRow = new BiFunction<Szemelyitorzs, Date, Map<String, Object>>() { @Override public Map<String, Object> apply(Szemelyitorzs szemelyitorzs, Date honap) { NullValueToEmptyStringMap sor = new NullValueToEmptyStringMap(); sor.put("nev", szemelyitorzs.getTeljesNev()); List<Szabadsag> szabadsagok = szabadsagDAO.findBySzemelyitorzsEsAdottHaviIlletveAzelottiDeCsakAdottEviSzabadsagok(szemelyitorzs, honap); String szabadsagSzabadsagok = new SzabadsagExcelKivettSzabadnapMezotSzabadsagokbolEloallito(SZABADSAG, honap).apply(szabadsagok); sor.put("szabadsag_szabadsagok", szabadsagSzabadsagok); String betegSzabadsagok = new SzabadsagExcelKivettSzabadnapMezotSzabadsagokbolEloallito(BETEGSZABADSAG, honap).apply(szabadsagok); sor.put("betegszabadsag_szabadsagok", betegSzabadsagok); String temetesiSzabadsagSzabadsagok = new SzabadsagExcelKivettSzabadnapMezotSzabadsagokbolEloallito(TEMETESI_SZABADSAG, honap).apply(szabadsagok); sor.put("temetesi_szabadsag_szabadsagok", temetesiSzabadsagSzabadsagok); String apaSzabadsagSzabadsagok = new SzabadsagExcelKivettSzabadnapMezotSzabadsagokbolEloallito(APA_SZABADSAG, honap).apply(szabadsagok); sor.put("apa_szabadsag_szabadsagok", apaSzabadsagSzabadsagok); String tanulmanyiSzabadsagSzabadsagok = new SzabadsagExcelKivettSzabadnapMezotSzabadsagokbolEloallito(TANULMANYI_SZABADSAG, honap).apply(szabadsagok); sor.put("tanulmanyi_szabadsag_szabadsagok", tanulmanyiSzabadsagSzabadsagok); Optional<EvesSzabadsagAdat> optionalEvesSzabadsagAdat = evesSzabadsagAdatDAO.findBySzemelyitorzsEsEv(szemelyitorzs.getTsz(), getCalendar(honap).get(Calendar.YEAR)); if (optionalEvesSzabadsagAdat.isPresent()) { EvesSzabadsagAdat evesSzabadsagAdat = optionalEvesSzabadsagAdat.get(); int alapszabadsag = evesSzabadsagAdat.getAlapszabadsag(); int gyermekekUtan = evesSzabadsagAdat.getGyermekekUtan(); int fiatalkoru = evesSzabadsagAdat.getFiatalkoru(); int vakSzemely = evesSzabadsagAdat.getVakSzemely(); int egyebMunkakor = evesSzabadsagAdat.getEgyebMunkakor(); int ktKaPotszabadsag = evesSzabadsagAdat.getKtKaPotszabadsag(); int ktKaVezetoi = evesSzabadsagAdat.getKtKaVezetoi(); int egyebCsokkento = evesSzabadsagAdat.getEgyebCsokkento(); int tanulmanyi = evesSzabadsagAdat.getTanulmanyi(); int multEviSzabadsag = evesSzabadsagAdat.getMultEviSzabadsag(); int szabadsagNapOsszesen = alapszabadsag + gyermekekUtan + fiatalkoru + vakSzemely + egyebMunkakor + ktKaPotszabadsag + ktKaVezetoi - egyebCsokkento + tanulmanyi + multEviSzabadsag; int felhasznaltSzabadsagEsTanulmanyiSzabadsagokSzama = szabadsagDAO.findBySzemelyitorzsEsIdopontElottiDeAdottEviCsakSzabadsagEsTanulmanyiSzabadsagok(szemelyitorzs, honap).size(); int maradekSzabadsagAzAdottHonapVege = szabadsagNapOsszesen - felhasznaltSzabadsagEsTanulmanyiSzabadsagokSzama; sor.put("maradek_szabadsag_a_honap_vegen", maradekSzabadsagAzAdottHonapVege); } else { int felhasznaltSzabadsagEsTanulmanyiSzabadsagokSzama = szabadsagDAO.findBySzemelyitorzsEsIdopontElottiDeAdottEviCsakSzabadsagEsTanulmanyiSzabadsagok(szemelyitorzs, honap).size(); int maradekSzabadsagAzAdottHonapVege = 0 - felhasznaltSzabadsagEsTanulmanyiSzabadsagokSzama; sor.put("maradek_szabadsag_a_honap_vegen", maradekSzabadsagAzAdottHonapVege); } return sor.getMap(); } }; }
mit