repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Bysmyyr/chromium-crosswalk
chrome/android/java/src/org/chromium/chrome/browser/crash/MinidumpUploadService.java
16460
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.crash; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.StrictMode; import android.preference.PreferenceManager; import android.support.annotation.StringDef; import org.chromium.base.Log; import org.chromium.base.StreamUtil; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.preferences.ChromePreferenceManager; import org.chromium.chrome.browser.preferences.privacy.PrivacyPreferencesManager; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; /** * Service that is responsible for uploading crash minidumps to the Google crash server. */ public class MinidumpUploadService extends IntentService { private static final String TAG = "MinidmpUploadService"; // Intent actions private static final String ACTION_FIND_LAST = "com.google.android.apps.chrome.crash.ACTION_FIND_LAST"; @VisibleForTesting static final String ACTION_FIND_ALL = "com.google.android.apps.chrome.crash.ACTION_FIND_ALL"; @VisibleForTesting static final String ACTION_UPLOAD = "com.google.android.apps.chrome.crash.ACTION_UPLOAD"; // Intent bundle keys @VisibleForTesting static final String FILE_TO_UPLOAD_KEY = "minidump_file"; static final String UPLOAD_LOG_KEY = "upload_log"; static final String FINISHED_LOGCAT_EXTRACTION_KEY = "upload_extraction_completed"; /** * The number of times we will try to upload a crash. */ @VisibleForTesting static final int MAX_TRIES_ALLOWED = 3; /** * Histogram related constants. */ private static final String HISTOGRAM_NAME_PREFIX = "Tab.AndroidCrashUpload_"; private static final int HISTOGRAM_MAX = 2; private static final int FAILURE = 0; private static final int SUCCESS = 1; @StringDef({BROWSER, RENDERER, GPU, OTHER}) public @interface ProcessType {} static final String BROWSER = "Browser"; static final String RENDERER = "Renderer"; static final String GPU = "GPU"; static final String OTHER = "Other"; static final String[] TYPES = {BROWSER, RENDERER, GPU, OTHER}; public MinidumpUploadService() { super(TAG); setIntentRedelivery(true); } /** * Attempts to populate logcat dumps to be associated with the minidumps * if they do not already exists. */ private void tryPopulateLogcat(Intent redirectAction) { redirectAction.putExtra(FINISHED_LOGCAT_EXTRACTION_KEY, true); Context context = getApplicationContext(); CrashFileManager fileManager = new CrashFileManager(context.getCacheDir()); File[] dumps = fileManager.getMinidumpWithoutLogcat(); if (dumps.length == 0) { onHandleIntent(redirectAction); return; } context.startService(LogcatExtractionService.createLogcatExtractionTask( context, dumps, redirectAction)); } @Override public void onCreate() { super.onCreate(); if (isMinidumpCleanNeeded()) { // Temporarily allowing disk access while fixing. TODO: http://crbug.com/527429 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); try { final CrashFileManager crashFileManager = new CrashFileManager(getApplicationContext().getCacheDir()); // Cleaning minidumps in a background not to block the Ui thread. // NOTE: {@link CrashFileManager#cleanAllMiniDumps()} is not thread-safe and can // possibly result in race condition by calling from multiple threads. However, this // should only result in warning messages in logs. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { crashFileManager.cleanAllMiniDumps(); return null; } }.execute(); } finally { StrictMode.setThreadPolicy(oldPolicy); } } } @Override protected void onHandleIntent(Intent intent) { if (intent == null) return; if (!intent.getBooleanExtra(FINISHED_LOGCAT_EXTRACTION_KEY, false)) { // The current intent was sent before a chance to gather some // logcat information. tryPopulateLogcat will re-send the // same action once it has a go at gather logcat. tryPopulateLogcat(intent); } else if (ACTION_FIND_LAST.equals(intent.getAction())) { handleFindAndUploadLastCrash(intent); } else if (ACTION_FIND_ALL.equals(intent.getAction())) { handleFindAndUploadAllCrashes(); } else if (ACTION_UPLOAD.equals(intent.getAction())) { handleUploadCrash(intent); } else { Log.w(TAG, "Got unknown action from intent: " + intent.getAction()); } } /** * Creates an intent that when started will find the last created or * updated minidump, and try to upload it. * * @param context the context to use for the intent. * @return an Intent to use to start the service. */ public static Intent createFindAndUploadLastCrashIntent(Context context) { Intent intent = new Intent(context, MinidumpUploadService.class); intent.setAction(ACTION_FIND_LAST); return intent; } /** * Stores the successes and failures from uploading crash to UMA, */ public static void storeBreakpadUploadStatsInUma(ChromePreferenceManager pref) { for (String type : TYPES) { for (int success = pref.getCrashSuccessUploadCount(type); success > 0; success--) { RecordHistogram.recordEnumeratedHistogram( HISTOGRAM_NAME_PREFIX + type, SUCCESS, HISTOGRAM_MAX); } for (int fail = pref.getCrashFailureUploadCount(type); fail > 0; fail--) { RecordHistogram.recordEnumeratedHistogram( HISTOGRAM_NAME_PREFIX + type, FAILURE, HISTOGRAM_MAX); } pref.setCrashSuccessUploadCount(type, 0); pref.setCrashFailureUploadCount(type, 0); } } private void handleFindAndUploadLastCrash(Intent intent) { CrashFileManager fileManager = new CrashFileManager(getApplicationContext().getCacheDir()); File[] minidumpFiles = fileManager.getAllMinidumpFilesSorted(); if (minidumpFiles.length == 0) { // Try again later. Maybe the minidump hasn't finished being written. Log.d(TAG, "Could not find any crash dumps to upload"); return; } File minidumpFile = minidumpFiles[0]; File logfile = fileManager.getCrashUploadLogFile(); Intent uploadIntent = createUploadIntent(getApplicationContext(), minidumpFile, logfile); // We should have at least one chance to secure logcat to the minidump now. uploadIntent.putExtra(FINISHED_LOGCAT_EXTRACTION_KEY, true); startService(uploadIntent); } /** * Creates an intent that when started will find all minidumps, and try to upload them. * * @param context the context to use for the intent. * @return an Intent to use to start the service. */ @VisibleForTesting static Intent createFindAndUploadAllCrashesIntent(Context context) { Intent intent = new Intent(context, MinidumpUploadService.class); intent.setAction(ACTION_FIND_ALL); return intent; } private void handleFindAndUploadAllCrashes() { CrashFileManager fileManager = new CrashFileManager(getApplicationContext().getCacheDir()); File[] minidumps = fileManager.getAllMinidumpFiles(); File logfile = fileManager.getCrashUploadLogFile(); Log.i(TAG, "Attempting to upload accumulated crash dumps."); for (File minidump : minidumps) { Intent uploadIntent = createUploadIntent(getApplicationContext(), minidump, logfile); startService(uploadIntent); } } /** * Creates an intent that when started will find all minidumps, and try to upload them. * * @param minidumpFile the minidump file to upload. * @return an Intent to use to start the service. */ @VisibleForTesting public static Intent createUploadIntent(Context context, File minidumpFile, File logfile) { Intent intent = new Intent(context, MinidumpUploadService.class); intent.setAction(ACTION_UPLOAD); intent.putExtra(FILE_TO_UPLOAD_KEY, minidumpFile.getAbsolutePath()); intent.putExtra(UPLOAD_LOG_KEY, logfile.getAbsolutePath()); return intent; } private void handleUploadCrash(Intent intent) { String minidumpFileName = intent.getStringExtra(FILE_TO_UPLOAD_KEY); if (minidumpFileName == null || minidumpFileName.isEmpty()) { Log.w(TAG, "Cannot upload crash data since minidump is absent."); return; } File minidumpFile = new File(minidumpFileName); if (!minidumpFile.isFile()) { Log.w(TAG, "Cannot upload crash data since specified minidump " + minidumpFileName + " is not present."); return; } int tries = CrashFileManager.readAttemptNumber(minidumpFileName); // Since we do not rename a file after reaching max number of tries, // files that have maxed out tries will NOT reach this. if (tries >= MAX_TRIES_ALLOWED || tries < 0) { // Reachable only if the file naming is incorrect by current standard. // Thus we log an error instead of recording failure to UMA. Log.e(TAG, "Giving up on trying to upload " + minidumpFileName + " after failing to read a valid attempt number."); return; } String logfileName = intent.getStringExtra(UPLOAD_LOG_KEY); File logfile = new File(logfileName); // Try to upload minidump MinidumpUploadCallable minidumpUploadCallable = createMinidumpUploadCallable(minidumpFile, logfile); @MinidumpUploadCallable.MinidumpUploadStatus int uploadStatus = minidumpUploadCallable.call(); if (uploadStatus == MinidumpUploadCallable.UPLOAD_SUCCESS) { // Only update UMA stats if an intended and successful upload. incrementCrashSuccessUploadCount(getNewNameAfterSuccessfulUpload(minidumpFileName)); } else if (uploadStatus == MinidumpUploadCallable.UPLOAD_FAILURE) { // Unable to upload minidump. Incrementing try number and restarting. // Only create another attempt if we have successfully renamed // the file. String newName = CrashFileManager.tryIncrementAttemptNumber(minidumpFile); if (newName != null) { if (++tries < MAX_TRIES_ALLOWED) { // TODO(nyquist): Do this as an exponential backoff. MinidumpUploadRetry.scheduleRetry(getApplicationContext()); } else { // Only record failure to UMA after we have maxed out the allotted tries. incrementCrashFailureUploadCount(newName); Log.d(TAG, "Giving up on trying to upload " + minidumpFileName + "after " + tries + " number of tries."); } } else { Log.w(TAG, "Failed to rename minidump " + minidumpFileName); } } } private static String getNewNameAfterSuccessfulUpload(String fileName) { return fileName.replace("dmp", "up"); } @ProcessType @VisibleForTesting protected static String getCrashType(String fileName) { // Read file and get the line containing name="ptype". BufferedReader fileReader = null; try { fileReader = new BufferedReader(new FileReader(fileName)); String line; while ((line = fileReader.readLine()) != null) { if (line.equals("Content-Disposition: form-data; name=\"ptype\"")) { // Crash type is on the line after the next line. fileReader.readLine(); String crashType = fileReader.readLine(); if (crashType == null) { return OTHER; } if (crashType.equals("browser")) { return BROWSER; } if (crashType.equals("renderer")) { return RENDERER; } if (crashType.equals("gpu-process")) { return GPU; } return OTHER; } } } catch (IOException e) { Log.w(TAG, "Error while reading crash file.", e); } finally { StreamUtil.closeQuietly(fileReader); } return OTHER; } /** * Increment the count of success/failure by 1 and distinguish between different types of * crashes by looking into the file. * @param fileName is the name of a minidump file that contains the type of crash. */ private void incrementCrashSuccessUploadCount(String fileName) { ChromePreferenceManager.getInstance(this) .incrementCrashSuccessUploadCount(getCrashType(fileName)); } private void incrementCrashFailureUploadCount(String fileName) { ChromePreferenceManager.getInstance(this) .incrementCrashFailureUploadCount(getCrashType(fileName)); } /** * Factory method for creating minidump callables. * * This may be overridden for tests. * * @param minidumpFile the File to upload. * @param logfile the Log file to write to upon successful uploads. * @return a new MinidumpUploadCallable. */ @VisibleForTesting MinidumpUploadCallable createMinidumpUploadCallable(File minidumpFile, File logfile) { return new MinidumpUploadCallable(minidumpFile, logfile, getApplicationContext()); } /** * Attempts to upload all minidump files using the given {@link android.content.Context}. * * Note that this method is asynchronous. All that is guaranteed is that * upload attempts will be enqueued. * * This method is safe to call from the UI thread. * * @param context Context of the application. */ public static void tryUploadAllCrashDumps(Context context) { Intent findAndUploadAllCrashesIntent = createFindAndUploadAllCrashesIntent(context); context.startService(findAndUploadAllCrashesIntent); } /** * Checks whether it is the first time restrictions for cellular uploads should apply. Is used * to determine whether unsent crash uploads should be deleted which should happen only once. */ @VisibleForTesting protected boolean isMinidumpCleanNeeded() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // If cellular upload logic is enabled and the preference used for that is not initialized // then this is the first time that logic is enabled. boolean cleanNeeded = !sharedPreferences.contains(MinidumpUploadCallable.PREF_LAST_UPLOAD_DAY) && PrivacyPreferencesManager.getInstance(getApplicationContext()).isUploadLimited(); // Initialize the preference with default value to make sure the above check works only // once. if (cleanNeeded) { sharedPreferences.edit().putInt(MinidumpUploadCallable.PREF_LAST_UPLOAD_DAY, 0).apply(); } return cleanNeeded; } }
bsd-3-clause
CraftSpider/RecycleRush2015-340-cRIO
NetBeansProjects/RecycleRush2015-340-Backdate/src/edu/wpi/first/wpilibj/templates/commands/StackerGrabTote.java
3489
package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.templates.RobotMap; /** * Command to send the stacker arm to a specific position * @author Jakob W. */ public class StackerGrabTote extends CommandBase { private int target; private int tolerance; private int initDelta; private int start; private int currentPos; private double percent; private double speed; public StackerGrabTote(int tolerance) { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); requires(stacker); this.tolerance = tolerance; } // Called just before this Command runs the first time protected void initialize() { currentPos = stacker.getStackerPosition(); start = currentPos; if(currentPos < RobotMap.StackerGrabTote1Target){ target = RobotMap.StackerGrabTote1Target; }else if(currentPos < RobotMap.StackerGrabTote2Target){ target = RobotMap.StackerGrabTote2Target; }else if(currentPos < RobotMap.StackerGrabTote3Target){ target = RobotMap.StackerGrabTote3Target; }else{ target = RobotMap.StackerGrabTote4Target; } initDelta = target - start; percent = 0.1; speed = RobotMap.StackerMaxUpSpeed; } // Called repeatedly when this Command is scheduled to run protected void execute() { currentPos = stacker.getStackerPosition(); speed = RobotMap.StackerMaxUpSpeed; // checks to see if at position if ((Math.abs(currentPos) <= (Math.abs(target) + tolerance)) && (Math.abs(currentPos) >= Math.abs(target) - tolerance)) { stacker.stackerStopVertical(); speed = 0; } // Checks to see if we are within a percentage from the target position. else if ((Math.abs(currentPos) >= (Math.abs(target) - (Math.abs(initDelta) * percent)))) { speed = RobotMap.StackerMaxUpSpeed * 0.5; } // If the stacker is not close to or at the position the stacker moves moves at full speed. else{ speed = RobotMap.StackerMaxUpSpeed; } // current delta. int currDelta = target - currentPos; //if delta is positive then move up if(currDelta > 0 && !stacker.isStackerMax()){ stacker.stackerMoveUp(speed); } // if delta is negative move down. else if (currDelta < 0 && !stacker.isStackerMin()) { stacker.stackerMoveDown(speed); } // Tells the stacker to stop if it should not move up or down. else{ speed = 0; stacker.stackerStopVertical(); } System.out.println("[StackerGoToPosition: execute] slowed down before getting to position to stop:" + " currentPosVal: " + this.currentPos + "targetVal: " + this.target + "toleranceVal: " + this.tolerance + "initDeltaVal: " + this.initDelta + "percentVal: " + this.percent + "currDeltaVal: " + currDelta); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return ((stacker.getStackerPosition() > (target-tolerance)) && (stacker.getStackerPosition() < (target+tolerance)) || speed==0); } // Called once after isFinished returns true protected void end() { stacker.stackerStopVertical(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { stacker.stackerStopVertical(); } }
bsd-3-clause
codehaus/jbehave-git
jbehave-maven-plugin/src/main/java/org/jbehave/mojo/StepdocMojo.java
550
package org.jbehave.mojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.jbehave.core.StoryEmbedder; /** * Mojo to generate stepdocs * * @author Mauro Talevi * @goal stepdoc */ public class StepdocMojo extends AbstractStoryMojo { public void execute() throws MojoExecutionException, MojoFailureException { StoryEmbedder embedder = newStoryEmbedder(); embedder.useRunnerMonitor(new MavenRunnerMonitor()); embedder.generateStepdoc(); } }
bsd-3-clause
segengine/segeng
src/Seg.java
111408
package SegEngine.seg; /** * @file Seg.java * @author SegEngine * @date Sunday April 15 19:00:00 CST 2009 * @version 1.0.0 * @brief * **/ import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.concurrent.*; import org.apache.commons.lang.StringUtils; import englishseg.Seg_English; public class Seg{ /** * @param args */ // private static Log log = LogFactory.getLog(Seg.class); private Dic myDic; //!<dictionary private Viterbi myViterbi;//!<viterbi for pos tagging private Seg_English mySegEn;//!<for English tagging private String sen;//!<sentence to be segmented boolean findOrg; boolean findNsUnit; boolean verifyName; boolean findNewWord; boolean seg_English; private HashMap<TTreeNode, ArrayList<Float>> word2score;//!< score of each class private HashMap<TTreeNode, String> word2weight;//!< TFIDF weight private HashMap<String, Integer> newWord2fre; private ArrayList<WordInSen> words;//!< all words in current sentence private ArrayList<comp> compList;//!< all competition pairs in current sentence private HashMap<Integer, Integer> compCount;//!< competition number of each word private HashMap<String, nameInfo> name2fre;//!< new person name private float[] classScore; private String[] className = {"電子類", "體育類", "金融投資類", "汽車類", "教育類", "旅遊類", "醫療衛生", "時尚", "无法判断类别"}; private String[] notname = {"更"}; HashSet<String> enPos; private ArrayList<Term> segResult; private float[][] observeMatrix;//!< pos distribution matrix for current sentence /** * @brief constructor of Seg class * @param dic the dictionary used for segmentation */ public Seg(Dic dic) { this.seg_English = true; if (this.seg_English) { System.out.print("Loading English Segmentation Resources......"); this.mySegEn = new Seg_English(); System.out.println("Done"); } this.myDic = dic; this.myViterbi = new Viterbi(60, myDic.transMatrix); } /** * @brief reset all parameters used for segmenting new sentence s * @param s the sentence to be segmented */ private void reset(String s) { this.sen = new String(s); this.segResult = new ArrayList<Term>(); this.name2fre = new HashMap<String, nameInfo>(); this.newWord2fre = new HashMap<String, Integer>(); this.words = new ArrayList<WordInSen>(); this.compList = new ArrayList<comp>(); this.compCount = new HashMap<Integer, Integer>(); this.enPos = new HashSet<String>(); this.enPos.add("nx"); this.word2score = new HashMap<TTreeNode, ArrayList<Float>>(); this.word2weight = new HashMap<TTreeNode, String>(); this.word2weight.put(null, "0"); this.classScore = new float[8]; } /** * @brief find all legal words in the sentence and store them in the word set */ private void findAllWords(int findName, int findOrg, int findPlace) { this.words.clear(); int curIndex = 0; while (curIndex < this.sen.length()) { int k = this.words.size(); ArrayList<WordInSen> ws = null; // additional dictionary first ws = myDic.additional_word_dic.findMatchedWords(this.sen, curIndex); if (ws.size() == 0) { ws = myDic.word_dic.findMatchedWords(this.sen, curIndex); if (ws.size() == 0) { WordInSen word = new WordInSen(curIndex, 1, null); word.setPos("?"); this.words.add(word); } else { for (int i = 0; i < ws.size(); i++) { this.words.add(ws.get(i)); } } } else { for (int i = 0; i < ws.size(); i++) { this.words.add(ws.get(i)); } } if (-1 == findName) {//find name int len = 0; len = this.findCName(curIndex, this.sen.length()); if (len > 0) { int i = k; while (i < this.words.size() && this.words.get(i).getLen() != len) i++; if (i == this.words.size()) { WordInSen word = new WordInSen(curIndex, len, null); word.setPos("nrc"); this.words.add(word); } // else { // this.words.get(i).setPos("nrc"); // } } len = this.findJName(curIndex, this.sen.length()); if (len > 0) { int i = k; while (i < this.words.size() && this.words.get(i).getLen() != len) i++; if (i == this.words.size()) { WordInSen word = new WordInSen(curIndex, len, null); word.setPos("nrj"); this.words.add(word); } // else { // this.words.get(i).setPos("nrj"); // } } len = this.findWName(curIndex, this.sen.length()); if (len > 0) { int i = k; while (i < this.words.size() && this.words.get(i).getLen() != len) i++; if (i == this.words.size()) { WordInSen word = new WordInSen(curIndex, len, null); word.setPos("nrf"); this.words.add(word); } // else { // this.words.get(i).setPos("nrf"); // } } } if (-1 == findOrg) {//find organization name } if (-1 == findPlace) {//find place name } curIndex++; } } /** * @brief find all possible Chinese names in current sentence * @param index the start position to find possible Chinese name * @param endIndex the end position of current sentence * @return the length of Chinese name, 0 for find nothing */ private int findCName(int index, int endIndex) { int result = 0; if (index+2 > endIndex) return result; String s1 = sen.substring(index, index+1); TTreeNode n1 = this.myDic.word_dic.string2Node(s1); if (null != n1 && n1.isCHLastName()) { String s2 = sen.substring(index+1, index+2); TTreeNode n2 = this.myDic.word_dic.string2Node(s2); if (null != n2 && n2.isCH2ndName()) { result = 2; if (index+3 <= endIndex) { String s3 = sen.substring(index+2, index+3); TTreeNode n3 = this.myDic.word_dic.string2Node(s3); if (null != n3 && n3.isCH3rddName()) { result = 3; } } } else if (null != n2 && n2.isCHLastName() && index+4 <= endIndex) {//double last name String s3 = sen.substring(index+2, index+3); TTreeNode n3 = this.myDic.word_dic.string2Node(s3); String s4 = sen.substring(index+3, index+4); TTreeNode n4 = this.myDic.word_dic.string2Node(s4); if (null != n3 && n3.isCH2ndName() && null != n4 && n4.isCH3rddName()) result = 4; } } else if (index+3 <= endIndex){ s1 = sen.substring(index, index+2); n1 = this.myDic.word_dic.string2Node(s1); if (null != n1 && n1.isCHLastName()) { String s2 = sen.substring(index+2, index+3); TTreeNode n2 = this.myDic.word_dic.string2Node(s2); if (null != n2 && n2.isCH2ndName()) { result = 3; if (index+4 <= endIndex) { String s3 = sen.substring(index+3, index+4); TTreeNode n3 = this.myDic.word_dic.string2Node(s3); if (null != n3 && n3.isCH3rddName()) { result = 4; } } } } } return result; } /** * @brief find all possible Japanese names in current sentence * @param index the start position to find possible Japanese name * @param endIndex the end position of current sentence * @return the length of Japanese name, 0 for find nothing */ private int findJName(int index, int endIndex) { int result = 0; if (index+3 > endIndex) return result; String s1 = sen.substring(index, index+2); TTreeNode n1 = this.myDic.word_dic.string2Node(s1); if (null != n1 && n1.isJLastName()) { String s2 = sen.substring(index+2, index+3); TTreeNode n2 = this.myDic.word_dic.string2Node(s2); if (null != n2 && n2.isJ2ndName()) { result = 3; if (index+4 <= endIndex) { String s3 = sen.substring(index+3, index+4); TTreeNode n3 = this.myDic.word_dic.string2Node(s3); if (null != n3 && n3.isJ3rdName()) { result = 4; if (index+5 <= endIndex) { String s4 = sen.substring(index+4, index+5); TTreeNode n4 = this.myDic.word_dic.string2Node(s4); if (null != n4 && n4.isJ4thName()) { result = 5; } } } } } } return result; } /** * @brief find all possible west names in current sentence * @param index the start position to find possible west name * @param endIndex the end position of current sentence * @return the length of west name, 0 for find nothing */ private int findWName(int index, int endIndex) { int result = 0; if (index+2 > endIndex) return result; String s1 = sen.substring(index, index+1); TTreeNode n1 = this.myDic.word_dic.string2Node(s1); if (null != n1 && n1.isWest1stName()) { result++; s1 = sen.substring(index+result, index+result+1); n1 = this.myDic.word_dic.string2Node(s1); while(null != n1 && n1.isWestFollowName()) { result++; if (index+result == endIndex) break; s1 = sen.substring(index+result, index+result+1); n1 = this.myDic.word_dic.string2Node(s1); } } if (result > 1) return result; result = 0; if (index+3 > endIndex) return result; s1 = sen.substring(index, index+2); n1 = this.myDic.word_dic.string2Node(s1); if (null != n1 && n1.isWest1stName()) { result += 2; s1 = sen.substring(index+result, index+result+1); n1 = this.myDic.word_dic.string2Node(s1); while(null != n1 && n1.isWestFollowName()) { result++; if (index+result == endIndex) break; s1 = sen.substring(index+result, index+result+1); n1 = this.myDic.word_dic.string2Node(s1); } } if (result > 2) return result; return 0; } /** * @brief show all words found by "findAllWords", this function is only used for debugging */ private void showAllWords() { System.out.println(this.sen); for (WordInSen word : this.words) { System.out.println(this.sen.substring(word.getBegin(), word.getBegin() + word.getLen())); } } /** * @brief find all word pair that conflict with each other */ private void findCompetition() { this.compList.clear(); this.compCount.clear(); for (int i = 0; i < this.words.size(); i++) { WordInSen w1 = this.words.get(i); TTreeNode n1 = w1.getNode(); // if (n1 != null && n1.isCH3rddName()) continue; int end1 = w1.getBegin() + w1.getLen(); // String s1 = this.sen.substring(w1.getBegin(), end1);//!<for debug if (!w1.isSelected()) continue; for (int j = i + 1; j < this.words.size(); j++) { WordInSen w2 = this.words.get(j); TTreeNode n2 = w2.getNode(); // if (n2 != null && n2.isCHLastName()) continue; int end2 = w2.getBegin() + w2.getLen(); // String s2 = this.sen.substring(w2.getBegin(), end2); if (!w2.isSelected()) continue; if (end1 <= w2.getBegin()) break; //!< later word cover former word that has only one or two characters if (w1.getBegin() == w2.getBegin() // && w1.getLen() == 1 && (w1.getLen() == 1 || w1.getLen() == 2) // && !n1.isStrongWord() // && !n1.isStrongPrefix() // && !n1.isTimeEnd() ) { w1.setSelected(false); break; } //!< former word cover later word that has only one character // else if (w1.getLen() != 1 && w2.getLen() == 1 ) { // w2.setSelected(false); // continue; // } else if (w1.getBegin() < w2.getBegin() && end1 >= end2 && w2.getLen() <= 2) { w2.setSelected(false); continue; } else if (end1 > w2.getBegin()) { if (end1 >= end2 && n1 != null && (n1.isHierarchical() || //!< has hierarchical segmentation n1.hasCode() || //!< has code 1 == w2.getLen() || //!<has only one character n1.isLongWord())) {//!< long word w2.setSelected(false); } else if (n1 != null && !n1.isStrongWord() && (w1.getBegin() == w2.getBegin() && w1.getLen() < w2.getLen() && n2 != null && (n2.isHierarchical() || //!< has hierarchical segmentation n2.hasCode() || //!< has code n2.isLongWord()))) {//!< long word w1.setSelected(false); break; } else { this.compList.add(new comp(i, j)); int count; if (this.compCount.containsKey(i)) { count = this.compCount.get(i) + 1; this.compCount.put(i, count); } else this.compCount.put(i, 1); if (this.compCount.containsKey(j)) { count = this.compCount.get(j) + 1; this.compCount.put(j, count); } else this.compCount.put(j, 1); } } } } } /** * @brief show all competitions that are found by "findCompetition", this function is used * only for debugging */ private void showAllComps() { System.out.println(this.sen); for (comp c : this.compList) { WordInSen w = this.words.get(c.i); String s1 = this.sen.substring(w.getBegin(), w.getBegin() + w.getLen()); w = this.words.get(c.j); String s2 = this.sen.substring(w.getBegin(), w.getBegin() + w.getLen()); System.out.println(s1 + "|" + s2); } } /** * @brief find the winner of each conflicting pair */ private void solveComp() { for (comp c : this.compList) { WordInSen w1 = this.words.get(c.i); int end1 = w1.getBegin() + w1.getLen(); String s1 = this.sen.substring(w1.getBegin(), end1); WordInSen w2 = this.words.get(c.j); int end2 = w2.getBegin() + w2.getLen(); String s2 = this.sen.substring(w2.getBegin(), end2); TTreeNode n1, n2; n1 = w1.getNode(); n2 = w2.getNode(); if (!w1.isSelected() && !w2.isSelected()) continue; else if (!w1.isSelected() && w2.isSelected()) { int count = this.compCount.get(c.j) - 1; this.compCount.put(c.j, count); continue; } else if (w1.isSelected() && !w2.isSelected()) { int count = this.compCount.get(c.i) - 1; this.compCount.put(c.i, count); continue; } if (n1 != null && n1.isAWord()) { w2.setSelected(false); int count = this.compCount.get(c.j) + 1; this.compCount.put(c.j, count); count = this.compCount.get(c.i) - 1; this.compCount.put(c.i, count); continue; } else if (n2 != null && n2.isAWord()) { w1.setSelected(false); int count = this.compCount.get(c.i) + 1; this.compCount.put(c.i, count); count = this.compCount.get(c.j) - 1; this.compCount.put(c.j, count); continue; } //!< simple conflict examination String conf = s1 + "|" + s2; boolean b1 = false, b2 = false; TTreeNode confN = myDic.conf_dic.string2Node(conf); if (confN != null) {// String winner = confN.weight; if (winner.compareTo("0") == 0) { w2.setSelected(false); w1.setSelected(true); } else { w1.setSelected(false); w2.setSelected(true); } continue; } // // conflict number examination if (this.compCount.get(c.i) > this.compCount.get(c.j)) { w1.setSelected(false); int count = this.compCount.get(c.i) + 1; this.compCount.put(c.i, count); count = this.compCount.get(c.j) - 1; this.compCount.put(c.j, count); continue; } else if (this.compCount.get(c.i) < this.compCount.get(c.j)) { w2.setSelected(false); int count = this.compCount.get(c.j) + 1; this.compCount.put(c.j, count); count = this.compCount.get(c.i) - 1; this.compCount.put(c.i, count); continue; } else if (n1 != null && n1.isOrgName() && n2 != null && !n2.isOrgName()) { w2.setSelected(false); int count = this.compCount.get(c.j) + 1; this.compCount.put(c.j, count); count = this.compCount.get(c.i) - 1; this.compCount.put(c.i, count); continue; } else if (n1 != null && !n1.isOrgName() && n2 != null && n2.isOrgName()) { w1.setSelected(false); int count = this.compCount.get(c.i) + 1; this.compCount.put(c.i, count); count = this.compCount.get(c.j) - 1; this.compCount.put(c.j, count); continue; } else if (w1.getBegin() < w2.getBegin() && end1 < end2) {//!<交叉型 String s11 = this.sen .substring(w1.getBegin(), w2.getBegin()); String s21 = this.sen.substring(end1, end2); TTreeNode n11 = myDic.word_dic.string2Node(s11); TTreeNode n21 = myDic.word_dic.string2Node(s21); if (n11 == null && n21 != null) { w2.setSelected(false); continue; } else if (n11 != null && n21 == null) { w1.setSelected(false); continue; } else if (n11 != null && n21 != null) { if (n21.isStrongSuffix()) { w2.setSelected(false); continue; } if (n11.isStrongPrefix()) { w1.setSelected(false); continue; } if (n21.isStrongWord()) { w2.setSelected(false); continue; } if (n11.isStrongWord()) { w1.setSelected(false); continue; } if (n21.isM()) { w2.setSelected(false); continue; } if (n11.isM()) { w1.setSelected(false); continue; } // if (w1.getLen() == 3 && w2.getLen() == 2 && // end1-w2.getBegin() == 1) { // w1.setSelected(false); // continue; // } if (w1.getLen() * s21.length() < w2.getLen() * s11.length()) { w1.setSelected(false); continue; } int f1 = n11.fre; int f2 = n21.fre; if (f1 > f2) { w1.setSelected(false); continue; } else if (f1 < f2) { w2.setSelected(false); continue; } int score1 = 0; int score2 = 0; if (n11.isStrongWord()) score1 += 2; if (n11.isVerbOrTime()) score1 += 1; if (n21.isStrongWord()) score2 += 2; if (n21.isVerbOrTime()) score2 += 1; if (score1 > score2) { w1.setSelected(false); continue; } if (score1 < score2) { w2.setSelected(false); continue; } if (s11.length() > s21.length()) { w1.setSelected(false); continue; } else if (s11.length() < s21.length()) { w2.setSelected(false); continue; } // else if (f1 > f2) { // w1.setSelected(false); // continue; // } else if (f1 < f2) { // w2.setSelected(false); // continue; // } } } //!< organization examination if (n1 != null && ((n1.flag & Const.IS_HIERARCHICAL) != 0 || (n1.flag & Const.HAS_CODE) != 0) && (n2 == null || (n2.flag & Const.IS_HIERARCHICAL) == 0 && (n2.flag & Const.HAS_CODE) == 0)) { w2.setSelected(false); continue; } else if (n2 != null && ((n2.flag & Const.IS_HIERARCHICAL) != 0 || (n2.flag & Const.HAS_CODE) != 0) && (n1 == null || (n1.flag & Const.IS_HIERARCHICAL) == 0 && (n1.flag & Const.HAS_CODE) == 0)) { w1.setSelected(false); continue; } //!< recent word examination // if (this.isRecentWord(n1) && !this.isRecentWord(n2)) { // w2.setSelected(false); // continue; // } else if (!this.isRecentWord(n1) && this.isRecentWord(n2)) { // w1.setSelected(false); // continue; // } //!< inclusion examination if (w1.getBegin() <= w2.getBegin() && w1.getBegin() + w1.getLen() >= w2.getBegin() + w2.getLen()) { w2.setSelected(false); continue; } else if (w1.getBegin() >= w2.getBegin() && w1.getBegin() + w1.getLen() <= w2.getBegin() + w2.getLen()) { w1.setSelected(false); continue; } //!< simple/complex conflict examination confN = myDic.conf_dic.string2Node(conf); if (confN != null) {//!< simple conflict String winner = confN.weight; if (winner.compareTo("0") == 0) { w2.setSelected(false); } else { w1.setSelected(false); } } else {//!< complex conflict //!< w1 if (!myDic.conf_next_list.keySet().contains(n1)) w1.setSelected(false); else { b1 = true; int begin = w1.getBegin() + w1.getLen(); boolean found = false; ArrayList<TTreeNode> nextList = myDic.conf_next_list.get(n1); //!< compare and find common for (WordInSen word : this.words) {//!< all next words if (begin != word.getBegin()) continue; TTreeNode node = word.getNode(); for (TTreeNode n : nextList) { if (node == n) found = true; } } if (!found) w1.setSelected(false); } //!< w2 if (!myDic.conf_pre_list.keySet().contains(n2)) w2.setSelected(false); else { b2 = true; boolean found = false; ArrayList<TTreeNode> preList = myDic.conf_pre_list.get(n2); //!< compare and find common for (WordInSen word : this.words) {//!< all next words int end = word.getBegin() + word.getLen(); if (end != w2.getBegin()) continue; TTreeNode node = word.getNode(); for (TTreeNode n : preList) { if (node == n) found = true; } } if (!found) w2.setSelected(false); } } } } /** * @brief show all the words survived after competition, this function is only used for debugging */ private void showAllLeftWords() { System.out.println(this.sen); for (WordInSen word : this.words) { if (word.isSelected()) { System.out.print(this.sen.substring(word.getBegin(), word .getBegin() + word.getLen()) + " "); } } System.out.println(); } /** * @brief reorganize word after competition and form final segmentation result */ private void getResult() { int begin = 0; int preWordIndex = -1; boolean needNewWord = false; //!< for (WordInSen word: this.words) { for (int j = 0; j < this.words.size(); j++) { WordInSen word = this.words.get(j); if (!word.isSelected()) continue;//!< loser, skip if (word.getBegin() == begin) {//!< winner, select begin += word.getLen(); preWordIndex = j; continue; } else if (word.getBegin() < begin) { word.setSelected(false); continue; } else {// word.getBegin() > begin needNewWord = true; if (preWordIndex != -1) { int k = preWordIndex + 1; for (; k < j; k++) { if (this.words.get(k).getBegin() > this.words.get( preWordIndex).getBegin()) break; if (this.words.get(k).getBegin() == this.words.get( preWordIndex).getBegin() && (this.words.get(k).getBegin() + this.words .get(k).getLen()) == word.getBegin()) { this.words.get(k).setSelected(true); this.words.get(preWordIndex).setSelected(false); needNewWord = false; } } } } //!< empty position that need to be filled // System.out.println("++++++++++++"+begin); // word.getBegin()>begin if (needNewWord) { int b = begin; int dis = word.getBegin() - b; int smallIndex; // if (preWordIndex == -1) // smallIndex = -1; // else smallIndex = preWordIndex; while (b < word.getBegin()) { boolean found = false; for (int i = j - 1; i > smallIndex; i--) { if (this.words.get(i).getBegin() == b && this.words.get(i).getLen() <= dis) { this.words.get(i).setSelected(true); b += this.words.get(i).getLen(); dis -= this.words.get(i).getLen(); smallIndex = i; found = true; break; } } if (!found) { this.words.get(smallIndex+1).setBegin(b); this.words.get(smallIndex+1).setLen(1); this.words.get(smallIndex+1).setNode(null); this.words.get(smallIndex+1).setPos("?"); this.words.get(smallIndex+1).setSelected(true); b++; dis--; smallIndex++; } } needNewWord = false; } begin = word.getBegin() + word.getLen(); } // System.out.println("_________"+begin); while (begin < this.sen.length()) { for (int i = this.words.size() - 1; i >= 0; i--) { if (this.words.get(i).getBegin() == begin) { this.words.get(i).setSelected(true); // System.out.println("<<<"+begin); // System.out.println(this.sen.substring(begin, // begin+this.words.get(i).getLen())); // System.out.println(">>>"); begin += this.words.get(i).getLen(); break; } } } for (int j = 0; j < this.words.size(); j++) { WordInSen word = this.words.get(j); TTreeNode n = word.getNode(); if (!word.isSelected() || n == null) continue;// if (this.word2score.containsKey(n)) { int i = 0; for (float d: this.word2score.get(n)) { this.classScore[i++] += d; } } } } /** * @brief combine digital, English letters and time end */ private void comb1() { String pos = null; int len = 0; ArrayList<Integer> saves = new ArrayList<Integer>(); for (int i = 0; i < this.words.size(); i++) { WordInSen w = this.words.get(i); if (!w.isSelected()) continue; TTreeNode n = w.getNode(); if (pos == null) { if (n != null && n.isM()) { pos = "m"; len = w.getLen(); saves.add(i); } else if (n != null && n.isNX()) { pos = "nx"; len = w.getLen(); saves.add(i); } } else if (pos.compareTo("m") == 0) { if (n != null && n.isM()) { len += w.getLen(); saves.add(i); } else if (n != null && n.isNX()) { pos = "nx"; len += w.getLen(); saves.add(i); } else { if (n != null && n.isTimeEnd()) { pos = "t"; len += w.getLen(); w.setSelected(false); this.words.get(saves.get(0)).setNode(null); } else if (n != null && n.isQ() && !(len == 1 && (this.sen.charAt(this.words.get(saves.get(0)).getBegin()) == '/' || this.sen.charAt(this.words.get(saves.get(0)).getBegin()) == '许' || this.sen.charAt(this.words.get(saves.get(0)).getBegin()) == '之'))) { pos = "mq"; len += w.getLen(); w.setSelected(false); this.words.get(saves.get(0)).setNode(null); } WordInSen w1 = this.words.get(saves.get(0)); if (saves.size() > 1 && this.sen.charAt(this.words.get(saves.get(saves.size()-1)).getBegin()) == '又') { saves.remove(saves.size()-1); len--; } w1.setLen(len); if (len > 1) w1.setPos(pos); if (saves.size() > 1) this.words.get(saves.get(0)).setNode(null); for (int j = 1; j < saves.size(); j++) { this.words.get(saves.get(j)).setSelected(false); } saves.clear(); pos = null; len = 0; } } else {//!<"nx" if (n != null && (n.isM() || n.isNX() || w.getLen() == 1 && this.sen.charAt(w.getBegin()) == '-')) { len += w.getLen(); saves.add(i); } else { WordInSen w1 = this.words.get(saves.get(0)); w1.setLen(len); w1.setPos(pos); for (int j = 1; j < saves.size(); j++) { this.words.get(saves.get(j)).setSelected(false); } saves.clear(); pos = null; len = 0; } } } if (pos != null) { WordInSen w1 = this.words.get(saves.get(0)); w1.setLen(len); if (len > 1) w1.setPos(pos); for (int j = 1; j < saves.size(); j++) { this.words.get(saves.get(j)).setSelected(false); } } } /** * @brief check whether the last name and its following character match */ private boolean checkMatch(TTreeNode n1, TTreeNode n2) { if (n1 == null || n2 == null) return true; if (myDic.not_match_name_list.containsKey(n2) && myDic.not_match_name_list.get(n2).contains(n1)) return false; return true; } /** * @brief name recognition module * @param result segmentation result */ private void findName(ArrayList<WordInSen> result) { if (result == null) return; result.clear(); ArrayList<WordInSen> saves = new ArrayList<WordInSen>(); int nameLen = 0; int nameBegin = 0; long flag = 0; int leftLen = 0; WordInSen name = null;//!<possible three-letter Chinese name WordInSen containName = null;//!<word that starts with Chinese last name boolean floatLast = false; TTreeNode c1Node = null; WordInSen w; // for (WordInSen w : this.words) { for (int wIndex = 0; wIndex < this.words.size(); wIndex++) { w = this.words.get(wIndex); if (!w.isSelected()) continue; TTreeNode n = w.getNode(); if (flag == 0) { if (n == null) { result.add(w); continue; } if (n.isNamePrefix()) { // for (WordInSen w1: saves) result.add(w1); // saves.clear(); flag = Const.IS_NAME_PREFIX; saves.add(w); } else if (n.isCHLastName()) { // for (WordInSen w1: saves) result.add(w1); // saves.clear(); flag = Const.IS_CH_LASTNAME; c1Node = n; saves.add(w); leftLen = 2; } else if (n.isJLastName()) { // for (WordInSen w1: saves) result.add(w1); // saves.clear(); flag = Const.IS_J_LASTNAME; saves.add(w); leftLen = 3; c1Node = n; } else if (n.isWest1stName() || (n.isName()&&w.getLen()>3)) { nameBegin = w.getBegin(); nameLen = w.getLen(); flag = Const.IS_WEST_1_NAME; c1Node = n; name = w;//!<start of west name } else if (n.isSingleName()) { // } else if (this.isSingleName(w)) { for (WordInSen w1 : saves) result.add(w1); saves.clear(); flag = Const.IS_CH_LASTNAME; saves.add(w); c1Node = n; leftLen = 1; } else { //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); // } } else if (flag == Const.IS_WEST_1_NAME) { if ( n == null && w.getPos() == null || n != null && n.isWestFollowName() || n != null && n.isWest1stName() || n != null && (n.isWest1stName() && w.getLen() > 1) // || n != null && (n.isWest1stName() && w.getLen() > 1) ) { if (c1Node == null) {//!<not close to the start word, no matching examination required nameLen += w.getLen(); name = null; } else { if (this.checkMatch(c1Node, n)) {//!<closely following the start word, matching examination is required nameLen += w.getLen(); name = null; } else { result.add(name); name = null; flag = 0; nameLen = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); // } c1Node = null; } } else { if (name == null) {//!<word sequence existing WordInSen newWord = new WordInSen(nameBegin, nameLen, null); newWord.setPos("nrf"); result.add(newWord); } else {//!<only start word result.add(name); name = null; } flag = 0; nameBegin = 0; nameLen = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } } else if (flag == Const.IS_NAME_PREFIX) {//!< pre+ch_l if (n != null && n.isCHLastName()) { WordInSen newWord = new WordInSen(saves.get(0).getBegin(), saves.get(0).getLen() + w.getLen(), null); newWord.setPos("nrcl"); result.add(newWord); flag = 0; saves.clear(); } else { result.add(saves.get(0)); saves.clear(); flag = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } } else if (flag == Const.IS_CH_LASTNAME) { if (n == null) {//!<word not in dictionary, end the recognizing process if (containName != null) { int index = result.size() - 1; result.set(index, containName); containName = null; } else if (saves.size() == 1) {//!<only one word in saves if (name == null) {//!<no optional name result.add(saves.get(0)); } else {//!<optional name exist (last name in saves is wrong) int index = result.size() - 1; result.set(index, name); name = null; } } else {//!<multiple elements in saves int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0).getBegin(), len, null); if (saves.size() == 2 && saves.get(1).getNode().notName())//!<e.g. “刘家” newWord.setPos("n"); else newWord.setPos("nrc"); result.add(newWord); } saves.clear(); flag = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } else if ((!n.isCH2ndName()&&!n.isCH3rddName()&&!n.isName()) &&n.isJLastName()) {//!<Japanese last name if (containName != null) {//!<e.g. "和黄" int index = result.size() - 1; result.set(index, containName); containName = null; } else if (saves.size() == 1) {//!<only one element in saves if (name == null) {//!<no optional names result.add(saves.get(0)); } else {//!<optional name exist, e.g. “王国林”,王国is a word,林is a last name, //!<“王国” in saves,“王国林”exist in name as optional names int index = result.size() - 1; result.set(index, name); name = null; } } else {//!<multiple elements in saves int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0).getBegin(), len, null); if (saves.size() == 2 && saves.get(1).getNode().notName()) newWord.setPos("n");//!<e.g. 张家、李家 etc. else newWord.setPos("nrc"); result.add(newWord); } saves.clear(); flag = Const.IS_J_LASTNAME; saves.add(w); leftLen = 3; }else if ((!n.isCH2ndName()&&!n.isCH3rddName()&&!n.isName()) &&(n.isWest1stName() || (n.isName()&&w.getLen()>2))) { //!<see explanation in Japanese name processing if (containName != null) { int index = result.size() - 1; result.set(index, containName); containName = null; } else if (saves.size() == 1) {//!< if (name == null) { result.add(saves.get(0)); } else { int index = result.size() - 1; result.set(index, name); name = null; } } else { int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0).getBegin(), len, null); if (saves.size() == 2 && saves.get(1).getNode().notName()) newWord.setPos("n"); else newWord.setPos("nrc"); result.add(newWord); } saves.clear(); nameBegin = w.getBegin(); nameLen = w.getLen(); flag = Const.IS_WEST_1_NAME; c1Node = n; name = w; } else if (w.getLen() != 1) {//!< double letter word c1Node = null; if (w.getLen() == leftLen) {//!< double letter word with single last name: ch_1+ch_23 // String str1 = this.sen.substring(w.getBegin(), w // .getBegin() + 1); // String str2 = this.sen.substring(w.getBegin() + 1, w // .getBegin() + 2); // TTreeNode node1 = this.word_dic.string2Node(str1); // TTreeNode node2 = this.word_dic.string2Node(str2); if (n != null && n.isNameSuffix()) {//!< name suffix if (name == null) {//!<e.g. 王某 WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), saves.get(0).getLen() + leftLen, null); newWord.setPos("nrcr"); result.add(newWord); floatLast = false; saves.clear(); flag = 0; leftLen = 0; containName = null; } else {//!<e.g. 王茂林大爷 saves.clear(); int index = result.size() - 1; result.set(index, name); name = null; flag = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } } // else if (n != null && n.isName() && !(n.isAfterName())) {//!<name with two letters, e.g. 桂花 else if (n != null && n.isName() && !(n.isAfterName() && (name != null || (result.size() > 0 && result.get(result.size()-1).getLen() == 2 && (result.get(result.size()-1).getPos() != null && result.get(result.size()-1).getPos().startsWith("nr") || result.get(result.size()-1).getNode() != null && result.get(result.size()-1).getNode().isOriginName()) || saves.size() > 0 && saves.get(saves.size()-1).getLen() == 2 && saves.get(saves.size()-1).getPos() != null && saves.get(saves.size()-1).getPos().startsWith("nrc"))))) {//!<name with two letters, e.g. 桂花 WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), saves.get(0).getLen() + leftLen, null); newWord.setPos("nrc"); result.add(newWord); floatLast = false; saves.clear(); flag = 0; leftLen = 0; name = null; containName = null; } else {//!< not name if (containName != null) { int index = result.size() - 1; result.set(index, containName); containName = null; } else if (name != null) { int index = result.size() - 1; result.set(index, name); name = null; } else result.add(saves.get(0)); saves.clear(); flag = 0; leftLen = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } } else {//!< word with more then 3 letters or leftLen == 1 if (containName != null) { int index = result.size() - 1; result.set(index, containName); containName = null; } else if (name != null) { int index = result.size() - 1; result.set(index, name); saves.clear(); name = null; } else if (saves.size() == 1) {//!< single name result.add(saves.get(0)); saves.clear(); } else {//!< ch_l+ch_2 WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), saves.get(0).getLen() + saves.get(1).getLen(), null); if (saves.size() == 2 && saves.get(1).getNode().notName()) newWord.setPos("n"); else newWord.setPos("nrc"); result.add(newWord); saves.clear(); } floatLast = false; flag = 0; name = null; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } } //!< single letter word else if (leftLen == 2) {//!< only ch_l if (n.isNameSuffix() && name == null) {//!<name suffix WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), saves.get(0).getLen() + w.getLen(), null); newWord.setPos("nrcr"); result.add(newWord); floatLast = false; saves.clear(); flag = 0; leftLen = 0; name = null; containName = null; } else if (n.isCHLastName() && floatLast) { WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), saves.get(0).getLen(), null); newWord.setPos("nrc"); result.add(newWord); floatLast = false; saves.clear(); c1Node = n; saves.add(w); leftLen = 2; name = null; } else if (n.isCHLastName() && !floatLast && this.checkMatch(c1Node, n) || (n.isCH2ndName() && this.checkMatch(c1Node, n)) || (floatLast && n.isCH3rddName())) {//!<second letter matching c1Node = n; if (n.isCHLastName() && !floatLast) {//!<second letter is last name //!< previous last name wrong if (saves.get(0).getNode().isStrongWord() // || saves.get(0).getNode().isVerbOrTime() ) {//!<e.g. 于陈水扁不利 if (containName != null) { int index = result.size() - 1; result.set(index, containName); containName = null; } else if (name != null) { int index = result.size()-1; result.set(index, name); name = null; } else result.add(saves.get(0)); saves.clear(); saves.add(w); } else { WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), saves.get(0).getLen() + w.getLen(), null); saves.clear(); if (saves.size() == 2 && saves.get(1).getNode().notName()) newWord.setPos("n"); else newWord.setPos("nrc"); saves.add(newWord); name = null; containName = null; } leftLen = 2; floatLast = true; } else if (n.isStrongWord() && containName != null) { int index = result.size() - 1; result.set(index, containName); containName = null; } else if (n.isStrongWord() && name != null) { int index = result.size() - 1; result.set(index, name); name = null; saves.clear(); flag = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } else { saves.add(w); leftLen = 1; name = null; containName = null; } } else {//!< previous last name wrong if (containName != null) { int index = result.size() - 1; result.set(index, containName); containName = null; } else if (name != null) { int index = result.size() - 1; result.set(index, name); name = null; } else result.add(saves.get(0)); saves.clear(); flag = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } } else {//!< ch_l+ch_2, leftLen == 1 if (n.isCHLastName()) { if (saves.size() == 1) {//!< single name result.add(saves.get(0)); } else {//!< ch_l+ch_2 WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), saves.get(0).getLen() + saves.get(1).getLen(), null); if (saves.size() == 2 && saves.get(1).getNode().notName()) newWord.setPos("n"); else newWord.setPos("nrc"); result.add(newWord); floatLast = false; } if (n.isCH3rddName() && !n.isStrongWord()) { int len = 0; for (WordInSen ww : saves) len += ww.getLen(); name = new WordInSen(saves.get(0).getBegin(), len + 1, null); name.setPos("nrc"); } saves.clear(); saves.add(w); leftLen = 2; c1Node = n; } else if (n.isNameSuffix()) { if (saves.size() == 1) {//!< single name result.add(saves.get(0)); } else {//!< ch_l+ch_2 WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), saves.get(0).getLen() + saves.get(1).getLen(), null); if (saves.size() == 2 && saves.get(1).getNode().notName()) newWord.setPos("n"); else newWord.setPos("nrc"); result.add(newWord); } saves.clear(); flag = 0; floatLast = false; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } else { if (n.isCH3rddName()) {//!< ch_l+ch_2+ch_3 if (saves.size() == 1 && (n.isStrongWord() ||!this.checkMatch(c1Node, n))) { result.add(saves.get(0)); saves.clear(); flag = 0; c1Node = null; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } else { int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), len + w.getLen(), null); newWord.setPos("nrc"); result.add(newWord); floatLast = false; saves.clear(); flag = 0; leftLen = 0; } } else { if (saves.size() == 1) { result.add(saves.get(0)); saves.clear(); } else {//!< ch_l+ch_2 int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), len, null); if (saves.size() == 2 && saves.get(1).getNode().notName()) newWord.setPos("n"); else newWord.setPos("nrc"); result.add(newWord); floatLast = false; saves.clear(); } leftLen = 0; flag = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } } } } else if (flag == Const.IS_J_LASTNAME) { if (n == null || w.getLen() > 3) { if (saves.size() == 1) { result.add(saves.get(0)); saves.clear(); } else { int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), len, null); newWord.setPos("nrj"); result.add(newWord); saves.clear(); } flag = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int len = result.get(lIndex).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen( result.get(lIndex).getBegin(), len, null); if (n.isOrgName()) newWord.setPos("nt"); else newWord.setPos("ns"); result.set(lIndex, newWord); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } else if (leftLen == 1) {//!< J_l+J_2+J_3 if (w.getLen() == 1 && w.getNode().isJ4thName()) {//!< J_l+J_2+J_3+J_4 int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), len + w.getLen(), null); newWord.setPos("nrj"); result.add(newWord); saves.clear(); flag = 0; } else {//!< J_l+J_2+J_3 int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), len, null); newWord.setPos("nrj"); result.add(newWord); saves.clear(); flag = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int nl = result.get(lIndex).getLen(); nl += w.getLen(); WordInSen nw = new WordInSen( result.get(lIndex).getBegin(), nl, null); if (n.isOrgName()) nw.setPos("nt"); else nw.setPos("ns"); result.set(lIndex, nw); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } } else if (leftLen == 2) { if (w.getLen() == 1 && w.getNode().isJ3rdName()) { saves.add(w); leftLen--; } else {//!< J_l+J_2 int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), len, null); newWord.setPos("nrj"); result.add(newWord); saves.clear(); flag = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int nl = result.get(lIndex).getLen(); nl += w.getLen(); WordInSen nw = new WordInSen( result.get(lIndex).getBegin(), nl, null); if (n.isOrgName()) nw.setPos("nt"); else nw.setPos("ns"); result.set(lIndex, nw); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } } else {//!< J_l if (w.getLen() == 1 && w.getNode().isJ2ndName() && this.checkMatch(c1Node, n)) { saves.add(w); leftLen--; } else if(w.getNode().isName()){ int len = saves.get(0).getLen(); len += w.getLen(); WordInSen newWord = new WordInSen(saves.get(0) .getBegin(), len, null); newWord.setPos("nrj"); result.add(newWord); saves.clear(); flag = 0; } else { result.add(saves.get(0)); saves.clear(); flag = 0; //!<organization recognition int lIndex = result.size()-1; if (lIndex < 0 || n == null) result.add(w); else if ((n.isOrgName() || n.isNSend()) &&result.get(lIndex).getLen()>1 &&((result.get(lIndex).getPos() != null &&result.get(lIndex).getPos().startsWith("nr")) ||(result.get(lIndex).getNode() != null &&(result.get(lIndex).getNode().isName() ||result.get(lIndex).getNode().isWest1stName())))) { int nl = result.get(lIndex).getLen(); nl += w.getLen(); WordInSen nw = new WordInSen( result.get(lIndex).getBegin(), nl, null); if (n.isOrgName()) nw.setPos("nt"); else nw.setPos("ns"); result.set(lIndex, nw); } else if (n.containChLastName()) { result.add(this.words.get(wIndex-1)); flag = Const.IS_CH_LASTNAME; c1Node = this.words.get(wIndex+1).getNode(); saves.add(this.words.get(wIndex+1)); leftLen = 2; containName = w; } else result.add(w); //!< } } } } //!< clean up work if (saves.size() > 0 || nameLen > 0) { if (flag == Const.IS_CH_LASTNAME) { if (saves.size() == 1) { if (name == null) { //!< if(saves.get(0).getLen() == 1) //!< saves.get(0).setPos(""); result.add(saves.get(0)); } else { int index = result.size() - 1; result.set(index, name); } } else { int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0).getBegin(), len, null); if (saves.size() == 2 && saves.get(1).getNode().notName()) newWord.setPos("n"); else newWord.setPos("nrc"); result.add(newWord); } } else if (flag == Const.IS_J_LASTNAME) { if (saves.size() == 1) { result.add(saves.get(0)); } else { int len = 0; for (WordInSen ww : saves) len += ww.getLen(); WordInSen newWord = new WordInSen(saves.get(0).getBegin(), len, null); newWord.setPos("nrj"); result.add(newWord); } } else if (flag == Const.IS_WEST_1_NAME) { if (name == null) { // this.word_dic.insertWord(null, this.word_dic.root, // this.sen.substring(nameBegin, nameBegin // + nameLen), 0, flag); // String[] words = { "", "", "(nr,1)\t(ns,1)" }; // this.myMarkpos.addWord2Dis(this.word_dic.terminal, words); WordInSen newWord = new WordInSen(nameBegin, nameLen, null); newWord.setPos("nrf"); result.add(newWord); } else { result.add(name); name = null; } } else { result.add(saves.get(0)); } } return; } /** * @brief segment a short sentence * @param sen the sentence to be segmented * @param sResult the segmentation result * @param debug whether output internal variables * @param findName name recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findOrg organization recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findPlace address recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation */ private void segSen(String sen, ArrayList<String> sResult, boolean debug, int findName, int findOrg, int findPlace) { if (sen == null || sResult == null || sen.length() == 0) return; sResult.clear(); ArrayList<String> result = new ArrayList<String>(); String s1 = ""; for (int i = 0; i < sen.length(); i++) { if (sen.charAt(i) >= 'A' && sen.charAt(i) <= 'Z') s1 += (char)(sen.charAt(i)+'a'-'A'); else s1 += sen.charAt(i); } this.sen = s1; this.findAllWords(findName, findOrg, findPlace);//!< step1 if (debug) { System.out .println("-----------------------------------AllLeftWords after find all words"); this.showAllLeftWords(); System.out .println("-----------------------------------AllLeftWords end"); } this.findCompetition();//!< step2 if (debug) { System.out .println("-----------------------------------AllLeftWords after find competition"); this.showAllLeftWords(); System.out .println("-----------------------------------AllLeftWords end"); } this.solveComp();//!< step3 if (debug) { System.out .println("-----------------------------------AllLeftWords after solve competition"); this.showAllLeftWords(); System.out .println("-----------------------------------AllLeftWords end"); } this.getResult();//!< step4 if (debug) { System.out .println("-----------------------------------AllLeftWords after getResult"); this.showAllLeftWords(); System.out .println("-----------------------------------AllLeftWords end"); } this.comb1();//!< step5 if (debug) { System.out .println("-----------------------------------AllLeftWords after comb1"); this.showAllLeftWords(); System.out .println("-----------------------------------AllLeftWords end"); } if (1 == findPlace) { this.findNSU();//!< step6 if (debug) { System.out .println("-----------------------------------AllLeftWords after findNSU"); this.showAllLeftWords(); System.out .println("-----------------------------------AllLeftWords end"); } } //!< this.confRecord(); ArrayList<WordInSen> wordList = new ArrayList<WordInSen>();//!< for pos tagging ArrayList<String> posList = new ArrayList<String>(); if (1 == findName) this.findName(wordList);//!< step7 else { for (WordInSen w: this.words) { if (w.isSelected()) wordList.add(w); } } //second combination WordInSen preword = null; for (WordInSen word : wordList) { if (word.getPos() != null && word.getLen() == 2 && word.getPos().compareTo("n") == 0 && this.sen.charAt(word.getBegin()+1) == '家' && preword != null && preword.getPos() != null && preword.getLen() == 2 && preword.getPos().compareTo("nrc") == 0 ) { preword.setLen(3); word.setBegin(word.getBegin()+1); word.setLen(1); result.set(result.size()-1, this.sen.substring(preword.getBegin(), preword.getBegin() + 3)); } result.add(this.sen.substring(word.getBegin(), word .getBegin() + word.getLen()));//!< segmentation result without pos tagging preword = word; } markSen(wordList, posList);//!< step8 pos tagging // for debug // System.out.println("---------before combination-----------"); //third combination ArrayList<Term> tmpResult = new ArrayList<Term>(); String preWord = ""; for (int i = 0; i < wordList.size(); i++) { String tmp = ""; Term tmpT; TTreeNode n = wordList.get(i).getNode(); if (i != 0 && n != null && n.isCH3rddName() && preWord.length() == 2 && posList.get(i-1).startsWith("nr")) {//!<composing name tmp = preWord+result.get(i)+"/nrc "; result.set(i-1, ""); tmpT = new Term(preWord+result.get(i), "nrc", "", "", "", null, "!0!", 0);//OK tmpResult.set(tmpResult.size()-1, tmpT); } else if (i != 0 && n != null && n.isPlaceEnd() && posList.get(i-1).startsWith("n")) {//!<composing address name tmp = preWord+result.get(i)+"/ns "; result.set(i-1, ""); tmpT = new Term(preWord+result.get(i), "ns", "", "", "", null, "!0!", 0);//OK tmpResult.set(tmpResult.size()-1, tmpT); } else if (posList.get(i).charAt(0) == '[') {//!<hierarchical segmentation tmp = posList.get(i) + " "; int k = posList.get(i).indexOf(']'); String hpos = posList.get(i).substring(k+2); tmpT = new Term(result.get(i), hpos, "", "", posList.get(i).substring(1, k), wordList.get(i).getNode(), this.word2weight.get(wordList.get(i).getNode()), 1);//OK tmpResult.add(tmpT); } else if ((result.get(i).endsWith(".") || result.get(i).endsWith("_") || result.get(i).endsWith("·") || result.get(i).endsWith("-")) && posList.get(i).startsWith("nr")) {//!<decompose west name tmp = result.get(i).substring(0, result.get(i).length()-1); String ss = result.get(i).substring(result.get(i).length()-1); tmpT = new Term(tmp, posList.get(i), "", "", "", null, "!0!", 0);//OK tmpResult.add(tmpT); tmp += "/" + posList.get(i) + " " + ss +"/w "; tmpT = new Term(ss, "w", "", "", "", null, "!0!", 0);//OK tmpResult.add(tmpT); } else { boolean isName = false; for (String s: this.notname) { if (result.get(i).endsWith(s)&& posList.get(i).startsWith("nr")) { tmp = result.get(i).substring(0, result.get(i).length()-1); String ss = result.get(i).substring(result.get(i).length()-1); tmpT = new Term(tmp, posList.get(i), "", "", "", null, "!0!", 0);//OK tmpResult.add(tmpT); tmp += "/" + posList.get(i) + " " + ss +"/ad "; tmpT = new Term(ss, "ad", "", "", "", null, "!0!", 0);//OK tmpResult.add(tmpT); isName = true; break; } } if (!isName) { tmp = result.get(i) + "/" + posList.get(i) + " "; int k = posList.get(i).indexOf(myDic.sep.charAt(0)); if (k > 0) { if (posList.get(i).charAt(k+1) >= '0' && posList.get(i).charAt(k+1) <= '9')//!<ID tmpT = new Term(result.get(i), posList.get(i).substring(0,k), posList.get(i).substring(k+1), "", "", wordList.get(i).getNode(), "!"+this.word2weight.get(wordList.get(i).getNode())+"!", 0);//OK else//!<positive or negative tmpT = new Term(result.get(i), posList.get(i).substring(0,k), "", posList.get(i).substring(k+1), "", wordList.get(i).getNode(), "!"+this.word2weight.get(wordList.get(i).getNode())+"!", 0);//OK } else tmpT = new Term(result.get(i), posList.get(i), "", "", "", wordList.get(i).getNode(), "!"+this.word2weight.get(wordList.get(i).getNode())+"!", 0);//OK tmpResult.add(tmpT); } } preWord = result.get(i); result.set(i, tmp); } for (String s: result) if (s.length() > 0) sResult.add(s); //find organization if (1 == findOrg) sResult = this.findNT(tmpResult, sResult); else this.segResult.addAll(tmpResult); // System.out.println(); } /** * @brief segment text * @param text the text to be segmented * @param result the String type segmentation result * @param debug whether output internal variables * @param findName name recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findOrg organization recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findPlace address recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @return the Term type segmentation result */ private ArrayList<Term> segText(String text, ArrayList<String> result, boolean debug, int findName, int findOrg, int findPlace) { if (text == null || result == null || text.length() == 0) return null; this.segResult.clear(); result.clear(); String seps = "  \t\n\r\"!?;﹕“”‘’;,﹐。、`《》?!|[]「」『』〖〗【】{}"; int begin = 0, i; String pre = "", cur; for (i = 0; i < text.length(); i++) { cur = text.substring(i, i + 1); if (seps.contains(cur)) {//!< separation if (begin < i) { if (pre.compareTo("《") == 0 && cur.compareTo("》") == 0 || pre.compareTo("“") == 0 && cur.compareTo("”") == 0 && i - begin <= 5) { result.add(text.substring(begin, i) + "/nz"); Term t = new Term(text.substring(begin, i), "nz", "", "", "", null, "!0!", 1);//OK this.segResult.add(t); } else { ArrayList<String> tmp = new ArrayList<String>(); this.segSen(text.substring(begin, i), tmp, debug, findName, findOrg, findPlace); for (String s : tmp) result.add(s); } //!< System.out.println("-----------------------------------showAllComps"); //!< this.showAllComps(); //!< System.out.println("-----------------------------------showAllLeftWords"); //!< this.showAllLeftWords(); } if (cur.compareTo(" ") != 0 && cur.compareTo(" ") != 0) { result.add(cur + "/w "); Term t = new Term(cur, "w", "", "", "", null, "!0!", 1);//OK this.segResult.add(t); } begin = i + 1; pre = cur; } } if (begin < i) { ArrayList<String> tmp = new ArrayList<String>(); this.segSen(text.substring(begin, i), tmp, debug, findName, findOrg, findPlace); for (String s : tmp) result.add(s); // System.out.println("-----------------------------------showAllComps"); // this.showAllComps(); // System.out.println("-----------------------------------showAllLeftWords"); // this.showAllLeftWords(); } if(this.verifyName) this.verifyName(result); if(this.findNewWord) this.findNewWord(true); if(this.seg_English) this.tagEnglish(result); result.clear(); for (int k = 0; k < this.segResult.size(); k++) { String s = this.segResult.get(k).word+"/"+this.segResult.get(k).pos+";"; // if (this.segResult.get(k).ID.length() > 0) // s += this.segResult.get(k).ID+";"; // if (this.segResult.get(k).posOrNeg.length() > 0) // s += this.segResult.get(k).posOrNeg+";"; // s += this.segResult.get(k).weight+" "; result.add(s); } // if (result.size() == this.segResult.size()) // for (int k = 0; k < result.size(); k++) { // String weight = ";"+this.segResult.get(k).weight; // result.set(k, result.get(k)+weight); // } // else // for (int k = 0; k < result.size(); k++) { // int end = result.get(k).indexOf('/'); // String word = result.get(k).substring(0, end); // TTreeNode n = this.word_dic.string2Node(word); // String weight = ";!"+this.word2weight.get(n)+"! "; // result.set(k, result.get(k)+weight); // } return this.segResult; } /** * @brief find new word in current sentence * @param clearResult whether clear previous new words */ private void findNewWord(boolean clearResult) { if(clearResult) this.newWord2fre.clear(); NTTree newWordTree = new NTTree(); ArrayList<String> words = new ArrayList<String>(); ArrayList<String> poses = new ArrayList<String>(); for (Term t: this.segResult) { words.add(t.word); poses.add(t.pos); } if (words.size() > 1) { for (int i = 0; i < words.size()-1; i++) { newWordTree.insertWord(null, newWordTree.root, words, poses, i); } } newWordTree.findAllWords(newWordTree.root, "", "", 0); // System.out.println(newWordTree.newTerms.size()); newWordTree.clearResult(Const.MIN_NEW_WORD_FRE); for (NTerm t: newWordTree.newTerms) { if (t.selected == true) { String s = t.word1+"\t"+t.word+"\t"+t.len+"\t"; if (this.newWord2fre.containsKey(s)) { int fre = this.newWord2fre.get(s) + t.fre; this.newWord2fre.put(s, fre); } else { this.newWord2fre.put(s, t.fre); } } } // System.out.println("nodeNum:"+newWordTree.getNodeNum()+"\tnew word number:"+this.newWord2fre.size()); // for (String s: this.newWord2fre.keySet()) { // System.out.println(s+"\t"+this.newWord2fre.get(s)); // } } /** * @brief get the new words with corresponding frequencies * @return word and frequency map */ private HashMap<String, Integer> getNewWord2fre() { return this.newWord2fre; } /** * @brief clear name frequencies map */ private void clearName2Fre() { this.name2fre.clear(); } /** * @brief verify Chinese name. some Chinese name might be wrongly recognized. this function * will change wrong long name to correct short name. sometimes this function might also * change correct long name to wrong short name * @param result the current segmentation result including POS * @note this function will modify the segmentation result, meanwhile, it will modify the other * form of segmentation result */ private void verifyName(ArrayList<String> result) { // this.name2fre.clear(); for (Term t: this.segResult) { if (t.pos.compareTo("nrc") == 0) { if (this.name2fre.containsKey(t.word)) { this.name2fre.get(t.word).fre++; } else { nameInfo ni = new nameInfo (1,-1); this.name2fre.put(t.word, ni); } } } if (name2fre.size() > 0) { boolean modify = false; for (String s: name2fre.keySet()) {//!<long name if (name2fre.get(s).newEnd > 0) continue; if (s.length() <= 2) continue; for (String s1: name2fre.keySet()) {//!<short name if (s == s1) continue; if (name2fre.get(s1).newEnd > 0) continue; if (s.startsWith(s1) && name2fre.get(s).fre < name2fre.get(s1).fre) { name2fre.get(s).newEnd = s1.length(); modify = true; break; } } } if (modify) { ArrayList<Term> tmp = new ArrayList<Term>(); HashMap<String, String> oName2nName = new HashMap<String, String>(); for (Term t: this.segResult) { if (this.name2fre.containsKey(t.word) && this.name2fre.get(t.word).newEnd > 0) { String s1 = t.word.substring(0, this.name2fre.get(t.word).newEnd); String s2 = t.word.substring(this.name2fre.get(t.word).newEnd); Term t1 = new Term(s1, "nrc", "", "", "", null, "!0!", 0);//OK tmp.add(t1); TTreeNode n = myDic.word_dic.string2Node(s2); String pos = ""; if (null == n) pos = "?"; else if (null != n.pd) { pos = this.myDic.id2Pos.get(n.pd.getMaxPos()); if (pos == null) pos = "?"; } Term t2 = new Term(s2, pos, "", "", "", n, this.word2weight.get(n), 0);//OK tmp.add(t2); String oName = t.word+"/nrc "; String nName = s1+"/nrc "+s2+"/"+pos+" "; oName2nName.put(oName, nName); } else tmp.add(t); } for (int k = 0; k < result.size(); k++) { if (oName2nName.containsKey(result.get(k))) result.set(k, oName2nName.get(result.get(k))); } this.segResult.clear(); this.segResult.addAll(tmp); } } } /** * @brief tag POS of English words in current sentence */ private void tagEnglish(ArrayList<String> result) { // this.name2fre.clear(); ArrayList<String> newResult = new ArrayList<String>(); ArrayList<Term> newSegResult = new ArrayList<Term>(); String curPhrase1 = ""; String curPhrase2 = ""; for (int i = 0, j = 0; i < this.segResult.size() && j < result.size(); i++, j++) { while (i < this.segResult.size() && this.segResult.get(i).pos.compareTo("nx") != 0) {//!<find begin point newSegResult.add(this.segResult.get(i)); i++; } if (i == this.segResult.size()) {//!<no English word while (j < result.size()) { newResult.add(result.get(j)); j++; } break; } curPhrase1 = this.segResult.get(i).word; i++; while (i < this.segResult.size() && this.enPos.contains(this.segResult.get(i).pos)) {//!<find end point curPhrase1 += " "+this.segResult.get(i).word; i++; } while (j < result.size() && result.get(j).substring(result.get(j).lastIndexOf('/')+1, result.get(j).length()-1).compareTo("nx") != 0) {//!<find begin point // String pos = result.get(j).substring(result.get(j).lastIndexOf('/')+1, result.get(j).length()-1); newResult.add(result.get(j)); j++; } if (j < result.size()) { curPhrase2 = result.get(j).substring(0, result.get(j).lastIndexOf('/')); j++; while (j < result.size() && this.enPos.contains(result.get(j).substring(result.get(j).lastIndexOf('/')+1, result.get(j).length()-1))) { curPhrase2 += " "+result.get(j).substring(0, result.get(j).lastIndexOf('/')); j++; } } if (curPhrase1.length() > 0 && curPhrase1.compareTo(curPhrase2) == 0) { try{ List<List<String>> lines = this.mySegEn.tokenizeToListWithPOS(curPhrase1+" "); for (List<String> line : lines) { for (String s: line) { String word = s.substring(0, s.lastIndexOf('/')); String pos = s.substring(s.lastIndexOf('/')+1); if (pos.startsWith("CD")) pos = "m"; Term t = new Term(word, pos, "", "", "", null, "!0!", 1);//OK newSegResult.add(t); newResult.add(word+"/"+pos); } } }catch(IOException e){e.printStackTrace();} } else { if (curPhrase1.length() > 0) { try{ List<List<String>> lines = this.mySegEn.tokenizeToListWithPOS(curPhrase1+" "); for (List<String> line : lines) { for (String s: line) { String word = s.substring(0, s.lastIndexOf('/')); String pos = s.substring(s.lastIndexOf('/')+1); if (pos.startsWith("CD")) pos = "m"; Term t = new Term(word, pos, "", "", "", null, "!0!", 1);//OK newSegResult.add(t); } } }catch(IOException e){e.printStackTrace();} } if (curPhrase2.length() > 0) { try{ List<List<String>> lines = this.mySegEn.tokenizeToListWithPOS(curPhrase2+" "); for (List<String> line : lines) { for (String s: line) { String word = s.substring(0, s.lastIndexOf('/')); String pos = s.substring(s.lastIndexOf('/')+1); if (pos.startsWith("CD")) pos = "m"; newResult.add(word+"/"+pos); } } }catch(IOException e){e.printStackTrace();} } } curPhrase1 = ""; curPhrase2 = ""; if (i < this.segResult.size()) newSegResult.add(this.segResult.get(i)); if (j < result.size()) newResult.add(result.get(j)); } if (curPhrase1.length() > 0 && curPhrase1.compareTo(curPhrase2) == 0) { try{ List<List<String>> lines = this.mySegEn.tokenizeToListWithPOS(curPhrase1); for (List<String> line : lines) { for (String s: line) { String word = s.substring(0, s.lastIndexOf('/')); String pos = s.substring(s.lastIndexOf('/')+1); if (pos.startsWith("CD")) pos = "m"; Term t = new Term(word, pos, "", "", "", null, "!0!", 1);//OK newSegResult.add(t); newResult.add(word+"/"+pos); } } }catch(IOException e){e.printStackTrace();} } else { if (curPhrase1.length() > 0) { try{ List<List<String>> lines = this.mySegEn.tokenizeToListWithPOS(curPhrase1); for (List<String> line : lines) { for (String s: line) { String word = s.substring(0, s.lastIndexOf('/')); String pos = s.substring(s.lastIndexOf('/')+1); if (pos.startsWith("CD")) pos = "m"; Term t = new Term(word, pos, "", "", "", null, "!0!", 1);//OK newSegResult.add(t); } } }catch(IOException e){e.printStackTrace();} } if (curPhrase2.length() > 0) { try{ List<List<String>> lines = this.mySegEn.tokenizeToListWithPOS(curPhrase2); for (List<String> line : lines) { for (String s: line) { String word = s.substring(0, s.lastIndexOf('/')); String pos = s.substring(s.lastIndexOf('/')+1); if (pos.startsWith("CD")) pos = "m"; newResult.add(word+"/"+pos); } } }catch(IOException e){e.printStackTrace();} } } this.segResult.clear(); this.segResult.addAll(newSegResult); result.clear(); result.addAll(newResult); } /** * @brief clear all class score of current sentence */ private void clearScore() { this.classScore = new float[8]; } /** * @brief get the class name of current sentence * @return the most possible class name */ private String getClassName() { int cId = 8; float maxScore = 0; for (int i = 0; i < 8; i++) { if (this.classScore[i] > maxScore) { maxScore = this.classScore[i]; cId = i; } } return this.className[cId]; } /** * @brief find organization name in current sentence * @param tList Term segmentation result * @param sList String segmentation result * @return the String segmentation result with recognized organization names */ private ArrayList<String> findNT(ArrayList<Term> tList, ArrayList<String> sList) { ArrayList<String> sResult = new ArrayList<String>(); if (tList.size() != sList.size()) { this.segResult.addAll(tList); return sList; } int state = 0; int begin = -1; int subBegin = -1; boolean combine = false; for (int i = 0; i < tList.size(); i++) { switch (state) { case 0: {//!<initial state if (tList.get(i).pos.startsWith("ns")) { state = 1; begin = i; } else if (tList.get(i).pos.startsWith("nr")) { state = 2; begin = i; } else { this.segResult.add(tList.get(i)); sResult.add(sList.get(i)); } break; } case 1: {//!<start of ns if (tList.get(i).pos.startsWith("ns")) continue; else if (tList.get(i).pos.startsWith("nr")) { state = 2; } else if (tList.get(i).n != null && tList.get(i).n.isOrgExclude() || tList.get(i).pos.compareTo("w") == 0) {//!<excluding word for (int j = begin; j <= i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } state = 0; begin = -1; } else if (tList.get(i).n != null && tList.get(i).n.isOrgName()) { if (i-begin < Const.MAX_ORG_LEN && i-begin > 1) {//!<new NT String word = "", sWord =""; for (int j = begin; j <= i; j++){ word += tList.get(j).word; sWord += sList.get(j)+" "; } Term t = new Term(word, "nt_", "", "", sWord, null, "!0!", 0);//OK this.segResult.add(t); sWord = "["+sWord+"]/nt_"; sResult.add(sWord); combine = true; } else { for (int j = begin; j <= i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } } begin = -1; if (tList.get(i).n.isOrgEnd() || !combine) { state = 0; } else { state = 4; subBegin = i+1; } combine = false; } else state = 3; break; } case 2: {//!<ns...nr if (tList.get(i).pos.startsWith("nr")) continue; else if (tList.get(i).pos.startsWith("ns")) {//!<restart state = 1; for (int j = begin; j < i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } begin = i; } else if (tList.get(i).n != null && tList.get(i).n.isOrgExclude() || tList.get(i).pos.compareTo("w") == 0 ) {//!<excluding word for (int j = begin; j <= i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } state = 0; begin = -1; } else if (tList.get(i).n != null && tList.get(i).n.isOrgName()) {//!<end of organization name if (i-begin < Const.MAX_ORG_LEN && i-begin > 1) {//!<new NT String word = "", sWord =""; for (int j = begin; j <= i; j++){ word += tList.get(j).word; sWord += sList.get(j)+" "; } Term t = new Term(word, "nt_", "", "", sWord, null, "!0!", 0);//OK this.segResult.add(t); sWord = "["+sWord+"]/nt_"; sResult.add(sWord); combine = true; } else { for (int j = begin; j <= i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } } begin = -1; if (tList.get(i).n.isOrgEnd() || !combine) { state = 0; } else { state = 4; subBegin = i+1; } combine = false; } else state = 3; break; } case 3: { if (tList.get(i).pos.startsWith("nr")) { state = 2; for (int j = begin; j < i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } begin = i; } else if (tList.get(i).pos.startsWith("ns")) { state = 1; for (int j = begin; j < i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } begin = i; } else if (tList.get(i).n != null && tList.get(i).n.isOrgExclude() || tList.get(i).pos.compareTo("w") == 0) {//!< excluding word for (int j = begin; j <= i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } state = 0; begin = -1; } else if (tList.get(i).n != null && tList.get(i).n.isOrgName()) { if (i-begin < Const.MAX_ORG_LEN && i-begin > 1) {//!<new NT String word = "", sWord =""; for (int j = begin; j <= i; j++){ word += tList.get(j).word; sWord += sList.get(j)+" "; } Term t = new Term(word, "nt_", "", "", sWord, null, "!0!", 0);//OK this.segResult.add(t); sWord = "["+sWord+"]/nt_"; sResult.add(sWord); combine = true; } else { for (int j = begin; j <= i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } } begin = -1; if (tList.get(i).n.isOrgEnd() || !combine) { state = 0; } else { state = 4; subBegin = i+1; } combine = false; } break; } case 4: {//!<part of organization name detected if (tList.get(i).pos.startsWith("nr")) { state = 2; for (int j = subBegin; j < i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } begin = i; subBegin = -1; } else if (tList.get(i).pos.startsWith("ns")) { state = 1; for (int j = subBegin; j < i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } begin = i; subBegin = -1; } else if (tList.get(i).n != null && tList.get(i).n.isOrgExclude() || tList.get(i).pos.compareTo("w") == 0) {//!<excluding name for (int j = subBegin; j <= i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } state = 0; subBegin = -1; } else if (tList.get(i).n != null && tList.get(i).n.isOrgEnd()) { if (i-subBegin < Const.MAX_ORG_LEN && i-subBegin > 1) {//!<new NT int index1 = segResult.size()-1; int index2 = sResult.size()-1; int index3 = sResult.get(index2).length()-5; String word = segResult.get(index1).word; if (index3 <= 1) System.out.println(); String sWord = sResult.get(index2).substring(1, index3); for (int j = subBegin; j <= i; j++){ word += tList.get(j).word; sWord += sList.get(j)+" "; } Term t = new Term(word, "nt_", "", "", sWord, null, "!0!", 0);//OK this.segResult.set(index1, t); sWord = "["+sWord+"]/nt_"; sResult.set(index2, sWord); } else { for (int j = subBegin; j <= i; j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } } subBegin = -1; state = 0; } break; } } } if (begin >= 0) { for (int j = begin; j < tList.size(); j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } } else if (subBegin >= 0) { for (int j = subBegin; j < tList.size(); j++) { this.segResult.add(tList.get(j)); sResult.add(sList.get(j)); } } sList.clear(); sList.addAll(sResult); return sResult; } /** * @brief find HongKong address name in current sentence */ private void findNSU() { boolean inNSU = false; ArrayList<Integer> positions = new ArrayList<Integer>();//!<for all units ArrayList<Integer> elements = new ArrayList<Integer>();//!<for all elements in one unit int begin = -1;//!<head of a unit int len = 0;//!<length of a unit for (int wIndex = 0; wIndex < this.words.size(); wIndex++) { WordInSen w = this.words.get(wIndex); if (!w.isSelected()) continue; String s = this.sen.substring(w.getBegin(), w.getBegin() + w.getLen()); if (inNSU) {//!<start of ns has been detected if (myDic.uExcept.contains(s)) {//!<ns units end inNSU = false; if (positions.size() > 1) { for (int i: positions) this.words.get(i).setPos("nsu"); } positions.clear(); begin = -1; len = 0; } else if (myDic.uEnd.contains(s.substring(s.length()-1)) || s.length() > 1 && myDic.uEnd.contains(s.substring(s.length()-2))) {//!<end of a unit positions.add(wIndex); if (begin != -1) { for (int i: elements) this.words.get(i).setSelected(false); this.words.get(wIndex).setBegin(begin); len += this.words.get(wIndex).getLen(); this.words.get(wIndex).setLen(len); this.words.get(wIndex).setNode(null); elements.clear(); begin = -1; len = 0; } } else {//!<possible elements of a unit elements.add(wIndex); if (begin == -1) { begin = this.words.get(wIndex).getBegin(); } len += this.words.get(wIndex).getLen(); if (elements.size() > Const.MAX_NSU_LEN) {//!<ns units end inNSU = false; if (positions.size() > 1) { for (int i: positions) this.words.get(i).setPos("nsu"); } positions.clear(); begin = -1; len = 0; } } } else { if (myDic.uStart.contains(s)) { inNSU = true; positions.add(wIndex); } } } if (positions.size() > 1) { for (int i: positions) this.words.get(i).setPos("nsu"); } } /** * @brief tag POS of each word in the sentence * @param wordList the words to be tagged * @param posList the result POS list */ private void markSen(ArrayList<WordInSen> wordList, ArrayList<String> posList) { if (wordList.size() == 0 || posList == null) { System.out.println("Mark pos error."); return; } int len = wordList.size(); int[] posIds = new int[len]; ArrayList<TTreeNode> viterbiWords = new ArrayList<TTreeNode>();//!< words in current phrase int bid = myDic.pos2Id.get("w");//!<start posing is a punctuation int eid; for (int i = 0; i < len; i++) {//!< word by word TTreeNode n = wordList.get(i).getNode(); if (wordList.get(i).getPos() != null && wordList.get(i).getPos().length() > 0) {//!<having pre-tagged POS if (wordList.get(i).getPos().startsWith("nr")) posIds[i] = myDic.pos2Id.get("nr"); else if (wordList.get(i).getPos().startsWith("m")) posIds[i] = myDic.pos2Id.get("m"); else if (wordList.get(i).getPos().startsWith("t")) posIds[i] = myDic.pos2Id.get("t"); else if (wordList.get(i).getPos().startsWith("nt")) posIds[i] = myDic.pos2Id.get("nt"); else if (wordList.get(i).getPos().startsWith("ns")) posIds[i] = myDic.pos2Id.get("ns"); else posIds[i] = myDic.pos2Id.get("w"); int m = viterbiWords.size();//!< number of words to be tagged if (m > 0) { this.observeMatrix = new float[60][m]; eid = posIds[i]; for (int j = 0; j < m; j++) {//!< word by word for (int k = 0; k < 60; k++) //!< POS by POS this.observeMatrix[k][j] = 0;//!< no POS distribution PosDistribution tmp = viterbiWords.get(j).pd;//!< get POS distribution for (int k = 0; k < tmp.posId.size(); k++) { this.observeMatrix[tmp.posId.get(k)][j] = tmp.prob .get(k); } } myViterbi.resetPara(bid, eid, this.observeMatrix, m);//!< set parameters for Viterbi myViterbi.viterbiRun();//!< tagging POS int[] posResult = new int[m]; myViterbi.getPos(posResult, m);//!< get POS result for (int k = 0; k < m; k++) posIds[k + i - m] = posResult[k];//!< save POS result //!< end viterbi viterbiWords.clear();//!< clear tagging result } else bid = posIds[i]; } else if (n.pd != null && n.isSinglePOS) {//!< word with only one POS posIds[i] = n.pd.get1stPos();//!< tag POS int m = viterbiWords.size();//!< number of words to be tagged if (m > 0) { this.observeMatrix = new float[60][m]; eid = posIds[i]; for (int j = 0; j < m; j++) {//!< word by word for (int k = 0; k < 60; k++) //!< POS by POS this.observeMatrix[k][j] = 0;//!< no POS distribution PosDistribution tmp = viterbiWords.get(j).pd;//!< get POS distribution for (int k = 0; k < tmp.posId.size(); k++) { this.observeMatrix[tmp.posId.get(k)][j] = tmp.prob .get(k); } } myViterbi.resetPara(bid, eid, this.observeMatrix, m);//!< set parameters for Viterbi myViterbi.viterbiRun();//!< tag POS int[] posResult = new int[m]; myViterbi.getPos(posResult, m);//!< get POS result for (int k = 0; k < m; k++) posIds[k + i - m] = posResult[k];//!< save POS result //!< end viterbi viterbiWords.clear();//!< clear tagging result } else bid = posIds[i]; } else if (n.pd != null) {//!< word with multiple POSes viterbiWords.add(n); } else {//!< not in dictionary posIds[i] = -1;//!< no POS information int m = viterbiWords.size();//!< number of words to be tagged if (m > 0) { this.observeMatrix = new float[60][m]; eid = this.myDic.pos2Id.get("w"); for (int j = 0; j < m; j++) {//!< word by word for (int k = 0; k < 60; k++) //!< POS by POS this.observeMatrix[k][j] = 0;//!< no POS distribution PosDistribution tmp = viterbiWords.get(j).pd;//!< get POS distribution for (int k = 0; k < tmp.posId.size(); k++) { this.observeMatrix[tmp.posId.get(k)][j] = tmp.prob .get(k); } } myViterbi.resetPara(bid, eid, this.observeMatrix, m);//!< set parameters for Viterbi myViterbi.viterbiRun();//!< tag POS int[] posResult = new int[m]; myViterbi.getPos(posResult, m);//!< get POS result for (int k = 0; k < m; k++) posIds[k + i - m] = posResult[k];//!< save POS result //!< end viterbi viterbiWords.clear();//!< clear tagging result } else bid = this.myDic.pos2Id.get("w"); } } //!< clean up int m = viterbiWords.size(); if (m > 0) { this.observeMatrix = new float[60][m]; eid = this.myDic.pos2Id.get("w"); for (int j = 0; j < m; j++) {//!< word by word for (int k = 0; k < 60; k++) //!< POS by POS this.observeMatrix[k][j] = 0;//!< no POS distribution PosDistribution tmp = viterbiWords.get(j).pd;//!< get POS distribution for (int k = 0; k < tmp.posId.size(); k++) { this.observeMatrix[tmp.posId.get(k)][j] = tmp.prob.get(k); } } myViterbi.resetPara(bid, eid, this.observeMatrix, m);//!< set parameters for Viterbi myViterbi.viterbiRun();//!< tag POS int[] posResult = new int[m]; myViterbi.getPos(posResult, m);//!< get POS result for (int k = 0; k < m; k++) posIds[k + len - m] = posResult[k];//!< save POS result //!< end viterbi viterbiWords.clear();//!< clear tagging result } for (int i = 0; i < len; i++) { String pos; if (wordList.get(i).getPos() != null) { pos = wordList.get(i).getPos(); } else pos = this.myDic.id2Pos.get(posIds[i]); TTreeNode n = wordList.get(i).getNode(); if (n != null && n.hasCode() && (pos.compareTo("nt") == 0 || pos.compareTo("nr") == 0 || pos.compareTo("nz") == 0)) { pos += wordList.get(i).getNode().code; } else if (n != null && n.isHierarchical()) { pos = wordList.get(i).getNode().hier_str + "/" + pos; } if (n != null && n.isNegative()) { // if (this.sepWithSemicolon) // pos += ";~"; // else // pos += "/~"; pos += this.myDic.sep+"~"; } if (n != null && n.isPositive()) { // if (this.sepWithSemicolon) // pos += ";*"; // else // pos += "/*"; pos += this.myDic.sep+"*"; } posList.add(pos); } } /** * @brief entrance of segmentation engine * @param sen the sentence to be segmented * @param name name recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param org organization recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param addr address recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @return String segmentation result */ public ArrayList<String> DoSeg(String sen, int name, int org, int addr) { ArrayList<String> sList = new ArrayList<String>(); this.reset(sen); this.segText(this.sen, sList, false, name, org, addr);//!< Step 2 // this.segText(this.sen, sList, true);//!< Step 2 return sList; } /** * @brief Entrance of structured segmentation engine. This method separates a given text into * segments. It stores the results into a list of Occurrence objects. Also required are: the * exact document, paragraph and the sentence the segment appears in. * @param docs the documents to be segmented * @param debug whether debug information will be output * @param findName name recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findOrg organization recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findPlace address recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @return Segmentation result -- A list of occurrence for a given text. */ public ArrayList<Occurrence> BatchSeg(String []docs, boolean debug, int findName, int findOrg, int findPlace) { if (null == docs) return null; ArrayList<Occurrence> result = new ArrayList<Occurrence>(); for (int i = 0; i < docs.length; i++) { ArrayList<Occurrence> tmp = this.segDoc(docs[i], debug, i, findName, findOrg, findPlace); if (tmp != null) result.addAll(tmp); } return result; } /** * @brief Separate one document into segments * @param doc the document to be segmented * @param debug whether debug information will be output * @param docID the id of current document * @param findName name recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findOrg organization recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findPlace address recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @return Segmentation result -- A list of occurrence for a given document. */ private ArrayList<Occurrence> segDoc(String doc, boolean debug, int docID, int findName, int findOrg, int findPlace) { if (null == doc || doc.length() == 0) return null; ArrayList<Occurrence> result = new ArrayList<Occurrence>(); String seps = "\n\r"; String[] paras = StringUtils.split(doc, seps); int startPos = 0; for (int i = 0; i < paras.length; i++) { int pStartPos = startPos + doc.substring(startPos).indexOf(paras[i].charAt(0)); ArrayList<Occurrence> pResult = this.segPara(paras[i], debug, docID, i, pStartPos, findName, findOrg, findPlace); if (pResult != null) result.addAll(pResult); startPos = pStartPos+paras[i].length(); } return result; } /** * @brief Separate one paragraph into segments * @param para the paragraph to be segmented * @param debug whether debug information will be output * @param docID the id of current document * @param paraID the id of current paragraph * @param paraStartPos the start position of this paragraph in current document * @param findName name recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findOrg organization recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findPlace address recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @return Segmentation result -- A list of occurrence for a given paragraph. */ private ArrayList<Occurrence> segPara(String para, boolean debug, int docID, int paraID, int paraStartPos, int findName, int findOrg, int findPlace) { if (null == para || para.length() == 0) return null; ArrayList<Occurrence> result = new ArrayList<Occurrence>(); String seps = "  \t\"!?;﹕“”‘’;,﹐。、`《》?!|[]「」『』〖〗【】{}"; String[] sens = StringUtils.split(para, seps); int startPos = 0; for (int i = 0; i < sens.length; i++) { char pre = ' ', next = ' '; int pStartPos = startPos + para.substring(startPos).indexOf(sens[i].charAt(0)); if (pStartPos != startPos) pre = para.charAt(pStartPos-1); startPos = pStartPos+sens[i].length(); if (startPos != para.length()) next = para.charAt(startPos); if ('《' == pre && '》' == next) { Occurrence occu = new Occurrence(); occu.documentID = docID; occu.paragraphID = paraID; occu.sentenceID = i; occu.phase = sens[i]; occu.startPos = paraStartPos + pStartPos; occu.endPos = paraStartPos + startPos; // occu.startPos = 0; // occu.endPos = sens[i].length(); occu.POS = "nz"; result.add(occu); } else { ArrayList<Occurrence> senResult = this.segSentence(sens[i], debug, docID, paraID, i, paraStartPos, pStartPos, findName, findOrg, findPlace); if (senResult != null) result.addAll(senResult); } } return result; } /** * @brief Separate one sentence into segments * @param sen the sentence to be segmented * @param debug whether debug information will be output * @param docID the id of current document * @param paraID the id of current paragraph * @param senID the id of the current sentence * @param pStartPos the start position of this paragraph in current document * @param startPos the start position of this sentence in current paragraph * @param findName name recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findOrg organization recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @param findPlace address recognition: 0 for none, -1 for before segmentation, * 1 for after segmentation * @return Segmentation result -- A list of occurrence for a given sentence. */ private ArrayList<Occurrence> segSentence(String sen, boolean debug, int docID, int paraID, int senID, int pStartPos, int startPos, int findName, int findOrg, int findPlace) { if (sen == null || sen.length() == 0) return null; ArrayList<Occurrence> result = new ArrayList<Occurrence>(); this.reset(sen); ArrayList<String> tmp = new ArrayList<String>(); this.segSen(sen, tmp, debug, findName, findOrg, findPlace); if(this.verifyName) this.verifyName(tmp); if(this.findNewWord) this.findNewWord(true); if(this.seg_English) this.tagEnglish(tmp); // int sStartPos = startPos; int sStartPos = 0; for (int k = 0; k < this.segResult.size(); k++) { Occurrence occu = new Occurrence(); occu.documentID = docID; occu.paragraphID = paraID; occu.sentenceID = senID; occu.phase = this.segResult.get(k).word; occu.startPos = pStartPos + startPos + sStartPos; occu.endPos = occu.startPos + occu.phase.length(); occu.POS = this.segResult.get(k).pos; result.add(occu); // sStartPos = occu.endPos; sStartPos += occu.phase.length(); } return result; } /** * @brief This method finds entities of several possible types in the supplied texts, i.e. * Location, Address Organization and Person. The method accepts multiple texts as input * and outputs a list of entities for each text. It also accepts parameters such as the * language and types of entities to extract. * @param docs the documents where entities will be found * @param languageCode the language code of the input documents. E.g. “zh” for Chinese * (this will always by “zh” now) * @param entitiesToExtract Type of entities to extract. (e.g. “Location”, “Address”, * “Organization”, “Person” * @param extractKeywords Number of keywords to extract. Now no keyword extraction model * available. So no keywords in the entity result * @return A list of entities from each of the documents. Each entity represents individual * address, location, organization, people found within the text. * @note currently no keywords extraction is performed */ public ArrayList<Entity> EntityExtract(String []docs, String languageCode, HashSet<String> entitiesToExtract, int extractKeywords) { if (null == docs || null == entitiesToExtract || languageCode.compareTo("zh") != 0 || extractKeywords < 0) return null; ArrayList<Entity> result = new ArrayList<Entity>(); HashMap<String, String> POS2Type = new HashMap<String, String>(); int name = 0; int org = 0; int addr = 0; for (String s: entitiesToExtract) { if (s.compareTo("Location") == 0 || s.compareTo("Address") == 0) { POS2Type.put("ns", "Location or Address"); addr = 1; } else if (s.compareTo("Organization") == 0) { POS2Type.put("nt", "Organization"); org = 1; } else if (s.compareTo("Person") == 0) { POS2Type.put("nr", "Person"); name = 1; } } ArrayList<Occurrence> oResult = this.BatchSeg(docs, false, name, org, addr); HashMap<String, ArrayList<EntityOccurrence>> key2list = new HashMap<String, ArrayList<EntityOccurrence>>(); for (Occurrence occu: oResult) { if (occu.POS.length() < 2) continue; String pos = occu.POS.substring(0, 2); if (!POS2Type.containsKey(pos)) continue; String key = pos + occu.phase; if (!key2list.containsKey(key)) { key2list.put(key, new ArrayList<EntityOccurrence>()); } EntityOccurrence eo = new EntityOccurrence(); eo.title = occu.phase; eo.type = POS2Type.get(pos); eo.score = occu.POS.length() > 2 ? 0.0 : 1.0; eo.docID = occu.documentID; eo.textStartLocation = occu.startPos; eo.textEndLocation = occu.endPos; key2list.get(key).add(eo); } for (String key: key2list.keySet()) { Entity e = new Entity(); e.title = key.substring(2); e.type = POS2Type.get(key.substring(0, 2)); e.frequency = key2list.get(key).size(); e.entityOccurrences = key2list.get(key); e.score = 0.0; for (EntityOccurrence eo: e.entityOccurrences) { e.score += eo.score; } e.score /= e.frequency; result.add(e); } return result; } }
bsd-3-clause
psh/Refuctoring
src/main/java/com/refuctor/example/HGetter.java
166
package com.refuctor.example; public class HGetter extends AbstractGetter { @Override public String getStr() { return getSpringProperty(); } }
bsd-3-clause
bdezonia/zorbage
src/main/java/nom/bdezonia/zorbage/procedure/impl/AcoshL.java
2529
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (c) 2016-2021 Barry DeZonia 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. * * Neither the name of the <copyright holder> nor the names of its contributors may * be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 nom.bdezonia.zorbage.procedure.impl; import nom.bdezonia.zorbage.procedure.Procedure; import nom.bdezonia.zorbage.algebra.Algebra; import nom.bdezonia.zorbage.algebra.InverseHyperbolic; /** * * @author Barry DeZonia * */ public class AcoshL<T extends Algebra<T,U> & InverseHyperbolic<U>,U> implements Procedure<U> { private final Procedure<U> ancestor; private final Acosh<T,U> lowerProc; private final T algebra; private final ThreadLocal<U> tmp; public AcoshL(T alg, Procedure<U> ancestor) { this.algebra = alg; this.ancestor = ancestor; this.lowerProc = new Acosh<T,U>(algebra); this.tmp = new ThreadLocal<U>() { @Override protected U initialValue() { return algebra.construct(); } }; } @Override @SuppressWarnings("unchecked") public void call(U result, U... inputs) { U u = tmp.get(); ancestor.call(u, inputs); lowerProc.call(u, result); } }
bsd-3-clause
backesj/jkind
jkind/src/jkind/translation/compound/FlattenCompoundVariables.java
4988
package jkind.translation.compound; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayType; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.Node; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordExpr; import jkind.lustre.RecordType; import jkind.lustre.Type; import jkind.lustre.VarDecl; import jkind.lustre.builders.NodeBuilder; import jkind.lustre.visitors.AstMapVisitor; import jkind.translation.SubstitutionVisitor; import jkind.util.Util; /** * Flatten array and record variables to scalars variables * * Assumption: All node calls have been inlined. * * Assumption: All array indices are integer literals */ public class FlattenCompoundVariables extends AstMapVisitor { public static Node node(Node node) { return new FlattenCompoundVariables().visit(node); } private final Map<String, Type> originalTypes = new HashMap<>(); @Override public Node visit(Node node) { addOriginalTypes(node.inputs); addOriginalTypes(node.outputs); addOriginalTypes(node.locals); NodeBuilder builder = new NodeBuilder(node); builder.clearInputs().addInputs(flattenVarDecls(node.inputs)); builder.clearOutputs().addOutputs(flattenVarDecls(node.outputs)); builder.clearLocals().addLocals(flattenVarDecls(node.locals)); builder.clearEquations().addEquations(flattenLeftHandSide(node.equations)); if (node.realizabilityInputs != null) { builder.setRealizabilityInputs(flattenNames(node.realizabilityInputs)); } builder.clearIvc().addIvcs(flattenNames(node.ivc)); Map<String, Expr> map = createExpandedVariables(Util.getVarDecls(node)); return new SubstitutionVisitor(map).visit(builder.build()); } private void addOriginalTypes(List<VarDecl> varDecls) { for (VarDecl varDecl : varDecls) { originalTypes.put(varDecl.id, varDecl.type); } } private List<VarDecl> flattenVarDecls(List<VarDecl> varDecls) { List<VarDecl> result = new ArrayList<>(); for (VarDecl varDecl : varDecls) { IdExpr id = new IdExpr(varDecl.id); for (ExprType et : CompoundUtil.flattenExpr(id, varDecl.type)) { result.add(new VarDecl(et.expr.toString(), et.type)); } } return result; } private List<String> flattenNames(List<String> names) { List<String> result = new ArrayList<>(); for (String name : names) { IdExpr id = new IdExpr(name); for (ExprType et : CompoundUtil.flattenExpr(id, originalTypes.get(name))) { result.add(et.expr.toString()); } } return result; } private List<Equation> flattenLeftHandSide(List<Equation> equations) { List<Equation> result = new ArrayList<>(); for (Equation eq : equations) { IdExpr lhs = eq.lhs.get(0); Type type = originalTypes.get(lhs.id); result.addAll(flattenLeftHandSide(lhs, eq.expr, type)); } return result; } private static List<Equation> flattenLeftHandSide(Expr lhs, Expr rhs, Type type) { List<Equation> result = new ArrayList<>(); if (type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; for (int i = 0; i < arrayType.size; i++) { Expr accessLhs = new ArrayAccessExpr(lhs, i); Expr accessRhs = new ArrayAccessExpr(rhs, i); result.addAll(flattenLeftHandSide(accessLhs, accessRhs, arrayType.base)); } } else if (type instanceof RecordType) { RecordType recordType = (RecordType) type; for (Entry<String, Type> entry : recordType.fields.entrySet()) { Expr accessLhs = new RecordAccessExpr(lhs, entry.getKey()); Expr accessRhs = new RecordAccessExpr(rhs, entry.getKey()); result.addAll(flattenLeftHandSide(accessLhs, accessRhs, entry.getValue())); } } else { result.add(new Equation(new IdExpr(lhs.toString()), rhs)); } return result; } private Map<String, Expr> createExpandedVariables(List<VarDecl> varDecls) { Map<String, Expr> map = new HashMap<>(); for (VarDecl varDecl : varDecls) { IdExpr expr = new IdExpr(varDecl.id); Type type = originalTypes.get(varDecl.id); map.put(varDecl.id, expand(expr, type)); } return map; } private Expr expand(Expr expr, Type type) { if (type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; List<Expr> elements = new ArrayList<>(); for (int i = 0; i < arrayType.size; i++) { elements.add(expand(new ArrayAccessExpr(expr, i), arrayType.base)); } return new ArrayExpr(elements); } else if (type instanceof RecordType) { RecordType recordType = (RecordType) type; Map<String, Expr> fields = new HashMap<>(); for (Entry<String, Type> entry : recordType.fields.entrySet()) { String field = entry.getKey(); Type fieldType = entry.getValue(); fields.put(field, expand(new RecordAccessExpr(expr, field), fieldType)); } return new RecordExpr(recordType.id, fields); } else { return new IdExpr(expr.toString()); } } }
bsd-3-clause
dcpang/fatline-libjingle
app/webrtc/java/android/org/webrtc/CameraEnumerationAndroid.java
9079
/* * libjingle * Copyright 2015 Google Inc. * * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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.webrtc; import static java.lang.Math.abs; import static java.lang.Math.ceil; import android.hardware.Camera; import android.util.Log; import android.graphics.ImageFormat; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; @SuppressWarnings("deprecation") public class CameraEnumerationAndroid { private final static String TAG = "CameraEnumerationAndroid"; // Synchronized on |CameraEnumerationAndroid.this|. private static Enumerator enumerator = new CameraEnumerator(); public interface Enumerator { /** * Returns a list of supported CaptureFormats for the camera with index |cameraId|. */ List<CaptureFormat> getSupportedFormats(int cameraId); } public static synchronized void setEnumerator(Enumerator enumerator) { CameraEnumerationAndroid.enumerator = enumerator; } public static synchronized List<CaptureFormat> getSupportedFormats(int cameraId) { return enumerator.getSupportedFormats(cameraId); } public static class CaptureFormat { public final int width; public final int height; public final int maxFramerate; public final int minFramerate; // TODO(hbos): If VideoCapturerAndroid.startCapture is updated to support // other image formats then this needs to be updated and // VideoCapturerAndroid.getSupportedFormats need to return CaptureFormats of // all imageFormats. public final int imageFormat = ImageFormat.YV12; public CaptureFormat(int width, int height, int minFramerate, int maxFramerate) { this.width = width; this.height = height; this.minFramerate = minFramerate; this.maxFramerate = maxFramerate; } // Calculates the frame size of this capture format. public int frameSize() { return frameSize(width, height, imageFormat); } // Calculates the frame size of the specified image format. Currently only // supporting ImageFormat.YV12. The YV12's stride is the closest rounded up // multiple of 16 of the width and width and height are always even. // Android guarantees this: // http://developer.android.com/reference/android/hardware/Camera.Parameters.html#setPreviewFormat%28int%29 public static int frameSize(int width, int height, int imageFormat) { if (imageFormat != ImageFormat.YV12) { throw new UnsupportedOperationException("Don't know how to calculate " + "the frame size of non-YV12 image formats."); } int yStride = roundUp(width, 16); int uvStride = roundUp(yStride / 2, 16); int ySize = yStride * height; int uvSize = uvStride * height / 2; return ySize + uvSize * 2; } // Rounds up |x| to the closest value that is a multiple of |alignment|. private static int roundUp(int x, int alignment) { return (int)ceil(x / (double)alignment) * alignment; } @Override public String toString() { return width + "x" + height + "@[" + minFramerate + ":" + maxFramerate + "]"; } @Override public boolean equals(Object that) { if (!(that instanceof CaptureFormat)) { return false; } final CaptureFormat c = (CaptureFormat) that; return width == c.width && height == c.height && maxFramerate == c.maxFramerate && minFramerate == c.minFramerate; } } // Returns device names that can be used to create a new VideoCapturerAndroid. public static String[] getDeviceNames() { String[] names = new String[Camera.getNumberOfCameras()]; for (int i = 0; i < Camera.getNumberOfCameras(); ++i) { names[i] = getDeviceName(i); } return names; } // Returns number of cameras on device. public static int getDeviceCount() { return Camera.getNumberOfCameras(); } // Returns the name of the camera with camera index. Returns null if the // camera can not be used. public static String getDeviceName(int index) { Camera.CameraInfo info = new Camera.CameraInfo(); try { Camera.getCameraInfo(index, info); } catch (Exception e) { Log.e(TAG, "getCameraInfo failed on index " + index,e); return null; } String facing = (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) ? "front" : "back"; return "Camera " + index + ", Facing " + facing + ", Orientation " + info.orientation; } // Returns the name of the front facing camera. Returns null if the // camera can not be used or does not exist. public static String getNameOfFrontFacingDevice() { for (int i = 0; i < Camera.getNumberOfCameras(); ++i) { Camera.CameraInfo info = new Camera.CameraInfo(); try { Camera.getCameraInfo(i, info); if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) return getDeviceName(i); } catch (Exception e) { Log.e(TAG, "getCameraInfo failed on index " + i, e); } } return null; } // Returns the name of the back facing camera. Returns null if the // camera can not be used or does not exist. public static String getNameOfBackFacingDevice() { for (int i = 0; i < Camera.getNumberOfCameras(); ++i) { Camera.CameraInfo info = new Camera.CameraInfo(); try { Camera.getCameraInfo(i, info); if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) return getDeviceName(i); } catch (Exception e) { Log.e(TAG, "getCameraInfo failed on index " + i, e); } } return null; } public static String getSupportedFormatsAsJson(int id) throws JSONException { List<CaptureFormat> formats = getSupportedFormats(id); JSONArray json_formats = new JSONArray(); for (CaptureFormat format : formats) { JSONObject json_format = new JSONObject(); json_format.put("width", format.width); json_format.put("height", format.height); json_format.put("framerate", (format.maxFramerate + 999) / 1000); json_formats.put(json_format); } Log.d(TAG, "Supported formats for camera " + id + ": " + json_formats.toString(2)); return json_formats.toString(); } // Helper class for finding the closest supported format for the two functions below. private static abstract class ClosestComparator<T> implements Comparator<T> { // Difference between supported and requested parameter. abstract int diff(T supportedParameter); @Override public int compare(T t1, T t2) { return diff(t1) - diff(t2); } } public static int[] getFramerateRange(Camera.Parameters parameters, final int framerate) { List<int[]> listFpsRange = parameters.getSupportedPreviewFpsRange(); if (listFpsRange.isEmpty()) { Log.w(TAG, "No supported preview fps range"); return new int[]{0, 0}; } return Collections.min(listFpsRange, new ClosestComparator<int[]>() { @Override int diff(int[] range) { return abs(framerate - range[Camera.Parameters.PREVIEW_FPS_MIN_INDEX]) + abs(framerate - range[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]); } }); } public static Camera.Size getClosestSupportedSize( List<Camera.Size> supportedSizes, final int requestedWidth, final int requestedHeight) { return Collections.min(supportedSizes, new ClosestComparator<Camera.Size>() { @Override int diff(Camera.Size size) { return abs(requestedWidth - size.width) + abs(requestedHeight - size.height); } }); } }
bsd-3-clause
NUBIC/psc-mirror
core/src/main/java/edu/northwestern/bioinformatics/studycalendar/xml/writers/StudyXmlSerializer.java
8164
package edu.northwestern.bioinformatics.studycalendar.xml.writers; import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException; import edu.northwestern.bioinformatics.studycalendar.domain.PlannedCalendar; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.StudySecondaryIdentifier; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment; import edu.northwestern.bioinformatics.studycalendar.xml.AbstractStudyCalendarXmlSerializer; import edu.northwestern.bioinformatics.studycalendar.xml.XsdAttribute; import edu.northwestern.bioinformatics.studycalendar.xml.XsdElement; import org.dom4j.Element; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.Required; import java.util.Date; import java.util.List; import static edu.northwestern.bioinformatics.studycalendar.xml.XsdAttribute.*; import static edu.northwestern.bioinformatics.studycalendar.xml.XsdElement.*; public class StudyXmlSerializer extends AbstractStudyCalendarXmlSerializer<Study> implements BeanFactoryAware { private StudySecondaryIdentifierXmlSerializer studySecondaryIdentifierXmlSerializer; private StudyXmlSerializerHelper studyXmlSerializerHelper; private PlannedCalendarXmlSerializer plannedCalendarXmlSerializer; private BeanFactory beanFactory; public Element createElement(Study study) { Element elt = XsdElement.STUDY.create(); STUDY_ASSIGNED_IDENTIFIER.addTo(elt, study.getAssignedIdentifier()); LAST_MODIFIED_DATE.addToDateTime(elt, study.getLastModifiedDate()); if (study.getProvider() != null) { STUDY_PROVIDER.addTo(elt, study.getProvider()); } if (study.getLongTitle() != null && study.getLongTitle().length() >0) { Element eltLongTitle = XsdElement.LONG_TITLE.create(); eltLongTitle.addText(study.getLongTitle()); elt.add(eltLongTitle); } for (StudySecondaryIdentifier studySecondaryIdent : study.getSecondaryIdentifiers()) { elt.add(studySecondaryIdentifierXmlSerializer.createElement(studySecondaryIdent)); } Element eCalendar = getPlannedCalendarXmlSerializer().createElement(study.getPlannedCalendar()); elt.add(eCalendar); for (Amendment amendment : study.getAmendmentsList()) { Element eAmendment = getAmendmentSerializer(study).createElement(amendment); elt.add(eAmendment); } if (study.getDevelopmentAmendment() != null) { Amendment developmentAmendment = study.getDevelopmentAmendment(); Element developmentAmendmentElement = getDevelopmentAmendmentSerializer(study).createElement(developmentAmendment); elt.add(developmentAmendmentElement); } Element eSources = studyXmlSerializerHelper.generateSourcesElementWithActivities(study); elt.add(eSources); return elt; } @Override @SuppressWarnings({"unchecked"}) public Study readElement(Element element) { validateElement(element); String key = XsdAttribute.STUDY_ASSIGNED_IDENTIFIER.from(element); Study study = new Study(); study.setAssignedIdentifier(key); String provider = STUDY_PROVIDER.from(element); if (provider != null && provider.length() > 0) { study.setProvider(provider); } Element eltLongTitle = element.element(LONG_TITLE.xmlName()); if (eltLongTitle != null) { String longTitleName = eltLongTitle.getText(); if (longTitleName != null && longTitleName.length() > 0) { study.setLongTitle(longTitleName.replaceAll("\\s+"," ").trim()); } } for(Element identifierElt:(List<Element>) element.elements("secondary-identifier")) { study.addSecondaryIdentifier(studySecondaryIdentifierXmlSerializer.readElement(identifierElt)); } Element eCalendar = element.element(PlannedCalendarXmlSerializer.PLANNED_CALENDAR); PlannedCalendar calendar = getPlannedCalendarXmlSerializer().readElement(eCalendar); study.setPlannedCalendar(calendar); List<Element> eAmendments = element.elements(XsdElement.AMENDMENT.xmlName()); Element currAmendment = findOriginalAmendment(eAmendments); while (currAmendment != null) { Amendment amendment = getAmendmentSerializer(study).readElement(currAmendment); study.pushAmendment(amendment); currAmendment = findNextAmendment(currAmendment, eAmendments); } Element developmentAmendmentElement = element.element(XsdElement.DEVELOPMENT_AMENDMENT.xmlName()); if (developmentAmendmentElement != null) { Amendment developmentAmendment = getDevelopmentAmendmentSerializer(study).readElement(developmentAmendmentElement); study.setDevelopmentAmendment(developmentAmendment); } studyXmlSerializerHelper.replaceActivityReferencesWithCorrespondingDefinitions(study, element); return study; } private void validateElement(Element element) { if (element.getName() != null && (!element.getName().equals(STUDY.xmlName()))) { throw new StudyCalendarValidationException("Element type is other than <study>"); } else if (element.elements(AMENDMENT.xmlName()).isEmpty() && element.element(DEVELOPMENT_AMENDMENT.xmlName()) == null) { throw new StudyCalendarValidationException("<study> must have at minimum an <amendment> or <development-amendment> child"); } } private Element findNextAmendment(Element currAmendment, List<Element> eAmendments) { String name = XsdAttribute.AMENDMENT_NAME.from(currAmendment); Date date = XsdAttribute.AMENDMENT_DATE.fromDate(currAmendment); String key = new Amendment.Key(date, name).toString(); for (Element amend : eAmendments) { if (key.equals(XsdAttribute.AMENDMENT_PREVIOUS_AMENDMENT_KEY.from(amend))) return amend; } return null; } private Element findOriginalAmendment(List<Element> eAmendments) { for (Element amend : eAmendments) { if (XsdAttribute.AMENDMENT_PREVIOUS_AMENDMENT_KEY.from(amend) == null) return amend; } return null; } private BeanFactory getBeanFactory() { return beanFactory; } public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } protected PlannedCalendarXmlSerializer getPlannedCalendarXmlSerializer() { return plannedCalendarXmlSerializer; } @Required public void setPlannedCalendarXmlSerializer(PlannedCalendarXmlSerializer plannedCalendarXmlSerializer) { this.plannedCalendarXmlSerializer = plannedCalendarXmlSerializer; } protected AmendmentXmlSerializer getAmendmentSerializer(Study study) { AmendmentXmlSerializer amendmentSerializer = (AmendmentXmlSerializer) getBeanFactory().getBean("amendmentXmlSerializer"); amendmentSerializer.setStudy(study); amendmentSerializer.setDevelopmentAmendment(false); return amendmentSerializer; } protected AmendmentXmlSerializer getDevelopmentAmendmentSerializer(Study study) { AmendmentXmlSerializer amendmentSerializer = (AmendmentXmlSerializer) getBeanFactory().getBean("amendmentXmlSerializer"); amendmentSerializer.setStudy(study); amendmentSerializer.setDevelopmentAmendment(true); return amendmentSerializer; } @Required public void setStudySecondaryIdentifierXmlSerializer(StudySecondaryIdentifierXmlSerializer studySecondaryIdentifierXmlSerializer) { this.studySecondaryIdentifierXmlSerializer = studySecondaryIdentifierXmlSerializer; } @Required public void setStudyXmlSerializerHelper(StudyXmlSerializerHelper studyXmlSerializerHelper) { this.studyXmlSerializerHelper = studyXmlSerializerHelper; } }
bsd-3-clause
motech-implementations/bbc-nms
masterdata/src/main/java/org/motechproject/nms/masterdata/repository/CircleDataService.java
612
package org.motechproject.nms.masterdata.repository; import org.motechproject.mds.annotations.Lookup; import org.motechproject.mds.annotations.LookupField; import org.motechproject.mds.service.MotechDataService; import org.motechproject.nms.masterdata.domain.Circle; /** * This interface is used to operate on Circle Csv using Motech Data service */ public interface CircleDataService extends MotechDataService<Circle> { /** * Finds the Circle details by its code * * @param code * @return Circle */ @Lookup Circle findByCode(@LookupField(name = "code") String code); }
bsd-3-clause
mhems/jhelp
src/com/binghamton/jhelp/JHelp.java
1215
package com.binghamton.jhelp; import com.binghamton.jhelp.util.Logger; import com.binghamton.jhelp.validators.*; /** * JHelp application entry point */ public class JHelp { public static final String VERSION = "1.0.1"; /** * Construct a new JHelp instance */ private JHelp() { // prevent public instantiation } /** * Main method to invoke jhelp application * @param args user-provided command-line arguments */ public static void main(String[] args) { JHelpRunner runner = new JHelpRunner(args); runner.addValidator(new EnvironmentValidator()); runner.addValidator(new UsageValidator()); runner.addValidator(new BalancedValidator()); runner.addValidator(new SyntaxValidator()); if (Program.config.PRETTY_PRINT) { runner.addValidator(new ASTPrinter()); } else { runner.addValidator(new TopLevelValidator()); MemberLevelValidator mV = new MemberLevelValidator(); runner.addValidator(mV); runner.addValidator(new CodeLevelValidator(mV)); } int rc = runner.run(); Logger.close(); System.exit(rc); } }
bsd-3-clause
jrialland/jrc
src/main/java/net/jr/jrc/qvm/syscalls/BasicIO.java
838
package net.jr.jrc.qvm.syscalls; import java.io.IOException; import java.io.Reader; import java.io.Writer; import net.jr.jrc.qvm.QvmInterpreter; /** * Created by julien on 10/10/16. */ public class BasicIO { private Reader in; private Writer out; public BasicIO(Reader in, Writer out) { this.in = in; this.out = out; } @QvmSyscall(1) public int putc(QvmInterpreter interpreter) { int i = interpreter.getStack().popInt(); try { out.write(i); } catch(IOException e) { throw new RuntimeException(e); } return 0; } @QvmSyscall(2) public int getc(QvmInterpreter interpreter) { try { return in.read(); } catch(IOException e) { throw new RuntimeException(e); } } }
bsd-3-clause
DevilTech/RobotObserverer
src/edu/wpi/first/wpilibj/templates/JoyButton.java
1400
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.Joystick; public class JoyButton { boolean[] buttonstates = new boolean[10]; final int a = 1; final int b = 2; final int x = 3; final int y = 4; final int lb = 5; final int rb = 6; final int back = 7; final int start = 8; final int lstick = 9; final int rstick = 10; boolean isPressed; Joystick joy; public JoyButton(Joystick joy){ this.joy = joy; for (int i = 1; i < 10; i++ ){ buttonstates[i-1] = false; } } final public boolean isNewPress(int button){ if( joy.getRawButton(button)){ if(buttonstates[button-1]){ return false; }else{ buttonstates[button-1] = true; return true; } }else{ buttonstates[button-1] = false; return false; } } final public boolean isNewOff(int button){ if( !joy.getRawButton(button)){ if(!buttonstates[button-1]){ return false; }else{ buttonstates[button-1] = false; return true; } }else{ buttonstates[button-1] = true; return false; } } }
bsd-3-clause
mikem2005/vijava
src/com/vmware/vim25/VmfsAmbiguousMount.java
1773
/*================================================================================ Copyright (c) 2009 VMware, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 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. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. 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 com.vmware.vim25; /** @author Steve Jin (sjin@vmware.com) */ public class VmfsAmbiguousMount extends VmfsMountFault { }
bsd-3-clause
tmr1/JavaGcUtils
src/tmr/utils/GcUtils.java
7779
/* Copyright 2017 tmr 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. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package tmr.utils; import java.lang.reflect.Field; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * <b>TL;DR:</b> Using this code can easily cause the JVM to stop running! Don't use this unless you really know what you are doing! * <br><br>This class contains methods that are experimental and will often in many cases cause the JVM to freeze and or crash and or cause other unexpected things. * <br><br>This is Java code that will disable (or at least prevent) the Garbage Collector in Java from running! It does so by locking an object that the GC needs to be able to perform the GC. * <br><br>This obviously has some bad side effects. But if you know what you are doing, how much memory you have and what your Java program will need in the future, this might be a useful program for you. <br>Obviously by preventing the GC from running memory will never get released and much [free] memory won't even be able to be used! So make sure you know what you are doing before using this. * <br><br>This is probably <b>NOT</b> safe for production code, but can be used to play around with and experiment with. <br>You can for instance use it to prevent the GC from running during critical sections (sections you need to run quickly without any interruptions from the GC) giving you a more exact run time. <br>You should make sure to enable the GC again before too much happens and the JVM stops running! * <br><br>This code will probably run on most platforms (Windows, Linux etc.) with OpenJDK and Oracle's JDK versions 8 & 9. However since this program is based on a specific object that the JVM needs to run the GC it might not work on all implementations since they might implement the GC differently or in future version which might change this. This code would probably even run on OpenJDK or Oracle's JDK versions 5-7 if you get rid of the use of Functional Interfaces. * <br><br>Using this program can easily cause a JVM to crash - or at least stop running! * <br><br><b>Note:</b> New objects are allocated to the Eden part of the heap, so even if you set your heap to be 8 gigabytes you can only use the Eden part which is by default considerbly smaller * * @author tmr * @version 1.0 */ public final class GcUtils { /** * Possible statuses that can be returned when disabling/enabling the Garbage Collection * @author tmr1 * @version 1.0 */ public enum Status { STARTED, IS_ALREADY_RUNNING, IS_NOT_RUNNING, STOPPED, FAILED_TO_DISABLE_GC_DUE_TO_ERROR } /** * This lock makes sure that {@link #enableGc} and {@link #disableGc} won't be called multiple times at the same time */ private static final Lock enableDisableGcLock = new ReentrantLock(); /** * The lock used to create a condition to wait on until it is released - the Garbage Collection is enabled again */ private static final Lock waitingLock = new ReentrantLock(); /** * The condition to wait on until it is released - the Garbage Collection is enabled again */ private static final Condition waitingLockCondition = GcUtils.waitingLock.newCondition(); /** * The thread that keeps the synchronization on {@link #gcLock} */ private static volatile Thread thread = null; /** * The object that the JVM tries to synchronize on in order to run garbage collection, * which is what this feature synchronizes on in order to prevent the Garbage Collection */ private static volatile Object gcLock = null; /** * "Disables" the JVM's Garbage Collection * This method basically synchronizes on an object used by the JRE's Garbage Collection which thereby prevents the Garbage Collection from running. * <br><br><b>NOTE:</b> This method can cause the JVM to freeze and/or crash or not function well in other ways. * This Function is inherently unstable and more of an experimental feature than a production feature. * This method may or may not function, depending on on which JVM, JVM version and platform. * @return the result from attempting to disable the Garbage Collection */ public static Status disableGc() { GcUtils.enableDisableGcLock.lock(); try { if(GcUtils.gcLock == null) { final Field gcLockField; try { gcLockField = java.lang.ref.Reference.class.getDeclaredField("lock"); } catch (final NoSuchFieldException e) { e.printStackTrace(); return Status.FAILED_TO_DISABLE_GC_DUE_TO_ERROR; } catch (final SecurityException e) { e.printStackTrace(); return Status.FAILED_TO_DISABLE_GC_DUE_TO_ERROR; } gcLockField.setAccessible(true); try { GcUtils.gcLock = gcLockField.get(null); } catch (final IllegalArgumentException e) { e.printStackTrace(); return Status.FAILED_TO_DISABLE_GC_DUE_TO_ERROR; } catch (final IllegalAccessException e) { e.printStackTrace(); return Status.FAILED_TO_DISABLE_GC_DUE_TO_ERROR; } } if(GcUtils.thread != null) { return Status.IS_ALREADY_RUNNING; } Runtime.getRuntime().gc(); GcUtils.thread = new Thread(() -> { synchronized (GcUtils.gcLock) { GcUtils.waitingLock.lock(); try { GcUtils.waitingLockCondition.awaitUninterruptibly(); } finally { GcUtils.waitingLock.unlock(); } } }, "GC Disabler Thread"); thread.start(); return Status.STARTED; } finally { GcUtils.enableDisableGcLock.unlock(); } } /** * "Enables" the JVM's Garbage Collection * This method "enables" the JVM's Garbage Collection again after it has been disabled by {@link #disableGc} * @return the result from attempting to enable the Garbage Collection */ public static Status enableGc() { GcUtils.enableDisableGcLock.lock(); try { if(GcUtils.thread == null || GcUtils.gcLock == null) { return Status.IS_NOT_RUNNING; } GcUtils.thread = null; GcUtils.waitingLock.lock(); try { GcUtils.waitingLockCondition.signalAll(); } finally { GcUtils.waitingLock.unlock(); } return Status.STOPPED; } finally { Runtime.getRuntime().gc(); GcUtils.enableDisableGcLock.unlock(); } } }
bsd-3-clause
exponentjs/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/notifications/notifications/channels/AndroidXNotificationsChannelsProvider.java
1844
package abi44_0_0.expo.modules.notifications.notifications.channels; import android.content.Context; import abi44_0_0.expo.modules.notifications.notifications.channels.managers.AndroidXNotificationsChannelGroupManager; import abi44_0_0.expo.modules.notifications.notifications.channels.managers.AndroidXNotificationsChannelManager; import abi44_0_0.expo.modules.notifications.notifications.channels.managers.NotificationsChannelGroupManager; import abi44_0_0.expo.modules.notifications.notifications.channels.managers.NotificationsChannelManager; import abi44_0_0.expo.modules.notifications.notifications.channels.serializers.ExpoNotificationsChannelGroupSerializer; import abi44_0_0.expo.modules.notifications.notifications.channels.serializers.ExpoNotificationsChannelSerializer; import abi44_0_0.expo.modules.notifications.notifications.channels.serializers.NotificationsChannelGroupSerializer; import abi44_0_0.expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer; public class AndroidXNotificationsChannelsProvider extends AbstractNotificationsChannelsProvider { public AndroidXNotificationsChannelsProvider(Context context) { super(context); } @Override protected NotificationsChannelManager createChannelManager() { return new AndroidXNotificationsChannelManager(mContext, getGroupManager()); } @Override protected NotificationsChannelGroupManager createChannelGroupManager() { return new AndroidXNotificationsChannelGroupManager(mContext); } @Override protected NotificationsChannelSerializer createChannelSerializer() { return new ExpoNotificationsChannelSerializer(); } @Override protected NotificationsChannelGroupSerializer createChannelGroupSerializer() { return new ExpoNotificationsChannelGroupSerializer(getChannelSerializer()); } }
bsd-3-clause
Griffins-1884/RobotCode2012
WPILibJ/src/edu/wpi/first/wpilibj/Resource.java
4624
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.util.AllocationException; import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * Track resources in the program. * The Resource class is a convenient way of keeping track of allocated arbitrary resources * in the program. Resources are just indicies that have an lower and upper bound that are * tracked by this class. In the library they are used for tracking allocation of hardware channels * but this is purely arbitrary. The resource class does not do any actual allocation, but * simply tracks if a given index is currently in use. * * WARNING: this should only be statically allocated. When the program loads into memory all the * static constructors are called. At that time a linked list of all the "Resources" is created. * Then when the program actually starts - in the Robot constructor, all resources are initialized. * This ensures that the program is restartable in memory without having to unload/reload. */ public class Resource { private static Resource m_resourceList = null; private final boolean m_numAllocated[]; private final int m_size; private final Resource m_nextResource; /** * Clears all allocated resources */ public static void restartProgram() { for (Resource r = Resource.m_resourceList; r != null; r = r.m_nextResource) { for (int i = 0; i < r.m_size; i++) { r.m_numAllocated[i] = false; } } } /** * Allocate storage for a new instance of Resource. * Allocate a bool array of values that will get initialized to indicate that no resources * have been allocated yet. The indicies of the resources are 0..size-1. * * @param size The number of blocks to allocate */ public Resource(final int size) { m_size = size; m_numAllocated = new boolean[m_size]; for (int i = 0; i < m_size; i++) { m_numAllocated[i] = false; } m_nextResource = Resource.m_resourceList; Resource.m_resourceList = this; } /** * Allocate a resource. * When a resource is requested, mark it allocated. In this case, a free resource value * within the range is located and returned after it is marked allocated. * * @return The index of the allocated block. * @throws CheckedAllocationException If there are no resources available to be allocated. */ public int allocate() throws CheckedAllocationException { for (int i = 0; i < m_size; i++) { if (m_numAllocated[i] == false) { m_numAllocated[i] = true; return i; } } throw new CheckedAllocationException("No available resources"); } /** * Allocate a specific resource value. * The user requests a specific resource value, i.e. channel number and it is verified * unallocated, then returned. * * @param index The resource to allocate * @return The index of the allocated block * @throws CheckedAllocationException If there are no resources available to be allocated. */ public int allocate(final int index) throws CheckedAllocationException { if (index >= m_size) { throw new CheckedAllocationException("Index " + index + " out of range"); } if (m_numAllocated[index] == true) { throw new CheckedAllocationException("Resource at index " + index + " already allocated"); } m_numAllocated[index] = true; return index; } /** * Free an allocated resource. * After a resource is no longer needed, for example a destructor is called for a channel assignment * class, Free will release the resource value so it can be reused somewhere else in the program. * * @param index The index of the resource to free. */ public void free(final int index) { if (m_numAllocated[index] == false) throw new AllocationException("No resource available to be freed"); m_numAllocated[index] = false; } }
bsd-3-clause
mhems/jhelp
src/com/binghamton/jhelp/types/NilType.java
1256
package com.binghamton.jhelp.types; import java.util.Map; import com.binghamton.jhelp.symbols.ClassSymbol; /** * A singleton class to represent the type of a null reference */ public final class NilType extends Type { public static final NilType TYPE = new NilType(); /** * Constructs a new NilType */ private NilType() { // prevent public instantiation } @Override public NilType copy() { return TYPE; } @Override public String getTypeName() { return "null"; } @Override public String getName() { return "null"; } @Override public ClassSymbol getClassSymbol() { throw new UnsupportedOperationException("the nil type represents no class"); } @Override public ClassSymbol getDeclaringClass() { throw new UnsupportedOperationException("the nil type has no declaring class"); } @Override public boolean isReference() { return false; } @Override public Type adapt(Map<TypeVariable, Type> map) { return this; } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return 31; } }
bsd-3-clause
patrickm/chromium.src
content/public/android/javatests/src/org/chromium/content/browser/ContentViewScrollingTest.java
8069
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser; import android.content.res.Configuration; import android.graphics.Canvas; import android.os.SystemClock; import android.test.suitebuilder.annotation.SmallTest; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.UrlUtils; import org.chromium.content.browser.ContentViewCore.InternalAccessDelegate; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.content_shell_apk.ContentShellTestBase; /* * Tests that we can scroll and fling a ContentView running inside ContentShell. */ public class ContentViewScrollingTest extends ContentShellTestBase { private static final String LARGE_PAGE = UrlUtils.encodeHtmlDataUri( "<html><head>" + "<meta name=\"viewport\" content=\"width=device-width, " + "initial-scale=2.0, maximum-scale=2.0\" />" + "<style>body { width: 5000px; height: 5000px; }</style></head>" + "<body>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</body>" + "</html>"); /** * InternalAccessDelegate to ensure AccessibilityEvent notifications (Eg:TYPE_VIEW_SCROLLED) * are being sent properly on scrolling a page. */ static class TestInternalAccessDelegate implements InternalAccessDelegate { private boolean mScrollChanged; private final Object mLock = new Object(); @Override public boolean drawChild(Canvas canvas, View child, long drawingTime) { return false; } @Override public boolean super_onKeyUp(int keyCode, KeyEvent event) { return false; } @Override public boolean super_dispatchKeyEventPreIme(KeyEvent event) { return false; } @Override public boolean super_dispatchKeyEvent(KeyEvent event) { return false; } @Override public boolean super_onGenericMotionEvent(MotionEvent event) { return false; } @Override public void super_onConfigurationChanged(Configuration newConfig) { } @Override public void onScrollChanged(int lPix, int tPix, int oldlPix, int oldtPix) { synchronized (mLock) { mScrollChanged = true; } } @Override public boolean awakenScrollBars() { return false; } @Override public boolean super_awakenScrollBars(int startDelay, boolean invalidate) { return false; } /** * @return Whether OnScrollChanged() has been called. */ public boolean isScrollChanged() { synchronized (mLock) { return mScrollChanged; } } } private void assertWaitForScroll(final boolean hugLeft, final boolean hugTop) throws InterruptedException { assertTrue(CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { // Scrolling and flinging don't result in exact coordinates. final int MIN_THRESHOLD = 5; final int MAX_THRESHOLD = 100; boolean xCorrect = hugLeft ? getContentViewCore().getNativeScrollXForTest() < MIN_THRESHOLD : getContentViewCore().getNativeScrollXForTest() > MAX_THRESHOLD; boolean yCorrect = hugTop ? getContentViewCore().getNativeScrollYForTest() < MIN_THRESHOLD : getContentViewCore().getNativeScrollYForTest() > MAX_THRESHOLD; return xCorrect && yCorrect; } })); } private void fling(final int vx, final int vy) throws Throwable { runTestOnUiThread(new Runnable() { @Override public void run() { getContentView().fling(SystemClock.uptimeMillis(), 0, 0, vx, vy); } }); } private void scrollTo(final int x, final int y) throws Throwable { runTestOnUiThread(new Runnable() { @Override public void run() { getContentView().scrollTo(x, y); } }); } @Override protected void setUp() throws Exception { super.setUp(); launchContentShellWithUrl(LARGE_PAGE); assertTrue("Page failed to load", waitForActiveShellToBeDoneLoading()); assertWaitForPageScaleFactorMatch(2.0f); assertEquals(0, getContentViewCore().getNativeScrollXForTest()); assertEquals(0, getContentViewCore().getNativeScrollYForTest()); } @SmallTest @Feature({"Main"}) public void testFling() throws Throwable { // Vertical fling to lower-left. fling(0, -1000); assertWaitForScroll(true, false); // Horizontal fling to lower-right. fling(-1000, 0); assertWaitForScroll(false, false); // Vertical fling to upper-right. fling(0, 1000); assertWaitForScroll(false, true); // Horizontal fling to top-left. fling(1000, 0); assertWaitForScroll(true, true); // Diagonal fling to bottom-right. fling(-1000, -1000); assertWaitForScroll(false, false); } @SmallTest @Feature({"Main"}) public void testScroll() throws Throwable { // Vertical scroll to lower-left. scrollTo(0, 2500); assertWaitForScroll(true, false); // Horizontal scroll to lower-right. scrollTo(2500, 2500); assertWaitForScroll(false, false); // Vertical scroll to upper-right. scrollTo(2500, 0); assertWaitForScroll(false, true); // Horizontal scroll to top-left. scrollTo(0, 0); assertWaitForScroll(true, true); // Diagonal scroll to bottom-right. scrollTo(2500, 2500); assertWaitForScroll(false, false); } /** * To ensure the device properly responds to bounds-exceeding scrolls, e.g., overscroll * effects are properly initialized. */ @SmallTest @Feature({"Main"}) public void testOverScroll() throws Throwable { // Overscroll lower-left. scrollTo(-10000, 10000); assertWaitForScroll(true, false); // Overscroll lower-right. scrollTo(10000, 10000); assertWaitForScroll(false, false); // Overscroll upper-right. scrollTo(10000, -10000); assertWaitForScroll(false, true); // Overscroll top-left. scrollTo(-10000, -10000); assertWaitForScroll(true, true); // Diagonal overscroll lower-right. scrollTo(10000, 10000); assertWaitForScroll(false, false); } /** * To ensure the AccessibilityEvent notifications (Eg:TYPE_VIEW_SCROLLED) are being sent * properly on scrolling a page. */ @SmallTest @Feature({"Main"}) public void testOnScrollChanged() throws Throwable { final int scrollToX = 2500; final int scrollToY = 2500; final TestInternalAccessDelegate containerViewInternals = new TestInternalAccessDelegate(); runTestOnUiThread(new Runnable() { @Override public void run() { getContentViewCore().setContainerViewInternals(containerViewInternals); } }); scrollTo(scrollToX, scrollToY); assertWaitForScroll(false, false); assertTrue(CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { return containerViewInternals.isScrollChanged(); } })); } }
bsd-3-clause
NCIP/i-spy
src/gov/nih/nci/ispy/web/helper/P53Retriever.java
1969
/*L * Copyright SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/i-spy/LICENSE.txt for details. */ package gov.nih.nci.ispy.web.helper; import gov.nih.nci.ispy.util.ispyConstants; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.struts.util.LabelValueBean; public class P53Retriever { private Map lookupMap; public P53Retriever(HttpSession session){ this.lookupMap = (Map) session.getAttribute(ispyConstants.UI_LOOKUPS); } public List getMutationStatuses(){ Collection mutationStatusCollectiion = (Collection) lookupMap.get(ispyConstants.P53_MUTATION_STATUS); ArrayList<String> mutationStatusList = new ArrayList<String>(mutationStatusCollectiion); ArrayList<LabelValueBean> mutationStatusCollectiionList = new ArrayList<LabelValueBean>(); for(String mutationStatusName: mutationStatusList){ if(mutationStatusName.equalsIgnoreCase("MUTANT")||mutationStatusName.equalsIgnoreCase("WILDTYPE")){ mutationStatusCollectiionList.add(new LabelValueBean(mutationStatusName,mutationStatusName)); } } return mutationStatusCollectiionList; } public List getMutationTypes(){ Collection mutationTypeCollectiion = (Collection) lookupMap.get(ispyConstants.P53_MUTATION_TYPE); ArrayList<String> mutationtypeList = new ArrayList<String>(mutationTypeCollectiion); ArrayList<LabelValueBean> mutationTypeCollectiionList = new ArrayList<LabelValueBean>(); for(String mutationTypeName: mutationtypeList){ mutationTypeCollectiionList.add(new LabelValueBean(mutationTypeName,mutationTypeName)); } return mutationTypeCollectiionList; } }
bsd-3-clause
messagebird/java-rest-api
examples/src/main/java/ExampleReadBalance.java
1414
import com.messagebird.MessageBirdClient; import com.messagebird.MessageBirdService; import com.messagebird.MessageBirdServiceImpl; import com.messagebird.exceptions.GeneralException; import com.messagebird.exceptions.NotFoundException; import com.messagebird.exceptions.UnauthorizedException; import com.messagebird.objects.Balance; /** * Created by rvt on 1/5/15. */ public class ExampleReadBalance { public static void main(String[] args) { if (args.length == 0) { System.out.println("Please specify your access key example : java -jar <this jar file> test_accesskey"); return; } // First create your service object final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); // Add the service to the client final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { // Get Balance System.out.println("Retrieving your balance:"); final Balance balance = messageBirdClient.getBalance(); // Display balance System.out.println(balance.toString()); } catch (UnauthorizedException | GeneralException | NotFoundException exception) { if (exception.getErrors() != null) { System.out.println(exception.getErrors().toString()); } exception.printStackTrace(); } } }
bsd-3-clause
thelateperseus/ant-ivy
src/java/fr/jayasoft/ivy/report/DownloadStatus.java
699
/* * This file is subject to the license found in LICENCE.TXT in the root directory of the project. * * #SNAPSHOT# */ package fr.jayasoft.ivy.report; /** * @author x.hanin * */ public class DownloadStatus { private String _name; private DownloadStatus(String name) { _name = name; } /** * means that download was not required */ public static final DownloadStatus NO = new DownloadStatus("no"); public static final DownloadStatus SUCCESSFUL = new DownloadStatus("successful"); public static final DownloadStatus FAILED = new DownloadStatus("failed"); public String toString() { return _name; } }
bsd-3-clause
NCIP/national-biomedical-image-archive
docs/analysis_and_design/5.1/CedaraAIMMapingTo3_0/code/com/mapforce/MappingConsole.java
4099
/*L * Copyright SAIC, Ellumen and RSNA (CTP) * * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/national-biomedical-image-archive/LICENSE.txt for details. */ /** * MappingConsole.java * * This file was generated by MapForce 2011r2sp1. * * YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE * OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. * * Refer to the MapForce Documentation for further details. * http://www.altova.com/mapforce */ package com.mapforce; import com.altova.types.*; import com.altova.io.*; import java.io.File; import java.io.InputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.BufferedReader; public class MappingConsole { public static void main(String[] args) { System.out.println("Mapping Application"); try { // Mapping TraceTargetConsole ttc = new TraceTargetConsole(); MappingMapToAIM_v3_rv9_XML MappingMapToAIM_v3_rv9_XMLObject = new MappingMapToAIM_v3_rv9_XML(); MappingMapToAIM_v3_rv9_XMLObject.registerTraceTarget(ttc); { //String filePath = "C:/workspace_nbia/software/cedaraAIMMapping/map/cedaraAIMtest2.xml"; String filePath = args[0]; System.out.println("Transform "+ filePath); String xmlcontent=""; File file = new File(filePath); long length = file.length(); byte[] array = new byte[(int) length]; InputStream in = new FileInputStream(file); long offset = 0; while (offset < length) { int count = in.read(array, (int) offset, (int) (length - offset)); offset += length; } in.close(); //xmlcontent = new String(array, "UTF-8"); xmlcontent = new String(array, "UTF-16"); //System.out.println("!!!!!!xmlcontent="+xmlcontent); String regex= "xsi:schemaLocation=\"gme://caCORE.caCORE/3.2/edu.northwestern.radiology.AIM C:/workspace_nbia/nbia-aim/cederaAIM/AIM_v2_rv15_XML.xsd\" xmlns=\"gme://caCORE.caCORE/3.2/edu.northwestern.radiology.AIM\""; xmlcontent = xmlcontent.replaceAll(regex, ""); String regex2 = "xmlns=\"gme://caCORE.caCORE/3.2/edu.northwestern.radiology.AIM\""; xmlcontent = xmlcontent.replaceAll(regex2, ""); xmlcontent = xmlcontent.replaceAll("n1:", ""); //String regex3 = "xsi:schemaLocation=\"xsi:schemaLocation=\"gme://caCORE.caCORE/3.2/edu.northwestern.radiology.AIM C:/workspace_nbia/nbia-aim/cederaAIM/AIM_v2_rv15_XML.xsd\""; //xmlcontent.replaceAll(regex3, ""); String regex4 = "xmlns:n1=\"gme://caCORE.caCORE/3.2/edu.northwestern.radiology.AIM\""; xmlcontent = xmlcontent.replace(regex4, ""); //System.out.println("xmlcontent="+xmlcontent); com.altova.io.Input generatedAIMSchema112Source = new com.altova.io.StringInput(xmlcontent); //com.altova.io.Input generatedAIMSchema112Source = com.altova.io.StreamInput.createInput("C:/workspace_nbia/software/cedaraAIMMapping/map/cedaraAIM.xml"); MappingMapToAIM_v3_rv9_XMLObject.run( generatedAIMSchema112Source); } System.out.println("Finished"); } catch (com.altova.UserException ue) { System.out.print("USER EXCEPTION:"); System.out.println( ue.getMessage() ); System.exit(1); } catch (com.altova.AltovaException e) { System.out.print("ERROR: "); System.out.println( e.getMessage() ); if (e.getInnerException() != null) { System.out.print("Inner exception: "); System.out.println(e.getInnerException().getMessage()); if (e.getInnerException().getCause() != null) { System.out.print("Cause: "); System.out.println(e.getInnerException().getCause().getMessage()); } } System.out.println("\nStack Trace: "); e.printStackTrace(); System.exit(1); } catch (Exception e) { System.out.print("ERROR: "); System.out.println( e.getMessage() ); System.out.println("\nStack Trace: "); e.printStackTrace(); System.exit(1); } } } class TraceTargetConsole implements com.altova.TraceTarget { public void writeTrace(String info) { System.out.println(info); } }
bsd-3-clause
wysekm/DistributedSystemMonitoring
DSM-common/src/main/java/pl/edu/agh/dsm/common/repository/MeasurementRepositoryImpl.java
1556
package pl.edu.agh.dsm.common.repository; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import pl.edu.agh.dsm.common.dto.MeasurementDto; import java.util.List; import java.util.NoSuchElementException; import java.util.UUID; @Component public class MeasurementRepositoryImpl implements MeasurementRepository { static final Logger logger = LoggerFactory .getLogger(MeasurementRepositoryImpl.class); static List<MeasurementDto> repo = Lists.newArrayList(); @Override public List<MeasurementDto> findAll(Predicate<MeasurementDto> preconditions) { logger.debug("find all measurements with conditions {}", preconditions); return Lists.newArrayList(Iterables.filter(repo, preconditions)); } @Override public MeasurementDto find(final UUID uuid) { logger.debug("find measurement with id {}", uuid); try { return Iterables.find(repo, new Predicate<MeasurementDto>() { @Override public boolean apply(MeasurementDto measurementDto) { return measurementDto.getId().equals(uuid); } }); } catch (NoSuchElementException e) { return null; } } @Override public void remove(UUID uuid) { logger.debug("remove measurement with id {}", uuid); repo.remove(find(uuid)); } @Override public void save(MeasurementDto measurementDto) { logger.debug("save measurement {}", measurementDto); repo.add(measurementDto); } }
bsd-3-clause
googleapis/api-client-staging
generated/java/proto-google-common-protos/src/main/java/com/google/api/ControlOrBuilder.java
787
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/control.proto package com.google.api; public interface ControlOrBuilder extends // @@protoc_insertion_point(interface_extends:google.api.Control) com.google.protobuf.MessageOrBuilder { /** * <pre> * The service control environment to use. If empty, no control plane * feature (like quota and billing) will be enabled. * </pre> * * <code>string environment = 1;</code> */ String getEnvironment(); /** * <pre> * The service control environment to use. If empty, no control plane * feature (like quota and billing) will be enabled. * </pre> * * <code>string environment = 1;</code> */ com.google.protobuf.ByteString getEnvironmentBytes(); }
bsd-3-clause
wsldl123292/jodd
jodd-vtor/src/main/java/jodd/vtor/constraint/MaxConstraint.java
1151
// Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved. package jodd.vtor.constraint; import jodd.typeconverter.Convert; import jodd.vtor.ValidationConstraint; import jodd.vtor.ValidationConstraintContext; public class MaxConstraint implements ValidationConstraint<Max> { public MaxConstraint() { } public MaxConstraint(double max) { this.max = max; } // ---------------------------------------------------------------- properties protected double max; public double getMax() { return max; } public void setMax(double max) { this.max = max; } // ---------------------------------------------------------------- configure public void configure(Max annotation) { this.max = annotation.value(); } // ---------------------------------------------------------------- valid public boolean isValid(ValidationConstraintContext vcc, Object value) { return validate(value, max); } public static boolean validate(Object value, double max) { if (value == null) { return true; } double val = Convert.toDoubleValue(value); return val < max; } }
bsd-3-clause
xe1gyq/OpenAttestation
integration/api-client-jar/src/main/java/com/intel/mtwilson/client/cmd/GetHostTrust.java
2316
/* * Copyright (c) 2013, Intel Corporation. * All rights reserved. * * The contents of this file are released under the BSD license, you may not use this file except in compliance with the License. * * 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. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.intel.mtwilson.client.cmd; import com.intel.mtwilson.ApiClient; import com.intel.mtwilson.client.AbstractCommand; import com.intel.mtwilson.datatypes.HostTrustResponse; import com.intel.mtwilson.datatypes.Hostname; /** * HostTrustResponse getHostTrust(Hostname hostname) throws IOException, ApiException, SignatureException; * * @author jbuhacoff */ public class GetHostTrust extends AbstractCommand { @Override public void execute(String[] args) throws Exception { ApiClient api = getClient(); HostTrustResponse response = api.getHostTrust(new Hostname(args[0])); System.out.println(toJson(response)); } }
bsd-3-clause
rbielak/Java-Abra
src/org/ephman/examples/family/SystemCodes.java
275
package org.ephman.examples.family; /** * a ValidationCodes for example * @version Tue Jan 15 14:20:14 EST 2002 * @author Paul Bethe */ public interface SystemCodes extends org.ephman.abra.validation.ValidationCodes { public static final int INVALID_STATE = 100; }
bsd-3-clause
aic-sri-international/aic-expresso
src/test/java/com/sri/ai/test/expresso/DefaultSymbolTest.java
11110
package com.sri.ai.test.expresso; import java.math.MathContext; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.sri.ai.expresso.ExpressoConfiguration; import com.sri.ai.expresso.helper.Expressions; import com.sri.ai.util.math.Rational; public class DefaultSymbolTest { int oldExactPrecision; int oldApproximatePrecision; boolean oldDisplayExact; int oldScientificGreater; int oldScientificAfter; @Before public void setUp() { oldExactPrecision = ExpressoConfiguration.setDisplayNumericsMostDecimalPlacesInExactRepresentationOfNumericalSymbols(1500); oldApproximatePrecision = ExpressoConfiguration.setDisplayNumericsMostDecimalPlacesInApproximateRepresentationOfNumericalSymbols(2); oldDisplayExact = ExpressoConfiguration.setDisplayNumericsExactlyForSymbols(false); oldScientificGreater = ExpressoConfiguration.setDisplayNumericsMostIntegerPlacesBeforeSwitchingToScientificNotation(6); oldScientificAfter = ExpressoConfiguration.setDisplayNumericsGreatestInitialNonZeroDecimalPlacePositionBeforeSwitchingToScientificNotation(4); // Ensure we are in approximation mode (i.e. the default) for these tests Rational.resetApproximationConfiguration(true, MathContext.DECIMAL128.getPrecision(), MathContext.DECIMAL128.getRoundingMode()); } @After public void tearDown() { ExpressoConfiguration.setDisplayNumericsMostDecimalPlacesInExactRepresentationOfNumericalSymbols(oldExactPrecision); ExpressoConfiguration.setDisplayNumericsMostDecimalPlacesInApproximateRepresentationOfNumericalSymbols(oldApproximatePrecision); ExpressoConfiguration.setDisplayNumericsExactlyForSymbols(oldDisplayExact); ExpressoConfiguration.setDisplayNumericsMostIntegerPlacesBeforeSwitchingToScientificNotation(oldScientificGreater); ExpressoConfiguration.setDisplayNumericsGreatestInitialNonZeroDecimalPlacePositionBeforeSwitchingToScientificNotation(oldScientificAfter); Rational.resetApproximationConfigurationFromAICUtilConfiguration(); } @Test public void testDisplayExact() { // NOTE: the tearDown method will set us back to the correct default. ExpressoConfiguration.setDisplayNumericsExactlyForSymbols(true); Assert.assertEquals("0.1", Expressions.makeSymbol(new Rational(1,10)).toString()); Assert.assertEquals("1.1", Expressions.makeSymbol(new Rational(11,10)).toString()); Assert.assertEquals("2/3", Expressions.makeSymbol(new Rational(2,3)).toString()); Assert.assertEquals("0.123456789", Expressions.makeSymbol(new Rational(123456789,1000000000)).toString()); Assert.assertEquals("0.999999999999999", Expressions.makeSymbol(new Rational(999999999999999L, 1000000000000000L)).toString()); Assert.assertEquals("1/3", Expressions.makeSymbol(new Rational(1, 3)).toString()); Assert.assertEquals("1/7", Expressions.makeSymbol(new Rational(1, 7)).toString()); Assert.assertEquals("-0.1", Expressions.makeSymbol(new Rational(-1,10)).toString()); Assert.assertEquals("-1.1", Expressions.makeSymbol(new Rational(-11,10)).toString()); Assert.assertEquals("-2/3", Expressions.makeSymbol(new Rational(-2,3)).toString()); Assert.assertEquals("-0.123456789", Expressions.makeSymbol(new Rational(-123456789,1000000000)).toString()); Assert.assertEquals("-0.999999999999999", Expressions.makeSymbol(new Rational(-999999999999999L, 1000000000000000L)).toString()); Assert.assertEquals("-1/3", Expressions.makeSymbol(new Rational(-1, 3)).toString()); Assert.assertEquals("-1/7", Expressions.makeSymbol(new Rational(-1, 7)).toString()); } @Test public void testDisplayLargeExact() { // NOTE: the tearDown method will set us back to the correct default. ExpressoConfiguration.setDisplayNumericsExactlyForSymbols(true); Rational largeRational = new Rational(3).pow(100000); Assert.assertEquals("1.334971414230401469458914390489782E47712", Expressions.makeSymbol(largeRational).toString()); largeRational = new Rational(3).pow(100000).divide(new Rational(7).pow(100)); Assert.assertEquals("1.334971414230401469458914390489782E+47661/3234476509624757991344647769100217", Expressions.makeSymbol(largeRational).toString()); } @Test public void testDisplayLargeApproximateNumber() { Rational largeRational = new Rational(3).pow(100000); Assert.assertEquals("1.33E47712", Expressions.makeSymbol(largeRational).toString()); largeRational = new Rational(3).pow(100000).divide(new Rational(7).pow(100)); Assert.assertEquals("4.13E47627", Expressions.makeSymbol(largeRational).toString()); } @Test public void testPrecisionOutput() { Assert.assertEquals("12345.68", Expressions.makeSymbol(12345.6789).toString()); // // Positive Assert.assertEquals("100000", Expressions.makeSymbol(100000).toString()); Assert.assertEquals("1E6", Expressions.makeSymbol(1000000).toString()); Assert.assertEquals("1E7", Expressions.makeSymbol(10000000).toString()); Assert.assertEquals("0.1", Expressions.makeSymbol(new Rational(1,10)).toString()); Assert.assertEquals("0.01", Expressions.makeSymbol(new Rational(1,100)).toString()); Assert.assertEquals("1E-3", Expressions.makeSymbol(new Rational(1,1000)).toString()); Assert.assertEquals("1E-4", Expressions.makeSymbol(new Rational(1,10000)).toString()); Assert.assertEquals("1E-5", Expressions.makeSymbol(0.00001).toString()); Assert.assertEquals("1E-6", Expressions.makeSymbol(0.000001).toString()); Assert.assertEquals("0.39", Expressions.makeSymbol(0.3928208).toString()); Assert.assertEquals("0.4", Expressions.makeSymbol(0.3998208).toString()); Assert.assertEquals("0.01", Expressions.makeSymbol(new Rational(129, 10000)).toString()); // 0.0129 Assert.assertEquals("123", Expressions.makeSymbol(123).toString()); Assert.assertEquals("10.01", Expressions.makeSymbol(new Rational(100143, 10000)).toString()); // 10.0143 Assert.assertEquals("10.93", Expressions.makeSymbol(new Rational(10926, 1000)).toString()); // 10.926 Assert.assertEquals("0.5", Expressions.makeSymbol(0.5).toString()); Assert.assertEquals("0.99", Expressions.makeSymbol(0.99).toString()); Assert.assertEquals("1", Expressions.makeSymbol(0.999).toString()); Assert.assertEquals("11", Expressions.makeSymbol(new Rational(10999, 1000)).toString()); // 10.999 Assert.assertEquals("20", Expressions.makeSymbol(new Rational(19999, 1000)).toString()); // 19.999 Assert.assertEquals("19", Expressions.makeSymbol(new Rational(1900000926, 100000000)).toString()); // 19.00000926 Assert.assertEquals("1", Expressions.makeSymbol(0.999973).toString()); Assert.assertEquals("100000.1", Expressions.makeSymbol(new Rational(1000001, 10)).toString()); // 100000.1 Assert.assertEquals("100000.9", Expressions.makeSymbol(new Rational(1000009, 10)).toString()); // 100000.9 Assert.assertEquals("123456.1", Expressions.makeSymbol(new Rational(1234561, 10)).toString()); // 123456.1 Assert.assertEquals("123456.9", Expressions.makeSymbol(new Rational(1234569, 10)).toString()); // 123456.9 Assert.assertEquals("1.23E6", Expressions.makeSymbol(new Rational(12345679, 10)).toString()); // 123456.9 Assert.assertEquals("1.23E9", Expressions.makeSymbol(1234567890).toString()); Assert.assertEquals("1E11", Expressions.makeSymbol(100234567890L).toString()); Assert.assertEquals("0.01", Expressions.makeSymbol(new Rational(1,100)).toString()); Assert.assertEquals("1E-3", Expressions.makeSymbol(new Rational(1,1000)).toString()); Assert.assertEquals("1E-4", Expressions.makeSymbol(new Rational(1,10000)).toString()); Assert.assertEquals("1E-5", Expressions.makeSymbol(new Rational(1,100000)).toString()); // // Negative Assert.assertEquals("-0.39", Expressions.makeSymbol(-0.3928208).toString()); Assert.assertEquals("-0.4", Expressions.makeSymbol(-0.3998208).toString()); Assert.assertEquals("-0.01", Expressions.makeSymbol(new Rational(-129, 10000)).toString()); // 0.0129 Assert.assertEquals("-123", Expressions.makeSymbol(-123).toString()); Assert.assertEquals("-10.01", Expressions.makeSymbol(new Rational(-100143, 10000)).toString()); // 10.143 Assert.assertEquals("-10.93", Expressions.makeSymbol(new Rational(-10926, 1000)).toString()); // 10.926 Assert.assertEquals("-0.5", Expressions.makeSymbol(-0.5).toString()); Assert.assertEquals("-0.99", Expressions.makeSymbol(-0.99).toString()); Assert.assertEquals("-1", Expressions.makeSymbol(-0.999).toString()); Assert.assertEquals("-11", Expressions.makeSymbol(new Rational(-10999, 1000)).toString()); // 10.999 Assert.assertEquals("-20", Expressions.makeSymbol(new Rational(-19999, 1000)).toString()); // 19.999 Assert.assertEquals("-19", Expressions.makeSymbol(new Rational(-1900000926, 100000000)).toString()); // 19.00000926 Assert.assertEquals("-1", Expressions.makeSymbol(-0.999973).toString()); Assert.assertEquals("-100000.1", Expressions.makeSymbol(new Rational(-1000001, 10)).toString()); // 100000.1 Assert.assertEquals("-100000.9", Expressions.makeSymbol(new Rational(-1000009, 10)).toString()); // 100000.9 Assert.assertEquals("-123456.1", Expressions.makeSymbol(new Rational(-1234561, 10)).toString()); // 123456.1 Assert.assertEquals("-123456.9", Expressions.makeSymbol(new Rational(-1234569, 10)).toString()); // 123456.9 Assert.assertEquals("-1.23E6", Expressions.makeSymbol(new Rational(-12345679, 10)).toString()); // 123456.9 Assert.assertEquals("-1.23E9", Expressions.makeSymbol(-1234567890).toString()); } @Test public void testScientificNotationTriggeredByNumberOfDecimalPlaces() { ExpressoConfiguration.setDisplayNumericsMostDecimalPlacesInApproximateRepresentationOfNumericalSymbols(10); ExpressoConfiguration.setDisplayNumericsGreatestInitialNonZeroDecimalPlacePositionBeforeSwitchingToScientificNotation(4); Assert.assertEquals("0.001", Expressions.makeSymbol(new Rational(1,1000)).toString()); Assert.assertEquals("0.0001", Expressions.makeSymbol(new Rational(1,10000)).toString()); Assert.assertEquals("1E-5", Expressions.makeSymbol(new Rational(1,100000)).toString()); Assert.assertEquals("1E-6", Expressions.makeSymbol(new Rational(1,1000000)).toString()); ExpressoConfiguration.setDisplayNumericsMostDecimalPlacesInApproximateRepresentationOfNumericalSymbols(3); ExpressoConfiguration.setDisplayNumericsGreatestInitialNonZeroDecimalPlacePositionBeforeSwitchingToScientificNotation(12); Assert.assertEquals("0.001", Expressions.makeSymbol(new Rational(1,1000)).toString()); Assert.assertEquals("1E-4", Expressions.makeSymbol(new Rational(1,10000)).toString()); Assert.assertEquals("1E-5", Expressions.makeSymbol(new Rational(1,100000)).toString()); Assert.assertEquals("1E-6", Expressions.makeSymbol(new Rational(1,1000000)).toString()); } }
bsd-3-clause
Uncodin/Android-Common
UncodinCommon-standalone/src/in/uncod/android/media/widget/AbstractMediaPickerFragment.java
2019
package in.uncod.android.media.widget; import java.io.File; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.support.v4.app.Fragment; /** * Created by IntelliJ IDEA. User: ddrboxman Date: 4/4/12 Time: 12:26 PM */ public abstract class AbstractMediaPickerFragment extends Fragment { protected abstract File mediaChanged(Uri mediaUri); protected abstract String getProgressTitle(); public abstract void updateMediaPreview(File mediaFile); protected void runOnUiThread(Runnable runnable) { getActivity().runOnUiThread(runnable); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { Uri mediaLocation = null; if (data != null) { mediaLocation = data.getData(); new UpdateMedia().execute(mediaLocation); } } } public class UpdateMedia extends AsyncTask<Uri, Object, File> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(getActivity()); dialog.setTitle(getProgressTitle()); dialog.show(); } @Override protected File doInBackground(Uri... uris) { if (uris.length > 0) { Uri mediaUri = uris[0]; return mediaChanged(mediaUri); } return null; } @Override protected void onPostExecute(File mediaFile) { if (mediaFile != null) { updateMediaPreview(mediaFile); } if (dialog.isShowing()) { try { dialog.dismiss(); } catch (Exception e) { } } } } }
bsd-3-clause
petablox-project/petablox
src/petablox/analyses/syntax/RelGotoInst.java
630
package petablox.analyses.syntax; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.jimple.internal.JGotoStmt; import petablox.program.visitors.IGotoInstVisitor; import petablox.project.Petablox; import petablox.project.analyses.ProgramRel; @Petablox(name = "GotoInst", sign = "P0,P1:P0_P1") public class RelGotoInst extends ProgramRel implements IGotoInstVisitor { @Override public void visit(SootClass m) { } @Override public void visit(SootMethod m) { } @Override public void visit(Unit u) { } public void visit(JGotoStmt s) { add(s, s.getTarget()); } }
bsd-3-clause
8kdata/javapostgres
java/helloJDBC/src/main/java/com/eightkdata/training/javapostgres/hellojdbc/main/_10/CountriesLanguageDAO.java
2190
/* * Copyright (c) 2014, 8Kdata Technology */ package com.eightkdata.training.javapostgres.hellojdbc.main._10; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * @author Alvaro Hernandez <aht@8kdata.com> */ public class CountriesLanguageDAO { public enum Columns { COUNTRIES("countries"), LANGUAGE("language"), AVG_PERCENTAGE("avg_percentage"); private final String columnName; private Columns(String columnName) { this.columnName = columnName; } public String getColumnName() { return columnName; } } private static final String QUERY = "SELECT array_agg(countrycode) AS " + Columns.COUNTRIES.columnName + ", " + Columns.LANGUAGE.columnName + ", to_char(avg(percentage), '999.00') AS " + Columns.AVG_PERCENTAGE.columnName + " FROM countrylanguage WHERE isofficial GROUP BY language HAVING avg(percentage) > ?" + " ORDER BY avg(percentage) DESC"; private final Connection connection; public CountriesLanguageDAO(Connection connection) { this.connection = connection; } private CountriesLanguage getInstanceFromResultSet(ResultSet rs) throws SQLException { return new CountriesLanguage( (String[]) rs.getArray(1).getArray(), rs.getString(2), rs.getDouble(3) ); } public List<CountriesLanguage> getCountriesLanguages(int percentage) throws SQLException { try( // Perform a query and extract some data. Statement is freed (closed) automagically too PreparedStatement statement = connection.prepareStatement(QUERY) ) { // Set the parameters and execute the query statement.setInt(1, percentage); List<CountriesLanguage> countriesLanguages = new ArrayList<>(); QueryExecutor.executeQuery(statement, (rs) -> { countriesLanguages.add(getInstanceFromResultSet(rs)); }); return countriesLanguages; } } }
bsd-3-clause
KingBowser/hatter-source-code
tools/btracescripts/main/src/ClassLoaderDefine.java
490
import com.sun.btrace.annotations.*; import static com.sun.btrace.BTraceUtils.*; @BTrace public class ClassLoaderDefine { @SuppressWarnings("rawtypes") @OnMethod(clazz = "+java.lang.ClassLoader", method = "defineClass", location = @Location(Kind.RETURN)) public static void onClassLoaderDefine(@Return Class cl) { println("=== java.lang.ClassLoader#defineClass ==="); println(Strings.strcat("Loaded class: ", Reflective.name(cl))); jstack(10); } }
bsd-3-clause
orc-lang/orc
OrcSites/src/orc/lib/net/Ping.java
1988
// // Ping.java -- Java class Ping // Project OrcSites // // Copyright (c) 2016 The University of Texas at Austin. All rights reserved. // // Use and redistribution of this file is governed by the license terms in // the LICENSE file found in the project's top-level directory and also found at // URL: http://orc.csres.utexas.edu/license.shtml . // package orc.lib.net; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import orc.error.runtime.JavaException; import orc.error.runtime.TokenException; import orc.values.sites.compatibility.Args; import orc.values.sites.compatibility.PartialSite; /** * Implement ping using {@link InetAddress#isReachable(int)}. Accepts the host * as a string and an optional timeout (defaulting to 10 seconds), and returns * the approximate time in milliseconds required to receive a response. If no * response is received within the timeout, does not publish. * <p> * WARNING: if ICMP cannot be used for some reason (e.g. you are running the * program as a non-root user on a Linux system), this will fall back to a * regular TCP/IP request to port 7 (echo), which often fails due to firewalls * and the like. * * @author quark */ public class Ping extends PartialSite { @Override public Object evaluate(final Args args) throws TokenException { try { final InetAddress host = InetAddress.getByName(args.stringArg(0)); final long start = System.currentTimeMillis(); final boolean reachable = host.isReachable(args.size() > 1 ? args.intArg(1) : 10000); if (!reachable) { System.err.println("Could not reach " + host.toString()); return null; } return System.currentTimeMillis() - start; } catch (final UnknownHostException e) { throw new JavaException(e); } catch (final IOException e) { throw new JavaException(e); } } }
bsd-3-clause
diLLec/Asterisk-ClickDial
javaSource/de/neue_phase/asterisk/ClickDial/controller/exception/QueryAlreadyRunningException.java
169
package de.neue_phase.asterisk.ClickDial.controller.exception; /** * Created by mky on 26.01.2015. */ public class QueryAlreadyRunningException extends Exception { }
bsd-3-clause
endlessm/chromium-browser
chrome/android/java/src/org/chromium/chrome/browser/NavigationPopup.java
13623
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnLayoutChangeListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; import androidx.annotation.IntDef; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.appcompat.content.res.AppCompatResources; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.ThreadUtils; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; import org.chromium.chrome.browser.history.HistoryManagerUtils; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.ui.favicon.FaviconHelper; import org.chromium.chrome.browser.ui.favicon.FaviconHelper.DefaultFaviconHelper; import org.chromium.chrome.browser.ui.favicon.FaviconHelper.FaviconImageCallback; import org.chromium.components.embedder_support.util.UrlConstants; import org.chromium.content_public.browser.NavigationController; import org.chromium.content_public.browser.NavigationEntry; import org.chromium.content_public.browser.NavigationHistory; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.HashSet; import java.util.Set; /** * A popup that handles displaying the navigation history for a given tab. */ public class NavigationPopup implements AdapterView.OnItemClickListener { private static final int MAXIMUM_HISTORY_ITEMS = 8; private static final int FULL_HISTORY_ENTRY_INDEX = -1; /** Specifies the type of navigation popup being shown */ @IntDef({Type.ANDROID_SYSTEM_BACK, Type.TABLET_BACK, Type.TABLET_FORWARD}) @Retention(RetentionPolicy.SOURCE) public @interface Type { int ANDROID_SYSTEM_BACK = 0; int TABLET_BACK = 1; int TABLET_FORWARD = 2; } private final Profile mProfile; private final Context mContext; private final ListPopupWindow mPopup; private final NavigationController mNavigationController; private NavigationHistory mHistory; private final NavigationAdapter mAdapter; private final @Type int mType; private final int mFaviconSize; @Nullable private final OnLayoutChangeListener mAnchorViewLayoutChangeListener; private DefaultFaviconHelper mDefaultFaviconHelper; /** * Loads the favicons asynchronously. */ private FaviconHelper mFaviconHelper; private Runnable mOnDismissCallback; private boolean mInitialized; /** * Constructs a new popup with the given history information. * * @param profile The profile used for fetching favicons. * @param context The context used for building the popup. * @param navigationController The controller which takes care of page navigations. * @param type The type of navigation popup being triggered. */ public NavigationPopup(Profile profile, Context context, NavigationController navigationController, @Type int type) { mProfile = profile; mContext = context; Resources resources = mContext.getResources(); mNavigationController = navigationController; mType = type; boolean isForward = type == Type.TABLET_FORWARD; boolean anchorToBottom = type == Type.ANDROID_SYSTEM_BACK; mHistory = mNavigationController.getDirectedNavigationHistory( isForward, MAXIMUM_HISTORY_ITEMS); mHistory.addEntry(new NavigationEntry(FULL_HISTORY_ENTRY_INDEX, UrlConstants.HISTORY_URL, null, null, null, resources.getString(R.string.show_full_history), null, 0, 0)); mAdapter = new NavigationAdapter(); mPopup = new ListPopupWindow(context, null, 0, R.style.NavigationPopupDialog); mPopup.setOnDismissListener(this::onDismiss); mPopup.setBackgroundDrawable(ApiCompatibilityUtils.getDrawable(resources, anchorToBottom ? R.drawable.popup_bg_bottom_tinted : R.drawable.popup_bg_tinted)); mPopup.setModal(true); mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); mPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); mPopup.setOnItemClickListener(this); mPopup.setAdapter(mAdapter); mPopup.setWidth(resources.getDimensionPixelSize( anchorToBottom ? R.dimen.navigation_popup_width : R.dimen.menu_width)); if (anchorToBottom) { // By default ListPopupWindow uses the top & bottom padding of the background to // determine the vertical offset applied to the window. This causes the popup to be // shifted up by the top padding, and thus we forcibly need to specify a vertical offset // of 0 to prevent that. mPopup.setVerticalOffset(0); mAnchorViewLayoutChangeListener = new OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { centerPopupOverAnchorViewAndShow(); } }; } else { mAnchorViewLayoutChangeListener = null; } mFaviconSize = resources.getDimensionPixelSize(R.dimen.default_favicon_size); } @VisibleForTesting ListPopupWindow getPopupForTesting() { return mPopup; } private String buildComputedAction(String action) { return (mType == Type.TABLET_FORWARD ? "ForwardMenu_" : "BackMenu_") + action; } /** * Shows the popup attached to the specified anchor view. */ public void show(View anchorView) { if (!mInitialized) initialize(); if (!mPopup.isShowing()) RecordUserAction.record(buildComputedAction("Popup")); if (mPopup.getAnchorView() != null && mAnchorViewLayoutChangeListener != null) { mPopup.getAnchorView().removeOnLayoutChangeListener(mAnchorViewLayoutChangeListener); } mPopup.setAnchorView(anchorView); if (mType == Type.ANDROID_SYSTEM_BACK) { anchorView.addOnLayoutChangeListener(mAnchorViewLayoutChangeListener); centerPopupOverAnchorViewAndShow(); } else { mPopup.show(); } } /** * Dismisses the popup. */ public void dismiss() { mPopup.dismiss(); } /** * Sets the callback to be notified when the popup has been dismissed. * @param onDismiss The callback to be notified. */ public void setOnDismissCallback(Runnable onDismiss) { mOnDismissCallback = onDismiss; } private void centerPopupOverAnchorViewAndShow() { assert mInitialized; int horizontalOffset = (mPopup.getAnchorView().getWidth() - mPopup.getWidth()) / 2; if (horizontalOffset > 0) mPopup.setHorizontalOffset(horizontalOffset); mPopup.show(); } private void onDismiss() { if (mInitialized) mFaviconHelper.destroy(); mInitialized = false; if (mDefaultFaviconHelper != null) mDefaultFaviconHelper.clearCache(); if (mAnchorViewLayoutChangeListener != null) { mPopup.getAnchorView().removeOnLayoutChangeListener(mAnchorViewLayoutChangeListener); } if (mOnDismissCallback != null) mOnDismissCallback.run(); } private void initialize() { ThreadUtils.assertOnUiThread(); mInitialized = true; mFaviconHelper = new FaviconHelper(); Set<String> requestedUrls = new HashSet<String>(); for (int i = 0; i < mHistory.getEntryCount(); i++) { NavigationEntry entry = mHistory.getEntryAtIndex(i); if (entry.getFavicon() != null) continue; final String pageUrl = entry.getUrl(); if (!requestedUrls.contains(pageUrl)) { FaviconImageCallback imageCallback = (bitmap, iconUrl) -> NavigationPopup.this.onFaviconAvailable(pageUrl, bitmap); mFaviconHelper.getLocalFaviconImageForURL( mProfile, pageUrl, mFaviconSize, imageCallback); requestedUrls.add(pageUrl); } } } /** * Called when favicon data requested by {@link #initialize()} is retrieved. * @param pageUrl the page for which the favicon was retrieved. * @param favicon the favicon data. */ private void onFaviconAvailable(String pageUrl, Bitmap favicon) { if (favicon == null) { if (mDefaultFaviconHelper == null) mDefaultFaviconHelper = new DefaultFaviconHelper(); favicon = mDefaultFaviconHelper.getDefaultFaviconBitmap( mContext.getResources(), pageUrl, true); } for (int i = 0; i < mHistory.getEntryCount(); i++) { NavigationEntry entry = mHistory.getEntryAtIndex(i); if (TextUtils.equals(pageUrl, entry.getUrl())) entry.updateFavicon(favicon); } mAdapter.notifyDataSetChanged(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { NavigationEntry entry = (NavigationEntry) parent.getItemAtPosition(position); if (entry.getIndex() == FULL_HISTORY_ENTRY_INDEX) { RecordUserAction.record(buildComputedAction("ShowFullHistory")); assert mContext instanceof ChromeActivity; ChromeActivity activity = (ChromeActivity) mContext; HistoryManagerUtils.showHistoryManager(activity, activity.getActivityTab()); } else { // 1-based index to keep in line with Desktop implementation. RecordUserAction.record(buildComputedAction("HistoryClick" + (position + 1))); int index = entry.getIndex(); RecordHistogram.recordBooleanHistogram( "Navigation.BackForward.NavigatingToEntryMarkedToBeSkipped", mNavigationController.isEntryMarkedToBeSkipped(index)); mNavigationController.goToNavigationIndex(index); } mPopup.dismiss(); } private class NavigationAdapter extends BaseAdapter { private Integer mTopPadding; @Override public int getCount() { return mHistory.getEntryCount(); } @Override public Object getItem(int position) { return mHistory.getEntryAtIndex(position); } @Override public long getItemId(int position) { return ((NavigationEntry) getItem(position)).getIndex(); } @Override public View getView(int position, View convertView, ViewGroup parent) { EntryViewHolder viewHolder; if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); convertView = inflater.inflate(R.layout.navigation_popup_item, parent, false); viewHolder = new EntryViewHolder(); viewHolder.mContainer = convertView; viewHolder.mImageView = convertView.findViewById(R.id.favicon_img); viewHolder.mTextView = convertView.findViewById(R.id.entry_title); convertView.setTag(viewHolder); } else { viewHolder = (EntryViewHolder) convertView.getTag(); } NavigationEntry entry = (NavigationEntry) getItem(position); setViewText(entry, viewHolder.mTextView); viewHolder.mImageView.setImageBitmap(entry.getFavicon()); if (entry.getIndex() == FULL_HISTORY_ENTRY_INDEX) { ApiCompatibilityUtils.setImageTintList(viewHolder.mImageView, AppCompatResources.getColorStateList( mContext, R.color.default_icon_color_blue)); } else { ApiCompatibilityUtils.setImageTintList(viewHolder.mImageView, null); } if (mType == Type.ANDROID_SYSTEM_BACK) { View container = viewHolder.mContainer; if (mTopPadding == null) { mTopPadding = container.getResources().getDimensionPixelSize( R.dimen.navigation_popup_top_padding); } viewHolder.mContainer.setPadding(container.getPaddingLeft(), position == 0 ? mTopPadding : 0, container.getPaddingRight(), container.getPaddingBottom()); } return convertView; } private void setViewText(NavigationEntry entry, TextView view) { String entryText = entry.getTitle(); if (TextUtils.isEmpty(entryText)) entryText = entry.getVirtualUrl(); if (TextUtils.isEmpty(entryText)) entryText = entry.getUrl(); view.setText(entryText); } } private static class EntryViewHolder { View mContainer; ImageView mImageView; TextView mTextView; } }
bsd-3-clause
winktoolkit/wink
utils/build/src/org/mozilla/intl/chardet/nsISO2022JPVerifier.java
8538
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * DO NOT EDIT THIS DOCUMENT MANUALLY !!! * THIS FILE IS AUTOMATICALLY GENERATED BY THE TOOLS UNDER * AutoDetect/tools/ */ package org.mozilla.intl.chardet; public class nsISO2022JPVerifier extends nsVerifier { static int[] cclass; static int[] states; static int stFactor; static String charset; @Override public int[] cclass() { return cclass; } @Override public int[] states() { return states; } @Override public int stFactor() { return stFactor; } @Override public String charset() { return charset; } public nsISO2022JPVerifier() { cclass = new int[256 / 8]; cclass[0] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (2))))))))); cclass[1] = ((((((((((((2) << 4) | (2)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[2] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[3] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((1) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[4] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (7))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[5] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (3))))))))); cclass[6] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[7] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[8] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (4)))) << 8) | (((((0) << 4) | (6))))))))); cclass[9] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (5)))) << 8) | (((((0) << 4) | (0))))))))); cclass[10] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[11] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[12] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[13] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[14] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[15] = ((((((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))) << 16) | (((((((((0) << 4) | (0)))) << 8) | (((((0) << 4) | (0))))))))); cclass[16] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[17] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[18] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[19] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[20] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[21] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[22] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[23] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[24] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[25] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[26] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[27] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[28] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[29] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[30] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); cclass[31] = ((((((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))) << 16) | (((((((((2) << 4) | (2)))) << 8) | (((((2) << 4) | (2))))))))); states = new int[6]; states[0] = ((((((((((((eStart) << 4) | (eStart)))) << 8) | (((((eStart) << 4) | (eStart))))))) << 16) | (((((((((eStart) << 4) | (eError)))) << 8) | (((((3) << 4) | (eStart))))))))); states[1] = ((((((((((((eError) << 4) | (eError)))) << 8) | (((((eError) << 4) | (eError))))))) << 16) | (((((((((eError) << 4) | (eError)))) << 8) | (((((eError) << 4) | (eError))))))))); states[2] = ((((((((((((eItsMe) << 4) | (eItsMe)))) << 8) | (((((eItsMe) << 4) | (eItsMe))))))) << 16) | (((((((((eItsMe) << 4) | (eItsMe)))) << 8) | (((((eItsMe) << 4) | (eItsMe))))))))); states[3] = ((((((((((((4) << 4) | (eError)))) << 8) | (((((eError) << 4) | (eError))))))) << 16) | (((((((((5) << 4) | (eError)))) << 8) | (((((eError) << 4) | (eError))))))))); states[4] = ((((((((((((eError) << 4) | (eItsMe)))) << 8) | (((((eError) << 4) | (eItsMe))))))) << 16) | (((((((((eError) << 4) | (eError)))) << 8) | (((((eError) << 4) | (eError))))))))); states[5] = ((((((((((((eError) << 4) | (eError)))) << 8) | (((((eItsMe) << 4) | (eItsMe))))))) << 16) | (((((((((eError) << 4) | (eError)))) << 8) | (((((eError) << 4) | (eError))))))))); charset = "ISO-2022-JP"; stFactor = 8; } @Override public boolean isUCS2() { return false; }; }
bsd-3-clause
ariordan/ical4j
src/main/java/net/fortuna/ical4j/model/property/Contact.java
4052
/** * Copyright (c) 2012, Ben Fortuna * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * o Neither the name of Ben Fortuna nor the names of any other contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.fortuna.ical4j.model.property; import net.fortuna.ical4j.model.*; import net.fortuna.ical4j.validate.PropertyValidator; import net.fortuna.ical4j.validate.ValidationException; import net.fortuna.ical4j.validate.ValidationRule; import net.fortuna.ical4j.validate.Validator; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import java.util.Arrays; import static net.fortuna.ical4j.model.Parameter.ALTREP; import static net.fortuna.ical4j.model.Parameter.LANGUAGE; /** * $Id$ * <p/> * Created: [Apr 6, 2004] * <p/> * Defines a CONTACT iCalendar component property. * * @author benf */ public class Contact extends Property implements Escapable { private static final long serialVersionUID = -4776654229643771385L; private String value; private Validator<Property> validator = new PropertyValidator(Arrays.asList( new ValidationRule(ValidationRule.ValidationType.OneOrLess, ALTREP, LANGUAGE))); /** * Default constructor. */ public Contact() { super(CONTACT, new ParameterList(), new Factory()); } /** * @param aValue a value string for this component */ public Contact(final String aValue) { super(CONTACT, new ParameterList(), new Factory()); setValue(aValue); } /** * @param aList a list of parameters for this component * @param aValue a value string for this component */ public Contact(final ParameterList aList, final String aValue) { super(CONTACT, aList, new Factory()); setValue(aValue); } /** * {@inheritDoc} */ public final void setValue(final String aValue) { this.value = aValue; } /** * {@inheritDoc} */ public final String getValue() { return value; } @Override public void validate() throws ValidationException { validator.validate(this); } public static class Factory extends Content.Factory implements PropertyFactory { private static final long serialVersionUID = 1L; public Factory() { super(CONTACT); } public Property createProperty(final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Contact(parameters, value); } public Property createProperty() { return new Contact(); } } }
bsd-3-clause
fresskarma/tinyos-1.x
tools/java/net/tinyos/sim/script/reflect/Mote.java
5718
// $Id: Mote.java,v 1.7 2004/04/14 18:30:31 mikedemmer Exp $ /* * * * "Copyright (c) 2004 and The Regents of the University * of California. All rights reserved. * * Permission to use, copy, modify, and distribute this software and * its documentation for any purpose, without fee, and without written * agreement is hereby granted, provided that the above copyright * notice and the following two paragraphs appear in all copies of * this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS * DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS." * * Authors: Michael Demmer * Date: January 9, 2004 * Desc: Reflected Mote object * */ /** * @author Michael Demmer */ package net.tinyos.sim.script.reflect; import net.tinyos.sim.*; import net.tinyos.sim.event.*; import net.tinyos.sim.script.ScriptInterpreter; import java.io.*; import org.python.core.*; /** * The Mote class provides access to the simulated mote objects.<p> * * Each mote that is simulated has a corresponding simulator object. * These simulator objects are bound into the simcore module as the * <i>motes</i> list. Hence for example, <tt>motes[3].turnOn()</tt> * will turn on mote number 3. * * Generic methods that are available on all simulator objects are * described in {@link SimObject}. * */ public class Mote extends net.tinyos.sim.script.reflect.SimObject { private MoteVariables moteVars; private MoteSimObject mote; public Mote(ScriptInterpreter interp, SimDriver driver, MoteSimObject mote) { super(interp, driver, mote); moteVars = driver.getVariables(); this.mote = mote; } /** * Return the mote's ID. */ public int getID() { return mote.getID(); } /** * Return a string representing the mote's state (i.e. power, * position). */ public String toString() { String msg = "Mote " + getID() + ": "; msg += "[power=" + (isOn()? "on":"off") + "] "; msg += "[state=active] "; msg += "[pos=" + (int)getXCoord() + "," + (int)getYCoord() + "]"; return msg; } /** * Turn the mote on. */ public void turnOn() throws IOException { boolean wasOn = mote.getPower(); if (wasOn) return; mote.setPower(true); driver.getSimComm().sendCommand( new TurnOnMoteCommand((short)mote.getID(), 0L)); driver.refreshMotePanel(); } /** * Turn the mote off. */ public void turnOff() throws IOException { boolean wasOn = mote.getPower(); if (! wasOn) return; mote.setPower(false); driver.getSimComm().sendCommand( new TurnOffMoteCommand((short)mote.getID(), 0L)); driver.refreshMotePanel(); } /** * Return whether or not the mote is on. */ public boolean isOn() { return mote.getPower(); } /** * Set a label in the TinyViz GUI for the given mote at a constant * offset to the mote's position. Has no effect if the gui is not * enabled. * * @param label the string to display * @param xoff x offset of the label * @param yoff y offset of the label */ public void setLabel(String label, int xoff, int yoff) { mote.addAttribute(new MoteLabelAttribute(label, xoff, yoff)); driver.refreshMotePanel(); } /** * Resolve and return the value of a mote frame variable, specifying * the length and the offset, and return it as a byte array. * * @param var variable name to resolve and return */ public byte[] getBytes(String var, long len, long offset) throws IOException { return moteVars.getBytes((short)mote.getID(), var, len, offset); } /** * Resolve and return the value of a mote frame variable, and return * it as a byte array. * * @param var variable name to resolve and return */ public byte[] getBytes(String var) throws IOException { return moteVars.getBytes((short)mote.getID(), var); } /** * Resolve and return the value of a mote frame variable, and return * it as a long. * * @param var variable name to resolve and return */ public long getLong(String var) throws IOException { return moteVars.getLong((short)mote.getID(), var); } /** * Resolve and return the value of a mote frame variable, and return * it as an int. * * @param var variable name to resolve and return */ public int getInt(String var) throws IOException { return (int)moteVars.getLong((short)mote.getID(), var); } /** * Resolve and return the value of a mote frame variable, and return * it as a short. * * @param var variable name to resolve and return */ public short getShort(String var) throws IOException { return (short)moteVars.getShort((short)mote.getID(), var); } /** * Resolve and return the value of a mote frame variable, and return * it as a byte. * * @param var variable name to resolve and return */ public byte getByte(String var) throws IOException { byte b[] = getBytes(var); if (b.length > 0) { return b[0]; } else { throw Py.IndexError(var + " is not a valid variable (it has length 0)"); } } }
bsd-3-clause
uwplse/Casper
bin/benchmarks/manual/bigλ/CyclingSpeed.java
433
package manual.bigλ; import org.apache.spark.api.java.JavaRDD; import scala.Tuple2; import java.util.Map; public class CyclingSpeed { class Record { public int fst; public int snd; public int emit; public double speed; } public Map<Integer,Integer> cyclingSpeed(JavaRDD<Record> data){ return data.mapToPair(r -> new Tuple2<Integer,Integer>((int)Math.ceil(r.speed),1)).reduceByKey((a, b) -> a+b).collectAsMap(); } }
bsd-3-clause
dvbu-test/PDTool
PDToolModules/src/com/cisco/dvbu/ps/deploytool/modules/ResourceCacheType.java
4081
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-257 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.04.07 at 07:27:56 AM EDT // package com.cisco.dvbu.ps.deploytool.modules; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * * Resource Cache Type: Provides the ability to configure cache on procedures and views. * * * <p>Java class for ResourceCacheType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ResourceCacheType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="resourcePath" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="resourceType" type="{http://www.dvbu.cisco.com/ps/deploytool/modules}ResourceTypeSimpleType"/> * &lt;element name="cacheConfig" type="{http://www.dvbu.cisco.com/ps/deploytool/modules}ResourceCacheConfigType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ResourceCacheType", propOrder = { "id", "resourcePath", "resourceType", "cacheConfig" }) public class ResourceCacheType { @XmlElement(required = true) protected String id; @XmlElement(required = true) protected String resourcePath; @XmlElement(required = true) protected ResourceTypeSimpleType resourceType; @XmlElement(required = true) protected ResourceCacheConfigType cacheConfig; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the resourcePath property. * * @return * possible object is * {@link String } * */ public String getResourcePath() { return resourcePath; } /** * Sets the value of the resourcePath property. * * @param value * allowed object is * {@link String } * */ public void setResourcePath(String value) { this.resourcePath = value; } /** * Gets the value of the resourceType property. * * @return * possible object is * {@link ResourceTypeSimpleType } * */ public ResourceTypeSimpleType getResourceType() { return resourceType; } /** * Sets the value of the resourceType property. * * @param value * allowed object is * {@link ResourceTypeSimpleType } * */ public void setResourceType(ResourceTypeSimpleType value) { this.resourceType = value; } /** * Gets the value of the cacheConfig property. * * @return * possible object is * {@link ResourceCacheConfigType } * */ public ResourceCacheConfigType getCacheConfig() { return cacheConfig; } /** * Sets the value of the cacheConfig property. * * @param value * allowed object is * {@link ResourceCacheConfigType } * */ public void setCacheConfig(ResourceCacheConfigType value) { this.cacheConfig = value; } }
bsd-3-clause
mkausas/SwervePOC
src/swerve/SwerveBase.java
1875
package swerve; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; /** * Proof of concept for Swerve drive for FIRST ROBOTICS Competition * Modified for use in FRC. Code adapted from Ether. * @author Marty */ public class SwerveBase extends IterativeRobot { private Joystick left, right; public void robotInit() { left = new Joystick(1); left = new Joystick(2); } public void autonomousPeriodic() { } public void teleopPeriodic() { calc(); try { Thread.sleep(20); } catch (Exception ex) { ex.printStackTrace(); } } public void testPeriodic() { } //calculation doubles used public double m1, m2, m3, m4, a1, a2, a3, a4, x, y, z; public void calc() { //creates g1, g2, g3, g4 (group[i]) new MtrTester class object giving each one the wheel id MtrTester g1 = new MtrTester(1), g2 = new MtrTester(2), g3 = new MtrTester(3), g4 = new MtrTester(4); x = left.getX(); y = left.getY(); z = right.getTwist(); //run genCalc method for each group[i] g1.genCalc(x, y, z); g2.genCalc(x, y, z); g3.genCalc(x, y, z); g4.genCalc(x, y, z); //run get calcspeed and calc angle mathods to get angle and speed (motor value) // for debugging // m1 = (Math.round(g1.calcSpeed()*1000))/10; // a1 = (Math.round(g1.calcAngl()*1000))/1000; // m2 = (Math.round(g2.calcSpeed()*1000))/10; // a2 = (Math.round(g2.calcAngl()*1000))/1000; // m3 = (Math.round(g3.calcSpeed()*1000))/10; // a3 = (Math.round(g3.calcAngl()*1000))/1000; // m4 = (Math.round(g4.calcSpeed()*1000))/10; // a4 = (Math.round(g4.calcAngl()*1000))/1000; } }
bsd-3-clause
connoc1/CMonster2017
src/org/usfirst/frc2084/CMonster2017/subsystems/DriveBase.java
7925
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc2084.CMonster2017.subsystems; import org.usfirst.frc2084.CMonster2017.Robot; import org.usfirst.frc2084.CMonster2017.RobotMap; import org.usfirst.frc2084.CMonster2017.Drive.ArcadeDrive; import org.usfirst.frc2084.CMonster2017.Drive.JoystickSensitivity; import org.usfirst.frc2084.CMonster2017.PID.DistancePID; import org.usfirst.frc2084.CMonster2017.PID.HeadingPID; import org.usfirst.frc2084.CMonster2017.commands.*; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.CounterBase.EncodingType; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.PIDSourceType; import edu.wpi.first.wpilibj.SpeedController; import com.ctre.*; import com.ctre.CANTalon.FeedbackDevice; import com.ctre.CANTalon.TalonControlMode; import edu.wpi.first.wpilibj.smartdashboard.*; import edu.wpi.first.wpilibj.command.Subsystem; /** * */ public class DriveBase extends Subsystem { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS private final AHRS ahrs = RobotMap.ahrs; // There are 2 driver motors on each side of the robot. // Here are the declarations. private final CANTalon leftTalon1 = RobotMap.driveBaseLeftTalon1; // private final PIDController leftPIDController2 = // RobotMap.driveBasePIDLeftPIDController2; private final CANTalon rightTalon1 = RobotMap.driveBaseRightTalon1; // private final PIDController rightPIDController2 = // RobotMap.driveBasePIDRightPIDController2; // Put methods for controlling this subsystem // here. Call these from Commands. double leftMotorSpeed; // variables used to calculate motor speed double rightMotorSpeed; double moveSpeed; double rotateSpeed; boolean InPosition; // variables for autonomous public static double LeftDistance; //left and right distance are averaged for the average distance public static double RightDistance; int Waypoint = 1; // the number of way points stating at 1. double[] WayPoints = new double[3]; // array with 3 elements holding the // distance to each way point; ArcadeDrive arcadeDrive = new ArcadeDrive(); JoystickSensitivity joystickSensitivity = new JoystickSensitivity(); private final double WheelDiameter = RobotMap.DRIVE_SUBSYSTEM_WHEEL_DIAMETER; double[] returnData = new double[2]; Joystick RightJoystick; Joystick LeftJoystick; public boolean isInverted = false; HeadingPID headingPID = RobotMap.headingPID; // instance variables DistancePID distancePID = RobotMap.distancePID; public void EnableDriveBase() { leftTalon1.reset(); // reset PID controllers before enable to prevent // "wind up" rightTalon1.reset(); leftTalon1.enable(); rightTalon1.enable(); distancePID.enable(); headingPID.enable(); Robot.gearBase.CompressorOn(); //turn on the compressor when the robot is enabled leftTalon1.setPosition(0); rightTalon1.setPosition(0); } public void DisableDriveBase() { leftTalon1.disable(); rightTalon1.disable(); distancePID.disable(); headingPID.disable(); } public void DriveAutonomous() { moveSpeed = distancePID.getOutput(); rotateSpeed = headingPID.getOutput(); // Get and store the output from // the heading PID controller. SmartDashboard.putNumber("HeadingPID", rotateSpeed);// rotateSpeed is // the value of // HeadingPID SmartDashboard.putNumber("YAW", (double) ahrs.getYaw()); SmartDashboard.putNumber("DistancePID", moveSpeed); // SmartDashboard.putNumber("pitch", (double)ahrs.getPitch()); // SmartDashboard.putNumber("roll", (double)ahrs.getRoll()); returnData = arcadeDrive.calculateSpeed(moveSpeed, rotateSpeed); leftMotorSpeed = returnData[0]; rightMotorSpeed = returnData[1]; // these 3 lines replace the arcade calculations blocks, call them from // ArchadeDrive class leftTalon1.set(leftMotorSpeed * 586); // set thing to max RPM rightTalon1.set(rightMotorSpeed * 586);// changed from * 586 // LeftDistance = leftEncoder.getDistance(); //Read encoder distance // traveled in meters. // RightDistance = rightEncoder.getDistance(); // have to invert rightDistance so the average isn't negative LeftDistance = leftTalon1.getPosition() * RobotMap.DISTANCE_PER_PULSE; RightDistance = rightTalon1.getPosition() * RobotMap.DISTANCE_PER_PULSE; //multiply the position of the talon by the distance traveled per rotation //this yields the total distance LeftDistance *= -1; //invert the leftDistance so values are positive RobotMap.AverageDistance = (LeftDistance + RightDistance) / 2; // Calculate // the // average // distance // traveled. //SmartDashboard stuff SmartDashboard.putNumber("WheelDiameter", WheelDiameter); SmartDashboard.putNumber("LeftDistance", LeftDistance); SmartDashboard.putNumber("AV Distance", RobotMap.AverageDistance); SmartDashboard.putNumber("Right Distance", RightDistance); SmartDashboard.putBoolean("Inversion", isInverted); SmartDashboard.putNumber("RightTalonPosition", rightTalon1.getPosition()); SmartDashboard.putNumber("LeftTalonPosition", leftTalon1.getPosition()); SmartDashboard.putNumber("DistancePerPulse", RobotMap.DISTANCE_PER_PULSE); // SmartDashboard.putNumber("HeadingPID", headingPID.getOutput()); } // method called during teleop from DriveWithJoystick command. executes // arcade drive algorithm using joy stick inputs. public void JoystickInputs(Joystick RightJoystick, Joystick LeftJoystick) { // teleop // method // moveSpeed = stick.getY() * -1; // set variables = Joystick inputs // invert the y value to -1 so that pushing the joystick forward gives a // positive value // rotateSpeed = stick.getX() * -1; //also invert the x value so // right/left aren't inverted // returnData = arcadeDrive.calculateSpeed(moveSpeed, rotateSpeed); //these are the commands for inverting the drive, called into the Inversion command if (isInverted == true) { rightTalon1.setInverted(true); leftTalon1.setInverted(true); leftMotorSpeed = RightJoystick.getY() * -1; rightMotorSpeed = LeftJoystick.getY(); } else { rightTalon1.setInverted(false); leftTalon1.setInverted(false); leftMotorSpeed = LeftJoystick.getY() * -1; rightMotorSpeed = RightJoystick.getY(); } //leftMotorSpeed = LeftJoystick.getY() * -1; //rightMotorSpeed = RightJoystick.getY(); leftMotorSpeed = joystickSensitivity.GetOutput(leftMotorSpeed); rightMotorSpeed = joystickSensitivity.GetOutput(rightMotorSpeed); //joystick sensitivity stuff // leftMotorSpeed *= -1; // invert motor speed command. // Drive the left and right sides of the robot at the specified speeds. rightTalon1.set(rightMotorSpeed * 586); //set to max RPM leftTalon1.set(leftMotorSpeed * 586); } public void initDefaultCommand() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND setDefaultCommand(new DriveWithJoystick()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // Set the default command for a subsystem here. // setDefaultCommand(new MySpecialCommand()); } }
bsd-3-clause
magicDGS/thaplv
src/main/java/org/magicdgs/thaplv/haplotypes/light/LightGenotype.java
9031
/* * Copyright (c) 2016, Daniel Gomez-Sanchez <daniel.gomez.sanchez@hotmail> All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.magicdgs.thaplv.haplotypes.light; import com.google.common.annotations.VisibleForTesting; import htsjdk.variant.variantcontext.Allele; import htsjdk.variant.variantcontext.Genotype; import htsjdk.variant.variantcontext.GenotypesContext; import htsjdk.variant.variantcontext.VariantContext; import java.io.Serializable; import java.util.HashSet; import java.util.List; import java.util.stream.Stream; /** * Class for a light-weight representation of genotypes (when storage in memory is needed). * * @author Daniel Gomez-Sanchez (magicDGS) * @deprecated AlleleVector is a better light representation */ @Deprecated public class LightGenotype implements Serializable { private static final long serialVersionUID = 1L; private final SNP[] orderedSNPlist; private final String contig; private final int pos; /** * Public constructor from a variant * * @param variant the variant to convert */ public LightGenotype(final VariantContext variant) { this(variant.getContig(), variant.getStart(), variant.getGenotypes(), variant.getReference(), variant.getAlternateAlleles()); } /** * Public constructor with all the parameters necessary * * @param contig the contig for the genotype * @param position the position for the genotype * @param genotypes the genotypes * @param ref the reference allele * @param alternatives the alternative alleles */ public LightGenotype(final String contig, final int position, final GenotypesContext genotypes, final Allele ref, final List<Allele> alternatives) { this.contig = contig; this.pos = position; orderedSNPlist = new SNP[genotypes.size()]; switch (alternatives.size()) { case 0: throw new IllegalArgumentException( "Trying to obtain a light genotype from a variant with only reference"); case 1: initBiallelic(genotypes); break; default: initMultiAllelic(genotypes, ref, alternatives); break; } } /** * Constructor for testing purposes. * * @param contig the contig for the genotype * @param pos the position for the genotype * @param orderedSNPlist the list of SNPs */ @VisibleForTesting public LightGenotype(final String contig, final int pos, final SNP[] orderedSNPlist) { this.contig = contig; this.pos = pos; this.orderedSNPlist = orderedSNPlist; } /** * Initialize the SNPlist from a ref/alt biallelic SNP. The reference will be considered the * SNP.A * * @param genotypes the genotypes */ private void initBiallelic(final GenotypesContext genotypes) { int i = 0; for (final Genotype geno : genotypes) { if (geno.isHomRef()) { orderedSNPlist[i++] = SNP.A; } else if (geno.isHomVar()) { orderedSNPlist[i++] = SNP.a; } else { orderedSNPlist[i++] = SNP.N; } } } /** * Initialize the SNPlist from various alternatives. The one for the first sample will be * considered the SNP.A * * @param genotypes the genotypes * @param ref the reference allele * @param alternatives the alternative alleles */ private void initMultiAllelic(final GenotypesContext genotypes, final Allele ref, final List<Allele> alternatives) { // create a set with the alleles final HashSet<Allele> alleles = new HashSet<>(); alleles.add(ref); alleles.addAll(alternatives); Allele snpA = null; Allele snpa = null; int i = 0; for (final Genotype geno : genotypes) { // if it is not homozygous, is a missing SNP if (!geno.isHom()) { orderedSNPlist[i++] = SNP.N; } else { final Allele current = geno.getAllele(0); if (snpA == null) { snpA = current; alleles.remove(snpA); } if (current.equals(snpA)) { orderedSNPlist[i++] = SNP.A; } else if (snpa != null && alleles.contains(current)) { throw new IllegalArgumentException( "Trying to construct a light genotype from a multi-allelic variant when is not. SNP_A=" + snpA + "; SNP_a=" + snpa + "; rest=" + alleles); } else if (snpa == null) { snpa = current; alleles.remove(snpa); orderedSNPlist[i++] = SNP.a; } else if (current.equals(snpa)) { orderedSNPlist[i++] = SNP.a; } else { throw new RuntimeException("Unreachable code"); } } } } /** * Get the position for the genotypes * * @return the position */ public int getPosition() { return this.pos; } /** * Get the contig reference for the genotypes * * @return the contig */ public String getContig() { return this.contig; } /** * Get the number of alleles A * * @return the count */ public int getNumberOfA() { return getNumberOf(SNP.A); } /** * Get the number of alleles a * * @return the count */ public int getNumberOfa() { return getNumberOf(SNP.a); } /** * Get the number of missing * * @return the count */ public int getNumberOfMissing() { return getNumberOf(SNP.N); } /** * Check if the counts for any of the alleles is only one. An invariant site is not singleton * * @return true if the count for one of the alleles is 1; false otherwise */ public boolean isSingleton() { return getNumberOfA() == 1 || getNumberOfa() == 1; } /** * Compute the number of SNPs of certain category * * @param snp the SNP to count * * @return the count of "snp" */ private int getNumberOf(final SNP snp) { return (int) Stream.of(orderedSNPlist).filter(x -> x == snp).count(); } /** * Get the number of genotypes * * @return the number of genotypes */ public int size() { return orderedSNPlist.length; } /** * Get the genotype at index position. The first index is 0 * * @param index the index to retrieve * * @return the genotype from the index sample */ public SNP getGenotypeAt(final int index) { return this.orderedSNPlist[index]; } /** * String representation of the LightGenotype * * @return the string representation */ public String toString() { final StringBuilder builder = new StringBuilder(); builder.append('['); for (final SNP snp : orderedSNPlist) { builder.append(snp); } builder.append(']'); return builder.toString(); } /** * Enum to light storage */ public static enum SNP { A, a, N } }
bsd-3-clause
gamma9mu/SOMa
src/cs437/som/visualization/GreyScaleHeat.java
611
package cs437.som.visualization; import java.awt.*; /** * A color progression from white (#FFFFFF) to black (#000000). */ public class GreyScaleHeat implements ColorProgression { private static final float SCALE = 100.0f; @Override public Color getColor(int intensity) { if (intensity < 0) return Color.white; else if (intensity > 100) return Color.black; else { final float brightness = (100-intensity) / SCALE; final int rgb = Color.HSBtoRGB(0.0f, 0.0f, brightness); return new Color(rgb); } } }
bsd-3-clause
jarlehansen/no5-events-publisher
no5-events-publisher-api/src/main/java/no/appspartner/events/device/DeviceService.java
632
package no.appspartner.events.device; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class DeviceService { @Autowired private DeviceRepository deviceRepository; public Device storeDevice(Device device) { device.setRegistered(System.currentTimeMillis()); deviceRepository.save(device); return device; } public List<Device> getRegisteredDevices() { return deviceRepository.findAllDevices(); } public void deleteAll() { deviceRepository.deleteAll(); } }
bsd-3-clause
JinMar/ComputerVision
src/main/java/cz/tul/bussiness/workers/EdgeDetectors.java
1582
package cz.tul.bussiness.workers; import cz.tul.bussiness.jobs.EdgeDetectors.Canny; import cz.tul.bussiness.jobs.EdgeDetectors.Laplacian; import cz.tul.bussiness.jobs.EdgeDetectors.Sobel; import cz.tul.bussiness.jobs.exceptions.MinimalArgumentsException; import cz.tul.bussiness.jobs.exceptions.NoTemplateFound; import cz.tul.bussiness.workers.enums.EdgeDetectorEnum; import cz.tul.bussiness.workers.exceptions.SelectionLayerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Bc. Marek Jindrák on 13.02.2017. */ public class EdgeDetectors extends AMethodWorker { private static final Logger logger = LoggerFactory.getLogger(EdgeDetectors.class); @Override public void work() throws SelectionLayerException, MinimalArgumentsException, NoTemplateFound { if (classifier.equals(EdgeDetectorEnum.SOBEL.getDetectorlName())) { job = new Sobel(); job.setPartAttributeValue(getAttributes()); job.setImgData(imgData); setImgData(job.start()); } if (classifier.equals(EdgeDetectorEnum.LAPLACIAN.getDetectorlName())) { job = new Laplacian(); job.setPartAttributeValue(getAttributes()); job.setImgData(imgData); setImgData(job.start()); } if (classifier.equals(EdgeDetectorEnum.CANNY.getDetectorlName())) { job = new Canny(); job.setPartAttributeValue(getAttributes()); job.setImgData(imgData); setImgData(job.start()); } saveImg(); } }
bsd-3-clause
CapCaval/ccProjects
01_src/test/test2components/numberproducer/impl/NumberProducerImpl.java
2648
/* Copyright (C) 2012 by CapCaval.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package test.test2components.numberproducer.impl; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.capcaval.c3.component.ComponentStateAdaptor; import org.capcaval.c3.component.annotation.ProducedEvent; import test.test2components.numberproducer.NumberProducer; import test.test2components.numberproducer.NumberProducerEvent; import test.test2components.numberproducer.NumberProducerService; public class NumberProducerImpl extends ComponentStateAdaptor implements NumberProducer, NumberProducerService{ @ProducedEvent protected NumberProducerEvent producerEvent; protected AtomicBoolean keepProduceNumber = new AtomicBoolean(false); protected Thread producerThread; @Override public void componentStarted() { System.out.println("NumberFeeder component Started"); this.producerThread = new Thread(new Runnable(){ AtomicInteger value = new AtomicInteger(0); @Override public void run() { while(keepProduceNumber.get() == true){ try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } int val = value.incrementAndGet(); // notify subscriber producerEvent.notifyNewValueCreated(val); System.out.println("ProduceNumber : " + val); } } }); } @Override public void start() { System.out.println("Start Produce number .. "); this.keepProduceNumber.set(true); producerThread.start(); } @Override public void stop() { keepProduceNumber.set(false); } }
mit
pietermartin/sqlg
sqlg-test/src/main/java/org/umlg/sqlg/test/edges/TestCreateEdgeBetweenVertices.java
4071
package org.umlg.sqlg.test.edges; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Assert; import org.junit.Test; import org.umlg.sqlg.test.BaseTest; import java.util.List; /** * Date: 2014/11/20 * Time: 9:31 PM */ public class TestCreateEdgeBetweenVertices extends BaseTest { @Test public void testCreateEdgeBetweenVertices() { Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person"); Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person"); this.sqlgGraph.tx().commit(); person1 = this.sqlgGraph.traversal().V(person1.id()).next(); person2 = this.sqlgGraph.traversal().V(person2.id()).next(); person1.addEdge("friend", person2); this.sqlgGraph.tx().commit(); Assert.assertEquals(1, vertexTraversal(this.sqlgGraph, person1).out("friend").count().next().intValue()); Assert.assertEquals(1, vertexTraversal(this.sqlgGraph, person2).in("friend").count().next().intValue()); } @Test public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHas() { Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john"); Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter"); this.sqlgGraph.tx().commit(); person1 = this.sqlgGraph.traversal().V(person1.id()).next(); person2 = this.sqlgGraph.traversal().V(person2.id()).next(); person1.addEdge("friend", person2); Assert.assertEquals("john", person1.value("name")); Assert.assertEquals("peter", person2.value("name")); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").toList(); Assert.assertEquals(1, vertexTraversal(this.sqlgGraph, vertices.get(0)).out("friend").count().next().intValue()); Assert.assertEquals(1, vertexTraversal(this.sqlgGraph, vertices.get(1)).in("friend").count().next().intValue()); Assert.assertEquals(2, vertices.size()); } @Test public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHasHas() { Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john"); Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter"); this.sqlgGraph.tx().commit(); person1 = this.sqlgGraph.traversal().V(person1.id()).next(); person2 = this.sqlgGraph.traversal().V(person2.id()).next(); person1.addEdge("friend", person2); Assert.assertEquals("john", person1.value("name")); Assert.assertEquals("peter", person2.value("name")); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").<Vertex>has("name", "john").toList(); Assert.assertEquals(1, vertexTraversal(this.sqlgGraph, vertices.get(0)).out("friend").count().next().intValue()); Assert.assertEquals(1, vertices.size()); vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").<Vertex>has("name", "peter").toList(); Assert.assertEquals(1, vertexTraversal(this.sqlgGraph, vertices.get(0)).in("friend").count().next().intValue()); Assert.assertEquals(1, vertices.size()); } @Test public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHasSortBy() { Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john"); for (int i = 0; i < 1000; i++) { Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter" + i); person1.addEdge("friend", person2); } this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").toList(); Assert.assertEquals("john", vertices.get(0).value("name")); Assert.assertEquals("peter0", vertices.get(1).value("name")); Assert.assertEquals("peter999", vertices.get(1000).value("name")); } }
mit
OpenModularTurretsTeam/OMLib
src/api/java/dan200/computercraft/api/lua/ILuaObject.java
2945
/* * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.lua; import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.api.peripheral.IPeripheral; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * An interface for representing custom objects returned by {@link IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])} * calls. * <p> * Return objects implementing this interface to expose objects with methods to lua. */ public interface ILuaObject { /** * Get the names of the methods that this object implements. This works the same as {@link IPeripheral#getMethodNames()}. * See that method for detailed documentation. * * @return The method names this object provides. * @see IPeripheral#getMethodNames() */ @Nonnull String[] getMethodNames(); /** * Called when a user calls one of the methods that this object implements. This works the same as * {@link IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])}}. See that method for detailed * documentation. * * @param context The context of the currently running lua thread. This can be used to wait for events * or otherwise yield. * @param method An integer identifying which of the methods from getMethodNames() the computercraft * wishes to call. The integer indicates the index into the getMethodNames() table * that corresponds to the string passed into peripheral.call() * @param arguments The arguments for this method. See {@link IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])} * the possible values and conversion rules. * @return An array of objects, representing the values you wish to return to the Lua program. * See {@link IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])} for the valid values and * conversion rules. * @throws LuaException If the task could not be queued, or if the task threw an exception. * @throws InterruptedException If the user shuts down or reboots the computer the coroutine is suspended, * InterruptedException will be thrown. This exception must not be caught or * intercepted, or the computer will leak memory and end up in a broken state.w * @see IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[]) */ @Nullable Object[] callMethod(@Nonnull ILuaContext context, int method, @Nonnull Object[] arguments) throws LuaException, InterruptedException; }
mit
mookkiah/java-design-patterns
flux/src/main/java/com/iluwatar/flux/action/ContentAction.java
1477
/* * The MIT License * Copyright © 2014-2019 Ilkka Seppälä * * 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.iluwatar.flux.action; /** * ContentAction is a concrete action. */ public class ContentAction extends Action { private final Content content; public ContentAction(Content content) { super(ActionType.CONTENT_CHANGED); this.content = content; } public Content getContent() { return content; } }
mit
aima-java/aima-java
aimax-osm/src/main/java/aimax/osm/data/WayNodeProvider.java
568
package aimax.osm.data; import java.util.List; import aimax.osm.data.entities.MapNode; import aimax.osm.data.entities.MapWay; /** * Provides different abstractions of a way for rendering. * @author Ruediger Lunde */ public interface WayNodeProvider { /** * Returns a list of nodes describing the specified way which * is suitable for the specified scale. Number of nodes will * typically decrease with decreasing scale * (e.g. 1/10 000 -> 80 nodes; 1/100 000 -> 10 nodes). */ List<MapNode> getWayNodes(MapWay way, float scale); }
mit
CubeEngine/Dirigent
src/test/java/org/cubeengine/dirigent/formatter/CurrencyFormatterTest.java
2339
/* * The MIT License * Copyright © 2013 Cube Island * * 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.cubeengine.dirigent.formatter; import java.util.Locale; import org.cubeengine.dirigent.parser.component.Component; import org.cubeengine.dirigent.context.Arguments; import org.cubeengine.dirigent.parser.Text; import org.junit.Assert; import org.junit.Test; import static org.cubeengine.dirigent.context.Contexts.createContext; /** * Tests the {@link CurrencyFormatter}. */ public class CurrencyFormatterTest { private final CurrencyFormatter currencyFormatter = new CurrencyFormatter(); @Test public void testFormat() { checkFormat("12.345,00 €", 12345, Locale.GERMANY); checkFormat("$12,345.00", 12345, Locale.US); checkFormat("45,26 €", 45.258, Locale.GERMANY); } @Test public void testFormatInvalidLocaleForCurrency() { checkFormat("¤ 45,26", 45.258, Locale.GERMAN); } private void checkFormat(final String expected, final Number number, final Locale locale) { final Component component = currencyFormatter.format(number, createContext(locale), Arguments.NONE); Assert.assertTrue(component instanceof Text); Assert.assertEquals(expected, ((Text)component).getText()); } }
mit
stormtrooper28/EffectLib
src/main/java/de/slikey/effectlib/Effect.java
10109
package de.slikey.effectlib; import de.slikey.effectlib.util.ParticleEffect; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.util.Vector; import java.lang.ref.WeakReference; public abstract class Effect implements Runnable { /** * Handles the type, the effect is played. * * @see {@link de.slikey.effectlib.EffectType} */ public EffectType type = EffectType.INSTANT; /** * Can be used to colorize certain particles. As of 1.8, those * include SPELL_MOB_AMBIENT, SPELL_MOB and REDSTONE. */ public Color color = null; /** This is only used when colorizing certain particles, * since the speed can't be 0 for the particle to look colored. */ public float speed = 1; /** * Delay to wait for delayed effects. * * @see {@link de.slikey.effectlib.EffectType} */ public int delay = 0; /** * Interval to wait for repeating effects. * * @see {@link de.slikey.effectlib.EffectType} */ public int period = 1; /** * Amount of repititions to do. * Set this to -1 for an infinite effect * * @see {@link de.slikey.effectlib.EffectType} */ public int iterations = 0; /** * Callback to run, after effect is done. * * @see {@link java.lang.Runnable} */ public Runnable callback = null; /** * Display particles to players within this radius. Squared radius for * performance reasons. */ public float visibleRange = 32; /** * If true, and a "target" Location or Entity is set, the two Locations * will orient to face one another. */ public boolean autoOrient = true; /** * If set, will offset all locations */ public Vector offset = null; /** * If set, will offset the target location */ public Vector targetOffset = null; /** * If set, will run asynchronously. * Some effects don't support this (TurnEffect, JumpEffect) * * Generally this shouldn't be changed, unless you want to * make an async effect synchronous. */ public boolean asynchronous = true; private Location location = null; private WeakReference<Entity> entity = new WeakReference<Entity>(null); private Location target = null; private WeakReference<Entity> targetEntity = new WeakReference<Entity>(null); private Vector locationEntityOffset = null; private Vector targetEntityOffset = null; private boolean done = false; protected final EffectManager effectManager; protected Runnable asyncRunnableTask; public Effect(EffectManager effectManager) { if (effectManager == null) { throw new IllegalArgumentException("EffectManager cannot be null!"); } this.effectManager = effectManager; } public final void cancel() { cancel(true); } public final void cancel(boolean callback) { if (callback) done(); else done = true; } private void done() { done = true; effectManager.done(this); onDone(); } public final boolean isDone() { return done; } public abstract void onRun(); /** * Called when this effect is done playing (when {@link #done()} is called). */ public void onDone() {} @Override public final void run() { if (!validate()) { cancel(); return; } if (done) return; if (asynchronous) { if (asyncRunnableTask == null) { final Effect effect = this; asyncRunnableTask = new Runnable() { @Override public void run() { try { effect.onRun(); } catch (Exception ex) { effectManager.onError(ex); Bukkit.getScheduler().runTask(effectManager.getOwningPlugin(), new Runnable() { @Override public void run() { effect.done(); } }); } } }; } Bukkit.getScheduler().runTaskAsynchronously(effectManager.getOwningPlugin(), asyncRunnableTask); } else { try { onRun(); } catch (Exception ex) { done(); effectManager.onError(ex); } } if (type == EffectType.REPEATING) { if (iterations == -1) return; iterations--; if (iterations < 1) done(); } else { done(); } } protected final boolean validate() { // Check for a valid Location updateLocation(); updateTarget(); if (location == null) return false; if (autoOrient) { if (target != null) { Vector direction = target.toVector().subtract(location.toVector()); location.setDirection(direction); target.setDirection(direction.multiply(-1)); } } return true; } public final void start() { effectManager.start(this); } public final void infinite() { type = EffectType.REPEATING; iterations = -1; } /** * Extending Effect classes can use this to determine the Entity this * Effect is centered upon. * * This may return null, even for an Effect that was set with an Entity, * if the Entity gets GC'd. */ public Entity getEntity() { return this.entity.get(); } /** * Extending Effect classes can use this to determine the Entity this * Effect is targeted upon. This is probably a very rare case, such as * an Effect that "links" two Entities together somehow. (Idea!) * * This may return null, even for an Effect that was set with a target Entity, * if the Entity gets GC'd. */ public Entity getTargetEntity() { return this.targetEntity.get(); } protected void updateLocation() { Entity entityReference = entity.get(); if (entityReference != null) { Location currentLocation = null; if (entityReference instanceof LivingEntity) { currentLocation = ((LivingEntity)entityReference).getEyeLocation(); } else { currentLocation = entityReference.getLocation(); } if (locationEntityOffset != null) { currentLocation.add(locationEntityOffset); } else if (location != null) { locationEntityOffset = location.toVector().subtract(currentLocation.toVector()); currentLocation = location; } setLocation(currentLocation); } } /** * Extending Effect classes should use this method to obtain the * current "root" Location of the effect. * * This method will not return null when called from onRun. Effects * with invalid locations will be cancelled. */ public final Location getLocation() { return location; } protected void updateTarget() { Entity entityReference = targetEntity.get(); if (entityReference != null) { Location currentLocation = null; if (entityReference instanceof LivingEntity) { currentLocation = ((LivingEntity)entityReference).getEyeLocation(); } else { currentLocation = entityReference.getLocation(); } if (targetEntityOffset != null) { currentLocation.add(targetEntityOffset); } else if (target != null) { targetEntityOffset = target.toVector().subtract(currentLocation.toVector()); currentLocation = target; } setTarget(currentLocation); } } /** * Extending Effect classes should use this method to obtain the * current "target" Location of the effect. * * Unlike getLocation, this may return null. */ public final Location getTarget() { return target; } /** * Set the Entity this Effect is centered on. */ public void setEntity(Entity entity) { this.entity = new WeakReference<Entity>(entity); } /** * Set the Entity this Effect is targeting. */ public void setTargetEntity(Entity entity) { this.targetEntity = new WeakReference<Entity>(entity); } /** * Set the Location this Effect is centered on. */ public void setLocation(Location location) { if (location == null) { throw new IllegalArgumentException("Location cannot be null!"); } this.location = location == null ? null : location.clone(); if (offset != null && this.location != null) { this.location = this.location.add(offset); } } /** * Set the Location this Effect is targeting. */ public void setTarget(Location location) { this.target = location == null ? null : location.clone(); if (targetOffset != null && this.target != null) { this.target = this.target.add(targetOffset); } } protected void display(ParticleEffect effect, Location location) { display(effect, location, this.color); } protected void display(ParticleEffect particle, Location location, Color color) { display(particle, location, color, 0, 1); } protected void display(ParticleEffect particle, Location location, float speed, int amount) { display(particle, location, this.color, speed, amount); } protected void display(ParticleEffect particle, Location location, Color color, float speed, int amount) { particle.display(null, location, color, visibleRange, 0, 0, 0, speed, amount); } }
mit
student-errant/mule-in-action-2e
chapter14/src/main/java/com/prancingdonkey/model/Address.java
905
package com.prancingdonkey.model; public class Address { String address1; String address2; String city; String state; String postalCode; public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } }
mit
OlegDokuka/spring-cloud-starter
jHipster/uaa/src/main/java/com/mycompany/myapp/web/rest/AuditResource.java
3577
package com.mycompany.myapp.web.rest; import com.mycompany.myapp.service.AuditEventService; import java.time.LocalDate; import com.mycompany.myapp.web.rest.util.PaginationUtil; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.http.HttpStatus; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import java.net.URISyntaxException; import javax.inject.Inject; import java.util.List; /** * REST controller for getting the audit events. */ @RestController @RequestMapping(value = "/management/jhipster/audits", produces = MediaType.APPLICATION_JSON_VALUE) public class AuditResource { private AuditEventService auditEventService; @Inject public AuditResource(AuditEventService auditEventService) { this.auditEventService = auditEventService; } /** * GET /audits : get a page of AuditEvents. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body * @throws URISyntaxException if there is an error to generate the pagination HTTP headers */ @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<AuditEvent>> getAll(Pageable pageable) throws URISyntaxException { Page<AuditEvent> page = auditEventService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/audits"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /audits : get a page of AuditEvents between the fromDate and toDate. * * @param fromDate the start of the time period of AuditEvents to get * @param toDate the end of the time period of AuditEvents to get * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body * @throws URISyntaxException if there is an error to generate the pagination HTTP headers */ @RequestMapping(method = RequestMethod.GET, params = {"fromDate", "toDate"}) public ResponseEntity<List<AuditEvent>> getByDates( @RequestParam(value = "fromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, @RequestParam(value = "toDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, Pageable pageable) throws URISyntaxException { Page<AuditEvent> page = auditEventService.findByDates(fromDate.atTime(0, 0), toDate.atTime(23, 59), pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/audits"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /audits/:id : get an AuditEvent by id. * * @param id the id of the entity to get * @return the ResponseEntity with status 200 (OK) and the AuditEvent in body, or status 404 (Not Found) */ @RequestMapping(value = "/{id:.+}", method = RequestMethod.GET) public ResponseEntity<AuditEvent> get(@PathVariable Long id) { return auditEventService.find(id) .map((entity) -> new ResponseEntity<>(entity, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } }
mit
selvasingh/azure-sdk-for-java
sdk/appplatform/mgmt-v2019_05_01_preview/src/main/java/com/microsoft/azure/management/appplatform/v2019_05_01_preview/ConfigServerSettings.java
1102
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appplatform.v2019_05_01_preview; import com.fasterxml.jackson.annotation.JsonProperty; /** * The settings of config server. */ public class ConfigServerSettings { /** * Property of git environment. */ @JsonProperty(value = "gitProperty") private ConfigServerGitProperty gitProperty; /** * Get property of git environment. * * @return the gitProperty value */ public ConfigServerGitProperty gitProperty() { return this.gitProperty; } /** * Set property of git environment. * * @param gitProperty the gitProperty value to set * @return the ConfigServerSettings object itself. */ public ConfigServerSettings withGitProperty(ConfigServerGitProperty gitProperty) { this.gitProperty = gitProperty; return this; } }
mit
gregwym/joos-compiler-java
testcases/a3/J1_typecheck_instanceof5.java
253
// TYPE_CHECKING public class J1_typecheck_instanceof5 { public J1_typecheck_instanceof5 () {} public static int test() { boolean b = true; b = !(new Object() instanceof Object[]); if (b) return 123; else return 17; } }
mit
nicorsm/S3-16-simone
app/src/test/java/app/simone/multiplayer/FacebookManagerTest.java
1633
package app.simone.multiplayer; import android.os.Bundle; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import akka.actor.ActorRef; import akka.testkit.JavaTestKit; import app.simone.ActorTests; import app.simone.multiplayer.messages.FbRequestFriendsMsgMock; import app.simone.multiplayer.messages.FbResponseFriendsMsg; import app.simone.shared.utils.Constants; import app.simone.shared.utils.Utilities; import static junit.framework.Assert.assertTrue; /** * Created by nicola on 28/08/2017. */ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(JUnit4.class) public class FacebookManagerTest extends ActorTests { @Test public void testCorrectFacebookFriends() { new JavaTestKit(system) {{ JavaTestKit probe = new JavaTestKit(system); Bundle bundle = Mockito.mock(Bundle.class); MockGraphRequestWrapper request = new MockGraphRequestWrapper(new CorrectMockingStrategy()); getFbManagerActor().tell(new FbRequestFriendsMsgMock(bundle, request), probe.getRef()); FbResponseFriendsMsg message = probe.expectMsgClass(defaultDuration, FbResponseFriendsMsg.class); assertTrue(message.getData().size() > 0); assertTrue(message.getErrorMessage() == null || message.getErrorMessage().equals("")); }}; } private ActorRef getFbManagerActor() { return Utilities.getActor(Constants.FACEBOOK_ACTOR_NAME, system); } }
mit
stoman/CompetitiveProgramming
problems/icecreamparlor/submissions/accepted/Stefan.java
903
//Author: Stefan Toman import java.io.*; import java.util.*; public class Stefan { static void solve(int[] arr, int money) { HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>(); for(int i = 0; i < arr.length; i++) { if(hs.containsKey(arr[i])) { System.out.format("%d %d\n", hs.get(arr[i]) + 1, i + 1); return; } hs.put(money - arr[i], i); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for(int a0 = 0; a0 < t; a0++){ int money = in.nextInt(); int n = in.nextInt(); int[] arr = new int[n]; for(int arr_i = 0; arr_i < n; arr_i++){ arr[arr_i] = in.nextInt(); } solve(arr, money); } in.close(); } }
mit
rextrebat/ecloudmanager
ecloud-manager-ejb/src/main/java/org/ecloudmanager/domain/template/SshConfiguration.java
5989
/* * MIT License * * Copyright (c) 2016 Altisource * * 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.ecloudmanager.domain.template; import org.ecloudmanager.domain.OwnedMongoObject; import org.ecloudmanager.security.Encrypted; import org.ecloudmanager.security.EncryptedStringConverter; import org.mongodb.morphia.annotations.Converters; import org.mongodb.morphia.annotations.Entity; import java.io.Serializable; @Entity(noClassnameStored = true) @Converters(EncryptedStringConverter.class) public class SshConfiguration extends OwnedMongoObject implements Serializable { private static final long serialVersionUID = 1293171298086413994L; private String name; private String jumpHost1; private String jumpHost1Username; private String jumpHost2; private String jumpHost2Username; private String username; @Encrypted private String privateKey; @Encrypted private String privateKeyPassphrase; @Encrypted private String jumpHost1PrivateKey; @Encrypted private String jumpHost1PrivateKeyPassphrase; @Encrypted private String jumpHost2PrivateKey; @Encrypted private String jumpHost2PrivateKeyPassphrase; public SshConfiguration() { } public SshConfiguration(SshConfiguration configuration) { setId(configuration.getId()); name = configuration.getName(); jumpHost1 = configuration.getJumpHost1(); jumpHost1Username = configuration.getJumpHost1Username(); jumpHost2 = configuration.getJumpHost2(); jumpHost2Username = configuration.getJumpHost2Username(); username = configuration.getUsername(); privateKey = configuration.getPrivateKey(); privateKeyPassphrase = configuration.getPrivateKeyPassphrase(); jumpHost1PrivateKey = configuration.getJumpHost1PrivateKey(); jumpHost1PrivateKeyPassphrase = configuration.getJumpHost1PrivateKeyPassphrase(); jumpHost2PrivateKey = configuration.getJumpHost2PrivateKey(); jumpHost2PrivateKeyPassphrase = configuration.getJumpHost2PrivateKeyPassphrase(); } public String getJumpHost1() { return jumpHost1; } public void setJumpHost1(String jumpHost1) { this.jumpHost1 = jumpHost1; } public String getJumpHost1Username() { return jumpHost1Username; } public void setJumpHost1Username(String jumpHost1Username) { this.jumpHost1Username = jumpHost1Username; } public String getJumpHost2() { return jumpHost2; } public void setJumpHost2(String jumpHost2) { this.jumpHost2 = jumpHost2; } public String getJumpHost2Username() { return jumpHost2Username; } public void setJumpHost2Username(String jumpHost2Username) { this.jumpHost2Username = jumpHost2Username; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public String getPrivateKeyPassphrase() { return privateKeyPassphrase; } public void setPrivateKeyPassphrase(String privateKeyPassphrase) { this.privateKeyPassphrase = privateKeyPassphrase; } public String getJumpHost1PrivateKey() { return jumpHost1PrivateKey; } public void setJumpHost1PrivateKey(String jumpHost1PrivateKey) { this.jumpHost1PrivateKey = jumpHost1PrivateKey; } public String getJumpHost1PrivateKeyPassphrase() { return jumpHost1PrivateKeyPassphrase; } public void setJumpHost1PrivateKeyPassphrase(String jumpHost1PrivateKeyPassphrase) { this.jumpHost1PrivateKeyPassphrase = jumpHost1PrivateKeyPassphrase; } public String getJumpHost2PrivateKey() { return jumpHost2PrivateKey; } public void setJumpHost2PrivateKey(String jumpHost2PrivateKey) { this.jumpHost2PrivateKey = jumpHost2PrivateKey; } public String getJumpHost2PrivateKeyPassphrase() { return jumpHost2PrivateKeyPassphrase; } public void setJumpHost2PrivateKeyPassphrase(String jumpHost2PrivateKeyPassphrase) { this.jumpHost2PrivateKeyPassphrase = jumpHost2PrivateKeyPassphrase; } @Override public String toString() { return "SshConfiguration{" + "name='" + name + '\'' + ", jumpHost1='" + jumpHost1 + '\'' + ", jumpHost1Username='" + jumpHost1Username + '\'' + ", jumpHost2='" + jumpHost2 + '\'' + ", jumpHost2Username='" + jumpHost2Username + '\'' + ", username='" + username + '\'' + '}'; } }
mit
navalev/azure-sdk-for-java
sdk/network/mgmt-v2018_12_01/src/main/java/com/microsoft/azure/management/network/v2018_12_01/AzureFirewallIPConfiguration.java
4914
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2018_12_01; import com.microsoft.azure.SubResource; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; /** * IP configuration of an Azure Firewall. */ @JsonFlatten public class AzureFirewallIPConfiguration extends SubResource { /** * The Firewall Internal Load Balancer IP to be used as the next hop in * User Defined Routes. */ @JsonProperty(value = "properties.privateIPAddress", access = JsonProperty.Access.WRITE_ONLY) private String privateIPAddress; /** * Reference of the subnet resource. This resource must be named * 'AzureFirewallSubnet'. */ @JsonProperty(value = "properties.subnet") private SubResource subnet; /** * Reference of the PublicIP resource. This field is a mandatory input if * subnet is not null. */ @JsonProperty(value = "properties.publicIPAddress") private SubResource publicIPAddress; /** * The provisioning state of the resource. Possible values include: * 'Succeeded', 'Updating', 'Deleting', 'Failed'. */ @JsonProperty(value = "properties.provisioningState") private ProvisioningState provisioningState; /** * Name of the resource that is unique within a resource group. This name * can be used to access the resource. */ @JsonProperty(value = "name") private String name; /** * A unique read-only string that changes whenever the resource is updated. */ @JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY) private String etag; /** * Get the Firewall Internal Load Balancer IP to be used as the next hop in User Defined Routes. * * @return the privateIPAddress value */ public String privateIPAddress() { return this.privateIPAddress; } /** * Get reference of the subnet resource. This resource must be named 'AzureFirewallSubnet'. * * @return the subnet value */ public SubResource subnet() { return this.subnet; } /** * Set reference of the subnet resource. This resource must be named 'AzureFirewallSubnet'. * * @param subnet the subnet value to set * @return the AzureFirewallIPConfiguration object itself. */ public AzureFirewallIPConfiguration withSubnet(SubResource subnet) { this.subnet = subnet; return this; } /** * Get reference of the PublicIP resource. This field is a mandatory input if subnet is not null. * * @return the publicIPAddress value */ public SubResource publicIPAddress() { return this.publicIPAddress; } /** * Set reference of the PublicIP resource. This field is a mandatory input if subnet is not null. * * @param publicIPAddress the publicIPAddress value to set * @return the AzureFirewallIPConfiguration object itself. */ public AzureFirewallIPConfiguration withPublicIPAddress(SubResource publicIPAddress) { this.publicIPAddress = publicIPAddress; return this; } /** * Get the provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'. * * @return the provisioningState value */ public ProvisioningState provisioningState() { return this.provisioningState; } /** * Set the provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'. * * @param provisioningState the provisioningState value to set * @return the AzureFirewallIPConfiguration object itself. */ public AzureFirewallIPConfiguration withProvisioningState(ProvisioningState provisioningState) { this.provisioningState = provisioningState; return this; } /** * Get name of the resource that is unique within a resource group. This name can be used to access the resource. * * @return the name value */ public String name() { return this.name; } /** * Set name of the resource that is unique within a resource group. This name can be used to access the resource. * * @param name the name value to set * @return the AzureFirewallIPConfiguration object itself. */ public AzureFirewallIPConfiguration withName(String name) { this.name = name; return this; } /** * Get a unique read-only string that changes whenever the resource is updated. * * @return the etag value */ public String etag() { return this.etag; } }
mit
paoesco/walkingdog
walkingdog-services/src/main/java/com/hubesco/software/walkingdog/services/location/Map.java
1415
package com.hubesco.software.walkingdog.services.location; import java.awt.Point; import java.awt.Polygon; import java.awt.Shape; import java.awt.geom.Path2D; import java.awt.geom.Point2D; /** * @author paoesco */ public class Map { private final Point2D topLeft; private final Point2D topRight; private final Point2D bottomRight; private final Point2D bottomLeft; public Map(Point2D topLeft, Point2D topRight, Point2D bottomRight, Point2D bottomLeft) { this.topLeft = topLeft; this.topRight = topRight; this.bottomRight = bottomRight; this.bottomLeft = bottomLeft; } private Path2D.Double polygon() { Path2D.Double polygon = new Path2D.Double(); polygon.moveTo(topLeft.getX(), topLeft.getY()); polygon.lineTo(topRight.getX(), topRight.getY()); polygon.lineTo(bottomRight.getX(), bottomRight.getY()); polygon.lineTo(bottomLeft.getX(), bottomLeft.getY()); polygon.closePath(); return polygon; } public boolean contains(Point2D point) { return polygon().contains(point.getX(), point.getY()); } public Point2D getTopLeft() { return topLeft; } public Point2D getTopRight() { return topRight; } public Point2D getBottomRight() { return bottomRight; } public Point2D getBottomLeft() { return bottomLeft; } }
mit
recena/github-api
src/main/java/org/kohsuke/github/GHDeployment.java
2362
package org.kohsuke.github; import java.io.IOException; import java.net.URL; /** * Represents a deployment * * @see <a href="https://developer.github.com/v3/repos/deployments/">documentation</a> * @see GHRepository#listDeployments(String, String, String, String) * @see GHRepository#getDeployment(long) */ public class GHDeployment extends GHObject { private GHRepository owner; private GitHub root; protected String sha; protected String ref; protected String task; protected Object payload; protected String environment; protected String description; protected String statuses_url; protected String repository_url; protected GHUser creator; GHDeployment wrap(GHRepository owner) { this.owner = owner; this.root = owner.root; if(creator != null) creator.wrapUp(root); return this; } public URL getStatusesUrl() { return GitHub.parseURL(statuses_url); } public URL getRepositoryUrl() { return GitHub.parseURL(repository_url); } public String getTask() { return task; } public String getPayload() { return (String) payload; } public String getEnvironment() { return environment; } public GHUser getCreator() throws IOException { return root.intern(creator); } public String getRef() { return ref; } public String getSha(){ return sha; } /** * @deprecated This object has no HTML URL. */ @Override public URL getHtmlUrl() { return null; } public GHDeploymentStatusBuilder createStatus(GHDeploymentState state) { return new GHDeploymentStatusBuilder(owner,id,state); } public PagedIterable<GHDeploymentStatus> listStatuses() { return new PagedIterable<GHDeploymentStatus>() { public PagedIterator<GHDeploymentStatus> _iterator(int pageSize) { return new PagedIterator<GHDeploymentStatus>(root.retrieve().asIterator(statuses_url, GHDeploymentStatus[].class, pageSize)) { @Override protected void wrapUp(GHDeploymentStatus[] page) { for (GHDeploymentStatus c : page) c.wrap(owner); } }; } }; } }
mit
OmicronProject/BakeoutController
src/test/java/unit/main/app_configuration/Kernel.java
412
package unit.main.app_configuration; import main.ApplicationConfiguration; import org.junit.Test; import static org.junit.Assert.assertNotNull; /** * Contains unit tests for {@link ApplicationConfiguration#kernel()} */ public final class Kernel extends AppConfigurationTestCase { @Test public void kernel(){ assertNotNull( context.getBean(kernel.Kernel.class) ); } }
mit
jenkinsci/github-pullrequest-plugin
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRMessage.java
4399
package org.jenkinsci.plugins.github.pullrequest; import hudson.Extension; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.Run; import hudson.model.TaskListener; import jenkins.model.Jenkins; import org.jenkinsci.Symbol; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static java.util.Objects.nonNull; import static org.apache.commons.lang.StringUtils.isEmpty; /** * Represents a comment for GitHub that can contain token macros. * * @author Kanstantsin Shautsou * @author Alina Karpovich */ public class GitHubPRMessage extends AbstractDescribableImpl<GitHubPRMessage> { private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRMessage.class); private String content; @DataBoundConstructor public GitHubPRMessage(String content) { this.content = content; } /** * Expand all what we can from given run */ @Restricted(NoExternalUse.class) @CheckForNull public String expandAll(Run<?, ?> run, TaskListener listener) throws IOException, InterruptedException { return expandAll(getContent(), run, listener); } /** * Expand all what we can from given run */ @Restricted(NoExternalUse.class) @CheckForNull public static String expandAll(String content, Run<?, ?> run, TaskListener listener) throws IOException, InterruptedException { if (isEmpty(content)) { return content; // Do nothing for an empty String } // Expand environment variables String body = run.getEnvironment(listener).expand(content); // Expand build variables + token macro if they available if (run instanceof AbstractBuild<?, ?>) { final AbstractBuild<?, ?> build = (AbstractBuild<?, ?>) run; body = Util.replaceMacro(body, build.getBuildVariableResolver()); try { Jenkins jenkins = Jenkins.getActiveInstance(); ClassLoader uberClassLoader = jenkins.pluginManager.uberClassLoader; List macros = null; if (nonNull(jenkins.getPlugin("token-macro"))) { // get private macroses like groovy template ${SCRIPT} if available if (nonNull(jenkins.getPlugin("email-ext"))) { Class<?> contentBuilderClazz = uberClassLoader.loadClass("hudson.plugins.emailext.plugins.ContentBuilder"); Method getPrivateMacrosMethod = contentBuilderClazz.getDeclaredMethod("getPrivateMacros"); macros = new ArrayList((Collection) getPrivateMacrosMethod.invoke(null)); } // call TokenMacro.expand(build, listener, content, false, macros) Class<?> tokenMacroClazz = uberClassLoader.loadClass("org.jenkinsci.plugins.tokenmacro.TokenMacro"); Method tokenMacroExpand = tokenMacroClazz.getDeclaredMethod("expand", AbstractBuild.class, TaskListener.class, String.class, boolean.class, List.class); body = (String) tokenMacroExpand.invoke(null, build, listener, body, false, macros); } } catch (ClassNotFoundException e) { LOGGER.error("Can't find class", e); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { LOGGER.error("Can't evaluate macro", e); } } return body; } public String getContent() { return content; } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } @Symbol("githubPRMessage") @Extension public static class DescriptorImpl extends Descriptor<GitHubPRMessage> { @Override public String getDisplayName() { return "Expandable comment field"; } } }
mit
manuel-zulian/Match-Point
trunk/src/java/it/gemmed/database/FindIscrizioneDatabase.java
9473
package it.gemmed.database; import it.gemmed.resource.Giocatore; import it.gemmed.resource.Iscrizione; import it.gemmed.resource.Torneo; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Classe usata per le ricerche nel database di elementi di tipo iscrizione * * @author GEMMED * @version 0.1 */ public class FindIscrizioneDatabase { /** * Query che ritorna le iscrizioni di un torneo */ private static final String SELECT_ISCRIZIONI = "SELECT * FROM iscrizione WHERE torneo = ?"; /** * Query che ritorna la iscrizione di un torneo per un giocatore */ private static final String SELECT_ISCRIZIONE_GIOCATORE = "SELECT * FROM iscrizione WHERE torneo = ? AND giocatore = ?"; /** * Query usata per ottenere una lista di tornei attivi in cui un giocatore si trova iscritto */ private static final String SELECT_TORNEO_INCORSO = "SELECT nome, data_inizio, data_fine, categoria, circolo, tipologia, arbitro, federazione, convalidato, id, iscrizione_inizio, iscrizione_fine FROM iscrizione as I INNER JOIN torneo AS T ON I.torneo = T.id WHERE giocatore = ? AND data_inizio < CURRENT_DATE AND CURRENT_DATE < data_fine AND convalidato ='si' "; /** * Query usata per ottenere una lista di tornei da disputare in cui un giocatore si trova iscritto */ private static final String SELECT_TORNEO_DADISPUTARE = "SELECT nome, data_inizio, data_fine, categoria, circolo, tipologia, arbitro, federazione, convalidato, id, iscrizione_inizio, iscrizione_fine FROM iscrizione as I INNER JOIN torneo AS T ON I.torneo = T.id WHERE giocatore = ? AND CURRENT_DATE < data_inizio AND iscrizione_inizio < CURRENT_DATE AND convalidato = 'si' "; /** * Query usata per ottenere una lista di tornei disponibili in cui un giocatore può iscriversi */ private static final String SELECT_TORNEO_DISPONIBILI = "SELECT nome, data_inizio, data_fine, categoria, circolo, tipologia, arbitro, federazione, convalidato, id, iscrizione_inizio, iscrizione_fine FROM torneo WHERE convalidato='si' AND iscrizione_inizio < CURRENT_DATE AND CURRENT_DATE < iscrizione_fine EXCEPT SELECT nome, data_inizio, data_fine, categoria, circolo, tipologia, arbitro, federazione, convalidato, id, iscrizione_inizio, iscrizione_fine FROM iscrizione as I INNER JOIN torneo AS T ON I.torneo = T.id WHERE giocatore = ? AND CURRENT_DATE < iscrizione_fine AND iscrizione_inizio < CURRENT_DATE AND convalidato = 'si' "; /** * Query usata per ottenere una lista di tornei conclusi in cui il giocatore ha partecipato. */ private static final String SELECT_TORNEO_CONCLUSO = "SELECT nome, data_inizio, data_fine, categoria, circolo, tipologia, arbitro, federazione, convalidato, id, iscrizione_inizio, iscrizione_fine FROM iscrizione as I INNER JOIN torneo AS T ON I.torneo = T.id WHERE giocatore = ? AND CURRENT_DATE > data_fine AND convalidato ='si' "; /** * Connessione al database */ private final Connection con; /** * Risultati della ricerca */ private final List<Torneo> tornei; private final List<Iscrizione> isc; /** * Crea una nuova connessione per ricercare informazioni nel database. * * @param con * connessione al database */ public FindIscrizioneDatabase(final Connection con) { this.con = con; this.tornei = new ArrayList<Torneo>(); this.isc = new ArrayList<Iscrizione>(); }//FindIscrizioneDatabase /** * Metodo * * @param giocatore * @return list Una lista contenente i tornei attivi in cui un giocatore si trova iscritto * * @throws SQLException * Errore nella ricerca del torneo */ public List<Torneo> findTorneoInCorso(String giocatore) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = con.prepareStatement(SELECT_TORNEO_INCORSO); pstmt.setString(1, giocatore); rs = pstmt.executeQuery(); while (rs.next()) { tornei.add(new Torneo(rs.getString("nome"), rs .getDate("data_inizio"), rs.getDate("data_fine"), rs.getString("categoria"), rs.getInt("id"), rs.getString("circolo"), rs.getString("tipologia"), rs.getString("arbitro"), rs.getString("federazione"), rs.getString("convalidato"), rs.getDate("iscrizione_inizio"), rs.getDate("iscrizione_fine") )); }//while } finally { if (rs != null) { rs.close(); }//if if (pstmt != null) { pstmt.close(); }//if con.close(); }//try-catch return tornei; }//findTorneoInCorso /** * Metodo * * @param giocatore * @return list Una lista contenente i tornei da disputare in cui un giocatore si trova iscritto * * @throws SQLException * Errore nella ricerca del torneo */ public List<Torneo> findTorneoDaDisputare(String giocatore) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = con.prepareStatement(SELECT_TORNEO_DADISPUTARE); pstmt.setString(1, giocatore); rs = pstmt.executeQuery(); while (rs.next()) { tornei.add(new Torneo(rs.getString("nome"), rs .getDate("data_inizio"), rs.getDate("data_fine"), rs.getString("categoria"), rs.getInt("id"), rs.getString("circolo"), rs.getString("tipologia"), rs.getString("arbitro"), rs.getString("federazione"), rs.getString("convalidato"),rs.getDate("iscrizione_inizio"), rs.getDate("iscrizione_fine") )); }//while } finally { if (rs != null) { rs.close(); }//if if (pstmt != null) { pstmt.close(); }//if con.close(); }//try-catch return tornei; }//findTorneoDaDisputare /** * Metodo * * @param giocatore * @return list Una lista contenente i tornei disponibili in cui un giocatore può iscriversi * * @throws SQLException * Errore nella ricerca del torneo */ public List<Torneo> findTorneoDisponibile(String giocatore) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = con.prepareStatement(SELECT_TORNEO_DISPONIBILI); pstmt.setString(1, giocatore); rs = pstmt.executeQuery(); while (rs.next()) { tornei.add(new Torneo(rs.getString("nome"), rs .getDate("data_inizio"), rs.getDate("data_fine"), rs.getString("categoria"), rs.getInt("id"), rs.getString("circolo"), rs.getString("tipologia"), rs.getString("arbitro"), rs.getString("federazione"), rs.getString("convalidato"), rs.getDate("iscrizione_inizio"), rs.getDate("iscrizione_fine") )); }//while } finally { if (rs != null) { rs.close(); }//if if (pstmt != null) { pstmt.close(); }//if con.close(); }//try-catch return tornei; }//findTorneoDisponibile /** * Metodo * * @param giocatore * @return list Una lista contenente i tornei conclusi in cui il giocatore ha partecipato. * * @throws SQLException * Errore nella ricerca del torneo */ public List<Torneo> findTorneoConcluso(String giocatore) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = con.prepareStatement(SELECT_TORNEO_CONCLUSO); pstmt.setString(1, giocatore); rs = pstmt.executeQuery(); while (rs.next()) { tornei.add(new Torneo(rs.getString("nome"), rs .getDate("data_inizio"), rs.getDate("data_fine"), rs.getString("categoria"), rs.getInt("id"), rs.getString("circolo"), rs.getString("tipologia"), rs.getString("arbitro"), rs.getString("federazione"), rs.getString("convalidato"), rs.getDate("iscrizione_inizio"), rs.getDate("iscrizione_fine") )); }//while } finally { if (rs != null) { rs.close(); }//if if (pstmt != null) { pstmt.close(); }//if con.close(); }//try-catch return tornei; }//findTorneoConcluso /** * * @param torneo * @return list Una lista contenente le iscrizioni. * * @throws SQLException * Errore nella ricerca del torneo */ public List<Iscrizione> findIscrizioni(String id) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = con.prepareStatement(SELECT_ISCRIZIONI); pstmt.setInt(1, Integer.parseInt(id)); rs = pstmt.executeQuery(); while (rs.next()) { isc.add(new Iscrizione(rs.getString("giocatore"), (Boolean[])rs.getArray("disponibilita").getArray(), rs .getInt("torneo"))); }//while } finally { if (rs != null) { rs.close(); }//if if (pstmt != null) { pstmt.close(); }//if con.close(); }//try-catch return isc; }//findTorneoConcluso public Iscrizione findIscrizioneGiocatore(String giocatore, int id) throws SQLException { Iscrizione isc = null; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = con.prepareStatement(SELECT_ISCRIZIONE_GIOCATORE); pstmt.setInt(1, id); pstmt.setString(2, giocatore); rs = pstmt.executeQuery(); while (rs.next()) { isc = new Iscrizione(rs.getString("giocatore"), (Boolean[])rs.getArray("disponibilita").getArray(), rs .getInt("torneo")); }//while } finally { if (rs != null) { rs.close(); }//if if (pstmt != null) { pstmt.close(); }//if con.close(); }//try-catch return isc; }//findTorneoConcluso }//FindIscrizioneDatabase
mit
JeffRisberg/BING01
src/test/java/com/microsoft/bingads/api/test/entities/adgroup/write/BulkAdGroupWriteToRowValuesNativeBidAdjustmentTest.java
1295
package com.microsoft.bingads.api.test.entities.adgroup.write; import com.microsoft.bingads.api.test.entities.adgroup.BulkAdGroupTest; import com.microsoft.bingads.bulk.entities.BulkAdGroup; import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public class BulkAdGroupWriteToRowValuesNativeBidAdjustmentTest extends BulkAdGroupTest { @Parameterized.Parameter(value = 1) public Integer propertyValue; @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"1", 1}, {"2147483647", Integer.MAX_VALUE}, {"0", 0}, {"-1", -1}, {"-2147483648", Integer.MIN_VALUE}, {null, null} }); } @Test public void testWrite() { testWriteProperty("Bid Adjustment", this.datum, this.propertyValue, new BiConsumer<BulkAdGroup, Integer>() { @Override public void accept(BulkAdGroup c, Integer v) { c.getAdGroup().setNativeBidAdjustment(v); } }); } }
mit
graphstream/gs-gephi
src-test/org/graphstream/stream/gephi/test/ExampleJSONStream.java
3319
/* * Copyright (C) 2012 wumalbert * * 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.graphstream.stream.gephi.test; import java.io.IOException; import java.net.UnknownHostException; import org.graphstream.graph.Graph; import org.graphstream.graph.implementations.MultiGraph; import org.graphstream.stream.gephi.JSONReceiver; import org.graphstream.stream.gephi.JSONSender; import org.graphstream.stream.thread.ThreadProxyPipe; /** * A simple example of use of the JSONSink and JSONReceiver to communicate with * Gephi. JSONSink sends events to Gephi, and JSONReceiver receiver events from * Gephi * * @author Min WU */ public class ExampleJSONStream { public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException { // ----- On the receiver side ----- // // - a graph that will display the received events Graph g = new MultiGraph("G", false, true); g.display(); // - the receiver that waits for events JSONReceiver receiver = new JSONReceiver("localhost", 8080, "workspace0"); receiver.setDebug(true); // - received events end up in the "default" pipe ThreadProxyPipe pipe = receiver.getStream(); // - plug the pipe to the sink of the graph pipe.addSink(g); // ----- The sender side (in another thread) ------ // new Thread() { public void run() { // - the original graph from which events are generated Graph g = new MultiGraph("G"); // - the sender JSONSender sender = new JSONSender("localhost", 8080, "workspace0"); // - plug the graph to the sender so that graph events can be // sent automatically g.addSink(sender); // - generate some events on the client side String style = "node{fill-mode:plain;fill-color:#567;size:6px;}"; g.addAttribute("stylesheet", style); g.addAttribute("ui.antialias", true); g.addAttribute("layout.stabilization-limit", 0); for (int i = 0; i < 50; i++) { g.addNode(i + ""); if (i > 0) { g.addEdge(i + "-" + (i - 1), i + "", (i - 1) + ""); g.addEdge(i + "--" + (i / 2), i + "", (i / 2) + ""); } } } }.start(); // ----- Back to the receiver side ----- // // -The receiver pro-actively checks for events on the ThreadProxyPipe while (true) { pipe.pump(); Thread.sleep(100); } } }
mit
planetguy32/EnterpriseEnergyEquipment
src/api/java/li/cil/oc/api/machine/Machine.java
9992
package li.cil.oc.api.machine; import li.cil.oc.api.network.ManagedEnvironment; import java.util.Map; /** * This interface allows interacting with a Machine obtained via the factory * method {@link li.cil.oc.api.Machine#create(MachineHost)}. */ @SuppressWarnings("unused") public interface Machine extends ManagedEnvironment, Context { /** * The owner of the machine, usually a tile entity hosting the machine. * * @return the owner of the machine. */ MachineHost host(); /** * This must be called from the host when something relevant to the * machine changes, such as a change in the amount of available memory. */ void onHostChanged(); /** * The underlying architecture of the machine. * <p/> * This is what actually evaluates code running on the machine, where the * machine class itself serves as a scheduler. * <p/> * This may be <tt>null</tt>, for example when the hosting computer has * no CPU installed. * * @return the architecture of this machine. */ Architecture architecture(); /** * Get the address of the file system component from which to try to boot. * <p/> * The underlying architecture may choose to ignore this setting. */ String getBootAddress(); /** * Set the address of the file system component from which to try to boot. * * @param value the new address to try to boot from. */ void setBootAddress(String value); /** * The list of components attached to this machine. * <p/> * This maps address to component type/name. Note that the list may not * immediately reflect changes after components were added to the network, * since such changes are cached in an internal list of 'added components' * that are processed in the machine's update logic (i.e. server tick). * <p/> * This list is kept up-to-date automatically, do <em>not</em> mess with it. * * @return the list of attached components. */ Map<String, String> components(); /** * The number of connected components. * <p/> * This number can differ from <tt>components().size()</tt>, since this is * the number of actually <em>connected</em> components, which is used to * determine whether the component limit has been exceeded, for example. It * takes into account components added but not processed, yet (see also * {@link #components()}). * * @return the number of connected components. */ int componentCount(); /** * Gets the amount of energy this machine consumes per tick when it is * running. * * @return the energy consumed per tick by the machine. */ double getCostPerTick(); /** * Sets the amount of energy this machine consumes per tick when it is * running. * * @param value the energy consumed per tick by the machine. */ void setCostPerTick(double value); /** * The address of the file system that holds the machine's temporary files * (tmpfs). This may return <tt>null</tt> if either the creation of the file * system failed, or if the size of the tmpfs has been set to zero in the * config. * <p/> * Use this in a custom architecture to allow code do differentiate the * tmpfs from other file systems, for example. * * @return the address of the tmpfs component, or <tt>null</tt>. */ String tmpAddress(); /** * A string with the last error message. * <p/> * The error string is set either when the machine crashes (see the * {@link #crash(String)} method), or when it fails to start (which, * technically, is also a crash). * <p/> * When the machine started, this is reset to <tt>null</tt>. * * @return the last error message, or <tt>null</tt>. */ String lastError(); /** * The current world time. This is updated each tick and provides a thread * safe way to access the world time for architectures. * <p/> * This is equivalent to <tt>owner().world().getWorldTime()</tt>. * * @return the current world time. */ long worldTime(); /** * The time that has passed since the machine was started, in seconds. * <p/> * Note that this is actually measured in world time, so the resolution is * pretty limited. This is done to avoid 'time skips' when leaving the game * and coming back later, resuming a persisted machine. */ double upTime(); /** * The time spent running the underlying architecture in execution threads, * i.e. the time spent in {@link Architecture#runThreaded(boolean)} since * the machine was last started, in seconds. */ double cpuTime(); /** * Crashes the computer. * <p/> * This is exactly the same as {@link Context#stop()}, except that it also * sets the error message in the machine. This message can be seen when the * Analyzer is used on computer cases, for example. * * @param message the message to set. * @return <tt>true</tt> if the computer switched to the stopping state. */ boolean crash(String message); /** * Tries to pop a signal from the queue and returns it. * <p/> * Signals are stored in a FIFO queue of limited size. This method is / must * be called by architectures regularly to process the queue. * * @return a signal or <tt>null</tt> if the queue was empty. */ Signal popSignal(); /** * Get a list of all methods and their annotations of the specified object. * <p/> * The specified object can be either a {@link li.cil.oc.api.machine.Value} * or a {@link li.cil.oc.api.network.Environment}. This is useful for * custom architectures, to allow providing a list of callback methods to * evaluated programs. * * @param value the value to get the method listing for. * @return the methods that can be called on the object. */ Map<String, Callback> methods(Object value); /** * Makes the machine call a component callback. * <p/> * This is intended to be used from architectures, but may be useful in * other scenarios, too. It will make the machine call the method with the * specified name on the attached component with the specified address. * <p/> * This will perform a visibility check, ensuring the component can be seen * from the machine. It will also ensure that the direct call limit for * individual callbacks is respected. * * @param address the address of the component to call the method on. * @param method the name of the method to call. * @param args the list of arguments to pass to the callback. * @return a list of results returned by the callback, or <tt>null</tt>. * @throws LimitReachedException when the called method supports direct * calling, but the number of calls in this * tick has exceeded the allowed limit. * @throws IllegalArgumentException if there is no such component. * @throws Exception if the callback throws an exception. */ Object[] invoke(String address, String method, Object[] args) throws Exception; /** * Makes the machine call a value callback. * <p/> * This is intended to be used from architectures, but may be useful in * other scenarios, too. It will make the machine call the method with the * specified name on the specified value. * <p/> * This will will ensure that the direct call limit for individual * callbacks is respected. * * @param value the value to call the method on. * @param method the name of the method to call. * @param args the list of arguments to pass to the callback. * @return a list of results returned by the callback, or <tt>null</tt>. * @throws LimitReachedException when the called method supports direct * calling, but the number of calls in this * tick has exceeded the allowed limit. * @throws IllegalArgumentException if there is no such component. * @throws Exception if the callback throws an exception. */ Object[] invoke(Value value, String method, Object[] args) throws Exception; /** * The list of users registered on this machine. * <p/> * This list is used for {@link Context#canInteract(String)}. Exposed for * informative purposes only, for example to expose it to user code. Note * that the returned array is a copy of the internal representation of the * user list. Changing it has no influence on the actual list. * * @return the list of registered users. */ String[] users(); /** * Add a player to the machine's list of users, by username. * <p/> * This requires for the player to be online. * * @param name the name of the player to add as a user. * @throws Exception if * <ul> * <li>There are already too many users.</li> * <li>The player is already registered.</li> * <li>The provided name is too long.</li> * <li>The player is not online.</li> * </ul> */ void addUser(String name) throws Exception; /** * Removes a player as a user from this machine, by username. * <p/> * Unlike when adding players, the player does <em>not</em> have to be * online to be removed from the list. * * @param name the name of the player to remove. * @return whether the player was removed from the user list. */ boolean removeUser(String name); }
mit
Elecs-Mods/RFTools
src/main/java/mcjty/rftools/blocks/logic/RedstoneReceiverBlock.java
2405
package mcjty.rftools.blocks.logic; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import mcjty.rftools.RFTools; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; import org.lwjgl.input.Keyboard; import java.util.List; public class RedstoneReceiverBlock extends LogicSlabBlock { public RedstoneReceiverBlock() { super(Material.iron, "redstoneReceiverBlock", RedstoneReceiverTileEntity.class); setCreativeTab(RFTools.tabRfTools); } @SideOnly(Side.CLIENT) @Override public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean whatIsThis) { super.addInformation(itemStack, player, list, whatIsThis); NBTTagCompound tagCompound = itemStack.getTagCompound(); if (tagCompound != null) { int channel = tagCompound.getInteger("channel"); list.add(EnumChatFormatting.GREEN + "Channel: " + channel); } if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) { list.add(EnumChatFormatting.WHITE + "This logic block sends redstone signals from"); list.add(EnumChatFormatting.WHITE + "a linked transmitter. Right click on a transmitter"); list.add(EnumChatFormatting.WHITE + "(or other receiver) to link"); } else { list.add(EnumChatFormatting.WHITE + RFTools.SHIFT_MESSAGE); } } @SideOnly(Side.CLIENT) @Override public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { super.getWailaBody(itemStack, currenttip, accessor, config); NBTTagCompound tagCompound = accessor.getNBTData(); if (tagCompound != null) { int channel = tagCompound.getInteger("channel"); currenttip.add(EnumChatFormatting.GREEN + "Channel: " + channel); } return currenttip; } @Override public int getGuiID() { return -1; } @Override public String getIdentifyingIconName() { return "machineRedstoneReceiver"; } }
mit
NorthFacing/Mapper
base/src/test/java/tk/mybatis/mapper/typehandler/User2.java
987
package tk.mybatis.mapper.typehandler; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; /** * @author liuzh */ @Table(name = "user") public class User2 implements Serializable { private static final long serialVersionUID = 1L; @Id private Integer id; private String name; @Column private Address address; private StateEnum state; public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public StateEnum getState() { return state; } public void setState(StateEnum state) { this.state = state; } }
mit
navalev/azure-sdk-for-java
sdk/network/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/network/v2019_04_01/IpFlowProtocol.java
1258
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_04_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for IpFlowProtocol. */ public final class IpFlowProtocol extends ExpandableStringEnum<IpFlowProtocol> { /** Static value TCP for IpFlowProtocol. */ public static final IpFlowProtocol TCP = fromString("TCP"); /** Static value UDP for IpFlowProtocol. */ public static final IpFlowProtocol UDP = fromString("UDP"); /** * Creates or finds a IpFlowProtocol from its string representation. * @param name a name to look for * @return the corresponding IpFlowProtocol */ @JsonCreator public static IpFlowProtocol fromString(String name) { return fromString(name, IpFlowProtocol.class); } /** * @return known IpFlowProtocol values */ public static Collection<IpFlowProtocol> values() { return values(IpFlowProtocol.class); } }
mit
eriqadams/computer-graphics
lib/lwjgl-2.9.1/lwjgl-source-2.9.1/src/generated/org/lwjgl/opengl/GL43.java
50945
/* MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengl; import org.lwjgl.*; import java.nio.*; public final class GL43 { /** * No. of supported Shading Language Versions. Accepted by the &lt;pname&gt; parameter of GetIntegerv. */ public static final int GL_NUM_SHADING_LANGUAGE_VERSIONS = 0x82E9; /** * Vertex attrib array has unconverted doubles. Accepted by the &lt;pname&gt; parameter of GetVertexAttribiv. */ public static final int GL_VERTEX_ATTRIB_ARRAY_LONG = 0x874E; /** * Accepted by the &lt;internalformat&gt; parameter of CompressedTexImage2D */ public static final int GL_COMPRESSED_RGB8_ETC2 = 0x9274, GL_COMPRESSED_SRGB8_ETC2 = 0x9275, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277, GL_COMPRESSED_RGBA8_ETC2_EAC = 0x9278, GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279, GL_COMPRESSED_R11_EAC = 0x9270, GL_COMPRESSED_SIGNED_R11_EAC = 0x9271, GL_COMPRESSED_RG11_EAC = 0x9272, GL_COMPRESSED_SIGNED_RG11_EAC = 0x9273; /** * Accepted by the &lt;target&gt; parameter of Enable and Disable: */ public static final int GL_PRIMITIVE_RESTART_FIXED_INDEX = 0x8D69; /** * Accepted by the &lt;target&gt; parameter of BeginQuery, EndQuery, * GetQueryIndexediv and GetQueryiv: */ public static final int GL_ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8D6A; /** * Accepted by the &lt;value&gt; parameter of the GetInteger* functions: */ public static final int GL_MAX_ELEMENT_INDEX = 0x8D6B; /** * Accepted by the &lt;type&gt; parameter of CreateShader and returned in the * &lt;params&gt; parameter by GetShaderiv: */ public static final int GL_COMPUTE_SHADER = 0x91B9; /** * Accepted by the &lt;pname&gt; parameter of GetIntegerv, GetBooleanv, GetFloatv, * GetDoublev and GetInteger64v: */ public static final int GL_MAX_COMPUTE_UNIFORM_BLOCKS = 0x91BB, GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS = 0x91BC, GL_MAX_COMPUTE_IMAGE_UNIFORMS = 0x91BD, GL_MAX_COMPUTE_SHARED_MEMORY_SIZE = 0x8262, GL_MAX_COMPUTE_UNIFORM_COMPONENTS = 0x8263, GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS = 0x8264, GL_MAX_COMPUTE_ATOMIC_COUNTERS = 0x8265, GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS = 0x8266, GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS = 0x90EB; /** * Accepted by the &lt;pname&gt; parameter of GetIntegeri_v, GetBooleani_v, * GetFloati_v, GetDoublei_v and GetInteger64i_v: */ public static final int GL_MAX_COMPUTE_WORK_GROUP_COUNT = 0x91BE, GL_MAX_COMPUTE_WORK_GROUP_SIZE = 0x91BF; /** * Accepted by the &lt;pname&gt; parameter of GetProgramiv: */ public static final int GL_COMPUTE_WORK_GROUP_SIZE = 0x8267; /** * Accepted by the &lt;pname&gt; parameter of GetActiveUniformBlockiv: */ public static final int GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER = 0x90EC; /** * Accepted by the &lt;pname&gt; parameter of GetActiveAtomicCounterBufferiv: */ public static final int GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER = 0x90ED; /** * Accepted by the &lt;target&gt; parameters of BindBuffer, BufferData, * BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, and * GetBufferPointerv: */ public static final int GL_DISPATCH_INDIRECT_BUFFER = 0x90EE; /** * Accepted by the &lt;value&gt; parameter of GetIntegerv, GetBooleanv, * GetInteger64v, GetFloatv, and GetDoublev: */ public static final int GL_DISPATCH_INDIRECT_BUFFER_BINDING = 0x90EF; /** * Accepted by the &lt;stages&gt; parameter of UseProgramStages: */ public static final int GL_COMPUTE_SHADER_BIT = 0x20; /** * Tokens accepted by the &lt;target&gt; parameters of Enable, Disable, and * IsEnabled: */ public static final int GL_DEBUG_OUTPUT = 0x92E0, GL_DEBUG_OUTPUT_SYNCHRONOUS = 0x8242; /** * Returned by GetIntegerv when &lt;pname&gt; is CONTEXT_FLAGS: */ public static final int GL_CONTEXT_FLAG_DEBUG_BIT = 0x2; /** * Tokens accepted by the &lt;value&gt; parameters of GetBooleanv, GetIntegerv, * GetFloatv, GetDoublev and GetInteger64v: */ public static final int GL_MAX_DEBUG_MESSAGE_LENGTH = 0x9143, GL_MAX_DEBUG_LOGGED_MESSAGES = 0x9144, GL_DEBUG_LOGGED_MESSAGES = 0x9145, GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 0x8243, GL_MAX_DEBUG_GROUP_STACK_DEPTH = 0x826C, GL_DEBUG_GROUP_STACK_DEPTH = 0x826D, GL_MAX_LABEL_LENGTH = 0x82E8; /** * Tokens accepted by the &lt;pname&gt; parameter of GetPointerv: */ public static final int GL_DEBUG_CALLBACK_FUNCTION = 0x8244, GL_DEBUG_CALLBACK_USER_PARAM = 0x8245; /** * Tokens accepted or provided by the &lt;source&gt; parameters of * DebugMessageControl, DebugMessageInsert and DEBUGPROC, and the &lt;sources&gt; * parameter of GetDebugMessageLog: */ public static final int GL_DEBUG_SOURCE_API = 0x8246, GL_DEBUG_SOURCE_WINDOW_SYSTEM = 0x8247, GL_DEBUG_SOURCE_SHADER_COMPILER = 0x8248, GL_DEBUG_SOURCE_THIRD_PARTY = 0x8249, GL_DEBUG_SOURCE_APPLICATION = 0x824A, GL_DEBUG_SOURCE_OTHER = 0x824B; /** * Tokens accepted or provided by the &lt;type&gt; parameters of * DebugMessageControl, DebugMessageInsert and DEBUGPROC, and the &lt;types&gt; * parameter of GetDebugMessageLog: */ public static final int GL_DEBUG_TYPE_ERROR = 0x824C, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR = 0x824D, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR = 0x824E, GL_DEBUG_TYPE_PORTABILITY = 0x824F, GL_DEBUG_TYPE_PERFORMANCE = 0x8250, GL_DEBUG_TYPE_OTHER = 0x8251, GL_DEBUG_TYPE_MARKER = 0x8268; /** * Tokens accepted or provided by the &lt;type&gt; parameters of * DebugMessageControl and DEBUGPROC, and the &lt;types&gt; parameter of * GetDebugMessageLog: */ public static final int GL_DEBUG_TYPE_PUSH_GROUP = 0x8269, GL_DEBUG_TYPE_POP_GROUP = 0x826A; /** * Tokens accepted or provided by the &lt;severity&gt; parameters of * DebugMessageControl, DebugMessageInsert and DEBUGPROC callback functions, * and the &lt;severities&gt; parameter of GetDebugMessageLog: */ public static final int GL_DEBUG_SEVERITY_HIGH = 0x9146, GL_DEBUG_SEVERITY_MEDIUM = 0x9147, GL_DEBUG_SEVERITY_LOW = 0x9148, GL_DEBUG_SEVERITY_NOTIFICATION = 0x826B; /** * Returned by GetError: */ public static final int GL_STACK_UNDERFLOW = 0x504, GL_STACK_OVERFLOW = 0x503; /** * Tokens accepted or provided by the &lt;identifier&gt; parameters of * ObjectLabel and GetObjectLabel: */ public static final int GL_BUFFER = 0x82E0, GL_SHADER = 0x82E1, GL_PROGRAM = 0x82E2, GL_QUERY = 0x82E3, GL_PROGRAM_PIPELINE = 0x82E4, GL_SAMPLER = 0x82E6, GL_DISPLAY_LIST = 0x82E7; /** * Accepted by the &lt;pname&gt; parameter of GetBooleanv, GetIntegerv, * GetFloatv, GetDoublev, and GetInteger64v: */ public static final int GL_MAX_UNIFORM_LOCATIONS = 0x826E; /** * Accepted by the &lt;pname&gt; parameter of FramebufferParameteri, * GetFramebufferParameteriv, NamedFramebufferParameteriEXT, and * GetNamedFramebufferParameterivEXT: */ public static final int GL_FRAMEBUFFER_DEFAULT_WIDTH = 0x9310, GL_FRAMEBUFFER_DEFAULT_HEIGHT = 0x9311, GL_FRAMEBUFFER_DEFAULT_LAYERS = 0x9312, GL_FRAMEBUFFER_DEFAULT_SAMPLES = 0x9313, GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS = 0x9314; /** * Accepted by the &lt;pname&gt; parameter of GetIntegerv, GetBooleanv, * GetInteger64v, GetFloatv, and GetDoublev: */ public static final int GL_MAX_FRAMEBUFFER_WIDTH = 0x9315, GL_MAX_FRAMEBUFFER_HEIGHT = 0x9316, GL_MAX_FRAMEBUFFER_LAYERS = 0x9317, GL_MAX_FRAMEBUFFER_SAMPLES = 0x9318; /** * Accepted by the &lt;target&gt; parameter of GetInternalformativ * and GetInternalformati64v: */ public static final int GL_TEXTURE_1D = 0xDE0, GL_TEXTURE_1D_ARRAY = 0x8C18, GL_TEXTURE_2D = 0xDE1, GL_TEXTURE_2D_ARRAY = 0x8C1A, GL_TEXTURE_3D = 0x806F, GL_TEXTURE_CUBE_MAP = 0x8513, GL_TEXTURE_CUBE_MAP_ARRAY = 0x9009, GL_TEXTURE_RECTANGLE = 0x84F5, GL_TEXTURE_BUFFER = 0x8C2A, GL_RENDERBUFFER = 0x8D41, GL_TEXTURE_2D_MULTISAMPLE = 0x9100, GL_TEXTURE_2D_MULTISAMPLE_ARRAY = 0x9102; /** * Accepted by the &lt;pname&gt; parameter of GetInternalformativ * and GetInternalformati64v: */ public static final int GL_SAMPLES = 0x80A9, GL_NUM_SAMPLE_COUNTS = 0x9380, GL_INTERNALFORMAT_SUPPORTED = 0x826F, GL_INTERNALFORMAT_PREFERRED = 0x8270, GL_INTERNALFORMAT_RED_SIZE = 0x8271, GL_INTERNALFORMAT_GREEN_SIZE = 0x8272, GL_INTERNALFORMAT_BLUE_SIZE = 0x8273, GL_INTERNALFORMAT_ALPHA_SIZE = 0x8274, GL_INTERNALFORMAT_DEPTH_SIZE = 0x8275, GL_INTERNALFORMAT_STENCIL_SIZE = 0x8276, GL_INTERNALFORMAT_SHARED_SIZE = 0x8277, GL_INTERNALFORMAT_RED_TYPE = 0x8278, GL_INTERNALFORMAT_GREEN_TYPE = 0x8279, GL_INTERNALFORMAT_BLUE_TYPE = 0x827A, GL_INTERNALFORMAT_ALPHA_TYPE = 0x827B, GL_INTERNALFORMAT_DEPTH_TYPE = 0x827C, GL_INTERNALFORMAT_STENCIL_TYPE = 0x827D, GL_MAX_WIDTH = 0x827E, GL_MAX_HEIGHT = 0x827F, GL_MAX_DEPTH = 0x8280, GL_MAX_LAYERS = 0x8281, GL_MAX_COMBINED_DIMENSIONS = 0x8282, GL_COLOR_COMPONENTS = 0x8283, GL_DEPTH_COMPONENTS = 0x8284, GL_STENCIL_COMPONENTS = 0x8285, GL_COLOR_RENDERABLE = 0x8286, GL_DEPTH_RENDERABLE = 0x8287, GL_STENCIL_RENDERABLE = 0x8288, GL_FRAMEBUFFER_RENDERABLE = 0x8289, GL_FRAMEBUFFER_RENDERABLE_LAYERED = 0x828A, GL_FRAMEBUFFER_BLEND = 0x828B, GL_READ_PIXELS = 0x828C, GL_READ_PIXELS_FORMAT = 0x828D, GL_READ_PIXELS_TYPE = 0x828E, GL_TEXTURE_IMAGE_FORMAT = 0x828F, GL_TEXTURE_IMAGE_TYPE = 0x8290, GL_GET_TEXTURE_IMAGE_FORMAT = 0x8291, GL_GET_TEXTURE_IMAGE_TYPE = 0x8292, GL_MIPMAP = 0x8293, GL_MANUAL_GENERATE_MIPMAP = 0x8294, GL_AUTO_GENERATE_MIPMAP = 0x8295, GL_COLOR_ENCODING = 0x8296, GL_SRGB_READ = 0x8297, GL_SRGB_WRITE = 0x8298, GL_SRGB_DECODE_ARB = 0x8299, GL_FILTER = 0x829A, GL_VERTEX_TEXTURE = 0x829B, GL_TESS_CONTROL_TEXTURE = 0x829C, GL_TESS_EVALUATION_TEXTURE = 0x829D, GL_GEOMETRY_TEXTURE = 0x829E, GL_FRAGMENT_TEXTURE = 0x829F, GL_COMPUTE_TEXTURE = 0x82A0, GL_TEXTURE_SHADOW = 0x82A1, GL_TEXTURE_GATHER = 0x82A2, GL_TEXTURE_GATHER_SHADOW = 0x82A3, GL_SHADER_IMAGE_LOAD = 0x82A4, GL_SHADER_IMAGE_STORE = 0x82A5, GL_SHADER_IMAGE_ATOMIC = 0x82A6, GL_IMAGE_TEXEL_SIZE = 0x82A7, GL_IMAGE_COMPATIBILITY_CLASS = 0x82A8, GL_IMAGE_PIXEL_FORMAT = 0x82A9, GL_IMAGE_PIXEL_TYPE = 0x82AA, GL_IMAGE_FORMAT_COMPATIBILITY_TYPE = 0x90C7, GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST = 0x82AC, GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST = 0x82AD, GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE = 0x82AE, GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE = 0x82AF, GL_TEXTURE_COMPRESSED = 0x86A1, GL_TEXTURE_COMPRESSED_BLOCK_WIDTH = 0x82B1, GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT = 0x82B2, GL_TEXTURE_COMPRESSED_BLOCK_SIZE = 0x82B3, GL_CLEAR_BUFFER = 0x82B4, GL_TEXTURE_VIEW = 0x82B5, GL_VIEW_COMPATIBILITY_CLASS = 0x82B6; /** * Returned as possible responses for various &lt;pname&gt; queries * to GetInternalformativ and GetInternalformati64v */ public static final int GL_FULL_SUPPORT = 0x82B7, GL_CAVEAT_SUPPORT = 0x82B8, GL_IMAGE_CLASS_4_X_32 = 0x82B9, GL_IMAGE_CLASS_2_X_32 = 0x82BA, GL_IMAGE_CLASS_1_X_32 = 0x82BB, GL_IMAGE_CLASS_4_X_16 = 0x82BC, GL_IMAGE_CLASS_2_X_16 = 0x82BD, GL_IMAGE_CLASS_1_X_16 = 0x82BE, GL_IMAGE_CLASS_4_X_8 = 0x82BF, GL_IMAGE_CLASS_2_X_8 = 0x82C0, GL_IMAGE_CLASS_1_X_8 = 0x82C1, GL_IMAGE_CLASS_11_11_10 = 0x82C2, GL_IMAGE_CLASS_10_10_10_2 = 0x82C3, GL_VIEW_CLASS_128_BITS = 0x82C4, GL_VIEW_CLASS_96_BITS = 0x82C5, GL_VIEW_CLASS_64_BITS = 0x82C6, GL_VIEW_CLASS_48_BITS = 0x82C7, GL_VIEW_CLASS_32_BITS = 0x82C8, GL_VIEW_CLASS_24_BITS = 0x82C9, GL_VIEW_CLASS_16_BITS = 0x82CA, GL_VIEW_CLASS_8_BITS = 0x82CB, GL_VIEW_CLASS_S3TC_DXT1_RGB = 0x82CC, GL_VIEW_CLASS_S3TC_DXT1_RGBA = 0x82CD, GL_VIEW_CLASS_S3TC_DXT3_RGBA = 0x82CE, GL_VIEW_CLASS_S3TC_DXT5_RGBA = 0x82CF, GL_VIEW_CLASS_RGTC1_RED = 0x82D0, GL_VIEW_CLASS_RGTC2_RG = 0x82D1, GL_VIEW_CLASS_BPTC_UNORM = 0x82D2, GL_VIEW_CLASS_BPTC_FLOAT = 0x82D3; /** * Accepted by the &lt;programInterface&gt; parameter of GetProgramInterfaceiv, * GetProgramResourceIndex, GetProgramResourceName, GetProgramResourceiv, * GetProgramResourceLocation, and GetProgramResourceLocationIndex: */ public static final int GL_UNIFORM = 0x92E1, GL_UNIFORM_BLOCK = 0x92E2, GL_PROGRAM_INPUT = 0x92E3, GL_PROGRAM_OUTPUT = 0x92E4, GL_BUFFER_VARIABLE = 0x92E5, GL_SHADER_STORAGE_BLOCK = 0x92E6, GL_VERTEX_SUBROUTINE = 0x92E8, GL_TESS_CONTROL_SUBROUTINE = 0x92E9, GL_TESS_EVALUATION_SUBROUTINE = 0x92EA, GL_GEOMETRY_SUBROUTINE = 0x92EB, GL_FRAGMENT_SUBROUTINE = 0x92EC, GL_COMPUTE_SUBROUTINE = 0x92ED, GL_VERTEX_SUBROUTINE_UNIFORM = 0x92EE, GL_TESS_CONTROL_SUBROUTINE_UNIFORM = 0x92EF, GL_TESS_EVALUATION_SUBROUTINE_UNIFORM = 0x92F0, GL_GEOMETRY_SUBROUTINE_UNIFORM = 0x92F1, GL_FRAGMENT_SUBROUTINE_UNIFORM = 0x92F2, GL_COMPUTE_SUBROUTINE_UNIFORM = 0x92F3, GL_TRANSFORM_FEEDBACK_VARYING = 0x92F4; /** * Accepted by the &lt;pname&gt; parameter of GetProgramInterfaceiv: */ public static final int GL_ACTIVE_RESOURCES = 0x92F5, GL_MAX_NAME_LENGTH = 0x92F6, GL_MAX_NUM_ACTIVE_VARIABLES = 0x92F7, GL_MAX_NUM_COMPATIBLE_SUBROUTINES = 0x92F8; /** * Accepted in the &lt;props&gt; array of GetProgramResourceiv: */ public static final int GL_NAME_LENGTH = 0x92F9, GL_TYPE = 0x92FA, GL_ARRAY_SIZE = 0x92FB, GL_OFFSET = 0x92FC, GL_BLOCK_INDEX = 0x92FD, GL_ARRAY_STRIDE = 0x92FE, GL_MATRIX_STRIDE = 0x92FF, GL_IS_ROW_MAJOR = 0x9300, GL_ATOMIC_COUNTER_BUFFER_INDEX = 0x9301, GL_BUFFER_BINDING = 0x9302, GL_BUFFER_DATA_SIZE = 0x9303, GL_NUM_ACTIVE_VARIABLES = 0x9304, GL_ACTIVE_VARIABLES = 0x9305, GL_REFERENCED_BY_VERTEX_SHADER = 0x9306, GL_REFERENCED_BY_TESS_CONTROL_SHADER = 0x9307, GL_REFERENCED_BY_TESS_EVALUATION_SHADER = 0x9308, GL_REFERENCED_BY_GEOMETRY_SHADER = 0x9309, GL_REFERENCED_BY_FRAGMENT_SHADER = 0x930A, GL_REFERENCED_BY_COMPUTE_SHADER = 0x930B, GL_TOP_LEVEL_ARRAY_SIZE = 0x930C, GL_TOP_LEVEL_ARRAY_STRIDE = 0x930D, GL_LOCATION = 0x930E, GL_LOCATION_INDEX = 0x930F, GL_IS_PER_PATCH = 0x92E7; /** * Accepted by the &lt;target&gt; parameters of BindBuffer, BufferData, * BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, and * GetBufferPointerv: */ public static final int GL_SHADER_STORAGE_BUFFER = 0x90D2; /** * Accepted by the &lt;pname&gt; parameter of GetIntegerv, GetIntegeri_v, * GetBooleanv, GetInteger64v, GetFloatv, GetDoublev, GetBooleani_v, * GetIntegeri_v, GetFloati_v, GetDoublei_v, and GetInteger64i_v: */ public static final int GL_SHADER_STORAGE_BUFFER_BINDING = 0x90D3; /** * Accepted by the &lt;pname&gt; parameter of GetIntegeri_v, GetBooleani_v, * GetIntegeri_v, GetFloati_v, GetDoublei_v, and GetInteger64i_v: */ public static final int GL_SHADER_STORAGE_BUFFER_START = 0x90D4, GL_SHADER_STORAGE_BUFFER_SIZE = 0x90D5; /** * Accepted by the &lt;pname&gt; parameter of GetIntegerv, GetBooleanv, * GetInteger64v, GetFloatv, and GetDoublev: */ public static final int GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS = 0x90D6, GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS = 0x90D7, GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS = 0x90D8, GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS = 0x90D9, GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS = 0x90DA, GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS = 0x90DB, GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS = 0x90DC, GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS = 0x90DD, GL_MAX_SHADER_STORAGE_BLOCK_SIZE = 0x90DE, GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT = 0x90DF; /** * Accepted in the &lt;barriers&gt; bitfield in glMemoryBarrier: */ public static final int GL_SHADER_STORAGE_BARRIER_BIT = 0x2000; /** * Alias for the existing token * MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS: */ public static final int GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES = 0x8F39; /** * Accepted by the &lt;pname&gt; parameter of TexParameter* and GetTexParameter*: */ public static final int GL_DEPTH_STENCIL_TEXTURE_MODE = 0x90EA; /** * Accepted by the &lt;pname&gt; parameter of GetTexLevelParameter: */ public static final int GL_TEXTURE_BUFFER_OFFSET = 0x919D, GL_TEXTURE_BUFFER_SIZE = 0x919E; /** * Accepted by the &lt;pname&gt; parameter of GetBooleanv, GetIntegerv, GetFloatv, * and GetDoublev: */ public static final int GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT = 0x919F; /** * Accepted by the &lt;pname&gt; parameters of GetTexParameterfv and * GetTexParameteriv: */ public static final int GL_TEXTURE_VIEW_MIN_LEVEL = 0x82DB, GL_TEXTURE_VIEW_NUM_LEVELS = 0x82DC, GL_TEXTURE_VIEW_MIN_LAYER = 0x82DD, GL_TEXTURE_VIEW_NUM_LAYERS = 0x82DE, GL_TEXTURE_IMMUTABLE_LEVELS = 0x82DF; /** * Accepted by the &lt;pname&gt; parameter of GetVertexAttrib*v: */ public static final int GL_VERTEX_ATTRIB_BINDING = 0x82D4, GL_VERTEX_ATTRIB_RELATIVE_OFFSET = 0x82D5; /** * Accepted by the &lt;target&gt; parameter of GetBooleani_v, GetIntegeri_v, * GetFloati_v, GetDoublei_v, and GetInteger64i_v: */ public static final int GL_VERTEX_BINDING_DIVISOR = 0x82D6, GL_VERTEX_BINDING_OFFSET = 0x82D7, GL_VERTEX_BINDING_STRIDE = 0x82D8; /** * Accepted by the &lt;pname&gt; parameter of GetIntegerv, ... */ public static final int GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET = 0x82D9, GL_MAX_VERTEX_ATTRIB_BINDINGS = 0x82DA; private GL43() {} public static void glClearBufferData(int target, int internalformat, int format, int type, ByteBuffer data) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glClearBufferData; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(data, 1); nglClearBufferData(target, internalformat, format, type, MemoryUtil.getAddress(data), function_pointer); } static native void nglClearBufferData(int target, int internalformat, int format, int type, long data, long function_pointer); public static void glClearBufferSubData(int target, int internalformat, long offset, int format, int type, ByteBuffer data) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glClearBufferSubData; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(data); nglClearBufferSubData(target, internalformat, offset, data.remaining(), format, type, MemoryUtil.getAddress(data), function_pointer); } static native void nglClearBufferSubData(int target, int internalformat, long offset, long data_size, int format, int type, long data, long function_pointer); public static void glDispatchCompute(int num_groups_x, int num_groups_y, int num_groups_z) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glDispatchCompute; BufferChecks.checkFunctionAddress(function_pointer); nglDispatchCompute(num_groups_x, num_groups_y, num_groups_z, function_pointer); } static native void nglDispatchCompute(int num_groups_x, int num_groups_y, int num_groups_z, long function_pointer); public static void glDispatchComputeIndirect(long indirect) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glDispatchComputeIndirect; BufferChecks.checkFunctionAddress(function_pointer); nglDispatchComputeIndirect(indirect, function_pointer); } static native void nglDispatchComputeIndirect(long indirect, long function_pointer); public static void glCopyImageSubData(int srcName, int srcTarget, int srcLevel, int srcX, int srcY, int srcZ, int dstName, int dstTarget, int dstLevel, int dstX, int dstY, int dstZ, int srcWidth, int srcHeight, int srcDepth) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glCopyImageSubData; BufferChecks.checkFunctionAddress(function_pointer); nglCopyImageSubData(srcName, srcTarget, srcLevel, srcX, srcY, srcZ, dstName, dstTarget, dstLevel, dstX, dstY, dstZ, srcWidth, srcHeight, srcDepth, function_pointer); } static native void nglCopyImageSubData(int srcName, int srcTarget, int srcLevel, int srcX, int srcY, int srcZ, int dstName, int dstTarget, int dstLevel, int dstX, int dstY, int dstZ, int srcWidth, int srcHeight, int srcDepth, long function_pointer); public static void glDebugMessageControl(int source, int type, int severity, IntBuffer ids, boolean enabled) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glDebugMessageControl; BufferChecks.checkFunctionAddress(function_pointer); if (ids != null) BufferChecks.checkDirect(ids); nglDebugMessageControl(source, type, severity, (ids == null ? 0 : ids.remaining()), MemoryUtil.getAddressSafe(ids), enabled, function_pointer); } static native void nglDebugMessageControl(int source, int type, int severity, int ids_count, long ids, boolean enabled, long function_pointer); public static void glDebugMessageInsert(int source, int type, int id, int severity, ByteBuffer buf) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glDebugMessageInsert; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(buf); nglDebugMessageInsert(source, type, id, severity, buf.remaining(), MemoryUtil.getAddress(buf), function_pointer); } static native void nglDebugMessageInsert(int source, int type, int id, int severity, int buf_length, long buf, long function_pointer); /** Overloads glDebugMessageInsert. */ public static void glDebugMessageInsert(int source, int type, int id, int severity, CharSequence buf) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glDebugMessageInsert; BufferChecks.checkFunctionAddress(function_pointer); nglDebugMessageInsert(source, type, id, severity, buf.length(), APIUtil.getBuffer(caps, buf), function_pointer); } /** * The {@code KHRDebugCallback.Handler} implementation passed to this method will be used for * KHR_debug messages. If callback is null, any previously registered handler for the current * thread will be unregistered and stop receiving messages. * <p> * @param callback the callback function to use */ public static void glDebugMessageCallback(KHRDebugCallback callback) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glDebugMessageCallback; BufferChecks.checkFunctionAddress(function_pointer); long userParam = callback == null ? 0 : CallbackUtil.createGlobalRef(callback.getHandler()); CallbackUtil.registerContextCallbackKHR(userParam); nglDebugMessageCallback(callback == null ? 0 : callback.getPointer(), userParam, function_pointer); } static native void nglDebugMessageCallback(long callback, long userParam, long function_pointer); public static int glGetDebugMessageLog(int count, IntBuffer sources, IntBuffer types, IntBuffer ids, IntBuffer severities, IntBuffer lengths, ByteBuffer messageLog) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetDebugMessageLog; BufferChecks.checkFunctionAddress(function_pointer); if (sources != null) BufferChecks.checkBuffer(sources, count); if (types != null) BufferChecks.checkBuffer(types, count); if (ids != null) BufferChecks.checkBuffer(ids, count); if (severities != null) BufferChecks.checkBuffer(severities, count); if (lengths != null) BufferChecks.checkBuffer(lengths, count); if (messageLog != null) BufferChecks.checkDirect(messageLog); int __result = nglGetDebugMessageLog(count, (messageLog == null ? 0 : messageLog.remaining()), MemoryUtil.getAddressSafe(sources), MemoryUtil.getAddressSafe(types), MemoryUtil.getAddressSafe(ids), MemoryUtil.getAddressSafe(severities), MemoryUtil.getAddressSafe(lengths), MemoryUtil.getAddressSafe(messageLog), function_pointer); return __result; } static native int nglGetDebugMessageLog(int count, int messageLog_bufsize, long sources, long types, long ids, long severities, long lengths, long messageLog, long function_pointer); public static void glPushDebugGroup(int source, int id, ByteBuffer message) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glPushDebugGroup; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(message); nglPushDebugGroup(source, id, message.remaining(), MemoryUtil.getAddress(message), function_pointer); } static native void nglPushDebugGroup(int source, int id, int message_length, long message, long function_pointer); /** Overloads glPushDebugGroup. */ public static void glPushDebugGroup(int source, int id, CharSequence message) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glPushDebugGroup; BufferChecks.checkFunctionAddress(function_pointer); nglPushDebugGroup(source, id, message.length(), APIUtil.getBuffer(caps, message), function_pointer); } public static void glPopDebugGroup() { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glPopDebugGroup; BufferChecks.checkFunctionAddress(function_pointer); nglPopDebugGroup(function_pointer); } static native void nglPopDebugGroup(long function_pointer); public static void glObjectLabel(int identifier, int name, ByteBuffer label) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glObjectLabel; BufferChecks.checkFunctionAddress(function_pointer); if (label != null) BufferChecks.checkDirect(label); nglObjectLabel(identifier, name, (label == null ? 0 : label.remaining()), MemoryUtil.getAddressSafe(label), function_pointer); } static native void nglObjectLabel(int identifier, int name, int label_length, long label, long function_pointer); /** Overloads glObjectLabel. */ public static void glObjectLabel(int identifier, int name, CharSequence label) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glObjectLabel; BufferChecks.checkFunctionAddress(function_pointer); nglObjectLabel(identifier, name, label.length(), APIUtil.getBuffer(caps, label), function_pointer); } public static void glGetObjectLabel(int identifier, int name, IntBuffer length, ByteBuffer label) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetObjectLabel; BufferChecks.checkFunctionAddress(function_pointer); if (length != null) BufferChecks.checkBuffer(length, 1); BufferChecks.checkDirect(label); nglGetObjectLabel(identifier, name, label.remaining(), MemoryUtil.getAddressSafe(length), MemoryUtil.getAddress(label), function_pointer); } static native void nglGetObjectLabel(int identifier, int name, int label_bufSize, long length, long label, long function_pointer); /** Overloads glGetObjectLabel. */ public static String glGetObjectLabel(int identifier, int name, int bufSize) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetObjectLabel; BufferChecks.checkFunctionAddress(function_pointer); IntBuffer label_length = APIUtil.getLengths(caps); ByteBuffer label = APIUtil.getBufferByte(caps, bufSize); nglGetObjectLabel(identifier, name, bufSize, MemoryUtil.getAddress0(label_length), MemoryUtil.getAddress(label), function_pointer); label.limit(label_length.get(0)); return APIUtil.getString(caps, label); } public static void glObjectPtrLabel(PointerWrapper ptr, ByteBuffer label) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glObjectPtrLabel; BufferChecks.checkFunctionAddress(function_pointer); if (label != null) BufferChecks.checkDirect(label); nglObjectPtrLabel(ptr.getPointer(), (label == null ? 0 : label.remaining()), MemoryUtil.getAddressSafe(label), function_pointer); } static native void nglObjectPtrLabel(long ptr, int label_length, long label, long function_pointer); /** Overloads glObjectPtrLabel. */ public static void glObjectPtrLabel(PointerWrapper ptr, CharSequence label) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glObjectPtrLabel; BufferChecks.checkFunctionAddress(function_pointer); nglObjectPtrLabel(ptr.getPointer(), label.length(), APIUtil.getBuffer(caps, label), function_pointer); } public static void glGetObjectPtrLabel(PointerWrapper ptr, IntBuffer length, ByteBuffer label) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetObjectPtrLabel; BufferChecks.checkFunctionAddress(function_pointer); if (length != null) BufferChecks.checkBuffer(length, 1); BufferChecks.checkDirect(label); nglGetObjectPtrLabel(ptr.getPointer(), label.remaining(), MemoryUtil.getAddressSafe(length), MemoryUtil.getAddress(label), function_pointer); } static native void nglGetObjectPtrLabel(long ptr, int label_bufSize, long length, long label, long function_pointer); /** Overloads glGetObjectPtrLabel. */ public static String glGetObjectPtrLabel(PointerWrapper ptr, int bufSize) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetObjectPtrLabel; BufferChecks.checkFunctionAddress(function_pointer); IntBuffer label_length = APIUtil.getLengths(caps); ByteBuffer label = APIUtil.getBufferByte(caps, bufSize); nglGetObjectPtrLabel(ptr.getPointer(), bufSize, MemoryUtil.getAddress0(label_length), MemoryUtil.getAddress(label), function_pointer); label.limit(label_length.get(0)); return APIUtil.getString(caps, label); } public static void glFramebufferParameteri(int target, int pname, int param) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glFramebufferParameteri; BufferChecks.checkFunctionAddress(function_pointer); nglFramebufferParameteri(target, pname, param, function_pointer); } static native void nglFramebufferParameteri(int target, int pname, int param, long function_pointer); public static void glGetFramebufferParameter(int target, int pname, IntBuffer params) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetFramebufferParameteriv; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(params, 1); nglGetFramebufferParameteriv(target, pname, MemoryUtil.getAddress(params), function_pointer); } static native void nglGetFramebufferParameteriv(int target, int pname, long params, long function_pointer); /** Overloads glGetFramebufferParameteriv. */ public static int glGetFramebufferParameteri(int target, int pname) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetFramebufferParameteriv; BufferChecks.checkFunctionAddress(function_pointer); IntBuffer params = APIUtil.getBufferInt(caps); nglGetFramebufferParameteriv(target, pname, MemoryUtil.getAddress(params), function_pointer); return params.get(0); } public static void glGetInternalformat(int target, int internalformat, int pname, LongBuffer params) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetInternalformati64v; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(params); nglGetInternalformati64v(target, internalformat, pname, params.remaining(), MemoryUtil.getAddress(params), function_pointer); } static native void nglGetInternalformati64v(int target, int internalformat, int pname, int params_bufSize, long params, long function_pointer); /** Overloads glGetInternalformati64v. */ public static long glGetInternalformati64(int target, int internalformat, int pname) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetInternalformati64v; BufferChecks.checkFunctionAddress(function_pointer); LongBuffer params = APIUtil.getBufferLong(caps); nglGetInternalformati64v(target, internalformat, pname, 1, MemoryUtil.getAddress(params), function_pointer); return params.get(0); } public static void glInvalidateTexSubImage(int texture, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glInvalidateTexSubImage; BufferChecks.checkFunctionAddress(function_pointer); nglInvalidateTexSubImage(texture, level, xoffset, yoffset, zoffset, width, height, depth, function_pointer); } static native void nglInvalidateTexSubImage(int texture, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, long function_pointer); public static void glInvalidateTexImage(int texture, int level) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glInvalidateTexImage; BufferChecks.checkFunctionAddress(function_pointer); nglInvalidateTexImage(texture, level, function_pointer); } static native void nglInvalidateTexImage(int texture, int level, long function_pointer); public static void glInvalidateBufferSubData(int buffer, long offset, long length) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glInvalidateBufferSubData; BufferChecks.checkFunctionAddress(function_pointer); nglInvalidateBufferSubData(buffer, offset, length, function_pointer); } static native void nglInvalidateBufferSubData(int buffer, long offset, long length, long function_pointer); public static void glInvalidateBufferData(int buffer) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glInvalidateBufferData; BufferChecks.checkFunctionAddress(function_pointer); nglInvalidateBufferData(buffer, function_pointer); } static native void nglInvalidateBufferData(int buffer, long function_pointer); public static void glInvalidateFramebuffer(int target, IntBuffer attachments) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glInvalidateFramebuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(attachments); nglInvalidateFramebuffer(target, attachments.remaining(), MemoryUtil.getAddress(attachments), function_pointer); } static native void nglInvalidateFramebuffer(int target, int attachments_numAttachments, long attachments, long function_pointer); public static void glInvalidateSubFramebuffer(int target, IntBuffer attachments, int x, int y, int width, int height) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glInvalidateSubFramebuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(attachments); nglInvalidateSubFramebuffer(target, attachments.remaining(), MemoryUtil.getAddress(attachments), x, y, width, height, function_pointer); } static native void nglInvalidateSubFramebuffer(int target, int attachments_numAttachments, long attachments, int x, int y, int width, int height, long function_pointer); public static void glMultiDrawArraysIndirect(int mode, ByteBuffer indirect, int primcount, int stride) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMultiDrawArraysIndirect; BufferChecks.checkFunctionAddress(function_pointer); GLChecks.ensureIndirectBOdisabled(caps); BufferChecks.checkBuffer(indirect, (stride == 0 ? 4 * 4 : stride) * primcount); nglMultiDrawArraysIndirect(mode, MemoryUtil.getAddress(indirect), primcount, stride, function_pointer); } static native void nglMultiDrawArraysIndirect(int mode, long indirect, int primcount, int stride, long function_pointer); public static void glMultiDrawArraysIndirect(int mode, long indirect_buffer_offset, int primcount, int stride) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMultiDrawArraysIndirect; BufferChecks.checkFunctionAddress(function_pointer); GLChecks.ensureIndirectBOenabled(caps); nglMultiDrawArraysIndirectBO(mode, indirect_buffer_offset, primcount, stride, function_pointer); } static native void nglMultiDrawArraysIndirectBO(int mode, long indirect_buffer_offset, int primcount, int stride, long function_pointer); /** Overloads glMultiDrawArraysIndirect. */ public static void glMultiDrawArraysIndirect(int mode, IntBuffer indirect, int primcount, int stride) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMultiDrawArraysIndirect; BufferChecks.checkFunctionAddress(function_pointer); GLChecks.ensureIndirectBOdisabled(caps); BufferChecks.checkBuffer(indirect, (stride == 0 ? 4 : stride >> 2) * primcount); nglMultiDrawArraysIndirect(mode, MemoryUtil.getAddress(indirect), primcount, stride, function_pointer); } public static void glMultiDrawElementsIndirect(int mode, int type, ByteBuffer indirect, int primcount, int stride) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMultiDrawElementsIndirect; BufferChecks.checkFunctionAddress(function_pointer); GLChecks.ensureIndirectBOdisabled(caps); BufferChecks.checkBuffer(indirect, (stride == 0 ? 5 * 4 : stride) * primcount); nglMultiDrawElementsIndirect(mode, type, MemoryUtil.getAddress(indirect), primcount, stride, function_pointer); } static native void nglMultiDrawElementsIndirect(int mode, int type, long indirect, int primcount, int stride, long function_pointer); public static void glMultiDrawElementsIndirect(int mode, int type, long indirect_buffer_offset, int primcount, int stride) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMultiDrawElementsIndirect; BufferChecks.checkFunctionAddress(function_pointer); GLChecks.ensureIndirectBOenabled(caps); nglMultiDrawElementsIndirectBO(mode, type, indirect_buffer_offset, primcount, stride, function_pointer); } static native void nglMultiDrawElementsIndirectBO(int mode, int type, long indirect_buffer_offset, int primcount, int stride, long function_pointer); /** Overloads glMultiDrawElementsIndirect. */ public static void glMultiDrawElementsIndirect(int mode, int type, IntBuffer indirect, int primcount, int stride) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMultiDrawElementsIndirect; BufferChecks.checkFunctionAddress(function_pointer); GLChecks.ensureIndirectBOdisabled(caps); BufferChecks.checkBuffer(indirect, (stride == 0 ? 5 : stride >> 2) * primcount); nglMultiDrawElementsIndirect(mode, type, MemoryUtil.getAddress(indirect), primcount, stride, function_pointer); } public static void glGetProgramInterface(int program, int programInterface, int pname, IntBuffer params) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramInterfaceiv; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(params, 1); nglGetProgramInterfaceiv(program, programInterface, pname, MemoryUtil.getAddress(params), function_pointer); } static native void nglGetProgramInterfaceiv(int program, int programInterface, int pname, long params, long function_pointer); /** Overloads glGetProgramInterfaceiv. */ public static int glGetProgramInterfacei(int program, int programInterface, int pname) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramInterfaceiv; BufferChecks.checkFunctionAddress(function_pointer); IntBuffer params = APIUtil.getBufferInt(caps); nglGetProgramInterfaceiv(program, programInterface, pname, MemoryUtil.getAddress(params), function_pointer); return params.get(0); } public static int glGetProgramResourceIndex(int program, int programInterface, ByteBuffer name) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramResourceIndex; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(name); BufferChecks.checkNullTerminated(name); int __result = nglGetProgramResourceIndex(program, programInterface, MemoryUtil.getAddress(name), function_pointer); return __result; } static native int nglGetProgramResourceIndex(int program, int programInterface, long name, long function_pointer); /** Overloads glGetProgramResourceIndex. */ public static int glGetProgramResourceIndex(int program, int programInterface, CharSequence name) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramResourceIndex; BufferChecks.checkFunctionAddress(function_pointer); int __result = nglGetProgramResourceIndex(program, programInterface, APIUtil.getBufferNT(caps, name), function_pointer); return __result; } public static void glGetProgramResourceName(int program, int programInterface, int index, IntBuffer length, ByteBuffer name) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramResourceName; BufferChecks.checkFunctionAddress(function_pointer); if (length != null) BufferChecks.checkBuffer(length, 1); if (name != null) BufferChecks.checkDirect(name); nglGetProgramResourceName(program, programInterface, index, (name == null ? 0 : name.remaining()), MemoryUtil.getAddressSafe(length), MemoryUtil.getAddressSafe(name), function_pointer); } static native void nglGetProgramResourceName(int program, int programInterface, int index, int name_bufSize, long length, long name, long function_pointer); /** Overloads glGetProgramResourceName. */ public static String glGetProgramResourceName(int program, int programInterface, int index, int bufSize) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramResourceName; BufferChecks.checkFunctionAddress(function_pointer); IntBuffer name_length = APIUtil.getLengths(caps); ByteBuffer name = APIUtil.getBufferByte(caps, bufSize); nglGetProgramResourceName(program, programInterface, index, bufSize, MemoryUtil.getAddress0(name_length), MemoryUtil.getAddress(name), function_pointer); name.limit(name_length.get(0)); return APIUtil.getString(caps, name); } public static void glGetProgramResource(int program, int programInterface, int index, IntBuffer props, IntBuffer length, IntBuffer params) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramResourceiv; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(props); if (length != null) BufferChecks.checkBuffer(length, 1); BufferChecks.checkDirect(params); nglGetProgramResourceiv(program, programInterface, index, props.remaining(), MemoryUtil.getAddress(props), params.remaining(), MemoryUtil.getAddressSafe(length), MemoryUtil.getAddress(params), function_pointer); } static native void nglGetProgramResourceiv(int program, int programInterface, int index, int props_propCount, long props, int params_bufSize, long length, long params, long function_pointer); public static int glGetProgramResourceLocation(int program, int programInterface, ByteBuffer name) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramResourceLocation; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(name); BufferChecks.checkNullTerminated(name); int __result = nglGetProgramResourceLocation(program, programInterface, MemoryUtil.getAddress(name), function_pointer); return __result; } static native int nglGetProgramResourceLocation(int program, int programInterface, long name, long function_pointer); /** Overloads glGetProgramResourceLocation. */ public static int glGetProgramResourceLocation(int program, int programInterface, CharSequence name) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramResourceLocation; BufferChecks.checkFunctionAddress(function_pointer); int __result = nglGetProgramResourceLocation(program, programInterface, APIUtil.getBufferNT(caps, name), function_pointer); return __result; } public static int glGetProgramResourceLocationIndex(int program, int programInterface, ByteBuffer name) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramResourceLocationIndex; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(name); BufferChecks.checkNullTerminated(name); int __result = nglGetProgramResourceLocationIndex(program, programInterface, MemoryUtil.getAddress(name), function_pointer); return __result; } static native int nglGetProgramResourceLocationIndex(int program, int programInterface, long name, long function_pointer); /** Overloads glGetProgramResourceLocationIndex. */ public static int glGetProgramResourceLocationIndex(int program, int programInterface, CharSequence name) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glGetProgramResourceLocationIndex; BufferChecks.checkFunctionAddress(function_pointer); int __result = nglGetProgramResourceLocationIndex(program, programInterface, APIUtil.getBufferNT(caps, name), function_pointer); return __result; } public static void glShaderStorageBlockBinding(int program, int storageBlockIndex, int storageBlockBinding) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glShaderStorageBlockBinding; BufferChecks.checkFunctionAddress(function_pointer); nglShaderStorageBlockBinding(program, storageBlockIndex, storageBlockBinding, function_pointer); } static native void nglShaderStorageBlockBinding(int program, int storageBlockIndex, int storageBlockBinding, long function_pointer); public static void glTexBufferRange(int target, int internalformat, int buffer, long offset, long size) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glTexBufferRange; BufferChecks.checkFunctionAddress(function_pointer); nglTexBufferRange(target, internalformat, buffer, offset, size, function_pointer); } static native void nglTexBufferRange(int target, int internalformat, int buffer, long offset, long size, long function_pointer); public static void glTexStorage2DMultisample(int target, int samples, int internalformat, int width, int height, boolean fixedsamplelocations) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glTexStorage2DMultisample; BufferChecks.checkFunctionAddress(function_pointer); nglTexStorage2DMultisample(target, samples, internalformat, width, height, fixedsamplelocations, function_pointer); } static native void nglTexStorage2DMultisample(int target, int samples, int internalformat, int width, int height, boolean fixedsamplelocations, long function_pointer); public static void glTexStorage3DMultisample(int target, int samples, int internalformat, int width, int height, int depth, boolean fixedsamplelocations) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glTexStorage3DMultisample; BufferChecks.checkFunctionAddress(function_pointer); nglTexStorage3DMultisample(target, samples, internalformat, width, height, depth, fixedsamplelocations, function_pointer); } static native void nglTexStorage3DMultisample(int target, int samples, int internalformat, int width, int height, int depth, boolean fixedsamplelocations, long function_pointer); public static void glTextureView(int texture, int target, int origtexture, int internalformat, int minlevel, int numlevels, int minlayer, int numlayers) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glTextureView; BufferChecks.checkFunctionAddress(function_pointer); nglTextureView(texture, target, origtexture, internalformat, minlevel, numlevels, minlayer, numlayers, function_pointer); } static native void nglTextureView(int texture, int target, int origtexture, int internalformat, int minlevel, int numlevels, int minlayer, int numlayers, long function_pointer); public static void glBindVertexBuffer(int bindingindex, int buffer, long offset, int stride) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glBindVertexBuffer; BufferChecks.checkFunctionAddress(function_pointer); nglBindVertexBuffer(bindingindex, buffer, offset, stride, function_pointer); } static native void nglBindVertexBuffer(int bindingindex, int buffer, long offset, int stride, long function_pointer); public static void glVertexAttribFormat(int attribindex, int size, int type, boolean normalized, int relativeoffset) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glVertexAttribFormat; BufferChecks.checkFunctionAddress(function_pointer); nglVertexAttribFormat(attribindex, size, type, normalized, relativeoffset, function_pointer); } static native void nglVertexAttribFormat(int attribindex, int size, int type, boolean normalized, int relativeoffset, long function_pointer); public static void glVertexAttribIFormat(int attribindex, int size, int type, int relativeoffset) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glVertexAttribIFormat; BufferChecks.checkFunctionAddress(function_pointer); nglVertexAttribIFormat(attribindex, size, type, relativeoffset, function_pointer); } static native void nglVertexAttribIFormat(int attribindex, int size, int type, int relativeoffset, long function_pointer); public static void glVertexAttribLFormat(int attribindex, int size, int type, int relativeoffset) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glVertexAttribLFormat; BufferChecks.checkFunctionAddress(function_pointer); nglVertexAttribLFormat(attribindex, size, type, relativeoffset, function_pointer); } static native void nglVertexAttribLFormat(int attribindex, int size, int type, int relativeoffset, long function_pointer); public static void glVertexAttribBinding(int attribindex, int bindingindex) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glVertexAttribBinding; BufferChecks.checkFunctionAddress(function_pointer); nglVertexAttribBinding(attribindex, bindingindex, function_pointer); } static native void nglVertexAttribBinding(int attribindex, int bindingindex, long function_pointer); public static void glVertexBindingDivisor(int bindingindex, int divisor) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glVertexBindingDivisor; BufferChecks.checkFunctionAddress(function_pointer); nglVertexBindingDivisor(bindingindex, divisor, function_pointer); } static native void nglVertexBindingDivisor(int bindingindex, int divisor, long function_pointer); }
mit
gregwym/joos-compiler-java
testcases/a2/J1_3_SingleTypeImport_NoClash/Main.java
146
// TYPE_LINKING import a.bc; import ab.c; public class Main { public Main() {} public static int test() { return bc.test()+c.test(); } }
mit
devopsmwas/javapractice
NetBeansProjects/practice/src/practice/DiceApp.java
440
public class DiceApp{ public static void main(String[] args){ int roll; String msg = "Here are a Hundred random rolls of the dice"; System.out.println(msg); for(int i =0; i <100;i++){ roll = randomInt(1,6); System.out.print(roll + " "); } System.out.println(); } public static int randomInt(int low,int high){ int result =(int)(Math.random()*(high - low + 1)) + low; return result; } }
mit
codeck/XChange
xchange-ripple/src/main/java/com/xeiam/xchange/ripple/service/polling/params/RippleTradeHistoryPreferredCurrencies.java
516
package com.xeiam.xchange.ripple.service.polling.params; import java.util.Collection; import com.xeiam.xchange.service.polling.trade.params.TradeHistoryParams; /** * Convert the Ripple trade currency pairs into having these preferred base or counter currency. Preferred base currency is considered first. */ public interface RippleTradeHistoryPreferredCurrencies extends TradeHistoryParams { public Collection<String> getPreferredBaseCurrency(); public Collection<String> getPreferredCounterCurrency(); }
mit
gnomex/ESw1ControleJuridico-EJB
EJB e Negocio/ControleJuridicoDesktop/build/generated/jax-wsCache/ClienteWS/br/unioeste/controle/juridico/ws/cliente/ObterClientePeloID.java
1143
package br.unioeste.controle.juridico.ws.cliente; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java de obterClientePeloID complex type. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * * <pre> * &lt;complexType name="obterClientePeloID"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "obterClientePeloID", propOrder = { "id" }) public class ObterClientePeloID { protected int id; /** * Obtém o valor da propriedade id. * */ public int getId() { return id; } /** * Define o valor da propriedade id. * */ public void setId(int value) { this.id = value; } }
mit
NorthFacing/Mapper
weekend/src/test/java/tk/mybatis/mapper/weekend/WeekendSqlsTest.java
3508
/* * The MIT License (MIT) * * Copyright (c) 2014-2017 the original author or authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package tk.mybatis.mapper.weekend; import org.apache.ibatis.session.SqlSession; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.util.Sqls; import tk.mybatis.mapper.weekend.entity.Country; import tk.mybatis.mapper.weekend.mapper.CountryMapper; import java.util.List; /** * 测试WeekendSql构建者模式类 * * @author XuYin */ public class WeekendSqlsTest { @Rule public TestRule runJava8 = new UseJava8Rule(); @Test public void testWeekend() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); List<Country> selectByWeekendSql = mapper.selectByExample(new Example.Builder(Country.class) .where(WeekendSqls.<Country>custom().andLike(Country::getCountryname, "China")).build()); List<Country> selectByExample = mapper.selectByExample( new Example.Builder(Country.class).where(Sqls.custom().andLike("countryname", "China")).build()); //判断两个结果数组内容是否相同 Assert.assertArrayEquals(selectByExample.toArray(), selectByWeekendSql.toArray()); } finally { sqlSession.close(); } } @Test public void testWeekendComplex() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); List<Country> selectByWeekendSql = mapper.selectByExample(new Example.Builder(Country.class) .where(WeekendSqls.<Country>custom().andLike(Country::getCountryname, "%a%") .andGreaterThan(Country::getCountrycode, "123")) .build()); List<Country> selectByExample = mapper.selectByExample(new Example.Builder(Country.class) .where(Sqls.custom().andLike("countryname", "%a%").andGreaterThan("countrycode", "123")).build()); // 判断两个结果数组内容是否相同 Assert.assertArrayEquals(selectByExample.toArray(), selectByWeekendSql.toArray()); } finally { sqlSession.close(); } } }
mit
najibghadri/NeuralNetworkSimulator
src/org/apache/commons/math3/ode/FieldODEStateAndDerivative.java
3295
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.ode; import org.apache.commons.math3.RealFieldElement; /** Container for time, main and secondary state vectors as well as their derivatives. * @see FirstOrderFieldDifferentialEquations * @see FieldSecondaryEquations * @see FirstOrderFieldIntegrator * @param <T> the type of the field elements * @since 3.6 */ public class FieldODEStateAndDerivative<T extends RealFieldElement<T>> extends FieldODEState<T> { /** Derivative of the main state at time. */ private final T[] derivative; /** Derivative of the secondary state at time. */ private final T[][] secondaryDerivative; /** Simple constructor. * <p>Calling this constructor is equivalent to call {@link * #FieldODEStateAndDerivative(RealFieldElement, RealFieldElement[], RealFieldElement[], * RealFieldElement[][], RealFieldElement[][]) FieldODEStateAndDerivative(time, state, * derivative, null, null)}.</p> * @param time time * @param state state at time * @param derivative derivative of the state at time */ public FieldODEStateAndDerivative(T time, T[] state, T[] derivative) { this(time, state, derivative, null, null); } /** Simple constructor. * @param time time * @param state state at time * @param derivative derivative of the state at time * @param secondaryState state at time (may be null) * @param secondaryDerivative derivative of the state at time (may be null) */ public FieldODEStateAndDerivative(T time, T[] state, T[] derivative, T[][] secondaryState, T[][] secondaryDerivative) { super(time, state, secondaryState); this.derivative = derivative.clone(); this.secondaryDerivative = copy(time.getField(), secondaryDerivative); } /** Get derivative of the main state at time. * @return derivative of the main state at time */ public T[] getDerivative() { return derivative.clone(); } /** Get derivative of the secondary state at time. * @param index index of the secondary set as returned * by {@link FieldExpandableODE#addSecondaryEquations(FieldSecondaryEquations)} * (beware index 0 corresponds to main state, additional states startToggle at 1) * @return derivative of the secondary state at time */ public T[] getSecondaryDerivative(final int index) { return index == 0 ? derivative.clone() : secondaryDerivative[index - 1].clone(); } }
mit
mmohan01/ReFactory
data/jhotdraw/jhotdraw-5.2/CH/ifa/draw/standard/HandleTracker.java
958
/* * @(#)HandleTracker.java 5.2 * */ package CH.ifa.draw.standard; import java.awt.*; import java.awt.event.MouseEvent; import CH.ifa.draw.framework.*; /** * HandleTracker implements interactions with the handles * of a Figure. * * @see SelectionTool */ public class HandleTracker extends AbstractTool { private Handle fAnchorHandle; public HandleTracker(DrawingView view, Handle anchorHandle) { super(view); fAnchorHandle = anchorHandle; } public void mouseDown(MouseEvent e, int x, int y) { super.mouseDown(e, x, y); fAnchorHandle.invokeStart(x, y, view()); } public void mouseDrag(MouseEvent e, int x, int y) { super.mouseDrag(e, x, y); fAnchorHandle.invokeStep(x, y, fAnchorX, fAnchorY, view()); } public void mouseUp(MouseEvent e, int x, int y) { super.mouseDrag(e, x, y); fAnchorHandle.invokeEnd(x, y, fAnchorX, fAnchorY, view()); } }
mit
ProfAmesBC/Game2013
src/inventory/Item.java
487
// Items differ from Power-Ups because // they are added to the inventory // rather than being used immediately package inventory; import game.PlayerMotionWatcher; import javax.media.opengl.GL2; import javax.media.opengl.glu.GLU; public interface Item extends PlayerMotionWatcher { public void draw(GL2 gl, GLU glu); public void draw(GL2 gl, GLU glu, float x, float y, float z); public void use(); public boolean grabbed(); public String getType(); }
mit
pivotal/jsunit
java/tests_core/net/jsunit/model/AbstractResultTest.java
1413
package net.jsunit.model; import junit.framework.TestCase; import org.jdom.Element; import java.util.List; public class AbstractResultTest extends TestCase { public void testDisplayString() { MyAbstractResult result = new MyAbstractResult(); result.setResultType(ResultType.FAILED_TO_LAUNCH); assertTrue(result.displayString().endsWith(ResultType.FAILED_TO_LAUNCH.getDisplayString())); result.setResultType(ResultType.UNRESPONSIVE); assertTrue(result.displayString().endsWith(ResultType.UNRESPONSIVE.getDisplayString())); result.setResultType(ResultType.ERROR); assertEquals("The test run had 0 error(s) and 0 failure(s).", result.displayString()); } private static class MyAbstractResult extends AbstractResult { private ResultType resultType; protected List<? extends Result> getChildren() { return null; } public Element asXml() { return null; } public void setResultType(ResultType resultType) { this.resultType = resultType; } public ResultType _getResultType() { return this.resultType; } public int getFailureCount() { return 0; } public int getErrorCount() { return 0; } public int getTestCount() { return 0; } } }
mit
mallowigi/material-theme-jetbrains
src/main/java/com/chrisrm/idea/icons/patchers/TasksIconsPatcher.java
1543
/* * The MIT License (MIT) * * Copyright (c) 2018 Chris Magnussen and Elior Boukhobza * * 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.chrisrm.idea.icons.patchers; import org.jetbrains.annotations.NotNull; /** * @author Konstantin Bulenkov */ public class TasksIconsPatcher extends MTIconPatcher { @Override @NotNull public final String getPathToAppend() { return "/icons/tasks"; } @Override @NotNull public final String getPathToRemove() { return "/icons"; } }
mit
ria-ee/X-Road
src/common-test/src/main/java/ee/ria/xroad/common/HttpUtils.java
7505
/** * The MIT License * Copyright (c) 2015 Estonian Information System Authority (RIA), Population Register Centre (VRK) * * 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 ee.ria.xroad.common; import ee.ria.xroad.common.util.CryptoUtils; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.ssl.AllowAllHostnameVerifier; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.nio.conn.NoopIOSessionStrategy; import org.apache.http.nio.conn.SchemeIOSessionStrategy; import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509ExtendedKeyManager; import javax.net.ssl.X509TrustManager; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * Contains utility methods for creating test HTTP clients. * * FUTURE Only 'extra' project uses it (subprojects 'testclient' and 'systemtest') */ public final class HttpUtils { private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class); private static final int CLIENT_TIMEOUT = 3000000; // milliseconds. private static final int CLIENT_MAX_TOTAL_CONNECTIONS = 10000; private static final int CLIENT_MAX_CONNECTIONS_PER_ROUTE = 2500; private HttpUtils() { } /** * Returns HTTP client with a specially configured thread pool. * @return CloseableHttpAsyncClient */ public static CloseableHttpAsyncClient getDefaultHttpClient() { return getHttpClient(true); } /** * Returns HTTP client with no special thread pool configuration. * * In testclient web application we need to do it like this in order to * be able to do more than one consecutive request. * * @return CloseableHttpAsyncClient */ public static CloseableHttpAsyncClient getHttpClientWithDefaultThreadPool() { return getHttpClient(false); } static CloseableHttpAsyncClient getHttpClient( boolean configureThreadPool) { HttpAsyncClientBuilder builder = HttpAsyncClients.custom(); if (configureThreadPool) { try { configureConnectionManager(builder, null); } catch (IOReactorException e) { throw new RuntimeException(e); } } return builder.build(); } /** * Returns HTTP client that uses the provided client key manager. * @param clientKeyManager the client key manager * @return CloseableHttpAsyncClient * @throws Exception in case of any errors */ public static CloseableHttpAsyncClient getHttpClient( X509ExtendedKeyManager clientKeyManager) throws Exception { return getHttpClient(clientKeyManager, new ClientTrustManager()); } /** * Returns HTTP client that uses the provided key manager and client trust manager. * @param clientKeyManager the client key manager * @param clientTrustManager the client trust manager * @return CloseableHttpAsyncClient * @throws Exception in case of any errors */ public static CloseableHttpAsyncClient getHttpClient( X509ExtendedKeyManager clientKeyManager, X509TrustManager clientTrustManager) throws Exception { SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL); ctx.init(new KeyManager[] {clientKeyManager}, new TrustManager[] {clientTrustManager}, new SecureRandom()); Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create() .register("http", NoopIOSessionStrategy.INSTANCE) .register("https", new SSLIOSessionStrategy(ctx, new AllowAllHostnameVerifier())) .build(); HttpAsyncClientBuilder builder = HttpAsyncClients.custom(); configureConnectionManager(builder, sessionStrategyRegistry); return builder.build(); } private static void configureConnectionManager( HttpAsyncClientBuilder builder, Registry<SchemeIOSessionStrategy> sessionStrategyRegistry) throws IOReactorException { IOReactorConfig ioReactorConfig = IOReactorConfig.custom() .setIoThreadCount(Runtime.getRuntime().availableProcessors()) .setConnectTimeout(CLIENT_TIMEOUT) .setSoTimeout(CLIENT_TIMEOUT) .build(); ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig); PoolingNHttpClientConnectionManager connManager = null; if (sessionStrategyRegistry != null) { connManager = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry); } else { connManager = new PoolingNHttpClientConnectionManager(ioReactor); } connManager.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS); connManager.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE); builder.setConnectionManager(connManager); } private static class ClientTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { LOG.debug("checkClientTrusted()"); } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { LOG.debug("checkServerTrusted()"); } @Override public X509Certificate[] getAcceptedIssuers() { LOG.debug("getAcceptedIssuers()"); return new X509Certificate[] {}; } } }
mit
b0noI/AIF2
src/main/java/io/aif/language/word/comparator/OptimizedComparatorWrapper.java
999
package io.aif.language.word.comparator; import java.util.Collection; import java.util.HashSet; import java.util.Set; class OptimizedComparatorWrapper implements IGroupComparator { private final IGroupComparator setComparator; OptimizedComparatorWrapper(IGroupComparator setComparator) { this.setComparator = setComparator; } @Override public double compare(final Collection<String> t1, final Collection<String> t2) { final Set<String> lowerCaseSet1 = new HashSet<>(); final Set<String> lowerCaseSet2 = new HashSet<>(); t1.forEach(token -> lowerCaseSet1.add(token.toLowerCase())); t2.forEach(token -> lowerCaseSet2.add(token.toLowerCase())); final double primitiveResult = Type.PRIMITIVE.getComparator().compare(lowerCaseSet1, lowerCaseSet2); if (primitiveResult == 1.) { return primitiveResult; } if (primitiveResult == .0) { return primitiveResult; } return setComparator.compare(lowerCaseSet1, lowerCaseSet2); } }
mit
nlgcoin/guldencoin-official
src/frontend/android/unity_wallet/app/src/main/java/com/gulden/jniunifiedbackend/IAccountsListener.java
878
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from libunity.djinni package com.gulden.jniunifiedbackend; /** Interface to receive updates about accounts */ public abstract class IAccountsListener { /** Notify that the active account has changed */ public abstract void onActiveAccountChanged(String accountUUID); /** Notify that the active account name has changed */ public abstract void onActiveAccountNameChanged(String newAccountName); /** Notify that an account name has changed */ public abstract void onAccountNameChanged(String accountUUID, String newAccountName); /** Notify that a new account has been added */ public abstract void onAccountAdded(String accountUUID, String accountName); /** Notify that an account has been deleted */ public abstract void onAccountDeleted(String accountUUID); }
mit
kaituo/sedge
trunk/src-kaituo/edu/umass/cs/pig/z3/PatternArrayTheirs.java
266
package edu.umass.cs.pig.z3; import edu.umass.cs.z3.PatternArray; import edu.umass.cs.z3.Z3JNI; public class PatternArrayTheirs extends PatternArray { public PatternArrayTheirs(int nrElements) { super(Z3JNI.new_PatternArray(nrElements), false); } }
mit
kineticadb/kinetica-api-java
api/src/main/java/com/gpudb/protocol/AlterUserResponse.java
4872
/* * This file was autogenerated by the GPUdb schema processor. * * DO NOT EDIT DIRECTLY. */ package com.gpudb.protocol; import java.util.LinkedHashMap; import java.util.Map; import org.apache.avro.Schema; import org.apache.avro.SchemaBuilder; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.IndexedRecord; /** * A set of results returned by {@link * com.gpudb.GPUdb#alterUser(AlterUserRequest)}. */ public class AlterUserResponse implements IndexedRecord { private static final Schema schema$ = SchemaBuilder .record("AlterUserResponse") .namespace("com.gpudb") .fields() .name("name").type().stringType().noDefault() .name("info").type().map().values().stringType().noDefault() .endRecord(); /** * This method supports the Avro framework and is not intended to be called * directly by the user. * * @return the schema for the class. * */ public static Schema getClassSchema() { return schema$; } private String name; private Map<String, String> info; /** * Constructs an AlterUserResponse object with default parameters. */ public AlterUserResponse() { } /** * * @return Value of {@code name}. * */ public String getName() { return name; } /** * * @param name Value of {@code name}. * * @return {@code this} to mimic the builder pattern. * */ public AlterUserResponse setName(String name) { this.name = (name == null) ? "" : name; return this; } /** * * @return Additional information. * */ public Map<String, String> getInfo() { return info; } /** * * @param info Additional information. * * @return {@code this} to mimic the builder pattern. * */ public AlterUserResponse setInfo(Map<String, String> info) { this.info = (info == null) ? new LinkedHashMap<String, String>() : info; return this; } /** * This method supports the Avro framework and is not intended to be called * directly by the user. * * @return the schema object describing this class. * */ @Override public Schema getSchema() { return schema$; } /** * This method supports the Avro framework and is not intended to be called * directly by the user. * * @param index the position of the field to get * * @return value of the field with the given index. * * @throws IndexOutOfBoundsException * */ @Override public Object get(int index) { switch (index) { case 0: return this.name; case 1: return this.info; default: throw new IndexOutOfBoundsException("Invalid index specified."); } } /** * This method supports the Avro framework and is not intended to be called * directly by the user. * * @param index the position of the field to set * @param value the value to set * * @throws IndexOutOfBoundsException * */ @Override @SuppressWarnings("unchecked") public void put(int index, Object value) { switch (index) { case 0: this.name = (String)value; break; case 1: this.info = (Map<String, String>)value; break; default: throw new IndexOutOfBoundsException("Invalid index specified."); } } @Override public boolean equals(Object obj) { if( obj == this ) { return true; } if( (obj == null) || (obj.getClass() != this.getClass()) ) { return false; } AlterUserResponse that = (AlterUserResponse)obj; return ( this.name.equals( that.name ) && this.info.equals( that.info ) ); } @Override public String toString() { GenericData gd = GenericData.get(); StringBuilder builder = new StringBuilder(); builder.append( "{" ); builder.append( gd.toString( "name" ) ); builder.append( ": " ); builder.append( gd.toString( this.name ) ); builder.append( ", " ); builder.append( gd.toString( "info" ) ); builder.append( ": " ); builder.append( gd.toString( this.info ) ); builder.append( "}" ); return builder.toString(); } @Override public int hashCode() { int hashCode = 1; hashCode = (31 * hashCode) + this.name.hashCode(); hashCode = (31 * hashCode) + this.info.hashCode(); return hashCode; } }
mit
benas/jPopulator
easy-random-core/src/test/java/org/jeasy/random/ExclusionCheckerTest.java
2197
/** * The MIT License * * Copyright (c) 2019, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.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 org.jeasy.random; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Field; import org.jeasy.random.api.RandomizerContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.jeasy.random.beans.Human; @ExtendWith(MockitoExtension.class) class ExclusionCheckerTest { @Mock private RandomizerContext randomizerContext; private ExclusionChecker checker; @BeforeEach void setUp() { checker = new ExclusionChecker(); } @Test void staticFieldsShouldBeExcluded() throws NoSuchFieldException { // Given Field field = Human.class.getDeclaredField("SERIAL_VERSION_UID"); // When boolean actual = checker.shouldBeExcluded(field, randomizerContext); // Then assertThat(actual).isTrue(); } }
mit
automenta/actrj
src/main/java/actr/model/Module.java
176
package actr.model; /** * Abstract class for an ACT-R module. * * @author Dario Salvucci */ public abstract class Module { void initialize () { } void update () { } }
mit
shardis/spring-angular2-starter
shardis-ui/src/main/java/com/shardis/ShardisUiApplication.java
727
package com.shardis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ErrorPageRegistrar; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; /** * Created by Tomasz Kucharzyk */ @SpringBootApplication @EnableDiscoveryClient @EnableCaching @EnableZuulProxy public class ShardisUiApplication { public static void main(String[] args) { SpringApplication.run(ShardisUiApplication.class, args); } }
mit
lilongcnc/Android_Study
SQLite20161206/app/src/test/java/com/example/lauren/sqlite20161206/ExampleUnitTest.java
411
package com.example.lauren.sqlite20161206; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
mmohan01/ReFactory
data/jhotdraw/jhotdraw-5.4b2/CH/ifa/draw/samples/pert/PertFigure.java
7445
/* * @(#)PertFigure.java * * Project: JHotdraw - a GUI framework for technical drawings * http://www.jhotdraw.org * http://jhotdraw.sourceforge.net * Copyright: © by the original author(s) and all contributors * License: Lesser GNU Public License (LGPL) * http://www.opensource.org/licenses/lgpl-license.html */ package CH.ifa.draw.samples.pert; import CH.ifa.draw.framework.*; import CH.ifa.draw.standard.*; import CH.ifa.draw.figures.*; import CH.ifa.draw.util.*; import java.awt.*; import java.io.*; import java.util.Iterator; import java.util.List; /** * @version <$CURRENT_VERSION$> */ public class PertFigure extends CompositeFigure { private static final int BORDER = 3; private Rectangle fDisplayBox; private List fPreTasks; private List fPostTasks; /* * Serialization support. */ private static final long serialVersionUID = -7877776240236946511L; private int pertFigureSerializedDataVersion = 1; public PertFigure() { initialize(); } public int start() { int start = 0; Iterator iter = fPreTasks.iterator(); while (iter.hasNext()) { PertFigure f = (PertFigure)iter.next(); start = Math.max(start, f.end()); } return start; } public int end() { return asInt(2); } public int duration() { return asInt(1); } public void setEnd(int value) { setInt(2, value); } public void addPreTask(PertFigure figure) { if (!fPreTasks.contains(figure)) { fPreTasks.add(figure); } } public void addPostTask(PertFigure figure) { if (!fPostTasks.contains(figure)) { fPostTasks.add(figure); } } public void removePreTask(PertFigure figure) { fPreTasks.remove(figure); } public void removePostTask(PertFigure figure) { fPostTasks.remove(figure); } private int asInt(int figureIndex) { NumberTextFigure t = (NumberTextFigure)figureAt(figureIndex); return t.getValue(); } private String taskName() { TextFigure t = (TextFigure)figureAt(0); return t.getText(); } private void setInt(int figureIndex, int value) { NumberTextFigure t = (NumberTextFigure)figureAt(figureIndex); t.setValue(value); } protected void basicMoveBy(int x, int y) { fDisplayBox.translate(x, y); super.basicMoveBy(x, y); } public Rectangle displayBox() { return new Rectangle( fDisplayBox.x, fDisplayBox.y, fDisplayBox.width, fDisplayBox.height); } public void basicDisplayBox(Point origin, Point corner) { fDisplayBox = new Rectangle(origin); fDisplayBox.add(corner); layout(); } private void drawBorder(Graphics g) { super.draw(g); Rectangle r = displayBox(); Figure f = figureAt(0); Rectangle rf = f.displayBox(); g.setColor(Color.gray); g.drawLine(r.x, r.y+rf.height+2, r.x+r.width, r.y + rf.height+2); g.setColor(Color.white); g.drawLine(r.x, r.y+rf.height+3, r.x+r.width, r.y + rf.height+3); g.setColor(Color.white); g.drawLine(r.x, r.y, r.x, r.y + r.height); g.drawLine(r.x, r.y, r.x + r.width, r.y); g.setColor(Color.gray); g.drawLine(r.x + r.width, r.y, r.x + r.width, r.y + r.height); g.drawLine(r.x , r.y + r.height, r.x + r.width, r.y + r.height); } public void draw(Graphics g) { drawBorder(g); super.draw(g); } public HandleEnumeration handles() { List handles = CollectionsFactory.current().createList(); handles.add(new NullHandle(this, RelativeLocator.northWest())); handles.add(new NullHandle(this, RelativeLocator.northEast())); handles.add(new NullHandle(this, RelativeLocator.southWest())); handles.add(new NullHandle(this, RelativeLocator.southEast())); handles.add(new ConnectionHandle(this, RelativeLocator.east(), new PertDependency()) ); return new HandleEnumerator(handles); } private void initialize() { fPostTasks = CollectionsFactory.current().createList(); fPreTasks = CollectionsFactory.current().createList(); fDisplayBox = new Rectangle(0, 0, 0, 0); Font f = new Font("Helvetica", Font.PLAIN, 12); Font fb = new Font("Helvetica", Font.BOLD, 12); TextFigure name = new TextFigure(); name.setFont(fb); name.setText("Task"); //name.setAttribute(FigureAttributeConstant.TEXT_COLOR.getName(), Color.white); add(name); NumberTextFigure duration = new NumberTextFigure(); duration.setValue(0); duration.setFont(fb); add(duration); NumberTextFigure end = new NumberTextFigure(); end.setValue(0); end.setFont(f); end.setReadOnly(true); add(end); } private void layout() { Point partOrigin = new Point(fDisplayBox.x, fDisplayBox.y); partOrigin.translate(BORDER, BORDER); Dimension extent = new Dimension(0, 0); FigureEnumeration fe = figures(); while (fe.hasNextFigure()) { Figure f = fe.nextFigure(); Dimension partExtent = f.size(); Point corner = new Point( partOrigin.x+partExtent.width, partOrigin.y+partExtent.height); f.basicDisplayBox(partOrigin, corner); extent.width = Math.max(extent.width, partExtent.width); extent.height += partExtent.height; partOrigin.y += partExtent.height; } fDisplayBox.width = extent.width + 2*BORDER; fDisplayBox.height = extent.height + 2*BORDER; } private boolean needsLayout() { Dimension extent = new Dimension(0, 0); FigureEnumeration fe = figures(); while (fe.hasNextFigure()) { Figure f = fe.nextFigure(); extent.width = Math.max(extent.width, f.size().width); } int newExtent = extent.width + 2*BORDER; return newExtent != fDisplayBox.width; } public void update(FigureChangeEvent e) { if (e.getFigure() == figureAt(1)) { // duration has changed updateDurations(); } if (needsLayout()) { layout(); changed(); } } public void figureChanged(FigureChangeEvent e) { update(e); } public void figureRemoved(FigureChangeEvent e) { update(e); } public void notifyPostTasks() { Iterator iter = fPostTasks.iterator(); while (iter.hasNext()) { ((PertFigure)iter.next()).updateDurations(); } } public void updateDurations() { int newEnd = start()+duration(); if (newEnd != end()) { setEnd(newEnd); notifyPostTasks(); } } public boolean hasCycle(Figure start) { if (start == this) { return true; } Iterator iter = fPreTasks.iterator(); while (iter.hasNext()) { if (((PertFigure)iter.next()).hasCycle(start)) { return true; } } return false; } //-- store / load ---------------------------------------------- public void write(StorableOutput dw) { super.write(dw); dw.writeInt(fDisplayBox.x); dw.writeInt(fDisplayBox.y); dw.writeInt(fDisplayBox.width); dw.writeInt(fDisplayBox.height); writeTasks(dw, fPreTasks); writeTasks(dw, fPostTasks); } public void writeTasks(StorableOutput dw, List l) { dw.writeInt(l.size()); Iterator iter = l.iterator(); while (iter.hasNext()) { dw.writeStorable((Storable)iter.next()); } } public void read(StorableInput dr) throws IOException { super.read(dr); fDisplayBox = new Rectangle( dr.readInt(), dr.readInt(), dr.readInt(), dr.readInt()); layout(); fPreTasks = readTasks(dr); fPostTasks = readTasks(dr); } public Insets connectionInsets() { Rectangle r = fDisplayBox; int cx = r.width/2; int cy = r.height/2; return new Insets(cy, cx, cy, cx); } public List readTasks(StorableInput dr) throws IOException { int size = dr.readInt(); List l = CollectionsFactory.current().createList(size); for (int i=0; i<size; i++) { l.add(dr.readStorable()); } return l; } }
mit
MolaynoxX/AMMP
src/main/java/de/molaynoxx/amperfi/ui/view/Viewable.java
69
package de.molaynoxx.amperfi.ui.view; public interface Viewable { }
mit
0x90sled/droidtowers
main/test/com/happydroids/droidtowers/achievements/AchievementEngineTest.java
699
/* * Copyright (c) 2012. HappyDroids LLC, All rights reserved. */ package com.happydroids.droidtowers.achievements; import com.happydroids.droidtowers.NonGLTestRunner; import com.happydroids.droidtowers.types.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(NonGLTestRunner.class) public class AchievementEngineTest { @Before public void setUp() { RoomTypeFactory.instance(); CommercialTypeFactory.instance(); ServiceRoomTypeFactory.instance(); ElevatorTypeFactory.instance(); StairTypeFactory.instance(); } @Test public void shouldParseAllAchievements() { AchievementEngine engine = new AchievementEngine(); } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/fluent/models/MigrateMySqlStatusInner.java
2546
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.appservice.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.appservice.models.OperationStatus; import com.azure.resourcemanager.appservice.models.ProxyOnlyResource; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** MySQL migration status. */ @Fluent public final class MigrateMySqlStatusInner extends ProxyOnlyResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(MigrateMySqlStatusInner.class); /* * MigrateMySqlStatus resource specific properties */ @JsonProperty(value = "properties") private MigrateMySqlStatusProperties innerProperties; /** * Get the innerProperties property: MigrateMySqlStatus resource specific properties. * * @return the innerProperties value. */ private MigrateMySqlStatusProperties innerProperties() { return this.innerProperties; } /** {@inheritDoc} */ @Override public MigrateMySqlStatusInner withKind(String kind) { super.withKind(kind); return this; } /** * Get the migrationOperationStatus property: Status of the migration task. * * @return the migrationOperationStatus value. */ public OperationStatus migrationOperationStatus() { return this.innerProperties() == null ? null : this.innerProperties().migrationOperationStatus(); } /** * Get the operationId property: Operation ID for the migration task. * * @return the operationId value. */ public String operationId() { return this.innerProperties() == null ? null : this.innerProperties().operationId(); } /** * Get the localMySqlEnabled property: True if the web app has in app MySql enabled. * * @return the localMySqlEnabled value. */ public Boolean localMySqlEnabled() { return this.innerProperties() == null ? null : this.innerProperties().localMySqlEnabled(); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (innerProperties() != null) { innerProperties().validate(); } } }
mit
navalev/azure-sdk-for-java
sdk/appplatform/mgmt-v2019_05_01_preview/src/main/java/com/microsoft/azure/management/appplatform/v2019_05_01_preview/OperationDetail.java
1172
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appplatform.v2019_05_01_preview; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.appplatform.v2019_05_01_preview.implementation.AppPlatformManager; import com.microsoft.azure.management.appplatform.v2019_05_01_preview.implementation.OperationDetailInner; /** * Type representing OperationDetail. */ public interface OperationDetail extends HasInner<OperationDetailInner>, HasManager<AppPlatformManager> { /** * @return the dataAction value. */ Boolean dataAction(); /** * @return the display value. */ OperationDisplay display(); /** * @return the name value. */ String name(); /** * @return the origin value. */ String origin(); /** * @return the properties value. */ OperationProperties properties(); }
mit
szpak/mockito
src/test/java/org/mockito/internal/verification/SmartPrinterTest.java
2197
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.verification; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.internal.invocation.InvocationMatcher; import org.mockito.internal.reporting.SmartPrinter; import org.mockitousage.IMethods; import org.mockitoutil.TestBase; public class SmartPrinterTest extends TestBase { private InvocationMatcher multi; private InvocationMatcher shortie; @Mock private IMethods mock; @Before public void setup() throws Exception { mock.varargs("first very long argument", "second very long argument", "another very long argument"); multi = new InvocationMatcher(getLastInvocation()); mock.varargs("short arg"); shortie = new InvocationMatcher(getLastInvocation()); } @Test public void shouldPrintBothInMultilinesWhenFirstIsMulti() { //when SmartPrinter printer = new SmartPrinter(multi, shortie.getInvocation()); //then assertThat(printer.getWanted()).contains("\n"); assertThat(printer.getActual()).contains("\n"); } @Test public void shouldPrintBothInMultilinesWhenSecondIsMulti() { //when SmartPrinter printer = new SmartPrinter(shortie, multi.getInvocation()); //then assertThat(printer.getWanted()).contains("\n"); assertThat(printer.getActual()).contains("\n"); } @Test public void shouldPrintBothInMultilinesWhenBothAreMulti() { //when SmartPrinter printer = new SmartPrinter(multi, multi.getInvocation()); //then assertThat(printer.getWanted()).contains("\n"); assertThat(printer.getActual()).contains("\n"); } @Test public void shouldPrintBothInSingleLineWhenBothAreShort() { //when SmartPrinter printer = new SmartPrinter(shortie, shortie.getInvocation()); //then assertThat(printer.getWanted()).doesNotContain("\n"); assertThat(printer.getActual()).doesNotContain("\n"); } }
mit
georghinkel/ttc2017smartGrids
solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/Informative/Reservation/impl/TransmissionServiceImpl.java
17328
/** */ package gluemodel.CIM.IEC61970.Informative.Reservation.impl; import gluemodel.CIM.IEC61970.Core.impl.IdentifiedObjectImpl; import gluemodel.CIM.IEC61970.Informative.EnergyScheduling.AvailableTransmissionCapacity; import gluemodel.CIM.IEC61970.Informative.EnergyScheduling.EnergySchedulingPackage; import gluemodel.CIM.IEC61970.Informative.Financial.FinancialPackage; import gluemodel.CIM.IEC61970.Informative.Financial.OpenAccessProduct; import gluemodel.CIM.IEC61970.Informative.Financial.TransmissionProduct; import gluemodel.CIM.IEC61970.Informative.Financial.TransmissionProvider; import gluemodel.CIM.IEC61970.Informative.Reservation.ReservationPackage; import gluemodel.CIM.IEC61970.Informative.Reservation.ServiceReservation; import gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionPath; import gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionService; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Transmission Service</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.impl.TransmissionServiceImpl#getOffering <em>Offering</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.impl.TransmissionServiceImpl#getOfferedAs <em>Offered As</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.impl.TransmissionServiceImpl#getScheduledBy <em>Scheduled By</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.impl.TransmissionServiceImpl#getReservedBy_ServiceReservation <em>Reserved By Service Reservation</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.impl.TransmissionServiceImpl#getTransContractFor <em>Trans Contract For</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.impl.TransmissionServiceImpl#getOffers <em>Offers</em>}</li> * </ul> * * @generated */ public class TransmissionServiceImpl extends IdentifiedObjectImpl implements TransmissionService { /** * The cached value of the '{@link #getOffering() <em>Offering</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOffering() * @generated * @ordered */ protected EList<TransmissionPath> offering; /** * The cached value of the '{@link #getOfferedAs() <em>Offered As</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOfferedAs() * @generated * @ordered */ protected EList<TransmissionProduct> offeredAs; /** * The cached value of the '{@link #getScheduledBy() <em>Scheduled By</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getScheduledBy() * @generated * @ordered */ protected EList<AvailableTransmissionCapacity> scheduledBy; /** * The cached value of the '{@link #getReservedBy_ServiceReservation() <em>Reserved By Service Reservation</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReservedBy_ServiceReservation() * @generated * @ordered */ protected EList<ServiceReservation> reservedBy_ServiceReservation; /** * The cached value of the '{@link #getTransContractFor() <em>Trans Contract For</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTransContractFor() * @generated * @ordered */ protected OpenAccessProduct transContractFor; /** * The cached value of the '{@link #getOffers() <em>Offers</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOffers() * @generated * @ordered */ protected TransmissionProvider offers; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TransmissionServiceImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ReservationPackage.Literals.TRANSMISSION_SERVICE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<TransmissionPath> getOffering() { if (offering == null) { offering = new EObjectWithInverseResolvingEList.ManyInverse<TransmissionPath>(TransmissionPath.class, this, ReservationPackage.TRANSMISSION_SERVICE__OFFERING, ReservationPackage.TRANSMISSION_PATH__OFFERED_ON); } return offering; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<TransmissionProduct> getOfferedAs() { if (offeredAs == null) { offeredAs = new EObjectWithInverseResolvingEList.ManyInverse<TransmissionProduct>(TransmissionProduct.class, this, ReservationPackage.TRANSMISSION_SERVICE__OFFERED_AS, FinancialPackage.TRANSMISSION_PRODUCT__OFFERS); } return offeredAs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<AvailableTransmissionCapacity> getScheduledBy() { if (scheduledBy == null) { scheduledBy = new EObjectWithInverseResolvingEList.ManyInverse<AvailableTransmissionCapacity>(AvailableTransmissionCapacity.class, this, ReservationPackage.TRANSMISSION_SERVICE__SCHEDULED_BY, EnergySchedulingPackage.AVAILABLE_TRANSMISSION_CAPACITY__SCHEDULE_FOR); } return scheduledBy; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ServiceReservation> getReservedBy_ServiceReservation() { if (reservedBy_ServiceReservation == null) { reservedBy_ServiceReservation = new EObjectWithInverseResolvingEList.ManyInverse<ServiceReservation>(ServiceReservation.class, this, ReservationPackage.TRANSMISSION_SERVICE__RESERVED_BY_SERVICE_RESERVATION, ReservationPackage.SERVICE_RESERVATION__RESERVES_TRANSMISSION_SERVICE); } return reservedBy_ServiceReservation; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OpenAccessProduct getTransContractFor() { if (transContractFor != null && transContractFor.eIsProxy()) { InternalEObject oldTransContractFor = (InternalEObject)transContractFor; transContractFor = (OpenAccessProduct)eResolveProxy(oldTransContractFor); if (transContractFor != oldTransContractFor) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, ReservationPackage.TRANSMISSION_SERVICE__TRANS_CONTRACT_FOR, oldTransContractFor, transContractFor)); } } return transContractFor; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OpenAccessProduct basicGetTransContractFor() { return transContractFor; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetTransContractFor(OpenAccessProduct newTransContractFor, NotificationChain msgs) { OpenAccessProduct oldTransContractFor = transContractFor; transContractFor = newTransContractFor; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ReservationPackage.TRANSMISSION_SERVICE__TRANS_CONTRACT_FOR, oldTransContractFor, newTransContractFor); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTransContractFor(OpenAccessProduct newTransContractFor) { if (newTransContractFor != transContractFor) { NotificationChain msgs = null; if (transContractFor != null) msgs = ((InternalEObject)transContractFor).eInverseRemove(this, FinancialPackage.OPEN_ACCESS_PRODUCT__PROVIDED_BY_TRANSMISSION_SERVICE, OpenAccessProduct.class, msgs); if (newTransContractFor != null) msgs = ((InternalEObject)newTransContractFor).eInverseAdd(this, FinancialPackage.OPEN_ACCESS_PRODUCT__PROVIDED_BY_TRANSMISSION_SERVICE, OpenAccessProduct.class, msgs); msgs = basicSetTransContractFor(newTransContractFor, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ReservationPackage.TRANSMISSION_SERVICE__TRANS_CONTRACT_FOR, newTransContractFor, newTransContractFor)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TransmissionProvider getOffers() { if (offers != null && offers.eIsProxy()) { InternalEObject oldOffers = (InternalEObject)offers; offers = (TransmissionProvider)eResolveProxy(oldOffers); if (offers != oldOffers) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, ReservationPackage.TRANSMISSION_SERVICE__OFFERS, oldOffers, offers)); } } return offers; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TransmissionProvider basicGetOffers() { return offers; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetOffers(TransmissionProvider newOffers, NotificationChain msgs) { TransmissionProvider oldOffers = offers; offers = newOffers; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ReservationPackage.TRANSMISSION_SERVICE__OFFERS, oldOffers, newOffers); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOffers(TransmissionProvider newOffers) { if (newOffers != offers) { NotificationChain msgs = null; if (offers != null) msgs = ((InternalEObject)offers).eInverseRemove(this, FinancialPackage.TRANSMISSION_PROVIDER__OFFERED_BY, TransmissionProvider.class, msgs); if (newOffers != null) msgs = ((InternalEObject)newOffers).eInverseAdd(this, FinancialPackage.TRANSMISSION_PROVIDER__OFFERED_BY, TransmissionProvider.class, msgs); msgs = basicSetOffers(newOffers, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ReservationPackage.TRANSMISSION_SERVICE__OFFERS, newOffers, newOffers)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ReservationPackage.TRANSMISSION_SERVICE__OFFERING: return ((InternalEList<InternalEObject>)(InternalEList<?>)getOffering()).basicAdd(otherEnd, msgs); case ReservationPackage.TRANSMISSION_SERVICE__OFFERED_AS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getOfferedAs()).basicAdd(otherEnd, msgs); case ReservationPackage.TRANSMISSION_SERVICE__SCHEDULED_BY: return ((InternalEList<InternalEObject>)(InternalEList<?>)getScheduledBy()).basicAdd(otherEnd, msgs); case ReservationPackage.TRANSMISSION_SERVICE__RESERVED_BY_SERVICE_RESERVATION: return ((InternalEList<InternalEObject>)(InternalEList<?>)getReservedBy_ServiceReservation()).basicAdd(otherEnd, msgs); case ReservationPackage.TRANSMISSION_SERVICE__TRANS_CONTRACT_FOR: if (transContractFor != null) msgs = ((InternalEObject)transContractFor).eInverseRemove(this, FinancialPackage.OPEN_ACCESS_PRODUCT__PROVIDED_BY_TRANSMISSION_SERVICE, OpenAccessProduct.class, msgs); return basicSetTransContractFor((OpenAccessProduct)otherEnd, msgs); case ReservationPackage.TRANSMISSION_SERVICE__OFFERS: if (offers != null) msgs = ((InternalEObject)offers).eInverseRemove(this, FinancialPackage.TRANSMISSION_PROVIDER__OFFERED_BY, TransmissionProvider.class, msgs); return basicSetOffers((TransmissionProvider)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ReservationPackage.TRANSMISSION_SERVICE__OFFERING: return ((InternalEList<?>)getOffering()).basicRemove(otherEnd, msgs); case ReservationPackage.TRANSMISSION_SERVICE__OFFERED_AS: return ((InternalEList<?>)getOfferedAs()).basicRemove(otherEnd, msgs); case ReservationPackage.TRANSMISSION_SERVICE__SCHEDULED_BY: return ((InternalEList<?>)getScheduledBy()).basicRemove(otherEnd, msgs); case ReservationPackage.TRANSMISSION_SERVICE__RESERVED_BY_SERVICE_RESERVATION: return ((InternalEList<?>)getReservedBy_ServiceReservation()).basicRemove(otherEnd, msgs); case ReservationPackage.TRANSMISSION_SERVICE__TRANS_CONTRACT_FOR: return basicSetTransContractFor(null, msgs); case ReservationPackage.TRANSMISSION_SERVICE__OFFERS: return basicSetOffers(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ReservationPackage.TRANSMISSION_SERVICE__OFFERING: return getOffering(); case ReservationPackage.TRANSMISSION_SERVICE__OFFERED_AS: return getOfferedAs(); case ReservationPackage.TRANSMISSION_SERVICE__SCHEDULED_BY: return getScheduledBy(); case ReservationPackage.TRANSMISSION_SERVICE__RESERVED_BY_SERVICE_RESERVATION: return getReservedBy_ServiceReservation(); case ReservationPackage.TRANSMISSION_SERVICE__TRANS_CONTRACT_FOR: if (resolve) return getTransContractFor(); return basicGetTransContractFor(); case ReservationPackage.TRANSMISSION_SERVICE__OFFERS: if (resolve) return getOffers(); return basicGetOffers(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ReservationPackage.TRANSMISSION_SERVICE__OFFERING: getOffering().clear(); getOffering().addAll((Collection<? extends TransmissionPath>)newValue); return; case ReservationPackage.TRANSMISSION_SERVICE__OFFERED_AS: getOfferedAs().clear(); getOfferedAs().addAll((Collection<? extends TransmissionProduct>)newValue); return; case ReservationPackage.TRANSMISSION_SERVICE__SCHEDULED_BY: getScheduledBy().clear(); getScheduledBy().addAll((Collection<? extends AvailableTransmissionCapacity>)newValue); return; case ReservationPackage.TRANSMISSION_SERVICE__RESERVED_BY_SERVICE_RESERVATION: getReservedBy_ServiceReservation().clear(); getReservedBy_ServiceReservation().addAll((Collection<? extends ServiceReservation>)newValue); return; case ReservationPackage.TRANSMISSION_SERVICE__TRANS_CONTRACT_FOR: setTransContractFor((OpenAccessProduct)newValue); return; case ReservationPackage.TRANSMISSION_SERVICE__OFFERS: setOffers((TransmissionProvider)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ReservationPackage.TRANSMISSION_SERVICE__OFFERING: getOffering().clear(); return; case ReservationPackage.TRANSMISSION_SERVICE__OFFERED_AS: getOfferedAs().clear(); return; case ReservationPackage.TRANSMISSION_SERVICE__SCHEDULED_BY: getScheduledBy().clear(); return; case ReservationPackage.TRANSMISSION_SERVICE__RESERVED_BY_SERVICE_RESERVATION: getReservedBy_ServiceReservation().clear(); return; case ReservationPackage.TRANSMISSION_SERVICE__TRANS_CONTRACT_FOR: setTransContractFor((OpenAccessProduct)null); return; case ReservationPackage.TRANSMISSION_SERVICE__OFFERS: setOffers((TransmissionProvider)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ReservationPackage.TRANSMISSION_SERVICE__OFFERING: return offering != null && !offering.isEmpty(); case ReservationPackage.TRANSMISSION_SERVICE__OFFERED_AS: return offeredAs != null && !offeredAs.isEmpty(); case ReservationPackage.TRANSMISSION_SERVICE__SCHEDULED_BY: return scheduledBy != null && !scheduledBy.isEmpty(); case ReservationPackage.TRANSMISSION_SERVICE__RESERVED_BY_SERVICE_RESERVATION: return reservedBy_ServiceReservation != null && !reservedBy_ServiceReservation.isEmpty(); case ReservationPackage.TRANSMISSION_SERVICE__TRANS_CONTRACT_FOR: return transContractFor != null; case ReservationPackage.TRANSMISSION_SERVICE__OFFERS: return offers != null; } return super.eIsSet(featureID); } } //TransmissionServiceImpl
mit