file_id
int64
1
250k
content
stringlengths
0
562k
repo
stringlengths
6
115
path
stringlengths
1
147
249,331
package water.api; import hex.*; import hex.DGLM.*; import hex.DLSM.ADMMSolver; import hex.DLSM.GeneralizedGradientSolver; import hex.DLSM.LSMSolver; import hex.DLSM.LSMSolverType; import hex.NewRowVecTask.DataFrame; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DecimalFormat; import java.util.*; import java.util.Map.Entry; import water.*; import water.api.RequestBuilders.KeyElementBuilder; import water.api.RequestBuilders.Response; import water.util.RString; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class GLM extends Request { protected final H2OHexKey _key = new H2OHexKey(KEY); protected final H2OHexKeyCol _y = new H2OHexKeyCol(Y, _key); protected final HexColumnSelect _x = new HexNonConstantColumnSelect(X, _key, _y); protected final H2OGLMModelKey _modelKey = new H2OGLMModelKey(MODEL_KEY,false); protected final EnumArgument<Family> _family = new EnumArgument(FAMILY,Family.gaussian,true); protected final LinkArg _link = new LinkArg(_family,LINK); protected final Real _lambda = new Real(LAMBDA, 1e-5); // TODO I do not know the bounds protected final Real _alpha = new Real(ALPHA, 0.5, 0, 1, ""); protected final Real _caseWeight = new Real(WEIGHT,1.0); protected final CaseModeSelect _caseMode = new CaseModeSelect(_key,_y,_family, CASE_MODE,CaseMode.none); protected final CaseSelect _case = new CaseSelect(_key,_y,_caseMode,CASE); protected final Int _xval = new Int(XVAL, 10, 0, 1000000); protected final Bool _expertSettings = new Bool("expert_settings", false,"Show expert settings."); // ------------------------------------- ADVANCED SETTINGS ------------------------------------------------------------------------------------ protected final Bool _standardize = new Bool("standardize", true, "Set to standardize (0 mean, unit variance) the data before training."); protected final RSeq _thresholds = new RSeq(DTHRESHOLDS, false, new NumberSequence("0:1:0.01", false, 0.01),false); protected final EnumArgument<LSMSolverType> _lsmSolver = new EnumArgument<LSMSolverType>("lsm_solver", LSMSolverType.AUTO); protected final Real _betaEps = new Real(BETA_EPS,1e-4); protected final Int _maxIter = new Int(MAX_ITER, 50, 1, 1000000); //protected final Bool _reweightGram = new Bool("reweigthed_gram_xval", false, "Set to force reweighted gram matrix for cross-validation (non-reweighted xval is much faster, less precise)."); public GLM() { _requestHelp = "Compute generalized linear model with penalized maximum likelihood. Penalties include the lasso (L1 penalty), ridge regression (L2 penalty) or elastic net penalty (combination of L1 and L2) penalties. The penalty function is defined as :<br/>" + "<pre>\n" + " P(&beta;) = 0.5*(1 - &alpha;)*||&beta;||<sub>2</sub><sup>2</sup> + &alpha;*||&beta;||<sub>1</sub><br/>"+ "</pre>" + "By setting &alpha; to 0, we get ridge regression, setting it to 1 gets us lasso. <p>See our <a href='https://github.com/0xdata/h2o/wiki/GLM#wiki-Details' target=\"_blank\">wiki</a> for details.<p>"; _key._requestHelp = "Dataset to be trained on."; _y._requestHelp = "Response variable column name."; _x._requestHelp = "Predictor columns to be trained on. Constant columns will be ignored."; _modelKey._hideInQuery = true; _modelKey._requestHelp = "The H2O's Key name for the model"; _family._requestHelp = "Pick the general mathematical family for the trained model.<br><ul>"+ "<li><b>gaussian</b> models describe a simple hyper-plane (for a single column this will be a simple line) for the response variable. This is a suitable model for when you expect the response variable to vary as a linear combination of predictor variables. An example might be predicting the gas mileage of cars, based on their weight, age, and engine size.</li>"+ "<li><b>binomial</b> models form an S-curve response, showing probabilities that vary from 0 to 1. This is a suitable model for when you expect a simple boolean result (e.g. alive/dead, or fraud/no-fraud). The model gives a probability of the true event. An example might be to predict the presence of prostate cancer given the patient age, race, and various blood chemical levels such as PSA.</li>"+ "</ul>"; _link._requestHelp = "Link function to be used."; _lambda._requestHelp = "Penalty argument. Higher lambda means higher penalty is applied on the size of the beta vector."; _alpha._requestHelp = "Penalty distribution argument. Controls distribution of penalty between L1 and L2 norm according to the formula above."; _betaEps._requestHelp = "Precision of the vector of coefficients. Computation stops when the maximal difference between two beta vectors is below than Beta epsilon."; _maxIter._requestHelp = "Number of maximum iterations."; _caseWeight._requestHelp = "All rows for which the predicate is true will be weighted by weight. Weight=1 is neutral. Weight = 0.5 treats negative examples as twice more important than positive ones. Weight = 2.0 does the opposite."; _caseMode._requestHelp = "Predicate selection."; _case._requestHelp = "Value to be used to compare against using predicate given by case mode selector to turn the y column into boolean."; _thresholds._requestHelp = "Sequence of decision thresholds to be evaluated during validation (used for ROC curce computation and for picking optimal decision threshold of the resulting classifier)."; _xval._requestHelp = "Number of fold used in cross-validation. 0 or 1 means no cross validation."; _expertSettings.setRefreshOnChange(); } public static String link(Key k, String content) { RString rs = new RString("<a href='GLM.query?%key_param=%$key'>%content</a>"); rs.replace("key_param", KEY); rs.replace("key", k.toString()); rs.replace("content", content); return rs.toString(); } static void getColumnIdxs(StringBuilder sb, ValueArray ary, String [] cols ){ Arrays.sort(cols); boolean firstCol = false; for(int i = 0; i < ary._cols.length; ++i) if(Arrays.binarySearch(cols, ary._cols[i]._name) >= 0) if(firstCol){ sb.append(""+i); firstCol = false; } else sb.append(","+i); } public static String link(Key k, GLMModel m, String content) { int [] colIds = m.selectedColumns(); if(colIds == null)return ""; /// the dataset is no longer on H2O, no link shoudl be produced! try { StringBuilder sb = new StringBuilder("<a href='GLM.query?"); sb.append(KEY + "=" + k.toString()); sb.append("&y=" + m.responseName()); // find the column idxs...(the model keeps only names) sb.append("&x=" + colIds[0]); for(int i = 1; i < colIds.length-1; ++i) sb.append(","+colIds[i]); sb.append("&family=" + m._glmParams._family.toString()); sb.append("&link=" + m._glmParams._link.toString()); sb.append("&lambda=" + m._solver._lambda); sb.append("&alpha=" + m._solver._alpha); sb.append("&beta_eps=" + m._glmParams._betaEps); sb.append("&weight=" + m._glmParams._caseWeight); sb.append("&max_iter=" + m._glmParams._maxIter); sb.append("&caseMode=" + URLEncoder.encode(m._glmParams._caseMode.toString(),"utf8")); sb.append("&case=" + m._glmParams._caseVal); sb.append("'>" + content + "</a>"); return sb.toString(); } catch( UnsupportedEncodingException e ) { throw new RuntimeException(e); } } @Override protected void queryArgumentValueSet(Argument arg, Properties inputArgs) { if(arg == _caseMode){ if(_caseMode.value() == CaseMode.none) _case.disable("n/a"); } else if (arg == _family) { if (_family.value() != Family.binomial) { _case.disable("Only for family binomial"); _caseMode.disable("Only for family binomial"); _caseWeight.disable("Only for family binomial"); _thresholds.disable("Only for family binomial"); } } else if (arg == _expertSettings){ if(_expertSettings.value()){ _lsmSolver._hideInQuery = false; _thresholds._hideInQuery = false; _maxIter._hideInQuery = false; _betaEps._hideInQuery = false; //_reweightGram._hideInQuery = false; _standardize._hideInQuery = false; } else { _lsmSolver._hideInQuery = true; _thresholds._hideInQuery = true; _maxIter._hideInQuery = true; _betaEps._hideInQuery = true; //_reweightGram._hideInQuery = true; _standardize._hideInQuery = true; } } } /** Returns an array of columns to use for GLM, the last of them being the * result column y. */ private int[] createColumns() { BitSet cols = new BitSet(); for( int i : _x.value() ) cols.set (i); //for( int i : _negX.value() ) cols.clear(i); int[] res = new int[cols.cardinality()+1]; int x=0; for( int i = cols.nextSetBit(0); i >= 0; i = cols.nextSetBit(i+1)) res[x++] = i; res[x] = _y.value(); return res; } static JsonObject getCoefficients(int [] columnIds, ValueArray ary, double [] beta){ JsonObject coefficients = new JsonObject(); for( int i = 0; i < beta.length; ++i ) { String colName = (i == (beta.length - 1)) ? "Intercept" : ary._cols[columnIds[i]]._name; coefficients.addProperty(colName, beta[i]); } return coefficients; } GLMParams getGLMParams(){ GLMParams res = new GLMParams(_family.value(),_link.value()); if( res._link == Link.familyDefault ) res._link = res._family.defaultLink; res._maxIter = _maxIter.value(); res._betaEps = _betaEps.value(); if(_caseWeight.valid()) res._caseWeight = _caseWeight.value(); if(_case.valid()) res._caseVal = _case.value(); res._caseMode = _caseMode.valid()?_caseMode.value():CaseMode.none; return res; } @Override protected Response serve() { try { JsonObject res = new JsonObject(); ValueArray ary = _key.value(); int[] columns = createColumns(); res.addProperty("key", ary._key.toString()); res.addProperty("h2o", H2O.SELF.toString()); GLMParams glmParams = getGLMParams(); DataFrame data = DGLM.getData(ary, columns, null, _standardize.value()); LSMSolver lsm = null; switch(_lsmSolver.value()){ case AUTO: lsm = //data.expandedSz() < 1000? new ADMMSolver(_lambda.value(),_alpha.value());//: //new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); break; case ADMM: lsm = new ADMMSolver(_lambda.value(),_alpha.value()); break; case GenGradient: lsm = new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); } GLMJob job = DGLM.startGLMJob(data, lsm, glmParams, null, _xval.value(), true); JsonObject j = new JsonObject(); j.addProperty(Constants.DEST_KEY, job.dest().toString()); Response r = GLMProgressPage.redirect(j, job.self(), job.dest(),job.progressKey()); r.setBuilder(Constants.DEST_KEY, new KeyElementBuilder()); return r; }catch(GLMException e){ return Response.error(e.getMessage()); } catch (Throwable t) { t.printStackTrace(); return Response.error(t.getMessage()); } } }
alixaxel/h2o
src/main/java/water/api/GLM.java
249,332
package nachos.threads; import java.util.*; import nachos.machine.*; /** * A <i>GameMatch</i> groups together player threads of the same * ability into fixed-sized groups to play matches with each other. * Implement the class <i>GameMatch</i> using <i>Lock</i> and * <i>Condition</i> to synchronize player threads into groups. */ public class GameMatch { private Condition2 beginnerCV; private Condition2 intermediateCV; private Condition2 expertCV; private static int matchIndex; private static int numPlayersInMatch; private static int beginnerSize; private static int intermediateSize; private static int expertSize; private static Lock beginnerLock; private static Lock intermediateLock; private static Lock expertLock; private static HashMap<KThread, Integer> matchMap; /* Three levels of player ability. */ public static final int abilityBeginner = 1, abilityIntermediate = 2, abilityExpert = 3; /** * Allocate a new GameMatch specifying the number of player * threads of the same ability required to form a match. Your * implementation may assume this number is always greater than zero. */ public GameMatch (int numPlayersInMatch) { beginnerLock = new Lock(); intermediateLock = new Lock(); expertLock = new Lock(); beginnerCV = new Condition2(beginnerLock); intermediateCV = new Condition2(intermediateLock); expertCV = new Condition2(expertLock); this.beginnerSize = 0; this.intermediateSize = 0; this.expertSize = 0; this.matchIndex = 1; this.numPlayersInMatch = numPlayersInMatch; this.matchMap = new HashMap<>(); } /** * Wait for the required number of player threads of the same * ability to form a game match, and only return when a game match * is formed. Many matches may be formed over time, but any one * player thread can be assigned to only one match. * * Returns the match number of the formed match. The first match * returned has match number 1, and every subsequent match * increments the match number by one, independent of ability. No * two matches should have the same match number, match numbers * should be strictly monotonically increasing, and there should * be no gaps between match numbers. * * @param ability should be one of abilityBeginner, abilityIntermediate, * or abilityExpert; return -1 otherwise. */ public int play (int ability) { // block for beginner ability if (ability == 1) { // for each thread, acquire the lock first beginnerLock.acquire(); // increment the value of the queue size beginnerSize++; // remember the match number for each thread matchMap.put(KThread.currentThread(), matchIndex); // if the queue.size() equals to the required number of players if (beginnerSize == numPlayersInMatch) { // increment the match number matchIndex++; System.out.println(KThread.currentThread().getName() + " Thread is calling wakeAll()"); // wake up all the previous thread beginnerCV.wakeAll(); // reset the queue size to zero beginnerSize = 0; } // if the queue.size() does not equal to the number of players else { System.out.println(KThread.currentThread().getName() + " Thread is sleeping"); // put the current thread to sleep beginnerCV.sleep(); } // release the lock beginnerLock.release(); } // block for intermediate ability if (ability == 2) { intermediateLock.acquire(); intermediateSize++; matchMap.put(KThread.currentThread(), matchIndex); if (intermediateSize == numPlayersInMatch) { matchIndex++; System.out.println(KThread.currentThread().getName() + " Thread is calling wakeAll()"); intermediateCV.wakeAll(); intermediateSize = 0; } else { System.out.println(KThread.currentThread().getName() + " Thread is sleeping"); intermediateCV.sleep(); } intermediateLock.release(); } // block for expert ability if (ability == 3) { expertLock.acquire(); expertSize++; matchMap.put(KThread.currentThread(), matchIndex); if (expertSize == numPlayersInMatch) { matchIndex++; System.out.println(KThread.currentThread().getName() + " Thread is calling wakeAll()"); expertCV.wakeAll(); expertSize = 0; } else { System.out.println(KThread.currentThread().getName() + " Thread is sleeping"); expertCV.sleep(); } expertLock.release(); } return matchMap.get(KThread.currentThread()); } // Place GameMatch test code inside of the GameMatch class. public static void matchTest4 () { final GameMatch match = new GameMatch(4); // Instantiate the threads KThread beg1 = new KThread( new Runnable () { public void run() { int r = match.play(GameMatch.abilityBeginner); System.out.println ("beg1 matched"+ ", match number: " + r); // beginners should match with a match number of 1 // Lib.assertTrue(r == 1, "expected match number of 1"); } }); beg1.setName("B1"); KThread beg2 = new KThread( new Runnable () { public void run() { int r = match.play(GameMatch.abilityBeginner); System.out.println ("beg2 matched" +", match number: " + r); // beginners should match with a match number of 1 // Lib.assertTrue(r == 1, "expected match number of 1"); } }); beg2.setName("B2"); KThread beg3 = new KThread( new Runnable () { public void run() { int r = match.play(GameMatch.abilityBeginner); System.out.println ("beg3 matched" + ", match number: " + r); // beginners should match with a match number of 2 // Lib.assertTrue(r == 2, "expected match number of 2"); } }); beg3.setName("B3"); KThread beg4 = new KThread( new Runnable () { public void run() { int r = match.play(GameMatch.abilityBeginner); System.out.println ("beg4 matched"+ ", match number: " + r); // beginners should match with a match number of 2 // Lib.assertTrue(r == 2, "expected match number of 2"); } }); beg4.setName("B4"); KThread beg5 = new KThread( new Runnable () { public void run() { int r = match.play(GameMatch.abilityExpert); System.out.println ("beg5 matched"+ ", match number: " + r); // beginners should match with a match number of 2 // Lib.assertTrue(r == 2, "expected match number of 2"); } }); beg5.setName("B5"); KThread beg6 = new KThread( new Runnable () { public void run() { int r = match.play(GameMatch.abilityIntermediate); System.out.println ("beg6 matched"+ ", match number: " + r); // beginners should match with a match number of 2 // Lib.assertTrue(r == 2, "expected match number of 2"); } }); beg6.setName("B6"); /* KThread int1 = new KThread( new Runnable () { public void run() { int r = match.play(GameMatch.abilityIntermediate); Lib.assertNotReached("int1 should not have matched!"); } }); int1.setName("I1"); KThread exp1 = new KThread( new Runnable () { public void run() { int r = match.play(GameMatch.abilityExpert); Lib.assertNotReached("exp1 should not have matched!"); } }); exp1.setName("E1");*/ // Run the threads. The beginner threads should successfully // form a match, the other threads should not. The outcome // should be the same independent of the order in which threads // are forked. beg1.fork(); // match 1 // int1.fork(); // exp1.fork(); beg2.fork(); // match 1 beg3.fork(); // match 2 beg4.fork(); // match 2 beg5.fork(); beg6.fork(); // Assume join is not implemented, use yield to allow other // threads to run for (int i = 0; i < 10000; i++) { KThread.currentThread().yield(); } } public static void selfTest() { matchTest4(); } }
cpwang96/Nachos
threads/GameMatch.java
249,333
package by.ai; import java.util.List; import java.util.Scanner; /** * Класс экспертной системы по определению * объекта по его характеристикам. * Система спрашивает у пользователя имеет ли * загаданный объект выбранную характеристику. * Пользователь отвечает и система на основе * его ответа делает заключения об объекте. */ class ExpertSystem { /** * Матрица элементов экспертной системы. * Содержит объекты класса {@link Element} * @see Element */ private Element[][] system; ExpertSystem() { } /** * Считывает данные из файлов и заполняет ими * матрицу экспертной системы. * * @param objFilename имя файла * @param charFilename имя файла * @param matrixFilename имя файла */ void fillSystemWithData(String objFilename, String charFilename, String matrixFilename) { FileReaderUtil fileReaderUtil = new FileReaderUtil(); List<String> objects = fileReaderUtil.getWordsFromFile(objFilename); List<String> chars = fileReaderUtil.getWordsFromFile(charFilename); int rows = chars.size(); int columns = objects.size(); int[][] matrix = fileReaderUtil.getMatrixFromFile(matrixFilename, rows, columns); system = new Element[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { Element element = new Element(); element.setCharacteristic(chars.get(i)); element.setObject(objects.get(j)); element.setValue(matrix[i][j]); system[i][j] = element; } } } /** * Задаёт вопрос о наличии характеристики у объекта пользователя. * Перед этим удаляет все пустые строки (характеристики, * которых нет ни у одного объекта). * Если пользователь отвечает 'Да', то удаляет все * объекты, которые не имеют данной характеристики. * Если пользователь отвечает 'Нет', то удаляет данную характеристику. * После этого вызывает функцию заново. * Если в матрице остался только один объект, то * система даёт ответ. */ void askQuestion() { if(system[0].length == 1) { System.out.println("Your object is " + system[0][0].getObject()); return; } deleteEmptyRows(); printTable(); Scanner in = new Scanner(System.in); int rowIndex = findMinRow(); String aChar = system[rowIndex][0].getCharacteristic(); System.out.println("Does it have " + aChar + "?"); System.out.print("Yes(1)/No(0): "); int answer = in.nextInt(); if (answer != 0) { deleteUnsuitableObjects(rowIndex); askQuestion(); } else { deleteUnsuitableObjectsAndChar(rowIndex); askQuestion(); } } /** * Выводит матрицу с объектами и * характеристиками в консоль. */ private void printTable() { System.out.println("_____________________________"); System.out.print(" "); for (int j = 0; j < system[0].length; j++) { System.out.print(system[0][j].getObject() + " "); } System.out.println(); for (Element[] aChar : system) { System.out.print(aChar[0].getCharacteristic() + " "); for (Element el : aChar) { System.out.print(el.getValue() + " "); } System.out.println(); } System.out.println("_____________________________"); } /** * Удаляет объекты из матрицы, которые не имееют * характеристику под заданным индексом. * * @param charIndex индекс характеристики */ private void deleteUnsuitableObjects(int charIndex) { int columnsNumber = system[charIndex].length; int iterator = 0; int j = 0; while(iterator != columnsNumber) { if (system[charIndex][j].getValue() == 0) { deleteColumn(j); } else { j++; } iterator++; } } /** * Удаляет заданную характеристику и объекты, * которые её имеют. * * @param charIndex индекс характеристики */ private void deleteUnsuitableObjectsAndChar(int charIndex) { int columnsNumber = system[charIndex].length; int iterator = 0; int j = 0; while(iterator != columnsNumber) { if (system[charIndex][j].getValue() == 1) { deleteColumn(j); } else { j++; } iterator++; } deleteRow(charIndex); } /** * Удаляет пустые строки в матрице. * Пустая строка та, если все элементы в ней * имею значение 0 в поле {@link Element#value}. */ private void deleteEmptyRows() { int i; while (true) { i = findEmptyRow(); if (i == -1) { break; } else { deleteRow(i); } } } /** * Удаляет строку в матрице по её индексу. * * @param deli индекс строки матрицы */ private void deleteRow(int deli) { int rows = system.length - 1; int columns = system[0].length; Element[][] newMatrix = new Element[rows][columns]; for (int i = 0, ln = 0; ln < rows; ) { if (i != deli) { for (int j = 0; j < columns; j++) { newMatrix[ln][j] = system[i][j]; } i++; ln++; } else { i++; } } system = newMatrix; } /** * Удаляет столбец в матрице по его индексу * * @param delj индекс столбца матрицы */ private void deleteColumn(int delj) { int rows = system.length; int columns = system[0].length - 1; Element[][] newMatrix = new Element[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0, cn = 0; cn < columns; j++, cn++) { if (j == delj) { j++; } newMatrix[i][cn] = system[i][j]; } } system = newMatrix; } /** * Находит строку с нулевыми значениями поля * {@link Element#value}. * * @return индекс пустой строки */ private int findEmptyRow() { int indexOfEmpty = -1; boolean isEmpty; for (int i = 0; i < system.length; i++) { isEmpty = true; for (int j = 0; j < system[i].length; j++) { if (system[i][j].getValue() == 1) { isEmpty = false; } } if (isEmpty) { indexOfEmpty = i; } } return indexOfEmpty; } /** * Находит индекс минимального элемента * в строке матрицы. * * @return индекс минимального элемента */ private int findMinRow() { int[] sumValues = new int[system.length]; int sum; for (int i = 0; i < system.length; i++) { sum = 0; for (int j = 0; j < system[i].length; j++) { sum += system[i][j].getValue(); } sumValues[i] = sum; } int minSum = findMinValue(sumValues); int indexOfMin = -1; for (int i = 0; i < system.length; i++) { sum = 0; for (int j = 0; j < system[i].length; j++) { sum += system[i][j].getValue(); } if (minSum == sum) { indexOfMin = i; break; } } return indexOfMin; } /** * Находит минимальный элемент в * целочисленном массиве. * * @param arr одномерный целочисленный массив * @return целое число */ private int findMinValue(int[] arr) { int min = arr[0]; for (int el : arr) { if (el < min) { min = el; } } return min; } }
AlaskanHusky/expert-system
src/by/ai/ExpertSystem.java
249,334
package water.api; import hex.*; import hex.DGLM.CaseMode; import hex.DGLM.Family; import hex.DGLM.GLMException; import hex.DGLM.GLMJob; import hex.DGLM.GLMModel; import hex.DGLM.GLMParams; import hex.DGLM.Link; import hex.DGLM.LinkIced; import hex.DLSM.ADMMSolver; import hex.DLSM.GeneralizedGradientSolver; import hex.DLSM.LSMSolver; import hex.DLSM.LSMSolverType; import hex.NewRowVecTask.DataFrame; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; import water.*; import water.util.Log; import water.util.RString; import com.google.gson.JsonObject; public class GLM extends Request { protected final H2OKey _dest = new H2OKey(DEST_KEY, false, true); protected final H2OHexKey _key = new H2OHexKey(KEY); protected final H2OHexKeyCol _y = new H2OHexKeyCol(Y, _key); protected final HexColumnSelect _x = new HexNonConstantColumnSelect(X, _key, _y); protected final H2OGLMModelKey _modelKey = new H2OGLMModelKey(MODEL_KEY,false); protected final EnumArgument<Family> _family = new EnumArgument(FAMILY,Family.gaussian,true); protected final LinkArg _link = new LinkArg(_family,LINK); protected final Real _lambda = new Real(LAMBDA, 1e-5); // TODO I do not know the bounds protected final Real _alpha = new Real(ALPHA, 0.5, 0, 1, ""); protected final Real _caseWeight = new Real(WEIGHT,1.0); protected final Real _tweediePower = new Real(TWEEDIE_POWER, 1.5); protected final CaseModeSelect _caseMode = new CaseModeSelect(_key,_y,_family, CASE_MODE,CaseMode.none); protected final CaseSelect _case = new CaseSelect(_key,_y,_caseMode,CASE); protected final Int _xval = new Int(XVAL, 10, 0, 1000000); protected final Bool _expertSettings = new Bool("expert_settings", true ,"Show expert settings."); // ------------------------------------- ADVANCED SETTINGS ------------------------------------------------------------------------------------ protected final Bool _standardize = new Bool("standardize", true, "Set to standardize (0 mean, unit variance) the data before training."); protected final RSeq _thresholds = new RSeq(DTHRESHOLDS, false, new NumberSequence("0:1:0.01", false, 0.01),false); protected final EnumArgument<LSMSolverType> _lsmSolver = new EnumArgument<LSMSolverType>("lsm_solver", LSMSolverType.AUTO); protected final Real _betaEps = new Real(BETA_EPS,1e-4); protected final Int _maxIter = new Int(MAX_ITER, 50, 1, 1000000); //protected final Bool _reweightGram = new Bool("reweigthed_gram_xval", false, "Set to force reweighted gram matrix for cross-validation (non-reweighted xval is much faster, less precise)."); public GLM() { _requestHelp = "Compute generalized linear model with penalized maximum likelihood. Penalties include the lasso (L1 penalty), ridge regression (L2 penalty) or elastic net penalty (combination of L1 and L2) penalties. The penalty function is defined as :<br/>" + "<pre>\n" + " P(&beta;) = 0.5*(1 - &alpha;)*||&beta;||<sub>2</sub><sup>2</sup> + &alpha;*||&beta;||<sub>1</sub><br/>"+ "</pre>" + "By setting &alpha; to 0, we get ridge regression, setting it to 1 gets us lasso. <p>See our <a href='https://github.com/0xdata/h2o/wiki/GLM#wiki-Details' target=\"_blank\">wiki</a> for details.<p>"; _key._requestHelp = "Dataset to be trained on."; _y._requestHelp = "Response variable column name."; _x._requestHelp = "Predictor columns to be trained on. Constant columns will be ignored."; _modelKey._hideInQuery = true; _modelKey._requestHelp = "The H2O's Key name for the model"; _family._requestHelp = "Pick the general mathematical family for the trained model.<br><ul>"+ "<li><b>gaussian</b> models describe a simple hyper-plane (for a single column this will be a simple line) for the response variable. This is a suitable model for when you expect the response variable to vary as a linear combination of predictor variables. An example might be predicting the gas mileage of cars, based on their weight, age, and engine size.</li>"+ "<li><b>binomial</b> models form an S-curve response, showing probabilities that vary from 0 to 1. This is a suitable model for when you expect a simple boolean result (e.g. alive/dead, or fraud/no-fraud). The model gives a probability of the true event. An example might be to predict the presence of prostate cancer given the patient age, race, and various blood chemical levels such as PSA.</li>"+ "</ul>"; _link._requestHelp = "Link function to be used."; _lambda._requestHelp = "Penalty argument. Higher lambda means higher penalty is applied on the size of the beta vector."; _alpha._requestHelp = "Penalty distribution argument. Controls distribution of penalty between L1 and L2 norm according to the formula above."; _betaEps._requestHelp = "Precision of the vector of coefficients. Computation stops when the maximal difference between two beta vectors is below than Beta epsilon."; _maxIter._requestHelp = "Number of maximum iterations."; _caseWeight._requestHelp = "All rows for which the predicate is true will be weighted by weight. Weight=1 is neutral. Weight = 0.5 treats negative examples as twice more important than positive ones. Weight = 2.0 does the opposite."; _caseMode._requestHelp = "Predicate selection."; _case._requestHelp = "Value to be used to compare against using predicate given by case mode selector to turn the y column into boolean."; _thresholds._requestHelp = "Sequence of decision thresholds to be evaluated during validation (used for ROC curce computation and for picking optimal decision threshold of the resulting classifier)."; _xval._requestHelp = "Number of fold used in cross-validation. 0 or 1 means no cross validation."; _expertSettings.setRefreshOnChange(); } public static String link(Key k, String content) { RString rs = new RString("<a href='GLM.query?%key_param=%$key'>%content</a>"); rs.replace("key_param", KEY); rs.replace("key", k.toString()); rs.replace("content", content); return rs.toString(); } static void getColumnIdxs(StringBuilder sb, ValueArray ary, String [] cols ){ Arrays.sort(cols); boolean firstCol = false; for(int i = 0; i < ary._cols.length; ++i) if(Arrays.binarySearch(cols, ary._cols[i]._name) >= 0) if(firstCol){ sb.append(""+i); firstCol = false; } else sb.append(","+i); } public static String link(Key k, GLMModel m, String content) { int [] colIds = m.selectedColumns(); if(colIds == null)return ""; /// the dataset is no longer on H2O, no link shoudl be produced! try { StringBuilder sb = new StringBuilder("<a href='GLM.query?"); sb.append(KEY + "=" + k.toString()); sb.append("&y=" + m.responseName()); // find the column idxs...(the model keeps only names) sb.append("&x=" + colIds[0]); for(int i = 1; i < colIds.length-1; ++i) sb.append(","+colIds[i]); sb.append("&family=" + m._glmParams._family._family.toString()); sb.append("&tweedie_power=" + m._glmParams._family._tweedieVariancePower); sb.append("&link=" + m._glmParams._link._link.toString()); sb.append("&lambda=" + m._solver._lambda); sb.append("&alpha=" + m._solver._alpha); sb.append("&beta_eps=" + m._glmParams._betaEps); sb.append("&weight=" + m._glmParams._caseWeight); sb.append("&max_iter=" + m._glmParams._maxIter); sb.append("&caseMode=" + URLEncoder.encode(m._glmParams._caseMode.toString(),"utf8")); sb.append("&case=" + m._glmParams._caseVal); sb.append("'>" + content + "</a>"); return sb.toString(); } catch( UnsupportedEncodingException e ) { throw Log.errRTExcept(e); } } @Override protected void queryArgumentValueSet(Argument arg, Properties inputArgs) { if(arg == _caseMode){ if(_caseMode.value() == CaseMode.none) _case.disable("n/a"); } else if (arg == _family) { if (_family.value() != Family.binomial) { _case.disable("Only for family binomial"); _caseMode.disable("Only for family binomial"); _caseWeight.disable("Only for family binomial"); _thresholds.disable("Only for family binomial"); } if (_family.value() != Family.tweedie){ _tweediePower.disable("Only for family tweedie"); } } else if (arg == _expertSettings){ if(_expertSettings.value()){ _lsmSolver._hideInQuery = false; _thresholds._hideInQuery = false; _maxIter._hideInQuery = false; _betaEps._hideInQuery = false; //_reweightGram._hideInQuery = false; _standardize._hideInQuery = false; } else { _lsmSolver._hideInQuery = true; _thresholds._hideInQuery = true; _maxIter._hideInQuery = true; _betaEps._hideInQuery = true; //_reweightGram._hideInQuery = true; _standardize._hideInQuery = true; } } } /** Returns an array of columns to use for GLM, the last of them being the * result column y. */ private int[] createColumns() { BitSet cols = new BitSet(); for( int i : _x.value() ) cols.set (i); //for( int i : _negX.value() ) cols.clear(i); int[] res = new int[cols.cardinality()+1]; int x=0; for( int i = cols.nextSetBit(0); i >= 0; i = cols.nextSetBit(i+1)) res[x++] = i; res[x] = _y.value(); return res; } static JsonObject getCoefficients(int [] columnIds, ValueArray ary, double [] beta){ JsonObject coefficients = new JsonObject(); for( int i = 0; i < beta.length; ++i ) { String colName = (i == (beta.length - 1)) ? "Intercept" : ary._cols[columnIds[i]]._name; coefficients.addProperty(colName, beta[i]); } return coefficients; } GLMParams getGLMParams(){ Family family = _family.value(); Link link = _link.value(); if( family == Family.tweedie && !(link == Link.tweedie || link == Link.familyDefault)){ return null; } GLMParams res; if (family != Family.tweedie) res = new GLMParams(_family.value(),_link.value()); else { double variancePower = _tweediePower.value(); //TODO let tweedie also control link power Link l = Link.tweedie; l.tweedieLinkPower = 1. - variancePower; Family f = Family.tweedie; f.defaultLink = l; f.tweedieVariancePower = variancePower; res = new GLMParams(f, l, f.tweedieVariancePower, l.tweedieLinkPower); } if( res._link._link == Link.familyDefault && res._link._link != Link.tweedie ) res._link = new LinkIced( res._family._family.defaultLink ); res._maxIter = _maxIter.value(); res._betaEps = _betaEps.value(); if(_caseWeight.valid()) res._caseWeight = _caseWeight.value(); if(_case.valid()) res._caseVal = _case.value(); res._caseMode = _caseMode.valid()?_caseMode.value():CaseMode.none; return res; } @Override protected Response serve() { try { JsonObject res = new JsonObject(); Key dest = _dest.value(); ValueArray ary = _key.value(); int[] columns = createColumns(); res.addProperty("key", ary._key.toString()); res.addProperty("h2o", H2O.SELF.toString()); GLMParams glmParams = getGLMParams(); if (glmParams == null){ if (_family.value() == Family.tweedie && _link.value() == Link.tweedie){ return Response.error("tweedie family requires tweedie link"); } return Response.error("error reading glm parameters"); } if (glmParams._family._family == Family.tweedie){ double p = _tweediePower.value(); if ( !(1. < p && p < 2.) ){ return Response.error("tweedie family specified but invalid tweedie power: must be in (1,2)"); } } DataFrame data = DGLM.getData(ary, columns, null, _standardize.value()); LSMSolver lsm = null; switch(_lsmSolver.value()){ case AUTO: lsm = //data.expandedSz() < 1000? new ADMMSolver(_lambda.value(),_alpha.value());//: //new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); break; case ADMM: lsm = new ADMMSolver(_lambda.value(),_alpha.value()); break; case GenGradient: lsm = new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); } GLMJob job = DGLM.startGLMJob(dest, data, lsm, glmParams, null, _xval.value(), true); JsonObject j = new JsonObject(); j.addProperty(Constants.DEST_KEY, job.dest().toString()); Response r = GLMProgressPage.redirect(j, job.self(), job.dest(),job.progressKey()); r.setBuilder(Constants.DEST_KEY, new KeyElementBuilder()); return r; } catch( Throwable t ) { return Response.error(t); } } }
blenderbox/h2o
src/main/java/water/api/GLM.java
249,335
package water.api; import hex.*; import hex.DGLM.*; import hex.DLSM.ADMMSolver; import hex.DLSM.GeneralizedGradientSolver; import hex.DLSM.LSMSolver; import hex.DLSM.LSMSolverType; import hex.NewRowVecTask.DataFrame; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DecimalFormat; import java.util.*; import java.util.Map.Entry; import water.*; import water.api.RequestBuilders.KeyElementBuilder; import water.api.RequestBuilders.Response; import water.util.Log; import water.util.RString; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class GLM extends Request { protected final H2OHexKey _key = new H2OHexKey(KEY); protected final H2OHexKeyCol _y = new H2OHexKeyCol(Y, _key); protected final HexColumnSelect _x = new HexNonConstantColumnSelect(X, _key, _y); protected final H2OGLMModelKey _modelKey = new H2OGLMModelKey(MODEL_KEY,false); protected final EnumArgument<Family> _family = new EnumArgument(FAMILY,Family.gaussian,true); protected final LinkArg _link = new LinkArg(_family,LINK); protected final Real _lambda = new Real(LAMBDA, 1e-5); // TODO I do not know the bounds protected final Real _alpha = new Real(ALPHA, 0.5, 0, 1, ""); protected final Real _caseWeight = new Real(WEIGHT,1.0); protected final CaseModeSelect _caseMode = new CaseModeSelect(_key,_y,_family, CASE_MODE,CaseMode.none); protected final CaseSelect _case = new CaseSelect(_key,_y,_caseMode,CASE); protected final Int _xval = new Int(XVAL, 10, 0, 1000000); protected final Bool _expertSettings = new Bool("expert_settings", false,"Show expert settings."); // ------------------------------------- ADVANCED SETTINGS ------------------------------------------------------------------------------------ protected final Bool _standardize = new Bool("standardize", true, "Set to standardize (0 mean, unit variance) the data before training."); protected final RSeq _thresholds = new RSeq(DTHRESHOLDS, false, new NumberSequence("0:1:0.01", false, 0.01),false); protected final EnumArgument<LSMSolverType> _lsmSolver = new EnumArgument<LSMSolverType>("lsm_solver", LSMSolverType.AUTO); protected final Real _betaEps = new Real(BETA_EPS,1e-4); protected final Int _maxIter = new Int(MAX_ITER, 50, 1, 1000000); //protected final Bool _reweightGram = new Bool("reweigthed_gram_xval", false, "Set to force reweighted gram matrix for cross-validation (non-reweighted xval is much faster, less precise)."); public GLM() { _requestHelp = "Compute generalized linear model with penalized maximum likelihood. Penalties include the lasso (L1 penalty), ridge regression (L2 penalty) or elastic net penalty (combination of L1 and L2) penalties. The penalty function is defined as :<br/>" + "<pre>\n" + " P(&beta;) = 0.5*(1 - &alpha;)*||&beta;||<sub>2</sub><sup>2</sup> + &alpha;*||&beta;||<sub>1</sub><br/>"+ "</pre>" + "By setting &alpha; to 0, we get ridge regression, setting it to 1 gets us lasso. <p>See our <a href='https://github.com/0xdata/h2o/wiki/GLM#wiki-Details' target=\"_blank\">wiki</a> for details.<p>"; _key._requestHelp = "Dataset to be trained on."; _y._requestHelp = "Response variable column name."; _x._requestHelp = "Predictor columns to be trained on. Constant columns will be ignored."; _modelKey._hideInQuery = true; _modelKey._requestHelp = "The H2O's Key name for the model"; _family._requestHelp = "Pick the general mathematical family for the trained model.<br><ul>"+ "<li><b>gaussian</b> models describe a simple hyper-plane (for a single column this will be a simple line) for the response variable. This is a suitable model for when you expect the response variable to vary as a linear combination of predictor variables. An example might be predicting the gas mileage of cars, based on their weight, age, and engine size.</li>"+ "<li><b>binomial</b> models form an S-curve response, showing probabilities that vary from 0 to 1. This is a suitable model for when you expect a simple boolean result (e.g. alive/dead, or fraud/no-fraud). The model gives a probability of the true event. An example might be to predict the presence of prostate cancer given the patient age, race, and various blood chemical levels such as PSA.</li>"+ "</ul>"; _link._requestHelp = "Link function to be used."; _lambda._requestHelp = "Penalty argument. Higher lambda means higher penalty is applied on the size of the beta vector."; _alpha._requestHelp = "Penalty distribution argument. Controls distribution of penalty between L1 and L2 norm according to the formula above."; _betaEps._requestHelp = "Precision of the vector of coefficients. Computation stops when the maximal difference between two beta vectors is below than Beta epsilon."; _maxIter._requestHelp = "Number of maximum iterations."; _caseWeight._requestHelp = "All rows for which the predicate is true will be weighted by weight. Weight=1 is neutral. Weight = 0.5 treats negative examples as twice more important than positive ones. Weight = 2.0 does the opposite."; _caseMode._requestHelp = "Predicate selection."; _case._requestHelp = "Value to be used to compare against using predicate given by case mode selector to turn the y column into boolean."; _thresholds._requestHelp = "Sequence of decision thresholds to be evaluated during validation (used for ROC curce computation and for picking optimal decision threshold of the resulting classifier)."; _xval._requestHelp = "Number of fold used in cross-validation. 0 or 1 means no cross validation."; _expertSettings.setRefreshOnChange(); } public static String link(Key k, String content) { RString rs = new RString("<a href='GLM.query?%key_param=%$key'>%content</a>"); rs.replace("key_param", KEY); rs.replace("key", k.toString()); rs.replace("content", content); return rs.toString(); } static void getColumnIdxs(StringBuilder sb, ValueArray ary, String [] cols ){ Arrays.sort(cols); boolean firstCol = false; for(int i = 0; i < ary._cols.length; ++i) if(Arrays.binarySearch(cols, ary._cols[i]._name) >= 0) if(firstCol){ sb.append(""+i); firstCol = false; } else sb.append(","+i); } public static String link(Key k, GLMModel m, String content) { int [] colIds = m.selectedColumns(); if(colIds == null)return ""; /// the dataset is no longer on H2O, no link shoudl be produced! try { StringBuilder sb = new StringBuilder("<a href='GLM.query?"); sb.append(KEY + "=" + k.toString()); sb.append("&y=" + m.responseName()); // find the column idxs...(the model keeps only names) sb.append("&x=" + colIds[0]); for(int i = 1; i < colIds.length-1; ++i) sb.append(","+colIds[i]); sb.append("&family=" + m._glmParams._family.toString()); sb.append("&link=" + m._glmParams._link.toString()); sb.append("&lambda=" + m._solver._lambda); sb.append("&alpha=" + m._solver._alpha); sb.append("&beta_eps=" + m._glmParams._betaEps); sb.append("&weight=" + m._glmParams._caseWeight); sb.append("&max_iter=" + m._glmParams._maxIter); sb.append("&caseMode=" + URLEncoder.encode(m._glmParams._caseMode.toString(),"utf8")); sb.append("&case=" + m._glmParams._caseVal); sb.append("'>" + content + "</a>"); return sb.toString(); } catch( UnsupportedEncodingException e ) { throw Log.errRTExcept(e); } } @Override protected void queryArgumentValueSet(Argument arg, Properties inputArgs) { if(arg == _caseMode){ if(_caseMode.value() == CaseMode.none) _case.disable("n/a"); } else if (arg == _family) { if (_family.value() != Family.binomial) { _case.disable("Only for family binomial"); _caseMode.disable("Only for family binomial"); _caseWeight.disable("Only for family binomial"); _thresholds.disable("Only for family binomial"); } } else if (arg == _expertSettings){ if(_expertSettings.value()){ _lsmSolver._hideInQuery = false; _thresholds._hideInQuery = false; _maxIter._hideInQuery = false; _betaEps._hideInQuery = false; //_reweightGram._hideInQuery = false; _standardize._hideInQuery = false; } else { _lsmSolver._hideInQuery = true; _thresholds._hideInQuery = true; _maxIter._hideInQuery = true; _betaEps._hideInQuery = true; //_reweightGram._hideInQuery = true; _standardize._hideInQuery = true; } } } /** Returns an array of columns to use for GLM, the last of them being the * result column y. */ private int[] createColumns() { BitSet cols = new BitSet(); for( int i : _x.value() ) cols.set (i); //for( int i : _negX.value() ) cols.clear(i); int[] res = new int[cols.cardinality()+1]; int x=0; for( int i = cols.nextSetBit(0); i >= 0; i = cols.nextSetBit(i+1)) res[x++] = i; res[x] = _y.value(); return res; } static JsonObject getCoefficients(int [] columnIds, ValueArray ary, double [] beta){ JsonObject coefficients = new JsonObject(); for( int i = 0; i < beta.length; ++i ) { String colName = (i == (beta.length - 1)) ? "Intercept" : ary._cols[columnIds[i]]._name; coefficients.addProperty(colName, beta[i]); } return coefficients; } GLMParams getGLMParams(){ GLMParams res = new GLMParams(_family.value(),_link.value()); if( res._link == Link.familyDefault ) res._link = res._family.defaultLink; res._maxIter = _maxIter.value(); res._betaEps = _betaEps.value(); if(_caseWeight.valid()) res._caseWeight = _caseWeight.value(); if(_case.valid()) res._caseVal = _case.value(); res._caseMode = _caseMode.valid()?_caseMode.value():CaseMode.none; return res; } @Override protected Response serve() { try { JsonObject res = new JsonObject(); ValueArray ary = _key.value(); int[] columns = createColumns(); res.addProperty("key", ary._key.toString()); res.addProperty("h2o", H2O.SELF.toString()); GLMParams glmParams = getGLMParams(); DataFrame data = DGLM.getData(ary, columns, null, _standardize.value()); LSMSolver lsm = null; switch(_lsmSolver.value()){ case AUTO: lsm = //data.expandedSz() < 1000? new ADMMSolver(_lambda.value(),_alpha.value());//: //new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); break; case ADMM: lsm = new ADMMSolver(_lambda.value(),_alpha.value()); break; case GenGradient: lsm = new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); } GLMJob job = DGLM.startGLMJob(data, lsm, glmParams, null, _xval.value(), true); JsonObject j = new JsonObject(); j.addProperty(Constants.DEST_KEY, job.dest().toString()); Response r = GLMProgressPage.redirect(j, job.self(), job.dest(),job.progressKey()); r.setBuilder(Constants.DEST_KEY, new KeyElementBuilder()); return r; }catch(GLMException e){ Log.err(e); return Response.error(e.getMessage()); } catch (Throwable t) { Log.err(t); return Response.error(t.getMessage()); } } }
usersbin/h2o
src/main/java/water/api/GLM.java
249,337
package water.api; import hex.*; import hex.DGLM.CaseMode; import hex.DGLM.Family; import hex.DGLM.GLMException; import hex.DGLM.GLMJob; import hex.DGLM.GLMModel; import hex.DGLM.GLMParams; import hex.DGLM.Link; import hex.DGLM.LinkIced; import hex.DLSM.ADMMSolver; import hex.DLSM.GeneralizedGradientSolver; import hex.DLSM.LSMSolver; import hex.DLSM.LSMSolverType; import hex.NewRowVecTask.DataFrame; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; import water.*; import water.util.Log; import water.util.RString; import com.google.gson.JsonObject; public class GLM extends Request { protected final H2OKey _dest = new H2OKey(DEST_KEY, false); protected final H2OHexKey _key = new H2OHexKey(KEY); protected final H2OHexKeyCol _y = new H2OHexKeyCol(Y, _key); protected final HexColumnSelect _x = new HexNonConstantColumnSelect(X, _key, _y); protected final H2OGLMModelKey _modelKey = new H2OGLMModelKey(MODEL_KEY,false); protected final EnumArgument<Family> _family = new EnumArgument(FAMILY,Family.gaussian,true); protected final LinkArg _link = new LinkArg(_family,LINK); protected final Real _lambda = new Real(LAMBDA, 1e-5); // TODO I do not know the bounds protected final Real _alpha = new Real(ALPHA, 0.5, 0, 1, ""); protected final Real _caseWeight = new Real(WEIGHT,1.0); protected final Real _tweediePower = new Real(TWEEDIE_POWER, 1.5); protected final CaseModeSelect _caseMode = new CaseModeSelect(_key,_y,_family, CASE_MODE,CaseMode.none); protected final CaseSelect _case = new CaseSelect(_key,_y,_caseMode,CASE); protected final Int _xval = new Int(XVAL, 10, 0, 1000000); protected final Bool _expertSettings = new Bool("expert_settings", true ,"Show expert settings."); // ------------------------------------- ADVANCED SETTINGS ------------------------------------------------------------------------------------ protected final Bool _standardize = new Bool("standardize", true, "Set to standardize (0 mean, unit variance) the data before training."); protected final RSeq _thresholds = new RSeq(DTHRESHOLDS, false, new NumberSequence("0:1:0.01", false, 0.01),false); protected final EnumArgument<LSMSolverType> _lsmSolver = new EnumArgument<LSMSolverType>("lsm_solver", LSMSolverType.AUTO); protected final Real _betaEps = new Real(BETA_EPS,1e-4); protected final Int _maxIter = new Int(MAX_ITER, 50, 1, 1000000); //protected final Bool _reweightGram = new Bool("reweigthed_gram_xval", false, "Set to force reweighted gram matrix for cross-validation (non-reweighted xval is much faster, less precise)."); public GLM() { _requestHelp = "Compute generalized linear model with penalized maximum likelihood. Penalties include the lasso (L1 penalty), ridge regression (L2 penalty) or elastic net penalty (combination of L1 and L2) penalties. The penalty function is defined as :<br/>" + "<pre>\n" + " P(&beta;) = 0.5*(1 - &alpha;)*||&beta;||<sub>2</sub><sup>2</sup> + &alpha;*||&beta;||<sub>1</sub><br/>"+ "</pre>" + "By setting &alpha; to 0, we get ridge regression, setting it to 1 gets us lasso. <p>See our <a href='https://github.com/0xdata/h2o/wiki/GLM#wiki-Details' target=\"_blank\">wiki</a> for details.<p>"; _key._requestHelp = "Dataset to be trained on."; _y._requestHelp = "Response variable column name."; _x._requestHelp = "Predictor columns to be trained on. Constant columns will be ignored."; _modelKey._hideInQuery = true; _modelKey._requestHelp = "The H2O's Key name for the model"; _family._requestHelp = "Pick the general mathematical family for the trained model.<br><ul>"+ "<li><b>gaussian</b> models describe a simple hyper-plane (for a single column this will be a simple line) for the response variable. This is a suitable model for when you expect the response variable to vary as a linear combination of predictor variables. An example might be predicting the gas mileage of cars, based on their weight, age, and engine size.</li>"+ "<li><b>binomial</b> models form an S-curve response, showing probabilities that vary from 0 to 1. This is a suitable model for when you expect a simple boolean result (e.g. alive/dead, or fraud/no-fraud). The model gives a probability of the true event. An example might be to predict the presence of prostate cancer given the patient age, race, and various blood chemical levels such as PSA.</li>"+ "</ul>"; _link._requestHelp = "Link function to be used."; _lambda._requestHelp = "Penalty argument. Higher lambda means higher penalty is applied on the size of the beta vector."; _alpha._requestHelp = "Penalty distribution argument. Controls distribution of penalty between L1 and L2 norm according to the formula above."; _betaEps._requestHelp = "Precision of the vector of coefficients. Computation stops when the maximal difference between two beta vectors is below than Beta epsilon."; _maxIter._requestHelp = "Number of maximum iterations."; _caseWeight._requestHelp = "All rows for which the predicate is true will be weighted by weight. Weight=1 is neutral. Weight = 0.5 treats negative examples as twice more important than positive ones. Weight = 2.0 does the opposite."; _caseMode._requestHelp = "Predicate selection."; _case._requestHelp = "Value to be used to compare against using predicate given by case mode selector to turn the y column into boolean."; _thresholds._requestHelp = "Sequence of decision thresholds to be evaluated during validation (used for ROC curce computation and for picking optimal decision threshold of the resulting classifier)."; _xval._requestHelp = "Number of fold used in cross-validation. 0 or 1 means no cross validation."; _expertSettings.setRefreshOnChange(); } public static String link(Key k, String content) { RString rs = new RString("<a href='GLM.query?%key_param=%$key'>%content</a>"); rs.replace("key_param", KEY); rs.replace("key", k.toString()); rs.replace("content", content); return rs.toString(); } static void getColumnIdxs(StringBuilder sb, ValueArray ary, String [] cols ){ Arrays.sort(cols); boolean firstCol = false; for(int i = 0; i < ary._cols.length; ++i) if(Arrays.binarySearch(cols, ary._cols[i]._name) >= 0) if(firstCol){ sb.append(""+i); firstCol = false; } else sb.append(","+i); } public static String link(Key k, GLMModel m, String content) { int [] colIds = m.selectedColumns(); if(colIds == null)return ""; /// the dataset is no longer on H2O, no link shoudl be produced! try { StringBuilder sb = new StringBuilder("<a href='GLM.query?"); sb.append(KEY + "=" + k.toString()); sb.append("&y=" + m.responseName()); // find the column idxs...(the model keeps only names) sb.append("&x=" + colIds[0]); for(int i = 1; i < colIds.length-1; ++i) sb.append(","+colIds[i]); sb.append("&family=" + m._glmParams._family._family.toString()); sb.append("&tweedie_power=" + m._glmParams._family._tweedieVariancePower); sb.append("&link=" + m._glmParams._link._link.toString()); sb.append("&lambda=" + m._solver._lambda); sb.append("&alpha=" + m._solver._alpha); sb.append("&beta_eps=" + m._glmParams._betaEps); sb.append("&weight=" + m._glmParams._caseWeight); sb.append("&max_iter=" + m._glmParams._maxIter); sb.append("&caseMode=" + URLEncoder.encode(m._glmParams._caseMode.toString(),"utf8")); sb.append("&case=" + m._glmParams._caseVal); sb.append("'>" + content + "</a>"); return sb.toString(); } catch( UnsupportedEncodingException e ) { throw Log.errRTExcept(e); } } @Override protected void queryArgumentValueSet(Argument arg, Properties inputArgs) { if(arg == _caseMode){ if(_caseMode.value() == CaseMode.none) _case.disable("n/a"); } else if (arg == _family) { if (_family.value() != Family.binomial) { _case.disable("Only for family binomial"); _caseMode.disable("Only for family binomial"); _caseWeight.disable("Only for family binomial"); _thresholds.disable("Only for family binomial"); } if (_family.value() != Family.tweedie){ _tweediePower.disable("Only for family tweedie"); } } else if (arg == _expertSettings){ if(_expertSettings.value()){ _lsmSolver._hideInQuery = false; _thresholds._hideInQuery = false; _maxIter._hideInQuery = false; _betaEps._hideInQuery = false; //_reweightGram._hideInQuery = false; _standardize._hideInQuery = false; } else { _lsmSolver._hideInQuery = true; _thresholds._hideInQuery = true; _maxIter._hideInQuery = true; _betaEps._hideInQuery = true; //_reweightGram._hideInQuery = true; _standardize._hideInQuery = true; } } } /** Returns an array of columns to use for GLM, the last of them being the * result column y. */ private int[] createColumns() { BitSet cols = new BitSet(); for( int i : _x.value() ) cols.set (i); //for( int i : _negX.value() ) cols.clear(i); int[] res = new int[cols.cardinality()+1]; int x=0; for( int i = cols.nextSetBit(0); i >= 0; i = cols.nextSetBit(i+1)) res[x++] = i; res[x] = _y.value(); return res; } static JsonObject getCoefficients(int [] columnIds, ValueArray ary, double [] beta){ JsonObject coefficients = new JsonObject(); for( int i = 0; i < beta.length; ++i ) { String colName = (i == (beta.length - 1)) ? "Intercept" : ary._cols[columnIds[i]]._name; coefficients.addProperty(colName, beta[i]); } return coefficients; } GLMParams getGLMParams(){ Family family = _family.value(); Link link = _link.value(); if( family == Family.tweedie && !(link == Link.tweedie || link == Link.familyDefault)){ return null; } GLMParams res; if (family != Family.tweedie) res = new GLMParams(_family.value(),_link.value()); else { double variancePower = _tweediePower.value(); //TODO let tweedie also control link power Link l = Link.tweedie; l.tweedieLinkPower = 1. - variancePower; Family f = Family.tweedie; f.defaultLink = l; f.tweedieVariancePower = variancePower; res = new GLMParams(f, l, f.tweedieVariancePower, l.tweedieLinkPower); } if( res._link._link == Link.familyDefault && res._link._link != Link.tweedie ) res._link = new LinkIced( res._family._family.defaultLink ); res._maxIter = _maxIter.value(); res._betaEps = _betaEps.value(); if(_caseWeight.valid()) res._caseWeight = _caseWeight.value(); if(_case.valid()) res._caseVal = _case.value(); res._caseMode = _caseMode.valid()?_caseMode.value():CaseMode.none; return res; } @Override protected Response serve() { try { JsonObject res = new JsonObject(); Key dest = _dest.value(); ValueArray ary = _key.value(); int[] columns = createColumns(); res.addProperty("key", ary._key.toString()); res.addProperty("h2o", H2O.SELF.toString()); GLMParams glmParams = getGLMParams(); if (glmParams == null){ if (_family.value() == Family.tweedie && _link.value() == Link.tweedie){ return Response.error("tweedie family requires tweedie link"); } return Response.error("error reading glm parameters"); } if (glmParams._family._family == Family.tweedie){ double p = _tweediePower.value(); if ( !(1. < p && p < 2.) ){ return Response.error("tweedie family specified but invalid tweedie power: must be in (1,2)"); } } DataFrame data = DGLM.getData(ary, columns, null, _standardize.value()); LSMSolver lsm = null; switch(_lsmSolver.value()){ case AUTO: lsm = //data.expandedSz() < 1000? new ADMMSolver(_lambda.value(),_alpha.value());//: //new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); break; case ADMM: lsm = new ADMMSolver(_lambda.value(),_alpha.value()); break; case GenGradient: lsm = new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); } GLMJob job = DGLM.startGLMJob(dest, data, lsm, glmParams, null, _xval.value(), true); JsonObject j = new JsonObject(); j.addProperty(Constants.DEST_KEY, job.dest().toString()); Response r = GLMProgressPage.redirect(j, job.self(), job.dest(),job.progressKey()); r.setBuilder(Constants.DEST_KEY, new KeyElementBuilder()); return r; } catch( Throwable t ) { return Response.error(t); } } }
brennane/h2o
src/main/java/water/api/GLM.java
249,338
package water.api; import hex.*; import hex.DGLM.CaseMode; import hex.DGLM.Family; import hex.DGLM.GLMException; import hex.DGLM.GLMJob; import hex.DGLM.GLMModel; import hex.DGLM.GLMParams; import hex.DGLM.Link; import hex.DGLM.LinkIced; import hex.DLSM.ADMMSolver; import hex.DLSM.GeneralizedGradientSolver; import hex.DLSM.LSMSolver; import hex.DLSM.LSMSolverType; import hex.NewRowVecTask.DataFrame; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; import water.*; import water.util.Log; import water.util.RString; import com.google.gson.JsonObject; public class GLM extends Request { protected final H2OKey _dest = new H2OKey(DEST_KEY, false); protected final H2OHexKey _key = new H2OHexKey(KEY); protected final H2OHexKeyCol _y = new H2OHexKeyCol(Y, _key); protected final HexColumnSelect _x = new HexNonConstantColumnSelect(X, _key, _y); protected final H2OGLMModelKey _modelKey = new H2OGLMModelKey(MODEL_KEY,false); protected final EnumArgument<Family> _family = new EnumArgument(FAMILY,Family.gaussian,true); protected final LinkArg _link = new LinkArg(_family,LINK); protected final Real _lambda = new Real(LAMBDA, 1e-5); // TODO I do not know the bounds protected final Real _alpha = new Real(ALPHA, 0.5, 0, 1, ""); protected final Real _caseWeight = new Real(WEIGHT,1.0); protected final Real _tweediePower = new Real(TWEEDIE_POWER, 1.5); protected final CaseModeSelect _caseMode = new CaseModeSelect(_key,_y,_family, CASE_MODE,CaseMode.none); protected final CaseSelect _case = new CaseSelect(_key,_y,_caseMode,CASE); protected final Int _xval = new Int(XVAL, 10, 0, 1000000); protected final Bool _expertSettings = new Bool("expert_settings", false,"Show expert settings."); // ------------------------------------- ADVANCED SETTINGS ------------------------------------------------------------------------------------ protected final Bool _standardize = new Bool("standardize", true, "Set to standardize (0 mean, unit variance) the data before training."); protected final RSeq _thresholds = new RSeq(DTHRESHOLDS, false, new NumberSequence("0:1:0.01", false, 0.01),false); protected final EnumArgument<LSMSolverType> _lsmSolver = new EnumArgument<LSMSolverType>("lsm_solver", LSMSolverType.AUTO); protected final Real _betaEps = new Real(BETA_EPS,1e-4); protected final Int _maxIter = new Int(MAX_ITER, 50, 1, 1000000); //protected final Bool _reweightGram = new Bool("reweigthed_gram_xval", false, "Set to force reweighted gram matrix for cross-validation (non-reweighted xval is much faster, less precise)."); public GLM() { _requestHelp = "Compute generalized linear model with penalized maximum likelihood. Penalties include the lasso (L1 penalty), ridge regression (L2 penalty) or elastic net penalty (combination of L1 and L2) penalties. The penalty function is defined as :<br/>" + "<pre>\n" + " P(&beta;) = 0.5*(1 - &alpha;)*||&beta;||<sub>2</sub><sup>2</sup> + &alpha;*||&beta;||<sub>1</sub><br/>"+ "</pre>" + "By setting &alpha; to 0, we get ridge regression, setting it to 1 gets us lasso. <p>See our <a href='https://github.com/0xdata/h2o/wiki/GLM#wiki-Details' target=\"_blank\">wiki</a> for details.<p>"; _key._requestHelp = "Dataset to be trained on."; _y._requestHelp = "Response variable column name."; _x._requestHelp = "Predictor columns to be trained on. Constant columns will be ignored."; _modelKey._hideInQuery = true; _modelKey._requestHelp = "The H2O's Key name for the model"; _family._requestHelp = "Pick the general mathematical family for the trained model.<br><ul>"+ "<li><b>gaussian</b> models describe a simple hyper-plane (for a single column this will be a simple line) for the response variable. This is a suitable model for when you expect the response variable to vary as a linear combination of predictor variables. An example might be predicting the gas mileage of cars, based on their weight, age, and engine size.</li>"+ "<li><b>binomial</b> models form an S-curve response, showing probabilities that vary from 0 to 1. This is a suitable model for when you expect a simple boolean result (e.g. alive/dead, or fraud/no-fraud). The model gives a probability of the true event. An example might be to predict the presence of prostate cancer given the patient age, race, and various blood chemical levels such as PSA.</li>"+ "</ul>"; _link._requestHelp = "Link function to be used."; _lambda._requestHelp = "Penalty argument. Higher lambda means higher penalty is applied on the size of the beta vector."; _alpha._requestHelp = "Penalty distribution argument. Controls distribution of penalty between L1 and L2 norm according to the formula above."; _betaEps._requestHelp = "Precision of the vector of coefficients. Computation stops when the maximal difference between two beta vectors is below than Beta epsilon."; _maxIter._requestHelp = "Number of maximum iterations."; _caseWeight._requestHelp = "All rows for which the predicate is true will be weighted by weight. Weight=1 is neutral. Weight = 0.5 treats negative examples as twice more important than positive ones. Weight = 2.0 does the opposite."; _caseMode._requestHelp = "Predicate selection."; _case._requestHelp = "Value to be used to compare against using predicate given by case mode selector to turn the y column into boolean."; _thresholds._requestHelp = "Sequence of decision thresholds to be evaluated during validation (used for ROC curce computation and for picking optimal decision threshold of the resulting classifier)."; _xval._requestHelp = "Number of fold used in cross-validation. 0 or 1 means no cross validation."; _expertSettings.setRefreshOnChange(); } public static String link(Key k, String content) { RString rs = new RString("<a href='GLM.query?%key_param=%$key'>%content</a>"); rs.replace("key_param", KEY); rs.replace("key", k.toString()); rs.replace("content", content); return rs.toString(); } static void getColumnIdxs(StringBuilder sb, ValueArray ary, String [] cols ){ Arrays.sort(cols); boolean firstCol = false; for(int i = 0; i < ary._cols.length; ++i) if(Arrays.binarySearch(cols, ary._cols[i]._name) >= 0) if(firstCol){ sb.append(""+i); firstCol = false; } else sb.append(","+i); } public static String link(Key k, GLMModel m, String content) { int [] colIds = m.selectedColumns(); if(colIds == null)return ""; /// the dataset is no longer on H2O, no link shoudl be produced! try { StringBuilder sb = new StringBuilder("<a href='GLM.query?"); sb.append(KEY + "=" + k.toString()); sb.append("&y=" + m.responseName()); // find the column idxs...(the model keeps only names) sb.append("&x=" + colIds[0]); for(int i = 1; i < colIds.length-1; ++i) sb.append(","+colIds[i]); sb.append("&family=" + m._glmParams._family.toString()); sb.append("&link=" + m._glmParams._link.toString()); sb.append("&lambda=" + m._solver._lambda); sb.append("&alpha=" + m._solver._alpha); sb.append("&beta_eps=" + m._glmParams._betaEps); sb.append("&weight=" + m._glmParams._caseWeight); sb.append("&max_iter=" + m._glmParams._maxIter); sb.append("&caseMode=" + URLEncoder.encode(m._glmParams._caseMode.toString(),"utf8")); sb.append("&case=" + m._glmParams._caseVal); sb.append("'>" + content + "</a>"); return sb.toString(); } catch( UnsupportedEncodingException e ) { throw Log.errRTExcept(e); } } @Override protected void queryArgumentValueSet(Argument arg, Properties inputArgs) { if(arg == _caseMode){ if(_caseMode.value() == CaseMode.none) _case.disable("n/a"); } else if (arg == _family) { if (_family.value() != Family.binomial) { _case.disable("Only for family binomial"); _caseMode.disable("Only for family binomial"); _caseWeight.disable("Only for family binomial"); _thresholds.disable("Only for family binomial"); } if (_family.value() != Family.tweedie){ _tweediePower.disable("Only for family tweedie"); } } else if (arg == _expertSettings){ if(_expertSettings.value()){ _lsmSolver._hideInQuery = false; _thresholds._hideInQuery = false; _maxIter._hideInQuery = false; _betaEps._hideInQuery = false; //_reweightGram._hideInQuery = false; _standardize._hideInQuery = false; } else { _lsmSolver._hideInQuery = true; _thresholds._hideInQuery = true; _maxIter._hideInQuery = true; _betaEps._hideInQuery = true; //_reweightGram._hideInQuery = true; _standardize._hideInQuery = true; } } } /** Returns an array of columns to use for GLM, the last of them being the * result column y. */ private int[] createColumns() { BitSet cols = new BitSet(); for( int i : _x.value() ) cols.set (i); //for( int i : _negX.value() ) cols.clear(i); int[] res = new int[cols.cardinality()+1]; int x=0; for( int i = cols.nextSetBit(0); i >= 0; i = cols.nextSetBit(i+1)) res[x++] = i; res[x] = _y.value(); return res; } static JsonObject getCoefficients(int [] columnIds, ValueArray ary, double [] beta){ JsonObject coefficients = new JsonObject(); for( int i = 0; i < beta.length; ++i ) { String colName = (i == (beta.length - 1)) ? "Intercept" : ary._cols[columnIds[i]]._name; coefficients.addProperty(colName, beta[i]); } return coefficients; } GLMParams getGLMParams(){ Family family = _family.value(); Link link = _link.value(); if( family == Family.tweedie && !(link == Link.tweedie || link == Link.familyDefault)){ return null; } GLMParams res; if (family != Family.tweedie) res = new GLMParams(_family.value(),_link.value()); else { double variancePower = _tweediePower.value(); //TODO let tweedie also control link power Link l = Link.tweedie; l.tweedieLinkPower = 1. - variancePower; Family f = Family.tweedie; f.defaultLink = l; f.tweedieVariancePower = variancePower; res = new GLMParams(f, l, f.tweedieVariancePower, l.tweedieLinkPower); } if( res._link._link == Link.familyDefault && res._link._link != Link.tweedie ) res._link = new LinkIced( res._family._family.defaultLink ); res._maxIter = _maxIter.value(); res._betaEps = _betaEps.value(); if(_caseWeight.valid()) res._caseWeight = _caseWeight.value(); if(_case.valid()) res._caseVal = _case.value(); res._caseMode = _caseMode.valid()?_caseMode.value():CaseMode.none; return res; } @Override protected Response serve() { try { JsonObject res = new JsonObject(); Key dest = _dest.value(); ValueArray ary = _key.value(); int[] columns = createColumns(); res.addProperty("key", ary._key.toString()); res.addProperty("h2o", H2O.SELF.toString()); GLMParams glmParams = getGLMParams(); if (glmParams == null){ if (_family.value() == Family.tweedie && _link.value() == Link.tweedie){ return Response.error("tweedie family requires tweedie link"); } return Response.error("error reading glm parameters"); } if (glmParams._family._family == Family.tweedie){ double p = _tweediePower.value(); if ( !(1. < p && p < 2.) ){ return Response.error("tweedie family specified but invalid tweedie power: must be in (1,2)"); } } DataFrame data = DGLM.getData(ary, columns, null, _standardize.value()); LSMSolver lsm = null; switch(_lsmSolver.value()){ case AUTO: lsm = //data.expandedSz() < 1000? new ADMMSolver(_lambda.value(),_alpha.value());//: //new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); break; case ADMM: lsm = new ADMMSolver(_lambda.value(),_alpha.value()); break; case GenGradient: lsm = new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); } GLMJob job = DGLM.startGLMJob(dest, data, lsm, glmParams, null, _xval.value(), true); JsonObject j = new JsonObject(); j.addProperty(Constants.DEST_KEY, job.dest().toString()); Response r = GLMProgressPage.redirect(j, job.self(), job.dest(),job.progressKey()); r.setBuilder(Constants.DEST_KEY, new KeyElementBuilder()); return r; }catch(GLMException e){ Log.err(e); return Response.error(e.getMessage()); } catch (Throwable t) { Log.err(t); return Response.error(t.getMessage()); } } }
selcukgun/h2o
src/main/java/water/api/GLM.java
249,339
package water.api; import hex.*; import hex.DGLM.CaseMode; import hex.DGLM.Family; import hex.DGLM.GLMException; import hex.DGLM.GLMJob; import hex.DGLM.GLMModel; import hex.DGLM.GLMParams; import hex.DGLM.Link; import hex.DGLM.LinkIced; import hex.DLSM.ADMMSolver; import hex.DLSM.GeneralizedGradientSolver; import hex.DLSM.LSMSolver; import hex.DLSM.LSMSolverType; import hex.NewRowVecTask.DataFrame; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; import water.*; import water.util.Log; import water.util.RString; import com.google.gson.JsonObject; public class GLM extends Request { protected final H2OKey _dest = new H2OKey(DEST_KEY, false); protected final H2OHexKey _key = new H2OHexKey(KEY); protected final H2OHexKeyCol _y = new H2OHexKeyCol(Y, _key); protected final HexColumnSelect _x = new HexNonConstantColumnSelect(X, _key, _y); protected final H2OGLMModelKey _modelKey = new H2OGLMModelKey(MODEL_KEY,false); protected final EnumArgument<Family> _family = new EnumArgument(FAMILY,Family.gaussian,true); protected final LinkArg _link = new LinkArg(_family,LINK); protected final Real _lambda = new Real(LAMBDA, 1e-5); // TODO I do not know the bounds protected final Real _alpha = new Real(ALPHA, 0.5, 0, 1, ""); protected final Real _caseWeight = new Real(WEIGHT,1.0); protected final Real _tweediePower = new Real(TWEEDIE_POWER, 1.5); protected final CaseModeSelect _caseMode = new CaseModeSelect(_key,_y,_family, CASE_MODE,CaseMode.none); protected final CaseSelect _case = new CaseSelect(_key,_y,_caseMode,CASE); protected final Int _xval = new Int(XVAL, 10, 0, 1000000); protected final Bool _expertSettings = new Bool("expert_settings", true ,"Show expert settings."); // ------------------------------------- ADVANCED SETTINGS ------------------------------------------------------------------------------------ protected final Bool _standardize = new Bool("standardize", true, "Set to standardize (0 mean, unit variance) the data before training."); protected final RSeq _thresholds = new RSeq(DTHRESHOLDS, false, new NumberSequence("0:1:0.01", false, 0.01),false); protected final EnumArgument<LSMSolverType> _lsmSolver = new EnumArgument<LSMSolverType>("lsm_solver", LSMSolverType.AUTO); protected final Real _betaEps = new Real(BETA_EPS,1e-4); protected final Int _maxIter = new Int(MAX_ITER, 50, 1, 1000000); //protected final Bool _reweightGram = new Bool("reweigthed_gram_xval", false, "Set to force reweighted gram matrix for cross-validation (non-reweighted xval is much faster, less precise)."); public GLM() { _requestHelp = "Compute generalized linear model with penalized maximum likelihood. Penalties include the lasso (L1 penalty), ridge regression (L2 penalty) or elastic net penalty (combination of L1 and L2) penalties. The penalty function is defined as :<br/>" + "<pre>\n" + " P(&beta;) = 0.5*(1 - &alpha;)*||&beta;||<sub>2</sub><sup>2</sup> + &alpha;*||&beta;||<sub>1</sub><br/>"+ "</pre>" + "By setting &alpha; to 0, we get ridge regression, setting it to 1 gets us lasso. <p>See our <a href='https://github.com/0xdata/h2o/wiki/GLM#wiki-Details' target=\"_blank\">wiki</a> for details.<p>"; _key._requestHelp = "Dataset to be trained on."; _y._requestHelp = "Response variable column name."; _x._requestHelp = "Predictor columns to be trained on. Constant columns will be ignored."; _modelKey._hideInQuery = true; _modelKey._requestHelp = "The H2O's Key name for the model"; _family._requestHelp = "Pick the general mathematical family for the trained model.<br><ul>"+ "<li><b>gaussian</b> models describe a simple hyper-plane (for a single column this will be a simple line) for the response variable. This is a suitable model for when you expect the response variable to vary as a linear combination of predictor variables. An example might be predicting the gas mileage of cars, based on their weight, age, and engine size.</li>"+ "<li><b>binomial</b> models form an S-curve response, showing probabilities that vary from 0 to 1. This is a suitable model for when you expect a simple boolean result (e.g. alive/dead, or fraud/no-fraud). The model gives a probability of the true event. An example might be to predict the presence of prostate cancer given the patient age, race, and various blood chemical levels such as PSA.</li>"+ "</ul>"; _link._requestHelp = "Link function to be used."; _lambda._requestHelp = "Penalty argument. Higher lambda means higher penalty is applied on the size of the beta vector."; _alpha._requestHelp = "Penalty distribution argument. Controls distribution of penalty between L1 and L2 norm according to the formula above."; _betaEps._requestHelp = "Precision of the vector of coefficients. Computation stops when the maximal difference between two beta vectors is below than Beta epsilon."; _maxIter._requestHelp = "Number of maximum iterations."; _caseWeight._requestHelp = "All rows for which the predicate is true will be weighted by weight. Weight=1 is neutral. Weight = 0.5 treats negative examples as twice more important than positive ones. Weight = 2.0 does the opposite."; _caseMode._requestHelp = "Predicate selection."; _case._requestHelp = "Value to be used to compare against using predicate given by case mode selector to turn the y column into boolean."; _thresholds._requestHelp = "Sequence of decision thresholds to be evaluated during validation (used for ROC curce computation and for picking optimal decision threshold of the resulting classifier)."; _xval._requestHelp = "Number of fold used in cross-validation. 0 or 1 means no cross validation."; _expertSettings.setRefreshOnChange(); } public static String link(Key k, String content) { RString rs = new RString("<a href='GLM.query?%key_param=%$key'>%content</a>"); rs.replace("key_param", KEY); rs.replace("key", k.toString()); rs.replace("content", content); return rs.toString(); } static void getColumnIdxs(StringBuilder sb, ValueArray ary, String [] cols ){ Arrays.sort(cols); boolean firstCol = false; for(int i = 0; i < ary._cols.length; ++i) if(Arrays.binarySearch(cols, ary._cols[i]._name) >= 0) if(firstCol){ sb.append(""+i); firstCol = false; } else sb.append(","+i); } public static String link(Key k, GLMModel m, String content) { int [] colIds = m.selectedColumns(); if(colIds == null)return ""; /// the dataset is no longer on H2O, no link shoudl be produced! try { StringBuilder sb = new StringBuilder("<a href='GLM.query?"); sb.append(KEY + "=" + k.toString()); sb.append("&y=" + m.responseName()); // find the column idxs...(the model keeps only names) sb.append("&x=" + colIds[0]); for(int i = 1; i < colIds.length-1; ++i) sb.append(","+colIds[i]); sb.append("&family=" + m._glmParams._family.toString()); sb.append("&link=" + m._glmParams._link.toString()); sb.append("&lambda=" + m._solver._lambda); sb.append("&alpha=" + m._solver._alpha); sb.append("&beta_eps=" + m._glmParams._betaEps); sb.append("&weight=" + m._glmParams._caseWeight); sb.append("&max_iter=" + m._glmParams._maxIter); sb.append("&caseMode=" + URLEncoder.encode(m._glmParams._caseMode.toString(),"utf8")); sb.append("&case=" + m._glmParams._caseVal); sb.append("'>" + content + "</a>"); return sb.toString(); } catch( UnsupportedEncodingException e ) { throw Log.errRTExcept(e); } } @Override protected void queryArgumentValueSet(Argument arg, Properties inputArgs) { if(arg == _caseMode){ if(_caseMode.value() == CaseMode.none) _case.disable("n/a"); } else if (arg == _family) { if (_family.value() != Family.binomial) { _case.disable("Only for family binomial"); _caseMode.disable("Only for family binomial"); _caseWeight.disable("Only for family binomial"); _thresholds.disable("Only for family binomial"); } if (_family.value() != Family.tweedie){ _tweediePower.disable("Only for family tweedie"); } } else if (arg == _expertSettings){ if(_expertSettings.value()){ _lsmSolver._hideInQuery = false; _thresholds._hideInQuery = false; _maxIter._hideInQuery = false; _betaEps._hideInQuery = false; //_reweightGram._hideInQuery = false; _standardize._hideInQuery = false; } else { _lsmSolver._hideInQuery = true; _thresholds._hideInQuery = true; _maxIter._hideInQuery = true; _betaEps._hideInQuery = true; //_reweightGram._hideInQuery = true; _standardize._hideInQuery = true; } } } /** Returns an array of columns to use for GLM, the last of them being the * result column y. */ private int[] createColumns() { BitSet cols = new BitSet(); for( int i : _x.value() ) cols.set (i); //for( int i : _negX.value() ) cols.clear(i); int[] res = new int[cols.cardinality()+1]; int x=0; for( int i = cols.nextSetBit(0); i >= 0; i = cols.nextSetBit(i+1)) res[x++] = i; res[x] = _y.value(); return res; } static JsonObject getCoefficients(int [] columnIds, ValueArray ary, double [] beta){ JsonObject coefficients = new JsonObject(); for( int i = 0; i < beta.length; ++i ) { String colName = (i == (beta.length - 1)) ? "Intercept" : ary._cols[columnIds[i]]._name; coefficients.addProperty(colName, beta[i]); } return coefficients; } GLMParams getGLMParams(){ Family family = _family.value(); Link link = _link.value(); if( family == Family.tweedie && !(link == Link.tweedie || link == Link.familyDefault)){ return null; } GLMParams res; if (family != Family.tweedie) res = new GLMParams(_family.value(),_link.value()); else { double variancePower = _tweediePower.value(); //TODO let tweedie also control link power Link l = Link.tweedie; l.tweedieLinkPower = 1. - variancePower; Family f = Family.tweedie; f.defaultLink = l; f.tweedieVariancePower = variancePower; res = new GLMParams(f, l, f.tweedieVariancePower, l.tweedieLinkPower); } if( res._link._link == Link.familyDefault && res._link._link != Link.tweedie ) res._link = new LinkIced( res._family._family.defaultLink ); res._maxIter = _maxIter.value(); res._betaEps = _betaEps.value(); if(_caseWeight.valid()) res._caseWeight = _caseWeight.value(); if(_case.valid()) res._caseVal = _case.value(); res._caseMode = _caseMode.valid()?_caseMode.value():CaseMode.none; return res; } @Override protected Response serve() { try { JsonObject res = new JsonObject(); Key dest = _dest.value(); ValueArray ary = _key.value(); int[] columns = createColumns(); res.addProperty("key", ary._key.toString()); res.addProperty("h2o", H2O.SELF.toString()); GLMParams glmParams = getGLMParams(); if (glmParams == null){ if (_family.value() == Family.tweedie && _link.value() == Link.tweedie){ return Response.error("tweedie family requires tweedie link"); } return Response.error("error reading glm parameters"); } if (glmParams._family._family == Family.tweedie){ double p = _tweediePower.value(); if ( !(1. < p && p < 2.) ){ return Response.error("tweedie family specified but invalid tweedie power: must be in (1,2)"); } } DataFrame data = DGLM.getData(ary, columns, null, _standardize.value()); LSMSolver lsm = null; switch(_lsmSolver.value()){ case AUTO: lsm = //data.expandedSz() < 1000? new ADMMSolver(_lambda.value(),_alpha.value());//: //new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); break; case ADMM: lsm = new ADMMSolver(_lambda.value(),_alpha.value()); break; case GenGradient: lsm = new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); } GLMJob job = DGLM.startGLMJob(dest, data, lsm, glmParams, null, _xval.value(), true); JsonObject j = new JsonObject(); j.addProperty(Constants.DEST_KEY, job.dest().toString()); Response r = GLMProgressPage.redirect(j, job.self(), job.dest(),job.progressKey()); r.setBuilder(Constants.DEST_KEY, new KeyElementBuilder()); return r; }catch(GLMException e){ Log.err(e); return Response.error(e.getMessage()); } catch (Throwable t) { Log.err(t); return Response.error(t.getMessage()); } } }
hardikk/h2o
src/main/java/water/api/GLM.java
249,340
package water.api; import hex.*; import hex.DGLM.CaseMode; import hex.DGLM.Family; import hex.DGLM.GLMJob; import hex.DGLM.GLMModel; import hex.DGLM.GLMParams; import hex.DGLM.Link; import hex.DGLM.LinkIced; import hex.DLSM.ADMMSolver; import hex.DLSM.GeneralizedGradientSolver; import hex.DLSM.LSMSolver; import hex.DLSM.LSMSolverType; import hex.NewRowVecTask.DataFrame; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; import water.*; import water.util.Log; import water.util.RString; import com.google.gson.JsonObject; public class GLM extends Request { protected final H2OKey _dest = new H2OKey(DEST_KEY, false, true); protected final H2OHexKey _key = new H2OHexKey(KEY); protected final H2OHexKeyCol _y = new H2OHexKeyCol(Y, _key); protected final HexColumnSelect _x = new HexNonConstantColumnSelect(X, _key, _y); protected final H2OGLMModelKey _modelKey = new H2OGLMModelKey(MODEL_KEY,false); protected final EnumArgument<Family> _family = new EnumArgument(FAMILY,Family.gaussian,true); protected final LinkArg _link = new LinkArg(_family,LINK); protected final Real _lambda = new Real(LAMBDA, 1e-5); // TODO I do not know the bounds protected final Real _alpha = new Real(ALPHA, 0.5, 0, 1, ""); protected final Real _prior = new Real(PRIOR,null){ @Override public Double defaultValue(){ ValueArray.Column col = _key.value()._cols[_y.value()]; return 0 <= col._min && col._max <= 1?col._mean:Double.NaN; } @Override protected String queryComment() { return "prior(real) probability of class 1"; } @Override protected String queryDescription() { return "Use to override expected mean of the response in case the dataset has been sampled and its mean differs from the expected one. Returned model will be rebalanced to reflect the expected mean."; } }; protected final Real _tweediePower = new Real(TWEEDIE_POWER, 1.5); protected final CaseModeSelect _caseMode = new CaseModeSelect(_key,_y,_family, CASE_MODE,CaseMode.none); protected final CaseSelect _case = new CaseSelect(_key,_y,_caseMode,CASE); protected final Int _xval = new Int(XVAL, 10, 0, 1000000); protected final Bool _expertSettings = new Bool("expert_settings", true ,"Show expert settings."); // ------------------------------------- ADVANCED SETTINGS ------------------------------------------------------------------------------------ protected final Bool _standardize = new Bool("standardize", true, "Set to standardize (0 mean, unit variance) the data before training."); protected final RSeq _thresholds = new RSeq(DTHRESHOLDS, false, new NumberSequence("0:1:0.01", false, 0.01),false); protected final EnumArgument<LSMSolverType> _lsmSolver = new EnumArgument<LSMSolverType>("lsm_solver", LSMSolverType.AUTO); protected final Real _betaEps = new Real(BETA_EPS,1e-4); protected final Int _maxIter = new Int(MAX_ITER, 50, 1, 1000000); public GLM() { _prior.addPrerequisite(_key); _prior.addPrerequisite(_y); _requestHelp = "Compute generalized linear model with penalized maximum likelihood. Penalties include the lasso (L1 penalty), ridge regression (L2 penalty) or elastic net penalty (combination of L1 and L2) penalties. The penalty function is defined as :<br/>" + "<pre>\n" + " P(&beta;) = 0.5*(1 - &alpha;)*||&beta;||<sub>2</sub><sup>2</sup> + &alpha;*||&beta;||<sub>1</sub><br/>"+ "</pre>" + "By setting &alpha; to 0, we get ridge regression, setting it to 1 gets us lasso. <p>See our <a href='https://github.com/0xdata/h2o/wiki/GLM#wiki-Details' target=\"_blank\">wiki</a> for details.<p>"; _key._requestHelp = "Dataset to be trained on."; _y._requestHelp = "Response variable column name."; _x._requestHelp = "Predictor columns to be trained on. Constant columns will be ignored."; _modelKey._hideInQuery = true; _modelKey._requestHelp = "The H2O's Key name for the model"; _family._requestHelp = "Pick the general mathematical family for the trained model.<br><ul>"+ "<li><b>gaussian</b> models describe a simple hyper-plane (for a single column this will be a simple line) for the response variable. This is a suitable model for when you expect the response variable to vary as a linear combination of predictor variables. An example might be predicting the gas mileage of cars, based on their weight, age, and engine size.</li>"+ "<li><b>binomial</b> models form an S-curve response, showing probabilities that vary from 0 to 1. This is a suitable model for when you expect a simple boolean result (e.g. alive/dead, or fraud/no-fraud). The model gives a probability of the true event. An example might be to predict the presence of prostate cancer given the patient age, race, and various blood chemical levels such as PSA.</li>"+ "</ul>"; _link._requestHelp = "Link function to be used."; _lambda._requestHelp = "Penalty argument. Higher lambda means higher penalty is applied on the size of the beta vector."; _alpha._requestHelp = "Penalty distribution argument. Controls distribution of penalty between L1 and L2 norm according to the formula above."; _betaEps._requestHelp = "Precision of the vector of coefficients. Computation stops when the maximal difference between two beta vectors is below than Beta epsilon."; _maxIter._requestHelp = "Number of maximum iterations."; _prior._requestHelp = "Prior probability of positive case (class = 1) for logistic regression. To be used if the data has been sampled."; _caseMode._requestHelp = "Predicate selection."; _case._requestHelp = "Value to be used to compare against using predicate given by case mode selector to turn the y column into boolean."; _thresholds._requestHelp = "Sequence of decision thresholds to be evaluated during validation (used for ROC curce computation and for picking optimal decision threshold of the resulting classifier)."; _xval._requestHelp = "Number of fold used in cross-validation. 0 or 1 means no cross validation."; _expertSettings.setRefreshOnChange(); } public static String link(Key k, String content) { RString rs = new RString("<a href='GLM.query?%key_param=%$key'>%content</a>"); rs.replace("key_param", KEY); rs.replace("key", k.toString()); rs.replace("content", content); return rs.toString(); } static void getColumnIdxs(StringBuilder sb, ValueArray ary, String [] cols ){ Arrays.sort(cols); boolean firstCol = false; for(int i = 0; i < ary._cols.length; ++i) if(Arrays.binarySearch(cols, ary._cols[i]._name) >= 0) if(firstCol){ sb.append(""+i); firstCol = false; } else sb.append(","+i); } public static String link(Key k, GLMModel m, String content) { int [] colIds = m.selectedColumns(); if(colIds == null)return ""; /// the dataset is no longer on H2O, no link shoudl be produced! try { StringBuilder sb = new StringBuilder("<a href='GLM.query?"); sb.append(KEY + "=" + k.toString()); sb.append("&y=" + m.responseName()); // find the column idxs...(the model keeps only names) sb.append("&x=" + colIds[0]); for(int i = 1; i < colIds.length-1; ++i) sb.append(","+colIds[i]); sb.append("&family=" + m._glmParams._family._family.toString()); sb.append("&tweedie_power=" + m._glmParams._family._tweedieVariancePower); sb.append("&link=" + m._glmParams._link._link.toString()); sb.append("&lambda=" + m._solver._lambda); sb.append("&alpha=" + m._solver._alpha); sb.append("&beta_eps=" + m._glmParams._betaEps); sb.append("&weight=" + m._glmParams._caseWeight); sb.append("&max_iter=" + m._glmParams._maxIter); sb.append("&caseMode=" + URLEncoder.encode(m._glmParams._caseMode.toString(),"utf8")); sb.append("&case=" + m._glmParams._caseVal); sb.append("'>" + content + "</a>"); return sb.toString(); } catch( UnsupportedEncodingException e ) { throw Log.errRTExcept(e); } } @Override protected void queryArgumentValueSet(Argument arg, Properties inputArgs) { if(arg == _caseMode){ if(_caseMode.value() == CaseMode.none) _case.disable("n/a"); } else if (arg == _family) { if (_family.value() != Family.binomial) { _case.disable("Only for family binomial"); _caseMode.disable("Only for family binomial"); _prior.disable("Only for family binomial"); _thresholds.disable("Only for family binomial"); } if (_family.value() != Family.tweedie){ _tweediePower.disable("Only for family tweedie"); } } else if (arg == _expertSettings){ if(_expertSettings.value()){ _lsmSolver._hideInQuery = false; _thresholds._hideInQuery = false; _maxIter._hideInQuery = false; _betaEps._hideInQuery = false; //_reweightGram._hideInQuery = false; _standardize._hideInQuery = false; } else { _lsmSolver._hideInQuery = true; _thresholds._hideInQuery = true; _maxIter._hideInQuery = true; _betaEps._hideInQuery = true; //_reweightGram._hideInQuery = true; _standardize._hideInQuery = true; } } } /** Returns an array of columns to use for GLM, the last of them being the * result column y. */ private int[] createColumns() { BitSet cols = new BitSet(); for( int i : _x.value() ) cols.set (i); //for( int i : _negX.value() ) cols.clear(i); int[] res = new int[cols.cardinality()+1]; int x=0; for( int i = cols.nextSetBit(0); i >= 0; i = cols.nextSetBit(i+1)) res[x++] = i; res[x] = _y.value(); return res; } static JsonObject getCoefficients(int [] columnIds, ValueArray ary, double [] beta){ JsonObject coefficients = new JsonObject(); for( int i = 0; i < beta.length; ++i ) { String colName = (i == (beta.length - 1)) ? "Intercept" : ary._cols[columnIds[i]]._name; coefficients.addProperty(colName, beta[i]); } return coefficients; } GLMParams getGLMParams(){ Family family = _family.value(); Link link = _link.value(); if( family == Family.tweedie && !(link == Link.tweedie || link == Link.familyDefault)){ return null; } GLMParams res; if (family != Family.tweedie) res = new GLMParams(_family.value(),_link.value()); else { double variancePower = _tweediePower.value(); //TODO let tweedie also control link power Link l = Link.tweedie; l.tweedieLinkPower = 1. - variancePower; Family f = Family.tweedie; f.defaultLink = l; f.tweedieVariancePower = variancePower; res = new GLMParams(f, l, f.tweedieVariancePower, l.tweedieLinkPower); } if( res._link._link == Link.familyDefault && res._link._link != Link.tweedie ) res._link = new LinkIced( res._family._family.defaultLink ); res._maxIter = _maxIter.value(); res._betaEps = _betaEps.value(); if(_case.valid()) res._caseVal = _case.value(); res._caseMode = _caseMode.valid()?_caseMode.value():CaseMode.none; return res; } @Override protected Response serve() { try { JsonObject res = new JsonObject(); Key dest = _dest.value(); ValueArray ary = _key.value(); int[] columns = createColumns(); res.addProperty("key", ary._key.toString()); res.addProperty("h2o", H2O.SELF.toString()); GLMParams glmParams = getGLMParams(); if (glmParams == null){ if (_family.value() == Family.tweedie && _link.value() == Link.tweedie){ return Response.error("tweedie family requires tweedie link"); } return Response.error("error reading glm parameters"); } if (glmParams._family._family == Family.tweedie){ double p = _tweediePower.value(); if ( !(1. < p && p < 2.) ){ return Response.error("tweedie family specified but invalid tweedie power: must be in (1,2)"); } } DataFrame data = DGLM.getData(ary, columns, null, _standardize.value()); LSMSolver lsm = null; switch(_lsmSolver.value()){ case AUTO: lsm = //data.expandedSz() < 1000? new ADMMSolver(_lambda.value(),_alpha.value());//: //new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); break; case ADMM: lsm = new ADMMSolver(_lambda.value(),_alpha.value()); break; case GenGradient: lsm = new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); } Double prior = _prior.value(); if(prior == null || prior == -1)prior = _prior.defaultValue(); GLMJob job = DGLM.startGLMJob(dest, data, lsm, glmParams, null, prior, _xval.value(), true); JsonObject j = new JsonObject(); j.addProperty(Constants.DEST_KEY, job.dest().toString()); Response r = GLMProgressPage.redirect(j, job.self(), job.dest(),job.progressKey()); r.setBuilder(Constants.DEST_KEY, new KeyElementBuilder()); return r; } catch( Throwable t ) { return Response.error(t); } } }
ctyeong/h2o
src/main/java/water/api/GLM.java
249,341
404: Not Found
HansHeidmann/RotLA
src/ExpertStrategy.java
249,342
package model; import controllers.MorphiaObject; import org.bson.types.ObjectId; import org.mongodb.morphia.annotations.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created by mahabaleshwar on 9/14/2016. */ @Entity("experts") @Indexes(@Index(value = "name", fields = @Field("name"))) public class Expert { @Id private ObjectId _id; @Indexed private String name; private String dept; private String emailid; private String imageURL; private String initials; private List<String> expertise; public List<String> findAllExpertiseTokens() { List<Expert> experts = (List<Expert>) MorphiaObject.datastore.createQuery(this.getClass()).asList(); Set<String> expertise = new HashSet<String>(); for(Expert expert: experts) { expertise.addAll(expert.getExpertise()); } return new ArrayList(expertise); } public List<String> getExpertise() { return expertise; } }
sebischair/akre-server
app/model/Expert.java
249,345
package water.api; import hex.*; import hex.DGLM.CaseMode; import hex.DGLM.Family; import hex.DGLM.GLMException; import hex.DGLM.GLMModel; import hex.DGLM.GLMParams; import hex.DGLM.GLMValidation; import hex.DGLM.Link; import hex.DLSM.ADMMSolver; import hex.DLSM.GeneralizedGradientSolver; import hex.DLSM.LSMSolver; import hex.DLSM.LSMSolverType; import hex.NewRowVecTask.DataFrame; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DecimalFormat; import java.util.*; import java.util.Map.Entry; import water.*; import water.util.RString; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class GLM extends Request { protected final H2OHexKey _key = new H2OHexKey(KEY); protected final H2OHexKeyCol _y = new H2OHexKeyCol(Y, _key); protected final HexColumnSelect _x = new HexNonConstantColumnSelect(X, _key, _y); protected final H2OGLMModelKey _modelKey = new H2OGLMModelKey(MODEL_KEY,false); protected final EnumArgument<Family> _family = new EnumArgument(FAMILY,Family.gaussian,true); protected final LinkArg _link = new LinkArg(_family,LINK); protected final Real _lambda = new Real(LAMBDA, 1e-5); // TODO I do not know the bounds protected final Real _alpha = new Real(ALPHA, 0.5, 0, 1, ""); protected final Real _caseWeight = new Real(WEIGHT,1.0); protected final CaseModeSelect _caseMode = new CaseModeSelect(_key,_y,_family, CASE_MODE,CaseMode.none); protected final CaseSelect _case = new CaseSelect(_key,_y,_caseMode,CASE); protected final Int _xval = new Int(XVAL, 10, 0, 1000000); protected final Bool _expertSettings = new Bool("expert_settings", false,"Show expert settings."); // ------------------------------------- ADVANCED SETTINGS ------------------------------------------------------------------------------------ protected final Bool _standardize = new Bool("standardize", true, "Set to standardize (0 mean, unit variance) the data before training."); protected final RSeq _thresholds = new RSeq(DTHRESHOLDS, false, new NumberSequence("0:1:0.01", false, 0.01),false); protected final EnumArgument<LSMSolverType> _lsmSolver = new EnumArgument<LSMSolverType>("lsm_solver", LSMSolverType.ADMM); protected final Real _betaEps = new Real(BETA_EPS,1e-4); protected final Int _maxIter = new Int(MAX_ITER, 50, 1, 1000000); //protected final Bool _reweightGram = new Bool("reweigthed_gram_xval", false, "Set to force reweighted gram matrix for cross-validation (non-reweighted xval is much faster, less precise)."); public GLM() { _requestHelp = "Compute generalized linear model with penalized maximum likelihood. Penalties include the lasso (L1 penalty), ridge regression (L2 penalty) or elastic net penalty (combination of L1 and L2) penalties. The penalty function is defined as :<br/>" + "<pre>\n" + " P(&beta;) = 0.5*(1 - &alpha;)*||&beta;||<sub>2</sub><sup>2</sup> + &alpha;*||&beta;||<sub>1</sub><br/>"+ "</pre>" + "By setting &alpha; to 0, we get ridge regression, setting it to 1 gets us lasso. <p>See our <a href='https://github.com/0xdata/h2o/wiki/GLM#wiki-Details' target=\"_blank\">wiki</a> for details.<p>"; _key._requestHelp = "Dataset to be trained on."; _y._requestHelp = "Response variable column name."; _x._requestHelp = "Predictor columns to be trained on. Constant columns will be ignored."; _modelKey._hideInQuery = true; _modelKey._requestHelp = "The H2O's Key name for the model"; _family._requestHelp = "Pick the general mathematical family for the trained model.<br><ul>"+ "<li><b>gaussian</b> models describe a simple hyper-plane (for a single column this will be a simple line) for the response variable. This is a suitable model for when you expect the response variable to vary as a linear combination of predictor variables. An example might be predicting the gas mileage of cars, based on their weight, age, and engine size.</li>"+ "<li><b>binomial</b> models form an S-curve response, showing probabilities that vary from 0 to 1. This is a suitable model for when you expect a simple boolean result (e.g. alive/dead, or fraud/no-fraud). The model gives a probability of the true event. An example might be to predict the presence of prostate cancer given the patient age, race, and various blood chemical levels such as PSA.</li>"+ "</ul>"; _link._requestHelp = "Link function to be used."; _lambda._requestHelp = "Penalty argument. Higher lambda means higher penalty is applied on the size of the beta vector."; _alpha._requestHelp = "Penalty distribution argument. Controls distribution of penalty between L1 and L2 norm according to the formula above."; _betaEps._requestHelp = "Precision of the vector of coefficients. Computation stops when the maximal difference between two beta vectors is below than Beta epsilon."; _maxIter._requestHelp = "Number of maximum iterations."; _caseWeight._requestHelp = "All rows for which the predicate is true will be weighted by weight. Weight=1 is neutral. Weight = 0.5 treats negative examples as twice more important than positive ones. Weight = 2.0 does the opposite."; _caseMode._requestHelp = "Predicate selection."; _case._requestHelp = "Value to be used to compare against using predicate given by case mode selector to turn the y column into boolean."; _thresholds._requestHelp = "Sequence of decision thresholds to be evaluated during validation (used for ROC curce computation and for picking optimal decision threshold of the resulting classifier)."; _xval._requestHelp = "Number of fold used in cross-validation. 0 or 1 means no cross validation."; _expertSettings.setRefreshOnChange(); } public static String link(Key k, String content) { RString rs = new RString("<a href='GLM.query?%key_param=%$key'>%content</a>"); rs.replace("key_param", KEY); rs.replace("key", k.toString()); rs.replace("content", content); return rs.toString(); } public static String link(Key k, GLMModel m, String content) { try { StringBuilder sb = new StringBuilder("<a href='GLM.query?"); sb.append(KEY + "=" + k.toString()); sb.append("&y=" + m.responseName()); sb.append("&x=" + URLEncoder.encode(m.xcolNames(),"utf8")); sb.append("&family=" + m._glmParams._family.toString()); sb.append("&link=" + m._glmParams._link.toString()); sb.append("&lambda=" + m._solver._lambda); sb.append("&alpha=" + m._solver._alpha); sb.append("&beta_eps=" + m._glmParams._betaEps); sb.append("&weight=" + m._glmParams._caseWeight); sb.append("&max_iter=" + m._glmParams._maxIter); sb.append("&caseMode=" + URLEncoder.encode(m._glmParams._caseMode.toString(),"utf8")); sb.append("&case=" + m._glmParams._caseVal); sb.append("'>" + content + "</a>"); return sb.toString(); } catch( UnsupportedEncodingException e ) { throw new RuntimeException(e); } } @Override protected void queryArgumentValueSet(Argument arg, Properties inputArgs) { if(arg == _caseMode){ if(_caseMode.value() == CaseMode.none) _case.disable("n/a"); } else if (arg == _family) { if (_family.value() != Family.binomial) { _case.disable("Only for family binomial"); _caseMode.disable("Only for family binomial"); _caseWeight.disable("Only for family binomial"); _thresholds.disable("Only for family binomial"); } } else if (arg == _expertSettings){ if(_expertSettings.value()){ _lsmSolver._hideInQuery = false; _thresholds._hideInQuery = false; _maxIter._hideInQuery = false; _betaEps._hideInQuery = false; //_reweightGram._hideInQuery = false; _standardize._hideInQuery = false; } else { _lsmSolver._hideInQuery = true; _thresholds._hideInQuery = true; _maxIter._hideInQuery = true; _betaEps._hideInQuery = true; //_reweightGram._hideInQuery = true; _standardize._hideInQuery = true; } } } /** Returns an array of columns to use for GLM, the last of them being the * result column y. */ private int[] createColumns() { BitSet cols = new BitSet(); for( int i : _x.value() ) cols.set (i); //for( int i : _negX.value() ) cols.clear(i); int[] res = new int[cols.cardinality()+1]; int x=0; for( int i = cols.nextSetBit(0); i >= 0; i = cols.nextSetBit(i+1)) res[x++] = i; res[x] = _y.value(); return res; } static JsonObject getCoefficients(int [] columnIds, ValueArray ary, double [] beta){ JsonObject coefficients = new JsonObject(); for( int i = 0; i < beta.length; ++i ) { String colName = (i == (beta.length - 1)) ? "Intercept" : ary._cols[columnIds[i]]._name; coefficients.addProperty(colName, beta[i]); } return coefficients; } GLMParams getGLMParams(){ GLMParams res = new GLMParams(_family.value(),_link.value()); if( res._link == Link.familyDefault ) res._link = res._family.defaultLink; res._maxIter = _maxIter.value(); res._betaEps = _betaEps.value(); if(_caseWeight.valid()) res._caseWeight = _caseWeight.value(); if(_case.valid()) res._caseVal = _case.value(); res._caseMode = _caseMode.valid()?_caseMode.value():CaseMode.none; return res; } @Override protected Response serve() { try { JsonObject res = new JsonObject(); ValueArray ary = _key.value(); int[] columns = createColumns(); res.addProperty("key", ary._key.toString()); res.addProperty("h2o", H2O.SELF.toString()); GLMParams glmParams = getGLMParams(); LSMSolverType t = _lsmSolver.value(); LSMSolver lsm = null; switch(t){ case ADMM: lsm = new ADMMSolver(_lambda.value(),_alpha.value()); break; case GenGradient: lsm = new GeneralizedGradientSolver(_lambda.value(),_alpha.value()); } DataFrame data = DGLM.getData(ary, columns, null, _standardize.value()); GLMModel m = DGLM.buildModel(data, lsm, glmParams); if( m.isSolved() ) { // Solved at all? NumberSequence nseq = _thresholds.value(); double[] arr = nseq == null ? null : nseq._arr; if( _xval.specified() && _xval.value() > 1 ) // ... and x-validate m.xvalidate(ary,_xval.value(),arr); else m.validateOn(ary, null,arr); // Full scoring on original dataset } // Convert to JSON res.add("GLMModel", m.toJson()); // Display HTML setup Response r = Response.done(res); r.setBuilder(""/*top-level do-it-all builder*/,new GLMBuilder(m)); return r; }catch(GLMException e){ return Response.error(e.getMessage()); } catch (Throwable t) { t.printStackTrace(); return Response.error(t.getMessage()); } } static class GLMBuilder extends ObjectBuilder { final GLMModel _m; GLMBuilder( GLMModel m) { _m=m; } public String build(Response response, JsonObject json, String contextName) { StringBuilder sb = new StringBuilder();; modelHTML(_m,json.get("GLMModel").getAsJsonObject(),sb); return sb.toString(); } private static void modelHTML( GLMModel m, JsonObject json, StringBuilder sb ) { sb.append("<div class='alert'>Actions: " + (m.isSolved() ? (GLMScore.link(m._selfKey,m._vals[0].bestThreshold(), "Validate on another dataset") + ", "):"") + GLM.link(m._dataKey,m, "Compute new model") + "</div>"); RString R = new RString( "<div class='alert %succ'>GLM on data <a href='/Inspect.html?"+KEY+"=%key'>%key</a>.<br>" + "%iterations iterations computed in %time. %xval %warnings %action</div>" + "<h4>GLM Parameters</h4>" + " %GLMParams %LSMParams" + "<h4>Equation: </h4>" + "<div><code>%modelSrc</code></div>"+ "<h4>Coefficients</h4>" + "<div>%coefficients</div>" + "<h4>Normalized Coefficients</h4>" + "<div>%normalized_coefficients</div>" ); // Warnings if( m._warnings != null ) { StringBuilder wsb = new StringBuilder(); for( String s : m._warnings ) wsb.append(s).append("<br>"); R.replace("warnings",wsb); R.replace("succ","alert-warning"); if(!m.converged()) R.replace("action","Suggested action: Go to " + (m.isSolved() ? (GLMGrid.link(m, "Grid search") + ", "):"") + " to search for better parameters"); } else { R.replace("succ","alert-success"); } // Basic model stuff R.replace("key",m._dataKey); R.replace("time",PrettyPrint.msecs(m._time,true)); int count = 0; long xtime = 0; for( GLMValidation v : m._vals ) { if(v._modelKeys != null)for( Key k : v._modelKeys) { GLMModel m2 = UKV.get(k, new GLMModel()); xtime += m2._time; ++count; } } if( xtime > 0 ) { R.replace("xval", "<br>"+count +" cross validations computed in " + PrettyPrint.msecs(xtime, true) +"."); } else { R.replace("xval", ""); } R.replace("iterations",m._iterations); R.replace("GLMParams",glmParamsHTML(m)); R.replace("LSMParams",lsmParamsHTML(m)); // Pretty equations if( m.isSolved() ) { JsonObject coefs = json.get("coefficients").getAsJsonObject(); R.replace("modelSrc",equationHTML(m,coefs)); R.replace("coefficients",coefsHTML(coefs)); if(json.has("normalized_coefficients")) R.replace("normalized_coefficients",coefsHTML(json.get("normalized_coefficients").getAsJsonObject())); } sb.append(R); // Validation / scoring if(m._vals != null) validationHTML(m._vals,sb); } private static final String ALPHA = "&alpha;"; private static final String LAMBDA = "&lambda;"; private static final String EPSILON = "&epsilon;<sub>&beta;</sub>"; private static final DecimalFormat DFORMAT = new DecimalFormat("###.####"); private static final String dformat( double d ) { return Double.isNaN(d) ? "NaN" : DFORMAT.format(d); } private static void parm( StringBuilder sb, String x, Object... y ) { sb.append("<span><b>").append(x).append(": </b>").append(y[0]).append("</span> "); } private static String glmParamsHTML( GLMModel m ) { StringBuilder sb = new StringBuilder(); GLMParams glmp = m._glmParams; parm(sb,"family",glmp._family); parm(sb,"link",glmp._link); parm(sb,"&alpha;",m._solver._alpha); parm(sb,"&lambda;",m._solver._lambda); parm(sb,EPSILON,glmp._betaEps); if( glmp._caseMode != CaseMode.none) { parm(sb,"case",glmp._caseMode.exp(glmp._caseVal)); parm(sb,"weight",glmp._caseWeight); } return sb.toString(); } private static String lsmParamsHTML( GLMModel m ) { StringBuilder sb = new StringBuilder(); LSMSolver lsm = m._solver; //parm(sb,LAMBDA,lsm._lambda); //parm(sb,ALPHA ,lsm._alpha); return sb.toString(); } // Pretty equations private static String equationHTML( GLMModel m, JsonObject coefs ) { RString eq = null; switch( m._glmParams._link ) { case identity: eq = new RString("y = %equation"); break; case logit: eq = new RString("y = 1/(1 + Math.exp(-(%equation)))"); break; default: eq = new RString("equation display not implemented"); break; } StringBuilder sb = new StringBuilder(); for( Entry<String,JsonElement> e : coefs.entrySet() ) { if( e.getKey().equals("Intercept") ) continue; double v = e.getValue().getAsDouble(); if( v == 0 ) continue; sb.append(dformat(v)).append("*x[").append(e.getKey()).append("] + "); } sb.append(coefs.get("Intercept").getAsDouble()); eq.replace("equation",sb.toString()); return eq.toString(); } private static String coefsHTML( JsonObject coefs ) { StringBuilder sb = new StringBuilder(); sb.append("<table class='table table-bordered table-condensed'>"); sb.append("<tr>"); sb.append("<th>").append("Intercept").append("</th>"); for( Entry<String,JsonElement> e : coefs.entrySet() ){ if(e.getKey().equals("Intercept"))continue; sb.append("<th>").append(e.getKey()).append("</th>"); } sb.append("</tr>"); sb.append("<tr>"); sb.append("<td>").append(coefs.get("Intercept").getAsDouble()).append("</td>"); for( Entry<String,JsonElement> e : coefs.entrySet()){ if(e.getKey().equals("Intercept"))continue; sb.append("<td>").append(e.getValue().getAsDouble()).append("</td>"); } sb.append("</tr>"); sb.append("</table>"); return sb.toString(); } static void validationHTML(GLMValidation val, StringBuilder sb){ RString valHeader = new RString("<div class='alert'>Validation of model <a href='/Inspect.html?"+KEY+"=%modelKey'>%modelKey</a> on dataset <a href='/Inspect.html?"+KEY+"=%dataKey'>%dataKey</a></div>"); RString xvalHeader = new RString("<div class='alert'>%valName of model <a href='/Inspect.html?"+KEY+"=%modelKey'>%modelKey</a></div>"); RString R = new RString("<table class='table table-striped table-bordered table-condensed'>" + "<tr><th>Degrees of freedom:</th><td>%DegreesOfFreedom total (i.e. Null); %ResidualDegreesOfFreedom Residual</td></tr>" + "<tr><th>Null Deviance</th><td>%nullDev</td></tr>" + "<tr><th>Residual Deviance</th><td>%resDev</td></tr>" + "<tr><th>AIC</th><td>%AIC</td></tr>" + "<tr><th>Training Error Rate Avg</th><td>%err</td></tr>" +"%CM" + "</table>"); RString R2 = new RString( "<tr><th>AUC</th><td>%AUC</td></tr>" + "<tr><th>Best Threshold</th><td>%threshold</td></tr>"); if(val.fold() > 1){ xvalHeader.replace("valName", val.fold() + " fold cross validation"); xvalHeader.replace("modelKey", val.modelKey()); sb.append(xvalHeader.toString()); } else { valHeader.replace("modelKey", val.modelKey()); valHeader.replace("dataKey",val.dataKey()); sb.append(valHeader.toString()); } R.replace("DegreesOfFreedom",val._n-1); R.replace("ResidualDegreesOfFreedom",val._dof); R.replace("nullDev",val._nullDeviance); R.replace("resDev",val._deviance); R.replace("AIC", dformat(val.AIC())); R.replace("err",val.err()); if(val._cm != null){ R2.replace("AUC", dformat(val.AUC())); R2.replace("threshold", dformat(val.bestThreshold())); R.replace("CM",R2); } sb.append(R); confusionHTML(val.bestCM(),sb); if(val.fold() > 1){ int nclasses = 2; sb.append("<table class='table table-bordered table-condensed'>"); if(val._cm != null){ sb.append("<tr><th>Model</th><th>Best Threshold</th><th>AUC</th>"); for(int c = 0; c < nclasses; ++c) sb.append("<th>Err(" + c + ")</th>"); sb.append("</tr>"); // Display all completed models int i=0; for(GLMModel xm:val.models()){ String mname = "Model " + i++; sb.append("<tr>"); try { sb.append("<td>" + "<a href='Inspect.html?"+KEY+"="+URLEncoder.encode(xm._selfKey.toString(),"UTF-8")+"'>" + mname + "</a></td>"); } catch( UnsupportedEncodingException e1 ) { throw new Error(e1); } sb.append("<td>" + dformat(xm._vals[0].bestThreshold()) + "</td>"); sb.append("<td>" + dformat(xm._vals[0].AUC()) + "</td>"); for(double e:xm._vals[0].classError()) sb.append("<td>" + dformat(e) + "</td>"); sb.append("</tr>"); } } else { sb.append("<tr><th>Model</th><th>Error</th>"); sb.append("</tr>"); // Display all completed models int i=0; for(GLMModel xm:val.models()){ String mname = "Model " + i++; sb.append("<tr>"); try { sb.append("<td>" + "<a href='Inspect.html?"+KEY+"="+URLEncoder.encode(xm._selfKey.toString(),"UTF-8")+"'>" + mname + "</a></td>"); } catch( UnsupportedEncodingException e1 ) { throw new Error(e1); } sb.append("<td>" + ((xm._vals != null)?xm._vals[0]._err:Double.NaN) + "</td>"); sb.append("</tr>"); } } sb.append("</table>"); } } private static void validationHTML( GLMValidation[] vals, StringBuilder sb) { if( vals == null || vals.length == 0 ) return; sb.append("<h4>Validations</h4>"); for( GLMValidation val : vals ) if(val != null)validationHTML(val, sb); } private static void cmRow( StringBuilder sb, String hd, double c0, double c1, double cerr ) { sb.append("<tr><th>").append(hd).append("</th><td>"); if( !Double.isNaN(c0 )) sb.append( dformat(c0 )); sb.append("</td><td>"); if( !Double.isNaN(c1 )) sb.append( dformat(c1 )); sb.append("</td><td>"); if( !Double.isNaN(cerr)) sb.append( dformat(cerr)); sb.append("</td></tr>"); } private static void confusionHTML( ConfusionMatrix cm, StringBuilder sb) { if( cm == null ) return; sb.append("<table class='table table-bordered table-condensed'>"); sb.append("<tr><th>Actual / Predicted</th><th>false</th><th>true</th><th>Err</th></tr>"); double err0 = cm._arr[0][1]/(double)(cm._arr[0][0]+cm._arr[0][1]); cmRow(sb,"false",cm._arr[0][0],cm._arr[0][1],err0); double err1 = cm._arr[1][0]/(double)(cm._arr[1][0]+cm._arr[1][1]); cmRow(sb,"true ",cm._arr[1][0],cm._arr[1][1],err1); double err2 = cm._arr[1][0]/(double)(cm._arr[0][0]+cm._arr[1][0]); double err3 = cm._arr[0][1]/(double)(cm._arr[0][1]+cm._arr[1][1]); cmRow(sb,"Err ",err2,err3,cm.err()); sb.append("</table>"); } } }
agibsonccc/h2o
src/main/java/water/api/GLM.java
249,346
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package experts; import experts.Database.FCDatabase; import experts.Entities.Rule; import java.util.ArrayList; /** * * @author owner */ public class Experts { /** * @param args the command line arguments */ public static void main(String[] args) { } }
5l1v3r1/Aplikasi-Pakar
Experts/src/experts/Experts.java
249,347
package ks; import javax.print.attribute.HashAttributeSet; import java.util.*; import java.util.stream.Collectors; public class KSGraph { Map<String,Person> persons = new HashMap<>(); Map<String,Word> words = new HashMap<>(); public void addPersonPersonRelation(String from , String to) { Person fromPerson = persons.computeIfAbsent(from,f->new Person(from)); Person toPerson = persons.computeIfAbsent(to,t->new Person(to)); fromPerson.add(toPerson); toPerson.add(fromPerson); } public void addPersonWordRelationship(String from , String wordStr) { Person fromPerson = persons.computeIfAbsent(from,f->new Person(from)); Word word = words.computeIfAbsent(wordStr,w->new Word(w)); word.add(fromPerson); fromPerson.add(word); } public List<String> whom(String name) { Person person = persons.get(name); if (person!=null) { List<String> results = person.persons.keySet().stream().map(p->p.emailid).collect(Collectors.toList()); return results; } else { return null; } } public List<String> topNPersons(String name, int count) { Person person = persons.get(name); if (person!=null) { List<String> results = person.persons.entrySet().stream().sorted((e1,e2)->{return Integer.compare(e2.getValue(),e1.getValue());}) .limit(count) .map(entry->entry.getKey().emailid).collect(Collectors.toList()); /* List<String> results = person.persons.entrySet().stream().sorted(Map.Entry<Person,Integer>::comparingByValue().reversed()) .limit(count) .map(entry->entry.getKey().emailid).collect(Collectors.toList());*/ return results; } else { return null; } } public List<String> topNAreasOfExpertise(String name, int count) { Person person = persons.get(name); if (person!=null) { List<String> results = person.words.entrySet().stream().sorted((e1,e2)->{return Integer.compare(e2.getValue(),e1.getValue());}) .limit(count) .map(entry->entry.getKey().word).collect(Collectors.toList()); /* List<String> results = person.persons.entrySet().stream().sorted(Map.Entry<Person,Integer>::comparingByValue().reversed()) .limit(count) .map(entry->entry.getKey().emailid).collect(Collectors.toList());*/ return results; } else { return null; } } public List<String> topNExperts(String name, int count) { Word word = words.get(name); if (word!=null) { List<String> results = word.persons.entrySet().stream().sorted((e1,e2)->{return Integer.compare(e2.getValue(),e1.getValue());}) .limit(count) .map(entry->entry.getKey().emailid).collect(Collectors.toList()); return results; } else { return null; } } public boolean doesP1knowP2(String name1, String name2) { Set<Person> visited = new HashSet<>(); Queue<Person> process = new ArrayDeque<>(); Person p1 = persons.get(name1); process.add(p1); while(!process.isEmpty()) { Person curr = process.remove(); if (curr.emailid.equalsIgnoreCase(name2)) return true; if (visited.contains(curr)) continue; curr.persons.keySet().stream().forEach(p->process.add(p)); visited.add(curr); } return false; } @Override public String toString() { return "KSGraph{" + "persons=" + persons + ", words=" + words + '}'; } public static void main(String[] args) { KSGraph ksGraph = new KSGraph(); FileProcessor fileProcessor = new FileProcessor(ksGraph); fileProcessor.processPersons(); fileProcessor.processWords(); System.out.println(ksGraph); System.out.println(ksGraph.whom("P1")); System.out.println(ksGraph.topNPersons("P1",2)); System.out.println(ksGraph.topNAreasOfExpertise("P5",2)); System.out.println(ksGraph.topNExperts("W5",2)); System.out.println(ksGraph.doesP1knowP2("P1" , "P7")); } }
manojkhanwalkar/EPI
main/src/ks/KSGraph.java
249,348
package tabPages; //import java.util.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.TreeSet; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import preprocessing.SegWords; import preprocessing.XMLReader; //import Pages.ExplorerPage; public class ComPreprocess extends Composite{ /** * show the filePath */ private String[] filePath; /** * show the filename */ private String filename; /** * when click the button ‘open file’, the filepath will be shown in the text */ private Text fileText; /** * a text show the number of unique user */ private Text userNumText; /** * a text show the num of docs in the file */ private Text docNumText; /** * a text shows the num of answers in the files */ private Text ansNumText; /** * a text shows the num of page in the table */ private Text pageNumText; /** * show the pages of the table */ private Text presentPageText; /** * input the page you want to go */ private Text turnPageText; /** * the class that translate the xml file */ private XMLReader xmlReader; /** * The number of column is 2 */ private static int COLUMNS_CNT = 2; /** * The number of row is 20 */ private static int ROWS_CNT = 20; /** * Show the page in the table */ private int page = 1; /** * show the title and ids of the xml file */ private Table tableTitle; /** * whether a xml file is open */ private boolean ifOpen = false; private boolean ifSeg = false; /** * a text that shows the details of a doc */ private Text docDetailText; /** * a text that shows the details of a segged doc */ private Text segDocDetailText; /** * the class that seg the words and rid off the stopwords */ private SegWords segWords; public static Map<Integer, Map<String,String>> segDocMapMap = new HashMap<Integer, Map<String,String>>(); public static Map<Integer, Map<String,String>> docMapMap = new HashMap<Integer, Map<String,String>>(); /** * the index of the model type<br> * 0:"不使用词典", <br>1: "使用词典", <br>2:"只保留词典" */ public static int indexType; /** * the number of the Experts passed to the tabPage ComPrecision */ public static int numExperts; /** * the number of the question passed to the tabPage ComPrecision */ public static int numQuestion; /** * the number of the answers passed to the tabPage ComPrecision */ public static int numAnswer; /** * a text that shows the words number */ private Text wordsNumText; /** * a text that shows the number of unique words */ private Text uniqueWordsNumText; /** * a text that shows the number of words that repeat more than 2 times */ private Text repeat2NumText; /** * a text that shows the number of words that repeat more than 10 times */ private Text repeat10NumText; /** * a text that shows the number of words that repeat more than 100 times */ private Text repeat100NumText; /** * the number of all the words */ private int wordsNum; /** * the number of all unique words */ private int uniqueWordsNum; /** * the number of all unique words, transfer to other class */ public static int uniqueWordsNumClone; /** * the number of all unique users; */ private int uniqueUserNum; /** * the number of all unique users, transfer to other class */ public static int uniqueUserNumClone; /** * the number of words repeat more than 2 */ private int repeat2Num; /** * the number of words repeat more than 10 */ private int repeat10Num; /** * the number of words repeat more than 10 */ private int repeat100Num; private Combo comboModelType; /** * the child node of the xml file */ private static String[] CHILDREN = {"问题标题","问题内容","提问者用户名","提问者性别","提问者年龄","提问时间", "回复人1姓名", "回复人1职称", "回复人1分析", "回复人1回复时间", "回复人2姓名", "回复人2职称", "回复人2分析", "回复人2回复时间", "回复人3姓名", "回复人3职称", "回复人3分析", "回复人3回复时间", "回复人4姓名", "回复人4职称", "回复人4分析", "回复人4回复时间", "回复人5姓名", "回复人5职称", "回复人5分析", "回复人5回复时间"}; /** * the child mode of the segged map */ private static String[] CHILDREN2 = {"问题内容","回复人1分析", "回复人2分析","回复人3分析","回复人4分析", "回复人5分析"}; /** * the child mode of the name of the user from the map */ private static String[] CHILDREN3 = {"回复人1姓名", "回复人2姓名","回复人3姓名","回复人4姓名", "回复人5姓名"}; /** * 0:"不使用词典", <br>1: "使用词典", <br>2:"只保留词典" */ private final String[] MODELTYPE = {"不使用词典", "使用词典","只保留词典"}; public ComPreprocess(Shell shell, Composite parent, int style) { super(parent, style); fileText = new Text(this, SWT.BORDER); fileText.setBounds(121, 40, 445, 22); /** * a group shows the basic info of xml file */ Group groupXmlInfo = new Group(this, SWT.BORDER); groupXmlInfo.setText("XML信息"); groupXmlInfo.setBounds(10, 70, 345, 90); userNumText = new Text(groupXmlInfo, SWT.BORDER | SWT.READ_ONLY); userNumText.setBounds(10, 10, 150, 22); userNumText.setBackground(new Color(null,245,245,245)); userNumText.setText("不同答者数:"); docNumText = new Text(groupXmlInfo, SWT.BORDER | SWT.READ_ONLY); docNumText.setBounds(10, 40, 150, 22); docNumText.setBackground(new Color(null,245,245,245)); docNumText.setText("文档数:"); ansNumText = new Text(groupXmlInfo, SWT.BORDER | SWT.READ_ONLY); ansNumText.setBounds(185, 40, 150, 22); ansNumText.setBackground(new Color(null,245,245,245)); ansNumText.setText("回答数:"); pageNumText= new Text(groupXmlInfo, SWT.BORDER | SWT.READ_ONLY); pageNumText.setBounds(185, 10, 150, 22); pageNumText.setBackground(new Color(null,245,245,245)); pageNumText.setText("总页数:"); /** * a group shows all the docs' titles */ Group groupDocTitle = new Group(this, SWT.BORDER); groupDocTitle.setText("文档标题"); groupDocTitle.setBounds(10, 160, 345, 300); presentPageText = new Text(groupDocTitle, SWT.BORDER | SWT.READ_ONLY); presentPageText.setBounds(5, 5, 75, 22); presentPageText.setText("当前页:"); presentPageText.setBackground(new Color(null,245,245,245)); /** * turn to the front page if possible */ Button buttonFront = new Button(groupDocTitle, SWT.BORDER); buttonFront.setBounds(85, 5, 60, 24); buttonFront.setText("Front"); buttonFront.addSelectionListener(new SelectionAdapter(){ @Override public void widgetSelected(SelectionEvent e){ if (ifOpen == true){ if (page != 1){ page -= 1; fillTableGroup(); } else { MessageBox messagebox=new MessageBox(shell,SWT.YES|SWT.ICON_ERROR); messagebox.setText("Error"); messagebox.setMessage("已是第一页,没有上一页"); messagebox.open(); } } } }); /** * turn to the next page if possible */ Button buttonNext = new Button(groupDocTitle,SWT.BORDER ); buttonNext.setBounds(145, 5, 60, 24); buttonNext.setText("Next"); buttonNext.addSelectionListener(new SelectionAdapter(){ @Override public void widgetSelected(SelectionEvent e){ if (ifOpen == true){ if (page * 20 < xmlReader.docNum){ page += 1; fillTableGroup(); } else { MessageBox messagebox=new MessageBox(shell,SWT.YES|SWT.ICON_ERROR); messagebox.setText("Error"); messagebox.setMessage("已是最后一页,没有下一页"); messagebox.open(); } } } }); /** * instruction about turning pages */ Label labelTurnPage = new Label(groupDocTitle,SWT.NONE); labelTurnPage.setBounds(210, 8, 50, 22); labelTurnPage.setText("转到第"); /** * turn to the next page if possible */ turnPageText = new Text(groupDocTitle, SWT.BORDER); turnPageText.setBounds(250, 5, 25, 22); /** * comfirm to turning to the next page */ Button buttonComfirmTurn = new Button(groupDocTitle, SWT.BORDER); buttonComfirmTurn.setBounds(282, 6, 60, 22); buttonComfirmTurn.setText("确认"); buttonComfirmTurn.addSelectionListener(new SelectionAdapter(){ @Override public void widgetSelected(SelectionEvent e){ if (ifOpen == true){ int pageGo = Integer.parseInt(turnPageText.getText()); if ((pageGo-1) * 20 < xmlReader.docNum && pageGo > 0){ page = pageGo; fillTableGroup(); } else { MessageBox messagebox=new MessageBox(shell,SWT.YES|SWT.ICON_ERROR); messagebox.setText("Error"); messagebox.setMessage("不存在该页"); messagebox.open(); } } } }); /** * initialize the table */ tableTitle = new Table(groupDocTitle, SWT.BORDER|SWT.FULL_SELECTION); tableTitle.setBounds(5, 30, 335, 240); tableTitle.setHeaderVisible(true); tableTitle.setLinesVisible(true); String[] tableTitleString = {"ID", "Title"}; int[] tableColumnWidth = {50,285}; for (int i = 0; i < COLUMNS_CNT ; i ++){ TableColumn columnTemp = new TableColumn(tableTitle, SWT.CENTER); columnTemp.setText(tableTitleString[i]); columnTemp.setResizable(false); tableTitle.getColumn(i).pack(); columnTemp.setWidth(tableColumnWidth[i]); } /** * a group shows the basic info after segged */ Group groupSegInfo = new Group(this, SWT.BORDER); groupSegInfo.setText("分词后的信息"); groupSegInfo.setBounds(365, 70, 310, 90); wordsNumText = new Text(groupSegInfo, SWT.BORDER | SWT.READ_ONLY ); wordsNumText.setBounds(10, 10, 135, 22); wordsNumText.setBackground(new Color(null,245,245,245)); wordsNumText.setText("总词数:"); uniqueWordsNumText = new Text(groupSegInfo, SWT.BORDER | SWT.READ_ONLY ); uniqueWordsNumText.setBounds(165, 10, 135, 22); uniqueWordsNumText.setBackground(new Color(null,245,245,245)); uniqueWordsNumText.setText("不同词数:"); repeat2NumText = new Text(groupSegInfo, SWT.BORDER | SWT.READ_ONLY ); repeat2NumText.setBounds(10, 40, 90, 22); repeat2NumText.setBackground(new Color(null,245,245,245)); repeat2NumText.setText(">2:"); repeat10NumText = new Text(groupSegInfo, SWT.BORDER | SWT.READ_ONLY ); repeat10NumText.setBounds(110, 40, 90, 22); repeat10NumText.setBackground(new Color(null,245,245,245)); repeat10NumText.setText(">10:"); repeat100NumText = new Text(groupSegInfo, SWT.BORDER | SWT.READ_ONLY ); repeat100NumText.setBounds(210, 40, 90, 22); repeat100NumText.setBackground(new Color(null,245,245,245)); repeat100NumText.setText(">100:"); /** * a group shows the detail of the selected doc */ Group groupDocDetail = new Group(this, SWT.BORDER); groupDocDetail.setText("文档详细信息"); groupDocDetail.setBounds(365, 160, 310, 160); docDetailText = new Text(groupDocDetail,SWT.BORDER | SWT.READ_ONLY |SWT.V_SCROLL | SWT.WRAP); docDetailText.setBounds(2,0,302,140); docDetailText.setBackground(new Color(null,230,230,230)); Label labelModelType = new Label(this, SWT.BORDER); labelModelType.setText("请选择 Model 类型:"); labelModelType.setBounds(50, 470, 120, 30); comboModelType = new Combo(this, SWT.BORDER); comboModelType.setBounds(200, 470, 150, 50); comboModelType.setItems(MODELTYPE); Button buttonSegWords = new Button(this, SWT.BORDER); buttonSegWords.setText("进行分词"); buttonSegWords.setBackground(new Color(null,230,230,230)); buttonSegWords.setBounds(400,465, 200, 40); buttonSegWords.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e){ if (ifSeg == false){ ifSeg = true; doSegging(); } } }); /** * a group shows the detail of the selected doc after segged */ Group groupSegDoc = new Group(this, SWT.BORDER); groupSegDoc.setText("分词后的文档"); groupSegDoc.setBounds(365, 320, 310, 140); segDocDetailText = new Text(groupSegDoc,SWT.BORDER | SWT.READ_ONLY |SWT.V_SCROLL | SWT.WRAP); segDocDetailText.setBounds(2, 0, 302, 120); segDocDetailText.setBackground(new Color(null,230,230,230)); Button buttonOpenFile = new Button(this, SWT.BORDER); buttonOpenFile.setText("Open File"); buttonOpenFile.setBounds(20, 40, 85, 22); buttonOpenFile.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e){ FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setText("请选择需要打开的文件"); dialog.setFilterExtensions(new String[]{"*.xml"}); dialog.setFilterNames(new String[] {"xml文件(*.xml)"}); filePath = new String[1]; filePath[0]=dialog.open(); filename=dialog.getFileName(); if (filename != null){ fileText.setText(filePath[0]); } } }); Button buttonComfirm = new Button(this, SWT.BORDER); buttonComfirm.setText("Comfirm"); buttonComfirm.setBounds(580, 40, 85, 22); buttonComfirm.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e){ if (filename != null){ openFile(); } } }); } protected void checkSubclass() { // Disable the check that prevents subclassing of SWT components } /** * open the selected xml file and show in other groups */ private void openFile() { xmlReader = new XMLReader(); xmlReader.readXml(filePath[0]); docMapMap = xmlReader.docMapMap; // fill the doc titles in the table fillDocInfo(); fillTableGroup(); fillDocDetail(); ifOpen = true; ifSeg = false; } /** * seg the words */ private void doSegging(){ segWords = new SegWords(); int type = comboModelType.getSelectionIndex(); // System.out.println(type); indexType = type; segWords.segWords(xmlReader.docMapMap, xmlReader.docNum,type); segDocMapMap = segWords.segDocMapMap; fillSegInfo(); fillSegDetail(); } /** * fill in the groupSegInfo */ private void fillSegInfo(){ getSegInfo(); wordsNumText.setText("总词数:" + wordsNum); uniqueWordsNumText.setText("不同词数:" + uniqueWordsNum); repeat2NumText.setText(">2:" + repeat2Num); repeat10NumText.setText(">10:" + repeat10Num); repeat100NumText.setText(">100:" + repeat100Num); } /** * fill in the groupSegDetail -- segDocDetailText */ private void fillSegDetail(){ tableTitle.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e){ int selectIndex = tableTitle.getSelectionIndex(); int id = selectIndex + 1 + (page-1) * ROWS_CNT; String childText; String childContent; String inputText; if (id <= xmlReader.docNum){ segDocDetailText.setText(""); for (int i = 0; i < CHILDREN2.length; i++){ childText = CHILDREN2[i]; childContent = segWords.segDocMapMap.get(id).get(childText); if (childContent.length() != 0){ inputText = "【" + childText +"】:" + childContent; segDocDetailText.append(inputText); segDocDetailText.append("\n\n"); } } } } }); } /** * fill in the groupDocInfo */ private void fillDocInfo(){ getUniqueUserNum(); uniqueUserNumClone = uniqueUserNum; userNumText.setText("不同答者数:" + uniqueUserNum); docNumText.setText("文档数:" + xmlReader.docNum); ansNumText.setText("回答数:" + xmlReader.ansNum); pageNumText.setText("总页数:" + ((xmlReader.docNum - 1) / ROWS_CNT + 1)); numExperts = uniqueUserNum; numQuestion = xmlReader.docNum; numAnswer = xmlReader.ansNum; } /** * fill in the table and refresh the other */ private void fillTableGroup(){ removeTableGroup(); presentPageText.setText("当前页:" + page); for (int i = 0; i < ROWS_CNT; i ++){ TableItem item = new TableItem(tableTitle,SWT.NULL); int id = i + 1 + ROWS_CNT * (page - 1); if (id <= xmlReader.docNum){ item.setText(0, id + ""); Integer id2 = new Integer(id); String title = xmlReader.docMapMap.get(id2).get("问题标题"); item.setText(1, title); } } // add addSelectionListener } /** * fill in the groupDocDetail */ private void fillDocDetail(){ tableTitle.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e){ int selectIndex = tableTitle.getSelectionIndex(); int id = selectIndex + 1 + (page-1) * ROWS_CNT; String childText; String childContent; String inputText; if (id <= xmlReader.docNum){ docDetailText.setText(""); for (int i = 0; i < CHILDREN.length; i++){ childText = CHILDREN[i]; childContent = xmlReader.docMapMap.get(id).get(childText); if (childContent.length() != 0){ inputText = "【" + childText +"】:" + childContent; docDetailText.append(inputText); docDetailText.append("\n\n"); } } } } }); } /** * get the unique user number */ private void getUniqueUserNum(){ TreeSet<String> userSet = new TreeSet<String>(); wordsNum = 0; uniqueUserNum = 0; String temp; for(Map.Entry<Integer, Map<String,String>> entry : xmlReader.docMapMap.entrySet()){ for (int i = 0; i < CHILDREN3.length; i++){ temp = entry.getValue().get(CHILDREN3[i]); if(temp.length() != 0 ){ userSet.add(temp); } } } uniqueUserNum = userSet.size(); } /** * get the number of the words' info after segged */ private void getSegInfo(){ TreeSet<String> wordsSet = new TreeSet<String>(); wordsNum = 0; uniqueWordsNum = 0; repeat2Num = 0; repeat10Num = 0; repeat100Num = 0; String[] temp; String answer; ArrayList<String> equalSet = new ArrayList<String>(); ArrayList<String> list = new ArrayList<String>(); for(Map.Entry<Integer, Map<String,String>> entry : segWords.segDocMapMap.entrySet()){ for (int i = 0; i < CHILDREN2.length; i++){ answer = entry.getValue().get(CHILDREN2[i]); if(answer.length() != 0){ temp = answer.split("\\s"); wordsNum += temp.length; for(int k = 0; k < temp.length; k ++){ list.add(temp[k]); if(wordsSet.add(temp[k])==true){ equalSet.add(temp[k]); } } } } } int[] damnRepeat = new int[equalSet.size()]; for(int i = 0; i<equalSet.size();i++){ damnRepeat[i] = 0; } for(int i = 0; i < list.size(); i++){ damnRepeat[equalSet.indexOf(list.get(i))] += 1; } for(int i = 0;i<equalSet.size();i++){ if (damnRepeat[i] >= 2){ repeat2Num += 1; } if (damnRepeat[i] >= 10){ repeat10Num += 1; } if (damnRepeat[i] >= 100){ repeat100Num += 1; } } uniqueWordsNum = wordsSet.size(); uniqueWordsNumClone = uniqueWordsNum; } /** * remove the content in the table and the other */ private void removeTableGroup(){ tableTitle.removeAll(); } }
Htiango/Advanced-LDA-Program
src/tabPages/ComPreprocess.java
249,349
package model.combat; import model.adventures.Adventurer; import model.creatures.Creature; import util.Utilities; // Strategy for combat. public class ExpertStrategy implements ICombatStrategy { @Override public boolean fight(Adventurer ad, Creature c, int extra) { return Utilities.fight(ad, c, extra + 2, 0); } }
adifire1/ROTLA-Java-Game
src/model/combat/ExpertStrategy.java
249,351
package generated; import java.util.HashMap; public class UriMap { public static final HashMap<String, Class> toClass = new HashMap<>(); static { toClass.put("\\/anti-addiction\\/v1\\/policies\\/[^/]+\\/anti-addiction-state", LolAntiAddictionAntiAddictionState.class); toClass.put("\\/async\\/v1\\/result\\/[^/]+", Object.class); toClass.put("\\/async\\/v1\\/status\\/[^/]+", Object.class); toClass.put("\\/client-config\\/v1\\/config", Object.class); toClass.put("\\/client-config\\/v1\\/config\\/[^/]+", Object.class); toClass.put("\\/client-config\\/v1\\/status\\/[^/]+", ClientConfigConfigStatus.class); toClass.put("\\/client-config\\/v2\\/config\\/[^/]+", Object.class); toClass.put("\\/client-config\\/v2\\/namespace\\/[^/]+", Object.class); toClass.put("\\/client-config\\/v2\\/namespace\\/[^/]+\\/player", Object.class); toClass.put("\\/client-config\\/v2\\/namespace\\/[^/]+\\/public", Object.class); toClass.put("\\/cookie-jar\\/v1\\/cookies", cookie[].class); toClass.put("\\/crash-reporting\\/v1\\/crash-status", Boolean.class); toClass.put("\\/data-store\\/v1\\/install-dir", String.class); toClass.put("\\/data-store\\/v1\\/install-settings\\/[^/]+", Object.class); toClass.put("\\/data-store\\/v1\\/system-settings\\/[^/]+", Object.class); toClass.put("\\/entitlements\\/v1\\/token", EntitlementsToken.class); toClass.put("\\/lol-account-verification\\/v1\\/device", LolAccountVerificationDeviceResponse.class); toClass.put("\\/lol-account-verification\\/v1\\/is-verified", LolAccountVerificationIsVerifiedResponse.class); toClass.put("\\/lol-active-boosts\\/v1\\/active-boosts", LolActiveBoostsActiveBoosts.class); toClass.put("\\/lol-anti-addiction\\/v1\\/anti-addiction-token", LolAntiAddictionAntiAddictionToken.class); toClass.put("\\/lol-banners\\/v1\\/current-summoner\\/flags", LolBannersBannerFlag[].class); toClass.put("\\/lol-banners\\/v1\\/current-summoner\\/flags\\/equipped", LolBannersBannerFlag.class); toClass.put("\\/lol-banners\\/v1\\/current-summoner\\/frames\\/equipped", LolBannersBannerFrame.class); toClass.put("\\/lol-banners\\/v1\\/players\\/[^/]+\\/flags\\/equipped", LolBannersBannerFlag.class); toClass.put("\\/lol-career-stats\\/v1\\/champion-averages\\/season\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+", LolCareerStatsChampionQueueStatsResponse.class); toClass.put("\\/lol-career-stats\\/v1\\/champion-averages\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+", LolCareerStatsChampionQueueStatsResponse.class); toClass.put("\\/lol-career-stats\\/v1\\/champion-experts\\/season\\/[^/]+\\/[^/]+\\/[^/]+", LolCareerStatsExpertPlayer[].class); toClass.put("\\/lol-career-stats\\/v1\\/champion-experts\\/[^/]+\\/[^/]+", LolCareerStatsExpertPlayer[].class); toClass.put("\\/lol-career-stats\\/v1\\/position-averages\\/season\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+", LolCareerStatsChampionQueueStatsResponse.class); toClass.put("\\/lol-career-stats\\/v1\\/position-averages\\/[^/]+\\/[^/]+\\/[^/]+", LolCareerStatsChampionQueueStatsResponse.class); toClass.put("\\/lol-career-stats\\/v1\\/position-experts\\/season\\/[^/]+\\/[^/]+", LolCareerStatsExpertPlayer[].class); toClass.put("\\/lol-career-stats\\/v1\\/position-experts\\/[^/]+", LolCareerStatsExpertPlayer[].class); toClass.put("\\/lol-career-stats\\/v1\\/summoner-games\\/[^/]+", Object.class); toClass.put("\\/lol-career-stats\\/v1\\/summoner-games\\/[^/]+\\/season\\/[^/]+", Object.class); toClass.put("\\/lol-career-stats\\/v1\\/summoner-stats\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+", Object.class); toClass.put("\\/lol-catalog\\/v1\\/item-details", LolCatalogCatalogPluginItemWithDetails.class); toClass.put("\\/lol-catalog\\/v1\\/items", LolCatalogItemChoiceDetails[].class); toClass.put("\\/lol-catalog\\/v1\\/items\\/[^/]+", LolCatalogCatalogPluginItem[].class); toClass.put("\\/lol-challenges\\/v1\\/available-queue-ids", Integer[].class); toClass.put("\\/lol-challenges\\/v1\\/challenges\\/[^/]+\\/local-player", LolChallengesUIChallenge[].class); toClass.put("\\/lol-challenges\\/v1\\/level-points", Object.class); toClass.put("\\/lol-challenges\\/v1\\/my-updated-challenges\\/[^/]+", LolChallengesUIChallenge[].class); toClass.put("\\/lol-challenges\\/v1\\/suggested-challenges\\/[^/]+\\/local-player", LolChallengesUIChallenge[].class); toClass.put("\\/lol-challenges\\/v1\\/summary-player-data\\/[^/]+\\/local-player", LolChallengesUIPlayerSummary.class); toClass.put("\\/lol-challenges\\/v1\\/summary-player-data\\/[^/]+\\/player\\/[^/]+", LolChallengesUIPlayerSummary.class); toClass.put("\\/lol-challenges\\/v1\\/summary-players-data\\/[^/]+\\/players", Object.class); toClass.put("\\/lol-challenges\\/v1\\/titles\\/local-player", LolChallengesUITitle[].class); toClass.put("\\/lol-challenges\\/v1\\/updated-challenge\\/[^/]+\\/[^/]+", LolChallengesUIChallenge.class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/bannable-champion-ids", Integer[].class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/current-champion", Integer.class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/disabled-champion-ids", Integer[].class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/implementation-active", Boolean.class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/pickable-champion-ids", Integer[].class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/pickable-skin-ids", Integer[].class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/session", LolChampSelectLegacyChampSelectSession.class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/session\\/timer", LolChampSelectLegacyChampSelectTimer.class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/session\\/trades", LolChampSelectLegacyChampSelectTradeContract[].class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/session\\/trades\\/[^/]+", LolChampSelectLegacyChampSelectTradeContract.class); toClass.put("\\/lol-champ-select-legacy\\/v1\\/team-boost", LolChampSelectLegacyTeamBoost.class); toClass.put("\\/lol-champ-select\\/v1\\/all-grid-champions", LolChampSelectChampGridChampion[].class); toClass.put("\\/lol-champ-select\\/v1\\/bannable-champion-ids", Integer[].class); toClass.put("\\/lol-champ-select\\/v1\\/current-champion", Integer.class); toClass.put("\\/lol-champ-select\\/v1\\/disabled-champion-ids", Integer[].class); toClass.put("\\/lol-champ-select\\/v1\\/grid-champions\\/[^/]+", LolChampSelectChampGridChampion.class); toClass.put("\\/lol-champ-select\\/v1\\/muted-players", LolChampSelectMutedPlayerInfo[].class); toClass.put("\\/lol-champ-select\\/v1\\/ongoing-trade", LolChampSelectChampSelectTradeNotification.class); toClass.put("\\/lol-champ-select\\/v1\\/pickable-champion-ids", Integer[].class); toClass.put("\\/lol-champ-select\\/v1\\/pickable-skin-ids", Integer[].class); toClass.put("\\/lol-champ-select\\/v1\\/pin-drop-notification", LolChampSelectChampSelectPinDropNotification.class); toClass.put("\\/lol-champ-select\\/v1\\/session", LolChampSelectChampSelectSession.class); toClass.put("\\/lol-champ-select\\/v1\\/session\\/timer", LolChampSelectChampSelectTimer.class); toClass.put("\\/lol-champ-select\\/v1\\/session\\/trades", LolChampSelectChampSelectTradeContract[].class); toClass.put("\\/lol-champ-select\\/v1\\/session\\/trades\\/[^/]+", LolChampSelectChampSelectTradeContract.class); toClass.put("\\/lol-champ-select\\/v1\\/sfx-notifications", LolChampSelectSfxNotification[].class); toClass.put("\\/lol-champ-select\\/v1\\/skin-carousel-skins", LolChampSelectSkinSelectorSkin[].class); toClass.put("\\/lol-champ-select\\/v1\\/skin-selector-info", LolChampSelectSkinSelectorInfo.class); toClass.put("\\/lol-champ-select\\/v1\\/summoners\\/[^/]+", LolChampSelectChampSelectSummoner.class); toClass.put("\\/lol-champ-select\\/v1\\/team-boost", LolChampSelectTeamBoost.class); toClass.put("\\/lol-champions\\/v1\\/inventories\\/[^/]+\\/champions", LolChampionsCollectionsChampion[].class); toClass.put("\\/lol-champions\\/v1\\/inventories\\/[^/]+\\/champions-minimal", LolChampionsCollectionsChampionMinimal[].class); toClass.put("\\/lol-champions\\/v1\\/inventories\\/[^/]+\\/champions-playable-count", LolChampionsCollectionsChampionPlayableCounts.class); toClass.put("\\/lol-champions\\/v1\\/inventories\\/[^/]+\\/champions\\/[^/]+", LolChampionsCollectionsChampion.class); toClass.put("\\/lol-champions\\/v1\\/inventories\\/[^/]+\\/champions\\/[^/]+\\/skins", LolChampionsCollectionsChampionSkin[].class); toClass.put("\\/lol-champions\\/v1\\/inventories\\/[^/]+\\/champions\\/[^/]+\\/skins\\/[^/]+", LolChampionsCollectionsChampionSkin.class); toClass.put("\\/lol-champions\\/v1\\/inventories\\/[^/]+\\/champions\\/[^/]+\\/skins\\/[^/]+\\/chromas", LolChampionsCollectionsChampionChroma[].class); toClass.put("\\/lol-champions\\/v1\\/inventories\\/[^/]+\\/skins-minimal", LolChampionsCollectionsChampionSkinMinimal[].class); toClass.put("\\/lol-champions\\/v1\\/owned-champions-minimal", LolChampionsCollectionsChampionMinimal[].class); toClass.put("\\/lol-chat\\/v1\\/blocked-players", LolChatBlockedPlayerResource[].class); toClass.put("\\/lol-chat\\/v1\\/blocked-players\\/[^/]+", LolChatBlockedPlayerResource.class); toClass.put("\\/lol-chat\\/v1\\/config", LolChatChatServiceDynamicClientConfig.class); toClass.put("\\/lol-chat\\/v1\\/conversations", LolChatConversationResource[].class); toClass.put("\\/lol-chat\\/v1\\/conversations\\/active", LolChatActiveConversationResource.class); toClass.put("\\/lol-chat\\/v1\\/conversations\\/notify", String.class); toClass.put("\\/lol-chat\\/v1\\/conversations\\/[^/]+", LolChatConversationResource.class); toClass.put("\\/lol-chat\\/v1\\/conversations\\/[^/]+\\/messages", LolChatConversationMessageResource[].class); toClass.put("\\/lol-chat\\/v1\\/conversations\\/[^/]+\\/participants", LolChatUserResource[].class); toClass.put("\\/lol-chat\\/v1\\/conversations\\/[^/]+\\/participants\\/[^/]+", LolChatUserResource.class); toClass.put("\\/lol-chat\\/v1\\/errors", LolChatErrorResource[].class); toClass.put("\\/lol-chat\\/v1\\/friend-counts", LolChatFriendCountsResource.class); toClass.put("\\/lol-chat\\/v1\\/friend-exists\\/[^/]+", Boolean.class); toClass.put("\\/lol-chat\\/v1\\/friend-groups", LolChatGroupResource[].class); toClass.put("\\/lol-chat\\/v1\\/friend-groups\\/[^/]+", LolChatGroupResource.class); toClass.put("\\/lol-chat\\/v1\\/friend-groups\\/[^/]+\\/friends", LolChatFriendResource[].class); toClass.put("\\/lol-chat\\/v1\\/friend-requests", LolChatFriendRequestResource[].class); toClass.put("\\/lol-chat\\/v1\\/friends", LolChatFriendResource[].class); toClass.put("\\/lol-chat\\/v1\\/friends\\/[^/]+", LolChatFriendResource.class); toClass.put("\\/lol-chat\\/v1\\/me", LolChatUserResource.class); toClass.put("\\/lol-chat\\/v1\\/resources", LolChatProductMetadataMap.class); toClass.put("\\/lol-chat\\/v1\\/session", LolChatSessionResource.class); toClass.put("\\/lol-chat\\/v1\\/settings", Object.class); toClass.put("\\/lol-chat\\/v1\\/settings\\/[^/]+", Object.class); toClass.put("\\/lol-clash\\/v1\\/all-tournaments", TournamentDTO[].class); toClass.put("\\/lol-clash\\/v1\\/bracket\\/[^/]+", LolClashBracket.class); toClass.put("\\/lol-clash\\/v1\\/checkin-allowed", Boolean.class); toClass.put("\\/lol-clash\\/v1\\/currentTournamentIds", Long[].class); toClass.put("\\/lol-clash\\/v1\\/disabled-config", LolClashClashDisabledConfig.class); toClass.put("\\/lol-clash\\/v1\\/enabled", Boolean.class); toClass.put("\\/lol-clash\\/v1\\/eog-player-update", LolClashEogPlayerUpdateDTO.class); toClass.put("\\/lol-clash\\/v1\\/event\\/[^/]+", ClashEventData.class); toClass.put("\\/lol-clash\\/v1\\/game-end", LolClashTournamentGameEnd.class); toClass.put("\\/lol-clash\\/v1\\/historyandwinners", LolClashTournamentHistoryAndWinners.class); toClass.put("\\/lol-clash\\/v1\\/iconconfig", Object.class); toClass.put("\\/lol-clash\\/v1\\/invited-roster-ids", String[].class); toClass.put("\\/lol-clash\\/v1\\/lft\\/team\\/requests", PendingOpenedTeamDTO[].class); toClass.put("\\/lol-clash\\/v1\\/notifications", LolClashPlayerNotificationData.class); toClass.put("\\/lol-clash\\/v1\\/ping", Object.class); toClass.put("\\/lol-clash\\/v1\\/player", LolClashPlayerData.class); toClass.put("\\/lol-clash\\/v1\\/player\\/chat-rosters", LolClashPlayerChatRoster[].class); toClass.put("\\/lol-clash\\/v1\\/player\\/history", LolClashRosterStats[].class); toClass.put("\\/lol-clash\\/v1\\/playmode-restricted", Boolean.class); toClass.put("\\/lol-clash\\/v1\\/ready", Boolean.class); toClass.put("\\/lol-clash\\/v1\\/rewards", LolClashPlayerRewards.class); toClass.put("\\/lol-clash\\/v1\\/roster\\/[^/]+", LolClashRoster.class); toClass.put("\\/lol-clash\\/v1\\/roster\\/[^/]+\\/stats", LolClashRosterStats.class); toClass.put("\\/lol-clash\\/v1\\/scouting\\/champions", LolClashScoutingChampions[].class); toClass.put("\\/lol-clash\\/v1\\/scouting\\/matchhistory", Object.class); toClass.put("\\/lol-clash\\/v1\\/season-rewards\\/[^/]+", ClashSeasonRewardResult.class); toClass.put("\\/lol-clash\\/v1\\/simple-state-flags", LolClashSimpleStateFlag[].class); toClass.put("\\/lol-clash\\/v1\\/thirdparty\\/team-data", LolClashThirdPartyApiRoster.class); toClass.put("\\/lol-clash\\/v1\\/time", Long.class); toClass.put("\\/lol-clash\\/v1\\/tournament-state-info", LolClashTournamentStateInfo[].class); toClass.put("\\/lol-clash\\/v1\\/tournament-summary", LolClashTournamentSummary[].class); toClass.put("\\/lol-clash\\/v1\\/tournament\\/cancelled", Long[].class); toClass.put("\\/lol-clash\\/v1\\/tournament\\/get-all-player-tiers", PlayerTierDTO[].class); toClass.put("\\/lol-clash\\/v1\\/tournament\\/[^/]+", LolClashTournament.class); toClass.put("\\/lol-clash\\/v1\\/tournament\\/[^/]+\\/get-player-tiers", PlayerTierDTO[].class); toClass.put("\\/lol-clash\\/v1\\/tournament\\/[^/]+\\/player", LolClashPlayerTournamentData.class); toClass.put("\\/lol-clash\\/v1\\/tournament\\/[^/]+\\/player-honor-restricted", Boolean.class); toClass.put("\\/lol-clash\\/v1\\/tournament\\/[^/]+\\/stateInfo", LolClashTournamentStateInfo.class); toClass.put("\\/lol-clash\\/v1\\/tournament\\/[^/]+\\/winners", LolClashTournamentWinnerHistory.class); toClass.put("\\/lol-clash\\/v1\\/visible", Boolean.class); toClass.put("\\/lol-clash\\/v1\\/voice-enabled", Boolean.class); toClass.put("\\/lol-clash\\/v2\\/playmode-restricted", LolClashPlaymodeRestrictedInfo.class); toClass.put("\\/lol-client-config\\/v3\\/client-config\\/[^/]+", Object.class); toClass.put("\\/lol-collections\\/v1\\/inventories\\/chest-eligibility", LolCollectionsCollectionsChestEligibility.class); toClass.put("\\/lol-collections\\/v1\\/inventories\\/local-player\\/champion-mastery-score", Long.class); toClass.put("\\/lol-collections\\/v1\\/inventories\\/scouting", RankedScoutingDTO[].class); toClass.put("\\/lol-collections\\/v1\\/inventories\\/[^/]+\\/backdrop", LolCollectionsCollectionsSummonerBackdrop.class); toClass.put("\\/lol-collections\\/v1\\/inventories\\/[^/]+\\/champion-mastery", LolCollectionsCollectionsChampionMastery[].class); toClass.put("\\/lol-collections\\/v1\\/inventories\\/[^/]+\\/champion-mastery\\/top", LolCollectionsCollectionsTopChampionMasteries.class); toClass.put("\\/lol-collections\\/v1\\/inventories\\/[^/]+\\/spells", LolCollectionsCollectionsSummonerSpells.class); toClass.put("\\/lol-collections\\/v1\\/inventories\\/[^/]+\\/ward-skins", LolCollectionsCollectionsWardSkin[].class); toClass.put("\\/lol-collections\\/v1\\/inventories\\/[^/]+\\/ward-skins\\/[^/]+", LolCollectionsCollectionsWardSkin.class); toClass.put("\\/lol-content-targeting\\/v1\\/filters", LolContentTargetingContentTargetingFilterResponse.class); toClass.put("\\/lol-content-targeting\\/v1\\/locale", LolContentTargetingContentTargetingLocaleResponse.class); toClass.put("\\/lol-content-targeting\\/v1\\/protected_filters", LolContentTargetingContentTargetingFilterResponse.class); toClass.put("\\/lol-cosmetics\\/v1\\/inventories\\/[^/]+\\/companions", LolCosmeticsCompanionsGroupedViewModel.class); toClass.put("\\/lol-cosmetics\\/v1\\/inventories\\/[^/]+\\/damage-skins", LolCosmeticsTFTDamageSkinGroupedViewModel.class); toClass.put("\\/lol-cosmetics\\/v1\\/inventories\\/[^/]+\\/map-skins", LolCosmeticsTFTMapSkinGroupedViewModel.class); toClass.put("\\/lol-email-verification\\/v1\\/email", LolEmailVerificationEmailVerificationSession.class); toClass.put("\\/lol-end-of-game\\/v1\\/champion-mastery-updates", LolEndOfGameChampionMasteryUpdate.class); toClass.put("\\/lol-end-of-game\\/v1\\/eog-stats-block", LolEndOfGameEndOfGameStats.class); toClass.put("\\/lol-end-of-game\\/v1\\/gameclient-eog-stats-block", LolEndOfGameGameClientEndOfGameStats.class); toClass.put("\\/lol-end-of-game\\/v1\\/reported-players", Long[].class); toClass.put("\\/lol-end-of-game\\/v1\\/tft-eog-stats", LolEndOfGameTFTEndOfGameViewModel.class); toClass.put("\\/lol-esport-stream-notifications\\/v1\\/live-streams", LolEsportStreamNotificationsESportsLiveStreams.class); toClass.put("\\/lol-esport-stream-notifications\\/v1\\/stream-url", String.class); toClass.put("\\/lol-game-client-chat\\/v1\\/buddies", String[].class); toClass.put("\\/lol-game-client-chat\\/v1\\/ignored-summoners", Long[].class); toClass.put("\\/lol-game-client-chat\\/v1\\/muted-summoners", Long[].class); toClass.put("\\/lol-game-queues\\/v1\\/custom", LolGameQueuesQueueCustomGame.class); toClass.put("\\/lol-game-queues\\/v1\\/custom-non-default", LolGameQueuesQueueCustomGame.class); toClass.put("\\/lol-game-queues\\/v1\\/game-type-config\\/[^/]+", LolGameQueuesQueueGameTypeConfig.class); toClass.put("\\/lol-game-queues\\/v1\\/game-type-config\\/[^/]+\\/map\\/[^/]+", LolGameQueuesQueueGameTypeConfig.class); toClass.put("\\/lol-game-queues\\/v1\\/queues", LolGameQueuesQueue[].class); toClass.put("\\/lol-game-queues\\/v1\\/queues\\/type\\/[^/]+", LolGameQueuesQueue.class); toClass.put("\\/lol-game-queues\\/v1\\/queues\\/[^/]+", LolGameQueuesQueue.class); toClass.put("\\/lol-game-settings\\/v1\\/didreset", Boolean.class); toClass.put("\\/lol-game-settings\\/v1\\/game-settings", Object.class); toClass.put("\\/lol-game-settings\\/v1\\/game-settings-schema", Object.class); toClass.put("\\/lol-game-settings\\/v1\\/input-settings", Object.class); toClass.put("\\/lol-game-settings\\/v1\\/input-settings-schema", Object.class); toClass.put("\\/lol-game-settings\\/v1\\/ready", Boolean.class); toClass.put("\\/lol-gameflow\\/v1\\/active-patcher-lock", Boolean.class); toClass.put("\\/lol-gameflow\\/v1\\/availability", LolGameflowGameflowAvailability.class); toClass.put("\\/lol-gameflow\\/v1\\/basic-tutorial", Boolean.class); toClass.put("\\/lol-gameflow\\/v1\\/battle-training", Boolean.class); toClass.put("\\/lol-gameflow\\/v1\\/early-exit-notifications\\/eog", Object[].class); toClass.put("\\/lol-gameflow\\/v1\\/early-exit-notifications\\/missions", Object[].class); toClass.put("\\/lol-gameflow\\/v1\\/extra-game-client-args", String[].class); toClass.put("\\/lol-gameflow\\/v1\\/gameflow-metadata\\/player-status", LolGameflowPlayerStatus.class); toClass.put("\\/lol-gameflow\\/v1\\/gameflow-metadata\\/registration-status", LolGameflowRegistrationStatus.class); toClass.put("\\/lol-gameflow\\/v1\\/gameflow-phase", LolGameflowGameflowPhase.class); toClass.put("\\/lol-gameflow\\/v1\\/session", LolGameflowGameflowSession.class); toClass.put("\\/lol-gameflow\\/v1\\/session\\/per-position-summoner-spells\\/disallowed", Object.class); toClass.put("\\/lol-gameflow\\/v1\\/session\\/per-position-summoner-spells\\/disallowed\\/as-string", String.class); toClass.put("\\/lol-gameflow\\/v1\\/session\\/per-position-summoner-spells\\/required", Object.class); toClass.put("\\/lol-gameflow\\/v1\\/session\\/per-position-summoner-spells\\/required\\/as-string", String.class); toClass.put("\\/lol-gameflow\\/v1\\/spectate", Boolean.class); toClass.put("\\/lol-gameflow\\/v1\\/watch", LolGameflowGameflowWatchPhase.class); toClass.put("\\/lol-geoinfo\\/v1\\/getlocation", LolGeoinfoGeoInfo.class); toClass.put("\\/lol-geoinfo\\/v1\\/whereami", LolGeoinfoGeoInfoResponse.class); toClass.put("\\/lol-highlights\\/v1\\/config", LolHighlightsHighlightsConfig.class); toClass.put("\\/lol-highlights\\/v1\\/highlights", LolHighlightsHighlight[].class); toClass.put("\\/lol-highlights\\/v1\\/highlights-folder-path", String.class); toClass.put("\\/lol-highlights\\/v1\\/highlights-folder-path\\/default", String.class); toClass.put("\\/lol-highlights\\/v1\\/highlights\\/[^/]+", LolHighlightsHighlight.class); toClass.put("\\/lol-honor-v2\\/v1\\/ballot", LolHonorV2Ballot.class); toClass.put("\\/lol-honor-v2\\/v1\\/config", LolHonorV2HonorConfig.class); toClass.put("\\/lol-honor-v2\\/v1\\/late-recognition", LolHonorV2Honor[].class); toClass.put("\\/lol-honor-v2\\/v1\\/latest-eligible-game", Long.class); toClass.put("\\/lol-honor-v2\\/v1\\/level-change", LolHonorV2VendedHonorChange.class); toClass.put("\\/lol-honor-v2\\/v1\\/mutual-honor", LolHonorV2MutualHonor.class); toClass.put("\\/lol-honor-v2\\/v1\\/profile", LolHonorV2ProfileInfo.class); toClass.put("\\/lol-honor-v2\\/v1\\/recognition", LolHonorV2Honor[].class); toClass.put("\\/lol-honor-v2\\/v1\\/reward-granted", LolHonorV2VendedReward.class); toClass.put("\\/lol-honor-v2\\/v1\\/team-choices", Long[].class); toClass.put("\\/lol-honor-v2\\/v1\\/vote-completion", LolHonorV2VoteCompletion.class); toClass.put("\\/lol-hovercard\\/v1\\/friend-info-by-summoner\\/[^/]+", LolHovercardHovercardUserInfo.class); toClass.put("\\/lol-hovercard\\/v1\\/friend-info\\/[^/]+", LolHovercardHovercardUserInfo.class); toClass.put("\\/lol-inventory\\/v1\\/champSelectInventory", String.class); toClass.put("\\/lol-inventory\\/v1\\/initial-configuration-complete", Boolean.class); toClass.put("\\/lol-inventory\\/v1\\/inventory", LolInventoryInventoryItemWithPayload[].class); toClass.put("\\/lol-inventory\\/v1\\/inventory\\/emotes", LolInventoryInventoryItemWithPayload[].class); toClass.put("\\/lol-inventory\\/v1\\/notifications\\/[^/]+", LolInventoryInventoryNotification[].class); toClass.put("\\/lol-inventory\\/v1\\/players\\/[^/]+\\/inventory", LolInventoryInventoryItemWithPayload[].class); toClass.put("\\/lol-inventory\\/v1\\/signedInventory", Object.class); toClass.put("\\/lol-inventory\\/v1\\/signedInventory\\/simple", String.class); toClass.put("\\/lol-inventory\\/v1\\/signedInventory\\/tournamentlogos", Object.class); toClass.put("\\/lol-inventory\\/v1\\/signedInventoryCache", Object.class); toClass.put("\\/lol-inventory\\/v1\\/signedWallet", Object.class); toClass.put("\\/lol-inventory\\/v1\\/signedWallet\\/[^/]+", Object.class); toClass.put("\\/lol-inventory\\/v1\\/wallet", Object.class); toClass.put("\\/lol-inventory\\/v1\\/wallet\\/[^/]+", Object.class); toClass.put("\\/lol-inventory\\/v2\\/inventory\\/[^/]+", LolInventoryInventoryItemWithPayload[].class); toClass.put("\\/lol-item-sets\\/v1\\/item-sets\\/[^/]+\\/sets", LolItemSetsItemSets.class); toClass.put("\\/lol-kickout\\/v1\\/notification", LolKickoutKickoutMessage.class); toClass.put("\\/lol-kr-playtime-reminder\\/v1\\/message", String.class); toClass.put("\\/lol-kr-playtime-reminder\\/v1\\/playtime", LolKrPlaytimeReminderPlaytimeReminder.class); toClass.put("\\/lol-kr-shutdown-law\\/v1\\/custom-status", LolKrShutdownLawQueueShutdownStatus.class); toClass.put("\\/lol-kr-shutdown-law\\/v1\\/disabled-queues", Integer[].class); toClass.put("\\/lol-kr-shutdown-law\\/v1\\/notification", LolKrShutdownLawShutdownLawNotification.class); toClass.put("\\/lol-kr-shutdown-law\\/v1\\/queue-status\\/[^/]+", LolKrShutdownLawQueueShutdownStatus.class); toClass.put("\\/lol-kr-shutdown-law\\/v1\\/rating-screen", LolKrShutdownLawRatingScreenInfo.class); toClass.put("\\/lol-kr-shutdown-law\\/v1\\/status", LolKrShutdownLawAllQueueShutdownStatus.class); toClass.put("\\/lol-league-session\\/v1\\/league-session-token", String.class); toClass.put("\\/lol-leaver-buster\\/v1\\/notifications", LolLeaverBusterLeaverBusterNotificationResource[].class); toClass.put("\\/lol-leaver-buster\\/v1\\/notifications\\/[^/]+", LolLeaverBusterLeaverBusterNotificationResource.class); toClass.put("\\/lol-license-agreement\\/v1\\/agreements", LolLicenseAgreementLicenseAgreement[].class); toClass.put("\\/lol-license-agreement\\/v1\\/all-agreements", LolLicenseAgreementLicenseAgreement[].class); toClass.put("\\/lol-license-agreement\\/v1\\/serve-location", LolLicenseAgreementLicenseServeLocation.class); toClass.put("\\/lol-loadouts\\/v1\\/loadouts-ready", Boolean.class); toClass.put("\\/lol-loadouts\\/v4\\/loadouts\\/scope\\/account", LolLoadoutsScopedLoadout[].class); toClass.put("\\/lol-loadouts\\/v4\\/loadouts\\/scope\\/[^/]+\\/[^/]+", LolLoadoutsScopedLoadout[].class); toClass.put("\\/lol-loadouts\\/v4\\/loadouts\\/[^/]+", LolLoadoutsScopedLoadout.class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/bannable-champion-ids", Integer[].class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/current-champion", Integer.class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/disabled-champion-ids", Integer[].class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/has-auto-assigned-smite", Boolean.class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/implementation-active", Boolean.class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/match-token", String.class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/pickable-champion-ids", Integer[].class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/pickable-skin-ids", Integer[].class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/preferences", LolLobbyTeamBuilderChampionSelectPreferences.class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/sending-loadouts-gcos-enabled", Boolean.class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/session", LolLobbyTeamBuilderChampSelectSession.class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/session\\/timer", LolLobbyTeamBuilderChampSelectTimer.class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/session\\/trades", LolLobbyTeamBuilderChampSelectTradeContract[].class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/session\\/trades\\/[^/]+", LolLobbyTeamBuilderChampSelectTradeContract.class); toClass.put("\\/lol-lobby-team-builder\\/champ-select\\/v1\\/team-boost", LolLobbyTeamBuilderTeamBoost.class); toClass.put("\\/lol-lobby-team-builder\\/v1\\/matchmaking", LolLobbyTeamBuilderMatchmakingSearchResource.class); toClass.put("\\/lol-lobby\\/v1\\/autofill-displayed", Boolean.class); toClass.put("\\/lol-lobby\\/v1\\/custom-games", LolLobbyLobbyCustomGame[].class); toClass.put("\\/lol-lobby\\/v1\\/custom-games\\/[^/]+", LolLobbyLobbyCustomGame.class); toClass.put("\\/lol-lobby\\/v1\\/lobby\\/availability", LolLobbyQueueAvailability.class); toClass.put("\\/lol-lobby\\/v1\\/lobby\\/countdown", Long.class); toClass.put("\\/lol-lobby\\/v1\\/lobby\\/invitations", LolLobbyLobbyInvitation[].class); toClass.put("\\/lol-lobby\\/v1\\/lobby\\/invitations\\/[^/]+", LolLobbyLobbyInvitation.class); toClass.put("\\/lol-lobby\\/v1\\/parties\\/gamemode", LolLobbyGameModeDto.class); toClass.put("\\/lol-lobby\\/v1\\/parties\\/player", LolLobbyPlayerDto.class); toClass.put("\\/lol-lobby\\/v1\\/party-rewards", LolLobbyLobbyPartyRewards.class); toClass.put("\\/lol-lobby\\/v2\\/comms\\/members", LolLobbyPremadePartyDto.class); toClass.put("\\/lol-lobby\\/v2\\/comms\\/token", String.class); toClass.put("\\/lol-lobby\\/v2\\/eligibility\\/game-select-eligibility-hash", Long.class); toClass.put("\\/lol-lobby\\/v2\\/eligibility\\/initial-configuration-complete", Boolean.class); toClass.put("\\/lol-lobby\\/v2\\/lobby", LolLobbyLobbyDto.class); toClass.put("\\/lol-lobby\\/v2\\/lobby\\/custom\\/available-bots", LolLobbyLobbyBotChampion[].class); toClass.put("\\/lol-lobby\\/v2\\/lobby\\/custom\\/bots-enabled", Boolean.class); toClass.put("\\/lol-lobby\\/v2\\/lobby\\/invitations", LolLobbyLobbyInvitationDto[].class); toClass.put("\\/lol-lobby\\/v2\\/lobby\\/matchmaking\\/search-state", LolLobbyLobbyMatchmakingSearchResource.class); toClass.put("\\/lol-lobby\\/v2\\/lobby\\/members", LolLobbyLobbyParticipantDto[].class); toClass.put("\\/lol-lobby\\/v2\\/notifications", LolLobbyLobbyNotification[].class); toClass.put("\\/lol-lobby\\/v2\\/party-active", Boolean.class); toClass.put("\\/lol-lobby\\/v2\\/party\\/eog-status", LolLobbyPartyStatusDto.class); toClass.put("\\/lol-lobby\\/v2\\/received-invitations", LolLobbyReceivedInvitationDto[].class); toClass.put("\\/lol-lobby\\/v2\\/registration-status", Object.class); toClass.put("\\/lol-login\\/v1\\/account-state", LolLoginAccountStateResource.class); toClass.put("\\/lol-login\\/v1\\/login-connection-state", LolLoginLoginConnectionState.class); toClass.put("\\/lol-login\\/v1\\/login-data-packet", Object.class); toClass.put("\\/lol-login\\/v1\\/login-in-game-creds", Object.class); toClass.put("\\/lol-login\\/v1\\/login-platform-credentials", LolLoginPlatformGeneratedCredentials.class); toClass.put("\\/lol-login\\/v1\\/login-queue-state", LolLoginLoginQueue.class); toClass.put("\\/lol-login\\/v1\\/session", LolLoginLoginSession.class); toClass.put("\\/lol-login\\/v1\\/wallet", LolLoginLoginSessionWallet.class); toClass.put("\\/lol-login\\/v2\\/league-session-init-token", LolLoginLeagueSessionTokenEnvelope.class); toClass.put("\\/lol-loot\\/v1\\/enabled", Boolean.class); toClass.put("\\/lol-loot\\/v1\\/loot-grants", LolLootLootGrantNotification[].class); toClass.put("\\/lol-loot\\/v1\\/loot-items", LolLootLootItem[].class); toClass.put("\\/lol-loot\\/v1\\/loot-odds\\/[^/]+", LolLootVerboseLootOddsResponse.class); toClass.put("\\/lol-loot\\/v1\\/milestones", LolLootLootMilestones[].class); toClass.put("\\/lol-loot\\/v1\\/milestones\\/counters", LolLootLootMilestonesCounter[].class); toClass.put("\\/lol-loot\\/v1\\/milestones\\/items", String[].class); toClass.put("\\/lol-loot\\/v1\\/milestones\\/[^/]+", LolLootLootMilestones.class); toClass.put("\\/lol-loot\\/v1\\/milestones\\/[^/]+\\/claimProgress", LolLootLootMilestonesClaimResponse.class); toClass.put("\\/lol-loot\\/v1\\/milestones\\/[^/]+\\/counter", LolLootLootMilestonesCounter.class); toClass.put("\\/lol-loot\\/v1\\/new-player-check-done", Boolean.class); toClass.put("\\/lol-loot\\/v1\\/player-display-categories", String[].class); toClass.put("\\/lol-loot\\/v1\\/player-loot", LolLootPlayerLoot[].class); toClass.put("\\/lol-loot\\/v1\\/player-loot-map", Object.class); toClass.put("\\/lol-loot\\/v1\\/player-loot-notifications", LolLootPlayerLootNotification[].class); toClass.put("\\/lol-loot\\/v1\\/player-loot\\/[^/]+", LolLootPlayerLoot.class); toClass.put("\\/lol-loot\\/v1\\/player-loot\\/[^/]+\\/context-menu", LolLootContextMenu[].class); toClass.put("\\/lol-loot\\/v1\\/ready", Boolean.class); toClass.put("\\/lol-loot\\/v1\\/recipes\\/initial-item\\/[^/]+", LolLootRecipeWithMilestones[].class); toClass.put("\\/lol-loot\\/v2\\/player-loot-map", LolLootPlayerLootMap.class); toClass.put("\\/lol-loyalty\\/v1\\/inventory-request-notification", LolLoyaltyLoyaltyStatusNotification.class); toClass.put("\\/lol-loyalty\\/v1\\/status-notification", LolLoyaltyLoyaltyStatusNotification.class); toClass.put("\\/lol-maps\\/v1\\/map\\/[^/]+", LolMapsMaps.class); toClass.put("\\/lol-maps\\/v1\\/maps", LolMapsMaps[].class); toClass.put("\\/lol-maps\\/v2\\/map\\/[^/]+\\/[^/]+", LolMapsMaps.class); toClass.put("\\/lol-maps\\/v2\\/map\\/[^/]+\\/[^/]+\\/[^/]+", LolMapsMaps.class); toClass.put("\\/lol-maps\\/v2\\/maps", LolMapsMaps[].class); toClass.put("\\/lol-match-history\\/v1\\/delta", LolMatchHistoryMatchHistoryPlayerDelta.class); toClass.put("\\/lol-match-history\\/v1\\/game-timelines\\/[^/]+", LolMatchHistoryMatchHistoryTimelineFrames.class); toClass.put("\\/lol-match-history\\/v1\\/games\\/[^/]+", LolMatchHistoryMatchHistoryGame.class); toClass.put("\\/lol-match-history\\/v1\\/products\\/lol\\/current-summoner\\/matches", LolMatchHistoryMatchHistoryList.class); toClass.put("\\/lol-match-history\\/v1\\/products\\/lol\\/[^/]+\\/matches", LolMatchHistoryMatchHistoryList.class); toClass.put("\\/lol-match-history\\/v1\\/products\\/tft\\/[^/]+\\/matches", LolMatchHistoryGAMHSMatchHistoryList.class); toClass.put("\\/lol-match-history\\/v1\\/recently-played-summoners", LolMatchHistoryRecentlyPlayedSummoner[].class); toClass.put("\\/lol-match-history\\/v1\\/web-url", String.class); toClass.put("\\/lol-match-history\\/v3\\/matchlist\\/account\\/[^/]+", LolMatchHistoryMatchHistoryList.class); toClass.put("\\/lol-matchmaking\\/v1\\/ready-check", LolMatchmakingMatchmakingReadyCheckResource.class); toClass.put("\\/lol-matchmaking\\/v1\\/search", LolMatchmakingMatchmakingSearchResource.class); toClass.put("\\/lol-matchmaking\\/v1\\/search\\/errors", LolMatchmakingMatchmakingSearchErrorResource[].class); toClass.put("\\/lol-matchmaking\\/v1\\/search\\/errors\\/[^/]+", LolMatchmakingMatchmakingSearchErrorResource.class); toClass.put("\\/lol-missions\\/v1\\/data", PlayerMissionEligibilityData.class); toClass.put("\\/lol-missions\\/v1\\/missions", PlayerMissionDTO[].class); toClass.put("\\/lol-missions\\/v1\\/series", SeriesDTO[].class); toClass.put("\\/lol-npe-rewards\\/v1\\/challenges\\/progress", LolNpeRewardsChallengesProgress.class); toClass.put("\\/lol-npe-rewards\\/v1\\/level-rewards", LolNpeRewardsRewardSeries.class); toClass.put("\\/lol-npe-rewards\\/v1\\/level-rewards\\/state", LolNpeRewardsRewardSeriesState.class); toClass.put("\\/lol-npe-rewards\\/v1\\/login-rewards", LolNpeRewardsRewardSeries.class); toClass.put("\\/lol-npe-rewards\\/v1\\/login-rewards\\/state", LolNpeRewardsRewardSeriesState.class); toClass.put("\\/lol-npe-tutorial-path\\/v1\\/rewards\\/champ", LolNpeTutorialPathCollectionsChampion.class); toClass.put("\\/lol-npe-tutorial-path\\/v1\\/settings", LolNpeTutorialPathAccountSettingsTutorial.class); toClass.put("\\/lol-npe-tutorial-path\\/v1\\/tutorials", LolNpeTutorialPathTutorial[].class); toClass.put("\\/lol-patch\\/v1\\/checking-enabled", Boolean.class); toClass.put("\\/lol-patch\\/v1\\/environment", LolPatchChunkingPatcherEnvironment.class); toClass.put("\\/lol-patch\\/v1\\/game-version", String.class); toClass.put("\\/lol-patch\\/v1\\/notifications", LolPatchNotification[].class); toClass.put("\\/lol-patch\\/v1\\/products\\/league_of_legends\\/install-location", LolPatchInstallPaths.class); toClass.put("\\/lol-patch\\/v1\\/products\\/league_of_legends\\/state", LolPatchProductState.class); toClass.put("\\/lol-patch\\/v1\\/products\\/league_of_legends\\/supported-game-releases", LolPatchSupportedGameReleases.class); toClass.put("\\/lol-patch\\/v1\\/status", LolPatchStatus.class); toClass.put("\\/lol-perks\\/v1\\/currentpage", LolPerksPerkPageResource.class); toClass.put("\\/lol-perks\\/v1\\/customizationlimits", LolPerksCustomizationLimits.class); toClass.put("\\/lol-perks\\/v1\\/inventory", LolPerksPlayerInventory.class); toClass.put("\\/lol-perks\\/v1\\/pages", LolPerksPerkPageResource[].class); toClass.put("\\/lol-perks\\/v1\\/pages\\/[^/]+", LolPerksPerkPageResource.class); toClass.put("\\/lol-perks\\/v1\\/perks", LolPerksPerkUIPerk[].class); toClass.put("\\/lol-perks\\/v1\\/perks\\/disabled", Integer[].class); toClass.put("\\/lol-perks\\/v1\\/perks\\/gameplay-updated", Integer[].class); toClass.put("\\/lol-perks\\/v1\\/schema-version", Integer.class); toClass.put("\\/lol-perks\\/v1\\/servicesettings", LolPerksServiceSettings.class); toClass.put("\\/lol-perks\\/v1\\/settings", LolPerksUISettings.class); toClass.put("\\/lol-perks\\/v1\\/show-auto-modified-pages-notification", Boolean.class); toClass.put("\\/lol-perks\\/v1\\/styles", LolPerksPerkUIStyle[].class); toClass.put("\\/lol-personalized-offers\\/v1\\/offers", LolPersonalizedOffersUIOffer[].class); toClass.put("\\/lol-personalized-offers\\/v1\\/ready", Boolean.class); toClass.put("\\/lol-personalized-offers\\/v1\\/status", LolPersonalizedOffersUIStatus.class); toClass.put("\\/lol-personalized-offers\\/v1\\/themed", Boolean.class); toClass.put("\\/lol-pft\\/v2\\/survey", LolPftPFTSurvey.class); toClass.put("\\/lol-platform-config\\/v1\\/initial-configuration-complete", Boolean.class); toClass.put("\\/lol-platform-config\\/v1\\/namespaces", Object.class); toClass.put("\\/lol-platform-config\\/v1\\/namespaces\\/[^/]+", Object.class); toClass.put("\\/lol-platform-config\\/v1\\/namespaces\\/[^/]+\\/[^/]+", Object.class); toClass.put("\\/lol-player-behavior\\/v1\\/ban", LolPlayerBehaviorBanNotification.class); toClass.put("\\/lol-player-behavior\\/v1\\/chat-restriction", LolPlayerBehaviorRestrictionNotification.class); toClass.put("\\/lol-player-behavior\\/v1\\/code-of-conduct-notification", LolPlayerBehaviorCodeOfConductNotification.class); toClass.put("\\/lol-player-behavior\\/v1\\/config", LolPlayerBehaviorPlayerBehaviorConfig.class); toClass.put("\\/lol-player-behavior\\/v1\\/ranked-restriction", LolPlayerBehaviorRestrictionNotification.class); toClass.put("\\/lol-player-behavior\\/v1\\/reform-card", LolPlayerBehaviorReformCard.class); toClass.put("\\/lol-player-behavior\\/v1\\/reporter-feedback", LolPlayerBehaviorReporterFeedback[].class); toClass.put("\\/lol-player-behavior\\/v1\\/reporter-feedback\\/[^/]+", LolPlayerBehaviorReporterFeedback.class); toClass.put("\\/lol-player-behavior\\/v2\\/reform-card", LolPlayerBehaviorReformCardV2.class); toClass.put("\\/lol-player-level-up\\/v1\\/level-up", LolPlayerLevelUpPlayerLevelUpEvent.class); toClass.put("\\/lol-player-level-up\\/v1\\/level-up-notifications\\/[^/]+", LolPlayerLevelUpPlayerLevelUpEventAck.class); toClass.put("\\/lol-player-messaging\\/v1\\/celebration\\/notification", LolPlayerMessagingDynamicCelebrationMessagingNotificationResource.class); toClass.put("\\/lol-player-messaging\\/v1\\/notification", LolPlayerMessagingPlayerMessagingNotificationResource.class); toClass.put("\\/lol-player-preferences\\/v1\\/player-preferences-ready", Boolean.class); toClass.put("\\/lol-player-preferences\\/v1\\/preference\\/[^/]+", Object.class); toClass.put("\\/lol-pre-end-of-game\\/v1\\/currentSequenceEvent", LolPreEndOfGameSequenceEvent.class); toClass.put("\\/lol-premade-voice\\/v1\\/availability", LolPremadeVoiceVoiceAvailability.class); toClass.put("\\/lol-premade-voice\\/v1\\/capturedevices", LolPremadeVoiceDeviceResource[].class); toClass.put("\\/lol-premade-voice\\/v1\\/first-experience", LolPremadeVoiceFirstExperience.class); toClass.put("\\/lol-premade-voice\\/v1\\/mic-test", LolPremadeVoiceAudioPropertiesResource.class); toClass.put("\\/lol-premade-voice\\/v1\\/participant-records", LolPremadeVoicePremadeVoiceParticipantDto[].class); toClass.put("\\/lol-premade-voice\\/v1\\/participants", LolPremadeVoicePremadeVoiceParticipantDto[].class); toClass.put("\\/lol-premade-voice\\/v1\\/settings", LolPremadeVoiceSettingsResource.class); toClass.put("\\/lol-publishing-content\\/v1\\/ready", Boolean.class); toClass.put("\\/lol-publishing-content\\/v1\\/tft-hub-cards", Object.class); toClass.put("\\/lol-purchase-widget\\/v1\\/configuration", LolPurchaseWidgetPurchaseWidgetConfig.class); toClass.put("\\/lol-purchase-widget\\/v1\\/order-notifications", LolPurchaseWidgetOrderNotificationResource[].class); toClass.put("\\/lol-purchase-widget\\/v1\\/purchasable-item", LolPurchaseWidgetPurchasableItem.class); toClass.put("\\/lol-purchase-widget\\/v3\\/base-skin-line-data\\/[^/]+", LolPurchaseWidgetBaseSkinLineDto.class); toClass.put("\\/lol-purchase-widget\\/v3\\/purchase-offer-order-statuses", LolPurchaseWidgetPurchaseOfferOrderStatuses.class); toClass.put("\\/lol-ranked\\/v1\\/apex-leagues\\/[^/]+\\/[^/]+", LolRankedLeagueLadderInfo.class); toClass.put("\\/lol-ranked\\/v1\\/challenger-ladders-enabled", String[].class); toClass.put("\\/lol-ranked\\/v1\\/current-lp-change-notification", LolRankedLcuLeagueNotification.class); toClass.put("\\/lol-ranked\\/v1\\/current-ranked-stats", LolRankedRankedStats.class); toClass.put("\\/lol-ranked\\/v1\\/eos-notifications", LolRankedEosNotificationResource[].class); toClass.put("\\/lol-ranked\\/v1\\/eos-rewards", LolRankedEosRewardsConfig.class); toClass.put("\\/lol-ranked\\/v1\\/league-ladders\\/[^/]+", LolRankedLeagueLadderInfo[].class); toClass.put("\\/lol-ranked\\/v1\\/notifications", LolRankedLcuLeagueNotification[].class); toClass.put("\\/lol-ranked\\/v1\\/ranked-stats", Object.class); toClass.put("\\/lol-ranked\\/v1\\/ranked-stats\\/[^/]+", LolRankedRankedStats.class); toClass.put("\\/lol-ranked\\/v1\\/rated-ladder\\/[^/]+", LolRankedRatedLadderInfo.class); toClass.put("\\/lol-ranked\\/v1\\/signed-ranked-stats", LolRankedSignedRankedStatsDTO.class); toClass.put("\\/lol-ranked\\/v1\\/social-leaderboard-ranked-queue-stats-for-puuids", Object.class); toClass.put("\\/lol-ranked\\/v1\\/splits-config", LolRankedRewardsInfo.class); toClass.put("\\/lol-ranked\\/v1\\/top-rated-ladders-enabled", String[].class); toClass.put("\\/lol-ranked\\/v2\\/tiers", LolRankedParticipantTiers[].class); toClass.put("\\/lol-regalia\\/v2\\/config", LolRegaliaRegaliaFrontendConfig.class); toClass.put("\\/lol-regalia\\/v2\\/current-summoner\\/regalia", LolRegaliaRegaliaWithPreferences.class); toClass.put("\\/lol-regalia\\/v2\\/summoners\\/[^/]+\\/queues\\/[^/]+\\/positions\\/[^/]+\\/regalia", LolRegaliaRegalia.class); toClass.put("\\/lol-regalia\\/v2\\/summoners\\/[^/]+\\/queues\\/[^/]+\\/regalia", LolRegaliaRegalia.class); toClass.put("\\/lol-regalia\\/v2\\/summoners\\/[^/]+\\/regalia", LolRegaliaRegalia.class); toClass.put("\\/lol-regalia\\/v2\\/summoners\\/[^/]+\\/regalia\\/async", LolRegaliaRegaliaAsync.class); toClass.put("\\/lol-replays\\/v1\\/configuration", LolReplaysReplaysConfiguration.class); toClass.put("\\/lol-replays\\/v1\\/metadata\\/[^/]+", LolReplaysReplayMetadata.class); toClass.put("\\/lol-replays\\/v1\\/rofls\\/path", String.class); toClass.put("\\/lol-replays\\/v1\\/rofls\\/path\\/default", String.class); toClass.put("\\/lol-rewards\\/v1\\/grants", LolRewardsRewardGrant[].class); toClass.put("\\/lol-rewards\\/v1\\/groups", LolRewardsSvcRewardGroup[].class); toClass.put("\\/lol-rms\\/v1\\/champion-mastery-leaveup-update", LolRiotMessagingServiceChampionMasteryLevelUp[].class); toClass.put("\\/lol-rso-auth\\/configuration\\/v3\\/ready-state", LolRsoAuthRSOConfigReadyState.class); toClass.put("\\/lol-rso-auth\\/v1\\/auth-hints\\/hint", LolRsoAuthAuthHint.class); toClass.put("\\/lol-rso-auth\\/v1\\/authorization", LolRsoAuthAuthorization.class); toClass.put("\\/lol-rso-auth\\/v1\\/authorization\\/access-token", LolRsoAuthAccessToken.class); toClass.put("\\/lol-rso-auth\\/v1\\/authorization\\/error", LolRsoAuthAuthError.class); toClass.put("\\/lol-rso-auth\\/v1\\/authorization\\/id-token", LolRsoAuthIdToken.class); toClass.put("\\/lol-rso-auth\\/v1\\/authorization\\/userinfo", LolRsoAuthUserInfo.class); toClass.put("\\/lol-rso-auth\\/v1\\/status\\/[^/]+", LolRsoAuthRegionStatus.class); toClass.put("\\/lol-service-status\\/v1\\/lcu-status", LolServiceStatusServiceStatusResource.class); toClass.put("\\/lol-service-status\\/v1\\/ticker-messages", LolServiceStatusTickerMessage[].class); toClass.put("\\/lol-settings\\/v1\\/account\\/didreset", Boolean.class); toClass.put("\\/lol-settings\\/v1\\/account\\/[^/]+", Object.class); toClass.put("\\/lol-settings\\/v1\\/local\\/[^/]+", Object.class); toClass.put("\\/lol-settings\\/v2\\/account\\/[^/]+\\/[^/]+", Object.class); toClass.put("\\/lol-settings\\/v2\\/didreset\\/[^/]+", Boolean.class); toClass.put("\\/lol-settings\\/v2\\/local\\/[^/]+", Object.class); toClass.put("\\/lol-settings\\/v2\\/ready", Boolean.class); toClass.put("\\/lol-shutdown\\/v1\\/notification", LolShutdownShutdownNotification.class); toClass.put("\\/lol-simple-dialog-messages\\/v1\\/messages", LolSimpleDialogMessagesMessage[].class); toClass.put("\\/lol-social-leaderboard\\/v1\\/leaderboard-next-update-time", Long.class); toClass.put("\\/lol-social-leaderboard\\/v1\\/social-leaderboard-data", LolSocialLeaderboardSocialLeaderboardData.class); toClass.put("\\/lol-spectator\\/v1\\/spectate", LolSpectatorSpectateGameInfo.class); toClass.put("\\/lol-statstones\\/v1\\/eog-notifications", Object[].class); toClass.put("\\/lol-statstones\\/v1\\/featured-champion-statstones\\/[^/]+", LolStatstonesStatstone[].class); toClass.put("\\/lol-statstones\\/v1\\/profile-summary\\/[^/]+", LolStatstonesProfileStatstoneSummary[].class); toClass.put("\\/lol-statstones\\/v1\\/statstone\\/[^/]+\\/owned", Boolean.class); toClass.put("\\/lol-statstones\\/v1\\/statstones-enabled-queue-ids", Integer[].class); toClass.put("\\/lol-statstones\\/v1\\/vignette-notifications", Object[].class); toClass.put("\\/lol-statstones\\/v2\\/player-statstones-self\\/[^/]+", LolStatstonesStatstoneSet[].class); toClass.put("\\/lol-statstones\\/v2\\/player-summary-self", LolStatstonesChampionStatstoneSummary[].class); toClass.put("\\/lol-store\\/v1\\/catalog", LolStoreCatalogItem[].class); toClass.put("\\/lol-store\\/v1\\/catalog\\/sales", LolStoreItemSale[].class); toClass.put("\\/lol-store\\/v1\\/catalog\\/[^/]+", LolStoreCatalogItem[].class); toClass.put("\\/lol-store\\/v1\\/catalogByInstanceIds", LolStoreCatalogItem[].class); toClass.put("\\/lol-store\\/v1\\/getStoreUrl", String.class); toClass.put("\\/lol-store\\/v1\\/giftablefriends", LolStoreGiftingFriend[].class); toClass.put("\\/lol-store\\/v1\\/itemKeysFromInstanceIds", Object.class); toClass.put("\\/lol-store\\/v1\\/itemKeysFromOfferIds", Object.class); toClass.put("\\/lol-store\\/v1\\/lastPage", String.class); toClass.put("\\/lol-store\\/v1\\/offers", LolStoreCapOffer[].class); toClass.put("\\/lol-store\\/v1\\/order-notifications", LolStoreOrderNotificationResource[].class); toClass.put("\\/lol-store\\/v1\\/order-notifications\\/[^/]+", LolStoreOrderNotificationResource.class); toClass.put("\\/lol-store\\/v1\\/paymentDetails", Object.class); toClass.put("\\/lol-store\\/v1\\/skins\\/[^/]+", LolStoreCatalogItem.class); toClass.put("\\/lol-store\\/v1\\/status", LolStoreStoreStatus.class); toClass.put("\\/lol-store\\/v1\\/store-ready", Boolean.class); toClass.put("\\/lol-store\\/v1\\/wallet", LolStoreWallet.class); toClass.put("\\/lol-store\\/v1\\/[^/]+", Object.class); toClass.put("\\/lol-suggested-players\\/v1\\/suggested-players", LolSuggestedPlayersSuggestedPlayersSuggestedPlayer[].class); toClass.put("\\/lol-summoner\\/v1\\/check-name-availability-new-summoners\\/[^/]+", Boolean.class); toClass.put("\\/lol-summoner\\/v1\\/check-name-availability\\/[^/]+", Boolean.class); toClass.put("\\/lol-summoner\\/v1\\/current-summoner", LolSummonerSummoner.class); toClass.put("\\/lol-summoner\\/v1\\/current-summoner\\/account-and-summoner-ids", LolSummonerAccountIdAndSummonerId.class); toClass.put("\\/lol-summoner\\/v1\\/current-summoner\\/autofill", LolSummonerAutoFillQueueDto[].class); toClass.put("\\/lol-summoner\\/v1\\/current-summoner\\/jwt", String.class); toClass.put("\\/lol-summoner\\/v1\\/current-summoner\\/profile-privacy", LolSummonerProfilePrivacy.class); toClass.put("\\/lol-summoner\\/v1\\/current-summoner\\/rerollPoints", LolSummonerSummonerRerollPoints.class); toClass.put("\\/lol-summoner\\/v1\\/current-summoner\\/summoner-profile", Object.class); toClass.put("\\/lol-summoner\\/v1\\/profile-privacy-enabled", LolSummonerProfilePrivacyEnabledState.class); toClass.put("\\/lol-summoner\\/v1\\/status", LolSummonerStatus.class); toClass.put("\\/lol-summoner\\/v1\\/summoner-profile", Object.class); toClass.put("\\/lol-summoner\\/v1\\/summoner-requests-ready", Boolean.class); toClass.put("\\/lol-summoner\\/v1\\/summoners", LolSummonerSummoner.class); toClass.put("\\/lol-summoner\\/v1\\/summoners-by-puuid-cached\\/[^/]+", LolSummonerSummoner.class); toClass.put("\\/lol-summoner\\/v1\\/summoners\\/[^/]+", LolSummonerSummoner.class); toClass.put("\\/lol-summoner\\/v2\\/summoner-icons", LolSummonerSummonerIdAndIcon[].class); toClass.put("\\/lol-summoner\\/v2\\/summoner-names", LolSummonerSummonerIdAndName[].class); toClass.put("\\/lol-summoner\\/v2\\/summoners", LolSummonerSummoner[].class); toClass.put("\\/lol-summoner\\/v2\\/summoners\\/puuid\\/[^/]+", LolSummonerSummoner.class); toClass.put("\\/lol-tastes\\/v1\\/ready", Boolean.class); toClass.put("\\/lol-tastes\\/v1\\/skins-model", LolTastesDataModelResponse.class); toClass.put("\\/lol-tft\\/v1\\/tft\\/hubFooterColors", LolTftLolTftHubFooterColors.class); toClass.put("\\/lol-tft\\/v1\\/tft\\/storePromos", LolTftLolTftStorePromos.class); toClass.put("\\/lol-tft\\/v2\\/tft\\/battlepass", LolMissionsTftPaidBattlepass.class); toClass.put("\\/lol-token-upsell\\/v1\\/all", LolWorldsTokenCardTokenUpsell[].class); toClass.put("\\/lol-trophies\\/v1\\/current-summoner\\/trophies\\/profile", LolTrophiesTrophyProfileData.class); toClass.put("\\/lol-trophies\\/v1\\/players\\/[^/]+\\/trophies\\/profile", LolTrophiesTrophyProfileData.class); toClass.put("\\/memory\\/v1\\/fe-processes-ready", Boolean.class); toClass.put("\\/patcher\\/v1\\/notifications", PatcherNotification[].class); toClass.put("\\/patcher\\/v1\\/p2p\\/status", PatcherP2PStatus.class); toClass.put("\\/patcher\\/v1\\/products", String[].class); toClass.put("\\/patcher\\/v1\\/products\\/[^/]+\\/paths", Object.class); toClass.put("\\/patcher\\/v1\\/products\\/[^/]+\\/state", PatcherProductState.class); toClass.put("\\/patcher\\/v1\\/products\\/[^/]+\\/tags", Object.class); toClass.put("\\/patcher\\/v1\\/status", PatcherStatus.class); toClass.put("\\/performance\\/v1\\/memory", Object.class); toClass.put("\\/performance\\/v1\\/report", Object[].class); toClass.put("\\/performance\\/v1\\/system-info", Object.class); toClass.put("\\/player-notifications\\/v1\\/config", PlayerNotificationsPlayerNotificationConfigResource.class); toClass.put("\\/player-notifications\\/v1\\/notifications", PlayerNotificationsPlayerNotificationResource[].class); toClass.put("\\/player-notifications\\/v1\\/notifications\\/[^/]+", PlayerNotificationsPlayerNotificationResource.class); toClass.put("\\/plugin-manager\\/v1\\/external-plugins\\/availability", ExternalPluginsResource.class); toClass.put("\\/plugin-manager\\/v1\\/status", PluginManagerResource.class); toClass.put("\\/plugin-manager\\/v2\\/descriptions", PluginDescriptionResource[].class); toClass.put("\\/plugin-manager\\/v2\\/descriptions\\/[^/]+", PluginDescriptionResource.class); toClass.put("\\/plugin-manager\\/v2\\/plugins", PluginResource[].class); toClass.put("\\/plugin-manager\\/v2\\/plugins\\/[^/]+", PluginResource.class); toClass.put("\\/plugin-manager\\/v3\\/plugins-manifest", Object.class); toClass.put("\\/process-control\\/v1\\/process", ProcessControlProcess.class); toClass.put("\\/riot-messaging-service\\/v1\\/message\\/[^/]+", RmsMessage.class); toClass.put("\\/riot-messaging-service\\/v1\\/message\\/[^/]+\\/[^/]+", RmsMessage.class); toClass.put("\\/riot-messaging-service\\/v1\\/message\\/[^/]+\\/[^/]+\\/[^/]+", RmsMessage.class); toClass.put("\\/riot-messaging-service\\/v1\\/message\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+", RmsMessage.class); toClass.put("\\/riot-messaging-service\\/v1\\/message\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+", RmsMessage.class); toClass.put("\\/riot-messaging-service\\/v1\\/message\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+\\/[^/]+", RmsMessage.class); toClass.put("\\/riot-messaging-service\\/v1\\/session", RiotMessagingServiceSession.class); toClass.put("\\/riot-messaging-service\\/v1\\/state", RiotMessagingServiceState.class); toClass.put("\\/riotclient\\/affinity", Object.class); toClass.put("\\/riotclient\\/app-name", String.class); toClass.put("\\/riotclient\\/app-port", Integer.class); toClass.put("\\/riotclient\\/auth-token", String.class); toClass.put("\\/riotclient\\/command-line-args", String[].class); toClass.put("\\/riotclient\\/get_region_locale", RegionLocale.class); toClass.put("\\/riotclient\\/machine-id", String.class); toClass.put("\\/riotclient\\/region-locale", RegionLocale.class); toClass.put("\\/riotclient\\/system-info\\/v1\\/basic-info", basicSystemInfo.class); toClass.put("\\/riotclient\\/trace", Object.class); toClass.put("\\/riotclient\\/ux-crash-count", Integer.class); toClass.put("\\/riotclient\\/ux-state", String.class); toClass.put("\\/riotclient\\/v1\\/crash-reporting\\/environment", CrashReportingEnvironment.class); toClass.put("\\/riotclient\\/zoom-scale", Double.class); toClass.put("\\/sanitizer\\/v1\\/status", SanitizerSanitizerStatus.class); toClass.put("\\/swagger\\/v1\\/api-docs", Object.class); toClass.put("\\/swagger\\/v1\\/api-docs\\/[^/]+", Object.class); toClass.put("\\/swagger\\/v2\\/swagger.json", Object.class); toClass.put("\\/swagger\\/v3\\/openapi.json", Object.class); toClass.put("\\/system\\/v1\\/builds", BuildInfo.class); toClass.put("\\/telemetry\\/v1\\/application-start-time", Long.class); toClass.put("\\/voice-chat\\/v1\\/audio-properties", VoiceChatAudioPropertiesResource.class); toClass.put("\\/voice-chat\\/v1\\/call-stats\\/aggregate", VoiceChatCallStatsResource.class); toClass.put("\\/voice-chat\\/v1\\/call-stats\\/[^/]+", VoiceChatCallStatsResource[].class); toClass.put("\\/voice-chat\\/v1\\/codec-settings", VoiceChatCodecSettingsResource.class); toClass.put("\\/voice-chat\\/v1\\/config", VoiceChatConfigResource.class); toClass.put("\\/voice-chat\\/v1\\/errors", VoiceChatVoiceErrorCounterResource[].class); toClass.put("\\/voice-chat\\/v1\\/push-to-talk", VoiceChatPushToTalkResource.class); toClass.put("\\/voice-chat\\/v2\\/devices\\/capture", VoiceChatDeviceResource[].class); toClass.put("\\/voice-chat\\/v2\\/devices\\/capture\\/permission", VoiceChatCaptureDevicePermissionStatus.class); toClass.put("\\/voice-chat\\/v2\\/devices\\/render", VoiceChatDeviceResource[].class); toClass.put("\\/voice-chat\\/v2\\/sessions", VoiceChatSessionResource[].class); toClass.put("\\/voice-chat\\/v2\\/sessions\\/[^/]+", VoiceChatSessionResource.class); toClass.put("\\/voice-chat\\/v2\\/sessions\\/[^/]+\\/participants\\/[^/]+", VoiceChatParticipantResource.class); toClass.put("\\/voice-chat\\/v2\\/settings", VoiceChatSettingsResource.class); toClass.put("\\/voice-chat\\/v2\\/state", VoiceChatStateResource.class); toClass.put("\\/[^/]+\\/assets\\/[^/]+", Object.class); } }
stirante/lol-client-java-api
src/main/java/generated/UriMap.java
249,354
import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import org.apache.solr.client.solrj.SolrServerException; /** * This is the receiver class that runs term and concept search * * @author chethans */ public class Searcher { CSExpertSearch csExpertSearcher; public Searcher(CSExpertSearch expertSearcher) { this.csExpertSearcher = expertSearcher; } public void researchConceptSearch() throws IOException, SolrServerException { System.out.println("\nResearch concept search started...\n"); CSExpertSearch.resultString += "\nResearch concept search started...\n"; SolrUtilities.setCurrentCore("people"); runConceptSearch(csExpertSearcher.getSearchString()); CSExpertSearch.resultString += "Research concept search completed.\n"; System.out.println("Research concept search completed.\n"); } public void researchTermSearch() throws SolrServerException, IOException { System.out.println("\nInput terms search started...\n"); CSExpertSearch.resultString += "\nInput terms search started...\n"; SolrUtilities.setCurrentCore("people"); runTermSearch(); System.out.println("Input terms search completed.\n"); CSExpertSearch.resultString += "Input terms search completed.\n"; } /** * Run concept search. * Perform concept based search for find experts * @param concept the concept * @return the array list * @throws IOException Signals that an I/O exception has occurred. * @throws SolrServerException the solr server exception */ private ArrayList<Map<String, String>> runConceptSearch(String concept) throws IOException, SolrServerException { CSExpertSearch. resultString += "\nResearch concept string:\n"; CSExpertSearch.resultString += concept; ArrayList<Map<String, String>> relevancyMapList = new ArrayList<Map<String, String>>(); Map<String,String> topDocumentsMap; Map<String,Double> finalWeightedMap; CSExpertSearch.resultString += "\n\nResearch concept search results:\n\n"; String[] conceptQueries = QueryGenerator.generateConceptQueries(concept); for(String conceptQuery:conceptQueries) { topDocumentsMap = SolrUtilities.getTopDocsWithScores(conceptQuery); relevancyMapList.add(topDocumentsMap); } finalWeightedMap = ResultScorer.scoreByLinearDecreasingWeighting(relevancyMapList,1); CSExpertSearch.resultString += "Person Name\t" + "Weighted Relevancy score for concept queries\n"; Iterator<String> iterator = finalWeightedMap.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = finalWeightedMap.get(key).toString(); CSExpertSearch.resultString += key + "\t" + value + "\n"; } CSExpertSearch.resultString += "\n"; return relevancyMapList; } /** * Run_term_search. * Perform term based search to find experts * @return the string * @throws SolrServerException the solr server exception * @throws IOException Signals that an I/O exception has occurred. */ private String runTermSearch() throws SolrServerException, IOException { String queryString = csExpertSearcher.getSearchString(); ArrayList<Map<String, String>> finalRelevancyList = new ArrayList<Map<String, String>>(); ArrayList<Map<String, String>> conceptRelevancyList = null; Map<String,Double> finalWeightedMap; Map<String, String> relevantConcepts; Map.Entry<String, String> bestRelevantConcept; SolrUtilities.setCurrentCore("concept"); relevantConcepts = SolrUtilities.getTopDocsWithScores(queryString); bestRelevantConcept = null; if(relevantConcepts.size() > 0) { for (Map.Entry<String, String> entry : relevantConcepts.entrySet()) { if (bestRelevantConcept == null || entry.getValue().compareTo( bestRelevantConcept.getValue()) > 0) { bestRelevantConcept = entry; } } SolrUtilities.setCurrentCore("people"); conceptRelevancyList = runConceptSearch(bestRelevantConcept.getKey().toString()); } String tmpString = CSExpertSearch.resultString; Map<String, String> termRelevancyMap = SolrUtilities.getTopDocsWithScores(queryString); CSExpertSearch.resultString = tmpString; CSExpertSearch.resultString += "\nInput term search string:\n"; CSExpertSearch.resultString += queryString; CSExpertSearch.resultString += "\n\nMost relevant concept to input terms:\n"; if(relevantConcepts.size() > 0) CSExpertSearch.resultString += bestRelevantConcept.getKey().toString(); CSExpertSearch.resultString += "\n\nInput terms search results:\n"; finalRelevancyList.add(termRelevancyMap); if(relevantConcepts.size() > 0) finalRelevancyList.addAll(conceptRelevancyList); finalWeightedMap = ResultScorer.scoreByLinearDecreasingWeighting(finalRelevancyList,2); Iterator<String> iterator = finalWeightedMap.keySet().iterator(); CSExpertSearch.resultString += "Person Name\t" + "Weighted Relevancy score for term/concept queries\n"; while (iterator.hasNext()) { String key = iterator.next(); String value = finalWeightedMap.get(key).toString(); CSExpertSearch.resultString += key + "\t" + value + "\n"; } CSExpertSearch.resultString += "\n"; return CSExpertSearch.resultString; } }
ksheeras/CSExpertSearch
src/Searcher.java
249,356
/* Licensed under GPL-3.0 */ package CWE_Reader; import java.util.HashMap; import java.util.Map; /** * CWEList class. * * @author CryptoguardTeam Created on 2018-12-05. * @version 03.07.01 * @since 01.00.07 * <p>The Lazy CWE Loader that retrieves CWES for Java */ public class CWEList { //region Attributes private final Double cweVersion = 3.1; private Map<Integer, CWE> cweList; //endregion /** The empty constructor for this class */ public CWEList() {} //region Getters /** * The "Lazy Loading" Getter for cweList * * <p>getCweList() * * @return a {@link java.util.Map} object. */ public Map<Integer, CWE> getCweList() { if (this.cweList == null) CWE_Loader(); return cweList; } /** * The "Lazy Loading" for CWE * * <p>CWE_Loader() */ private void CWE_Loader() { this.cweList = new HashMap<>(); this.cweList.put( 256, new CWE( 256, "Unprotected Storage of Credentials", "Variant,Incomplete", "Storing a password in plaintext may result in a system compromise.", "Password management issues occur when a password is stored in plaintext in an application's properties or configuration file. Storing a plaintext password in a configuration file allows anyone who can read the file access to the password-protected resource.\n::NATURE:ChildOf:CWE ID:522:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:522:VIEW ID:699:ORDINAL:Primary::NATURE:CanAlsoBe:CWE ID:319:VIEW ID:1000::NATURE:CanAlsoBe:CWE ID:319:VIEW ID:699::\n::ORDINALITY:Primary:DESCRIPTION:::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Architecture and Design:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Gain Privileges or Assume Identity::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Avoid storing passwords in easily accessible locations.::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Consider storing cryptographic hashes of passwords as an alternative to storing in plaintext.::PHASE::STRATEGY::EFFECTIVENESS:None:DESCRIPTION:A programmer might attempt to remedy the password management problem by obscuring the password with an encoding function, such as base 64 encoding, but this effort does not adequately protect the password because the encoding can be detected and decoded easily.::\nTAXONOMY NAME:7 Pernicious Kingdoms:ENTRY NAME:Password Management::::TAXONOMY NAME:Software Fault Patterns:ENTRY ID:SFP23:ENTRY NAME:Exposed Data::")); this.cweList.put( 759, new CWE( 759, "Use of a One-Way Hash without a Salt", "Base ", "Incomplete", "The software uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the software does not also use a salt as part of the input.\nThis makes it easier for attackers to pre-compute the hash value using dictionary attack techniques such as rainbow tables. It should be noted that, despite common perceptions, the use of a good salt with a hash does not sufficiently increase the effort for an attacker who is targeting an individual password, or who has a large amount of computing resources available, such as with cloud-based services or specialized, inexpensive hardware. Offline password cracking can still be effective if the hash function is not expensive to compute; many cryptographic functions are designed to be efficient and can be vulnerable to attacks using massive computing resources, even if the hash is cryptographically strong. The use of a salt only slightly increases the computing requirements for an attacker compared to other strategies such as adaptive hash functions. See CWE-916 for more details.\n::NATURE:ChildOf:CWE ID:916:VIEW ID:699:ORDINAL:Primary::NATURE:ChildOf:CWE ID:916:VIEW ID:1000:ORDINAL:Primary::\n::In cryptography, salt refers to some random addition of data to an input before hashing to make dictionary attacks more difficult.::\n:::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Bypass Protection Mechanism Gain Privileges or Assume Identity:NOTE:Access Control Bypass Protection Mechanism Gain Privileges or Assume Identity If an attacker can gain access to the hashes, then the lack of a salt makes it easier to conduct brute force attacks using techniques such as rainbow tables.::\n::METHOD:Automated Static Analysis - Binary or Bytecode:EFFECTIVENESS:SOAR Partial:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Cost effective for partial coverage: Bytecode Weakness Analysis - including disassembler + source code weakness analysis Binary Weakness Analysis - including disassembler + source code weakness analysis::METHOD:Manual Static Analysis - Binary or Bytecode:EFFECTIVENESS:SOAR Partial:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Cost effective for partial coverage: Binary / Bytecode disassembler - then use manual analysis for vulnerabilities & anomalies::METHOD:Manual Static Analysis - Source Code:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Focused Manual Spotcheck - Focused manual analysis of source Manual Source Code Review (not inspections)::METHOD:Automated Static Analysis - Source Code:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Source code Weakness Analyzer Context-configured Source Code Weakness Analyzer::METHOD:Automated Static Analysis:EFFECTIVENESS:SOAR Partial:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Cost effective for partial coverage: Configuration Checker::METHOD:Architecture or Design Review:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Formal Methods / Correct-By-Construction Cost effective for partial coverage: Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS:High:DESCRIPTION:Use an adaptive hash function that can be configured to change the amount of computational effort needed to compute the hash, such as the number of iterations (stretching) or the amount of memory required. Some hash functions perform salting automatically. These functions can significantly increase the overhead for a brute force attack compared to intentionally-fast functions such as MD5. For example, rainbow table attacks can become infeasible due to the high computing overhead. Finally, since computing power gets faster and cheaper over time, the technique can be reconfigured to increase the workload without forcing an entire replacement of the algorithm in use. Some hash functions that have one or more of these desired properties include bcrypt [REF-291], scrypt [REF-292], and PBKDF2 [REF-293]. While there is active debate about which of these is the most effective, they are all stronger than using salts with hash functions with very little computing overhead. Note that using these functions can have an impact on performance, so they require special consideration to avoid denial-of-service attacks. However, their configurability provides finer control over how much CPU and memory is used, so it could be adjusted to suit the environment's needs.::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS:Limited:DESCRIPTION:If a technique that requires extra computational effort can not be implemented, then for each password that is processed, generate a new random salt using a strong random number generator with unpredictable seeds. Add the salt to the plaintext password before hashing it. When storing the hash, also store the salt. Do not use the same salt for every password.::PHASE:Implementation Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:When using industry-approved techniques, use them correctly. Don't cut corners by skipping resource-intensive steps (CWE-325). These steps are often essential for preventing common attacks.::\n::REFERENCE:CVE-2008-1526:DESCRIPTION:Router does not use a salt with a hash, making it easier to crack passwords.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1526REFERENCE:CVE-2006-1058:DESCRIPTION:Router does not use a salt with a hash, making it easier to crack passwords.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1058\n")); this.cweList.put( 547, new CWE( 547, "Use of Hard-coded, Security-relevant Constants", "Variant", "Draft", "The program uses hard-coded constants instead of symbolic names for security-critical values, which increases the likelihood of mistakes during code maintenance or security policy change.\nIf the developer does not find all occurrences of the hard-coded constants, an incorrect policy decision may be made if one of the constants is not changed. Making changes to these values will require code changes that may be difficult or impossible once the system is released to the field. In addition, these hard-coded values may become available to attackers if the code is ever disclosed.\n::NATURE:ChildOf:CWE ID:710:VIEW ID:1000:ORDINAL:Primary::\n:::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Other:TECHNICAL IMPACT:Varies by Context Quality Degradation:NOTE:Other Varies by Context Quality Degradation The existence of hardcoded constants could cause unexpected behavior and the introduction of weaknesses during code maintenance or when making changes to the code if all occurrences are not modified. The use of hardcoded constants is an indication of poor quality.::\n::PHASE:Implementation:STRATEGY::EFFECTIVENESS::DESCRIPTION:Avoid using hard-coded constants. Configuration files offer a more flexible solution.::\nTAXONOMY NAME:CERT C Secure Coding:ENTRY ID:DCL06-C:ENTRY NAME:Use meaningful symbolic constants to represent literal values in program logic::")); this.cweList.put( 349, new CWE( 349, "Acceptance of Extraneous Untrusted Data With Trusted Data", "Base", "Draft", "The software, when processing trusted data, accepts any untrusted data that is also included with the trusted data, treating the untrusted data as if it were trusted.\n::NATURE:ChildOf:CWE ID:345:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:345:VIEW ID:699:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:SCOPE:Integrity:TECHNICAL IMPACT:Bypass Protection Mechanism Modify Application Data:NOTE:Access Control Integrity Bypass Protection Mechanism Modify Application Data An attacker could package untrusted data with trusted data to bypass protection mechanisms to gain access to and possibly modify sensitive data.::\n::REFERENCE:CVE-2002-0018:DESCRIPTION:Does not verify that trusted entity is authoritative for all entities in its response.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-0018\nTAXONOMY NAME:PLOVER:ENTRY NAME:Untrusted Data Appended with Trusted Data::::TAXONOMY NAME:CERT Java Secure Coding:ENTRY ID:ENV01-J:ENTRY NAME:Place all security-sensitive code in a single JAR and sign and seal it::\n::141::142::75::")); this.cweList.put( 321, new CWE( 321, "Use of Hard-coded Cryptographic Key", "Base", "Draft", "The use of a hard-coded cryptographic key significantly increases the possibility that encrypted data may be recovered.\n::NATURE:ChildOf:CWE ID:798:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:798:VIEW ID:699:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Bypass Protection Mechanism Gain Privileges or Assume Identity:NOTE:Access Control Bypass Protection Mechanism Gain Privileges or Assume Identity If hard-coded cryptographic keys are used, it is almost certain that malicious users will gain access through the account in question.::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Prevention schemes mirror that of hard-coded password storage.::\nTAXONOMY NAME:CLASP:ENTRY NAME:Use of hard-coded cryptographic key::::TAXONOMY NAME:OWASP Top Ten 2007:ENTRY ID:A8:ENTRY NAME:Insecure Cryptographic Storage:MAPPING FIT:CWE More Specific::::TAXONOMY NAME:OWASP Top Ten 2007:ENTRY ID:A9:ENTRY NAME:Insecure Communications:MAPPING FIT:CWE More Specific::::TAXONOMY NAME:OWASP Top Ten 2004:ENTRY ID:A8:ENTRY NAME:Insecure Storage:MAPPING FIT:CWE More Specific::::TAXONOMY NAME:Software Fault Patterns:ENTRY ID:SFP33:ENTRY NAME:Hardcoded sensitive data::\nTYPE:Other:NOTE:The main difference between the use of hard-coded passwords and the use of hard-coded cryptographic keys is the false sense of security that the former conveys. Many people believe that simply hashing a hard-coded password before storage will protect the information from malicious users. However, many hashes are reversible (or at least vulnerable to brute force attacks) -- and further, many authentication protocols simply request the hash itself, making it no better than a password.::")); this.cweList.put( 601, new CWE( 601, "URL Redirection to Untrusted Site ('Open Redirect')", "Variant", "Draft", "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.\nAn http parameter may contain a URL value and could cause the web application to redirect the request to the specified URL. By modifying the URL value to a malicious site, an attacker may successfully launch a phishing scam and steal user credentials. Because the server name in the modified link is identical to the original site, phishing attempts have a more trustworthy appearance.\n::NATURE:ChildOf:CWE ID:610:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:20:VIEW ID:699:ORDINAL:Primary::NATURE:ChildOf:CWE ID:20:VIEW ID:1003:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::PARADIGN NAME:Web Based:PARADIGN PREVALENCE:Undetermined::\n::Phishing is a general term for deceptive attempts to coerce private information from users that will be used for identity theft.::\n::TERM:Open Redirect:DESCRIPTION:::TERM:Cross-site Redirect:DESCRIPTION:::TERM:Cross-domain Redirect:DESCRIPTION:::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Bypass Protection Mechanism Gain Privileges or Assume Identity:NOTE:Access Control Bypass Protection Mechanism Gain Privileges or Assume Identity The user may be redirected to an untrusted page that contains malware which may then compromise the user's machine. This will expose the user to extensive risk and the user's interaction with the web server may also be compromised if the malware conducts keylogging or other attacks that steal credentials, personally identifiable information (PII), or other important data.::SCOPE:Access Control:SCOPE:Confidentiality:SCOPE:Other:TECHNICAL IMPACT:Bypass Protection Mechanism Gain Privileges or Assume Identity Other:NOTE:Access Control Confidentiality Other Bypass Protection Mechanism Gain Privileges or Assume Identity Other The user may be subjected to phishing attacks by being redirected to an untrusted page. The phishing attack may point to an attacker controlled web page that appears to be a trusted web site. The phishers may then steal the user's credentials and then use these credentials to access the legitimate web site.::\n::METHOD:Manual Static Analysis:EFFECTIVENESS:High:DESCRIPTION:Since this weakness does not typically appear frequently within a single software package, manual white box techniques may be able to provide sufficient code coverage and reduction of false positives if all potentially-vulnerable operations can be assessed within limited time constraints.::METHOD:Automated Dynamic Analysis:EFFECTIVENESS::DESCRIPTION:Automated black box tools that supply URLs to every input may be able to spot Location header modifications, but test case coverage is a factor, and custom redirects may not be detected.::METHOD:Automated Static Analysis:EFFECTIVENESS::DESCRIPTION:Automated static analysis tools may not be able to determine whether input influences the beginning of a URL, which is important for reducing false positives.::METHOD:Other:EFFECTIVENESS::DESCRIPTION:Whether this issue poses a vulnerability will be subject to the intended behavior of the application. For example, a search engine might intentionally provide redirects to arbitrary URLs.::METHOD:Automated Static Analysis - Binary or Bytecode:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Bytecode Weakness Analysis - including disassembler + source code weakness analysis Binary Weakness Analysis - including disassembler + source code weakness analysis::METHOD:Dynamic Analysis with Automated Results Interpretation:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Web Application Scanner Web Services Scanner Database Scanners::METHOD:Dynamic Analysis with Manual Results Interpretation:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Fuzz Tester Framework-based Fuzzer::METHOD:Manual Static Analysis - Source Code:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Manual Source Code Review (not inspections)::METHOD:Automated Static Analysis - Source Code:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Source code Weakness Analyzer Context-configured Source Code Weakness Analyzer::METHOD:Architecture or Design Review:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Formal Methods / Correct-By-Construction Cost effective for partial coverage: Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)::\n::PHASE:Implementation:STRATEGY:Input Validation:EFFECTIVENESS::DESCRIPTION:Assume all input is malicious. Use an accept known good input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, boat may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as red or blue. Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Use a whitelist of approved URLs or domains to be used for redirection.::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Use an intermediate disclaimer page that provides the user with a clear warning that they are leaving the current site. Implement a long timeout before the redirect occurs, or force the user to click on the link. Be careful to avoid XSS problems (CWE-79) when generating the disclaimer page.::PHASE:Architecture and Design:STRATEGY:Enforcement by Conversion:EFFECTIVENESS::DESCRIPTION:When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs. For example, ID 1 could map to /login.asp and ID 2 could map to http://www.example.com/. Features such as the ESAPI AccessReferenceMap [REF-45] provide this capability.::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Ensure that no externally-supplied requests are honored by requiring that all redirect requests include a unique nonce generated by the application [REF-483]. Be sure that the nonce is not predictable (CWE-330).::PHASE:Architecture and Design Implementation:STRATEGY:Attack Surface Reduction:EFFECTIVENESS::DESCRIPTION:Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Many open redirect problems occur because the programmer assumed that certain inputs could not be modified, such as cookies and hidden form fields.::PHASE:Operation:STRATEGY:Firewall:EFFECTIVENESS:Moderate:DESCRIPTION:Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth.::\n::REFERENCE:CVE-2005-4206:DESCRIPTION:URL parameter loads the URL into a frame and causes it to appear to be part of a valid page.:LINK:http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-4206REFERENCE:CVE-2008-2951:DESCRIPTION:An open redirect vulnerability in the search script in the software allows remote attackers to redirect users to arbitrary web sites and conduct phishing attacks via a URL as a parameter to the proper function.:LINK:http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2951REFERENCE:CVE-2008-2052:DESCRIPTION:Open redirect vulnerability in the software allows remote attackers to redirect users to arbitrary web sites and conduct phishing attacks via a URL in the proper parameter.:LINK:http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2052\nTAXONOMY NAME:WASC:ENTRY ID:38:ENTRY NAME:URl Redirector Abuse::::TAXONOMY NAME:Software Fault Patterns:ENTRY ID:SFP24:ENTRY NAME:Tainted input to command::\n::194::")); this.cweList.put( 650, new CWE( 650, "Trusting HTTP Permission Methods on the Server Side", "Variant", "Incomplete", "The server contains a protection mechanism that assumes that any URI that is accessed using HTTP GET will not cause a state change to the associated resource. This might allow attackers to bypass intended access restrictions and conduct resource modification and deletion attacks, since some applications allow GET to modify state.\nThe HTTP GET method and some other methods are designed to retrieve resources and not to alter the state of the application or resources on the server side. Furthermore, the HTTP specification requires that GET requests (and other requests) should not have side effects. Believing that it will be enough to prevent unintended resource alterations, an application may disallow the HTTP requests to perform DELETE, PUT and POST operations on the resource representation. However, there is nothing in the HTTP protocol itself that actually prevents the HTTP GET method from performing more than just query of the data. Developers can easily code programs that accept a HTTP GET request that do in fact create, update or delete data on the server. For instance, it is a common practice with REST based Web Services to have HTTP GET requests modifying resources on the server side. However, whenever that happens, the access control needs to be properly enforced in the application. No assumptions should be made that only HTTP DELETE, PUT, POST, and other methods have the power to alter the representation of the resource being accessed in the request.\n::NATURE:ChildOf:CWE ID:436:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:436:VIEW ID:699:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Implementation:DESCRIPTION::::PHASE:Operation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Gain Privileges or Assume Identity:NOTE:Access Control Gain Privileges or Assume Identity An attacker could escalate privileges.::SCOPE:Integrity:TECHNICAL IMPACT:Modify Application Data:NOTE:Integrity Modify Application Data An attacker could modify resources.::SCOPE:Confidentiality:TECHNICAL IMPACT:Read Application Data:NOTE:Confidentiality Read Application Data An attacker could obtain sensitive information.::\n::PHASE:System Configuration:STRATEGY::EFFECTIVENESS::DESCRIPTION:Configure ACLs on the server side to ensure that proper level of access control is defined for each accessible resource representation.::\n")); this.cweList.put( 326, new CWE( 326, "Inadequate Encryption Strength", "Class", "Draft", "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.\nA weak encryption scheme can be subjected to brute force attacks that have a reasonable chance of succeeding using current attack methods and resources.\n::NATURE:ChildOf:CWE ID:693:VIEW ID:1000:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION:::\n::SCOPE:Access Control:SCOPE:Confidentiality:TECHNICAL IMPACT:Bypass Protection Mechanism Read Application Data:NOTE:Access Control Confidentiality Bypass Protection Mechanism Read Application Data An attacker may be able to decrypt the data using brute force attacks.::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Use a cryptographic algorithm that is currently considered to be strong by experts in the field.::\n::REFERENCE:CVE-2001-1546:DESCRIPTION:Weak encryption:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2001-1546REFERENCE:CVE-2004-2172:DESCRIPTION:Weak encryption (chosen plaintext attack):LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2004-2172REFERENCE:CVE-2002-1682:DESCRIPTION:Weak encryption:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1682REFERENCE:CVE-2002-1697:DESCRIPTION:Weak encryption produces same ciphertext from the same plaintext blocks.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1697REFERENCE:CVE-2002-1739:DESCRIPTION:Weak encryption:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1739REFERENCE:CVE-2005-2281:DESCRIPTION:Weak encryption scheme:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-2281REFERENCE:CVE-2002-1872:DESCRIPTION:Weak encryption (XOR):LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1872REFERENCE:CVE-2002-1910:DESCRIPTION:Weak encryption (reversible algorithm).:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1910REFERENCE:CVE-2002-1946:DESCRIPTION:Weak encryption (one-to-one mapping).:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1946REFERENCE:CVE-2002-1975:DESCRIPTION:Encryption error uses fixed salt, simplifying brute force / dictionary attacks (overlaps randomness).:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1975\nTAXONOMY NAME:PLOVER:ENTRY NAME:Weak Encryption::::TAXONOMY NAME:OWASP Top Ten 2007:ENTRY ID:A8:ENTRY NAME:Insecure Cryptographic Storage:MAPPING FIT:CWE More Specific::::TAXONOMY NAME:OWASP Top Ten 2007:ENTRY ID:A9:ENTRY NAME:Insecure Communications:MAPPING FIT:CWE More Specific::::TAXONOMY NAME:OWASP Top Ten 2004:ENTRY ID:A8:ENTRY NAME:Insecure Storage:MAPPING FIT:CWE More Specific::\n::112::20::\nTYPE:Maintenance:NOTE:A variety of encryption algorithms exist, with various weaknesses. This category could probably be split into smaller sub-categories.::::TYPE:Maintenance:NOTE:Relationships between CWE-310, CWE-326, and CWE-327 and all their children need to be reviewed and reorganized.::")); this.cweList.put( 760, new CWE( 760, "Use of a One-Way Hash with a Predictable Salt", "Base", "Incomplete", "The software uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the software uses a predictable salt as part of the input.\nThis makes it easier for attackers to pre-compute the hash value using dictionary attack techniques such as rainbow tables, effectively disabling the protection that an unpredictable salt would provide. It should be noted that, despite common perceptions, the use of a good salt with a hash does not sufficiently increase the effort for an attacker who is targeting an individual password, or who has a large amount of computing resources available, such as with cloud-based services or specialized, inexpensive hardware. Offline password cracking can still be effective if the hash function is not expensive to compute; many cryptographic functions are designed to be efficient and can be vulnerable to attacks using massive computing resources, even if the hash is cryptographically strong. The use of a salt only slightly increases the computing requirements for an attacker compared to other strategies such as adaptive hash functions. See CWE-916 for more details.\n::NATURE:ChildOf:CWE ID:916:VIEW ID:699:ORDINAL:Primary::NATURE:ChildOf:CWE ID:916:VIEW ID:1000:ORDINAL:Primary::\n::In cryptography, salt refers to some random addition of data to an input before hashing to make dictionary attacks more difficult.::\n:::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Bypass Protection Mechanism::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS:High:DESCRIPTION:Use an adaptive hash function that can be configured to change the amount of computational effort needed to compute the hash, such as the number of iterations (stretching) or the amount of memory required. Some hash functions perform salting automatically. These functions can significantly increase the overhead for a brute force attack compared to intentionally-fast functions such as MD5. For example, rainbow table attacks can become infeasible due to the high computing overhead. Finally, since computing power gets faster and cheaper over time, the technique can be reconfigured to increase the workload without forcing an entire replacement of the algorithm in use. Some hash functions that have one or more of these desired properties include bcrypt [REF-291], scrypt [REF-292], and PBKDF2 [REF-293]. While there is active debate about which of these is the most effective, they are all stronger than using salts with hash functions with very little computing overhead. Note that using these functions can have an impact on performance, so they require special consideration to avoid denial-of-service attacks. However, their configurability provides finer control over how much CPU and memory is used, so it could be adjusted to suit the environment's needs.::PHASE:Implementation:STRATEGY::EFFECTIVENESS:Limited:DESCRIPTION:If a technique that requires extra computational effort can not be implemented, then for each password that is processed, generate a new random salt using a strong random number generator with unpredictable seeds. Add the salt to the plaintext password before hashing it. When storing the hash, also store the salt. Do not use the same salt for every password.::\n::REFERENCE:CVE-2008-4905:DESCRIPTION:Blogging software uses a hard-coded salt when calculating a password hash.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-4905REFERENCE:CVE-2002-1657:DESCRIPTION:Database server uses the username for a salt when encrypting passwords, simplifying brute force attacks.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1657REFERENCE:CVE-2001-0967:DESCRIPTION:Server uses a constant salt when encrypting passwords, simplifying brute force attacks.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2001-0967REFERENCE:CVE-2005-0408:DESCRIPTION:chain: product generates predictable MD5 hashes using a constant value combined with username, allowing authentication bypass.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-0408")); this.cweList.put( 338, new CWE( 338, "Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)", "Base", "Draft", "The product uses a Pseudo-Random Number Generator (PRNG) in a security context, but the PRNG's algorithm is not cryptographically strong.\nWhen a non-cryptographic PRNG is used in a cryptographic context, it can expose the cryptography to certain types of attacks. Often a pseudo-random number generator (PRNG) is not designed for cryptography. Sometimes a mediocre source of randomness is sufficient or preferable for algorithms that use random numbers. Weak generators generally take less processing power and/or do not use the precious, finite, entropy sources on a system. While such PRNGs might have very useful features, these same features could be used to break the cryptography.\n::NATURE:ChildOf:CWE ID:330:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:330:VIEW ID:699:ORDINAL:Primary::NATURE:ChildOf:CWE ID:330:VIEW ID:1003:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Bypass Protection Mechanism:NOTE:Access Control Bypass Protection Mechanism If a PRNG is used for authentication and authorization, such as a session ID or a seed for generating a cryptographic key, then an attacker may be able to easily guess the ID or cryptographic key and gain access to restricted functionality.::\n::PHASE:Implementation:STRATEGY::EFFECTIVENESS::DESCRIPTION:Use functions or hardware which use a hardware-based random number generation for all crypto. This is the recommended solution. Use CyptGenRandom on Windows, or hw_rand() on Linux.::\n::REFERENCE:CVE-2009-3278:DESCRIPTION:Crypto product uses rand() library function to generate a recovery key, making it easier to conduct brute force attacks.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3278REFERENCE:CVE-2009-3238:DESCRIPTION:Random number generator can repeatedly generate the same value.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3238REFERENCE:CVE-2009-2367:DESCRIPTION:Web application generates predictable session IDs, allowing session hijacking.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-2367REFERENCE:CVE-2008-0166:DESCRIPTION:SSL library uses a weak random number generator that only generates 65,536 unique keys.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-0166\nTAXONOMY NAME:CLASP:ENTRY NAME:Non-cryptographic PRNG::::TAXONOMY NAME:CERT C Secure Coding:ENTRY ID:MSC30-C:ENTRY NAME:Do not use the rand() function for generating pseudorandom numbers:MAPPING FIT:CWE More Abstract::")); this.cweList.put( 297, new CWE( 297, "Improper Validation of Certificate with Host Mismatch", "Variant", "Incomplete", "The software communicates with a host that provides a certificate, but the software does not properly ensure that the certificate is actually associated with that host.\nEven if a certificate is well-formed, signed, and follows the chain of trust, it may simply be a valid certificate for a different site than the site that the software is interacting with. If the certificate's host-specific data is not properly checked - such as the Common Name (CN) in the Subject or the Subject Alternative Name (SAN) extension of an X.509 certificate - it may be possible for a redirection or spoofing attack to allow a malicious host with a valid certificate to provide data, impersonating a trusted host. In order to ensure data integrity, the certificate must be valid and it must pertain to the site that is being accessed. Even if the software attempts to check the hostname, it is still possible to incorrectly check the hostname. For example, attackers could create a certificate with a name that begins with a trusted name followed by a NUL byte, which could cause some string-based comparisons to only examine the portion that contains the trusted name. This weakness can occur even when the software uses Certificate Pinning, if the software does not verify the hostname at the time a certificate is pinned.\n::NATURE:ChildOf:CWE ID:295:VIEW ID:1000::NATURE:ChildOf:CWE ID:295:VIEW ID:699:ORDINAL:Primary::NATURE:ChildOf:CWE ID:295:VIEW ID:1003:ORDINAL:Primary::NATURE:ChildOf:CWE ID:923:VIEW ID:1000:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::PARADIGN NAME:Mobile:PARADIGN PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Gain Privileges or Assume Identity:NOTE:Access Control Gain Privileges or Assume Identity The data read from the system vouched for by the certificate may not be from the expected system.::SCOPE:Authentication:SCOPE:Other:TECHNICAL IMPACT:Other:NOTE:Authentication Other Other Trust afforded to the system in question - based on the malicious certificate - may allow for spoofing or redirection attacks.::\n::METHOD:Dynamic Analysis with Manual Results Interpretation:EFFECTIVENESS::DESCRIPTION:Set up an untrusted endpoint (e.g. a server) with which the software will connect. Create a test certificate that uses an invalid hostname but is signed by a trusted CA and provide this certificate from the untrusted endpoint. If the software performs any operations instead of disconnecting and reporting an error, then this indicates that the hostname is not being checked and the test certificate has been accepted.::METHOD:Black Box:EFFECTIVENESS::DESCRIPTION:When Certificate Pinning is being used in a mobile application, consider using a tool such as Spinner [REF-955]. This methodology might be extensible to other technologies.::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Fully check the hostname of the certificate and provide the user with adequate information about the nature of the problem and how to proceed.::PHASE:Implementation:STRATEGY::EFFECTIVENESS::DESCRIPTION:If certificate pinning is being used, ensure that all relevant properties of the certificate are fully validated before the certificate is pinned, including the hostname.::\n::REFERENCE:CVE-2012-5810:DESCRIPTION:Mobile banking application does not verify hostname, leading to financial loss.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5810REFERENCE:CVE-2012-5811:DESCRIPTION:Mobile application for printing documents does not verify hostname, allowing attackers to read sensitive documents.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5811REFERENCE:CVE-2012-5807:DESCRIPTION:Software for electronic checking does not verify hostname, leading to financial loss.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5807REFERENCE:CVE-2012-3446:DESCRIPTION:Cloud-support library written in Python uses incorrect regular expression when matching hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-3446REFERENCE:CVE-2009-2408:DESCRIPTION:Web browser does not correctly handle '0' character (NUL) in Common Name, allowing spoofing of https sites.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-2408REFERENCE:CVE-2012-0867:DESCRIPTION:Database program truncates the Common Name during hostname verification, allowing spoofing.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-0867REFERENCE:CVE-2010-2074:DESCRIPTION:Incorrect handling of '0' character (NUL) in hostname verification allows spoofing.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2010-2074REFERENCE:CVE-2009-4565:DESCRIPTION:Mail server's incorrect handling of '0' character (NUL) in hostname verification allows spoofing.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-4565REFERENCE:CVE-2009-3767:DESCRIPTION:LDAP server's incorrect handling of '0' character (NUL) in hostname verification allows spoofing.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3767REFERENCE:CVE-2012-5806:DESCRIPTION:Payment processing module does not verify hostname when connecting to PayPal using PHP fsockopen function.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5806REFERENCE:CVE-2012-2993:DESCRIPTION:Smartphone device does not verify hostname, allowing spoofing of mail services.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-2993REFERENCE:CVE-2012-5804:DESCRIPTION:E-commerce module does not verify hostname when connecting to payment site.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5804REFERENCE:CVE-2012-5824:DESCRIPTION:Chat application does not validate hostname, leading to loss of privacy.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5824REFERENCE:CVE-2012-5822:DESCRIPTION:Application uses third-party library that does not validate hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5822REFERENCE:CVE-2012-5819:DESCRIPTION:Cloud storage management application does not validate hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5819REFERENCE:CVE-2012-5817:DESCRIPTION:Java library uses JSSE SSLSocket and SSLEngine classes, which do not verify the hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5817REFERENCE:CVE-2012-5784:DESCRIPTION:SOAP platform does not verify the hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5784REFERENCE:CVE-2012-5782:DESCRIPTION:PHP library for payments does not verify the hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5782REFERENCE:CVE-2012-5780:DESCRIPTION:Merchant SDK for payments does not verify the hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5780REFERENCE:CVE-2003-0355:DESCRIPTION:Web browser does not validate Common Name, allowing spoofing of https sites.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2003-0355\nTAXONOMY NAME:CLASP:ENTRY NAME:Failure to validate host-specific certificate data::")); } /** * The lookup for the CWE * * <p>CWE_Lookup({@link java.lang.Integer}) * * @param cweId {@link java.lang.Integer} * @return a {@link CWE_Reader.CWE} object. */ public CWE CWE_Lookup(Integer cweId) { if (this.getCweList().containsKey(cweId)) return this.cweList.get(cweId); else return this.cweList.get(-1); } /** * Getter for the field <code>cweVersion</code>. * * @return a {@link java.lang.Double} object. */ public Double getCweVersion() { return this.cweVersion; } //endregion }
CryptoGuardOSS/cryptoguard
src/main/java/CWE_Reader/CWEList.java
249,357
package model; import java.io.Serializable; import java.util.Queue; import java.util.PriorityQueue; /** * Represents the Highscores game object used to store and provide the highscores */ public class HighScores implements Serializable { /** * generated serial version ID */ private static final long serialVersionUID = -8510255117516896366L; private Queue<ScoreEntry> easyScores; private Queue<ScoreEntry> medScores; private Queue<ScoreEntry> expertScores; /** * Main constructor */ public HighScores() { easyScores = new PriorityQueue<>(); // Add 5 dummy scores easyScores.add(new ScoreEntry("JEFF", 999)); easyScores.add(new ScoreEntry("ABEL", 999)); easyScores.add(new ScoreEntry("MARK", 999)); easyScores.add(new ScoreEntry("JOEY", 999)); easyScores.add(new ScoreEntry("KADE", 999)); medScores = new PriorityQueue<>(); // Add 5 dummy scores medScores.add(new ScoreEntry("JEFF", 999)); medScores.add(new ScoreEntry("ABEL", 999)); medScores.add(new ScoreEntry("MARK", 999)); medScores.add(new ScoreEntry("JOEY", 999)); medScores.add(new ScoreEntry("KADE", 999)); expertScores = new PriorityQueue<>(); // Add 5 dummy scores expertScores.add(new ScoreEntry("JEFF", 999)); expertScores.add(new ScoreEntry("ABEL", 999)); expertScores.add(new ScoreEntry("MARK", 999)); expertScores.add(new ScoreEntry("JOEY", 999)); expertScores.add(new ScoreEntry("KADE", 999)); } /** * Adds a score entry to the priority queue * * @param name * @param score * @param difficulty */ public void addScore(String name, int score, int difficulty) { if (difficulty == Difficulty.EASY) easyScores.add(new ScoreEntry(name, score)); else if (difficulty == Difficulty.MEDIUM) medScores.add(new ScoreEntry(name, score)); else if (difficulty == Difficulty.EXPERT) expertScores.add(new ScoreEntry(name, score)); } /** * Returns an array of the scores * * @return array of scores */ public ScoreEntry[] getScores(int difficulty) { Queue<ScoreEntry> scores; if (difficulty == Difficulty.EASY) scores = easyScores; else if (difficulty == Difficulty.MEDIUM) scores = medScores; else scores = expertScores; ScoreEntry[] retval = new ScoreEntry[5]; // Take off the top 5 scores for (int i = 0; i < 5; i++) { retval[i] = scores.poll(); } // Put them back because we polled them for (ScoreEntry e : retval) { scores.add(e); } return retval; } /** * The data type used to represent the score and name pairs within the Highscores priority queue */ public class ScoreEntry implements Comparable, Serializable { // FIXME: parameterize with a generic type /** * generated serial version ID */ private static final long serialVersionUID = -1640787370787311993L; public String name; public Integer score; /** * Default constructor * @param name * @param score */ public ScoreEntry(String name, int score) { this.name = name; this.score = score; } /** * used to compare ScoreEntry objects in the priority queue * @param o * @return */ @Override public int compareTo(Object o) { return -(((ScoreEntry) o).score - this.score); // we want to order based on least amount of time taken } } }
CSC335-Spring-2021/csc-335-minesweeper-csc335-bindra-colby-gothi-kantarges
src/model/HighScores.java
249,358
/* java.beans.FeatureDescriptor Copyright (C) 1998 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. As a special exception, if you link this library with other files to produce an executable, this library does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ package java.beans; import java.util.*; /** ** FeatureDescriptor is the common superclass for all JavaBeans Descriptor classes. ** JavaBeans descriptors are abstract descriptors of properties, ** events, methods, beans, etc.<P> ** ** <STRONG>Documentation Convention:</STRONG> for proper ** Internalization of Beans inside an RAD tool, sometimes there ** are two names for a property or method: a programmatic, or ** locale-independent name, which can be used anywhere, and a ** localized, display name, for ease of use. In the ** documentation I will specify different String values as ** either <EM>programmatic</EM> or <EM>localized</EM> to ** make this distinction clear. ** ** @author John Keiser ** @since JDK1.1 ** @version 1.1.0, 31 May 1998 **/ public class FeatureDescriptor { String name; String displayName; String shortDescription; boolean expert; boolean hidden; Hashtable valueHash; /** Instantiate this FeatureDescriptor with appropriate default values.**/ public FeatureDescriptor() { valueHash = new Hashtable(); } /** Get the programmatic name of this feature. **/ public String getName() { return name; } /** Set the programmatic name of this feature. ** @param name the new name for this feature. **/ public void setName(String name) { this.name = name; } /** Get the localized (display) name of this feature. **/ public String getDisplayName() { return displayName; } /** Set the localized (display) name of this feature. ** @param displayName the new display name for this feature. **/ public void setDisplayName(String displayName) { this.displayName = displayName; } /** Get the localized short description for this feature. **/ public String getShortDescription() { return shortDescription; } /** Set the localized short description for this feature. ** @param shortDescription the new short description for this feature. **/ public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } /** Indicates whether this feature is for expert use only. ** @return true if for use by experts only, or false if anyone can use it. **/ public boolean isExpert() { return expert; } /** Set whether this feature is for expert use only. ** @param expert true if for use by experts only, or false if anyone can use it. **/ public void setExpert(boolean expert) { this.expert = expert; } /** Indicates whether this feature is for use by tools only. ** If it is for use by tools only, then it should not be displayed. ** @return true if tools only should use it, or false if anyone can see it. **/ public boolean isHidden() { return hidden; } /** Set whether this feature is for use by tools only. ** If it is for use by tools only, then it should not be displayed. ** @param hidden true if tools only should use it, or false if anyone can see it. **/ public void setHidden(boolean hidden) { this.hidden = hidden; } /** Get an arbitrary value set with setValue(). ** @param name the programmatic name of the key. ** @return the value associated with this name, or null if there is none. **/ public Object getValue(String name) { return valueHash.get(name); } /** Set an arbitrary string-value pair with this feature. ** @param name the programmatic name of the key. ** @param value the value to associate with the name. **/ public void setValue(String name, Object value) { valueHash.put(name, value); } /** Get a list of the programmatic key names set with setValue(). ** @return an Enumerator over all the programmatic key names associated ** with this feature. **/ public Enumeration attributeNames() { return valueHash.keys(); } }
mczero80/jx
libs/jdk_beans/java/beans/FeatureDescriptor.java
249,359
package bestpractice; // More computing sins are committed in the name of efficiency (without neces- // sarily achieving it) than for any other single reason—including blind stupidity. // —William A. Wulf // We should forget about small efficiencies, say about 97% of the time: prema- // ture optimization is the root of all evil. // —Donald E. Knuth // We follow two rules in the matter of optimization: // Rule 1. Don’t do it. // Rule 2 (for experts only). Don’t do it yet—that is, not until you have a // perfectly clear and unoptimized solution. // —M. A. Jackson //write good programs rather than fast ones //measure performance before and after each attempted optimization public class DontOptimize { }
hacker85/JavaLessons
src/bestpractice/DontOptimize.java
249,360
/* * =========================================== * Java Pdf Extraction Decoding Access Library * =========================================== * * Project Info: http://www.idrsolutions.com * Help section for developers at http://www.idrsolutions.com/java-pdf-library-support/ * * (C) Copyright 1997-2013, IDRsolutions and Contributors. * * This file is part of JPedal * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * --------------- * Type1C.java * --------------- */ package org.jpedal.fonts; import java.io.*; import java.util.ArrayList; import java.util.Map; import java.awt.*; import org.jpedal.fonts.glyph.T1Glyphs; import org.jpedal.fonts.glyph.PdfJavaGlyphs; import org.jpedal.fonts.objects.FontData; import org.jpedal.io.PdfObjectReader; import org.jpedal.io.ObjectStore; import org.jpedal.utils.LogWriter; import org.jpedal.objects.raw.PdfObject; import org.jpedal.objects.raw.PdfDictionary; /** * handlestype1 specifics */ public class Type1C extends Type1{ static final boolean debugFont=false; static final boolean debugDictionary=false; int ros=-1,CIDFontVersion=0,CIDFontRevision=0,CIDFontType=0,CIDcount=0,UIDBase=-1,FDArray=-1,FDSelect=-1; final static String[] OneByteCCFDict={"version","Notice","FullName","FamilyName","Weight", "FontBBox","BlueValues","OtherBlues","FamilyBlues","FamilyOtherBlues", "StdHW","StdVW","Escape","UniqueID","XUID", "charset","Encoding","CharStrings","Private", "Subrs", "defaultWidthX","nominalWidthX","-reserved-","-reserved-","-reserved-", "-reserved-","-reserved-","-reserved-","shortint","longint", "BCD","-reserved-"}; final static String[] TwoByteCCFDict={"Copyright","isFixedPitch","ItalicAngle","UnderlinePosition","UnderlineThickness", "PaintType","CharstringType","FontMatrix","StrokeWidth","BlueScale", "BlueShift","BlueFuzz","StemSnapH","StemSnapV","ForceBold", "-reserved-","-reserved-","LanguageGroup","ExpansionFactor","initialRandomSeed", "SyntheticBase","PostScript","BaseFontName","BaseFontBlend","-reserved-", "-reserved-","-reserved-","-reserved-","-reserved-","-reserved-", "ROS","CIDFontVersion","CIDFontRevision","CIDFontType","CIDCount", "UIDBase","FDArray","FDSelect","FontName"}; //current location in file private int top = 0; private int charset = 0; private int enc = 0; private int charstrings = 0; private int stringIdx; private int stringStart; private int stringOffSize; private Rectangle BBox=null; private boolean hasFontMatrix=false;// hasFontBBox=false,; private int[] privateDict = {-1},privateDictOffset={-1}; private int currentFD=-1; private int[] defaultWidthX = {0}, nominalWidthX = {0}, fdSelect; /** decoding table for Expert */ private static final int ExpertSubCharset[] = { // 87 // elements 0, 1, 231, 232, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 272, 300, 301, 302, 305, 314, 315, 158, 155, 163, 320, 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346 }; /** lookup table for names for type 1C glyphs */ public static final String type1CStdStrings[] = { // 391 // elements ".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "exclamdown", "cent", "sterling", "fraction", "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", "endash", "dagger", "daggerdbl", "periodcentered", "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", "ellipsis", "perthousand", "questiondown", "grave", "acute", "circumflex", "tilde", "macron", "breve", "dotaccent", "dieresis", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "emdash", "AE", "ordfeminine", "Lslash", "Oslash", "OE", "ordmasculine", "ae", "dotlessi", "lslash", "oslash", "oe", "germandbls", "onesuperior", "logicalnot", "mu", "trademark", "Eth", "onehalf", "plusminus", "Thorn", "onequarter", "divide", "brokenbar", "degree", "thorn", "threequarters", "twosuperior", "registered", "minus", "eth", "multiply", "threesuperior", "copyright", "Aacute", "Acircumflex", "Adieresis", "Agrave", "Aring", "Atilde", "Ccedilla", "Eacute", "Ecircumflex", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis", "Ograve", "Otilde", "Scaron", "Uacute", "Ucircumflex", "Udieresis", "Ugrave", "Yacute", "Ydieresis", "Zcaron", "aacute", "acircumflex", "adieresis", "agrave", "aring", "atilde", "ccedilla", "eacute", "ecircumflex", "edieresis", "egrave", "iacute", "icircumflex", "idieresis", "igrave", "ntilde", "oacute", "ocircumflex", "odieresis", "ograve", "otilde", "scaron", "uacute", "ucircumflex", "udieresis", "ugrave", "yacute", "ydieresis", "zcaron", "exclamsmall", "Hungarumlautsmall", "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "zerooldstyle", "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "commasuperior", "threequartersemdash", "periodsuperior", "questionsmall", "asuperior", "bsuperior", "centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior", "msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior", "tsuperior", "ff", "ffi", "ffl", "parenleftinferior", "parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall", "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", "Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall", "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", "colonmonetary", "onefitted", "rupiah", "Tildesmall", "exclamdownsmall", "centoldstyle", "Lslashsmall", "Scaronsmall", "Zcaronsmall", "Dieresissmall", "Brevesmall", "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash", "hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall", "questiondownsmall", "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "zerosuperior", "foursuperior", "fivesuperior", "sixsuperior", "sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", "threeinferior", "fourinferior", "fiveinferior", "sixinferior", "seveninferior", "eightinferior", "nineinferior", "centinferior", "dollarinferior", "periodinferior", "commainferior", "Agravesmall", "Aacutesmall", "Acircumflexsmall", "Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall", "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall", "Odieresissmall", "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall", "001.000", "001.001", "001.002", "001.003", "Black", "Bold", "Book", "Light", "Medium", "Regular", "Roman", "Semibold" }; /** Lookup table to map values */ private static final int ISOAdobeCharset[] = { // 229 // elements 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228 }; /** lookup data to convert Expert values */ private static final int ExpertCharset[] = { // 166 // elements 0, 1, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 158, 155, 163, 319, 320, 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378 }; //one byte operators public final static int VERSION = 0 ; public final static int NOTICE = 1 ; public final static int FULLNAME = 2 ; public final static int FAMILYNAME = 3 ; public final static int WEIGHT = 4 ; public final static int FONTBBOX = 5 ; public final static int BLUEVALUES = 6 ; public final static int OTHERBLUES = 7 ; public final static int FAMILYBLUES = 8 ; public final static int FAMILYOTHERBLUES = 9 ; public final static int STDHW = 10 ; public final static int STDVW = 11 ; public final static int ESCAPE = 12 ; public final static int UNIQUEID = 13 ; public final static int XUID = 14 ; public final static int CHARSET = 15 ; public final static int ENCODING = 16 ; public final static int CHARSTRINGS = 17 ; public final static int PRIVATE = 18 ; public final static int SUBRS = 19 ; public final static int DEFAULTWIDTHX = 20 ; public final static int NOMINALWIDTHX = 21 ; public final static int RESERVED = 22 ; public final static int SHORTINT = 28 ; public final static int LONGINT = 29 ; public final static int BCD = 30 ; //two byte operators public final static int COPYRIGHT = 3072 ; public final static int ISFIXEDPITCH = 3073 ; public final static int ITALICANGLE = 3074 ; public final static int UNDERLINEPOSITION = 3075 ; public final static int UNDERLINETHICKNESS = 3076 ; public final static int PAINTTYPE = 3077 ; public final static int CHARSTRINGTYPE = 3078 ; public final static int FONTMATRIX = 3079 ; public final static int STROKEWIDTH = 3080 ; public final static int BLUESCALE = 3081 ; public final static int BLUESHIFT = 3082 ; public final static int BLUEFUZZ = 3083 ; public final static int STEMSNAPH = 3084 ; public final static int STEMSNAPV = 3085 ; public final static int FORCEBOLD = 3086 ; public final static int LANGUAGEGROUP = 3089 ; public final static int EXPANSIONFACTOR = 3090 ; public final static int INITIALRANDOMSEED = 3091 ; public final static int SYNTHETICBASE = 3092 ; public final static int POSTSCRIPT = 3093 ; public final static int BASEFONTNAME = 3094 ; public final static int BASEFONTBLEND = 3095 ; public final static int ROS = 3102 ; public final static int CIDFONTVERSION = 3103 ; public final static int CIDFONTREVISION = 3104 ; public final static int CIDFONTTYPE = 3105 ; public final static int CIDCOUNT = 3106 ; public final static int UIDBASE = 3107 ; public final static int FDARRAY = 3108 ; public final static int FDSELECT = 3109 ; public final static int FONTNAME = 3110 ; private int weight = 388;//make it default private int[] blueValues = null; private int[] otherBlues = null; private int[] familyBlues = null; private int[] familyOtherBlues = null; private int stdHW = -1, stdVW = -1, subrs = -1; private byte[] encodingDataBytes = null; private String[] stringIndexData = null; private int[] charsetGlyphCodes = null; private int charsetGlyphFormat = 0 ; private int[] rosArray = new int[3]; /** needed so CIDFOnt0 can extend */ public Type1C() {} /** get handles onto Reader so we can access the file */ public Type1C(PdfObjectReader current_pdf_file,String substituteFont) { glyphs=new T1Glyphs(false); init(current_pdf_file); this.substituteFont=substituteFont; } /** read details of any embedded fontFile */ protected void readEmbeddedFont(PdfObject pdfFontDescriptor) throws Exception { if(substituteFont!=null){ byte[] bytes ; //read details BufferedInputStream from; //create streams ByteArrayOutputStream to = new ByteArrayOutputStream(); InputStream jarFile = null; try{ if(substituteFont.startsWith("jar:")|| substituteFont.startsWith("http:")) jarFile = loader.getResourceAsStream(substituteFont); else jarFile = loader.getResourceAsStream("file:///"+substituteFont); }catch(Exception e){ if(LogWriter.isOutput()) LogWriter.writeLog("3.Unable to open "+substituteFont); }catch(Error err){ if(LogWriter.isOutput()) LogWriter.writeLog("3.Unable to open "+substituteFont); } if(jarFile==null){ /** from=new BufferedInputStream(new FileInputStream(substituteFont)); //write byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); to.close(); from.close(); /**/ File file=new File(substituteFont); InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { System.out.println("Sorry! Your given file is too large."); return; } bytes = new byte[(int)length]; int offset = 0; int numRead ; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } is.close(); // new BufferedReader // (new InputStreamReader(loader.getResourceAsStream("org/jpedal/res/cid/" + encodingName), "Cp1252")); /** FileReader from2=null; try { from2 = new FileReader(substituteFont); //new BufferedReader); //outputStream = new FileWriter("characteroutput.txt"); int c; while ((c = from2.read()) != -1) { to.write(c); } } finally { if (from2 != null) { from2.close(); } if (to != null) { to.close(); } }/**/ }else{ from= new BufferedInputStream(jarFile); //write byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); to.close(); from.close(); bytes=to.toByteArray(); } /**load the font*/ try{ isFontSubstituted=true; //if (substituteFont.indexOf(".afm") != -1) readType1FontFile(bytes); //else // readType1CFontFile(to.toByteArray(),null); } catch (Exception e) { e.printStackTrace(System.out); if(LogWriter.isOutput()) LogWriter.writeLog("[PDF]Substitute font="+substituteFont+"Type 1 exception=" + e); } //over-ride font remapping if substituted if(isFontSubstituted && glyphs.remapFont) glyphs.remapFont=false; }else if(pdfFontDescriptor!=null){ PdfObject FontFile=pdfFontDescriptor.getDictionary(PdfDictionary.FontFile); /** try type 1 first then type 1c/0c */ if (FontFile != null) { try { byte[] stream=currentPdfFile.readStream(FontFile,true,true,false, false,false, FontFile.getCacheName(currentPdfFile.getObjectReader())); if(stream!=null) readType1FontFile(stream); } catch (Exception e) { //tell user and log if(LogWriter.isOutput()) LogWriter.writeLog("Exception: "+e.getMessage()); } }else{ PdfObject FontFile3=pdfFontDescriptor.getDictionary(PdfDictionary.FontFile3); if(FontFile3!=null){ byte[] stream=currentPdfFile.readStream(FontFile3,true,true,false, false,false, FontFile3.getCacheName(currentPdfFile.getObjectReader())); if(stream!=null){ //if it fails, null returned //check for type1c or ottf if(stream.length>3 && stream[0]==719 && stream[1]==84 && stream[2]==84 && stream[3]==79){ }else //assume all standard cff for moment readType1CFontFile(stream,null); } } } } } /** read in a font and its details from the pdf file */ public void createFont( PdfObject pdfObject, String fontID, boolean renderPage, ObjectStore objectStore, Map substitutedFonts) throws Exception { fontTypes = StandardFonts.TYPE1; //generic setup init(fontID, renderPage); /** * get FontDescriptor object - if present contains metrics on glyphs */ PdfObject pdfFontDescriptor=pdfObject.getDictionary(PdfDictionary.FontDescriptor); //FontBBox and FontMatix setBoundsAndMatrix(pdfFontDescriptor); setName(pdfObject, fontID); setEncoding(pdfObject, pdfFontDescriptor); try{ readEmbeddedFont(pdfFontDescriptor); }catch(Exception e){ //tell user and log if(LogWriter.isOutput()) LogWriter.writeLog("Exception: "+e.getMessage()); } //setWidths(pdfObject); readWidths(pdfObject,true); // if(embeddedFontName!=null && is1C() && PdfStreamDecoder.runningStoryPad){ // embeddedFontName= cleanupFontName(embeddedFontName); // this.setBaseFontName(embeddedFontName); // this.setFontName(embeddedFontName); // } //make sure a font set if (renderPage) setFont(getBaseFontName(), 1); } /** Constructor for html fonts */ public Type1C(byte[] fontDataAsArray,PdfJavaGlyphs glyphs, boolean is1C) throws Exception{ this.glyphs=glyphs; //generate reverse lookup so we can encode CMAP this.trackIndices=true; //flags we extract all details (used originally by rendering and now by PS2OTF) this.renderPage=true; if(is1C) readType1CFontFile(fontDataAsArray,null); else readType1FontFile(fontDataAsArray); } /** Constructor for OTF fonts */ public Type1C(byte[] fontDataAsArray,FontData fontData, PdfJavaGlyphs glyphs) throws Exception{ this.glyphs=glyphs; readType1CFontFile(fontDataAsArray,fontData); } /** Handle encoding for type1C fonts. Also used for CIDFontType0C */ final private void readType1CFontFile(byte[] fontDataAsArray,FontData fontDataAsObject) throws Exception{ if(LogWriter.isOutput()) LogWriter.writeLog("Embedded Type1C font used"); glyphs.setis1C(true); boolean isByteArray=(fontDataAsArray!=null); //debugFont=getBaseFontName().indexOf("LC")!=-1; if(debugFont) System.err.println(getBaseFontName()); int start; //pointers within table int size=2; /** * read Header */ int major,minor; if(isByteArray){ major = fontDataAsArray[0]; minor = fontDataAsArray[1]; }else{ major = fontDataAsObject.getByte(0); minor = fontDataAsObject.getByte(1); } if ((major != 1 || minor != 0) && LogWriter.isOutput()) LogWriter.writeLog("1C format "+ major+ ':' + minor+ " not fully supported"); if(debugFont) System.out.println("major="+major+" minor="+minor); // read header size to workout start of names index if(isByteArray) top = fontDataAsArray[2]; else top = fontDataAsObject.getByte(2); /** * read names index */ // read name index for the first font int count,offsize; if(isByteArray){ count = getWord(fontDataAsArray, top, size); offsize = fontDataAsArray[top + size]; }else{ count = getWord(fontDataAsObject, top, size); offsize = fontDataAsObject.getByte(top + size); } /** * get last offset and use to move to top dict index */ top += (size+1); //move pointer to start of font names start = top + (count + 1) * offsize - 1; //move pointer to end of offsets if(isByteArray) top = start + getWord(fontDataAsArray, top + count * offsize, offsize); else top = start + getWord(fontDataAsObject, top + count * offsize, offsize); /** * read the dict index */ if(isByteArray){ count = getWord(fontDataAsArray, top, size); offsize = fontDataAsArray[top + size]; }else{ count = getWord(fontDataAsObject, top, size); offsize = fontDataAsObject.getByte(top + size); } top += (size+1); //update pointer start = top + (count + 1) * offsize - 1; int dicStart,dicEnd; if(isByteArray){ dicStart = start + getWord(fontDataAsArray, top, offsize); dicEnd = start + getWord(fontDataAsArray, top + offsize, offsize); }else{ dicStart = start + getWord(fontDataAsObject, top, offsize); dicEnd = start + getWord(fontDataAsObject, top + offsize, offsize); } /** * read string index */ String[] strings=readStringIndex(fontDataAsArray, fontDataAsObject, start, offsize, count); /** * read global subroutines (top set by Strings code) */ readGlobalSubRoutines(fontDataAsArray,fontDataAsObject); /** * decode the dictionary */ decodeDictionary(fontDataAsArray, fontDataAsObject, dicStart, dicEnd, strings); /** * allow for subdictionaries in CID font */ if(FDSelect!=-1 ){ if(debugDictionary) System.out.println("=============FDSelect===================="+getBaseFontName()); //Read FDSelect int nextDic = FDSelect; int format; if (isByteArray) { format = getWord(fontDataAsArray, nextDic, 1); } else { format = getWord(fontDataAsObject, nextDic, 1); } int glyphCount; if (isByteArray) { glyphCount = getWord(fontDataAsArray, charstrings, 2); } else { glyphCount = getWord(fontDataAsObject, charstrings, 2); } fdSelect = new int[glyphCount]; if (format == 0) { //Format 0 is just an array of which to use for each glyph for (int i=0; i<glyphCount; i++) { if (isByteArray) { fdSelect[i] = getWord(fontDataAsArray, nextDic + 1 + i, 1); } else { fdSelect[i] = getWord(fontDataAsObject, nextDic + 1 + i, 1); } } } else if (format == 3) { int nRanges; if (isByteArray) { nRanges = getWord(fontDataAsArray, nextDic+1, 2); } else { nRanges = getWord(fontDataAsObject, nextDic+1, 2); } int[] rangeStarts= new int[nRanges+1], fDicts = new int[nRanges]; //Find ranges of glyphs with their DICT index for (int i=0; i<nRanges; i++) { if (isByteArray) { rangeStarts[i] = getWord(fontDataAsArray, nextDic+3+(3*i), 2); fDicts[i] = getWord(fontDataAsArray, nextDic+5+(3*i), 1); } else { rangeStarts[i] = getWord(fontDataAsObject, nextDic+3+(3*i), 2); fDicts[i] = getWord(fontDataAsObject, nextDic+5+(3*i), 1); } } rangeStarts[rangeStarts.length-1] = glyphCount; //Fill fdSelect array for (int i=0; i<nRanges; i++) { for (int j=rangeStarts[i]; j<rangeStarts[i+1]; j++) { fdSelect[j] = fDicts[i]; } } } ((T1Glyphs)glyphs).setFDSelect(fdSelect); //Read FDArray nextDic=FDArray; if(isByteArray){ count = getWord(fontDataAsArray, nextDic, size); offsize = fontDataAsArray[nextDic + size]; }else{ count = getWord(fontDataAsObject, nextDic, size); offsize = fontDataAsObject.getByte(nextDic + size); } nextDic += (size+1); //update pointer start = nextDic + (count + 1) * offsize - 1; privateDict = new int[count]; privateDictOffset = new int[count]; defaultWidthX = new int[count]; nominalWidthX = new int[count]; for (int i=0; i<count; i++) { currentFD = i; privateDict[i] = -1; privateDictOffset[i] = -1; if(isByteArray){ dicStart = start+getWord(fontDataAsArray, nextDic+(i*offsize), offsize); dicEnd =start+getWord(fontDataAsArray, nextDic+((i+1)*offsize), offsize); }else{ dicStart = start+getWord(fontDataAsObject, nextDic+(i*offsize), offsize); dicEnd =start+getWord(fontDataAsObject, nextDic+((i+1)*offsize), offsize); } decodeDictionary(fontDataAsArray, fontDataAsObject, dicStart, dicEnd, strings); } currentFD = -1; if(debugDictionary) System.out.println("================================="+getBaseFontName()); } /** * get number of glyphs from charstrings index */ top = charstrings; int nGlyphs; if(isByteArray) nGlyphs = getWord(fontDataAsArray, top, size); //start of glyph index else nGlyphs = getWord(fontDataAsObject, top, size); //start of glyph index glyphs.setGlyphCount(nGlyphs); if(debugFont) System.out.println("nGlyphs="+nGlyphs); int[] names =readCharset(charset, nGlyphs, fontDataAsObject,fontDataAsArray); if(debugFont){ System.out.println("=======charset==============="); int count2=names.length; for(int jj=0;jj<count2;jj++){ System.out.println(jj+" "+names[jj]); } System.out.println("=======Encoding==============="); } /** * set encoding if not set */ setEncoding(fontDataAsArray, fontDataAsObject,nGlyphs,names); /** * read glyph index */ top = charstrings; readGlyphs(fontDataAsArray, fontDataAsObject, nGlyphs, names); /**/ for (int i=0; i<privateDict.length; i++) { currentFD = i; int dict = privateDict[i]; if(dict!=-1){ int dictOffset = privateDictOffset[i]; decodeDictionary(fontDataAsArray, fontDataAsObject, dict, dictOffset+dict, strings); top = dict + dictOffset; int len,nSubrs; if(isByteArray) len=fontDataAsArray.length; else len=fontDataAsObject.length(); if(top+2<len){ if(isByteArray) nSubrs = getWord(fontDataAsArray, top, size); else nSubrs = getWord(fontDataAsObject, top, size); if(nSubrs>0) readSubrs(fontDataAsArray, fontDataAsObject, nSubrs); }else if(debugFont || debugDictionary){ System.out.println("Private subroutine out of range"); } } } currentFD = -1; /**/ /** * set flags to tell software to use these descritpions */ isFontEmbedded = true; glyphs.setFontEmbedded(true); } /**pick up encoding from embedded font*/ final private void setEncoding(byte[] fontDataAsArray, FontData fontDataAsObject,int nGlyphs,int[] names){ boolean isByteArray=fontDataAsArray!=null; if(debugFont) System.out.println("Enc="+enc); // read encoding (glyph -> code mapping) if (enc == 0){ embeddedEnc=StandardFonts.STD; if (fontEnc == -1) putFontEncoding(StandardFonts.STD); if(isCID){ //store values for lookup on text try{ String name; for (int i = 1; i < nGlyphs; ++i) { if(names[i]<391){ if(isByteArray) name =getString(fontDataAsArray,names[i],stringIdx,stringStart,stringOffSize); else name =getString(fontDataAsObject,names[i],stringIdx,stringStart,stringOffSize); putMappedChar(names[i],StandardFonts.getUnicodeName(name) ); } } }catch(Exception e){ //tell user and log if(LogWriter.isOutput()) LogWriter.writeLog("Exception: "+e.getMessage()); } } }else if (enc == 1){ embeddedEnc=StandardFonts.MACEXPERT; if (fontEnc == -1) putFontEncoding(StandardFonts.MACEXPERT); }else { //custom mapping if(debugFont) System.out.println("custom mapping"); top = enc; int encFormat,c; if(isByteArray) encFormat = (fontDataAsArray[top++] & 0xff); else encFormat = (fontDataAsObject.getByte(top++) & 0xff); String name; if ((encFormat & 0x7f) == 0) { //format 0 int nCodes; if(isByteArray) nCodes = 1 + (fontDataAsArray[top++] & 0xff); else nCodes = 1 + (fontDataAsObject.getByte(top++) & 0xff); if (nCodes > nGlyphs) nCodes = nGlyphs; for (int i = 1; i < nCodes; ++i) { if(isByteArray){ c =fontDataAsArray[top++] & 0xff; name =getString(fontDataAsArray,names[i],stringIdx,stringStart,stringOffSize); }else{ c =fontDataAsObject.getByte(top++) & 0xff; name =getString(fontDataAsObject,names[i],stringIdx,stringStart,stringOffSize); } putChar(c, name); } } else if ((encFormat & 0x7f) == 1) { //format 1 int nRanges; if(isByteArray) nRanges = (fontDataAsArray[top++] & 0xff); else nRanges = (fontDataAsObject.getByte(top++) & 0xff); int nCodes = 1; for (int i = 0; i < nRanges; ++i) { int nLeft; if(isByteArray){ c = (fontDataAsArray[top++] & 0xff); nLeft = (fontDataAsArray[top++] & 0xff); }else{ c = (fontDataAsObject.getByte(top++) & 0xff); nLeft = (fontDataAsObject.getByte(top++) & 0xff); } for (int j = 0; j <= nLeft && nCodes < nGlyphs; ++j) { if(isByteArray) name =getString(fontDataAsArray,names[nCodes],stringIdx,stringStart,stringOffSize); else name =getString(fontDataAsObject,names[nCodes],stringIdx,stringStart,stringOffSize); putChar(c, name); nCodes++; c++; } } } if ((encFormat & 0x80) != 0) { //supplimentary encodings int nSups; if(isByteArray) nSups = (fontDataAsArray[top++] & 0xff); else nSups = (fontDataAsObject.getByte(top++) & 0xff); for (int i = 0; i < nSups; ++i) { if(isByteArray) c = (fontDataAsArray[top++] & 0xff); else c = (fontDataAsObject.getByte(top++) & 0xff); int sid; if(isByteArray) sid = getWord(fontDataAsArray, top, 2); else sid = getWord(fontDataAsObject, top, 2); top += 2; if(isByteArray) name =getString(fontDataAsArray,sid,stringIdx,stringStart,stringOffSize); else name =getString(fontDataAsObject,sid,stringIdx,stringStart,stringOffSize); putChar(c, name); } } } } // LILYPONDTOOL private final void readSubrs(byte[] fontDataAsArray, FontData fontDataAsObject, int nSubrs) throws Exception { boolean isByteArray=fontDataAsArray!=null; int subrOffSize; if(isByteArray) subrOffSize = fontDataAsArray[top+2]; else subrOffSize = fontDataAsObject.getByte(top+2); top+=3; int subrIdx = top; int subrStart = top + (nSubrs + 1) * subrOffSize - 1; int nextTablePtr= top+nSubrs*subrOffSize; if(isByteArray){ if(nextTablePtr<fontDataAsArray.length) //allow for table at end of file top = subrStart + getWord(fontDataAsArray,nextTablePtr, subrOffSize); else top=fontDataAsArray.length-1; }else{ if(nextTablePtr<fontDataAsArray.length) //allow for table at end of file top = subrStart + getWord(fontDataAsObject, nextTablePtr, subrOffSize); else top=fontDataAsObject.length()-1; } int[] subrOffset = new int [nSubrs + 2]; int ii = subrIdx; for (int jj = 0; jj<nSubrs+1; jj++) { if(isByteArray){ if((ii+subrOffSize)<fontDataAsArray.length) subrOffset[jj] = subrStart + getWord(fontDataAsArray, ii, subrOffSize); }else{ if((ii+subrOffSize)<fontDataAsObject.length()) subrOffset[jj] = subrStart + getWord(fontDataAsObject, ii, subrOffSize); } ii += subrOffSize; } subrOffset[nSubrs + 1] = top; glyphs.setLocalBias(calculateSubroutineBias(nSubrs)); //read the glyphs and store int current = subrOffset[0]; for (int jj = 1; jj < nSubrs+1; jj++) { //skip if out of bounds if(current==0 || subrOffset[jj]>fontDataAsArray.length || subrOffset[jj]<0 || subrOffset[jj]==0) continue; ByteArrayOutputStream nextSubr = new ByteArrayOutputStream(); for (int c = current; c < subrOffset[jj]; c++){ if(!isByteArray && c<fontDataAsObject.length()) nextSubr.write(fontDataAsObject.getByte(c)); } if(isByteArray){ int length=subrOffset[jj]-current; if(length>0){ byte[] nextSub=new byte[length]; System.arraycopy(fontDataAsArray,current,nextSub,0,length); glyphs.setCharString("subrs"+(jj-1),nextSub, jj); } }else{ nextSubr.close(); glyphs.setCharString("subrs"+(jj-1),nextSubr.toByteArray(), jj); } current = subrOffset[jj]; } } private final void readGlyphs(byte[] fontDataAsArray, FontData fontDataAsObject,int nGlyphs,int[] names) throws Exception{ boolean isByteArray=fontDataAsArray!=null; int glyphOffSize; if(isByteArray) glyphOffSize = fontDataAsArray[top + 2]; else glyphOffSize = fontDataAsObject.getByte(top + 2); top += 3; int glyphIdx = top; int glyphStart = top + (nGlyphs + 1) * glyphOffSize - 1; if(isByteArray) top =glyphStart+ getWord(fontDataAsArray,top + nGlyphs * glyphOffSize,glyphOffSize); else top =glyphStart+ getWord(fontDataAsObject,top + nGlyphs * glyphOffSize,glyphOffSize); int[] glyphoffset = new int[nGlyphs + 2]; int ii = glyphIdx; //read the offsets for (int jj = 0; jj < nGlyphs + 1; jj++) { if(isByteArray) glyphoffset[jj] = glyphStart+getWord(fontDataAsArray,ii,glyphOffSize); else glyphoffset[jj] = glyphStart+getWord(fontDataAsObject,ii,glyphOffSize); ii = ii + glyphOffSize; } glyphoffset[nGlyphs + 1] = top; //read the glyphs and store int current = glyphoffset[0]; String glyphName; byte[] nextGlyph; for (int jj = 1; jj < nGlyphs+1; jj++) { nextGlyph=new byte[glyphoffset[jj]-current]; //read name of glyph //get data for the glyph for (int c = current; c < glyphoffset[jj]; c++){ if(isByteArray) nextGlyph[c-current]=fontDataAsArray[c]; else nextGlyph[c-current]=fontDataAsObject.getByte(c); } if(isCID){ glyphName =String.valueOf(names[jj - 1]); }else{ if(isByteArray) glyphName =getString(fontDataAsArray,names[jj-1],stringIdx,stringStart,stringOffSize); else glyphName =getString(fontDataAsObject,names[jj-1],stringIdx,stringStart,stringOffSize); } if(debugFont) System.out.println("glyph= "+ glyphName +" start="+current+" length="+glyphoffset[jj]+" isCID="+isCID); glyphs.setCharString(glyphName,nextGlyph, jj); current = glyphoffset[jj]; if(trackIndices){ glyphs.setIndexForCharString(jj, glyphName); } } } private static final int calculateSubroutineBias(int subroutineCount) { int bias; if (subroutineCount < 1240) { bias = 107; } else if (subroutineCount < 33900) { bias = 1131; } else { bias = 32768; } return bias; } private final void readGlobalSubRoutines(byte[] fontDataAsArray, FontData fontDataAsObject) throws Exception{ boolean isByteArray=(fontDataAsArray!=null); int subOffSize,count; if(isByteArray){ subOffSize = (fontDataAsArray[top + 2] & 0xff); count= getWord(fontDataAsArray, top, 2); }else{ subOffSize = (fontDataAsObject.getByte(top + 2) & 0xff); count= getWord(fontDataAsObject, top, 2); } top += 3; if(count>0){ int idx = top; int start = top + (count + 1) * subOffSize - 1; if(isByteArray) top =start+ getWord(fontDataAsArray,top + count * subOffSize,subOffSize); else top =start+ getWord(fontDataAsObject,top + count * subOffSize,subOffSize); int[] offset = new int[count + 2]; int ii = idx; //read the offsets for (int jj = 0; jj < count + 1; jj++) { if(isByteArray) offset[jj] = start + getWord(fontDataAsArray,ii,subOffSize); else offset[jj] = start + getWord(fontDataAsObject,ii,subOffSize); ii = ii + subOffSize; } offset[count + 1] = top; glyphs.setGlobalBias(calculateSubroutineBias(count)); //read the subroutines and store int current = offset[0]; for (int jj = 1; jj < count+1; jj++) { ByteArrayOutputStream nextStream = new ByteArrayOutputStream(); for (int c = current; c < offset[jj]; c++){ if(isByteArray) nextStream.write(fontDataAsArray[c]); else nextStream.write(fontDataAsObject.getByte(c)); } nextStream.close(); //store glyphs.setCharString("global"+(jj-1),nextStream.toByteArray(), jj); //setGlobalSubroutine(new Integer(jj-1+bias),nextStream.toByteArray()); current = offset[jj]; } } } private void decodeDictionary(byte[] fontDataAsArray, FontData fontDataAsObject, int dicStart, int dicEnd, String[] strings){ boolean fdReset=false; if(debugDictionary) System.out.println("=============Read dictionary===================="+getBaseFontName()); boolean isByteArray=fontDataAsArray!=null; int p = dicStart, nextVal,key; int i=0; double[] op = new double[48]; //current operand in dictionary while (p < dicEnd) { if(isByteArray) nextVal = fontDataAsArray[p] & 0xFF; else nextVal = fontDataAsObject.getByte(p) & 0xFF; if (nextVal <= 27 || nextVal == 31) { // operator key = nextVal; p++; if(debugDictionary && key!=12) System.out.println(key +" (1) "+OneByteCCFDict[key]); if (key == 0x0c) { //handle escaped keys if(isByteArray) key = fontDataAsArray[p] & 0xFF; else key = fontDataAsObject.getByte(p) & 0xFF; if(debugDictionary) System.out.println(key +" (2) "+TwoByteCCFDict[key]); p++; if(key!=36 && key!=37 && key!=7 && FDSelect!=-1){ if(debugDictionary){ System.out.println("Ignored as part of FDArray "); for(int ii=0;ii<6;ii++) System.out.println(op[ii]); } }else if (key == 2) { //italic italicAngle=(int)op[0]; if(debugDictionary) System.out.println("Italic="+op[0]); }else if (key == 7) { //fontMatrix if(!hasFontMatrix) System.arraycopy(op, 0, FontMatrix, 0, 6); if(debugDictionary){ for(int ii=0;ii<6;ii++) System.out.println(ii+"="+op[ii]+ ' ' +this); } hasFontMatrix=true; }else if (key == 6) { if(op[0]>0){ blueValues = new int[6]; for (int z = 0; z < blueValues.length; z++) { blueValues[z] = (int) op[z]; } } } else if (key == 7) { if(op[0]>0){ otherBlues = new int[6]; for (int z = 0; z < otherBlues.length; z++) { otherBlues[z] = (int) op[z]; } } } else if (key == 8) { familyBlues = new int[6]; for (int z = 0; z < familyBlues.length; z++) { familyBlues[z] = (int) op[z]; } } else if (key == 9) { if(op[0]>0){ familyOtherBlues = new int[6]; for (int z = 0; z < familyOtherBlues.length; z++) { familyOtherBlues[z] = (int) op[z]; } } } else if (key == 10) { stdHW = (int) op[0]; } else if (key == 11) { stdVW = (int) op[0]; } else if (key == 30) { //ROS ros=(int)op[0]; isCID=true; if(debugDictionary) System.out.println(op[0]); }else if(key==31){ //CIDFontVersion CIDFontVersion=(int)op[0]; if(debugDictionary) System.out.println(op[0]); }else if(key==32){ //CIDFontRevision CIDFontRevision=(int)op[0]; if(debugDictionary) System.out.println(op[0]); }else if(key==33){ //CIDFontType CIDFontType=(int)op[0]; if(debugDictionary) System.out.println(op[0]); }else if(key==34){ //CIDcount CIDcount=(int)op[0]; if(debugDictionary) System.out.println(op[0]); }else if(key==35){ //UIDBase UIDBase=(int)op[0]; if(debugDictionary) System.out.println(op[0]); }else if(key==36){ //FDArray FDArray=(int)op[0]; if(debugDictionary) System.out.println(op[0]); }else if(key==37){ //FDSelect FDSelect=(int)op[0]; fdReset=true; if(debugDictionary) System.out.println(op[0]); }else if(key==0){ //copyright int id=(int)op[0]; if(id>390) id=id-390; copyright=strings[id]; if(debugDictionary) System.out.println("copyright= "+copyright); }else if(key==21){ //Postscript //postscriptFontName=strings[id]; if(debugDictionary) { int id=(int)op[0]; if(id>390) id=id-390; System.out.println("Postscript= "+strings[id]); System.out.println(TwoByteCCFDict[key]+ ' ' +op[0]); } }else if(key==22){ //BaseFontname //baseFontName=strings[id]; if(debugDictionary){ int id=(int)op[0]; if(id>390) id=id-390; System.out.println("BaseFontname= "+embeddedFontName); System.out.println(TwoByteCCFDict[key]+ ' ' +op[0]); } }else if(key==38){ //fullname //fullname=strings[id]; if(debugDictionary){ int id=(int)op[0]; if(id>390) id=id-390; System.out.println("fullname= "+strings[id]); System.out.println(TwoByteCCFDict[key]+ ' ' +op[0]); } }else if(debugDictionary) System.out.println(op[0]); } else { if(key==2){ //fullname int id=(int)op[0]; if(id>390) id=id-390; embeddedFontName=strings[id]; if(debugDictionary){ System.out.println("name= "+embeddedFontName); System.out.println(OneByteCCFDict[key]+ ' ' +op[0]); } }else if(key==3){ //familyname //embeddedFamilyName=strings[id]; if(debugDictionary){ int id=(int)op[0]; if(id>390) id=id-390; System.out.println("FamilyName= "+embeddedFamilyName); System.out.println(OneByteCCFDict[key]+ ' ' +op[0]); } }else if (key == 5) { //fontBBox if(debugDictionary){ for(int ii=0;ii<4;ii++) System.out.println(op[ii]); } for(int ii=0;ii<4;ii++){ //System.out.println(" "+ii+" "+op[ii]); this.FontBBox[ii]=(float) op[ii]; } //hasFontBBox=true; }else if (key == 0x0f) { // charset charset = (int) op[0]; if(debugDictionary) System.out.println(op[0]); } else if (key == 0x10) { // encoding enc = (int) op[0]; if(debugDictionary) System.out.println(op[0]); } else if (key == 0x11) { // charstrings charstrings = (int) op[0]; if(debugDictionary) System.out.println(op[0]); //System.out.println("charStrings="+charstrings); } else if (key == 18 && glyphs.is1C()) { // readPrivate int dictNo = currentFD; if (dictNo == -1) { dictNo = 0; } privateDict[dictNo] = (int) op[1]; privateDictOffset[dictNo] = (int) op[0]; if(debugDictionary) System.out.println("privateDict="+op[0]+" Offset="+op[1]); } else if (key == 20) { //defaultWidthX int dictNo = currentFD; if (dictNo == -1) { dictNo = 0; } defaultWidthX[dictNo] = (int)op[0]; if (glyphs instanceof T1Glyphs) ((T1Glyphs)glyphs).setWidthValues(defaultWidthX, nominalWidthX); if(debugDictionary) System.out.println("defaultWidthX="+op[0]); } else if (key == 21) { //nominalWidthX int dictNo = currentFD; if (dictNo == -1) { dictNo = 0; } nominalWidthX[dictNo] = (int)op[0]; if (glyphs instanceof T1Glyphs) ((T1Glyphs)glyphs).setWidthValues(defaultWidthX, nominalWidthX); if(debugDictionary) System.out.println("nominalWidthX="+op[0]); } else if(debugDictionary){ // System.out.println(p+" "+key+" "+T1CcharCodes1Byte[key]+" <<<"+op); System.out.println("Other value "+key); /**if(op <type1CStdStrings.length) System.out.println(type1CStdStrings[(int)op]); else if((op-390) <strings.length) System.out.println("interesting key:"+key);*/ } //System.out.println(p+" "+key+" "+raw1ByteValues[key]+" <<<"+op); } i=0; }else{ if(isByteArray) p=glyphs.getNumber(fontDataAsArray, p,op,i,false); else p=glyphs.getNumber(fontDataAsObject, p,op,i,false); i++; } } if(debugDictionary) System.out.println("================================="+getBaseFontName()); //reset if(!fdReset) FDSelect=-1; } private String[] readStringIndex(byte[] fontDataAsArray,FontData fontDataAsObject,int start,int offsize,int count){ int nStrings; boolean isByteArray=(fontDataAsArray!=null); if(isByteArray){ top = start + getWord(fontDataAsArray, top + count * offsize, offsize); //start of string index nStrings = getWord(fontDataAsArray, top, 2); stringOffSize = fontDataAsArray[top + 2]; }else{ top = start + getWord(fontDataAsObject, top + count * offsize, offsize); //start of string index nStrings = getWord(fontDataAsObject, top, 2); stringOffSize = fontDataAsObject.getByte(top + 2); } top += 3; stringIdx = top; stringStart = top + (nStrings + 1) * stringOffSize - 1; if(isByteArray) top =stringStart+ getWord(fontDataAsArray,top + nStrings * stringOffSize,stringOffSize); else top =stringStart+ getWord(fontDataAsObject,top + nStrings * stringOffSize,stringOffSize); int[] offsets = new int[nStrings + 2]; String[] strings = new String[nStrings + 2]; int ii = stringIdx; //read the offsets for (int jj = 0; jj < nStrings + 1; jj++) { if(isByteArray) offsets[jj] = getWord(fontDataAsArray,ii,stringOffSize); //content[ii] & 0xff; else offsets[jj] = getWord(fontDataAsObject,ii,stringOffSize); //content[ii] & 0xff; //getWord(content,ii,stringOffSize); ii = ii + stringOffSize; } offsets[nStrings + 1] = top - stringStart; //read the strings int current = 0; StringBuilder nextString; for (int jj = 0; jj < nStrings + 1; jj++) { nextString = new StringBuilder(offsets[jj]-current); for (int c = current; c < offsets[jj]; c++){ if(isByteArray) nextString.append((char) fontDataAsArray[stringStart + c]); else nextString.append((char) fontDataAsObject.getByte(stringStart + c)); } if(debugFont) System.out.println("String "+jj+" ="+nextString); strings[jj] = nextString.toString(); current = offsets[jj]; } return strings; } /** Utility method used during processing of type1C files */ static final private String getString(FontData fontDataAsObject,int sid,int idx,int start,int offsize) { int len; String result ; if (sid < 391) result = type1CStdStrings[sid]; else { sid -= 391; int idx0 =start+ getWord(fontDataAsObject, idx + sid * offsize,offsize); int idxPtr1 =start+ getWord(fontDataAsObject, idx + (sid + 1) * offsize,offsize); //System.out.println(sid+" "+idx0+" "+idxPtr1); if ((len = idxPtr1 - idx0) > 255) len = 255; result = new String(fontDataAsObject.getBytes(idx0,len)); } return result; } /** Utility method used during processing of type1C files */ static final private String getString(byte[] fontDataAsArray,int sid,int idx,int start,int offsize) { int len; String result ; if (sid < 391) result = type1CStdStrings[sid]; else { sid -= 391; int idx0 =start+ getWord(fontDataAsArray, idx + sid * offsize,offsize); int idxPtr1 =start+ getWord(fontDataAsArray, idx + (sid + 1) * offsize,offsize); //System.out.println(sid+" "+idx0+" "+idxPtr1); if ((len = idxPtr1 - idx0) > 255) len = 255; result=new String(fontDataAsArray,idx0,len); } return result; } /** get standard charset or extract from type 1C font */ static final private int[] readCharset(int charset, int nGlyphs, FontData fontDataAsObject, byte[] fontDataAsArray) { boolean isByteArray=fontDataAsArray!=null; int glyphNames[] ; int i, j; if(debugFont) System.out.println("charset="+charset); /** //handle CIDS first if(isCID){ glyphNames = new int[nGlyphs]; glyphNames[0] = 0; for (i = 1; i < nGlyphs; ++i) { glyphNames[i] = i;//getWord(fontData, top, 2); //top += 2; } // read appropriate non-CID charset }else */if (charset == 0) glyphNames = ISOAdobeCharset; else if (charset == 1) glyphNames = ExpertCharset; else if (charset == 2) glyphNames = ExpertSubCharset; else { glyphNames = new int[nGlyphs+1]; glyphNames[0] = 0; int top = charset; int charsetFormat; if(isByteArray) charsetFormat = fontDataAsArray[top++] & 0xff; else charsetFormat = fontDataAsObject.getByte(top++) & 0xff; if(debugFont) System.out.println("charsetFormat="+charsetFormat); if (charsetFormat == 0) { for (i = 1; i < nGlyphs; ++i) { if(isByteArray) glyphNames[i] = getWord(fontDataAsArray, top, 2); else glyphNames[i] = getWord(fontDataAsObject, top, 2); top += 2; } } else if (charsetFormat == 1) { i = 1; int c,nLeft; while (i < nGlyphs) { if(isByteArray) c = getWord(fontDataAsArray, top, 2); else c = getWord(fontDataAsObject, top, 2); top += 2; if(isByteArray) nLeft = fontDataAsArray[top++] & 0xff; else nLeft = fontDataAsObject.getByte(top++) & 0xff; for (j = 0; j <= nLeft; ++j) glyphNames[i++] =c++; } } else if (charsetFormat == 2) { i = 1; int c,nLeft; while (i < nGlyphs) { if(isByteArray) c = getWord(fontDataAsArray, top, 2); else c = getWord(fontDataAsObject, top, 2); top += 2; if(isByteArray) nLeft = getWord(fontDataAsArray, top, 2); else nLeft = getWord(fontDataAsObject, top, 2); top += 2; for (j = 0; j <= nLeft; ++j) glyphNames[i++] =c++; } } } return glyphNames; } /** Utility method used during processing of type1C files */ static final private int getWord(FontData fontDataAsObject, int index, int size) { int result = 0; for (int i = 0; i < size; i++) { result = (result << 8) + (fontDataAsObject.getByte(index + i) & 0xff); } return result; } /** Utility method used during processing of type1C files */ static final private int getWord(byte[] fontDataAsArray, int index, int size) { int result = 0; for (int i = 0; i < size; i++) { result = (result << 8) + (fontDataAsArray[index + i] & 0xff); } return result; } /** * get bounding box to highlight * @return */ public Rectangle getBoundingBox() { if(BBox==null){ if(isFontEmbedded) BBox=new Rectangle((int)FontBBox[0], (int)FontBBox[1], (int)(FontBBox[2]-FontBBox[0]), (int)(FontBBox[3]-FontBBox[1])); //To change body of created methods use File | Settings | File Templates. else BBox=super.getBoundingBox(); } return BBox; } /** * @return The Font Dictionary select array */ public int[] getFDSelect() { return fdSelect; } public int[] getRosArray(){ return rosArray; } public Object getKeyValue(int key){ switch(key){ case WEIGHT: return weight; case ITALICANGLE: return italicAngle; case FONTMATRIX: return FontMatrix; case FONTBBOX: return FontBBox; case ENCODING: return enc; case DEFAULTWIDTHX: return defaultWidthX[0]; case NOMINALWIDTHX: return nominalWidthX[0]; case BLUEVALUES: return blueValues; case OTHERBLUES: return otherBlues; case FAMILYBLUES: return familyBlues; case FAMILYOTHERBLUES: return familyOtherBlues; case STDHW: return stdHW; case STDVW: return stdVW; case SUBRS: return subrs; case ROS: return ros; case CIDCOUNT: return CIDcount; case CIDFONTREVISION: return CIDFontRevision; case CIDFONTVERSION: return CIDFontVersion; case CIDFONTTYPE: return CIDFontType; case FDARRAY: return FDArray; case FDSELECT: return FDSelect; default: throw new RuntimeException("Key is unknown or value is not yet assigned "+key ); } } }
on-site/JPedal
src/org/jpedal/fonts/Type1C.java
249,361
/* * Copyright (C) 2015 joulupunikki [email protected]. * * Disclaimer of Warranties and Limitation of Liability. * * The creators and distributors offer this software as-is and * as-available, and make no representations or warranties of any * kind concerning this software, whether express, implied, statutory, * or other. This includes, without limitation, warranties of title, * merchantability, fitness for a particular purpose, non-infringement, * absence of latent or other defects, accuracy, or the presence or * absence of errors, whether or not known or discoverable. * * To the extent possible, in no event will the creators or distributors * be liable on any legal theory (including, without limitation, * negligence) or otherwise for any direct, special, indirect, * incidental, consequential, punitive, exemplary, or other losses, * costs, expenses, or damages arising out of the use of this software, * even if the creators or distributors have been advised of the * possibility of such losses, costs, expenses, or damages. * * The disclaimer of warranties and limitation of liability provided * above shall be interpreted in a manner that, to the extent possible, * most closely approximates an absolute disclaimer and waiver of * all liability. * */ package phoenix; import gui.Gui; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Date; import java.util.LinkedList; import javax.swing.AbstractButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JTextArea; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import util.C; import util.CrashReporter; import util.FN; import util.FileNameCapitalizer; import util.Util; import util.UtilG; /** * Main entry point of Phoenix, clone/remake/patch/replacement of the EFS.EXE in * the game Emperor of the Fading Suns. * * @author joulupunikki */ public class Phoenix { // public static final Logger logger = LogManager.getLogger(); public static final long start_time; private static int event_number = 0; private static LinkedList<String> log_buffer = new LinkedList<>(); //true iff a JMenu is open private static boolean log_mouse_move = false; private static String last_jmenu = null; private static Gui gui = null; private static PrintWriter input_log_writer; private static JFrame boot_frame = null; private static JTextArea boot_text = null; private static String boot_string = null; /** * true iff Phoenix is doing an arbitrarily long task with user input * dependent length (such as stack moving with animation, which can be * stopped by user input at any point along the movement path) and wait * times should not be culled. Will be set by Phoenix event handlers which * start such tasks. Will be reset by after MousePressed event logged in an * AWTEventListener which is set in Phoenix.main. */ private static boolean is_real_time = false; public static int FOLLOW_UNIT; static { start_time = System.nanoTime(); } public static void closeBootFrame() { try { Thread.sleep(500); } catch (InterruptedException ex) { } boot_frame.dispose(); } public static void addBootMsg(String s) { System.out.println(s); boot_string += s; boot_text.setText(boot_string); boot_text.paintImmediately(BOOT_FRAME_X, BOOT_FRAME_Y, BOOT_FRAME_W, BOOT_FRAME_H); } /** * Main entry point of Phoenix. * <p> * parse commandline options <br> * log all uncaught Throwables <br> * log input events <br> * start GUI (the Phoenix proper) * * @param args the command line arguments */ public static void main(String[] args) { boot_string = "Phoenix started.\n" + "OS: " + System.getProperty("os.arch", "No arch info.") + " " + System.getProperty("os.name", "No name info.") + " " + System.getProperty("os.version", "No version info.") + "\n" + "System: " + "available cores " + Runtime.getRuntime().availableProcessors() + "\n" + "Best large cursor size: " + Toolkit.getDefaultToolkit().getBestCursorSize(64, 64); ; System.out.println(boot_string); boot_frame = new JFrame("Phoenix boot GUI"); boot_text = new JTextArea(); boot_text.setText(boot_string); boot_text.setForeground(C.COLOR_GOLD); boot_text.setBackground(Color.BLACK); boot_frame.getContentPane().add(boot_text, BorderLayout.CENTER); boot_frame.pack(); boot_frame.setVisible(true); boot_frame.setBounds(BOOT_FRAME_X, BOOT_FRAME_Y, BOOT_FRAME_W, BOOT_FRAME_H); setLAF(); // logger.debug("Test log4j logging"); // parse options CommandLine cli_opts = parseCLI(args); // wait if requested if (cli_opts.hasOption(C.OPT_WAIT_BEFORE_START)) { System.out.print("Press enter to start Phoenix"); try { System.in.read(); } catch (IOException ex) { } } // if (cli_opts.hasOption(C.OPT_CAPITALIZE_FILE_NAMES) && !FileNameCapitalizer.run()) { addBootMsg("\nFailed to ensure all filenames are uppercase."); addBootMsg("\nPhoenix halted."); CrashReporter.removeEventListeners(); return; } // log all errors and exceptions rollLogs(FN.S_LOG_FILE); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("Uncaught exception."); Util.logEx(t, e); CrashReporter.showCrashReport(e); } }); // start GUI Gui.execute(cli_opts); } public static boolean startInputEventLogging(CommandLine cli_opts) { // log input events String file_name = FN.S_DIST_PREFIX + "input.log"; rollLogs(file_name); Path input_log_file = FileSystems.getDefault().getPath(file_name); BufferedWriter event_log_buf = null; try { event_log_buf = Files.newBufferedWriter(input_log_file, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); } catch (IOException ex) { System.out.println("Unable to open input event log file \"" + file_name + "\""); Util.logEx(null, ex); CrashReporter.showCrashReport(ex); return true; } input_log_writer = new PrintWriter(event_log_buf, true); Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { //WORKAROUND JDK-6778087 : getLocationOnScreen() always returns (0, 0) for mouse wheel events, on Windows private Point prev_xy = new Point(-1, -1); private boolean prefix = true; @Override public void eventDispatched(AWTEvent event) { //System.out.println("#####Event : " + event.paramString()); if (prefix) { prefix = false; Long random_seed = Phoenix.start_time; if (cli_opts.hasOption(C.OPT_RANDOM_SEED)) { random_seed = Long.getLong(cli_opts.getOptionValue(C.OPT_RANDOM_SEED)); } if (RobotTester.isRobotTest()) { random_seed = RobotTester.getRandomSeed(); } input_log_writer.println(RobotTester.RANDOM_SEED_PREFIX + random_seed); input_log_writer.println("# input logging started at " + (new Date()).toString()); input_log_writer.println("# fields (#8): nr time(ms) eventID button/wheel/key clicks screenX screenY source[=text]"); } int id = event.getID(); // On windows certain events always return 0,0 as their getLocationOnScreen() // This causes problems with robottester, so we skip here everything // except that which may go into input.log switch (id) { case MouseEvent.MOUSE_DRAGGED: case MouseEvent.MOUSE_MOVED: case MouseEvent.MOUSE_PRESSED: case MouseEvent.MOUSE_RELEASED: case MouseEvent.MOUSE_WHEEL: case KeyEvent.KEY_PRESSED: case KeyEvent.KEY_RELEASED: break; default: return; } String details = "" + id; if (event instanceof MouseWheelEvent) { // check this first since ME is super of MWE // Wheel Events seem to propagate beyond the original source // multiple dispatches confuse RobotTester so return here if // source container is not the first below mouse pointer Container co = (Container) event.getSource(); if (co.getMousePosition(false) == null) { return; } MouseWheelEvent me = (MouseWheelEvent) event; details += " " + me.getWheelRotation() + " -1 " + getCoordinates(me); //System.out.println("MWE at : " + getCoordinates(me)); } else if (event instanceof MouseEvent) { MouseEvent me = (MouseEvent) event; details += " " + me.getButton() + " " + me.getClickCount() + " " + getCoordinates(me); } else if (event instanceof KeyEvent) { KeyEvent ke = (KeyEvent) event; details += " " + ke.getExtendedKeyCode() + " -1 -1 -1"; // int r = ke.getKeyCode(); // String key_char = "<non-unicode>"; // if (r <= KeyEvent.VK_ALT && r >= KeyEvent.VK_SHIFT) { // key_char = "<alt/ctrl/shift>"; // } else { // String tmp = Character.getName(ke.getKeyChar()); // if (tmp != null) { // key_char = tmp.replace(' ', '_'); // } // } // details += " " + ke.getExtendedKeyCode() + " " + key_char; } else { return; } String event_src = ""; Object s = event.getSource(); event_src += s.getClass().getCanonicalName(); if (s instanceof AbstractButton) { event_src += "=" + ((AbstractButton) s).getText(); } details = details + RobotTester.S_SOURCE_SEP + event_src; //System.out.println("id: " + id); switch (id) { // Mouse button/move events need special treatment // with respect to JMenus. case MouseEvent.MOUSE_DRAGGED: // C.p("DRAG MOUSE " + (gui.getJMenuBar().findComponentAt(((MouseEvent) event).getLocationOnScreen()))); // C.p("DRAG MOUSE " + (((MouseEvent) event).getLocationOnScreen())); if (log_mouse_move) { logDispatched(details, event); } case MouseEvent.MOUSE_MOVED: // if a JMenu is open and mouse cursor moves to a different // JMenu, make note of the menu change if (log_mouse_move && event_src.startsWith("javax.swing.JMenu=") && !last_jmenu.equals(event_src)) { last_jmenu = event_src; logDispatched(details, event); } break; case MouseEvent.MOUSE_PRESSED: // if on a JMenu, toggle mouse move logging if (s instanceof JMenu) { log_mouse_move = !log_mouse_move; last_jmenu = event_src; } else { log_mouse_move = false; } logDispatched(details, event); is_real_time = false; break; case MouseEvent.MOUSE_RELEASED: // if not on a JMenu, disable mouse move logging if (!(s instanceof javax.swing.JMenu)) { log_mouse_move = false; } logDispatched(details, event); break; case MouseEvent.MOUSE_WHEEL: log_mouse_move = false; case KeyEvent.KEY_PRESSED: case KeyEvent.KEY_RELEASED: logDispatched(details, event); break; default: break; } } private void logDispatched(String details, AWTEvent event) { int number = ++event_number; int time = (int) ((System.nanoTime() - start_time) / 1_000_000); if (is_real_time) { number *= -1; } String logged = number + " " + time + " " + details; // logging delayed during 2click sequences if (RobotTester.isDelayedLogging()) { log_buffer.addLast(logged); } else { flushLogMessages(); input_log_writer.println(logged); } RobotTester.dispatchedEvent(logged); //System.out.println("#D " + number + " " + event); } private String getCoordinates(MouseEvent me) { Point p = Gui.getOrigin(); //WORKAROUND JDK-6778087 : getLocationOnScreen() always returns (0, 0) for mouse wheel events, on Windows if (me.getID() != MouseEvent.MOUSE_WHEEL) { //System.out.println(me); //System.out.println("Non-Wheel event"); prev_xy = me.getLocationOnScreen(); } return ((prev_xy.x - p.x) + " " + (prev_xy.y - p.y)); } }, ROBOTTESTER_INPUT_EVENT_MASK); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { input_log_writer.println("# input logging stopped due to jvm shutdown at " + (new Date()).toString()); input_log_writer.close(); } }); return false; } private static final int BOOT_FRAME_H = 400; private static final int BOOT_FRAME_W = 400; private static final int BOOT_FRAME_Y = 0; private static final int BOOT_FRAME_X = 0; public static final long ROBOTTESTER_INPUT_EVENT_MASK = AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK | AWTEvent.KEY_EVENT_MASK; private static void setLAF() { try { // Set cross-platform Java L&F (also called "Metal") UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); //MetalLookAndFeel.setCurrentTheme(new DarkTheme()); UtilG.setUIDefaults(); } catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { System.out.println("setLAF failed"); } } private static CommandLine parseCLI(String[] args) { CommandLine ret_val = null; Options opts = new Options(); opts.addOption(C.OPT_DOUBLE_RES, "Double resolution (1280x960)"); opts.addOption(C.OPT_NAMED_GALAXY, true, "Name of galaxy file"); opts.addOption(C.OPT_HELP, "Print help"); opts.addOption(null, C.OPT_ROBOT_TEST, true, "(WARNING: EXPERTS ONLY) Run Robot test with file"); opts.addOption(null, C.OPT_WAIT_BEFORE_START, false, "Wait for enter before initiliazing"); opts.addOption(null, C.OPT_ECONOMY_PRINT, false, "Printout economy details at start of turn"); opts.addOption(null, C.OPT_AUTO_DELAY, true, "Set Robot test auto delay in ms"); opts.addOption(null, C.OPT_CLEAN_UP_2CLICK, false, "Delay IO and do gc() before 2click"); opts.addOption(null, C.OPT_GAME_STATE_FILE, true, "Game state record file to check against"); opts.addOption(null, C.OPT_MAX_DELAY, true, "Maximum event delay (in ms) during Robot testing"); opts.addOption(null, C.OPT_WIZARD_MODE, false, "Activate wizard mode"); opts.addOption(null, C.OPT_ROBOT_STOP, true, "Execute Robot test for this number of events then stop " + "Robot and leave game as is"); opts.addOption(null, C.OPT_RANDOM_SEED, true, "Set argument as random seed"); opts.addOption(null, C.OPT_ENABLE_AI, false, "Enable AI"); opts.addOption(null, C.OPT_AI_TEST, true, "Do AI test run, for arg number of turns"); opts.addOption(null, C.OPT_ENABLE_SYMBIOT_AI, false, "Enable symbiot AI"); opts.addOption(null, C.OPT_CAPITALIZE_FILE_NAMES, false, "convert lower case to upper case in EFS file names"); opts.addOption(null, C.OPT_EFS_SPACE_SPOT, false, "EFS1.4 style space spotting: need 100 camo to remain unspotted"); opts.addOption(null, C.OPT_FOLLOW_UNIT, true, "follow unit with specified unit number"); opts.addOption(null, C.OPT_DEBUG_STOP, false, "stop ai run and drop to game UI on fatal ai errors"); HelpFormatter formatter = new HelpFormatter(); DefaultParser parser = new DefaultParser(); try { ret_val = parser.parse(opts, args); } catch (ParseException ex) { System.out.println("Error parsing arguments: " + ex.getMessage()); System.exit(0); } if (ret_val.hasOption(C.OPT_HELP)) { formatter.printHelp("java -jar -Xss32m Phoenix.jar\n phoenix.sh\n phoenix.bat" + "\n\nLong options are for debugging", opts); System.exit(0); } FOLLOW_UNIT = Integer.parseInt(ret_val.getOptionValue(C.OPT_FOLLOW_UNIT, "0")); return ret_val; } private static void rollLogs(String name) { // roll logs final int MAX_BACKUP = 5; for (int i = MAX_BACKUP; i > 0; i--) { File log_file = new File(name + "." + (i - 1)); if (i == 1) { log_file = new File(name); } File old_log = new File(name + "." + i); if (old_log.exists()) { old_log.delete(); } if (log_file.exists()) { log_file.renameTo(old_log); } } } public static void setGui(Gui g) { gui = g; } public static void setRealTime() { Phoenix.is_real_time = true; } static void flushLogMessages() { for (String tmp : log_buffer) { input_log_writer.println(tmp); } log_buffer.clear(); } public static void logGuiState(String state) { String STATE_PREFIX = "# s->"; if (is_real_time) { log_buffer.addLast(STATE_PREFIX + state); } else { input_log_writer.println(STATE_PREFIX + state); } } }
joulupunikki/Phoenix
src/phoenix/Phoenix.java
249,362
package util.gen; import java.io.*; import javax.servlet.http.*; import java.nio.*; import java.nio.channels.*; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.*; import org.apache.tools.bzip2.*; import java.net.*; /** * Static methods for Input Output related tasks. */ public class IO { public static final Pattern COMMA = Pattern.compile(","); /**Writes a String, max length 256.*/ public static void writeStringShort(String x, DataOutputStream out) throws IOException{ int length = x.length(); if (length > 256) throw new IOException("String length exceeds 256 characters. See "+x); length = length -128; //write length - 128 out.writeByte(length); //write string out.writeBytes(x); } /**Reads a String, max length 256.*/ public static String readStringShort(DataInputStream dis) throws IOException{ //read length byte[] barray = new byte[dis.readByte() + 128]; dis.readFully(barray); return new String(barray); } /**Attempts to fetch the 'Implementation-Version' from the calling jar file's manifest.*/ public static String fetchUSeqVersion(){ String version = ""; try { String jarPath = IO.class.getProtectionDomain().getCodeSource().getLocation().getPath(); jarPath = URLDecoder.decode(jarPath, "UTF-8"); if (jarPath.endsWith(".jar") == false) return version; JarFile jar = new JarFile(new File (jarPath)); Manifest manifest = jar.getManifest(); version = manifest.getMainAttributes().getValue("Implementation-Version"); if (version == null) version = ""; } catch (Exception x) { System.err.println("\nProblem fetching version information from the jar file.\n"); x.printStackTrace(); } return "["+Misc.getDateTime()+"] "+version; } /**Returns the names of the files or directories.*/ public static String[] fetchFileNames(File[] files){ String[] names = new String[files.length]; for (int i=0; i< files.length; i++){ names[i] = files[i].getName(); } return names; } /**Returns the names of the files or directories sans their extension*/ public static String[] fetchFileNamesNoExtensions(File[] files){ String[] names = new String[files.length]; for (int i=0; i< files.length; i++){ names[i] = Misc.removeExtension(files[i].getName()); } return names; } /**Concatinates files regardless of type. Good for gz! Doesn't check for failed line return so its possible to join two lines together :( * @throws IOException */ public static void concatinateFiles(ArrayList<File> filesToConcatinate, File destination) throws IOException{ Vector<InputStream> inputStreams = new Vector<InputStream>(); int num = filesToConcatinate.size(); for (int i=0; i< num; i++){ FileInputStream fis = new FileInputStream(filesToConcatinate.get(i)); inputStreams.add(fis); } Enumeration<InputStream> enu = inputStreams.elements(); SequenceInputStream sis = new SequenceInputStream(enu); OutputStream bos = new FileOutputStream(destination); byte[] buffer = new byte[8192]; int intsRead; while ((intsRead = sis.read(buffer)) != -1) { bos.write(buffer, 0, intsRead); } bos.close(); sis.close(); } /**Merges files watching for lack of a line return on last line to avoid line concatination. GZ/Zip OK.*/ public static void mergeFiles(ArrayList<File> toMerge, File destination) throws IOException{ PrintWriter out = new PrintWriter( new FileWriter(destination)); String line; for (File f : toMerge){ BufferedReader in = IO.fetchBufferedReader(f); while ((line = in.readLine()) != null) out.println(line); in.close(); } out.close(); } /**Returns the amount of memory being used.*/ public static String memoryUsed(){ System.gc(); Runtime rt = Runtime.getRuntime(); System.gc(); long usedMB = (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024; return usedMB+"MB @ "+System.currentTimeMillis()/1000+"Sec"; } /**Returns the amount of memory being used.*/ public static String memory(){ System.gc(); Runtime rt = Runtime.getRuntime(); System.gc(); long usedMB = (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024; return usedMB+"MB"; } /**Checks to see if the current java is 1.6, 1.7, or 1.8 by executing and parsing 'java -version'*/ public static boolean checkJava(){ String[] cmd = {"java","-version"}; String[] results = IO.executeCommandLineReturnAll(cmd); if (results == null || results.length ==0) return false; for (int i=0; i< results.length; i++){ if (results[i].startsWith("java version")){ if (results[i].contains("1.6.") || results[i].contains("1.7.")|| results[i].contains("1.8.")) return true; return false; } } return false; } /**Returns null is something bad happened, otherwise returns the r output lines containing 'error' case insensitive or returns '' if no error found.*/ public static String runRCommandLookForError(String rCmdLine, File rApp, File tempDir){ //look for R if (rApp.canExecute() == false) return "Cannot execute R check -> "+rApp; String rndWrd = Passwords.createRandowWord(7); File inFile = new File (tempDir, "RCmdLine_"+rndWrd); File outFile = new File (tempDir, "ROutput_"+rndWrd); String[] command = { rApp.toString(), "CMD", "BATCH", "--no-save", "--no-restore", inFile.toString(), outFile.toString() }; if (IO.writeString(rCmdLine, inFile) == false) return null; String[] messages = IO.executeCommandLineReturnAll(command); inFile.delete(); if (messages == null || messages.length !=0){ Misc.printArray(messages); outFile.delete(); return null; } //load results String[] rLines = IO.loadFile(outFile); outFile.delete(); //look for error boolean errorFound = false; StringBuilder errors = new StringBuilder(); Pattern errorPat = Pattern.compile("error", Pattern.CASE_INSENSITIVE); for (int i=0; i< rLines.length; i++){ if (errorFound) { errors.append(" "); errors.append(rLines[i]); } else if (errorPat.matcher(rLines[i]).lookingAt()){ errors.append(rLines[i]); errorFound = true; } } if (errorFound) return errors.toString(); return ""; } /**Takes a file, capitalizes the text, strips off .gz or .zip and any other extension, then makes a directory of the file and returns it. * returns null if the new directory exists.*/ public static File makeDirectory (File file, String extension){ String name = file.getName(); name = Misc.capitalizeFirstLetter(name); name = name.replace(".gz", ""); name = name.replace(".zip", ""); name = Misc.removeExtension(name); File dir = new File (file.getParentFile(), name+ extension); if (dir.exists()) return null; dir.mkdir(); return dir; } /**Takes a file strips off .gz or .zip and returns it's extension without the leading . or "".*/ public static String fetchFileExtension (File file){ String name = file.getName(); name = name.replace(".gz", ""); name = name.replace(".zip", ""); int index = name.lastIndexOf("."); if (index != -1) return name.substring(index+1); return ""; } /**Uses Ants implementation of the bzip2 compression algorithm. * Be sure to text your file xxx.bz2*/ public static boolean bzip2(File toZip, File zipped) { try { //output BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(zipped)); bos.write('B'); bos.write('Z'); CBZip2OutputStream zOut = new CBZip2OutputStream(bos); //input FileInputStream in = new FileInputStream(toZip); //zip it byte[] buffer = new byte[8 * 1024]; int count = 0; do { zOut.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); //close streams zOut.close(); in.close(); return true; } catch (IOException ioe) { ioe.printStackTrace(); return false; } } /**Uncompressed bzip2 files using the Ant implementation. * Be sure to text your file xxx.bz2*/ public static boolean bunzip2(File zippedFile, File decompressedFile) { try { FileOutputStream out = new FileOutputStream(decompressedFile); FileInputStream fis = new FileInputStream(zippedFile); BufferedInputStream bis = new BufferedInputStream(fis); int b = bis.read(); int z = bis.read(); if (b != 'B' && z != 'Z') { System.out.println("Invalid bz2 file! "+ zippedFile); return false; } CBZip2InputStream zIn = new CBZip2InputStream(bis); byte[] buffer = new byte[8 * 1024]; int count = 0; do { out.write(buffer, 0, count); count = zIn.read(buffer, 0, buffer.length); } while (count != -1); out.close(); fis.close(); return true; } catch (IOException ioe) { System.out.println("Problem bunzip2ing your file! "); ioe.printStackTrace(); } return false; } /**Returns number of days its been since the file was last modified.*/ public static double numberDaysOld(File file){ double diff = (double) (new Date().getTime() - file.lastModified()); return diff/(24*60*60*1000); } /**Fetches the first set of # lines at the beginning of the file. Stops when a non # line is found. * @throws IOException */ public static String fetchHeader(File file) throws IOException{ BufferedReader in = IO.fetchBufferedReader(file); StringBuilder sb = new StringBuilder(); String line; while ((line = in.readLine()) !=null) { line = line.trim(); if (line.length() ==0) continue; if (line.startsWith("#")){ sb.append(line); sb.append("\n"); } else break; } return sb.toString(); } /**Converts a String of "grp1=/my/Dir1,grp2=/my/Dir2, etc that contains * directories into a LinkedHashMap. * Returns null and prints an error message if an error was thrown, ie no directory, not a directory */ public static LinkedHashMap buildDirectoryFileGroups (String map){ //convert key=value into a hashmap String[] lines = map.split(","); LinkedHashMap hash = new LinkedHashMap(); for (int i=0; i<lines.length; i++){ String[] keyValue= lines[i].split("="); //check if keyValue exists if (keyValue.length != 2) { System.out.println("\nError: key=value pair not found? -> "+lines[i]+"\n"); return null; } //check if file exists and is readable File file = new File (keyValue[1]); if (file.canRead() == false || file.isDirectory() == false){ System.out.println("\nError: could not read this directory -> "+file+"\n"); return null; } //check to see if key already exists if (hash.containsKey(keyValue[0])){ System.out.println("\nError: duplicate key found -> "+lines[i]+"\n"); return null; } //add hash.put(keyValue[0], file); } return hash; } /**This removes parent dirs shared by all, assumes / as the dir divider.*/ public static String[] trimCommonParentDirs(File[] f){ //convert into String arrays String[][] fileDirs = new String[f.length][]; int minNumDirs = 10000000; for (int i=0; i< f.length; i++){ fileDirs[i] = Misc.FORWARD_SLASH.split(f[i].toString()); if (fileDirs[i].length < minNumDirs) minNumDirs = fileDirs[i].length; } //for each dir int firstUncommonIndex = 0; for (int i=0; i< minNumDirs; i++){ String testDirName = fileDirs[0][i]; boolean common = true; //for each file for (int j=1; j< fileDirs.length; j++){ if (fileDirs[j][i].equals(testDirName) == false){ common = false; break; } } if (common == false) { firstUncommonIndex = i; break; } } //concatinate firstUncommon and afterward String[] trimmed = new String[f.length]; for (int i=0; i< fileDirs.length; i++){ ArrayList<String> al = new ArrayList<String>(); for (int j=firstUncommonIndex; j< fileDirs[i].length; j++) al.add(fileDirs[i][j]); trimmed[i] = Misc.stringArrayListToString(al, "/"); } return trimmed; } /**Converts a String of "grp1=/my/file1,grp1=/my/old/file2,grp2=/my/file2, * grp2=/my/new/file3,grp3=/my/new/dir/,/my/default etc" * to a File[][] where the files have been broken by grouping into different File[]. * If no key is provided, the files are assigned to a common 'default' grouping. * If a directory is provided all files within are grouped together. * Mixing of keyed and unkeyed is permitted. * Returns null if an error was thrown. * @param directoryFileExtensionFilter - if directories are given in the map, you can * filter which files to extract (ie 'cel'), case insensitive, set to "." for everything. * @return - ArrayList containing String[] groupNames and a File[][] of grouped files, and * a LinkedHashMap of the two.*/ public static ArrayList buildFileGroups (String map, String directoryFileExtensionFilter){ //convert key=value into a hashmap if (map == null){ System.out.println("\nError: please enter files to check.\n"); return null; } String[] lines = map.split(","); LinkedHashMap hash = new LinkedHashMap(); for (int i=0; i<lines.length; i++){ String[] keyValue= lines[i].split("="); //check if keyValue exists if (keyValue.length == 1) { keyValue = new String[]{"Default", lines[i]}; } else if (keyValue.length > 2){ System.out.println("\nError: splitting of your grouping=filename failed?! Problem line -> "+lines[i]+"\n"); return null; } //check if file exists and is readable File file = new File (keyValue[1]); if (file.canRead() == false){ System.out.println("\nError: could not read this file/ directory -> "+file+"\n"); return null; } //is it a directory? if (file.isDirectory()){ //get cel files File[] all = IO.extractFiles(file,directoryFileExtensionFilter); Arrays.sort(all); //load hash //does the grouping already exist? if (hash.containsKey(keyValue[0])){ ArrayList files = (ArrayList)hash.get(keyValue[0]); for (int x=0; x<all.length; x++) files.add(all[x]); } else { ArrayList files = new ArrayList(); for (int x=0; x<all.length; x++) files.add(all[x]); hash.put(keyValue[0],files); } } //no it is not a directory else { //does the grouping already exist? if (hash.containsKey(keyValue[0])){ ArrayList files = (ArrayList)hash.get(keyValue[0]); files.add(file); } else { ArrayList files = new ArrayList(); files.add(file); hash.put(keyValue[0],files); } } } //convert hash to File[][] File[][] files = new File[hash.size()][]; String[] groupNames = new String[hash.size()]; Iterator it = hash.keySet().iterator(); int counter = 0; while (it.hasNext()){ String key = (String)it.next(); groupNames[counter] = key; ArrayList al = (ArrayList)hash.get(key); File[] fileGrp = new File[al.size()]; al.toArray(fileGrp); //sort Arrays.sort(fileGrp); files[counter++] = fileGrp; //set in hash replacing original hash.put(key, fileGrp); } ArrayList results = new ArrayList(3); results.add(groupNames); results.add(files); results.add(hash); return results; } /** * Use to read in xxx.bz2 files directly to a String[]. * Returns null if a problem encountered. * Must have bunzip2 installed. */ public static String[] bunZip2(File bunZip2App, File bz2FileToUncompress) { String[] command = {IO.getFullPathName(bunZip2App), "--stdout", "--decompress", IO.getFullPathName(bz2FileToUncompress)}; return IO.executeCommandLine(command); } /**Check to see that a file exists and is not a directory.*/ public static void checkFile(String par){ File f = new File(par); if (f.exists()) return; if (f.isDirectory()) return; System.out.println("\nSorry, I can't find your file or directory! ->"+par); System.exit(0); } /**Merges all files in File[][] to a File[].*/ public static File[] collapseFileArray(File[][] f){ ArrayList al = new ArrayList(); for (int i=0; i< f.length; i++){ if (f[i] != null){ for (int j=0; j< f[i].length; j++){ al.add(f[i][j]); } } } File[] files = new File[al.size()]; al.toArray(files); //just to be safe convertToCanonicalPaths(files); return files; } /** converts local files to their full path files */ public static void convertToCanonicalPaths(File[] f) { int num = f.length; for (int i=0; i< num; i++) try { f[i] = f[i].getCanonicalFile(); } catch (IOException e) { System.err.println("\nFAILED to convert to canonical paths.\n"); e.printStackTrace(); } } /**Concatinates the full path file names for the given File array.*/ public static String concatinateFileFullPathNames (File[] f, String seperator){ try{ String[] names = new String[f.length]; for (int i=0; i< f.length; i++) names[i] = f[i].getCanonicalPath(); return Misc.stringArrayToString(names, seperator); } catch (Exception e){ e.printStackTrace(); } return null; } /** Fast & simple file copy. From GForman http://www.experts-exchange.com/M_500026.html * Hit an odd bug with a "Size exceeds Integer.MAX_VALUE" error when copying a vcf file. -Nix.*/ public static boolean copyViaFileChannel(File source, File dest){ FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } /** Copy via read line. Slower than channel copy but doesn't have Integer.MAX_Value problem. * Source file can be txt, txt.gz, or txt.zip. So decompresses if needed. * @author Nix*/ public static boolean copyViaReadLine(File source, File dest){ BufferedReader in = null; PrintWriter out = null; try { in = IO.fetchBufferedReader(source); out = new PrintWriter (new FileWriter (dest)); String line; while ((line = in.readLine()) != null) out.println(line); return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) {} } } /**Attempts to uncompress a xxx.gz or xxx.zip file and write it to the same location without the extension. * Returns null if any issues are encountered. If the uncompressed file already exists, it is returned. * If uncompressed file is null then it is created from the gzipOrZipCompressed's name.*/ public static File uncompress (File gzipOrZipCompressed, File uncompressed) { File f = null; PrintWriter out = null; BufferedReader in = null; try { String name = gzipOrZipCompressed.getName(); if (name.endsWith(".zip")) name = name.substring(0, name.length()-4); else if (name.endsWith(".gz")) name = name.substring(0, name.length()-3); else return null; if (uncompressed != null) f = uncompressed; else { f = new File (gzipOrZipCompressed.getParentFile(), name); if (f.exists() && f.length() > 40) return f; } out = new PrintWriter( new FileWriter(f)); in = IO.fetchBufferedReader(gzipOrZipCompressed); String line; while ((line = in.readLine()) != null) out.println(line); in.close(); out.close(); return f; } catch (IOException e){ e.printStackTrace(); return null; } finally { try { if (out != null) out.close(); if (in != null) in.close(); } catch (IOException e){ e.printStackTrace(); } } } /**Copies a given directory and it's contents to the destination directory. * Use a extension (e.g. "class$|properties$") to limit the files copied over or set to null for all.*/ public static boolean copyDirectoryRecursive (File sourceDir, File destDir, String extension){ Pattern pat = null; if(extension != null) pat = Pattern.compile(extension); if (destDir.exists() == false) destDir.mkdir(); //for each file in source copy to destDir File[] files = IO.extractFiles(sourceDir); for (int i=0; i< files.length; i++){ if (files[i].isDirectory()) { copyDirectoryRecursive(files[i], new File (destDir, files[i].getName()), extension); } else { if (pat != null){ Matcher mat = pat.matcher(files[i].getName()); if (mat.find()){ File copied = new File (destDir, files[i].getName()); if (copyViaFileChannel(files[i], copied) == false ) return false; } } else { File copied = new File (destDir, files[i].getName()); if (copyViaFileChannel(files[i], copied) == false ) return false; } } } return true; } /**Counts the number of lines in a file skipping blanks.*/ public static long countNonBlankLines(File file){ long num =0; try { BufferedReader in = new BufferedReader(new FileReader(file)); String line; while ((line = in.readLine()) !=null) { line = line.trim(); if (line.length() !=0) num++; } in.close(); } catch (IOException e){ System.out.println("\nProblem counting the number of lines in the file: "+file); e.printStackTrace(); } return num; } /**Counts the number of lines in a file skipping blanks and those starting with #. * gz, zip, or txt OK.*/ public static long countNonBlankOrCommentLines(File file){ long num =0; try { BufferedReader in = IO.fetchBufferedReader(file); String line; while ((line = in.readLine()) !=null) { line = line.trim(); if (line.startsWith("#")) continue; if (line.length() !=0) num++; } in.close(); } catch (IOException e){ System.out.println("\nProblem counting the number of lines in the file: "+file); e.printStackTrace(); } return num; } /**Counts the number of lines in a file*/ public static long countNumberOfLines(File file){ long num =0; try { BufferedReader in = new BufferedReader(new FileReader(file)); while ((in.readLine()) !=null) { num++; } in.close(); } catch (IOException e){ System.out.println("\nProblem counting the number of lines in the file: "+file); e.printStackTrace(); } return num; } /**Counts the number of File in the array that actually exist.*/ public static int countNumberThatExist(File[] f){ int num =0; for (int i=0; i< f.length; i++) if (f[i].exists()) num++; return num; } /**Attempts to delete a directory and it's contents. * Returns false if all the file cannot be deleted or the directory is null. * Files contained within scheduled for deletion upon close will cause the return to be false.*/ public static void deleteDirectory(File dir){ if (dir == null || dir.exists() == false) return; if (dir.isDirectory()) { File[] children = dir.listFiles(); for (int i=0; i<children.length; i++) { deleteDirectory(children[i]); } dir.delete(); } dir.delete(); if (dir.exists()) deleteDirectoryViaCmdLine(dir); } public static void deleteDirectoryViaCmdLine(File dir){ try { IO.executeCommandLine(new String[]{"rm","-rf",dir.getCanonicalPath()}); } catch (IOException e) { e.printStackTrace(); } } /**Seems to work in most cases provided files aren't in use in the app.*/ public static boolean deleteDirectorySimple(File dir) { File[] allContents = dir.listFiles(); if (allContents != null) { for (File file : allContents) deleteDirectory(file); } return dir.delete(); } /**Executes rm -f file.getCanonicalPath() * Don't use this on soft links, will destroy the original file.*/ public static void deleteFileViaCmdLine(File file){ try { IO.executeCommandLine(new String[]{"rm","-f", file.getCanonicalPath()}); } catch (IOException e) { e.printStackTrace(); } } /**Attempts to delete a file.*/ public static boolean deleteFile(File file) { String name = ""; try { name = file.getCanonicalPath(); if (!file.delete()) { System.out.println("Warning: could not delete the file " + name); return false; } return true; } catch (Exception ex){ System.out.println("Problem with not deleteFile() " + name); ex.printStackTrace(); return false; } } /**Attempts to delete a file.*/ public static boolean deleteFile (String fullPathFileName){ return deleteFile(new File(fullPathFileName)); } /**Deletes files in a given directory with a given extension.*/ public static boolean deleteFiles(File directory, String extension){ boolean deleted = true; if (directory.isDirectory()){ String[] files = directory.list(); int num = files.length; try{ String path = directory.getCanonicalPath(); for (int i=0; i< num; i++) { if (files[i].endsWith(extension)) { deleted = new File(path,files[i]).delete(); if (deleted ==false) return false; } } }catch(IOException e){ System.out.println("Prob deleteFiles, dir ->"+directory+" "+extension); e.printStackTrace(); } } else deleted = false; return deleted; } /**Deletes files in a given directory with a given prefix, that are older cutoff.*/ public static void deleteFiles(File directory, String prefix, int minutes){ if (directory.isDirectory()){ long cutoff = minutes*1000*60; long current = System.currentTimeMillis(); cutoff = current - cutoff; File[] files = directory.listFiles(); int num = files.length; for (int i=0; i< num; i++) { if (files[i].getName().startsWith(prefix) && files[i].lastModified()< cutoff) { files[i].delete(); } } } } /**Attempts to delete the array of File.*/ public static boolean deleteFiles (File[] files){ if (files == null) return false; for (int i=0; i< files.length; i++){ boolean deleted = files[i].delete(); if (deleted == false) return false; } return true; } /**Looks in the given directory for files ending with given String and deletes them.*/ public static void deleteFiles (String directory, String endsWith){ File dir = new File (directory); String[] files = dir.list(); int numFiles = files.length; for (int i=0; i< numFiles; i++){ if (files[i].endsWith(endsWith)){ new File (directory, files[i]).delete(); } } } /**Deletes files in a given directory that don't stop in a given extension.*/ public static void deleteFilesNotEndingInExtension(File directory, String extension){ File[] files = directory.listFiles(); for (int i=0; i < files.length; i++){ if (files[i].getName().endsWith(extension) == false) files[i].delete(); } } /**Executes tokenized params on command line, use full paths. * Put each param in its own String. * Returns null if a problem is encountered. */ public static String[] executeCommandLine(String[] command){ ArrayList al = new ArrayList(); try { Runtime rt = Runtime.getRuntime(); //rt.traceInstructions(true); //for debugging //rt.traceMethodCalls(true); //for debugging Process p = rt.exec(command); BufferedReader data = new BufferedReader(new InputStreamReader(p.getInputStream())); //BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream())); //for debugging String line; while ((line = data.readLine()) != null){ al.add(line); } //while ((line = error.readLine()) != null){ // System.out.println(line); //} data.close(); //error.close(); } catch (Exception e) { System.out.println("Problem executingCommandLine(), command -> "+Misc.stringArrayToString(command," ")); e.printStackTrace(); return null; } String[] res = new String[al.size()]; al.toArray(res); return res; } /**Executes tokenized params on command line, use full paths. * Put each param in its own String. * Returns null if a problem is encountered. Does not print any stack trace. Returns the output to standard out and standard error. */ public static String[] executeCommandLineNoError(String[] command){ ArrayList<String> al = new ArrayList<String>(); try { Runtime rt = Runtime.getRuntime(); Process p = rt.exec(command); BufferedReader data = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; while ((line = data.readLine()) != null){ al.add(line); } while ((line = error.readLine()) != null){ al.add(line); } data.close(); error.close(); } catch (Exception e) { return null; } String[] res = new String[al.size()]; al.toArray(res); return res; } /**Executes tokenized params on command line, use full paths. * Put each param in its own String. * Writes lines to a file. */ public static String[] executeCommandLine(String[] command, File txtOutPutFile){ ArrayList al = new ArrayList(); try { Runtime rt = Runtime.getRuntime(); //rt.traceInstructions(true); //for debugging //rt.traceMethodCalls(true); //for debugging Process p = rt.exec(command); BufferedReader data = new BufferedReader(new InputStreamReader(p.getInputStream())); //BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream())); //for debugging PrintWriter out = new PrintWriter( new FileWriter(txtOutPutFile)); String line; while ((line = data.readLine()) != null){ out.println(line); } //while ((line = error.readLine()) != null){ // System.out.println(line); //} out.close(); data.close(); //error.close(); } catch (Exception e) { System.out.println("Problem executingCommandLine(), command -> "+Misc.stringArrayToString(command," ")); e.printStackTrace(); } String[] res = new String[al.size()]; al.toArray(res); return res; } /**Executes tokenized params on command line, use full paths. * Put each param in its own String. * Writes lines to a file. */ public static String[] executeCommandLine(String[] command, File txtOutPutFile, String[] env){ ArrayList<String> al = new ArrayList<String>(); try { Runtime rt = Runtime.getRuntime(); Process p = rt.exec(command, env); BufferedReader data = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream())); //for debugging PrintWriter out = new PrintWriter( new FileWriter(txtOutPutFile)); String line; int counter = 0; while ((line = error.readLine()) != null){ System.out.println(line); } while ((line = data.readLine()) != null){ out.println(line); if (counter++ == 10) break; } out.close(); data.close(); error.close(); } catch (Exception e) { System.out.println("Problem executingCommandLine(), command -> "+Misc.stringArrayToString(command," ")); e.printStackTrace(); } String[] res = new String[al.size()]; al.toArray(res); return res; } /**Executes tokenized params on command line, use full paths. * Put each param in its own String. * Returns null if a problem is encountered. * Returns both error and data from execution. */ public static String[] executeCommandLineReturnAll(String[] command){ ArrayList<String> al = new ArrayList<String>(); try { Runtime rt = Runtime.getRuntime(); Process p = rt.exec(command); //Process p = rt.exec(Misc.stringArrayToString(command, " ")); BufferedReader data = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream())); //for debugging String line; while ((line = data.readLine()) != null){ al.add(line); } while ((line = error.readLine()) != null){ al.add(line); } data.close(); error.close(); } catch (Exception e) { System.out.println("Problem executing -> "+Misc.stringArrayToString(command," ")+" "+e.getLocalizedMessage()); e.printStackTrace(); return null; } String[] res = new String[al.size()]; al.toArray(res); return res; } /**Uses ProcessBuilder to execute a cmd, combines standard error and standard out into one and returns their output.*/ public static String[] executeViaProcessBuilder(String[] command, boolean printToStandardOut){ ArrayList<String> al = new ArrayList<String>(); try { ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(true); Process proc = pb.start(); BufferedReader data = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; while ((line = data.readLine()) != null){ line = line.trim(); if (line.length() !=0) { al.add(line); if (printToStandardOut) System.out.println(line); } } data.close(); } catch (Exception e) { System.err.println("Problem executing -> "+Misc.stringArrayToString(command," ")); e.printStackTrace(); return null; } String[] res = new String[al.size()]; al.toArray(res); return res; } /**Uses ProcessBuilder to execute a cmd, combines standard error and standard out into one and returns and prints their output.*/ public static String[] executeViaProcessBuilder(String[] command, File log){ ArrayList<String> al = new ArrayList<String>(); try { PrintWriter out = new PrintWriter(new FileWriter(log)); ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(true); Process proc = pb.start(); BufferedReader data = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; while ((line = data.readLine()) != null){ al.add(line); out.println(line); out.flush(); } data.close(); out.close(); } catch (Exception e) { System.err.println("Problem executing -> "+Misc.stringArrayToString(command," ")); e.printStackTrace(); return null; } String[] res = new String[al.size()]; al.toArray(res); return res; } /**Uses ProcessBuilder to execute a cmd, combines standard error and standard out into one writes it to file and returns the exit code.*/ public static int executeViaProcessBuilderReturnExit(String[] command, File log){ Process proc = null; PrintWriter out = null; BufferedReader data = null; try { out = new PrintWriter(new FileWriter(log)); ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(true); proc = pb.start(); data = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; while ((line = data.readLine()) != null) { out.println(line); out.flush(); } data.close(); out.close(); int numToWait = 100; while (proc.isAlive()) { Thread.currentThread().sleep(100); if (numToWait-- < 0) throw new Exception("ERROR: Process failed to complete in timely fashion."); } return proc.exitValue(); } catch (Exception e) { try { out.flush(); proc.destroy(); data.close(); out.close(); } catch (IOException e1) {} return 1; } } /**Uses ProcessBuilder to execute a cmd, returns the exit code.*/ public static int executeViaProcessBuilderReturnExit(String[] command){ Process proc = null; try { ProcessBuilder pb = new ProcessBuilder(command); proc = pb.start(); int numToWait = 100000; while (proc.isAlive()) { Thread.currentThread().sleep(100); if (numToWait-- < 0) throw new Exception("ERROR: Process failed to complete in timely fashion."); } return proc.exitValue(); } catch (Exception e) { proc.destroy(); return 1; } } /**Executes tokenized params on command line, use full paths. * Put each param in its own String. * Returns the output, starting with ERROR if it encountered an issue * Returns both error and data from execution. */ public static String executeCommandReturnError(String[] command){ ArrayList<String> al = new ArrayList<String>(); try { Runtime rt = Runtime.getRuntime(); Process p = rt.exec(command); BufferedReader data = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; while ((line = data.readLine()) != null) al.add(line); while ((line = error.readLine()) != null) al.add(line); data.close(); error.close(); } catch (Exception e) { System.err.println("Problem executing -> "+Misc.stringArrayToString(command," ")+" "+e.getLocalizedMessage()); e.printStackTrace(); al.add(0, "ERROR"); } String res = Misc.stringArrayListToString(al, "\n"); return res; } /**Executes a String of shell script commands via a temp file. Only good for Unix.*/ public static String[] executeShellScript (String shellScript, File tempDirectory){ //make shell file File shellFile = new File (tempDirectory, "tempFile_"+Passwords.createRandowWord(10) +".sh"); String fullPath = IO.getFullPathName(shellFile); //write to shell file IO.writeString(shellScript, shellFile); //set permissions for execution String[] cmd = {"chmod", "777", fullPath}; String[] res = IO.executeCommandLineReturnAll(cmd); if (res == null || res.length !=0 ) { //shellFile.delete(); return null; } //execute cmd = new String[]{fullPath}; res = IO.executeCommandLineReturnAll(cmd); //shellFile.delete(); return res; } /**Takes a String, possibly comma delimited, no spaces. Looks for URLs defined by the http prefix, otherwise assumes it's a file, * fetches all files recursively if it is a directory. Set the extension to null if you want everything. "." hidden files are ignored. * Returns null if something bad happened or no files were returned.*/ public static String[] fetchFileURLStrings(String s, String extension){ //attempt to split on , String[] names = COMMA.split(s); //add or attempt to pull file names ArrayList<String> toReturn = new ArrayList<String>(); for (int i=0; i< names.length; i++){ //is it a url? if (names[i].startsWith("http")) { if (extension !=null && names[i].endsWith(extension)) toReturn.add(names[i]); else toReturn.add(names[i]); } else { File[] f = null; if (extension != null) f = fetchFilesRecursively(new File(names[i]), extension); else f = fetchFilesRecursively(new File(names[i])); if (f != null){ for (int x=0; x< f.length; x++) toReturn.add(f[x].toString()); } } } int num = toReturn.size(); if (num == 0) return null; names = new String[num]; toReturn.toArray(names); return names; } /**Extracts the full path file names of all the files and directories in a given directory. If a file is given it is * returned as the File[0]. * Skips files starting with a '.'*/ public static File[] extractFiles(File directory){ try{ directory = directory.getCanonicalFile(); File[] files = null; String[] fileNames; if (directory.isDirectory()){ fileNames = directory.list(); if (fileNames != null) { int num = fileNames.length; ArrayList<File> al = new ArrayList<File>(); String path = directory.getCanonicalPath(); for (int i=0; i< num; i++) { if (fileNames[i].startsWith(".") == false) al.add(new File(path, fileNames[i])); } //convert arraylist to file[] if (al.size() != 0){ files = new File[al.size()]; al.toArray(files); } } } if (files == null){ files = new File[1]; files[0] = directory; } Arrays.sort(files); return files; }catch(IOException e){ System.out.println("Problem extractFiles() "+directory); e.printStackTrace(); return null; } } /**Returns a hash of the directory name and its File object.*/ public static HashMap<String, File> extractDirectories(File directory){ File[] fileNames = directory.listFiles(); HashMap<String, File> toReturn = new HashMap<String, File>(); for (int i=0; i< fileNames.length; i++) { if (fileNames[i].isDirectory() == false) continue; toReturn.put(fileNames[i].getName(), fileNames[i]); } return toReturn; } /**Returns directories or null if none found. Not recursive. * Skips those beginning with a period.*/ public static File[] extractOnlyDirectories(File directory){ if (directory.isDirectory() == false) return null; File[] fileNames = directory.listFiles(); ArrayList<File> al = new ArrayList<File>(); Pattern pat = Pattern.compile("^\\w+.*"); Matcher mat; for (int i=0; i< fileNames.length; i++) { if (fileNames[i].isDirectory() == false) continue; mat = pat.matcher(fileNames[i].getName()); if (mat.matches()) al.add(fileNames[i]); } //convert arraylist to file[] if (al.size() != 0){ File[] files = new File[al.size()]; al.toArray(files); Arrays.sort(files); return files; } else return new File[]{directory}; } /**Returns directories starting with the String. Not recursive.*/ public static ArrayList<File> extractOnlyDirectories(File directory, String startsWith){ if (directory.isDirectory() == false) return null; File[] fileNames = directory.listFiles(); ArrayList<File> al = new ArrayList<File>(); for (int i=0; i< fileNames.length; i++) { if (fileNames[i].isDirectory() == false) continue; if (fileNames[i].getName().startsWith(startsWith)) al.add(fileNames[i]); } return al; } public static void pl(Object obj){ System.out.println(obj.toString()); } public static void p(Object obj){ System.out.print(obj.toString()); } public static void pl(){ System.out.println(); } public static void el(Object obj){ System.err.println(obj.toString()); } /**Creates symbolicLinks in the destinationDir*/ public static void createSymbolicLinks(File[] filesToLink, File destinationDir) throws IOException { //remove any linked files File f = destinationDir.getCanonicalFile(); for (File fn: filesToLink) new File(f, fn.getName()).delete(); //soft link in the new ones for (File fn: filesToLink) { Path real = fn.toPath(); Path link = new File(f, fn.getName()).toPath(); Files.createSymbolicLink(link, real); } } /**Creates symbolicLinks in the destinationDir*/ public static void createSymbolicLinks(ArrayList<File>filesToLink, File destinationDir) throws IOException { File[] toLink = new File[filesToLink.size()]; filesToLink.toArray(toLink); createSymbolicLinks(toLink, destinationDir); } /**Extracts the full path file names of all the files in a given directory with a given extension (ie txt or .txt). * If the dirFile is a file and ends with the extension then it returns a File[] with File[0] the * given directory. Returns null if nothing found. Case insensitive.*/ public static File[] extractFiles(File dirOrFile, String extension){ if (dirOrFile == null || dirOrFile.exists() == false) return null; File[] files = null; Pattern p = Pattern.compile(".*"+extension+"$", Pattern.CASE_INSENSITIVE); Matcher m; if (dirOrFile.isDirectory()){ files = dirOrFile.listFiles(); int num = files.length; ArrayList chromFiles = new ArrayList(); for (int i=0; i< num; i++) { m= p.matcher(files[i].getName()); if (m.matches()) chromFiles.add(files[i]); } files = new File[chromFiles.size()]; chromFiles.toArray(files); } else{ m= p.matcher(dirOrFile.getName()); if (m.matches()) { files=new File[1]; files[0]= dirOrFile; } } if (files != null) Arrays.sort(files); return files; } /**Extracts all files from a comma delimited text of files and directories. * No spaces. Returns null if file.canRead() is false. Not recursive.*/ public static File[] extractFiles(String commaSeparList){ if (commaSeparList == null) return null; String[] items = commaSeparList.split(","); File[] files = new File[items.length]; for (int i=0; i<items.length; i++){ files[i] = new File(items[i]); if (files[i].canRead()==false) return null; } Arrays.sort(files); return files; } /**Extracts all files with a given extension from a comma delimited text of files and directories. * No spaces.*/ public static File[] extractFiles(String commaSeparList, String extension){ ArrayList filesAL = new ArrayList(); String[] items = commaSeparList.split(","); for (int i=0; i<items.length; i++){ File test = new File(items[i]); if (test.canRead()==false) return null; File[] files = extractFiles(test, extension); if (files == null) return null; for (int j=0; j<files.length; j++){ filesAL.add(files[j]); } } File[] collection = new File[filesAL.size()]; filesAL.toArray(collection); return collection; } /**Given full path file or directory names, extracts all files given an extension.*/ public static File[] extractFiles(String[] dirFiles, String extension){ int numDirectories = dirFiles.length; ArrayList celFilesAL = new ArrayList(); String[] fileNames; try{ for (int i=0; i<numDirectories; i++){ File dir = new File(dirFiles[i]); if (dir.isDirectory()){ String path = dir.getCanonicalPath(); fileNames = dir.list(); int num = fileNames.length; for (int j=0; j< num; i++) { if (fileNames[j].endsWith(extension)) celFilesAL.add(new File(path,fileNames[j])); } } else if (dir.isFile() && dir.getName().endsWith(extension)) celFilesAL.add(dir); } }catch(IOException e){ System.out.println("Problem extractFiles() "); e.printStackTrace(); } File[] celFiles = new File[celFilesAL.size()]; celFilesAL.toArray(celFiles); return celFiles; } /**Extracts the full path file names of all the files in a given directory with a given extension.*/ public static File[] extractFilesReturnFiles(File directory, String extension){ String[] files = extractFilesStringNames(directory, extension); int numFiles = files.length; File[] finalFiles = new File[numFiles]; for (int i=0; i<numFiles; i++){ finalFiles[i]= new File(files[i]); } return finalFiles; } /**Extracts the full path file names of all the files in a given directory with a given extension. * If the directory is file and starts with the correct word then it is returned.*/ public static File[] extractFilesStartingWith(File directory, String startingWith){ File[] files = null; ArrayList<File> filesAL = new ArrayList<File>(); if (directory.isDirectory()){ File[] toExamine = directory.listFiles(); for (File f: toExamine){ if (f.getName().startsWith(startingWith)) filesAL.add(f); } files = new File[filesAL.size()]; filesAL.toArray(files); } else if (directory.getName().startsWith(startingWith)) files = new File[]{directory}; return files; } /**Extracts the full path file names of all the files in a given directory with a given extension.*/ public static String[] extractFilesStringNames(File directory, String extension){ String[] files = null; if (directory.isDirectory()){ files = directory.list(); int num = files.length; ArrayList chromFiles = new ArrayList(); try{ String path = directory.getCanonicalPath() + File.separator; for (int i=0; i< num; i++) { if (files[i].endsWith(extension)) chromFiles.add(path+files[i]); } files = new String[chromFiles.size()]; chromFiles.toArray(files); }catch(IOException e){ System.out.println("Problem extractFilesStringNames() "+directory+" "+extension); e.printStackTrace();} } return files; } /**Extracts the full path file names of all the files not directories in a given directory. * Skips files starting with a non word character (e.g. '.', '_', etc). * Returns null if no files found.*/ public static File[] extractOnlyFiles(File directory){ File[] fileNames = directory.listFiles(); if (fileNames == null) return null; ArrayList<File> al = new ArrayList<File>(); Pattern pat = Pattern.compile("^\\w+.*"); Matcher mat; for (int i=0; i< fileNames.length; i++) { if (fileNames[i].isDirectory()) continue; mat = pat.matcher(fileNames[i].getName()); if (mat.matches()) al.add(fileNames[i]); } //convert arraylist to file[] if (al.size() != 0){ File[] files = new File[al.size()]; al.toArray(files); Arrays.sort(files); return files; } else return null; } /**Fetches files that don't start with a '.' from a directory recursing through sub directories.*/ public static ArrayList<File> fetchAllFilesRecursively (File directory){ ArrayList<File> files = new ArrayList<File>(); File[] list = directory.listFiles(); if (list != null){ for (int i=0; i< list.length; i++){ if (list[i].isDirectory()) { ArrayList<File> al = fetchAllFilesRecursively (list[i]); int size = al.size(); for (int x=0; x< size; x++){ File test = al.get(x); if (test.getName().startsWith(".") == false) files.add(test); } } else if (list[i].getName().startsWith(".") == false) files.add(list[i]); } } return files; } /**Fetches files that don't start with a '.' from a directory recursing through sub directories.*/ public static ArrayList<File> fetchFilesDirsRecursively (File directory){ ArrayList<File> files = new ArrayList<File>(); File[] list = directory.listFiles(); if (list != null){ for (int i=0; i< list.length; i++){ if (list[i].isDirectory()) { ArrayList<File> al = fetchAllFilesRecursively (list[i]); al.add(list[i]); int size = al.size(); for (int x=0; x< size; x++){ File test = al.get(x); if (test.getName().startsWith(".") == false) files.add(test); } } else if (list[i].getName().startsWith(".") == false) files.add(list[i]); } } return files; } /**Fetches directories recursively.*/ public static ArrayList<File> fetchDirectoriesRecursively (File directory){ ArrayList<File> dirs = new ArrayList<File>(); File[] list = directory.listFiles(); if (list != null){ for (int i=0; i< list.length; i++){ if (list[i].isDirectory()) { dirs.add(list[i]); dirs.addAll(fetchDirectoriesRecursively(list[i])); } } } return dirs; } /**Fetches directories recursively.*/ public static File[] fetchDirsRecursively (File directory){ ArrayList<File> dirs = fetchDirectoriesRecursively (directory); File[] list = new File[dirs.size()]; dirs.toArray(list); return list; } /**Fetches directories recursively with a given name.*/ public static ArrayList<File> fetchDirectoriesRecursively (File directory, String name){ ArrayList<File> dirs = new ArrayList<File>(); File[] list = directory.listFiles(); if (list != null){ for (int i=0; i< list.length; i++){ if (list[i].isDirectory()) { if (list[i].getName().equals(name))dirs.add(list[i]); dirs.addAll(fetchDirectoriesRecursively(list[i], name)); } } } return dirs; } /**Zips the contents of the provided directory using relative paths.*/ public static boolean zipDirectory(File directory) throws IOException{ String toTrim = directory.getParentFile().getCanonicalPath()+"/"; File zipFile = new File (directory.getCanonicalPath()+".zip"); //overwrites any existing ArrayList<File> filesToZip = fetchAllFilesAndDirsRecursively(directory); byte[] buf = new byte[2048]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); // Compress the files for (int i=0; i<filesToZip.size(); i++) { File f = filesToZip.get(i); String relPath = f.getCanonicalPath().replace(toTrim, ""); if (f.isFile()) { out.putNextEntry(new ZipEntry(relPath)); FileInputStream in = new FileInputStream(f); int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } //for directories add the / else { out.putNextEntry(new ZipEntry(relPath+"/")); out.closeEntry(); } } out.close(); } catch (IOException e) { IO.el("ERROR zip archiving the directory "+directory); zipFile.delete(); e.printStackTrace(); return false; } return true; } /**Zips the contents of the provided directories using relative paths. Make sure your zipFile ends in .zip */ public static boolean zipDirectoriesInSameParentDirectory(File[] dirs, File zipFile) throws IOException{ boolean success = false; ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(zipFile)); byte[] buf = new byte[2048]; for (File d: dirs) { String toTrim = d.getParentFile().getCanonicalPath()+"/"; ArrayList<File> filesToZip = fetchAllFilesAndDirsRecursively(d); // Compress the files with a relative path for (File f: filesToZip) { String relPath = f.getCanonicalPath().replace(toTrim, ""); if (f.isFile()) { out.putNextEntry(new ZipEntry(relPath)); FileInputStream in = new FileInputStream(f); int len; while ((len = in.read(buf)) != -1) out.write(buf, 0, len); out.closeEntry(); in.close(); } //for directories add the / else { out.putNextEntry(new ZipEntry(relPath+"/")); out.closeEntry(); } } } success = true; } catch (IOException e) { IO.el("ERROR zip archiving "+zipFile); zipFile.delete(); e.printStackTrace(); } finally { out.close(); } return success; } /**Fetches all of the files and dirs in the provided directory.*/ public static ArrayList<File> fetchAllFilesAndDirsRecursively (File directory) throws IOException{ ArrayList<File> files = new ArrayList<File>(); files.add(directory.getCanonicalFile()); File[] list = directory.listFiles(); if (list != null){ for (int i=0; i< list.length; i++){ if (list[i].isDirectory()) { ArrayList<File> al = fetchAllFilesAndDirsRecursively (list[i]); files.addAll(al); } else files.add(list[i].getCanonicalFile()); } } return files; } /**Fetch parent directories*/ public static File[] fetchParentDirectories (ArrayList<File> dirs){ File[] p = new File[dirs.size()]; for (int i=0; i< p.length; i++) p[i]=dirs.get(i).getParentFile(); return p; } /**Fetches all files with a given extension in a directory recursing through sub directories. * Will return a file if a file is given with the appropriate extension, or null.*/ public static File[] fetchFilesRecursively (File directory, String extension){ if (directory.isDirectory() == false){ return extractFiles(directory, extension); } ArrayList<File> al = fetchAllFilesRecursively (directory, extension); File[] files = new File[al.size()]; al.toArray(files); return files; } /**Fetches all files with a given extension in a directory recursing through sub directories.*/ public static ArrayList<File> fetchAllFilesRecursively (File directory, String extension){ ArrayList<File> files = new ArrayList<File>(); File[] list = directory.listFiles(); for (int i=0; i< list.length; i++){ if (list[i].isDirectory()) { ArrayList<File> al = fetchAllFilesRecursively (list[i], extension); files.addAll(al); } else{ if (list[i].getName().endsWith(extension)) files.add(list[i]); } } return files; } /**Fetches an ArrayList stored as a serialize object file.*/ public static ArrayList fetchArrayList(File file) { return (ArrayList)fetchObject(file); } /**For each base text (ie /home/data/treat1 ), makes a File object using the chromExtenstion * (ie /home/data/treat1.chromExtension ), if it actually exists, it is saved and a File[] * returned.*/ public static File[] fetchFiles(String[] baseNames, String chromExtension){ ArrayList al = new ArrayList(); //for each base text look for an associated file with the chromExtension for (int x=0; x<baseNames.length; x++){ File f = new File(baseNames[x]+"."+chromExtension); if (f.exists())al.add(f); } File[] files = new File[al.size()]; al.toArray(files); return files; } /**Fetches all files in a directory recursing through sub directories.*/ public static File[] fetchFilesRecursively (File directory){ ArrayList<File> al = fetchAllFilesRecursively (directory); File[] files = new File[al.size()]; al.toArray(files); return files; } /**Loads float[][]s from disk.*/ public static float[][][] fetchFloatFloatArrays(File[] files){ int i=0; try { int num = files.length; float[][][] f = new float[num][][]; for (;i<num; i++){ f[i] = (float[][])IO.fetchObject(files[i]); } return f; } catch (Exception e){ System.out.println("\nError: One of your 'xxx.cela' files does not appear" + " to be a serialized java float[][] array?! -> "+files[i]+"\n"); System.exit(0); } return null; } /**Given a directory, returns a HashMap<String, File> of the containing directories' names and a File obj for the directory. */ public static HashMap<String, File> fetchNamesAndDirectories(File directory){ HashMap<String, File> nameFile = new HashMap<String, File>(); File[] files = IO.extractFiles(directory); for (int i=0; i< files.length; i++){ if (files[i].isDirectory()) nameFile.put(files[i].getName(), files[i]); } return nameFile; } /**Given a directory, returns a HashMap<String, File> of the containing files names and a File obj for the directory. */ public static HashMap<String, File> fetchNamesAndFiles(File directory){ HashMap<String, File> nameFile = new HashMap<String, File>(); File[] files = IO.extractFiles(directory); for (int i=0; i< files.length; i++){ if (files[i].isDirectory() == false) nameFile.put(files[i].getName(), files[i]); } return nameFile; } /**Fetches an Object stored as a serialized file. * Can be zip/gz compressed too.*/ public static Object fetchObject(File file) { Object a = null; try { ObjectInputStream in; if (file.getName().endsWith(".zip")){ ZipFile zf = new ZipFile(file); ZipEntry ze = (ZipEntry) zf.entries().nextElement(); in = new ObjectInputStream( zf.getInputStream(ze)); } else if (file.getName().endsWith(".gz")) { in = new ObjectInputStream(new GZIPInputStream(new FileInputStream(file))); } else in = new ObjectInputStream(new FileInputStream(file)); a = in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("Problem fetchObject() "+file); } return a; } /**Fetches a BufferedReader from a url or file, zip/gz OK.*/ public static BufferedReader fetchBufferedReader(String s){ try { if (s.startsWith("http")) return fetchBufferedReader (new URL(s)); return fetchBufferedReader (new File (s)); } catch (Exception e) { System.out.println("Problem fetching buffered reader fro -> "+s); e.printStackTrace(); } return null; } /**Fetches a BufferedReader from a url, zip/gz OK.*/ public static BufferedReader fetchBufferedReader(URL url) throws IOException{ BufferedReader in = null; InputStream is = url.openStream(); String name = url.toString(); if (name.endsWith(".gz")) { in = new BufferedReader(new InputStreamReader(new GZIPInputStream(is))); } else if (name.endsWith(".zip")){ ZipInputStream zis = new ZipInputStream(is); zis.getNextEntry(); in = new BufferedReader(new InputStreamReader(zis)); } else in = new BufferedReader(new InputStreamReader(is)); return in; } /**Returns a gz zip or straight file reader on the file based on it's extension. * @author davidnix*/ public static BufferedReader fetchBufferedReader( File txtFile) throws IOException{ BufferedReader in; String name = txtFile.getName().toLowerCase(); if (name.endsWith(".zip")) { ZipFile zf = new ZipFile(txtFile); ZipEntry ze = (ZipEntry) zf.entries().nextElement(); in = new BufferedReader(new InputStreamReader(zf.getInputStream(ze))); } else if (name.endsWith(".gz")) { in = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(txtFile)))); } else in = new BufferedReader (new FileReader (txtFile)); return in; } /**Returns a gz zip or straight input strean on the file based on it's extension compression.*/ public static InputStream fetchInputStream( File txtFile) throws IOException{ InputStream in; String name = txtFile.getName().toLowerCase(); if (name.endsWith(".zip")) { ZipFile zf = new ZipFile(txtFile); ZipEntry ze = (ZipEntry) zf.entries().nextElement(); in = zf.getInputStream(ze); } else if (name.endsWith(".gz")) { in = new GZIPInputStream(new FileInputStream(txtFile)); } else in = new FileInputStream(txtFile); return in; } /**Returns a BufferedReader from which you can call readLine() directly from a single entry zipped file without decompressing. * Returns null if there is a problem.*/ public static BufferedReader fetchReaderOnZippedFile (File zippedFile) { try { ZipFile zf = new ZipFile(zippedFile); ZipEntry ze = (ZipEntry) zf.entries().nextElement(); return new BufferedReader(new InputStreamReader(zf.getInputStream(ze))); } catch(Exception e) { e.printStackTrace(); } return null; } /**Returns a BufferedReader from which you can call readLine() directly from a gzipped (.gz) file without decompressing. * Returns null if there is a problem.*/ public static BufferedReader fetchReaderOnGZippedFile (File gzFile) { try { return new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(gzFile)))); } catch(Exception e) { e.printStackTrace(); } return null; } /**Fires qsub with the commands. * @return String beginning with 'Error: ' if the error stream or java bombed. * otherwise it returns a tab delimited list of the output and the qsub parameters. * Will leave the shell file in the temp directory, renamed as the jobNumber.sh * @param qsubParams = '-q queue@loc -l nodes=1' */ public static String fireQSub(String qsubParams, String commands, File tempDir){ //make random word String name = "N"+Passwords.createRandowWord(9); //Create Results directory and files File resultsDirectory = new File (tempDir, "Results"); if (resultsDirectory.exists() == false) resultsDirectory.mkdir(); File launched = new File (resultsDirectory, "L_"+name); File results = new File (resultsDirectory, "E_"+ name); File returned = new File (resultsDirectory, "R_"+name); //create shell script wrapper file StringBuffer shell = new StringBuffer(); shell.append ("echo running >> "); shell.append(launched); shell.append("\n"); shell.append ("date > "); shell.append(results); shell.append("\n"); shell.append (commands); shell.append(" >> "); shell.append(results);shell.append(" 2>> "); shell.append(results); shell.append("\n"); shell.append ("date >> "); shell.append(results); shell.append("\n"); shell.append ("rm "); shell.append(launched); shell.append("\n"); shell.append ("mv "); shell.append(results); shell.append(" "); shell.append(returned); shell.append("\n"); //QSub messages File qsubDir = new File (tempDir, "QSub"); if (qsubDir.exists() == false) qsubDir.mkdir(); String qsub = "qsub "+"-N "+name+" -j oe -o "+qsubDir+" "+qsubParams; //Save in shell directory File shellDirectory = new File(tempDir,"ShellScripts"); if (shellDirectory.exists() == false) shellDirectory.mkdir(); File shellFile = new File(shellDirectory,name +".sh"); writeString(shell.toString(), shellFile); //write command line to launched writeString(qsub+" "+shellFile+"\n", launched); try { //fire shell script Runtime rt = Runtime.getRuntime(); //System.out.println("\nFiring: "+qsub+shellFile+ "\n"); Process p = rt.exec(qsub +shellFile); BufferedReader data = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; //collect potential error ArrayList errorAL = new ArrayList(); while ((line = error.readLine()) != null){ errorAL.add(line); } if (errorAL.size()!=0){ data.close(); error.close(); Misc.printExit("Error: "+Misc.stringArrayListToString(errorAL, "\n") +"\n"+ commands +"\n"+ qsub+" "+shellFile); } //collect output of firing qsub ArrayList dataAL = new ArrayList(); while ((line = data.readLine()) != null){ dataAL.add(line); } //close handles data.close(); error.close(); //get job text String job = ((String)dataAL.get(0)).replaceAll("\\.cluster.+",""); return name+"\t"+job; } catch (Exception e){ return "Error: "+ e; } } /**Fires qsub with the commands, will wait and return results and delete x.sh and the output files if you like. * Be sure to put an stop of line '\n' after each command.*/ public static String[] fireQSub(String queue, String commands, String fullPathToTempDir, boolean waitAndClean){ //create shell script wrapper file String name = "tmp"+Passwords.createRandowWord(6); String shell = "#!/bin/sh \n" + "#$ -N "+name+" \n" + "#$ -j oe \n" + "#$ -o "+fullPathToTempDir+" \n"+ "#$ -q "+queue+" \n"+ "#$ -l nodes=1 \n"+ commands+" \n" + "echo \"Finished!\"\n"; System.out.print(shell); //System.exit(0); File shellFile = new File(fullPathToTempDir,name +".sh"); writeString(shell, shellFile); //fire shell script try { Runtime rt = Runtime.getRuntime(); Process p = rt.exec("qsub "+shellFile); System.out.println("Fired qsub"); //check if user wants to wait for results and clean up files if (waitAndClean == false) return null; //Wait 5min then check for file and for Finished! boolean wait = true; File dir = new File(fullPathToTempDir); File outputFile = null; long counter =0; long milSec = 30000; //checking every 30 sec ArrayList dataArrayList = new ArrayList(1000); System.out.print("Waiting"); while (wait){ Thread.sleep(milSec); //find file if (outputFile==null){ //fetch contents of directory String[] fileNames = dir.list(); //run through each file for (int i= fileNames.length-1; i>=0; i--){ if (fileNames[i].startsWith(name+".o")) { //the qsub output file MemeR1081900495429.o50151 outputFile = new File(fullPathToTempDir, fileNames[i]); System.out.println("\nFound results file: "+outputFile.getName()); break; } } } if (outputFile!=null){ //check if null again //check if the last line is "Finnished!" String lastLine = ""; String line; dataArrayList.clear(); BufferedReader in = new BufferedReader(new FileReader(outputFile)); while ((line = in.readLine()) !=null) { lastLine= line; dataArrayList.add(line); } in.close(); //System.out.println("\nLast line is : "+lastLine); if (lastLine.startsWith("Finished!") || lastLine.startsWith("cd: Too many arguments")) wait=false; //stop found exit wait loop } //put break in so thread will stop after a very long time. counter++; System.out.print("."); if (counter>57600000) { //16hrs 57600000 System.out.println("\n Error: shell script failed to return from qsub after "+counter/60000+ " minutes.\nFind and kill the job: (text Nix, process number is the last digits after the .o in -> "+outputFile.getName()); System.exit(1); } } System.out.println("\nResults are ready!"); //delete files String[] fileNames = dir.list(); //run through each file for (int i= fileNames.length-1; i>=0; i--){ if (fileNames[i].startsWith(name)) { //the qsub output file MemeR1081900495429.o50151 new File(fullPathToTempDir, fileNames[i]).delete(); System.out.println("Deleting-> "+fileNames[i]); } } System.out.println("Time for run: "+(counter*(milSec/1000))+" seconds\n"); //return program output dataArrayList.trimToSize(); String[] x = new String[dataArrayList.size()]; dataArrayList.toArray(x); return x; } catch (Exception e){ System.out.println("Problem with fireQSub()"); e.printStackTrace(); } return null; } /**Gets full path text using getCanonicalPath() on a File*/ public static String getFullPathName(File fileDirectory){ String full = null; try { full = fileDirectory.getCanonicalPath(); }catch (IOException e){ System.out.println("Problem with getFullPathtName(), "+fileDirectory); e.printStackTrace(); } return full; } /**Fetches and truncates common chars, from file names, front and back, uses getName() so no path info is involved.*/ public static String[] getTruncatedNames(File[] files){ String[] names = new String[files.length]; for (int i=0; i< names.length; i++){ names[i] = files[i].getName(); } names = Misc.trimCommon(names); return names; } /**Fetches and truncates common chars, from file names, front and back, uses getName() so no path info is involved.*/ public static String[][] getTruncatedNames(File[][] files){ //collapse to single array ArrayList names = new ArrayList(); for (int i=0; i< files.length; i++){ for (int j=0; j< files[i].length; j++){ names.add(files[i][j].getName()); } } //trim edges and break into original structure String[] trimmed = new String[names.size()]; names.toArray(trimmed); trimmed = Misc.trimCommon(trimmed); String[][] finalTrimmed = new String[files.length][]; int index = 0; for (int i=0; i< files.length; i++){ finalTrimmed[i] = new String[files[i].length]; for (int j=0; j< files[i].length; j++){ finalTrimmed[i][j] = trimmed[index++]; } } return finalTrimmed; } /**Loads a file's lines into a String[], will save blank lines. gz/zip OK*/ public static String[] loadFile(File file){ ArrayList<String> a = new ArrayList<String>(); try{ BufferedReader in = IO.fetchBufferedReader(file); String line; while ((line = in.readLine())!=null){ line = line.trim(); a.add(line); } in.close(); }catch(Exception e){ System.out.println("Prob loadFileInto String[]"); e.printStackTrace(); } String[] strings = new String[a.size()]; a.toArray(strings); return strings; } /**Loads a file's lines into a String, will save blank lines. gz/zip OK.*/ public static String loadFile(File file, String seperator, boolean trimLeadingTrailing){ StringBuilder sb = new StringBuilder(); try{ BufferedReader in = IO.fetchBufferedReader(file); String line; while ((line = in.readLine())!=null){ if (trimLeadingTrailing) line = line.trim(); sb.append(line); sb.append(seperator); } in.close(); }catch(Exception e){ System.out.println("Prob loadFileInto String "+file); e.printStackTrace(); } return sb.toString(); } /**Loads a file's lines into a hash first column is the key, second the value. * */ public static HashMap<String,String> loadFileIntoHashMap(File file){ HashMap<String,String> names = new HashMap<String,String>(1000); try{ BufferedReader in = IO.fetchBufferedReader(file); String line; String[] keyValue; while ((line = in.readLine())!=null){ keyValue = line.split("\\s+"); if (keyValue.length !=2 || keyValue[0].startsWith("#")) continue; names.put(keyValue[0].trim(), keyValue[1].trim()); } in.close(); }catch(Exception e){ System.out.println("Prob loadFileInttoHash()"); e.printStackTrace(); } return names; } /**Loads a file's lines into a hash first column is the key, second the value. Splits on tab. * Keeps first key. If value is a duplicate, it is appended with the unique key and separated by the delimiter. * Thus both the keys and the values are unique. * Keys and values are trims keys and values of whitespace. * @return null if an error is encountered. * */ public static HashMap<String,String> loadFileIntoHashMapUniqueValues(File file, String duplicateValueDelimiter){ HashMap<String,String> names = new HashMap<String,String>(1000); try{ BufferedReader in = IO.fetchBufferedReader(file); String line; String[] keyValue; HashSet<String> values = new HashSet<String>(); HashMap<String, String> keyDupValues = new HashMap<String, String>(); while ((line = in.readLine())!=null){ keyValue = Misc.TAB.split(line); if (keyValue.length !=2 || keyValue[0].startsWith("#")) continue; String key = keyValue[0].trim(); if (key.length()==0)continue; //check if key is already present if (names.containsKey(key)) { IO.el("\tDup key, skipping -> "+line); continue; } //check if value is a duplicate String value = keyValue[1].trim(); if (value.length()==0)continue; if (values.contains(value)) keyDupValues.put(key, value); else values.add(value); //always add irregardless of value duplicates names.put(key, value); } //for each duplicate value, append the key and replace them in the names hashmap for (String key: keyDupValues.keySet()) { String dupValue = keyDupValues.get(key); dupValue = dupValue+ duplicateValueDelimiter+ key; names.put(key, dupValue); IO.el("\tDup value, appending key to value -> "+key+"\t"+dupValue); } in.close(); }catch(Exception e){ e.printStackTrace(); names = null; } return names; } /**Loads a file's lines into a hash first column is the key, second the value. * */ public static HashMap<String,String> loadFileIntoHashMapLowerCaseKey(File file){ HashMap<String,String> names = new HashMap<String,String>(1000); try{ BufferedReader in = IO.fetchBufferedReader(file); String line; String[] keyValue; while ((line = in.readLine())!=null){ keyValue = line.trim().split("\\s+"); if (keyValue.length !=2 || keyValue[0].startsWith("#")) continue; names.put(keyValue[0].trim().toLowerCase(), keyValue[1].trim()); } in.close(); }catch(Exception e){ System.out.println("Prob loadFileInttoHash()"); e.printStackTrace(); } return names; } /**Loads a file's lines into a hash first column is the key, second the value. * */ public static HashMap<String,Integer> loadFileIntoHashMapStringInteger(File file){ HashMap<String,Integer> names = new HashMap<String,Integer>(1000); try{ BufferedReader in = IO.fetchBufferedReader(file); String line; String[] keyValue; while ((line = in.readLine())!=null){ keyValue = line.split("\\s+"); if (keyValue.length !=2 || keyValue[0].startsWith("#")) continue; names.put(keyValue[0].trim(), new Integer(keyValue[1].trim())); } in.close(); }catch(Exception e){ System.out.println("Prob loadFileInttoHash()"); e.printStackTrace(); } return names; } /**Loads a file's lines into a hash splitting on tab, using the designated keys. Returns null if a problem.*/ public static HashMap<String,String> loadFileIntoHash(File file, int keyIndex, int valueIndex){ HashMap<String,String> names = new HashMap<String,String>(1000); BufferedReader in = null; try{ in = IO.fetchBufferedReader(file); String line; String[] fields; while ((line = in.readLine())!=null){ line = line.trim(); if (line.length()==0 || line.startsWith("#")) continue; fields = Misc.TAB.split(line); names.put(fields[keyIndex].trim(), fields[valueIndex].trim()); } in.close(); }catch(Exception e){ e.printStackTrace(); names = null; } finally { IO.closeNoException(in); } return names; } /**Loads a file's lines into a hash set, keys only.*/ public static HashSet<String> loadFileIntoHashSet(File file){ HashSet<String> names = new HashSet(10000); try{ BufferedReader in = fetchBufferedReader(file); String line; while ((line = in.readLine())!=null){ line = line.trim(); if (line.length() ==0) continue; names.add(line); } in.close(); }catch(Exception e){ System.out.println("Prob loadFileInttoHash()"); e.printStackTrace(); } return names; } /**Loads a file's lines into a hash set, counts duplicates.*/ public static HashMap<String, Integer> loadFileIntoHashMapCounter(File file){ HashMap<String,Integer> names = new HashMap<String,Integer>(10000); try{ BufferedReader in = fetchBufferedReader(file); String line; while ((line = in.readLine())!=null){ line = line.trim(); if (line.length() ==0) continue; Integer i = names.get(line); if (i == null) names.put(line, new Integer(1)); else names.put(line, new Integer(i.intValue() + 1)); } in.close(); }catch(Exception e){ System.out.println("Prob loadFileInttoHash()"); e.printStackTrace(); } return names; } /**Loads a file's lines into a hash.*/ public static HashSet loadFileIntoHashSplitLines(File file){ HashSet names = new HashSet(10000); try{ BufferedReader in = fetchBufferedReader(file); String line; String[] tokens; while ((line = in.readLine())!=null){ line = line.trim(); tokens = line.split("\\s+"); if (tokens.length ==0) continue; for (int i=0; i< tokens.length; i++) names.add(tokens[i]); } in.close(); }catch(Exception e){ System.out.println("Prob loadFileInttoHashSplitLines()"); e.printStackTrace(); } return names; } /**Loads a file's lines into a linked hash set, keys only.*/ public static LinkedHashSet loadFileIntoLinkedHashSet(File file){ LinkedHashSet names = new LinkedHashSet(10000); try{ BufferedReader in = fetchBufferedReader(file); String line; while ((line = in.readLine())!=null){ line = line.trim(); if (line.length() ==0) continue; names.add(line); } in.close(); }catch(Exception e){ System.out.println("Prob loadFileIntoLinkedHashSet()"); e.printStackTrace(); } return names; } /**Loads a file's lines into a String[] trimming blank lines and beginning and ending whitespace.*/ public static String[] loadFileIntoStringArray(File file){ ArrayList a = new ArrayList(); try{ BufferedReader in = fetchBufferedReader(file); String line; while ((line = in.readLine())!=null){ line = line.trim(); if (line.length() ==0) continue; a.add(line); } }catch(Exception e){ System.out.println("Prob loadFileInto String[]"); e.printStackTrace(); } String[] strings = new String[a.size()]; a.toArray(strings); return strings; } /**Loads a tab delimited file into a LinkedHashMap where each line is broken into cells and loaded into * a LinkedHashMap where the cells are the keys and the value is the line.*/ public static LinkedHashMap loadHash (File tabDelimited){ LinkedHashMap hash = new LinkedHashMap(); try{ BufferedReader in = fetchBufferedReader(tabDelimited); String line; String[] cells; Pattern pat = Pattern.compile("\\s"); //run through each line while ((line = in.readLine()) != null){ String trimmedLine = new String (line.trim()); if (trimmedLine.length() == 0 || trimmedLine.startsWith("#")) continue; cells = pat.split(trimmedLine); //only add cells that are unique to big hash HashSet unique = new HashSet(); for (int i=0; i< cells.length; i++){ //is it blank? cells[i] = cells[i].trim(); if (cells[i].length() == 0) continue; //is it unique? if (unique.contains(cells[i]) == false){ //add to hash unique.add(cells[i]); //add to big hash only if it isn't present, throw warning if present if (hash.containsKey(cells[i])) { System.err.println("Warning: duplicate key found!\n\tLine -> "+line +"\n\tKey -> "+cells[i]); } else hash.put(cells[i], trimmedLine); } } } in.close(); } catch (Exception e){ e.printStackTrace(); return null; } return hash; } /**Loads a key = value containing text file into a LinkedHashMap. * Strips all white space, ignores lines beginning with / or #. * Ignores blank lines.*/ public static LinkedHashMap loadKeyValueFile(File file){ LinkedHashMap map = new LinkedHashMap(); try{ BufferedReader in = fetchBufferedReader(file); String line; Pattern comment = Pattern.compile("^[/|#].*"); Pattern whiteSpace = Pattern.compile("\\s+"); Pattern equal = Pattern.compile("="); while ((line = in.readLine())!=null){ line = line.trim(); //ignore blank lines and comment lines '// or #' if (line.length() == 0 || comment.matcher(line).matches()) continue; //strip white space line = whiteSpace.matcher(line).replaceAll(""); //split and put String[] keyValue = equal.split(line); if (keyValue.length !=2) continue; map.put(keyValue[0], keyValue[1]); } }catch(Exception e){ System.out.println("Prob with loadKeyValueFile()"); e.printStackTrace(); } return map; } /**Loads a key value containing text file into a LinkedHashMap. * Ignores lines beginning with / or #. * Ignores blank lines. * Splits on spaces/ tabs thus no spaces within key or value. * Returns null if split keyValue number is != 2.*/ public static LinkedHashMap loadKeyValueSpaceTabDelimited(File file, boolean printErrorMessages){ LinkedHashMap map = new LinkedHashMap(); try{ BufferedReader in = fetchBufferedReader(file); String line; Pattern comment = Pattern.compile("^[/|#].*"); Pattern whiteSpace = Pattern.compile("\\s+"); while ((line = in.readLine())!=null){ line = line.trim(); //ignore blank lines and comment lines '// or #' if (line.length() == 0 || comment.matcher(line).matches()) continue; //split and put String[] keyValue = whiteSpace.split(line); if (keyValue.length !=2) { if (printErrorMessages) System.err.println("Cannot parse line -> "+line); return null; } map.put(keyValue[0], keyValue[1]); } }catch(Exception e){ if (printErrorMessages) e.printStackTrace(); } return map; } /**Loads a tab delimited file containing ints into an int[columns][rows], all lines included, assumes no missing values.*/ public static int[][] loadTableOfInts (File file){ int[][] columnsRows = null; try{ BufferedReader in = fetchBufferedReader(file); //read first line String line=in.readLine(); if (line == null) return null; String[] tokens = line.split("\\t"); //find number columns int numColumns = tokens.length; //find number of rows int numRows = (int)IO.countNumberOfLines(file); columnsRows = new int[numColumns][numRows]; //assign first row to table int y=0; for (int x =0; x< numColumns; x++) columnsRows[x][y] = Integer.parseInt(tokens[x]); y++; //load other rows to table for (; y< numRows; y++){ line=in.readLine(); tokens = line.split("\\t"); for (int x =0; x< numColumns; x++) columnsRows[x][y] = Integer.parseInt(tokens[x]); } in.close(); } catch (Exception e){ System.out.println("Problem loading table"); e.printStackTrace(); } return columnsRows; } /**Loads a tab delimited file containing double into an double[columns][rows], all lines included, assumes no missing values. No headers please.*/ public static double[][] loadTableOfDoubles (File file){ double[][] columnsRows = null; try{ BufferedReader in = fetchBufferedReader(file); //read first line String line=in.readLine(); if (line == null) return null; String[] tokens = line.split("\\t"); //find number columns int numColumns = tokens.length; //find number of rows int numRows = (int)IO.countNumberOfLines(file); columnsRows = new double[numColumns][numRows]; //assign first row to table int y=0; for (int x =0; x< numColumns; x++) columnsRows[x][y] = Double.parseDouble(tokens[x]); y++; //load other rows to table for (; y< numRows; y++){ line=in.readLine(); tokens = line.split("\\t"); for (int x =0; x< numColumns; x++) columnsRows[x][y] = Double.parseDouble(tokens[x]); } in.close(); } catch (Exception e){ System.out.println("Problem loading table"); e.printStackTrace(); } return columnsRows; } /**Attempts to make a file and return it's canonical path text (full path text).*/ public static String makeFullPathName(String resultsDirectory, String fileName){ File dump = new File(resultsDirectory, fileName); String fullPathName = ""; try{ fullPathName = dump.getCanonicalPath(); } catch (IOException e){ System.out.println("Problem building text to write files!"); e.printStackTrace(); } return fullPathName; } /**Returns a HashMap of the file text sans extension and the file. * Returns null if duplicate text is found.*/ public static HashMap makeNameFileHash(File[] files){ HashMap hash = new HashMap(); for (int i=0; i< files.length; i++){ String name = Misc.removeExtension(files[i].getName()); if (hash.containsKey(name)) return null; hash.put(name, files[i]); } return hash; } /**Returns the number of files that stop with the given extension.*/ public static int numberFilesExist(File directory, String extension){ String[] fileNames = directory.list(); int num = 0; for (int i=0; i< fileNames.length; i++){ if (fileNames[i].endsWith(extension)) num++; } return num; } /**Returns the number of files that exist in the array.*/ public static int numberFilesExist(File[] f){ int num =0; for (int i=0; i< f.length; i++) if (f[i].exists()) num++; return num; } /**Parses the indexed column of a tab delimited file, all lines included. * Will return an empty String if index column doesn't exist*/ public static String[] parseColumn (File file, int index){ ArrayList al = new ArrayList(); try{ BufferedReader in = new BufferedReader (new FileReader(file)); String line; String[] tokens; while ((line=in.readLine()) != null){ tokens = line.split("\\t"); if (tokens.length <= index) al.add(""); else al.add(tokens[index].trim()); } in.close(); } catch (Exception e){ e.printStackTrace(); Misc.printExit("\nError: problem parsing matcher file, aborting.\n"); } String[] col = new String[al.size()]; al.toArray(col); return col; } /**Parses the indexed columns of a tab delimited file, all lines included. * Will return an empty String if index column doesn't exist, separates values with a tab. * Skips # comment lines.*/ public static String[] parseColumns (File file, int[] indexes){ ArrayList<String> al = new ArrayList<String>(); try{ BufferedReader in = IO.fetchBufferedReader(file); String line; String[] tokens; while ((line=in.readLine()) != null){ if (line.startsWith("#")) continue; tokens = Misc.TAB.split(line); //for each column StringBuilder sb = new StringBuilder(tokens[indexes[0]]); for (int i=1; i< indexes.length; i++){ sb.append("\t"); sb.append(tokens[indexes[i]]); } al.add(sb.toString()); } in.close(); } catch (Exception e){ e.printStackTrace(); Misc.printExit("\nError: problem extracting columns from "+file+", aborting.\n"); } String[] col = new String[al.size()]; al.toArray(col); return col; } /**Parses a tab delimited file, the indexed column is used as the key, * the entire line as the value, blank lines skipped, returns null if * a duplicate key is found.*/ public static HashMap parseFile (File file, int index, boolean ignoreDuplicateKeys){ HashMap al = new HashMap(); String line = null; try{ BufferedReader in = fetchBufferedReader(file); String[] tokens; while ((line=in.readLine()) != null){ line = line.trim(); if (line.length() == 0) continue; tokens = line.split("\\t"); String item = tokens[index].trim(); if (ignoreDuplicateKeys) al.put(item, line); else if (al.containsKey(item)) throw new Exception("Duplicate found for -> "+tokens[index]); else al.put(item, line); } in.close(); } catch (Exception e){ e.printStackTrace(); System.err.println("\nError: problem parsing file to hash. Line -> "+line); return null; } return al; } /**Parses a tab delimited file, the indexed column is used as the key, * the entire line as the value, blank lines skipped, removes duplicate keys.*/ public static HashMap parseUniqueKeyFile (File file, int index){ HashMap al = new HashMap(); String line = null; try{ BufferedReader in = fetchBufferedReader(file); HashSet<String> badKeys = new HashSet<String>(); String[] tokens; while ((line=in.readLine()) != null){ line = line.trim(); if (line.length() == 0) continue; tokens = line.split("\\t"); String item = tokens[index].trim(); if(al.containsKey(item)) badKeys.add(item); else al.put(item, line); } //remove bad keys for (String baddie: badKeys) al.remove(baddie); if (badKeys.size()!=0) System.err.println("Dropped duplicate keys -> "+badKeys); in.close(); } catch (Exception e){ e.printStackTrace(); System.err.println("\nError: problem parsing file to hash."); return null; } return al; } /**Removes the extension from each File in the directory.*/ public static void removeExtension(File directory, String extension){ File[] files = directory.listFiles(); for (int i=0; i < files.length; i++){ String name = files[i].getName(); if (name.endsWith(extension)) { int index = name.lastIndexOf(extension); name = name.substring(0,index); File renamed = new File (directory, name); files[i].renameTo(renamed); } } } /**Renames files containing the toReplace with replaceWith using String.replaceAll(String, String)*/ public static void renameFiles(File directory, String toReplace, String replaceWith){ File[] files = directory.listFiles(); for (int i=0; i< files.length; i++){ String name = files[i].getName(); String changed = name.replaceAll(toReplace,replaceWith); if (name.equals(changed) == false) files[i].renameTo(new File (files[i].getParent()+File.separator+changed)); } } public static boolean saveObject(File file, Object ob) { try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file)); out.writeObject(ob); out.close(); return true; } catch (Exception e) { System.out.println("There appears to be a problem with saving this file: "+ file); e.printStackTrace(); } return false; } /**Writes each element of an Arraylist on a seperate line to a file.*/ public static boolean writeArrayList(ArrayList al, File file){ try{ PrintWriter out = new PrintWriter(new FileWriter(file)); int num = al.size(); for (int i=0; i<num; i++){ out.println(al.get(i)); } out.close(); }catch (Exception e){ e.printStackTrace(); return false; } return true; } /**Writes each key tab value on a separate line to the file.*/ public static boolean writeHashMap(HashMap hashMap, File file){ try{ PrintWriter out = new PrintWriter(new FileWriter(file)); Iterator it = hashMap.keySet().iterator(); while (it.hasNext()){ Object obj = it.next(); out.println(obj+"\t"+hashMap.get(obj)); } out.close(); }catch (Exception e){ e.printStackTrace(); return false; } return true; } /**Writes each key tab value on a separate line to the file.*/ public static boolean writeHashSet(HashSet set, File file){ try{ PrintWriter out = new PrintWriter(new FileWriter(file)); Iterator it = set.iterator(); while (it.hasNext()){ out.println(it.next()); } out.close(); }catch (Exception e){ e.printStackTrace(); return false; } return true; } /**Checks to see if the browser sending the request is from a windows machine. * If so it converts the file text dividers to unix. * In either case, replaces any spaces with underscores.*/ public static String winFileConvert(String fileName, HttpServletRequest request){ String name = fileName; if (request.getHeader("user-agent").indexOf("Win")!=-1){ int index = fileName.lastIndexOf("\\"); name = fileName.substring(index+1); } return name.replaceAll(" ","_"); } /**Writes a String to disk. */ public static boolean writeString(String data, File file) { try { PrintWriter out = new PrintWriter(new FileWriter(file)); out.print(data); out.close(); return true; } catch (IOException e) { System.out.println("Problem writing String to disk!"); e.printStackTrace(); return false; } } /**Writes a String to disk.*/ public static boolean writeString(String data, String fullPathFileName) { return writeString(data, new File(fullPathFileName)); } /**Writes a String onto the stop of a file. * No need to add a \n onto the final stop. */ public static boolean writeStringAppend(String data, File file) { try { PrintWriter out = new PrintWriter(new FileWriter(file, true)); out.print(data); out.close(); return true; } catch (IOException e) { System.out.println("Problem writing String to disk!"); e.printStackTrace(); return false; } } /**Zip compress a single file.*/ public static boolean zip(File fileToZip, File zipFile){ File[] file = new File[1]; file[0]= fileToZip; return zip(file, zipFile); } /**Zip compresses an array of Files, be sure to text your zipFile with a .zip extension!*/ public static boolean zip(File[] filesToZip, File zipFile ){ byte[] buf = new byte[2048]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); // Compress the files for (int i=0; i<filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); out.putNextEntry(new ZipEntry(filesToZip[i].getName())); int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); } catch (IOException e) { System.err.println("Can't zip()"); e.printStackTrace(); return false; } return true; } /**Zip compresses the file and if sucessful, then deletes the original file.*/ public static boolean zipAndDelete(File f){ File zip = null; try { //make new file with .zip extension zip = new File(f.getCanonicalPath()+".zip"); //zip it and delete original if (IO.zip(f, zip)) { f.delete(); return true; } else { zip.delete(); return false; } } catch (Exception e){ e.printStackTrace(); zip.delete(); return false; } } /**Returns the contents of a zipped file. Returns null if there is a problem.*/ public static String[] zippedFile2StringArray(File zippedFile){ try { BufferedReader in = fetchReaderOnZippedFile(zippedFile); ArrayList al = new ArrayList(); String line = null; while ((line= in.readLine()) !=null) al.add(line); return Misc.stringArrayListToStringArray(al); } catch(Exception e) { e.printStackTrace(); } return null; } public static void deleteZeroSizedFiles(File[] alignments) { for (File f: alignments) { if (f.exists()){ if (f.getName().endsWith(".gz") && f.length() <= 20) f.delete(); else if (f.length() == 0 ) f.delete(); } } } public static void closeNoException(BufferedReader in) { try { in.close(); } catch (IOException e) { } } public static void closeNoException(PrintWriter out) { try { out.close(); } catch (Exception e) { } } public static double gigaBytes(File file) { double bytes = file.length(); double kilobytes = (bytes / 1024); double megabytes = (kilobytes / 1024); double gigabytes = (megabytes / 1024); return gigabytes; } /**Return's path or null, traps error, prints stacktrace.*/ public static String getCanonicalPath(File saveDir) { // TODO Auto-generated method stub try { return saveDir.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); return null; } } }
HuntsmanCancerInstitute/USeq
Source/util/gen/IO.java
249,363
/* * @(#)FeatureDescriptor.java 1.35 10/03/23 * * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.beans; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.ref.SoftReference; /** * The FeatureDescriptor class is the common baseclass for PropertyDescriptor, * EventSetDescriptor, and MethodDescriptor, etc. * <p> * It supports some common information that can be set and retrieved for * any of the introspection descriptors. * <p> * In addition it provides an extension mechanism so that arbitrary * attribute/value pairs can be associated with a design feature. */ public class FeatureDescriptor { private Reference classRef; /** * Constructs a <code>FeatureDescriptor</code>. */ public FeatureDescriptor() { } /** * Gets the programmatic name of this feature. * * @return The programmatic name of the property/method/event */ public String getName() { return name; } /** * Sets the programmatic name of this feature. * * @param name The programmatic name of the property/method/event */ public void setName(String name) { this.name = name; } /** * Gets the localized display name of this feature. * * @return The localized display name for the property/method/event. * This defaults to the same as its programmatic name from getName. */ public String getDisplayName() { if (displayName == null) { return getName(); } return displayName; } /** * Sets the localized display name of this feature. * * @param displayName The localized display name for the * property/method/event. */ public void setDisplayName(String displayName) { this.displayName = displayName; } /** * The "expert" flag is used to distinguish between those features that are * intended for expert users from those that are intended for normal users. * * @return True if this feature is intended for use by experts only. */ public boolean isExpert() { return expert; } /** * The "expert" flag is used to distinguish between features that are * intended for expert users from those that are intended for normal users. * * @param expert True if this feature is intended for use by experts only. */ public void setExpert(boolean expert) { this.expert = expert; } /** * The "hidden" flag is used to identify features that are intended only * for tool use, and which should not be exposed to humans. * * @return True if this feature should be hidden from human users. */ public boolean isHidden() { return hidden; } /** * The "hidden" flag is used to identify features that are intended only * for tool use, and which should not be exposed to humans. * * @param hidden True if this feature should be hidden from human users. */ public void setHidden(boolean hidden) { this.hidden = hidden; } /** * The "preferred" flag is used to identify features that are particularly * important for presenting to humans. * * @return True if this feature should be preferentially shown to human users. */ public boolean isPreferred() { return preferred; } /** * The "preferred" flag is used to identify features that are particularly * important for presenting to humans. * * @param preferred True if this feature should be preferentially shown * to human users. */ public void setPreferred(boolean preferred) { this.preferred = preferred; } /** * Gets the short description of this feature. * * @return A localized short description associated with this * property/method/event. This defaults to be the display name. */ public String getShortDescription() { if (shortDescription == null) { return getDisplayName(); } return shortDescription; } /** * You can associate a short descriptive string with a feature. Normally * these descriptive strings should be less than about 40 characters. * @param text A (localized) short description to be associated with * this property/method/event. */ public void setShortDescription(String text) { shortDescription = text; } /** * Associate a named attribute with this feature. * * @param attributeName The locale-independent name of the attribute * @param value The value. */ public void setValue(String attributeName, Object value) { if (table == null) { table = new java.util.Hashtable(); } table.put(attributeName, value); } /** * Retrieve a named attribute with this feature. * * @param attributeName The locale-independent name of the attribute * @return The value of the attribute. May be null if * the attribute is unknown. */ public Object getValue(String attributeName) { if (table == null) { return null; } return table.get(attributeName); } /** * Gets an enumeration of the locale-independent names of this * feature. * * @return An enumeration of the locale-independent names of any * attributes that have been registered with setValue. */ public java.util.Enumeration<String> attributeNames() { if (table == null) { table = new java.util.Hashtable(); } return table.keys(); } /** * Package-private constructor, * Merge information from two FeatureDescriptors. * The merged hidden and expert flags are formed by or-ing the values. * In the event of other conflicts, the second argument (y) is * given priority over the first argument (x). * * @param x The first (lower priority) MethodDescriptor * @param y The second (higher priority) MethodDescriptor */ FeatureDescriptor(FeatureDescriptor x, FeatureDescriptor y) { expert = x.expert | y.expert; hidden = x.hidden | y.hidden; preferred = x.preferred | y.preferred; name = y.name; shortDescription = x.shortDescription; if (y.shortDescription != null) { shortDescription = y.shortDescription; } displayName = x.displayName; if (y.displayName != null) { displayName = y.displayName; } classRef = x.classRef; if (y.classRef != null) { classRef = y.classRef; } addTable(x.table); addTable(y.table); } /* * Package-private dup constructor * This must isolate the new object from any changes to the old object. */ FeatureDescriptor(FeatureDescriptor old) { expert = old.expert; hidden = old.hidden; preferred = old.preferred; name = old.name; shortDescription = old.shortDescription; displayName = old.displayName; classRef = old.classRef; addTable(old.table); } private void addTable(java.util.Hashtable t) { if (t == null) { return; } java.util.Enumeration keys = t.keys(); while (keys.hasMoreElements()) { String key = (String)keys.nextElement(); Object value = t.get(key); setValue(key, value); } } // Package private methods for recreating the weak/soft referent void setClass0(Class cls) { classRef = createReference(cls); } Class getClass0() { return (Class)getObject(classRef); } /** * Create a Reference wrapper for the object. * * @param obj object that will be wrapped * @param soft true if a SoftReference should be created; otherwise Soft * @return a Reference or null if obj is null. */ static Reference createReference(Object obj, boolean soft) { Reference ref = null; if (obj != null) { if (soft) { ref = new SoftReference(obj); } else { ref = new WeakReference(obj); } } return ref; } // Convenience method which creates a WeakReference. static Reference createReference(Object obj) { return createReference(obj, false); } /** * Returns an object from a Reference wrapper. * * @return the Object in a wrapper or null. */ static Object getObject(Reference ref) { return (ref == null) ? null : (Object)ref.get(); } static String capitalize(String s) { return NameGenerator.capitalize(s); } private boolean expert; private boolean hidden; private boolean preferred; private String shortDescription; private String name; private String displayName; private java.util.Hashtable table; }
ru-doc/java-sdk
java/beans/FeatureDescriptor.java
249,364
/** * Domains * Copyright 2007 by Michael Peter Christen, [email protected], Frankfurt a. M., Germany, @orbiterlab * First released 23.7.2007 at http://yacy.net * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program in the file lgpl21.txt * If not, see <http://www.gnu.org/licenses/>. */ package eu.searchlab.tools; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import com.google.common.net.InetAddresses; import com.google.common.util.concurrent.UncheckedTimeoutException; public class Domains { public static final String LOCALHOST = "localhost"; // replace with IPv6 0:0:0:0:0:0:0:1 ? private static String LOCALHOST_NAME = LOCALHOST; // this will be replaced with the actual name of the local host private static final Set<String> ccSLD_TLD = new HashSet<>(); private static final String PRESENT = ""; private static final String LOCALHOST_IPv4_PATTERN = "(127\\..*)"; private static final String LOCALHOST_IPv6_PATTERN = "((\\[?fe80\\:.*)|(\\[?0\\:0\\:0\\:0\\:0\\:0\\:0\\:1.*)|(\\[?\\:\\:1))(/.*|%.*|\\z)"; private static final String INTRANET_IPv4_PATTERN = "(10\\..*)|(172\\.(1[6-9]|2[0-9]|3[0-1])\\..*)|(169\\.254\\..*)|(192\\.168\\..*)"; private static final String INTRANET_IPv6_PATTERN = "(\\[?(fc|fd).*\\:.*)"; private static final Pattern LOCALHOST_PATTERNS = Pattern.compile("(localhost)|" + LOCALHOST_IPv4_PATTERN + "|" + LOCALHOST_IPv6_PATTERN, Pattern.CASE_INSENSITIVE); private static final Pattern INTRANET_PATTERNS = Pattern.compile(LOCALHOST_PATTERNS.pattern() + "|" + INTRANET_IPv4_PATTERN + "|" + INTRANET_IPv6_PATTERN, Pattern.CASE_INSENSITIVE); private static final int MAX_NAME_CACHE_HIT_SIZE = 10000; private static final int MAX_NAME_CACHE_MISS_SIZE = 1000; private static final int CONCURRENCY_LEVEL = Runtime.getRuntime().availableProcessors() * 2; // a dns cache private static final ARC<String, InetAddress> NAME_CACHE_HIT = new ConcurrentARC<>(MAX_NAME_CACHE_HIT_SIZE, CONCURRENCY_LEVEL); private static final ARC<String, String> NAME_CACHE_MISS = new ConcurrentARC<>(MAX_NAME_CACHE_MISS_SIZE, CONCURRENCY_LEVEL); private static final ConcurrentHashMap<String, Object> LOOKUP_SYNC = new ConcurrentHashMap<>(100, 0.75f, Runtime.getRuntime().availableProcessors() * 2); private static List<Pattern> nameCacheNoCachingPatterns = Collections.synchronizedList(new LinkedList<Pattern>()); public static long cacheHit_Hit = 0, cacheHit_Miss = 0, cacheHit_Insert = 0; // for statistics only; do not write public static long cacheMiss_Hit = 0, cacheMiss_Miss = 0, cacheMiss_Insert = 0; // for statistics only; do not write private static Set<InetAddress> myHostAddresses = new HashSet<>(); private static Set<InetAddress> localHostAddresses = new HashSet<>(); // subset of myHostAddresses private static Set<InetAddress> publicIPv4HostAddresses = new HashSet<>(); // subset of myHostAddresses private static Set<InetAddress> publicIPv6HostAddresses = new HashSet<>(); // subset of myHostAddresses private static Set<String> localHostNames = new HashSet<>(); // subset of myHostNames static { localHostNames.add(LOCALHOST); try { final InetAddress localHostAddress = InetAddress.getLocalHost(); if (localHostAddress != null) { myHostAddresses.add(localHostAddress); localHostAddresses.add(localHostAddress); } } catch (final UnknownHostException e) {} try { final InetAddress[] moreAddresses = InetAddress.getAllByName(LOCALHOST_NAME); if (moreAddresses != null) myHostAddresses.addAll(Arrays.asList(moreAddresses)); } catch (final UnknownHostException e) {} // to get the local host name, a dns lookup is necessary. // if such a lookup blocks, it can cause that the static initiatializer does not finish fast // therefore we start the host name lookup as concurrent thread // meanwhile the host name is "127.0.0.1" which is not completely wrong new Thread() { @Override public void run() { Thread.currentThread().setName("Domains: init"); // try to get local addresses from interfaces try { final Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); while (nis.hasMoreElements()) { final NetworkInterface ni = nis.nextElement(); final Enumeration<InetAddress> addrs = ni.getInetAddresses(); while (addrs.hasMoreElements()) { final InetAddress addr = addrs.nextElement(); if (addr != null) myHostAddresses.add(addr); } } } catch (final SocketException e) { } // now look up the host name try { LOCALHOST_NAME = getHostName(InetAddress.getLocalHost()); } catch (final UnknownHostException e) {} // after the host name was resolved, we try to look up more local addresses // using the host name: try { final InetAddress[] moreAddresses = InetAddress.getAllByName(LOCALHOST_NAME); if (moreAddresses != null) myHostAddresses.addAll(Arrays.asList(moreAddresses)); } catch (final UnknownHostException e) { } // fill a cache of local host names for (final InetAddress a: myHostAddresses) { final String hostaddressP = chopZoneID(a.getHostAddress()); final Set<String> hns = new LinkedHashSet<>(); // generate alternative representations of IPv6 addresses which are needed to check access on the interface (i.e. localhost check) if (hostaddressP.indexOf("::") < 0) { hns.add(hostaddressP.replaceFirst(":0:0:0:0:0:0:", "::")); hns.add(hostaddressP.replaceFirst(":0:0:0:0:0:", "::")); hns.add(hostaddressP.replaceFirst(":0:0:0:0:", "::")); hns.add(hostaddressP.replaceFirst(":0:0:0:", "::")); hns.add(hostaddressP.replaceFirst(":0:0:", "::")); hns.add(hostaddressP.replaceFirst(":0:", "::")); } hns.add(hostaddressP); final String hostname = getHostName(a); for (final String hostaddress: hns) { if (hostaddress.contains("::0:") || hostaddress.contains(":0::")) continue; // not common (but possible); we skip that // we write the local tests into variables to be able to debug these values final boolean isAnyLocalAddress = a.isAnyLocalAddress(); final boolean isLinkLocalAddress = a.isLinkLocalAddress(); // true i.e. for localhost/fe80:0:0:0:0:0:0:1%1, myhost.local/fe80:0:0:0:223:dfff:fedf:30ce%7 final boolean isLoopbackAddress = a.isLoopbackAddress(); // true i.e. for localhost/0:0:0:0:0:0:0:1, localhost/127.0.0.1 final boolean isSiteLocalAddress = a.isSiteLocalAddress(); // true i.e. for myhost.local/192.168.1.33 if (isAnyLocalAddress || isLinkLocalAddress || isLoopbackAddress || isSiteLocalAddress) { localHostAddresses.add(a); if (hostname != null) {localHostNames.add(chopZoneID(hostname)); localHostNames.add(chopZoneID(hostaddress));} } else { if (a instanceof Inet4Address) { publicIPv4HostAddresses.add(a); } else { publicIPv6HostAddresses.add(a); } } } } } }.start(); } private static final String[] ccSLD_TLD_list = new String[] { "com.ac", "net.ac", "gov.ac", "org.ac", "mil.ac", "co.ae", "net.ae", "gov.ae", "ac.ae", "sch.ae", "org.ae", "mil.ae", "pro.ae", "name.ae", "com.af", "edu.af", "gov.af", "net.af", "org.af", "com.al", "edu.al", "gov.al", "mil.al", "net.al", "org.al", "ed.ao", "gv.ao", "og.ao", "co.ao", "pb.ao", "it.ao", "com.ar", "edu.ar", "gob.ar", "gov.ar", "int.ar", "mil.ar", "net.ar", "org.ar", "tur.ar", "gv.at", "ac.at", "co.at", "or.at", "com.au", "net.au", "org.au", "edu.au", "gov.au", "csiro.au", "asn.au", "id.au", "org.ba", "net.ba", "edu.ba", "gov.ba", "mil.ba", "unsa.ba", "untz.ba", "unmo.ba", "unbi.ba", "unze.ba", "co.ba", "com.ba", "rs.ba", "co.bb", "com.bb", "net.bb", "org.bb", "gov.bb", "edu.bb", "info.bb", "store.bb", "tv.bb", "biz.bb", "com.bh", "info.bh", "cc.bh", "edu.bh", "biz.bh", "net.bh", "org.bh", "gov.bh", "com.bn", "edu.bn", "gov.bn", "net.bn", "org.bn", "com.bo", "net.bo", "org.bo", "tv.bo", "mil.bo", "int.bo", "gob.bo", "gov.bo", "edu.bo", "adm.br", "adv.br", "agr.br", "am.br", "arq.br", "art.br", "ato.br", "b.br", "bio.br", "blog.br", "bmd.br", "cim.br", "cng.br", "cnt.br", "com.br", "coop.br", "ecn.br", "edu.br", "eng.br", "esp.br", "etc.br", "eti.br", "far.br", "flog.br", "fm.br", "fnd.br", "fot.br", "fst.br", "g12.br", "ggf.br", "gov.br", "imb.br", "ind.br", "inf.br", "jor.br", "jus.br", "lel.br", "mat.br", "med.br", "mil.br", "mus.br", "net.br", "nom.br", "not.br", "ntr.br", "odo.br", "org.br", "ppg.br", "pro.br", "psc.br", "psi.br", "qsl.br", "rec.br", "slg.br", "srv.br", "tmp.br", "trd.br", "tur.br", "tv.br", "vet.br", "vlog.br", "wiki.br", "zlg.br", "com.bs", "net.bs", "org.bs", "edu.bs", "gov.bs", "com.bz", "edu.bz", "gov.bz", "net.bz", "org.bz", "om.bz", "du.bz", "ov.bz", "et.bz", "rg.bz", "ab.ca", "bc.ca", "mb.ca", "nb.ca", "nf.ca", "nl.ca", "ns.ca", "nt.ca", "nu.ca", "on.ca", "pe.ca", "qc.ca", "sk.ca", "yk.ca", "co.ck", "org.ck", "edu.ck", "gov.ck", "net.ck", "gen.ck", "biz.ck", "info.ck", "ac.cn", "com.cn", "edu.cn", "gov.cn", "mil.cn", "net.cn", "org.cn", "ah.cn", "bj.cn", "cq.cn", "fj.cn", "gd.cn", "gs.cn", "gz.cn", "gx.cn", "ha.cn", "hb.cn", "he.cn", "hi.cn", "hl.cn", "hn.cn", "jl.cn", "js.cn", "jx.cn", "ln.cn", "nm.cn", "nx.cn", "qh.cn", "sc.cn", "sd.cn", "sh.cn", "sn.cn", "sx.cn", "tj.cn", "tw.cn", "xj.cn", "xz.cn", "yn.cn", "zj.cn", "com.co", "org.co", "edu.co", "gov.co", "net.co", "mil.co", "nom.co", "ac.cr", "co.cr", "ed.cr", "fi.cr", "go.cr", "or.cr", "sa.cr", "cr", "ac.cy", "net.cy", "gov.cy", "org.cy", "pro.cy", "name.cy", "ekloges.cy", "tm.cy", "ltd.cy", "biz.cy", "press.cy", "parliament.cy", "com.cy", "edu.do", "gob.do", "gov.do", "com.do", "sld.do", "org.do", "net.do", "web.do", "mil.do", "art.do", "com.dz", "org.dz", "net.dz", "gov.dz", "edu.dz", "asso.dz", "pol.dz", "art.dz", "com.ec", "info.ec", "net.ec", "fin.ec", "med.ec", "pro.ec", "org.ec", "edu.ec", "gov.ec", "mil.ec", "com.eg", "edu.eg", "eun.eg", "gov.eg", "mil.eg", "name.eg", "net.eg", "org.eg", "sci.eg", "com.er", "edu.er", "gov.er", "mil.er", "net.er", "org.er", "ind.er", "rochest.er", "w.er", "com.es", "nom.es", "org.es", "gob.es", "edu.es", "com.et", "gov.et", "org.et", "edu.et", "net.et", "biz.et", "name.et", "info.et", "ac.fj", "biz.fj", "com.fj", "info.fj", "mil.fj", "name.fj", "net.fj", "org.fj", "pro.fj", "co.fk", "org.fk", "gov.fk", "ac.fk", "nom.fk", "net.fk", "fr", "tm.fr", "asso.fr", "nom.fr", "prd.fr", "presse.fr", "com.fr", "gouv.fr", "co.gg", "net.gg", "org.gg", "com.gh", "edu.gh", "gov.gh", "org.gh", "mil.gh", "com.gn", "ac.gn", "gov.gn", "org.gn", "net.gn", "com.gr", "edu.gr", "net.gr", "org.gr", "gov.gr", "mil.gr", "com.gt", "edu.gt", "net.gt", "gob.gt", "org.gt", "mil.gt", "ind.gt", "com.gu", "net.gu", "gov.gu", "org.gu", "edu.gu", "com.hk", "edu.hk", "gov.hk", "idv.hk", "net.hk", "org.hk", "ac.id", "co.id", "net.id", "or.id", "web.id", "sch.id", "mil.id", "go.id", "war.net.id", "ac.il", "co.il", "org.il", "net.il", "k12.il", "gov.il", "muni.il", "idf.il", "in", "co.in", "firm.in", "net.in", "org.in", "gen.in", "ind.in", "ac.in", "edu.in", "res.in", "ernet.in", "gov.in", "mil.in", "nic.in", "iq", "gov.iq", "edu.iq", "com.iq", "mil.iq", "org.iq", "net.iq", "ir", "ac.ir", "co.ir", "gov.ir", "id.ir", "net.ir", "org.ir", "sch.ir", "dnssec.ir", "gov.it", "edu.it", "co.je", "net.je", "org.je", "com.jo", "net.jo", "gov.jo", "edu.jo", "org.jo", "mil.jo", "name.jo", "sch.jo", "ac.jp", "ad.jp", "co.jp", "ed.jp", "go.jp", "gr.jp", "lg.jp", "ne.jp", "or.jp", "co.ke", "or.ke", "ne.ke", "go.ke", "ac.ke", "sc.ke", "me.ke", "mobi.ke", "info.ke", "per.kh", "com.kh", "edu.kh", "gov.kh", "mil.kh", "net.kh", "org.kh", "com.ki", "biz.ki", "de.ki", "net.ki", "info.ki", "org.ki", "gov.ki", "edu.ki", "mob.ki", "tel.ki", "km", "com.km", "coop.km", "asso.km", "nom.km", "presse.km", "tm.km", "medecin.km", "notaires.km", "pharmaciens.km", "veterinaire.km", "edu.km", "gouv.km", "mil.km", "net.kn", "org.kn", "edu.kn", "gov.kn", "kr", "co.kr", "ne.kr", "or.kr", "re.kr", "pe.kr", "go.kr", "mil.kr", "ac.kr", "hs.kr", "ms.kr", "es.kr", "sc.kr", "kg.kr", "seoul.kr", "busan.kr", "daegu.kr", "incheon.kr", "gwangju.kr", "daejeon.kr", "ulsan.kr", "gyeonggi.kr", "gangwon.kr", "chungbuk.kr", "chungnam.kr", "jeonbuk.kr", "jeonnam.kr", "gyeongbuk.kr", "gyeongnam.kr", "jeju.kr", "edu.kw", "com.kw", "net.kw", "org.kw", "gov.kw", "com.ky", "org.ky", "net.ky", "edu.ky", "gov.ky", "com.kz", "edu.kz", "gov.kz", "mil.kz", "net.kz", "org.kz", "com.lb", "edu.lb", "gov.lb", "net.lb", "org.lb", "gov.lk", "sch.lk", "net.lk", "int.lk", "com.lk", "org.lk", "edu.lk", "ngo.lk", "soc.lk", "web.lk", "ltd.lk", "assn.lk", "grp.lk", "hotel.lk", "com.lr", "edu.lr", "gov.lr", "org.lr", "net.lr", "com.lv", "edu.lv", "gov.lv", "org.lv", "mil.lv", "id.lv", "net.lv", "asn.lv", "conf.lv", "com.ly", "net.ly", "gov.ly", "plc.ly", "edu.ly", "sch.ly", "med.ly", "org.ly", "id.ly", "ma", "net.ma", "ac.ma", "org.ma", "gov.ma", "press.ma", "co.ma", "tm.mc", "asso.mc", "co.me", "net.me", "org.me", "edu.me", "ac.me", "gov.me", "its.me", "priv.me", "org.mg", "nom.mg", "gov.mg", "prd.mg", "tm.mg", "edu.mg", "mil.mg", "com.mg", "com.mk", "org.mk", "net.mk", "edu.mk", "gov.mk", "inf.mk", "name.mk", "pro.mk", "com.ml", "net.ml", "org.ml", "edu.ml", "gov.ml", "presse.ml", "gov.mn", "edu.mn", "org.mn", "com.mo", "edu.mo", "gov.mo", "net.mo", "org.mo", "com.mt", "org.mt", "net.mt", "edu.mt", "gov.mt", "aero.mv", "biz.mv", "com.mv", "coop.mv", "edu.mv", "gov.mv", "info.mv", "int.mv", "mil.mv", "museum.mv", "name.mv", "net.mv", "org.mv", "pro.mv", "ac.mw", "co.mw", "com.mw", "coop.mw", "edu.mw", "gov.mw", "int.mw", "museum.mw", "net.mw", "org.mw", "com.mx", "net.mx", "org.mx", "edu.mx", "gob.mx", "com.my", "net.my", "org.my", "gov.my", "edu.my", "sch.my", "mil.my", "name.my", "com.nf", "net.nf", "arts.nf", "store.nf", "web.nf", "firm.nf", "info.nf", "other.nf", "per.nf", "rec.nf", "com.ng", "org.ng", "gov.ng", "edu.ng", "net.ng", "sch.ng", "name.ng", "mobi.ng", "biz.ng", "mil.ng", "gob.ni", "co.ni", "com.ni", "ac.ni", "edu.ni", "org.ni", "nom.ni", "net.ni", "mil.ni", "com.np", "edu.np", "gov.np", "org.np", "mil.np", "net.np", "edu.nr", "gov.nr", "biz.nr", "info.nr", "net.nr", "org.nr", "com.nr", "com.om", "co.om", "edu.om", "ac.om", "sch.om", "gov.om", "net.om", "org.om", "mil.om", "museum.om", "biz.om", "pro.om", "med.om", "edu.pe", "gob.pe", "nom.pe", "mil.pe", "sld.pe", "org.pe", "com.pe", "net.pe", "com.ph", "net.ph", "org.ph", "mil.ph", "ngo.ph", "i.ph", "gov.ph", "edu.ph", "com.pk", "net.pk", "edu.pk", "org.pk", "fam.pk", "biz.pk", "web.pk", "gov.pk", "gob.pk", "gok.pk", "gon.pk", "gop.pk", "gos.pk", "pwr.pl", "com.pl", "biz.pl", "net.pl", "art.pl", "edu.pl", "org.pl", "ngo.pl", "gov.pl", "info.pl", "mil.pl", "waw.pl", "warszawa.pl", "wroc.pl", "wroclaw.pl", "krakow.pl", "katowice.pl", "poznan.pl", "lodz.pl", "gda.pl", "gdansk.pl", "slupsk.pl", "radom.pl", "szczecin.pl", "lublin.pl", "bialystok.pl", "olsztyn.pl", "torun.pl", "gorzow.pl", "zgora.pl", "biz.pr", "com.pr", "edu.pr", "gov.pr", "info.pr", "isla.pr", "name.pr", "net.pr", "org.pr", "pro.pr", "est.pr", "prof.pr", "ac.pr", "com.ps", "net.ps", "org.ps", "edu.ps", "gov.ps", "plo.ps", "sec.ps", "co.pw", "ne.pw", "or.pw", "ed.pw", "go.pw", "belau.pw", "arts.ro", "com.ro", "firm.ro", "info.ro", "nom.ro", "nt.ro", "org.ro", "rec.ro", "store.ro", "tm.ro", "www.ro", "co.rs", "org.rs", "edu.rs", "ac.rs", "gov.rs", "in.rs", "com.sb", "net.sb", "edu.sb", "org.sb", "gov.sb", "com.sc", "net.sc", "edu.sc", "gov.sc", "org.sc", "co.sh", "com.sh", "org.sh", "gov.sh", "edu.sh", "net.sh", "nom.sh", "com.sl", "net.sl", "org.sl", "edu.sl", "gov.sl", "gov.st", "saotome.st", "principe.st", "consulado.st", "embaixada.st", "org.st", "edu.st", "net.st", "com.st", "store.st", "mil.st", "co.st", "edu.sv", "gob.sv", "com.sv", "org.sv", "red.sv", "co.sz", "ac.sz", "org.sz", "com.tr", "gen.tr", "org.tr", "biz.tr", "info.tr", "av.tr", "dr.tr", "pol.tr", "bel.tr", "tsk.tr", "bbs.tr", "k12.tr", "edu.tr", "name.tr", "net.tr", "gov.tr", "web.tr", "tel.tr", "tv.tr", "co.tt", "com.tt", "org.tt", "net.tt", "biz.tt", "info.tt", "pro.tt", "int.tt", "coop.tt", "jobs.tt", "mobi.tt", "travel.tt", "museum.tt", "aero.tt", "cat.tt", "tel.tt", "name.tt", "mil.tt", "edu.tt", "gov.tt", "edu.tw", "gov.tw", "mil.tw", "com.tw", "net.tw", "org.tw", "idv.tw", "game.tw", "ebiz.tw", "club.tw", "com.mu", "gov.mu", "net.mu", "org.mu", "ac.mu", "co.mu", "or.mu", "ac.mz", "co.mz", "edu.mz", "org.mz", "gov.mz", "com.na", "co.na", "ac.nz", "co.nz", "cri.nz", "geek.nz", "gen.nz", "govt.nz", "health.nz", "iwi.nz", "maori.nz", "mil.nz", "net.nz", "org.nz", "parliament.nz", "school.nz", "abo.pa", "ac.pa", "com.pa", "edu.pa", "gob.pa", "ing.pa", "med.pa", "net.pa", "nom.pa", "org.pa", "sld.pa", "com.pt", "edu.pt", "gov.pt", "int.pt", "net.pt", "nome.pt", "org.pt", "publ.pt", "com.py", "edu.py", "gov.py", "mil.py", "net.py", "org.py", "com.qa", "edu.qa", "gov.qa", "mil.qa", "net.qa", "org.qa", "asso.re", "com.re", "nom.re", "ac.ru", "adygeya.ru", "altai.ru", "amur.ru", "arkhangelsk.ru", "astrakhan.ru", "bashkiria.ru", "belgorod.ru", "bir.ru", "bryansk.ru", "buryatia.ru", "cbg.ru", "chel.ru", "chelyabinsk.ru", "chita.ru", "chukotka.ru", "chuvashia.ru", "com.ru", "dagestan.ru", "e-burg.ru", "edu.ru", "gov.ru", "grozny.ru", "int.ru", "irkutsk.ru", "ivanovo.ru", "izhevsk.ru", "jar.ru", "joshkar-ola.ru", "kalmykia.ru", "kaluga.ru", "kamchatka.ru", "karelia.ru", "kazan.ru", "kchr.ru", "kemerovo.ru", "khabarovsk.ru", "khakassia.ru", "khv.ru", "kirov.ru", "koenig.ru", "komi.ru", "kostroma.ru", "kranoyarsk.ru", "kuban.ru", "kurgan.ru", "kursk.ru", "lipetsk.ru", "magadan.ru", "mari.ru", "mari-el.ru", "marine.ru", "mil.ru", "mordovia.ru", "mosreg.ru", "msk.ru", "murmansk.ru", "nalchik.ru", "net.ru", "nnov.ru", "nov.ru", "novosibirsk.ru", "nsk.ru", "omsk.ru", "orenburg.ru", "org.ru", "oryol.ru", "penza.ru", "perm.ru", "pp.ru", "pskov.ru", "ptz.ru", "rnd.ru", "ryazan.ru", "sakhalin.ru", "samara.ru", "saratov.ru", "simbirsk.ru", "smolensk.ru", "spb.ru", "stavropol.ru", "stv.ru", "surgut.ru", "tambov.ru", "tatarstan.ru", "tom.ru", "tomsk.ru", "tsaritsyn.ru", "tsk.ru", "tula.ru", "tuva.ru", "tver.ru", "tyumen.ru", "udm.ru", "udmurtia.ru", "ulan-ude.ru", "vladikavkaz.ru", "vladimir.ru", "vladivostok.ru", "volgograd.ru", "vologda.ru", "voronezh.ru", "vrn.ru", "vyatka.ru", "yakutia.ru", "yamal.ru", "yekaterinburg.ru", "yuzhno-sakhalinsk.ru", "ac.rw", "co.rw", "com.rw", "edu.rw", "gouv.rw", "gov.rw", "int.rw", "mil.rw", "net.rw", "com.sa", "edu.sa", "gov.sa", "med.sa", "net.sa", "org.sa", "pub.sa", "sch.sa", "com.sd", "edu.sd", "gov.sd", "info.sd", "med.sd", "net.sd", "org.sd", "tv.sd", "a.se", "ac.se", "b.se", "bd.se", "c.se", "d.se", "e.se", "f.se", "g.se", "h.se", "i.se", "k.se", "l.se", "m.se", "n.se", "o.se", "org.se", "p.se", "parti.se", "pp.se", "press.se", "r.se", "s.se", "t.se", "tm.se", "u.se", "w.se", "x.se", "y.se", "z.se", "com.sg", "edu.sg", "gov.sg", "idn.sg", "net.sg", "org.sg", "per.sg", "art.sn", "com.sn", "edu.sn", "gouv.sn", "org.sn", "perso.sn", "univ.sn", "com.sy", "edu.sy", "gov.sy", "mil.sy", "net.sy", "news.sy", "org.sy", "ac.th", "co.th", "go.th", "in.th", "mi.th", "net.th", "or.th", "ac.tj", "biz.tj", "co.tj", "com.tj", "edu.tj", "go.tj", "gov.tj", "info.tj", "int.tj", "mil.tj", "name.tj", "net.tj", "nic.tj", "org.tj", "test.tj", "web.tj", "agrinet.tn", "com.tn", "defense.tn", "edunet.tn", "ens.tn", "fin.tn", "gov.tn", "ind.tn", "info.tn", "intl.tn", "mincom.tn", "nat.tn", "net.tn", "org.tn", "perso.tn", "rnrt.tn", "rns.tn", "rnu.tn", "tourism.tn", "ac.tz", "co.tz", "go.tz", "ne.tz", "or.tz", "biz.ua", "cherkassy.ua", "chernigov.ua", "chernovtsy.ua", "ck.ua", "cn.ua", "co.ua", "com.ua", "crimea.ua", "cv.ua", "dn.ua", "dnepropetrovsk.ua", "donetsk.ua", "dp.ua", "edu.ua", "gov.ua", "if.ua", "in.ua", "ivano-frankivsk.ua", "kh.ua", "kharkov.ua", "kherson.ua", "khmelnitskiy.ua", "kiev.ua", "kirovograd.ua", "km.ua", "kr.ua", "ks.ua", "kv.ua", "lg.ua", "lugansk.ua", "lutsk.ua", "lviv.ua", "me.ua", "mk.ua", "net.ua", "nikolaev.ua", "od.ua", "odessa.ua", "org.ua", "pl.ua", "poltava.ua", "pp.ua", "rovno.ua", "rv.ua", "sebastopol.ua", "sumy.ua", "te.ua", "ternopil.ua", "uzhgorod.ua", "vinnica.ua", "vn.ua", "zaporizhzhe.ua", "zhitomir.ua", "zp.ua", "zt.ua", "ac.ug", "co.ug", "go.ug", "ne.ug", "or.ug", "org.ug", "sc.ug", "ac.uk", "bl.uk", "british-library.uk", "co.uk", "cym.uk", "gov.uk", "govt.uk", "icnet.uk", "jet.uk", "lea.uk", "ltd.uk", "me.uk", "mil.uk", "mod.uk", "national-library-scotland.uk", "nel.uk", "net.uk", "nhs.uk", "nic.uk", "nls.uk", "org.uk", "orgn.uk", "parliament.uk", "plc.uk", "police.uk", "sch.uk", "scot.uk", "soc.uk", "dni.us", "fed.us", "isa.us", "kids.us", "nsn.us", "com.uy", "edu.uy", "gub.uy", "mil.uy", "net.uy", "org.uy", "co.ve", "com.ve", "edu.ve", "gob.ve", "info.ve", "mil.ve", "net.ve", "org.ve", "web.ve", "co.vi", "com.vi", "k12.vi", "net.vi", "org.vi", "ac.vn", "biz.vn", "com.vn", "edu.vn", "gov.vn", "health.vn", "info.vn", "int.vn", "name.vn", "net.vn", "org.vn", "pro.vn", "co.ye", "com.ye", "gov.ye", "ltd.ye", "me.ye", "net.ye", "org.ye", "plc.ye", "ac.yu", "co.yu", "edu.yu", "gov.yu", "org.yu", "ac.za", "agric.za", "alt.za", "bourse.za", "city.za", "co.za", "cybernet.za", "db.za", "ecape.school.za", "edu.za", "fs.school.za", "gov.za", "gp.school.za", "grondar.za", "iaccess.za", "imt.za", "inca.za", "kzn.school.za", "landesign.za", "law.za", "lp.school.za", "mil.za", "mpm.school.za", "ncape.school.za", "net.za", "ngo.za", "nis.za", "nom.za", "nw.school.za", "olivetti.za", "org.za", "pix.za", "school.za", "tm.za", "wcape.school.za", "web.za", "ac.zm", "co.zm", "com.zm", "edu.zm", "gov.zm", "net.zm", "org.zm", "sch.zm", "e164.arpa", "au.com", "br.com", "cn.com", "de.com", "eu.com", "gb.com", "hu.com", "no.com", "qc.com", "ru.com", "sa.com", "se.com", "uk.com", "us.com", "uy.com", "za.com", "de.net", "gb.net", "uk.net", "dk.org", "eu.org", "edu.ac", "com.ae", "com.ai", "edu.ai", "gov.ai", "org.ai", "uba.ar", "esc.edu.ar", "priv.at", "conf.au", "info.au", "otc.au", "oz.au", "telememo.au", "com.az", "net.az", "org.az", "ac.be", "belgie.be", "dns.be", "fgov.be", "com.bm", "edu.bm", "gov.bm", "net.bm", "org.bm", "sp.br", "hk.cn", "mo.cn", "arts.co", "firm.co", "info.co", "int.co", "rec.co", "store.co", "web.co", "com.cu", "net.cu", "org.cu", "co.dk", "ass.dz", "k12.ec", "gov.fj", "id.fj", "school.fj", "com.fk", "aeroport.fr", "assedic.fr", "avocat.fr", "avoues.fr", "barreau.fr", "cci.fr", "chambagri.fr", "chirurgiens-dentistes.fr", "experts-comptables.fr", "geometre-expert.fr", "greta.fr", "huissier-justice.fr", "medecin.fr", "notaires.fr", "pharmacien.fr", "port.fr", "veterinaire.fr", "com.ge", "edu.ge", "gov.ge", "mil.ge", "net.ge", "org.ge", "pvt.ge", "ac.gg", "alderney.gg", "gov.gg", "guernsey.gg", "ind.gg", "ltd.gg", "sark.gg", "sch.gg", "mil.gu", "2000.hu", "agrar.hu", "bolt.hu", "casino.hu", "city.hu", "co.hu", "erotica.hu", "erotika.hu", "film.hu", "forum.hu", "games.hu", "hotel.hu", "info.hu", "ingatlan.hu", "jogasz.hu", "konyvelo.hu", "lakas.hu", "media.hu", "news.hu", "org.hu", "priv.hu", "reklam.hu", "sex.hu", "shop.hu", "sport.hu", "suli.hu", "szex.hu", "tm.hu", "tozsde.hu", "utazas.hu", "video.hu", "ac.im", "co.im", "gov.im", "net.im", "nic.im", "org.im", "ac.je", "gov.je", "ind.je", "jersey.je", "ltd.je", "sch.je", "aichi.jp", "akita.jp", "aomori.jp", "chiba.jp", "ehime.jp", "fukui.jp", "fukuoka.jp", "fukushima.jp", "gifu.jp", "gov.jp", "gunma.jp", "hiroshima.jp", "hokkaido.jp", "hyogo.jp", "ibaraki.jp", "ishikawa.jp", "iwate.jp", "kagawa.jp", "kagoshima.jp", "kanagawa.jp", "kanazawa.jp", "kawasaki.jp", "kitakyushu.jp", "kobe.jp", "kochi.jp", "kumamoto.jp", "kyoto.jp", "matsuyama.jp", "mie.jp", "miyagi.jp", "miyazaki.jp", "nagano.jp", "nagasaki.jp", "nagoya.jp", "nara.jp", "net.jp", "niigata.jp", "oita.jp", "okayama.jp", "okinawa.jp", "org.jp", "osaka.jp", "saga.jp", "saitama.jp", "sapporo.jp", "sendai.jp", "shiga.jp", "shimane.jp", "shizuoka.jp", "takamatsu.jp", "tochigi.jp", "tokushima.jp", "tokyo.jp", "tottori.jp", "toyama.jp", "utsunomiya.jp", "wakayama.jp", "yamagata.jp", "yamaguchi.jp", "yamanashi.jp", "yokohama.jp", "kyonggi.kr", "com.la", "net.la", "org.la", "mil.lb", "com.lc", "edu.lc", "gov.lc", "net.lc", "org.lc", "com.mm", "edu.mm", "gov.mm", "net.mm", "org.mm", "tm.mt", "uu.mt", "alt.na", "cul.na", "edu.na", "net.na", "org.na", "telecom.na", "unam.na", "com.nc", "net.nc", "org.nc", "ac.ng", "tel.no", "fax.nr", "mob.nr", "mobil.nr", "mobile.nr", "tel.nr", "tlf.nr", "mod.om", "ac.pg", "com.pg", "net.pg", "agro.pl", "aid.pl", "atm.pl", "auto.pl", "gmina.pl", "gsm.pl", "mail.pl", "media.pl", "miasta.pl", "nieruchomosci.pl", "nom.pl", "pc.pl", "powiat.pl", "priv.pl", "realestate.pl", "rel.pl", "sex.pl", "shop.pl", "sklep.pl", "sos.pl", "szkola.pl", "targi.pl", "tm.pl", "tourism.pl", "travel.pl", "turystyka.pl", "sch.sd", "mil.sh", "mil.tr", "at.tt", "au.tt", "be.tt", "ca.tt", "de.tt", "dk.tt", "es.tt", "eu.tt", "fr.tt", "it.tt", "nic.tt", "se.tt", "uk.tt", "us.tt", "co.tv", "gove.tw", "edu.uk", "arts.ve", "bib.ve", "firm.ve", "gov.ve", "int.ve", "nom.ve", "rec.ve", "store.ve", "tec.ve", "ch.vu", "com.vu", "de.vu", "edu.vu", "fr.vu", "net.vu", "org.vu", "com.ws", "edu.ws", "gov.ws", "net.ws", "org.ws", "edu.ye", "mil.ye", "ac.zw", "co.zw", "gov.zw", "org.zw" }; static { ccSLD_TLD.addAll(Arrays.asList(ccSLD_TLD_list)); } private static Map<String, Integer> TLDID = new ConcurrentHashMap<>(32); //private static HashMap<String, String> TLDName = new HashMap<String, String>(); private static boolean noLocalCheck = false; /** * the isLocal check can be switched off to gain a better crawling speed. * however, if the check is switched off, then ALL urls are considered as local * this will create url-hashes for global domains which do not fit in environments * where the isLocal switch is not de-activated. Please handle this method with great care * Bad usage will make peers inoperable. * @param v */ public static void setNoLocalCheck(final boolean v) { noLocalCheck = v; } /** * Does an DNS-Check to resolve a hostname to an IP. * * @param host Hostname of the host in demand. * @return String with the ip. null, if the host could not be resolved. */ public static InetAddress dnsResolveFromCache(String host) throws UnknownHostException { if ((host == null) || host.isEmpty()) return null; host = host.toLowerCase().trim(); // trying to resolve host by doing a name cache lookup final InetAddress ip = NAME_CACHE_HIT.get(host); if (ip != null) { cacheHit_Hit++; return ip; } cacheHit_Miss++; if (NAME_CACHE_MISS.containsKey(host)) { cacheMiss_Hit++; return null; } cacheMiss_Miss++; throw new UnknownHostException("host not in cache"); } public static void setNoCachingPatterns(final String patternList) throws PatternSyntaxException { nameCacheNoCachingPatterns = makePatterns(patternList); } public static List<Pattern> makePatterns(final String patternList) throws PatternSyntaxException { final String[] entries = (patternList != null) ? CommonPattern.COMMA.split(patternList) : new String[0]; final List<Pattern> patterns = new ArrayList<>(entries.length); for (final String entry : entries) { patterns.add(Pattern.compile(entry.trim())); } return patterns; } public static boolean matchesList(final String obj, final List<Pattern> patterns) { for (final Pattern nextPattern: patterns) { if (nextPattern.matcher(obj).matches()) return true; } return false; } public static String getHostName(final InetAddress i) { final Collection<String> hosts = NAME_CACHE_HIT.getKeys(i); if (!hosts.isEmpty()) return hosts.iterator().next(); final String host = i.getHostName(); NAME_CACHE_HIT.insertIfAbsent(host, i); cacheHit_Insert++; return host; } /** * in case that the host name was resolved using a time-out request * it can be nice to push that information to the name cache * @param i the inet address * @param host the known host name */ public static void setHostName(final InetAddress i, final String host) { NAME_CACHE_HIT.insertIfAbsent(host, i); cacheHit_Insert++; } /** * strip off any parts of an url, address string (containing host/ip:port) or raw IPs/Hosts, * considering that the host may also be an (IPv4) IP or a IPv6 IP in brackets. * @param target * @return a host name or IP string */ public static String stripToHostName(String target) { // normalize if (target == null || target.isEmpty()) return null; target = target.toLowerCase().trim(); // we can lowercase this because host names are case-insensitive // extract the address (host:port) part (applies if this is an url) int p = target.indexOf("://"); if (p > 0) target = target.substring(p + 3); p = target.indexOf('/'); if (p > 0) target = target.substring(0, p); // IPv4 / host heuristics p = target.lastIndexOf(':'); if ( p < 0 ) { p = target.lastIndexOf('%'); if (p > 0) target = target.substring(0, p); return target; } // the ':' at pos p may be either a port divider or a part of an IPv6 address if ( p > target.lastIndexOf(']')) { // if after ] it's a port divider (not IPv6 part) target = target.substring(0, p ); } // may be IPv4 or IPv6, we chop off brackets if exist if (target.charAt(0) == '[') target = target.substring(1); if (target.charAt(target.length() - 1) == ']') target = target.substring(0, target.length() - 1); p = target.lastIndexOf('%'); if (p > 0) target = target.substring(0, p); return target; } /** * Reads the port out of a url string (the url must start with a protocol * like http:// to return correct default port). If no port is given, default * ports are returned. On missing protocol, port=80 is assumed. * @param target url (must start with protocol) * @return port number */ public static int stripToPort(String target) { int port = 80; // default port // normalize if (target == null || target.isEmpty()) return port; target = target.toLowerCase().trim(); // we can lowercase this because host names are case-insensitive // extract the address (host:port) part (applies if this is an url) int p = target.indexOf("://"); if (p > 0) { final String protocol = target.substring(0, p); target = target.substring(p + 3); if ("https".equals(protocol)) port = 443; if ("s3".equals(protocol)) port = 9000; if ("ftp".equals(protocol)) port = 21; if ("smb".equals(protocol)) port = 445; } p = target.indexOf('/'); if (p > 0) target = target.substring(0, p); // IPv4 / host heuristics p = target.lastIndexOf(':'); if ( p < 0 ) return port; // the ':' must be a port divider or part of ipv6 if (target.lastIndexOf(']') < p) { port = Integer.parseInt(target.substring(p + 1)); } return port; } /** * resolve a host address using a local DNS cache and a DNS lookup if necessary * @param clienthost * @return the hosts InetAddress or null if the address cannot be resolved */ public static InetAddress dnsResolve(final String host0) { // consider to call stripToHostName() before calling this if (host0 == null || host0.isEmpty()) return null; final String host = host0.toLowerCase().trim(); if (host0.endsWith(".yacyh")) { // that should not happen here return null; } // try to resolve host by doing a name cache lookup InetAddress ip = NAME_CACHE_HIT.get(host); if (ip != null) { //System.out.println("DNSLOOKUP-CACHE-HIT(CONC) " + host); cacheHit_Hit++; return ip; } cacheHit_Miss++; if (NAME_CACHE_MISS.containsKey(host)) { //System.out.println("DNSLOOKUP-CACHE-MISS(CONC) " + host); cacheMiss_Hit++; return null; } cacheMiss_Miss++; // call dnsResolveNetBased(host) using concurrency to interrupt execution in case of a time-out final Object sync_obj_new = new Object(); Object sync_obj = LOOKUP_SYNC.putIfAbsent(host, sync_obj_new); if (sync_obj == null) sync_obj = sync_obj_new; synchronized (sync_obj) { // now look again if the host is in the cache where it may be meanwhile because of the synchronization ip = NAME_CACHE_HIT.get(host); if (ip != null) { //System.out.println("DNSLOOKUP-CACHE-HIT(SYNC) " + host); LOOKUP_SYNC.remove(host); cacheHit_Hit++; return ip; } cacheHit_Miss++; if (NAME_CACHE_MISS.containsKey(host)) { //System.out.println("DNSLOOKUP-CACHE-MISS(SYNC) " + host); LOOKUP_SYNC.remove(host); cacheMiss_Hit++; return null; } cacheMiss_Miss++; // do the dns lookup on the dns server //if (!matchesList(host, nameCacheNoCachingPatterns)) System.out.println("DNSLOOKUP " + host); try { //final long t = System.currentTimeMillis(); final String oldName = Thread.currentThread().getName(); Thread.currentThread().setName("Domains: DNS resolve of '" + host + "'"); // thread dump show which host is resolved if (InetAddresses.isInetAddress(host)) { try { ip = InetAddresses.forString(host); } catch (final IllegalArgumentException e) { ip = null; } } Thread.currentThread().setName(oldName); if (ip == null) try { ip = InetAddress.getByName(host); //ip = TimeoutRequest.getByName(host, 1000); // this makes the DNS request to backbone } catch (final UncheckedTimeoutException e) { // in case of a timeout - maybe cause of massive requests - do not fill NAME_CACHE_MISS LOOKUP_SYNC.remove(host); return null; } //.out.println("DNSLOOKUP-*LOOKUP* " + host + ", time = " + (System.currentTimeMillis() - t) + "ms"); } catch (final Throwable e) { // add new entries NAME_CACHE_MISS.insertIfAbsent(host, PRESENT); cacheMiss_Insert++; LOOKUP_SYNC.remove(host); return null; } if (ip == null) { // add new entries NAME_CACHE_MISS.insertIfAbsent(host, PRESENT); cacheMiss_Insert++; LOOKUP_SYNC.remove(host); return null; } if (!ip.isLoopbackAddress() && !matchesList(host, nameCacheNoCachingPatterns)) { // add new ip cache entries NAME_CACHE_HIT.insertIfAbsent(host, ip); cacheHit_Insert++; } LOOKUP_SYNC.remove(host); return ip; } } public static void clear() { NAME_CACHE_HIT.clear(); NAME_CACHE_MISS.clear(); } /** * Returns the number of entries in the nameCacheHit map * * @return int The number of entries in the nameCacheHit map */ public static int nameCacheHitSize() { return NAME_CACHE_HIT.size(); } public static int nameCacheMissSize() { return NAME_CACHE_MISS.size(); } public static int nameCacheNoCachingPatternsSize() { return nameCacheNoCachingPatterns.size(); } public static InetAddress myLocalhostIP() { if (localHostAddresses.size() > 0) return localHostAddresses.iterator().next(); if (myHostAddresses.size() > 0) return myHostAddresses.iterator().next(); try { final InetAddress localHostAddress = InetAddress.getLocalHost(); localHostAddresses.add(localHostAddress); return localHostAddress; } catch (final UnknownHostException e) { return null; } } /** * myPublicLocalIP() returns the IP of this host which is reachable in the public network under this address * This is deprecated since it should be possible that the host is reachable with more than one IP * That is particularly the case if the host supports IPv4 and IPv6. * Please use myPublicIPv4() or (preferred) myPublicIPv6() instead. * @return */ @Deprecated public static InetAddress myPublicLocalIP() { // for backward compatibility, we try to select a IPv4 address here. // future methods should use myPublicIPs() and prefer IPv6 if (publicIPv4HostAddresses.size() > 0) return publicIPv4HostAddresses.iterator().next(); if (publicIPv6HostAddresses.size() > 0) return publicIPv6HostAddresses.iterator().next(); return null; } public static Set<String> myPublicIPs() { // use a LinkedHashSet to get an order of IPs where the IPv4 are preferred to get a better compatibility with older implementations final Set<String> h = new LinkedHashSet<>(publicIPv4HostAddresses.size() + publicIPv6HostAddresses.size()); for (final InetAddress i: publicIPv4HostAddresses) h.add(i.getHostAddress()); for (final InetAddress i: publicIPv6HostAddresses) h.add(i.getHostAddress()); return h; } /** * Get all IPv4 addresses which are assigned to the local host but are public IP addresses. * These should be the possible addresses which can be used to access this peer. * @return the public IPv4 Addresses of this peer */ public static Set<InetAddress> myPublicIPv4() { return publicIPv4HostAddresses; } /** * Get all IPv6 addresses which are assigned to the local host but are public IP addresses. * These should be the possible addresses which can be used to access this peer. * @return the public IPv6 addresses of this peer */ public static Set<InetAddress> myPublicIPv6() { return publicIPv6HostAddresses; } /** * generate a list of intranet InetAddresses * @return list of all intranet addresses */ public static Set<InetAddress> myIntranetIPs() { if (localHostAddresses.size() < 1) try {Thread.sleep(1000);} catch (final InterruptedException e) {} return localHostAddresses; } /** * this method is deprecated in some way because it is not applicable on IPv6 * TODO: remove / replace * @param hostName * @return */ public static boolean isThisHostIP(final String hostName) { if ((hostName == null) || (hostName.isEmpty())) return false; if (hostName.indexOf(':') > 0) return false; // IPv6 addresses do not count because they are always host IPs return isThisHostIP(Domains.dnsResolve(hostName)); } /** * this method is deprecated in some way because it is not applicable on IPv6 * TODO: remove / replace * @param hostName * @return */ public static boolean isThisHostIP(final Set<String> hostNames) { if ((hostNames == null) || (hostNames.isEmpty())) return false; for (final String hostName: hostNames) { if (hostName.indexOf(':') > 0) return false; // IPv6 addresses do not count because they are always host IPs if (isThisHostIP(Domains.dnsResolve(hostName))) return true; } return false; } public static boolean isThisHostIP(final InetAddress clientAddress) { if (clientAddress == null) return false; if (clientAddress.isAnyLocalAddress() || clientAddress.isLoopbackAddress()) return true; return myHostAddresses.contains(clientAddress); // includes localHostAddresses } public static String chopZoneID(final String ip) { final int i = ip.indexOf('%'); return i < 0 ? ip : ip.substring(0, i); } /** * check the host ip string against localhost names * @param host * @return true if the host from the string is the localhost */ public static boolean isLocalhost(String host) { if (host == null) return true; // filesystems do not have host names host = chopZoneID(host); return LOCALHOST_PATTERNS.matcher(host).matches() || localHostNames.contains(host); } /** * check if a given host is the name for a local host address * this method will return true if noLocalCheck is switched on. This means that * not only local and global addresses are then not distinguished but also that * global address hashes do not fit any more to previously stored address hashes since * local/global is marked in the hash. * @param host * @return */ public static boolean isIntranet(final String host) { return (noLocalCheck || // DO NOT REMOVE THIS! it is correct to return true if the check is off host == null || // filesystems do not have host names INTRANET_PATTERNS.matcher(host).matches()) || localHostNames.contains(host); } /** * check if the given host is a local address. * the hostaddress is optional and shall be given if the address is already known * @param host * @param hostaddress may be null if not known yet * @return true if the given host is local */ public static boolean isLocal(final String host, final InetAddress hostaddress) { return isLocal(host, hostaddress, true); } private static boolean isLocal(final String host, InetAddress hostaddress, final boolean recursive) { if (noLocalCheck || // DO NOT REMOVE THIS! it is correct to return true if the check is off host == null || host.isEmpty()) return true; // check local ip addresses if (isIntranet(host)) return true; if (hostaddress != null && (isIntranet(hostaddress.getHostAddress()) || isLocal(hostaddress))) return true; // check if there are other local IP addresses that are not in // the standard IP range if (localHostNames.contains(host)) return true; // check simply if the tld in the host is a known tld final int p = host.lastIndexOf('.'); final String tld = (p > 0) ? host.substring(p + 1) : ""; final Integer i = TLDID.get(tld); if (i != null) return false; // check dns lookup: may be a local address even if the domain name looks global if (!recursive) return false; if (hostaddress == null) hostaddress = dnsResolve(host); return isLocal(hostaddress); } private static boolean isLocal(final InetAddress a) { final boolean localp = noLocalCheck || // DO NOT REMOVE THIS! it is correct to return true if the check is off a == null || a.isAnyLocalAddress() || a.isLinkLocalAddress() || a.isLoopbackAddress() || a.isSiteLocalAddress(); return localp; } /** * Compute the Second Level Domain of a host name excluding a possible use of a ccSLD. * If the SLD is a ccSLD, then the Third Level Domain is returned * @param host * @return the SLD or the Third Level Domain, if the SLD is a ccSLD */ public static String getSmartSLD(final String host) { if (host == null || host.length() == 0) return ""; final int p0 = host.lastIndexOf('.'); if (p0 < 0) return host.toLowerCase(); // no subdomain present final int p1 = host.lastIndexOf('.', p0 - 1); if (p1 < 0) return host.substring(0, p0).toLowerCase(); // no third-level domain present, just use the second level final String ccSLDTLD = host.substring(p1 + 1).toLowerCase(); if (!ccSLD_TLD.contains(ccSLDTLD)) return host.substring(p1 + 1, p0).toLowerCase(); // because the ccSLDTLD is not contained in the list of knwon ccSDL, we use the SLD from p1 to p0 // the third level domain is the correct one final int p2 = host.lastIndexOf('.', p1 - 1); if (p2 < 0) return host.substring(0, p1).toLowerCase(); return host.substring(p2 + 1, p1); } public static void main(final String[] args) { InetAddress a; a = dnsResolve("yacy.net"); System.out.println(a); a = dnsResolve("kaskelix.de"); System.out.println(a); a = dnsResolve("yacy.net"); System.out.println(a); try { Thread.sleep(1000);} catch (final InterruptedException e) {} // get time for class init System.out.println("myPublicLocalIP: " + myPublicLocalIP()); for (final InetAddress b : myIntranetIPs()) { System.out.println("Intranet IP: " + b); } } }
yacy/searchlab
src/eu/searchlab/tools/Domains.java
249,365
package main.user; import java.time.Instant; import java.time.LocalDate; import java.time.Period; import java.time.ZoneId; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Score { private final List<ScoreEntry> aScoreHistory = new ArrayList<>(); private final List<ScoreEntry> eScoreHistory = new ArrayList<>(); private int activeScore = zero; private int expertScore = zero; private static final int zero = 0; //getter public int getActiveScore() { return activeScore; } public int getExpertScore() { return expertScore; } public List<ScoreEntry> getaScoreHistory() { return Collections.unmodifiableList(aScoreHistory); // for testing purposes only // return aScoreHistory; } public List<ScoreEntry> geteScoreHistory() { return Collections.unmodifiableList(eScoreHistory); } //setter public void setaScore(String caseTitel,String reason, int aScore) { this.activeScore += aScore; aScoreHistory.add(new ScoreEntry(caseTitel, reason, aScore)); } public void seteScoer(String caseTitel,String reason, int eScoer) { this.expertScore += eScoer; eScoreHistory.add(new ScoreEntry(caseTitel, reason, eScoer)); } //print from to with period public void printFromToPeriod(Instant cDate,Instant endDate, Period period, boolean offset) { StringBuilder sb = new StringBuilder(); LocalDate start = LocalDate.ofInstant(cDate, ZoneId.systemDefault()); LocalDate end = LocalDate.ofInstant(endDate, ZoneId.systemDefault()); List<LocalDate> dateList = new ArrayList<>(); start.datesUntil(end ,period).forEach((dateList::add)); dateList.add(end); int lastListEntry = (dateList.size() - 1); int sum = zero; for (int i = zero; i < lastListEntry; i++) { LocalDate from = dateList.get(i); LocalDate to = dateList.get(i+1); for (ScoreEntry s: aScoreHistory) { if((from.compareTo(s.getCreatedAtAsLocalDate()) <= zero && to.compareTo(s.getCreatedAtAsLocalDate()) > zero) || (to.isEqual(dateList.get(lastListEntry)) && from.compareTo(s.getCreatedAtAsLocalDate()) <= zero && to.compareTo(s.getCreatedAtAsLocalDate()) >= zero)) sum+=s.getAddedScore(); } sb.append(from.toString()).append(" - ").append(to.toString()).append(" | Added Score : ").append(sum).append("\n"); if(!offset) sum = zero; } System.out.println(sb); } // // print all entrys public void printAllAScoreEntrys() { StringBuilder sb = new StringBuilder(); for (ScoreEntry s: aScoreHistory) { sb.append(s).append("\n"); } System.out.println(sb); } public void printAllEScoreEntrys() { StringBuilder sb = new StringBuilder(); for (ScoreEntry s: eScoreHistory) { sb.append(s).append("\n"); } System.out.println(sb); } }
sualak/FivePenals
src/domain/main/user/Score.java
249,366
/** * Copyright (c) 2012-2013, Daniele Codecasa <[email protected]>, * Models and Algorithms for Data & Text Mining (MAD) laboratory of * Milano-Bicocca University, and all the CTBNCToolkit contributors * that will follow. * All rights reserved. * * @author Daniele Codecasa and all the CTBNCToolkit contributors that will follow. * @copyright 2012-2013 Daniele Codecasa, MAD laboratory, and all the CTBNCToolkit contributors that will follow */ package CTBNCToolkit; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Vector; /** * @author Daniele Codecasa <[email protected]> * * Class that define a classifiers container where a model * is learned for each class and the classification is made * using the experts votes. * * Example: in a 3 class problem 3 binary CTNBClassifier are * generated one to classify class 1 against the others, 2 * for class 2 against the others, 3 for class 3 against the * others. * The classification relies on the model voting for their * specialization class. * * @param <TimeType> type of the time interval (Integer = discrete time, Double = continuous time) * @param <NodeType> node type */ public class MultipleCTBNC<TimeType extends Number & Comparable<TimeType>, NodeType extends INode> implements ICTClassifier<TimeType,NodeType> { static public String otherStateName = "#"; private String name; private ICTClassifier<TimeType,NodeType> baseModel; private List<ICTClassifier<TimeType,NodeType>> models; private boolean[][] adjMatrix; /** * Base constructor. * * @param name model name * @param baseModel original model to use to generate the models experts */ public MultipleCTBNC(String name, ICTClassifier<TimeType,NodeType> baseModel) { this.name = name; this.baseModel = baseModel; DiscreteNode classNode = baseModel.getClassNode(); this.models = new Vector<ICTClassifier<TimeType,NodeType>>( classNode.getStatesNumber()); for( int i = 0; i < classNode.getStatesNumber(); ++i) { ICTClassifier<TimeType,NodeType> newModel = (ICTClassifier<TimeType,NodeType>) baseModel.clone(); // Change the class of the new model in a binary class newModel.getClassNode().forceBinaryStates( newModel.getClassNode().getStateName( i)); this.models.add( newModel); } } /** * Constructor to insert directly the elements. * * @param name model name * @param baseModel original model used to generate the models experts * @param models list of models experts */ private MultipleCTBNC(String name, ICTClassifier<TimeType,NodeType> baseModel, List<ICTClassifier<TimeType,NodeType>> models) { if( name == null || name.isEmpty()) throw new IllegalArgumentException("Error: null or empty model name"); if( baseModel == null) throw new IllegalArgumentException("Error: null base models arguments"); if( models == null || models.isEmpty()) throw new IllegalArgumentException("Error: null or empty list of experts models"); this.name = name; this.baseModel = baseModel; this.models = models; } /** * Get the name of the class with that index. * * @param classIndex index of the class * @return name of the class with index idx */ public String getClassName(int classIndex) { if( classIndex < 0 || classIndex >= models.size()) throw new IllegalArgumentException("Error: class index out of range"); return this.baseModel.getClassNode().getStateName( classIndex); } /** * Return the number of model (it is equal * to the number of classes). * * @return number of models */ public int getNumberOfModel() { return this.models.size(); } /** * Get the model by index. * * @param classIndex class index for which the model is an expert * @throws IllegalArgumentException in case of illegal argument */ public ICTClassifier<TimeType,NodeType> getModel(int classIndex) throws IllegalArgumentException { if( classIndex < 0 || classIndex >= models.size()) throw new IllegalArgumentException("Error: a model is defined for each class, so the range of value is {0,..., #classes}"); return this.models.get( classIndex); } /* (non-Javadoc) * @see CTBNToolkit.IModel#getName() */ @Override public String getName() { return this.name; } /* (non-Javadoc) * @see CTBNToolkit.IModel#getNode(int) */ @Override public NodeType getNode(int iNode) throws IllegalArgumentException { return this.baseModel.getNode(iNode); } /* (non-Javadoc) * @see CTBNToolkit.IModel#generateTrajectory(double) */ @Override public ITrajectory<TimeType> generateTrajectory(double T) throws RuntimeException { throw new RuntimeException("Error: MultipleCTBNC class does not support trajectories generation"); } /* (non-Javadoc) * @see CTBNToolkit.IModel#getAdjMatrix() */ @Override public boolean[][] getAdjMatrix() { return this.adjMatrix; } /* (non-Javadoc) * @see CTBNToolkit.IModel#setStructure(boolean[][]) */ @Override public void setStructure(boolean[][] adjMatrix) throws RuntimeException { for(int i = 0; i < this.models.size(); ++i) this.models.get(i).setStructure(adjMatrix); this.adjMatrix = adjMatrix; } /* (non-Javadoc) * @see CTBNToolkit.IModel#getNodeIndexing() */ @Override public NodeIndexing getNodeIndexing() { return this.baseModel.getNodeIndexing(); } /* (non-Javadoc) * @see CTBNToolkit.ICTClassifier#getClassNode() */ @Override public DiscreteNode getClassNode() { return this.baseModel.getClassNode(); } /* (non-Javadoc) * @see CTBNToolkit.ICTClassifier#classify(CTBNToolkit.IClassifyAlgorithm, CTBNToolkit.ITrajectory) */ @Override public IClassificationResult<TimeType> classify( IClassifyAlgorithm<TimeType, NodeType> algorithm, ITrajectory<TimeType> trajectory) throws Exception { // Classify with all the models List<IClassificationResult<TimeType>> results = new Vector<IClassificationResult<TimeType>>(this.models.size()); for( int i = 0; i < this.models.size(); ++i) { // Transform the trajectory ITrajectory<TimeType> trj = generateClassTrajectory(trajectory, i); // Classify the trajectory results.add( algorithm.classify( this.getModel(i), trj)); } // Generate the result // Initialization DiscreteNode classNode = this.baseModel.getClassNode(); Map<String,Integer> stateToIndex = new TreeMap<String,Integer>(); for(int i = 0; i < classNode.getStatesNumber(); ++i) stateToIndex.put(classNode.getStateName(i), i); // Result initialization ClassificationResults<TimeType> finalResult = new ClassificationResults<TimeType>( trajectory); int iJmp; if( algorithm.probabilityFlag()) iJmp = 0; else iJmp = finalResult.getTransitionsNumber() - 1; // Calculate the probabilities for(; iJmp < finalResult.getTransitionsNumber(); ++iJmp) { double[] p = new double[results.size()]; // Get the probability for each class for(int iC = 0; iC < p.length; ++iC) p[iC] = results.get( iC).getProbability( classNode.getStateName( iC)); // Normalize p = MultipleCTBNC.normalizeDistribution(p); // Set result finalResult.setProbability(iJmp, p, stateToIndex); if( iJmp == finalResult.getTransitionsNumber() - 1) finalResult.setClassification( classNode.getStateName( MultipleCTBNC.indexMax(p))); } return finalResult; } @Override public IClassificationResult<TimeType> classify( IClassifyAlgorithm<TimeType, NodeType> algorithm, ITrajectory<TimeType> trajectory, TimeType samplingInterval) throws Exception { // Classify with all the models List<IClassificationResult<TimeType>> results = new Vector<IClassificationResult<TimeType>>(this.models.size()); for( int i = 0; i < this.models.size(); ++i) { // Transform the trajectory ITrajectory<TimeType> trj = generateClassTrajectory(trajectory, i); // Classify the trajectory results.add( algorithm.classify( this.getModel(i), trj, samplingInterval)); } // Generate the result // Initialization DiscreteNode classNode = this.baseModel.getClassNode(); Map<String,Integer> stateToIndex = new TreeMap<String,Integer>(); for(int i = 0; i < classNode.getStatesNumber(); ++i) stateToIndex.put(classNode.getStateName(i), i); Vector<TimeType> timeStream = new Vector<TimeType>( results.get(0).getTransitionsNumber()); for(int i = 0; i < results.get(0).getTransitionsNumber(); ++i) timeStream.add( results.get(0).getTransitionTime(i)); // Result initialization ClassificationResults<TimeType> finalResult = new ClassificationResults<TimeType>( trajectory, timeStream); int iJmp; if( algorithm.probabilityFlag()) iJmp = 0; else iJmp = finalResult.getTransitionsNumber() - 1; // Calculate the probabilities for(; iJmp < finalResult.getTransitionsNumber(); ++iJmp) { double[] p = new double[results.size()]; // Get the probability for each class for(int iC = 0; iC < p.length; ++iC) p[iC] = results.get( iC).getProbability( classNode.getStateName( iC)); // Normalize p = MultipleCTBNC.normalizeDistribution(p); // Set result finalResult.setProbability(iJmp, p, stateToIndex); if( iJmp == finalResult.getTransitionsNumber() - 1) finalResult.setClassification( classNode.getStateName( MultipleCTBNC.indexMax(p))); } return finalResult; } /* (non-Javadoc) * @see CTBNToolkit.ICTClassifier#classify(CTBNToolkit.IClassifyAlgorithm, CTBNToolkit.ITrajectory, java.util.Vector) */ @Override public IClassificationResult<TimeType> classify( IClassifyAlgorithm<TimeType, NodeType> algorithm, ITrajectory<TimeType> trajectory, Vector<TimeType> timeStream) throws Exception { // Classify with all the models List<IClassificationResult<TimeType>> results = new Vector<IClassificationResult<TimeType>>(this.models.size()); for( int i = 0; i < this.models.size(); ++i) { // Transform the trajectory ITrajectory<TimeType> trj = generateClassTrajectory(trajectory, i); // Classify the trajectory results.add( algorithm.classify( this.getModel(i), trj, timeStream)); } // Generate the result // Initialization DiscreteNode classNode = this.baseModel.getClassNode(); Map<String,Integer> stateToIndex = new TreeMap<String,Integer>(); for(int i = 0; i < classNode.getStatesNumber(); ++i) stateToIndex.put(classNode.getStateName(i), i); // Result initialization ClassificationResults<TimeType> finalResult = new ClassificationResults<TimeType>( trajectory, timeStream); int iJmp; if( algorithm.probabilityFlag()) iJmp = 0; else iJmp = finalResult.getTransitionsNumber() - 1; // Calculate the probabilities for(; iJmp < finalResult.getTransitionsNumber(); ++iJmp) { double[] p = new double[results.size()]; // Get the probability for each class for(int iC = 0; iC < p.length; ++iC) p[iC] = results.get( iC).getProbability( classNode.getStateName( iC)); // Normalize p = MultipleCTBNC.normalizeDistribution(p); // Set result finalResult.setProbability(iJmp, p, stateToIndex); if( iJmp == finalResult.getTransitionsNumber() - 1) finalResult.setClassification( classNode.getStateName( MultipleCTBNC.indexMax(p))); } return finalResult; } @Override public IModel<TimeType,NodeType> clone() { List<ICTClassifier<TimeType,NodeType>> newModels = new Vector<ICTClassifier<TimeType,NodeType>>(this.models.size()); for(int i = 0; i < this.models.size(); ++i) newModels.add(( ICTClassifier<TimeType,NodeType>) this.models.get( i).clone()); MultipleCTBNC<TimeType,NodeType> clonedModel = new MultipleCTBNC<TimeType, NodeType>(this.name, this.baseModel, newModels); return clonedModel; } /** * Print the model in string. * * @return the representation of the model */ public String toString() { StringBuilder strBuilder = new StringBuilder(); for( int i = 0; i < this.models.size(); ++i) { strBuilder.append("Model " + i + " Class " + this.baseModel.getClassNode().getStateName(i) + "\n"); strBuilder.append(this.models.get(i).toString() + "\n\n"); } return strBuilder.toString(); } /** * Transform the input trajectories in an * equal trajectory where the class variable * has only 2 states: the one associated to * the class index and all the others. * * @param trajectory trajectory to transform * @param classIdx class index * @return binary trajectory */ public ITrajectory<TimeType> generateClassTrajectory(ITrajectory<TimeType> trajectory, int classIdx) { List<TimeType> times = new Vector<TimeType>( trajectory.getTransitionsNumber()); List<String[]> values = new Vector<String[]>( trajectory.getTransitionsNumber()); int nNodes = trajectory.getNodeIndexing().getNodesNumber(); int classNodeIndex = trajectory.getNodeIndexing().getClassIndex(); for( int i = 0; i < trajectory.getTransitionsNumber(); ++i) { // Copy the time times.add( trajectory.getTransitionTime(i)); // Copy the states String[] v = new String[nNodes]; for(int j = 0; j < nNodes; ++j) v[j] = trajectory.getNodeValue(i, j); // Change the class state if( !v[classNodeIndex].equals( this.baseModel.getClassNode().getStateName( classIdx))) v[classNodeIndex] = MultipleCTBNC.otherStateName; // Update the values values.add(v); } return (ITrajectory<TimeType>) new CTTrajectory<TimeType>( trajectory.getNodeIndexing(), times, values); } /** * Normalize a vector generating a distribution. * * @param p vector to normalize * @return a probability distribution */ private static double[] normalizeDistribution(double[] p) throws IllegalArgumentException { if( p == null || p.length < 1) throw new IllegalArgumentException("Error: empty vector"); double s = 0; double[] newP = new double[p.length]; for( int i = 0; i < p.length; ++i) s += p[i]; for( int i = 0; i < p.length; ++i) newP[i] = p[i]/s; return newP; } /** * Find the index of the maximum value. * * @param p vector of values * @return index of the maximum value */ private static int indexMax(double[] p) throws IllegalArgumentException { if( p == null || p.length < 1) throw new IllegalArgumentException("Error: empty vector"); double max = p[0]; int iMax = 0; for(int i = 1; i < p.length; ++i) if( p[i] > max) { max = p[i]; iMax = i; } return iMax; } }
dcodecasa/CTBNCToolkit
CTBNCToolkit/MultipleCTBNC.java
249,367
package admin; /* * - BEWARE! FILE ENCODED BY UTF-8! * * - OH NO! WHY, CAP? * - JUST. * */ import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.ListSelectionModel; import javax.swing.Popup; import javax.swing.PopupFactory; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import GUI.database_unavailable; import components.querys; public class main extends JApplet implements ActionListener, ListSelectionListener, TableModelListener { //TABS JTabbedPane tabbedPane; JComponent panel1, panel2; JPanel TablePanel; //MENU /*JMenuBar menuBar; JMenu mode; JMenuItem expertMode, normalMode;*/ //TOOLBARS //EXPERT JToolBar expertToolbar; Dimension toolBarWidth = new Dimension(700,40); //Combo! JComboBox expertCombo; //BEWARE! LOoK at folowing, in cgi and there String[] comboWhat = { "Клиенты", "Заявки", "Работы заявки", "Работники в заявке", "Работы", "Работники" }; //ALIGNMENT (VERTICAL) Box expertTableBox; //STATUS //JLabel expertStatus; JTextArea expertStatusArea; //NoRMAL //TABLE JPanel expertTablePanel; Dimension expertTableWidth = new Dimension(480,380); JTable expertTable; JTableHeader expertTableHeader; JScrollPane expertScrollTable; DefaultTableModel dtm; String value1 = "", value2 = ""; static ArrayList<Object> popUps = new ArrayList<Object>(); //FIELDS JPanel expertFieldPanel; Dimension expertFieldWidth = new Dimension( toolBarWidth.width - expertTableWidth.width - 5, expertTableWidth.height ); JPanel inlayGrid; // For generated content Box expertFieldBox; // For vertical alligment JButton expertAdd, expertFieldClear; //.. other generates in table request //QUWERY querys q,q1; final public static String cgipath = "http://localhost/cgi-bin/cgi_job_list_project.exe?"; final public static String expChdd = "action=query&t=0"; Boolean god = true; poper pop; JPanel treePanel, addPanel; JTree tree, childTree; JScrollPane jst; ArrayList<Request> Requests = new ArrayList<Request>(); DefaultMutableTreeNode rootTreeModel = new DefaultMutableTreeNode("Requests"); JPopupMenu popupTreeActionMenu; JMenuItem popupTreeAdd, popupTreeRemove, popupTreeCheck, popupTreeunCheck; JList treeAddDataList; DefaultListModel dlm; JButton addOK, addNO; DefaultMutableTreeNode popapedObj, globePopapedObj; ArrayList<String> excludeIDs; Boolean isListShowing = false; final static String pathToIcons = "../images/"; database_unavailable dbu; ActionListener aa = new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (components.database.isDatabaseOK(cgipath.concat(expChdd))) { getContentPane().remove(dbu); initTabs(); initTreePanel(); initTablePanel(); initnShowList(1,null); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } };;; public void init() { //Execute a job on the event-dispatching thread; creating this applet's GUI. try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception evt) {} try { if (components.database.isDatabaseOK(cgipath.concat(expChdd))) { initTabs(); initTreePanel(); initTablePanel(); initnShowList(1,null); } else { dbu = new database_unavailable(aa);//, main.this); getContentPane().add(dbu); } } catch (IOException e) { dbu = new database_unavailable(aa);//, main.this); getContentPane().add(dbu); e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } public void initTabs() { /* Инициализация... * */ tabbedPane = new JTabbedPane(); add(tabbedPane); } public void setPopupWhat(Boolean a, Boolean b, Boolean c, Boolean d) { popupTreeAdd.setVisible(a); popupTreeRemove.setVisible(b); popupTreeCheck.setVisible(c); popupTreeunCheck.setVisible(d); } public void initTreePanel() { treePanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); if (Request.GrowForestIn(rootTreeModel)) { popupTreeActionMenu = new JPopupMenu(); popupTreeActionMenu.setPreferredSize(new Dimension(100,50)); popupTreeAdd = new JMenuItem("Добавить"); popupTreeAdd.setVisible(false); popupTreeActionMenu.add(popupTreeAdd); popupTreeAdd.addActionListener(this); popupTreeAdd.setIcon(createImageIcon(pathToIcons+"03.png", "")); popupTreeRemove = new JMenuItem("Удалить"); popupTreeRemove.setVisible(false); popupTreeActionMenu.add(popupTreeRemove); popupTreeRemove.addActionListener(this); popupTreeRemove.setIcon(createImageIcon(pathToIcons+"04.png", "")); popupTreeCheck = new JMenuItem("Завершить"); popupTreeCheck.setVisible(false); popupTreeActionMenu.add(popupTreeCheck); popupTreeCheck.addActionListener(this); popupTreeCheck.setIcon(createImageIcon(pathToIcons+"rDone.png", "")); popupTreeunCheck = new JMenuItem("Продолжить"); popupTreeunCheck.setVisible(false); popupTreeActionMenu.add(popupTreeunCheck); popupTreeunCheck.addActionListener(this); popupTreeunCheck.setIcon(createImageIcon(pathToIcons+"runDone.png", "")); tree = new JTree(rootTreeModel); tree.setCellRenderer(new myTreeRenderer()); tree.setRootVisible(false); // Установка режима выбора 1 узла дерева TreeSelectionModel tsm = tree.getSelectionModel(); tsm.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); jst = new JScrollPane(tree); jst.setPreferredSize(new Dimension(toolBarWidth.width-50, 300)); Border aquaBorder = UIManager.getBorder( "TitledBorder.aquaVariant" ); jst.setBorder( new TitledBorder( aquaBorder, "Список заявок" ) ); treePanel.add(jst); ImageIcon icon = createImageIcon("../images/p1.png", ""); tabbedPane.addTab("Учет заявок", icon, treePanel, "Does nothing"); // tree.add(popupTreeActionMenu); tree.addMouseListener(new TreeMouseListener()); } else JOptionPane.showMessageDialog(null, "Something wrong with the tree!"); } public void rechargeTree() { DefaultTreeModel model = (DefaultTreeModel)tree.getModel(); Request.GrowForestIn(rootTreeModel); model.reload(); } public void initnShowList(int what, ArrayList<Integer> excludeWhat){ /* * Функция отображает лист элементов для выбора * Получает что, получает список исключений * */ //JOBS, Please if (what==0) { //TODO HELLO! } else //WoRKERS if(what==1) { addPanel = new JPanel(); dlm = new DefaultListModel(); Object[] wha = db_selectAllDataFrom(5, true); for (int i=0; i < wha.length; i++) { dlm.addElement(wha[i]); } //dlm.addElement("Debbie Scott"); treeAddDataList = new JList(dlm); treeAddDataList.setCellRenderer(new IconListRenderer()); treeAddDataList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); treeAddDataList.setLayoutOrientation(JList.HORIZONTAL_WRAP); treeAddDataList.setVisibleRowCount(-1); JScrollPane jsa = new JScrollPane(treeAddDataList); jsa.setPreferredSize(new Dimension(toolBarWidth.width-200, 100)); Border aquaBorder = UIManager.getBorder( "TitledBorder.aquaVariant" ); jsa.setBorder( new TitledBorder( aquaBorder, "Выбор" ) ); addPanel.add(jsa); //treePanel.add(addPanel); JPanel jpadds = new JPanel(); jpadds.setPreferredSize(new Dimension(100,60)); // Border aquaBorder1 = UIManager.getBorder( "TitledBorder.aquaVariant" ); // jpadds.setBorder( new TitledBorder( aquaBorder1, " " ) ); addPanel.add(jpadds); addOK = new JButton("Добавить"); addOK.setPreferredSize(new Dimension(90,25)); addOK.addActionListener(this); jpadds.add(addOK); addNO = new JButton("Отмена"); addNO.setPreferredSize(new Dimension(90,25)); addNO.addActionListener(this); jpadds.add(addNO); } } public void initTablePanel() { TablePanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); //initMenu(); initToolbar(); initTable(); initFieldPanel(); ImageIcon icon = createImageIcon("../images/p2.png", ""); tabbedPane.addTab("Расширенные возможности работы с базой", icon, TablePanel, "Does nothing"); } /*public void initMenu() { Инициализация... * Меню апплета. Содержит главное меню с одним элементом, * включающим в себя еще два элемента. Предполагается * больше элементов menuBar = new JMenuBar(); setJMenuBar(menuBar); mode = new JMenu("Режим"); menuBar.add(mode); normalMode = new JMenuItem("Обычный"); //uncomment below if you need it (; //normalMode.addActionListener(this); expertMode = new JMenuItem("Эксперт"); expertMode.setEnabled(false); expertMode.addActionListener(this); mode.add(normalMode); mode.add(expertMode); }*/ public void initToolbar() { /* Инициализация... * Под меню апплета расположена панель инструментов. * Включает выпадающий список табличек и управляторы * основными действиями с табличками * */ //TOOLBAR_MAIN expertToolbar = new JToolBar(); TablePanel.add(expertToolbar); //SIZE expertToolbar.setPreferredSize(new Dimension(toolBarWidth)); //FLOAT?OH_NO! expertToolbar.setFloatable(false); //expertToolbar.setMargin(new Insets(-10, -10, 0, 0)); //OPAQUE?F**K_IT! expertToolbar.setOpaque(false); //FLOAT_CAP!FLOAT_TO_LEFT! expertToolbar.setAlignmentX(LEFT_ALIGNMENT); //SEXY-BORDER.DO_YA? Border empty = BorderFactory.createLineBorder(Color.LIGHT_GRAY); expertToolbar.setBorder(empty); //TOOLBAR_ELEMENTS //ЫУЗфКФещК! expertToolbar.addSeparator(); //COMBO_КОРОБКА ;) expertCombo = new JComboBox(comboWhat); expertToolbar.add(expertCombo); //SETTINGS_OF_КОМБО-КОРОБКА! //DID_U_SEEN_FOCUS? expertCombo.setFocusable(false); //APPLET_HEARING_COMBO! expertCombo.addActionListener(this); //COMBO-SIZE! expertCombo.setMaximumSize(new Dimension(150,23)); //ЫУЗфКФещК! expertToolbar.addSeparator(); //STATUS_LABEL //expertStatus = new JLabel("..:: Прикладное направление"); //expertToolbar.add(expertStatus); expertStatusArea = new JTextArea(); //expertStatusArea.setPreferredSize(new Dimension(150, 10)); expertStatusArea.setFont(new Font("sansserif", Font.PLAIN, 12)); expertStatusArea.setLineWrap(true); expertStatusArea.setWrapStyleWord(true); expertStatusArea.setEditable(false); expertStatusArea.insert("Журнал событий" , expertStatusArea.getLineCount()-1); JScrollPane jsca = new JScrollPane(expertStatusArea); jsca.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); jsca.setMaximumSize(new Dimension((toolBarWidth.width-180), 25)); expertToolbar.add(jsca); } public void initTable() { /* Инициализация... * Все, что связано с панелью с таблицей * */ //TABLE_PANEL (MAIN) expertTablePanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); expertTablePanel.setPreferredSize(new Dimension(expertTableWidth)); //+Border Border empty = BorderFactory.createLineBorder(Color.LIGHT_GRAY); expertTablePanel.setBorder(empty); TablePanel.add(expertTablePanel); //TABLE expertTable = new JTable(); //TABLE_MOUSE expertTable.addMouseListener(new TableMouseListener()); //DRAG'N'DROP? //expertTable.setDragEnabled(true); //TABLE_SCROLL expertScrollTable = new JScrollPane(expertTable); expertTablePanel.add(expertScrollTable); expertScrollTable.setPreferredSize(new Dimension(expertTableWidth.width-10,expertTableWidth.height-10)); // expertTable.setPreferredScrollableViewportSize(new Dimension(expertTableWidth)); // expertTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN); //TABLE_OPTIONS // TABLE_ROWSORTER expertTable.setAutoCreateRowSorter(true); // FOCUS expertTable.setFocusable(false); // TABLE_SELECTIONS expertTable.setColumnSelectionAllowed(false); expertTable.setCellSelectionEnabled(false); expertTable.setRowSelectionAllowed(true); expertTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //TABLE_ACTION_SELECT_LISTENER ListSelectionModel rowSM = expertTable.getSelectionModel(); rowSM.addListSelectionListener(this); //TABLE_COLSELECT_LISTENER (need in cell recognition as y) TableColumnModel tcol2 = expertTable.getColumnModel(); ListSelectionModel lsm = tcol2.getSelectionModel(); lsm.addListSelectionListener(this); } public void initFieldPanel(){ expertFieldPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); TablePanel.add(expertFieldPanel); expertFieldPanel.setPreferredSize(new Dimension(expertFieldWidth)); Border empty = BorderFactory.createLineBorder(Color.LIGHT_GRAY); expertFieldPanel.setBorder(empty); /* * TODO BEWARE, %Username%, * expertFieldBox.add(something); * ... * expertFieldBox.add(something); * remember yo! */ } //*** ACTIONS N LISTENERS *** //PROCESS_CLICK_ACTIONS public void actionPerformed(ActionEvent e) { /* * В событийной модели данный метод Слушателя * обрабатывает события ActionEvent e. * В программе сделан один слушатель - сам апплет, * и этот его метод (actionPerformed) обрабатывает все события, * требуется только определить кто породил и какое событие, * что делается ниже if'ами и case'ами * */ Object firedObject = e.getSource(); /*if (e.getSource() == expertMode) { } else if (e.getSource() == normalMode) { }else */ //IF_CLICK_COMBO if (firedObject == expertCombo) { switch (expertCombo.getSelectedIndex()) { //CLIENT case 0: { Object[][] chd = {{"№", "Фамилия", "Имя", "Отчество", "Адрес", "Телефон"}, {20, 90, 70, 80, 120, 60}}; setTable(0, chd); generateFields(chd[0]); break; } //REQUEST case 1: { Object[][] rhd = {{"№", "Приход", "Сдача", "Готово ли?", "Клиент"}, {20, 70, 70, 70, 50}}; setTable(1, rhd); generateFields(rhd[0]); break; } //JOB_LIST case 2: { Object[][] jlhd = {{"№", "№Заявки", "№Работы"}, {20, 70, 70}}; setTable(2, jlhd); generateFields(jlhd[0]); break; } //WORKER_LIST case 3: { Object[][] wlhd = {{"№", "№Заявки", "№Работника"}, {20, 80, 90}}; setTable(3, wlhd); generateFields(wlhd[0]); break; } //JOB case 4: { Object[][] jjhd = {{"№", "Описание", "Стоимость"}, {20, 400, 70}}; setTable(4, jjhd); generateFields(jjhd[0]); break; } //WORKER case 5: { Object[][] wwhd = {{"№", "Фамилия", "Имя", "Отчество", "Стаж"}, {50, 90, 70, 80, 50}}; setTable(5, wwhd); generateFields(wwhd[0]); break; } default: break; }//END_SWITCH } else if (firedObject == expertFieldClear) { clearFieldData(); // expertTable.getSelectionModel().clearSelection(); } else if (firedObject == expertAdd) { if (checkFields()) { expertStatusArea.append("\n" + now("HH:mm:ss - ") + "Статус добавленной записи:" + processInsertTableRecord()); rechargeTree(); expertCombo.setSelectedIndex(expertCombo.getSelectedIndex()); } else { /* * TODO popup * */ expertStatusArea.append("\n" + now("HH:mm:ss - ") + "Ошибка в заполнении формы!"); } //THERE_FIELD_FILLER /*TODO Сделать филлер драгндропный*/ /* int selectedRow = lsm.getMinSelectionIndex(); //GET_WHOLE_EDITS_AS_COMPONENTSofTHATPANEL int j=0; //Out counter JTextField jf; Object[] values = getSelectedRowDatums(selectedRow); for (int i = 0; i < inlayGrid.getComponentCount();i++) { Component heyhey = inlayGrid.getComponent(i); if (heyhey.getClass().getSimpleName().equals("JTextField")) { jf = (JTextField) heyhey; jf.setText((String)values[j]); j++; } }*/ } else //Если нажали в дереве добавить if (firedObject == addOK) { //Если что-то выбрано if (!treeAddDataList.isSelectionEmpty()) { //GET PARENT NEED REQUEST ID //Если выбрали заявку DefaultMutableTreeNode dmtaa = (DefaultMutableTreeNode) globePopapedObj.getParent(); if (dmtaa.getUserObject().getClass().equals(Request.class)) { // Выбираем ид заявки String id = ((Request) dmtaa.getUserObject()).getId(); System.out.println(id); //Вставляем выбранных работников в дерево addNewItems(globePopapedObj, treeAddDataList.getSelectedValues()); // Вставляем работников в базу db_insertRecords(3,id, treeAddDataList.getSelectedValues()); treeAddDataList.clearSelection(); treePanel.remove(addPanel); isListShowing = false; treePanel.validate(); repaint(); } } } else if (firedObject == addNO) { treePanel.remove(addPanel); isListShowing = false; treePanel.validate(); repaint(); } else // Popup actions // Добавить if (firedObject == popupTreeAdd) { globePopapedObj = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //globePopapedObj = //(DefaultMutableTreeNode) globePopapedObj.getParent(); treeAddDataList.clearSelection(); isListShowing = true; treePanel.add(addPanel); treePanel.validate(); repaint(); } else // Удалить if (firedObject == popupTreeRemove) { DefaultMutableTreeNode sel = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); db_RemoveRecords(3,((Request.Worker) sel.getUserObject()).getId()); removeItem(); } else // Завершить if (firedObject == popupTreeCheck) { DefaultMutableTreeNode sel = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); ((Request) sel.getUserObject()).setIsDone("1"); db_setRequestState(true, true, sel.getUserObject()); tree.invalidate(); tree.repaint(); } else // Продолжить if (firedObject == popupTreeunCheck) { DefaultMutableTreeNode sel = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); ((Request) sel.getUserObject()).setIsDone("0"); db_setRequestState(false, false, sel.getUserObject()); tree.invalidate(); tree.repaint(); } } public void addNewItems(DefaultMutableTreeNode where, Object[] what) { // ВАЖНО - работа с уже готовым деревом может производится только через модель дерева. // Только в этом случае гарантируется правильная работа и вызов событий // В противном случае новые узлы могут быть не прорисованы DefaultTreeModel model = (DefaultTreeModel)tree.getModel(); Object obj = tree.getLastSelectedPathComponent(); if(obj!=null) { //DefaultMutableTreeNode sel = (DefaultMutableTreeNode)obj; // Смотрим уровень вложенности и работаем в соответствии с ним // if(sel.getLevel()==1) { for (int i=0; i< what.length; i++) { DefaultMutableTreeNode tmp = new DefaultMutableTreeNode(what[i]); model.insertNodeInto(tmp, where, where.getChildCount()); tree.expandPath(new TreePath(where.getPath())); } //System.out.println(sel.getLevel()); } } public void removeItem() { // Смотри замечание в addNewItem() DefaultTreeModel model = (DefaultTreeModel)tree.getModel(); Object obj = tree.getLastSelectedPathComponent(); if(obj!=null) { DefaultMutableTreeNode sel = (DefaultMutableTreeNode)obj; // Корень удалять нельзя if(!sel.isRoot()) { if(sel.getChildCount()==0) model.removeNodeFromParent(sel); else // Если есть "детишки" выведем сообщение JOptionPane.showMessageDialog(null, "Remove all subnodes"); } } } public void valueChanged(ListSelectionEvent le) { //Ignore extra messages. if (le.getValueIsAdjusting()) return; ListSelectionModel lsm = (ListSelectionModel)le.getSource(); if (lsm.isSelectionEmpty()) { // HELLO! } else { if ((expertTable.getSelectedRow()!=-1) && (expertTable.getSelectedColumn()!=-1)) { value1 = (String) dtm.getValueAt(expertTable.getSelectedRow(), expertTable.getSelectedColumn()); /* * BUG Почему-то тут берет значение пустой ячейки как null * а в tableChanged(TableModelEvent tme) его как пусту строку * */ if (value1 == null) { value1 = ""; //expertStatusArea.append("\n"+"emptied"); } } //System.out.println(value); //expertTable.getSelectedColumn(); //dtm.getValueAt(row, column) /* int selectedRow = lsm.getMinSelectionIndex(); //GET_WHOLE_EDITS_AS_COMPONENTSofTHATPANEL int j=0; //Out counter JTextField jf; Object[] values = getSelectedRowDatums(selectedRow); for (int i = 0; i < inlayGrid.getComponentCount();i++) { Component heyhey = inlayGrid.getComponent(i); if (heyhey.getClass().getSimpleName().equals("JTextField")) { jf = (JTextField) heyhey; jf.setText((String)values[j]); j++; } }*/ // System.out.print(selectedRow + " | " +getSelectedRowDatums(selectedRow)); } } public void tableChanged(TableModelEvent tme) { if (tme.getType() == TableModelEvent.UPDATE) { value2 = (String) dtm.getValueAt(expertTable.getSelectedRow(), expertTable.getSelectedColumn()); if (!value1.equals(value2)) { processUpdateTableRecord(tme.getLastRow()); if (processUpdateTableRecord(tme.getLastRow()).equals( "OK (executed)")) { pop = new poper("OK",expertTableWidth.width-20, (expertTable.getSelectedRow()*20) - 21); } else { pop = new poper("BAD",expertTableWidth.width-20, (expertTable.getSelectedRow()*20) - 21); dtm.setValueAt(value1, expertTable.getSelectedRow(), expertTable.getSelectedColumn()); } rechargeTree(); } } } public class TableMouseListener extends MouseAdapter { /* * Мышиный адаптер к таблицке * Он нужен для выделения строк таблицы * правой кнопкой мыши и генерации popUP'ов * TODO много всяких скобок + куери переделать */ public void mouseClicked( MouseEvent e ) { //LEFT_MOUSE if ( SwingUtilities.isLeftMouseButton( e ) ) { //HELLO! } //RIGHT_MOUSE else if ( SwingUtilities.isRightMouseButton(e)) { // get the coordinates of the mouse click Point p = e.getPoint(); // get the row index that contains that coordinate int rowNumber = expertTable.rowAtPoint(p) ; // Get the ListSelectionModel of the JTable ListSelectionModel model = expertTable.getSelectionModel(); // set the selected interval of rows. Using the "rowNumber" // variable for the beginning and end selects only that one row. model.setSelectionInterval( rowNumber, rowNumber ); //DIALOG_CONFIRM Object[] options = {"Подтверждаю", "Я передумал!"}; int rez=JOptionPane.showOptionDialog(expertTablePanel, "Вы действительно хотите удалить запись: " + (rowNumber+1), "Удаление", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); //CLICKED_YO! DELETE RECORD! if (rez == JOptionPane.YES_OPTION) { //DELETE-QUERY String recordID = (String) dtm.getValueAt(rowNumber, 0); String qDelRequest = cgipath + "action=del"; qDelRequest += "&id=" + recordID; qDelRequest += "&t="+expertCombo.getSelectedIndex(); q = new querys(qDelRequest); if (q!= null) { String nextLine = ""; nextLine = q.getNextQueryLine(); nextLine = q.getNextQueryLine();// Берем 2-ю строку ответа if (nextLine.equals("OK")) { pop = new poper("OK",expertTableWidth.width-20, p.y - 21); dtm.removeRow(rowNumber); rechargeTree(); } else { pop = new poper("BAD",expertTableWidth.width-20, p.y - 21); } } } } } } public class TreeMouseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub //System.out.println("mc"); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub //System.out.println("me"); } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub //System.out.println("me"); } @Override public void mousePressed(MouseEvent mpr) { //DefaultMutableTreeNode what = getSelectedNodePlease() ; if ( mpr.isPopupTrigger() ) { formatePopupOfNode(mpr); } } @Override public void mouseReleased(MouseEvent mre) { int selRow = tree.getRowForLocation( mre.getX(), mre.getY()); if ( selRow<0 ) return; TreePath selPath = tree.getPathForLocation(mre.getX(), mre.getY()); tree.setSelectionPath(selPath); //DefaultMutableTreeNode what = getSelectedNodePlease(); if ( mre.isPopupTrigger() ) { formatePopupOfNode(mre); popapedObj = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //Формируем лист исключения рабочих if (popapedObj.getUserObject().equals("Работники")) { excludeIDs = new ArrayList<String>(); for (int i=0; i< popapedObj.getChildCount(); i++) { DefaultMutableTreeNode dn = (DefaultMutableTreeNode) popapedObj.getChildAt(i); excludeIDs.add(((Request.Worker) dn.getUserObject()).getId()); } System.out.println(Arrays.toString(excludeIDs.toArray())); } //Return Parent of // popapedObj = (DefaultMutableTreeNode) popapedObj.getParent(); //System.out.println(popapedObj.toString()); } // TODO: do task with the selected path } } public void formatePopupOfNode( MouseEvent me ) { DefaultMutableTreeNode what = null; Object obj = tree.getLastSelectedPathComponent(); if(obj!=null) { what = (DefaultMutableTreeNode)obj; } if ( what.getUserObject().getClass().equals(Request.Worker.class) ) { setPopupWhat(false, true, false, false); popupTreeActionMenu.setPreferredSize( new Dimension(110,40)); popupTreeActionMenu.show(me.getComponent(), me.getX(), me.getY()); } else if (what.getUserObject().equals("Работники") ) { setPopupWhat(true, false, false, false); popupTreeActionMenu.setPreferredSize( new Dimension(110,21)); popupTreeActionMenu.show(me.getComponent(), me.getX(), me.getY()); } else if ( what.getUserObject().getClass().equals(Request.class) ) { if (((Request)what.getUserObject()).getIsDone().equals("0")) { setPopupWhat(false, false, true, false); popupTreeActionMenu.setPreferredSize( new Dimension(120,21)); popupTreeActionMenu.show(me.getComponent(), me.getX(), me.getY()); } else if (((Request)what.getUserObject()).getIsDone().equals("1")) { setPopupWhat(false, false, false, true); popupTreeActionMenu.setPreferredSize( new Dimension(130,21)); popupTreeActionMenu.show(me.getComponent(), me.getX(), me.getY()); } } } // *** GENERIC FUNCTIONS *** public String now(String dateFormat) { /* Функция формирует текущее время * по шаблону */ Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); return sdf.format(cal.getTime()); } public ImageIcon createImageIcon(String path, String description) { /** Returns an ImageIcon, or null if the path was invalid. */ java.net.URL imgURL = getClass().getResource(path); if (imgURL != null) { return new ImageIcon(imgURL, description); } else { System.err.println("Couldn't find file: " + path); return null; } } public class poper implements ActionListener { /* * Всплывалка с информацией. * Используется для отражения * результатов запроса * */ Timer timer = new Timer(3000, this); Popup popup; public poper(String message, int x, int y) { createPopUpElement(message); PopupFactory factory = PopupFactory.getSharedInstance(); popup = factory.getPopup(main.this, (JButton)popUps.get(popUps.size()-1), expertTable.getLocationOnScreen().x+x, expertTable.getLocationOnScreen().y+y); popup.show(); timer.start(); } public void actionPerformed(ActionEvent e) { // Hide popup in n seconds if (e.getSource() == timer) { popup.hide(); popUps.remove(popUps.size()-1); //System.out.println(popUps.size()); timer.stop(); } } public void createPopUpElement(String w) { Dimension dSize = new Dimension(49,21); JButton bb = new JButton(w); Font bf = new Font("sansserif",Font.BOLD,11); bb.setFont(bf); if (w.equals("OK")) { bb.setBackground(new Color(154,200,153)); } else bb.setBackground(new Color(238,126,7)); bb.setEnabled(false); bb.setPreferredSize(new Dimension(dSize.width+10,dSize.height)); popUps.add(bb); } } // *** SPECIFIC FUNCTIONS *** //DATABASEeee //| //1 SELECT_ALL public Object[] db_selectAllDataFrom(int t, Boolean forceClass) { /** Возвращает Обжект обжектов! * Мобжкект джобжектов и * бобжект вобжектов * */ ArrayList<Object> YARRRR = new ArrayList<Object>(); Object[] aRow = null; String nextLine = ""; q = new querys(cgipath + "action=query&t=" + t); //IFEXISTS if ( q != null ) { //READ_QUERY //SKIP_FIRST nextLine = q.getNextQueryLine(); //READ_EM_ALL while (nextLine!=null) { nextLine = q.getNextQueryLine(); if (nextLine!=null) { //F**K_PATTERN - "something;something;something;...;something" aRow = nextLine.split(";"); //TABLE_ADD_F****D_ROW //FORCE CLASS FOR TREE if ( (forceClass) && (t==5/**WORKER*/) ) { Request.Worker wo = new Request.Worker( (String)aRow[0], (String)aRow[1], (String)aRow[2], (String)aRow[3], (String)aRow[4]); YARRRR.add(wo); //System.out.println(wo); } else YARRRR.add(aRow); //System.out.print(Arrays.asList(aRow)+"\n"); } } } return YARRRR.toArray(); } //| //2 ADD RECORDS public void db_insertRecords(int t, String id, Object[] what) { /* * TODO Ркализовать для осталных таблиц * или абстракция или зафорсить * * * !!! Предполагается что все записи успешно добавятся * */ //ArrayList<Object> YARRRR = new ArrayList<Object>(); for (int i = 0; i<what.length;i++) { //IF WORKER //System.out.println(what.getClass().getCanonicalName()); if (what[i].getClass().equals(Request.Worker.class)) { String insertQ = cgipath + "action=add"; Request.Worker heyhey = ((Request.Worker)what[i]); insertQ += "&j=NULL&a="+id; insertQ += "&"+i+"=" + heyhey.getId().trim(); insertQ += "&t=" + t; q = new querys(insertQ); /* if (q!= null) { String nextLine = ""; nextLine = q.getNextQueryLine(); // Берем 2-ю строку ответа nextLine = q.getNextQueryLine(); System.out.println(insertQ + " " + nextLine); }*/ } } } //| //3 DELETE RECORD public void db_RemoveRecords(int t, String id) { String insertQ = cgipath + "action=del"; insertQ += "&0="+id; insertQ += "&t="+t; q = new querys(insertQ); if (q!= null) { String nextLine = ""; nextLine = q.getNextQueryLine(); // Берем 2-ю строку ответа nextLine = q.getNextQueryLine(); System.out.println(insertQ + " " + nextLine); } } //| //4 UPDATE RECORD public void db_updateRecord() { /** TODO */ } public void db_setRequestState(Boolean state, Boolean d, Object what) { String stateQ = cgipath + "action=update"; Request r = (Request) what; if (d) { stateQ += r.prepareToState(true).replace("$ouch!", state?"1":"0").replace("$datuuum!", now("yyyy-MM-dd")); } else stateQ += r.prepareToState(false).replace("$ouch!", state?"1":"0"); q = new querys(stateQ); if (q!= null) { String nextLine = ""; nextLine = q.getNextQueryLine(); // Берем 2-ю строку ответа nextLine = q.getNextQueryLine(); System.out.println(stateQ + " " + nextLine); } stateQ = null; } public String setTable(int t, Object[][] header) { /* * Функция получает номер таблички и двумерный * массив (имена столбиков/их ширина) и * выводит содержимое сущности из базы в * табличку * */ Object[] aRow = null; String result = "BAD", nextLine = ""; q = new querys(cgipath + "action=query&t=" + t); //IFEXISTS if ( q != null ) { result = "OK"; //TABLE(MODEL)_SET_HEADER dtm = new DefaultTableModel(header[0], 0); //TABLE_ROWSELECT_LISTENER (need in cell recognition as x) dtm.addTableModelListener(this); expertTable.setModel(dtm); //READ_QUERY //SKIP_FIRST nextLine = q.getNextQueryLine(); //READ_EM_ALL while (nextLine!=null) { nextLine = q.getNextQueryLine(); if (nextLine!=null) { //F**K_PATTERN - "something;something;something;...;something" aRow = nextLine.split(";"); //TABLE_ADD_F****D_ROW dtm.addRow(aRow); //System.out.print(Arrays.asList(aRow)+"\n"); } } //TABLE_SET_COLUMN_SIZES for (int i=0; i<expertTable.getColumnCount();i++){ TableColumn tcol = expertTable.getColumnModel().getColumn(i); tcol.setCellRenderer(new CustomTableCellRenderer()); Integer siz = new Integer(header[1][i].toString()); tcol.setPreferredWidth(siz.intValue()); } //OH_NO!SOme thing went! } else result = "BAD"; //aRow = null; return result; } public Object[] getSelectedRowDatums(int cRow) { /* → valueChanged * Данная функция получает на вход номер (строки таблички), * а на выходе возвращает массив значений всех элементов (строки) * (возможно, каким-то методом можно возвращать всю строку сразу, * но в данный момент он мне не известен (: * */ ArrayList<String> result = new ArrayList<String>(); TableModel tm = expertTable.getModel(); int end = tm.getColumnCount(); for (int i=0; i < end; i++) { result.add((String)tm.getValueAt(cRow,i)); } return result.toArray(); } public String processInsertTableRecord() { /* * Die Funktion ist ähnlich zu aktualisieren und * erhält eine Liste der Elemente hinzufügen (; * */ String insertQ = cgipath + "action=add"; String result = ""; for (int i = 0; i<inlayGrid.getComponentCount();i++) { Component heyhey = inlayGrid.getComponent(i); if (heyhey.getClass().getSimpleName().equals("JTextField")) { insertQ += "&"+i+"=" + ((JTextField) heyhey).getText().trim(); } } insertQ += "&t=" + expertCombo.getSelectedIndex(); q = new querys(insertQ); if (q!= null) { String nextLine = ""; nextLine = q.getNextQueryLine(); // Берем 2-ю строку ответа nextLine = q.getNextQueryLine(); result = nextLine; } return result; } public String processUpdateTableRecord(int cRow) { /* * Функция получает номер строки для обновления * аналогичной записи в базе * */ String updateQ = cgipath + "action=update"; String result = ""; //1.PREPARE_UPDATE_QUERY //1.1_WALK_THE_CHANGED_TABLE_ROW Object[] rowDatum = getSelectedRowDatums(cRow); for (int i=0; i < rowDatum.length; i++) { //LET_WITHOUT_UTF /* * TODO trim it! */ updateQ += "&"+i+"=" + rowDatum[i]; } updateQ += "&t=" + expertCombo.getSelectedIndex(); updateQ += "&where=" + rowDatum[0]; /**/ q = new querys(updateQ); if (q!= null) { String nextLine = ""; nextLine = q.getNextQueryLine(); // Берем 2-ю строку ответа nextLine = q.getNextQueryLine(); result = nextLine; } return result; } public void generateFields(Object[] names) { /* * Данный функций генерирует форму полей * с лейблами для табличек. Получает массив, предположительно, * с названиями полей таблицки * */ //REMOVE_ALL_COMPONENTS expertFieldPanel.removeAll(); expertFieldPanel.repaint(); //CENTRED_FORMATTING_INLAY_ELEMENTS inlayGrid = new JPanel(); expertFieldPanel.add(inlayGrid); inlayGrid.setLayout(new GridLayout(names.length*2+1,1)); //GENERATE_ALL_LABLESandFIELDS for (int i=0; i<names.length; i++) { JLabel jl = new JLabel((String) names[i]); //jl.setName(names.); inlayGrid.add(jl); JTextField jf = new JTextField(); inlayGrid.add(jf); jf.setPreferredSize(new Dimension(expertFieldWidth.width-14,24)); } //ACTION_BUTTONS //ADD expertAdd = new JButton("[+] Добавить"); expertAdd.addActionListener(this); expertFieldPanel.add(expertAdd); expertAdd.setPreferredSize(new Dimension(110,25)); //CLEAR expertFieldClear = new JButton("X"); expertFieldPanel.add(expertFieldClear); expertFieldClear.addActionListener(this); expertFieldClear.setPreferredSize(new Dimension(50,25)); //WTF?WITHouT_IT_and_SCROLLPANE_IF_USE_CONTENT_HIDING validate(); } //CLEAR_FIELDS public void clearFieldData() { //GET_WHOLE_EDITS_AS_COMPONENTSofTHATPANEL JTextField jf; for (int i = 0; i < inlayGrid.getComponentCount();i++) { Component heyhey = inlayGrid.getComponent(i); if (heyhey.getClass().getSimpleName().equals("JTextField")) { jf = (JTextField) heyhey; //SET_NULL jf.setText(""); } } } public Boolean checkFields() { Boolean rr = true; //GET_WHOLE_EDITS_AS_COMPONENTSofTHATPANEL JTextField jf; for (int i = 0; i < inlayGrid.getComponentCount();i++) { Component heyhey = inlayGrid.getComponent(i); if (heyhey.getClass().getSimpleName().equals("JTextField")) { jf = (JTextField) heyhey; rr = rr && !jf.getText().equals(""); } } return rr; } // *** RENDERERS class myTreeRenderer extends DefaultTreeCellRenderer { //icons String r1 = "rDone.png", r2 = "runDone.png", c = "client.png", j = "jobs.png", w = "workers.gif"; public myTreeRenderer() { //nope } public Component getTreeCellRendererComponent( JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent( tree, value, sel, expanded, leaf, row, hasFocus); DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; Object obj = node.getUserObject(); /*if (sel) { setBackgroundNonSelectionColor(null); setBackgroundSelectionColor(new Color(232,242,252)); }*/ if ( (obj.getClass().equals(Request.class) //&& (((Request)obj).getIsDone().equals("0")) )){ setFont(new Font("sansserif",Font.BOLD,12)); } else setFont(new Font("sansserif",Font.PLAIN,12)); setIcon(setMyIcon(obj)); return this; } protected ImageIcon setMyIcon(Object obj) { if (obj.getClass().equals(Request.class)) { if (((Request)obj).getIsDone().equals("1")) { ImageIcon icon = createImageIcon(pathToIcons+r1,""); return icon; } else if (((Request)obj).getIsDone().equals("0")) { ImageIcon icon = createImageIcon(pathToIcons+r2,""); return icon; } } else if (obj.getClass().equals(Request.Client.class)) { ImageIcon icon = createImageIcon(pathToIcons+c,""); return icon; } else if (obj.equals("Работы")) { ImageIcon icon = createImageIcon(pathToIcons+j,""); return icon; } else if (obj.equals("Работники")) { ImageIcon icon = createImageIcon(pathToIcons+w,""); return icon; } return null; } } public class IconListRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { // Get the renderer component from parent class JLabel label = null; if (isListShowing) { String rw = ((Request.Worker) value).getId(); if ( excludeIDs.contains(rw) ) { label = (JLabel) super.getListCellRendererComponent(list, value, index, false, false); label.setEnabled(false); label.setFocusable(false); label.setVisible(false); } else { label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } } else { label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } // Set icon to display for value ImageIcon icon = createImageIcon(pathToIcons+"workers.gif",""); label.setIcon(icon); return label; } } }
boa/javaJo
src/admin/main.java
249,368
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class ExpertSetter { public static void main (String[] args) throws java.lang.Exception { Scanner s = new Scanner(System.in); int cases = s.nextInt(); for (int index = 0;index < cases;index++){ double x = s.nextDouble(); double y = s.nextDouble(); if((y/x) >= 0.50) System.out.println("YES"); else System.out.println("NO"); } } }
SairamCharanX/source
codechef/ExpertSetter.java
249,369
/* * =========================================== * Java Pdf Extraction Decoding Access Library * =========================================== * * Project Info: http://www.idrsolutions.com * Help section for developers at http://www.idrsolutions.com/java-pdf-library-support/ * * (C) Copyright 1997-2013, IDRsolutions and Contributors. * * This file is part of JPedal * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * --------------- * Type1C.java * --------------- */ package org.jpedal.fonts; import java.awt.Rectangle; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.jpedal.fonts.glyph.PdfJavaGlyphs; import org.jpedal.fonts.glyph.T1Glyphs; import org.jpedal.fonts.objects.FontData; import org.jpedal.io.ObjectStore; import org.jpedal.io.PdfObjectReader; import org.jpedal.objects.raw.PdfDictionary; import org.jpedal.objects.raw.PdfObject; import org.jpedal.utils.LogWriter; /** * handlestype1 specifics */ public class Type1C extends Type1 { private static final long serialVersionUID = -3010162163120599585L; static final boolean debugFont = false; static final boolean debugDictionary = false; int ros = -1, CIDFontVersion = 0, CIDFontRevision = 0, CIDFontType = 0, CIDcount = 0, UIDBase = -1, FDArray = -1, FDSelect = -1; final static String[] OneByteCCFDict = { "version", "Notice", "FullName", "FamilyName", "Weight", "FontBBox", "BlueValues", "OtherBlues", "FamilyBlues", "FamilyOtherBlues", "StdHW", "StdVW", "Escape", "UniqueID", "XUID", "charset", "Encoding", "CharStrings", "Private", "Subrs", "defaultWidthX", "nominalWidthX", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "shortint", "longint", "BCD", "-reserved-" }; final static String[] TwoByteCCFDict = { "Copyright", "isFixedPitch", "ItalicAngle", "UnderlinePosition", "UnderlineThickness", "PaintType", "CharstringType", "FontMatrix", "StrokeWidth", "BlueScale", "BlueShift", "BlueFuzz", "StemSnapH", "StemSnapV", "ForceBold", "-reserved-", "-reserved-", "LanguageGroup", "ExpansionFactor", "initialRandomSeed", "SyntheticBase", "PostScript", "BaseFontName", "BaseFontBlend", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "ROS", "CIDFontVersion", "CIDFontRevision", "CIDFontType", "CIDCount", "UIDBase", "FDArray", "FDSelect", "FontName" }; // current location in file private int top = 0; private int charset = 0; private int enc = 0; private int charstrings = 0; private int stringIdx; private int stringStart; private int stringOffSize; private Rectangle BBox = null; private boolean hasFontMatrix = false;// hasFontBBox=false,; private int[] privateDict = { -1 }, privateDictOffset = { -1 }; private int currentFD = -1; private int[] defaultWidthX = { 0 }, nominalWidthX = { 0 }, fdSelect; /** decoding table for Expert */ private static final int ExpertSubCharset[] = { // 87 // elements 0, 1, 231, 232, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 272, 300, 301, 302, 305, 314, 315, 158, 155, 163, 320, 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346 }; /** lookup table for names for type 1C glyphs */ public static final String type1CStdStrings[] = { // 391 // elements ".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "exclamdown", "cent", "sterling", "fraction", "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", "endash", "dagger", "daggerdbl", "periodcentered", "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", "ellipsis", "perthousand", "questiondown", "grave", "acute", "circumflex", "tilde", "macron", "breve", "dotaccent", "dieresis", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "emdash", "AE", "ordfeminine", "Lslash", "Oslash", "OE", "ordmasculine", "ae", "dotlessi", "lslash", "oslash", "oe", "germandbls", "onesuperior", "logicalnot", "mu", "trademark", "Eth", "onehalf", "plusminus", "Thorn", "onequarter", "divide", "brokenbar", "degree", "thorn", "threequarters", "twosuperior", "registered", "minus", "eth", "multiply", "threesuperior", "copyright", "Aacute", "Acircumflex", "Adieresis", "Agrave", "Aring", "Atilde", "Ccedilla", "Eacute", "Ecircumflex", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis", "Ograve", "Otilde", "Scaron", "Uacute", "Ucircumflex", "Udieresis", "Ugrave", "Yacute", "Ydieresis", "Zcaron", "aacute", "acircumflex", "adieresis", "agrave", "aring", "atilde", "ccedilla", "eacute", "ecircumflex", "edieresis", "egrave", "iacute", "icircumflex", "idieresis", "igrave", "ntilde", "oacute", "ocircumflex", "odieresis", "ograve", "otilde", "scaron", "uacute", "ucircumflex", "udieresis", "ugrave", "yacute", "ydieresis", "zcaron", "exclamsmall", "Hungarumlautsmall", "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "zerooldstyle", "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "commasuperior", "threequartersemdash", "periodsuperior", "questionsmall", "asuperior", "bsuperior", "centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior", "msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior", "tsuperior", "ff", "ffi", "ffl", "parenleftinferior", "parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall", "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", "Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall", "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", "colonmonetary", "onefitted", "rupiah", "Tildesmall", "exclamdownsmall", "centoldstyle", "Lslashsmall", "Scaronsmall", "Zcaronsmall", "Dieresissmall", "Brevesmall", "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash", "hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall", "questiondownsmall", "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "zerosuperior", "foursuperior", "fivesuperior", "sixsuperior", "sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", "threeinferior", "fourinferior", "fiveinferior", "sixinferior", "seveninferior", "eightinferior", "nineinferior", "centinferior", "dollarinferior", "periodinferior", "commainferior", "Agravesmall", "Aacutesmall", "Acircumflexsmall", "Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall", "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall", "Odieresissmall", "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall", "001.000", "001.001", "001.002", "001.003", "Black", "Bold", "Book", "Light", "Medium", "Regular", "Roman", "Semibold" }; /** Lookup table to map values */ private static final int ISOAdobeCharset[] = { // 229 // elements 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228 }; /** lookup data to convert Expert values */ private static final int ExpertCharset[] = { // 166 // elements 0, 1, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 158, 155, 163, 319, 320, 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378 }; // one byte operators public final static int VERSION = 0; public final static int NOTICE = 1; public final static int FULLNAME = 2; public final static int FAMILYNAME = 3; public final static int WEIGHT = 4; public final static int FONTBBOX = 5; public final static int BLUEVALUES = 6; public final static int OTHERBLUES = 7; public final static int FAMILYBLUES = 8; public final static int FAMILYOTHERBLUES = 9; public final static int STDHW = 10; public final static int STDVW = 11; public final static int ESCAPE = 12; public final static int UNIQUEID = 13; public final static int XUID = 14; public final static int CHARSET = 15; public final static int ENCODING = 16; public final static int CHARSTRINGS = 17; public final static int PRIVATE = 18; public final static int SUBRS = 19; public final static int DEFAULTWIDTHX = 20; public final static int NOMINALWIDTHX = 21; public final static int RESERVED = 22; public final static int SHORTINT = 28; public final static int LONGINT = 29; public final static int BCD = 30; // two byte operators public final static int COPYRIGHT = 3072; public final static int ISFIXEDPITCH = 3073; public final static int ITALICANGLE = 3074; public final static int UNDERLINEPOSITION = 3075; public final static int UNDERLINETHICKNESS = 3076; public final static int PAINTTYPE = 3077; public final static int CHARSTRINGTYPE = 3078; public final static int FONTMATRIX = 3079; public final static int STROKEWIDTH = 3080; public final static int BLUESCALE = 3081; public final static int BLUESHIFT = 3082; public final static int BLUEFUZZ = 3083; public final static int STEMSNAPH = 3084; public final static int STEMSNAPV = 3085; public final static int FORCEBOLD = 3086; public final static int LANGUAGEGROUP = 3089; public final static int EXPANSIONFACTOR = 3090; public final static int INITIALRANDOMSEED = 3091; public final static int SYNTHETICBASE = 3092; public final static int POSTSCRIPT = 3093; public final static int BASEFONTNAME = 3094; public final static int BASEFONTBLEND = 3095; public final static int ROS = 3102; public final static int CIDFONTVERSION = 3103; public final static int CIDFONTREVISION = 3104; public final static int CIDFONTTYPE = 3105; public final static int CIDCOUNT = 3106; public final static int UIDBASE = 3107; public final static int FDARRAY = 3108; public final static int FDSELECT = 3109; public final static int FONTNAME = 3110; private int weight = 388;// make it default private int[] blueValues = null; private int[] otherBlues = null; private int[] familyBlues = null; private int[] familyOtherBlues = null; private int stdHW = -1, stdVW = -1, subrs = -1; private byte[] encodingDataBytes = null; private String[] stringIndexData = null; private int[] charsetGlyphCodes = null; private int charsetGlyphFormat = 0; private int[] rosArray = new int[3]; /** needed so CIDFOnt0 can extend */ public Type1C() {} /** get handles onto Reader so we can access the file */ public Type1C(PdfObjectReader current_pdf_file, String substituteFont) { this.glyphs = new T1Glyphs(false); init(current_pdf_file); this.substituteFont = substituteFont; } /** read details of any embedded fontFile */ protected void readEmbeddedFont(PdfObject pdfFontDescriptor) throws Exception { if (this.substituteFont != null) { byte[] bytes; // read details BufferedInputStream from; // create streams ByteArrayOutputStream to = new ByteArrayOutputStream(); InputStream jarFile = null; try { if (this.substituteFont.startsWith("jar:") || this.substituteFont.startsWith("http:")) jarFile = this.loader .getResourceAsStream(this.substituteFont); else jarFile = this.loader.getResourceAsStream("file:///" + this.substituteFont); } catch (Exception e) { if (LogWriter.isOutput()) LogWriter.writeLog("3.Unable to open " + this.substituteFont); } catch (Error err) { if (LogWriter.isOutput()) LogWriter.writeLog("3.Unable to open " + this.substituteFont); } if (jarFile == null) { /** * from=new BufferedInputStream(new FileInputStream(substituteFont)); * * //write byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, * bytes_read); * * to.close(); from.close(); * * / **/ File file = new File(this.substituteFont); InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { System.out.println("Sorry! Your given file is too large."); return; } bytes = new byte[(int) length]; int offset = 0; int numRead; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } is.close(); // new BufferedReader // (new InputStreamReader(loader.getResourceAsStream("org/jpedal/res/cid/" + encodingName), "Cp1252")); /** * FileReader from2=null; try { from2 = new FileReader(substituteFont); //new BufferedReader); //outputStream = new * FileWriter("characteroutput.txt"); * * int c; while ((c = from2.read()) != -1) { to.write(c); } } finally { if (from2 != null) { from2.close(); } if (to != null) { * to.close(); } }/ **/ } else { from = new BufferedInputStream(jarFile); // write byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); to.close(); from.close(); bytes = to.toByteArray(); } /** load the font */ try { this.isFontSubstituted = true; // if (substituteFont.indexOf(".afm") != -1) readType1FontFile(bytes); // else // readType1CFontFile(to.toByteArray(),null); } catch (Exception e) { e.printStackTrace(System.out); if (LogWriter.isOutput()) LogWriter.writeLog("[PDF]Substitute font=" + this.substituteFont + "Type 1 exception=" + e); } // over-ride font remapping if substituted if (this.isFontSubstituted && this.glyphs.remapFont) this.glyphs.remapFont = false; } else if (pdfFontDescriptor != null) { PdfObject FontFile = pdfFontDescriptor.getDictionary(PdfDictionary.FontFile); /** try type 1 first then type 1c/0c */ if (FontFile != null) { try { byte[] stream = this.currentPdfFile.readStream(FontFile, true, true, false, false, false, FontFile.getCacheName(this.currentPdfFile.getObjectReader())); if (stream != null) readType1FontFile(stream); } catch (Exception e) { // tell user and log if (LogWriter.isOutput()) LogWriter.writeLog("Exception: " + e.getMessage()); } } else { PdfObject FontFile3 = pdfFontDescriptor.getDictionary(PdfDictionary.FontFile3); if (FontFile3 != null) { byte[] stream = this.currentPdfFile.readStream(FontFile3, true, true, false, false, false, FontFile3.getCacheName(this.currentPdfFile.getObjectReader())); if (stream != null) { // if it fails, null returned // check for type1c or ottf if (stream.length > 3 && stream[0] == 719 && stream[1] == 84 && stream[2] == 84 && stream[3] == 79) {} else // assume all standard cff for moment readType1CFontFile(stream, null); } } } } } /** read in a font and its details from the pdf file */ @Override public void createFont(PdfObject pdfObject, String fontID, boolean renderPage, ObjectStore objectStore, Map substitutedFonts) throws Exception { this.fontTypes = StandardFonts.TYPE1; // generic setup init(fontID, renderPage); /** * get FontDescriptor object - if present contains metrics on glyphs */ PdfObject pdfFontDescriptor = pdfObject.getDictionary(PdfDictionary.FontDescriptor); // FontBBox and FontMatix setBoundsAndMatrix(pdfFontDescriptor); setName(pdfObject, fontID); setEncoding(pdfObject, pdfFontDescriptor); try { readEmbeddedFont(pdfFontDescriptor); } catch (Exception e) { // tell user and log if (LogWriter.isOutput()) LogWriter.writeLog("Exception: " + e.getMessage()); } // setWidths(pdfObject); readWidths(pdfObject, true); // if(embeddedFontName!=null && is1C() && PdfStreamDecoder.runningStoryPad){ // embeddedFontName= cleanupFontName(embeddedFontName); // this.setBaseFontName(embeddedFontName); // this.setFontName(embeddedFontName); // } // make sure a font set if (renderPage) setFont(getBaseFontName(), 1); } /** Constructor for html fonts */ public Type1C(byte[] fontDataAsArray, PdfJavaGlyphs glyphs, boolean is1C) throws Exception { this.glyphs = glyphs; // generate reverse lookup so we can encode CMAP this.trackIndices = true; // flags we extract all details (used originally by rendering and now by PS2OTF) this.renderPage = true; if (is1C) readType1CFontFile(fontDataAsArray, null); else readType1FontFile(fontDataAsArray); } /** Constructor for OTF fonts */ public Type1C(byte[] fontDataAsArray, FontData fontData, PdfJavaGlyphs glyphs) throws Exception { this.glyphs = glyphs; readType1CFontFile(fontDataAsArray, fontData); } /** Handle encoding for type1C fonts. Also used for CIDFontType0C */ final private void readType1CFontFile(byte[] fontDataAsArray, FontData fontDataAsObject) throws Exception { if (LogWriter.isOutput()) LogWriter.writeLog("Embedded Type1C font used"); this.glyphs.setis1C(true); boolean isByteArray = (fontDataAsArray != null); // debugFont=getBaseFontName().indexOf("LC")!=-1; if (debugFont) System.err.println(getBaseFontName()); int start; // pointers within table int size = 2; /** * read Header */ int major, minor; if (isByteArray) { major = fontDataAsArray[0]; minor = fontDataAsArray[1]; } else { major = fontDataAsObject.getByte(0); minor = fontDataAsObject.getByte(1); } if ((major != 1 || minor != 0) && LogWriter.isOutput()) LogWriter.writeLog("1C format " + major + ':' + minor + " not fully supported"); if (debugFont) System.out.println("major=" + major + " minor=" + minor); // read header size to workout start of names index if (isByteArray) this.top = fontDataAsArray[2]; else this.top = fontDataAsObject.getByte(2); /** * read names index */ // read name index for the first font int count, offsize; if (isByteArray) { count = getWord(fontDataAsArray, this.top, size); offsize = fontDataAsArray[this.top + size]; } else { count = getWord(fontDataAsObject, this.top, size); offsize = fontDataAsObject.getByte(this.top + size); } /** * get last offset and use to move to top dict index */ this.top += (size + 1); // move pointer to start of font names start = this.top + (count + 1) * offsize - 1; // move pointer to end of offsets if (isByteArray) this.top = start + getWord(fontDataAsArray, this.top + count * offsize, offsize); else this.top = start + getWord(fontDataAsObject, this.top + count * offsize, offsize); /** * read the dict index */ if (isByteArray) { count = getWord(fontDataAsArray, this.top, size); offsize = fontDataAsArray[this.top + size]; } else { count = getWord(fontDataAsObject, this.top, size); offsize = fontDataAsObject.getByte(this.top + size); } this.top += (size + 1); // update pointer start = this.top + (count + 1) * offsize - 1; int dicStart, dicEnd; if (isByteArray) { dicStart = start + getWord(fontDataAsArray, this.top, offsize); dicEnd = start + getWord(fontDataAsArray, this.top + offsize, offsize); } else { dicStart = start + getWord(fontDataAsObject, this.top, offsize); dicEnd = start + getWord(fontDataAsObject, this.top + offsize, offsize); } /** * read string index */ String[] strings = readStringIndex(fontDataAsArray, fontDataAsObject, start, offsize, count); /** * read global subroutines (top set by Strings code) */ readGlobalSubRoutines(fontDataAsArray, fontDataAsObject); /** * decode the dictionary */ decodeDictionary(fontDataAsArray, fontDataAsObject, dicStart, dicEnd, strings); /** * allow for subdictionaries in CID font */ if (this.FDSelect != -1) { if (debugDictionary) System.out.println("=============FDSelect====================" + getBaseFontName()); // Read FDSelect int nextDic = this.FDSelect; int format; if (isByteArray) { format = getWord(fontDataAsArray, nextDic, 1); } else { format = getWord(fontDataAsObject, nextDic, 1); } int glyphCount; if (isByteArray) { glyphCount = getWord(fontDataAsArray, this.charstrings, 2); } else { glyphCount = getWord(fontDataAsObject, this.charstrings, 2); } this.fdSelect = new int[glyphCount]; if (format == 0) { // Format 0 is just an array of which to use for each glyph for (int i = 0; i < glyphCount; i++) { if (isByteArray) { this.fdSelect[i] = getWord(fontDataAsArray, nextDic + 1 + i, 1); } else { this.fdSelect[i] = getWord(fontDataAsObject, nextDic + 1 + i, 1); } } } else if (format == 3) { int nRanges; if (isByteArray) { nRanges = getWord(fontDataAsArray, nextDic + 1, 2); } else { nRanges = getWord(fontDataAsObject, nextDic + 1, 2); } int[] rangeStarts = new int[nRanges + 1], fDicts = new int[nRanges]; // Find ranges of glyphs with their DICT index for (int i = 0; i < nRanges; i++) { if (isByteArray) { rangeStarts[i] = getWord(fontDataAsArray, nextDic + 3 + (3 * i), 2); fDicts[i] = getWord(fontDataAsArray, nextDic + 5 + (3 * i), 1); } else { rangeStarts[i] = getWord(fontDataAsObject, nextDic + 3 + (3 * i), 2); fDicts[i] = getWord(fontDataAsObject, nextDic + 5 + (3 * i), 1); } } rangeStarts[rangeStarts.length - 1] = glyphCount; // Fill fdSelect array for (int i = 0; i < nRanges; i++) { for (int j = rangeStarts[i]; j < rangeStarts[i + 1]; j++) { this.fdSelect[j] = fDicts[i]; } } } ((T1Glyphs) this.glyphs).setFDSelect(this.fdSelect); // Read FDArray nextDic = this.FDArray; if (isByteArray) { count = getWord(fontDataAsArray, nextDic, size); offsize = fontDataAsArray[nextDic + size]; } else { count = getWord(fontDataAsObject, nextDic, size); offsize = fontDataAsObject.getByte(nextDic + size); } nextDic += (size + 1); // update pointer start = nextDic + (count + 1) * offsize - 1; this.privateDict = new int[count]; this.privateDictOffset = new int[count]; this.defaultWidthX = new int[count]; this.nominalWidthX = new int[count]; for (int i = 0; i < count; i++) { this.currentFD = i; this.privateDict[i] = -1; this.privateDictOffset[i] = -1; if (isByteArray) { dicStart = start + getWord(fontDataAsArray, nextDic + (i * offsize), offsize); dicEnd = start + getWord(fontDataAsArray, nextDic + ((i + 1) * offsize), offsize); } else { dicStart = start + getWord(fontDataAsObject, nextDic + (i * offsize), offsize); dicEnd = start + getWord(fontDataAsObject, nextDic + ((i + 1) * offsize), offsize); } decodeDictionary(fontDataAsArray, fontDataAsObject, dicStart, dicEnd, strings); } this.currentFD = -1; if (debugDictionary) System.out.println("=================================" + getBaseFontName()); } /** * get number of glyphs from charstrings index */ this.top = this.charstrings; int nGlyphs; if (isByteArray) nGlyphs = getWord(fontDataAsArray, this.top, size); // start of glyph index else nGlyphs = getWord(fontDataAsObject, this.top, size); // start of glyph index this.glyphs.setGlyphCount(nGlyphs); if (debugFont) System.out.println("nGlyphs=" + nGlyphs); int[] names = readCharset(this.charset, nGlyphs, fontDataAsObject, fontDataAsArray); if (debugFont) { System.out.println("=======charset==============="); int count2 = names.length; for (int jj = 0; jj < count2; jj++) { System.out.println(jj + " " + names[jj]); } System.out.println("=======Encoding==============="); } /** * set encoding if not set */ setEncoding(fontDataAsArray, fontDataAsObject, nGlyphs, names); /** * read glyph index */ this.top = this.charstrings; readGlyphs(fontDataAsArray, fontDataAsObject, nGlyphs, names); /**/ for (int i = 0; i < this.privateDict.length; i++) { this.currentFD = i; int dict = this.privateDict[i]; if (dict != -1) { int dictOffset = this.privateDictOffset[i]; decodeDictionary(fontDataAsArray, fontDataAsObject, dict, dictOffset + dict, strings); this.top = dict + dictOffset; int len, nSubrs; if (isByteArray) len = fontDataAsArray.length; else len = fontDataAsObject.length(); if (this.top + 2 < len) { if (isByteArray) nSubrs = getWord(fontDataAsArray, this.top, size); else nSubrs = getWord(fontDataAsObject, this.top, size); if (nSubrs > 0) readSubrs(fontDataAsArray, fontDataAsObject, nSubrs); } else if (debugFont || debugDictionary) { System.out.println("Private subroutine out of range"); } } } this.currentFD = -1; /**/ /** * set flags to tell software to use these descritpions */ this.isFontEmbedded = true; this.glyphs.setFontEmbedded(true); } /** pick up encoding from embedded font */ final private void setEncoding(byte[] fontDataAsArray, FontData fontDataAsObject, int nGlyphs, int[] names) { boolean isByteArray = fontDataAsArray != null; if (debugFont) System.out.println("Enc=" + this.enc); // read encoding (glyph -> code mapping) if (this.enc == 0) { this.embeddedEnc = StandardFonts.STD; if (this.fontEnc == -1) putFontEncoding(StandardFonts.STD); if (this.isCID) { // store values for lookup on text try { String name; for (int i = 1; i < nGlyphs; ++i) { if (names[i] < 391) { if (isByteArray) name = getString(fontDataAsArray, names[i], this.stringIdx, this.stringStart, this.stringOffSize); else name = getString(fontDataAsObject, names[i], this.stringIdx, this.stringStart, this.stringOffSize); putMappedChar(names[i], StandardFonts.getUnicodeName(name)); } } } catch (Exception e) { // tell user and log if (LogWriter.isOutput()) LogWriter.writeLog("Exception: " + e.getMessage()); } } } else if (this.enc == 1) { this.embeddedEnc = StandardFonts.MACEXPERT; if (this.fontEnc == -1) putFontEncoding(StandardFonts.MACEXPERT); } else { // custom mapping if (debugFont) System.out.println("custom mapping"); this.top = this.enc; int encFormat, c; if (isByteArray) encFormat = (fontDataAsArray[this.top++] & 0xff); else encFormat = (fontDataAsObject.getByte(this.top++) & 0xff); String name; if ((encFormat & 0x7f) == 0) { // format 0 int nCodes; if (isByteArray) nCodes = 1 + (fontDataAsArray[this.top++] & 0xff); else nCodes = 1 + (fontDataAsObject.getByte(this.top++) & 0xff); if (nCodes > nGlyphs) nCodes = nGlyphs; for (int i = 1; i < nCodes; ++i) { if (isByteArray) { c = fontDataAsArray[this.top++] & 0xff; name = getString(fontDataAsArray, names[i], this.stringIdx, this.stringStart, this.stringOffSize); } else { c = fontDataAsObject.getByte(this.top++) & 0xff; name = getString(fontDataAsObject, names[i], this.stringIdx, this.stringStart, this.stringOffSize); } putChar(c, name); } } else if ((encFormat & 0x7f) == 1) { // format 1 int nRanges; if (isByteArray) nRanges = (fontDataAsArray[this.top++] & 0xff); else nRanges = (fontDataAsObject.getByte(this.top++) & 0xff); int nCodes = 1; for (int i = 0; i < nRanges; ++i) { int nLeft; if (isByteArray) { c = (fontDataAsArray[this.top++] & 0xff); nLeft = (fontDataAsArray[this.top++] & 0xff); } else { c = (fontDataAsObject.getByte(this.top++) & 0xff); nLeft = (fontDataAsObject.getByte(this.top++) & 0xff); } for (int j = 0; j <= nLeft && nCodes < nGlyphs; ++j) { if (isByteArray) name = getString(fontDataAsArray, names[nCodes], this.stringIdx, this.stringStart, this.stringOffSize); else name = getString(fontDataAsObject, names[nCodes], this.stringIdx, this.stringStart, this.stringOffSize); putChar(c, name); nCodes++; c++; } } } if ((encFormat & 0x80) != 0) { // supplimentary encodings int nSups; if (isByteArray) nSups = (fontDataAsArray[this.top++] & 0xff); else nSups = (fontDataAsObject.getByte(this.top++) & 0xff); for (int i = 0; i < nSups; ++i) { if (isByteArray) c = (fontDataAsArray[this.top++] & 0xff); else c = (fontDataAsObject.getByte(this.top++) & 0xff); int sid; if (isByteArray) sid = getWord(fontDataAsArray, this.top, 2); else sid = getWord(fontDataAsObject, this.top, 2); this.top += 2; if (isByteArray) name = getString(fontDataAsArray, sid, this.stringIdx, this.stringStart, this.stringOffSize); else name = getString(fontDataAsObject, sid, this.stringIdx, this.stringStart, this.stringOffSize); putChar(c, name); } } } } // LILYPONDTOOL private final void readSubrs(byte[] fontDataAsArray, FontData fontDataAsObject, int nSubrs) throws Exception { boolean isByteArray = fontDataAsArray != null; int subrOffSize; if (isByteArray) subrOffSize = fontDataAsArray[this.top + 2]; else subrOffSize = fontDataAsObject.getByte(this.top + 2); this.top += 3; int subrIdx = this.top; int subrStart = this.top + (nSubrs + 1) * subrOffSize - 1; int nextTablePtr = this.top + nSubrs * subrOffSize; if (isByteArray) { if (nextTablePtr < fontDataAsArray.length) // allow for table at end of file this.top = subrStart + getWord(fontDataAsArray, nextTablePtr, subrOffSize); else this.top = fontDataAsArray.length - 1; } else { if (nextTablePtr < fontDataAsArray.length) // allow for table at end of file this.top = subrStart + getWord(fontDataAsObject, nextTablePtr, subrOffSize); else this.top = fontDataAsObject.length() - 1; } int[] subrOffset = new int[nSubrs + 2]; int ii = subrIdx; for (int jj = 0; jj < nSubrs + 1; jj++) { if (isByteArray) { if ((ii + subrOffSize) < fontDataAsArray.length) subrOffset[jj] = subrStart + getWord(fontDataAsArray, ii, subrOffSize); } else { if ((ii + subrOffSize) < fontDataAsObject.length()) subrOffset[jj] = subrStart + getWord(fontDataAsObject, ii, subrOffSize); } ii += subrOffSize; } subrOffset[nSubrs + 1] = this.top; this.glyphs.setLocalBias(calculateSubroutineBias(nSubrs)); // read the glyphs and store int current = subrOffset[0]; for (int jj = 1; jj < nSubrs + 1; jj++) { // skip if out of bounds if (current == 0 || subrOffset[jj] > fontDataAsArray.length || subrOffset[jj] < 0 || subrOffset[jj] == 0) continue; ByteArrayOutputStream nextSubr = new ByteArrayOutputStream(); for (int c = current; c < subrOffset[jj]; c++) { if (!isByteArray && c < fontDataAsObject.length()) nextSubr.write(fontDataAsObject.getByte(c)); } if (isByteArray) { int length = subrOffset[jj] - current; if (length > 0) { byte[] nextSub = new byte[length]; System.arraycopy(fontDataAsArray, current, nextSub, 0, length); this.glyphs.setCharString("subrs" + (jj - 1), nextSub, jj); } } else { nextSubr.close(); this.glyphs.setCharString("subrs" + (jj - 1), nextSubr.toByteArray(), jj); } current = subrOffset[jj]; } } private final void readGlyphs(byte[] fontDataAsArray, FontData fontDataAsObject, int nGlyphs, int[] names) throws Exception { boolean isByteArray = fontDataAsArray != null; int glyphOffSize; if (isByteArray) glyphOffSize = fontDataAsArray[this.top + 2]; else glyphOffSize = fontDataAsObject.getByte(this.top + 2); this.top += 3; int glyphIdx = this.top; int glyphStart = this.top + (nGlyphs + 1) * glyphOffSize - 1; if (isByteArray) this.top = glyphStart + getWord(fontDataAsArray, this.top + nGlyphs * glyphOffSize, glyphOffSize); else this.top = glyphStart + getWord(fontDataAsObject, this.top + nGlyphs * glyphOffSize, glyphOffSize); int[] glyphoffset = new int[nGlyphs + 2]; int ii = glyphIdx; // read the offsets for (int jj = 0; jj < nGlyphs + 1; jj++) { if (isByteArray) glyphoffset[jj] = glyphStart + getWord(fontDataAsArray, ii, glyphOffSize); else glyphoffset[jj] = glyphStart + getWord(fontDataAsObject, ii, glyphOffSize); ii = ii + glyphOffSize; } glyphoffset[nGlyphs + 1] = this.top; // read the glyphs and store int current = glyphoffset[0]; String glyphName; byte[] nextGlyph; for (int jj = 1; jj < nGlyphs + 1; jj++) { nextGlyph = new byte[glyphoffset[jj] - current]; // read name of glyph // get data for the glyph for (int c = current; c < glyphoffset[jj]; c++) { if (isByteArray) nextGlyph[c - current] = fontDataAsArray[c]; else nextGlyph[c - current] = fontDataAsObject.getByte(c); } if (this.isCID) { glyphName = String.valueOf(names[jj - 1]); } else { if (isByteArray) glyphName = getString(fontDataAsArray, names[jj - 1], this.stringIdx, this.stringStart, this.stringOffSize); else glyphName = getString(fontDataAsObject, names[jj - 1], this.stringIdx, this.stringStart, this.stringOffSize); } if (debugFont) System.out.println("glyph= " + glyphName + " start=" + current + " length=" + glyphoffset[jj] + " isCID=" + this.isCID); this.glyphs.setCharString(glyphName, nextGlyph, jj); current = glyphoffset[jj]; if (this.trackIndices) { this.glyphs.setIndexForCharString(jj, glyphName); } } } private static final int calculateSubroutineBias(int subroutineCount) { int bias; if (subroutineCount < 1240) { bias = 107; } else if (subroutineCount < 33900) { bias = 1131; } else { bias = 32768; } return bias; } private final void readGlobalSubRoutines(byte[] fontDataAsArray, FontData fontDataAsObject) throws Exception { boolean isByteArray = (fontDataAsArray != null); int subOffSize, count; if (isByteArray) { subOffSize = (fontDataAsArray[this.top + 2] & 0xff); count = getWord(fontDataAsArray, this.top, 2); } else { subOffSize = (fontDataAsObject.getByte(this.top + 2) & 0xff); count = getWord(fontDataAsObject, this.top, 2); } this.top += 3; if (count > 0) { int idx = this.top; int start = this.top + (count + 1) * subOffSize - 1; if (isByteArray) this.top = start + getWord(fontDataAsArray, this.top + count * subOffSize, subOffSize); else this.top = start + getWord(fontDataAsObject, this.top + count * subOffSize, subOffSize); int[] offset = new int[count + 2]; int ii = idx; // read the offsets for (int jj = 0; jj < count + 1; jj++) { if (isByteArray) offset[jj] = start + getWord(fontDataAsArray, ii, subOffSize); else offset[jj] = start + getWord(fontDataAsObject, ii, subOffSize); ii = ii + subOffSize; } offset[count + 1] = this.top; this.glyphs.setGlobalBias(calculateSubroutineBias(count)); // read the subroutines and store int current = offset[0]; for (int jj = 1; jj < count + 1; jj++) { ByteArrayOutputStream nextStream = new ByteArrayOutputStream(); for (int c = current; c < offset[jj]; c++) { if (isByteArray) nextStream.write(fontDataAsArray[c]); else nextStream.write(fontDataAsObject.getByte(c)); } nextStream.close(); // store this.glyphs.setCharString("global" + (jj - 1), nextStream.toByteArray(), jj); // setGlobalSubroutine(new Integer(jj-1+bias),nextStream.toByteArray()); current = offset[jj]; } } } private void decodeDictionary(byte[] fontDataAsArray, FontData fontDataAsObject, int dicStart, int dicEnd, String[] strings) { boolean fdReset = false; if (debugDictionary) System.out.println("=============Read dictionary====================" + getBaseFontName()); boolean isByteArray = fontDataAsArray != null; int p = dicStart, nextVal, key; int i = 0; double[] op = new double[48]; // current operand in dictionary while (p < dicEnd) { if (isByteArray) nextVal = fontDataAsArray[p] & 0xFF; else nextVal = fontDataAsObject.getByte(p) & 0xFF; if (nextVal <= 27 || nextVal == 31) { // operator key = nextVal; p++; if (debugDictionary && key != 12) System.out.println(key + " (1) " + OneByteCCFDict[key]); if (key == 0x0c) { // handle escaped keys if (isByteArray) key = fontDataAsArray[p] & 0xFF; else key = fontDataAsObject.getByte(p) & 0xFF; if (debugDictionary) System.out.println(key + " (2) " + TwoByteCCFDict[key]); p++; if (key != 36 && key != 37 && key != 7 && this.FDSelect != -1) { if (debugDictionary) { System.out.println("Ignored as part of FDArray "); for (int ii = 0; ii < 6; ii++) System.out.println(op[ii]); } } else if (key == 2) { // italic this.italicAngle = (int) op[0]; if (debugDictionary) System.out.println("Italic=" + op[0]); } else if (key == 7) { // fontMatrix if (!this.hasFontMatrix) System.arraycopy(op, 0, this.FontMatrix, 0, 6); if (debugDictionary) { for (int ii = 0; ii < 6; ii++) System.out.println(ii + "=" + op[ii] + ' ' + this); } this.hasFontMatrix = true; } else if (key == 6) { if (op[0] > 0) { this.blueValues = new int[6]; for (int z = 0; z < this.blueValues.length; z++) { this.blueValues[z] = (int) op[z]; } } } else if (key == 7) { if (op[0] > 0) { this.otherBlues = new int[6]; for (int z = 0; z < this.otherBlues.length; z++) { this.otherBlues[z] = (int) op[z]; } } } else if (key == 8) { this.familyBlues = new int[6]; for (int z = 0; z < this.familyBlues.length; z++) { this.familyBlues[z] = (int) op[z]; } } else if (key == 9) { if (op[0] > 0) { this.familyOtherBlues = new int[6]; for (int z = 0; z < this.familyOtherBlues.length; z++) { this.familyOtherBlues[z] = (int) op[z]; } } } else if (key == 10) { this.stdHW = (int) op[0]; } else if (key == 11) { this.stdVW = (int) op[0]; } else if (key == 30) { // ROS this.ros = (int) op[0]; this.isCID = true; if (debugDictionary) System.out.println(op[0]); } else if (key == 31) { // CIDFontVersion this.CIDFontVersion = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 32) { // CIDFontRevision this.CIDFontRevision = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 33) { // CIDFontType this.CIDFontType = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 34) { // CIDcount this.CIDcount = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 35) { // UIDBase this.UIDBase = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 36) { // FDArray this.FDArray = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 37) { // FDSelect this.FDSelect = (int) op[0]; fdReset = true; if (debugDictionary) System.out.println(op[0]); } else if (key == 0) { // copyright int id = (int) op[0]; if (id > 390) id = id - 390; this.copyright = strings[id]; if (debugDictionary) System.out.println("copyright= " + this.copyright); } else if (key == 21) { // Postscript // postscriptFontName=strings[id]; if (debugDictionary) { int id = (int) op[0]; if (id > 390) id = id - 390; System.out.println("Postscript= " + strings[id]); System.out.println(TwoByteCCFDict[key] + ' ' + op[0]); } } else if (key == 22) { // BaseFontname // baseFontName=strings[id]; if (debugDictionary) { int id = (int) op[0]; if (id > 390) id = id - 390; System.out.println("BaseFontname= " + this.embeddedFontName); System.out.println(TwoByteCCFDict[key] + ' ' + op[0]); } } else if (key == 38) { // fullname // fullname=strings[id]; if (debugDictionary) { int id = (int) op[0]; if (id > 390) id = id - 390; System.out.println("fullname= " + strings[id]); System.out.println(TwoByteCCFDict[key] + ' ' + op[0]); } } else if (debugDictionary) System.out .println(op[0]); } else { if (key == 2) { // fullname int id = (int) op[0]; if (id > 390) id = id - 390; this.embeddedFontName = strings[id]; if (debugDictionary) { System.out.println("name= " + this.embeddedFontName); System.out.println(OneByteCCFDict[key] + ' ' + op[0]); } } else if (key == 3) { // familyname // embeddedFamilyName=strings[id]; if (debugDictionary) { int id = (int) op[0]; if (id > 390) id = id - 390; System.out.println("FamilyName= " + this.embeddedFamilyName); System.out.println(OneByteCCFDict[key] + ' ' + op[0]); } } else if (key == 5) { // fontBBox if (debugDictionary) { for (int ii = 0; ii < 4; ii++) System.out.println(op[ii]); } for (int ii = 0; ii < 4; ii++) { // System.out.println(" "+ii+" "+op[ii]); this.FontBBox[ii] = (float) op[ii]; } // hasFontBBox=true; } else if (key == 0x0f) { // charset this.charset = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 0x10) { // encoding this.enc = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 0x11) { // charstrings this.charstrings = (int) op[0]; if (debugDictionary) System.out.println(op[0]); // System.out.println("charStrings="+charstrings); } else if (key == 18 && this.glyphs.is1C()) { // readPrivate int dictNo = this.currentFD; if (dictNo == -1) { dictNo = 0; } this.privateDict[dictNo] = (int) op[1]; this.privateDictOffset[dictNo] = (int) op[0]; if (debugDictionary) System.out.println("privateDict=" + op[0] + " Offset=" + op[1]); } else if (key == 20) { // defaultWidthX int dictNo = this.currentFD; if (dictNo == -1) { dictNo = 0; } this.defaultWidthX[dictNo] = (int) op[0]; if (this.glyphs instanceof T1Glyphs) ((T1Glyphs) this.glyphs).setWidthValues(this.defaultWidthX, this.nominalWidthX); if (debugDictionary) System.out.println("defaultWidthX=" + op[0]); } else if (key == 21) { // nominalWidthX int dictNo = this.currentFD; if (dictNo == -1) { dictNo = 0; } this.nominalWidthX[dictNo] = (int) op[0]; if (this.glyphs instanceof T1Glyphs) ((T1Glyphs) this.glyphs).setWidthValues( this.defaultWidthX, this.nominalWidthX); if (debugDictionary) System.out.println("nominalWidthX=" + op[0]); } else if (debugDictionary) { // System.out.println(p+" "+key+" "+T1CcharCodes1Byte[key]+" <<<"+op); System.out.println("Other value " + key); /** * if(op <type1CStdStrings.length) System.out.println(type1CStdStrings[(int)op]); else * if((op-390) <strings.length) System.out.println("interesting key:"+key); */ } // System.out.println(p+" "+key+" "+raw1ByteValues[key]+" <<<"+op); } i = 0; } else { if (isByteArray) p = this.glyphs.getNumber(fontDataAsArray, p, op, i, false); else p = this.glyphs.getNumber(fontDataAsObject, p, op, i, false); i++; } } if (debugDictionary) System.out.println("=================================" + getBaseFontName()); // reset if (!fdReset) this.FDSelect = -1; } private String[] readStringIndex(byte[] fontDataAsArray, FontData fontDataAsObject, int start, int offsize, int count) { int nStrings; boolean isByteArray = (fontDataAsArray != null); if (isByteArray) { this.top = start + getWord(fontDataAsArray, this.top + count * offsize, offsize); // start of string index nStrings = getWord(fontDataAsArray, this.top, 2); this.stringOffSize = fontDataAsArray[this.top + 2]; } else { this.top = start + getWord(fontDataAsObject, this.top + count * offsize, offsize); // start of string index nStrings = getWord(fontDataAsObject, this.top, 2); this.stringOffSize = fontDataAsObject.getByte(this.top + 2); } this.top += 3; this.stringIdx = this.top; this.stringStart = this.top + (nStrings + 1) * this.stringOffSize - 1; if (isByteArray) this.top = this.stringStart + getWord(fontDataAsArray, this.top + nStrings * this.stringOffSize, this.stringOffSize); else this.top = this.stringStart + getWord(fontDataAsObject, this.top + nStrings * this.stringOffSize, this.stringOffSize); int[] offsets = new int[nStrings + 2]; String[] strings = new String[nStrings + 2]; int ii = this.stringIdx; // read the offsets for (int jj = 0; jj < nStrings + 1; jj++) { if (isByteArray) offsets[jj] = getWord(fontDataAsArray, ii, this.stringOffSize); // content[ii] & 0xff; else offsets[jj] = getWord(fontDataAsObject, ii, this.stringOffSize); // content[ii] & 0xff; // getWord(content,ii,stringOffSize); ii = ii + this.stringOffSize; } offsets[nStrings + 1] = this.top - this.stringStart; // read the strings int current = 0; StringBuilder nextString; for (int jj = 0; jj < nStrings + 1; jj++) { nextString = new StringBuilder(offsets[jj] - current); for (int c = current; c < offsets[jj]; c++) { if (isByteArray) nextString.append((char) fontDataAsArray[this.stringStart + c]); else nextString.append((char) fontDataAsObject.getByte(this.stringStart + c)); } if (debugFont) System.out.println("String " + jj + " =" + nextString); strings[jj] = nextString.toString(); current = offsets[jj]; } return strings; } /** Utility method used during processing of type1C files */ static final private String getString(FontData fontDataAsObject, int sid, int idx, int start, int offsize) { int len; String result; if (sid < 391) result = type1CStdStrings[sid]; else { sid -= 391; int idx0 = start + getWord(fontDataAsObject, idx + sid * offsize, offsize); int idxPtr1 = start + getWord(fontDataAsObject, idx + (sid + 1) * offsize, offsize); // System.out.println(sid+" "+idx0+" "+idxPtr1); if ((len = idxPtr1 - idx0) > 255) len = 255; result = new String(fontDataAsObject.getBytes(idx0, len)); } return result; } /** Utility method used during processing of type1C files */ static final private String getString(byte[] fontDataAsArray, int sid, int idx, int start, int offsize) { int len; String result; if (sid < 391) result = type1CStdStrings[sid]; else { sid -= 391; int idx0 = start + getWord(fontDataAsArray, idx + sid * offsize, offsize); int idxPtr1 = start + getWord(fontDataAsArray, idx + (sid + 1) * offsize, offsize); // System.out.println(sid+" "+idx0+" "+idxPtr1); if ((len = idxPtr1 - idx0) > 255) len = 255; result = new String(fontDataAsArray, idx0, len); } return result; } /** get standard charset or extract from type 1C font */ static final private int[] readCharset(int charset, int nGlyphs, FontData fontDataAsObject, byte[] fontDataAsArray) { boolean isByteArray = fontDataAsArray != null; int glyphNames[]; int i, j; if (debugFont) System.out.println("charset=" + charset); /** * //handle CIDS first if(isCID){ glyphNames = new int[nGlyphs]; glyphNames[0] = 0; * * for (i = 1; i < nGlyphs; ++i) { glyphNames[i] = i;//getWord(fontData, top, 2); //top += 2; } * * * // read appropriate non-CID charset }else */ if (charset == 0) glyphNames = ISOAdobeCharset; else if (charset == 1) glyphNames = ExpertCharset; else if (charset == 2) glyphNames = ExpertSubCharset; else { glyphNames = new int[nGlyphs + 1]; glyphNames[0] = 0; int top = charset; int charsetFormat; if (isByteArray) charsetFormat = fontDataAsArray[top++] & 0xff; else charsetFormat = fontDataAsObject.getByte(top++) & 0xff; if (debugFont) System.out.println("charsetFormat=" + charsetFormat); if (charsetFormat == 0) { for (i = 1; i < nGlyphs; ++i) { if (isByteArray) glyphNames[i] = getWord(fontDataAsArray, top, 2); else glyphNames[i] = getWord(fontDataAsObject, top, 2); top += 2; } } else if (charsetFormat == 1) { i = 1; int c, nLeft; while (i < nGlyphs) { if (isByteArray) c = getWord(fontDataAsArray, top, 2); else c = getWord(fontDataAsObject, top, 2); top += 2; if (isByteArray) nLeft = fontDataAsArray[top++] & 0xff; else nLeft = fontDataAsObject.getByte(top++) & 0xff; for (j = 0; j <= nLeft; ++j) glyphNames[i++] = c++; } } else if (charsetFormat == 2) { i = 1; int c, nLeft; while (i < nGlyphs) { if (isByteArray) c = getWord(fontDataAsArray, top, 2); else c = getWord(fontDataAsObject, top, 2); top += 2; if (isByteArray) nLeft = getWord(fontDataAsArray, top, 2); else nLeft = getWord(fontDataAsObject, top, 2); top += 2; for (j = 0; j <= nLeft; ++j) glyphNames[i++] = c++; } } } return glyphNames; } /** Utility method used during processing of type1C files */ static final private int getWord(FontData fontDataAsObject, int index, int size) { int result = 0; for (int i = 0; i < size; i++) { result = (result << 8) + (fontDataAsObject.getByte(index + i) & 0xff); } return result; } /** Utility method used during processing of type1C files */ static final private int getWord(byte[] fontDataAsArray, int index, int size) { int result = 0; for (int i = 0; i < size; i++) { result = (result << 8) + (fontDataAsArray[index + i] & 0xff); } return result; } /** * @return bounding box to highlight */ @Override public Rectangle getBoundingBox() { if (this.BBox == null) { if (this.isFontEmbedded) this.BBox = new Rectangle((int) this.FontBBox[0], (int) this.FontBBox[1], (int) (this.FontBBox[2] - this.FontBBox[0]), (int) (this.FontBBox[3] - this.FontBBox[1])); // To change body of created methods // use File | Settings | File // Templates. else this.BBox = super.getBoundingBox(); } return this.BBox; } /** * @return The Font Dictionary select array */ public int[] getFDSelect() { return this.fdSelect; } public int[] getRosArray() { return this.rosArray; } public Object getKeyValue(int key) { switch (key) { case WEIGHT: return this.weight; case ITALICANGLE: return this.italicAngle; case FONTMATRIX: return this.FontMatrix; case FONTBBOX: return this.FontBBox; case ENCODING: return this.enc; case DEFAULTWIDTHX: return this.defaultWidthX[0]; case NOMINALWIDTHX: return this.nominalWidthX[0]; case BLUEVALUES: return this.blueValues; case OTHERBLUES: return this.otherBlues; case FAMILYBLUES: return this.familyBlues; case FAMILYOTHERBLUES: return this.familyOtherBlues; case STDHW: return this.stdHW; case STDVW: return this.stdVW; case SUBRS: return this.subrs; case ROS: return this.ros; case CIDCOUNT: return this.CIDcount; case CIDFONTREVISION: return this.CIDFontRevision; case CIDFONTVERSION: return this.CIDFontVersion; case CIDFONTTYPE: return this.CIDFontType; case FDARRAY: return this.FDArray; case FDSELECT: return this.FDSelect; default: throw new RuntimeException("Key is unknown or value is not yet assigned " + key); } } }
kwart/jsign-jpedal
src/main/java/org/jpedal/fonts/Type1C.java
249,370
/* * =========================================== * Java Pdf Extraction Decoding Access Library * =========================================== * * Project Info: http://www.idrsolutions.com * Help section for developers at http://www.idrsolutions.com/java-pdf-library-support/ * * (C) Copyright 1997-2013, IDRsolutions and Contributors. * * This file is part of JPedal * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * --------------- * Type1C.java * --------------- */ package org.jpedal.fonts; import java.awt.Rectangle; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.jpedal.fonts.glyph.PdfJavaGlyphs; import org.jpedal.fonts.glyph.T1Glyphs; import org.jpedal.fonts.objects.FontData; import org.jpedal.io.ObjectStore; import org.jpedal.io.PdfObjectReader; import org.jpedal.objects.raw.PdfDictionary; import org.jpedal.objects.raw.PdfObject; import org.jpedal.utils.LogWriter; /** * handlestype1 specifics */ public class Type1C extends Type1 { private static final long serialVersionUID = -3010162163120599585L; static final boolean debugFont = false; static final boolean debugDictionary = false; int ros = -1, CIDFontVersion = 0, CIDFontRevision = 0, CIDFontType = 0, CIDcount = 0, UIDBase = -1, FDArray = -1, FDSelect = -1; final static String[] OneByteCCFDict = { "version", "Notice", "FullName", "FamilyName", "Weight", "FontBBox", "BlueValues", "OtherBlues", "FamilyBlues", "FamilyOtherBlues", "StdHW", "StdVW", "Escape", "UniqueID", "XUID", "charset", "Encoding", "CharStrings", "Private", "Subrs", "defaultWidthX", "nominalWidthX", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "shortint", "longint", "BCD", "-reserved-" }; final static String[] TwoByteCCFDict = { "Copyright", "isFixedPitch", "ItalicAngle", "UnderlinePosition", "UnderlineThickness", "PaintType", "CharstringType", "FontMatrix", "StrokeWidth", "BlueScale", "BlueShift", "BlueFuzz", "StemSnapH", "StemSnapV", "ForceBold", "-reserved-", "-reserved-", "LanguageGroup", "ExpansionFactor", "initialRandomSeed", "SyntheticBase", "PostScript", "BaseFontName", "BaseFontBlend", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "-reserved-", "ROS", "CIDFontVersion", "CIDFontRevision", "CIDFontType", "CIDCount", "UIDBase", "FDArray", "FDSelect", "FontName" }; // current location in file private int top = 0; private int charset = 0; private int enc = 0; private int charstrings = 0; private int stringIdx; private int stringStart; private int stringOffSize; private Rectangle BBox = null; private boolean hasFontMatrix = false;// hasFontBBox=false,; private int[] privateDict = { -1 }, privateDictOffset = { -1 }; private int currentFD = -1; private int[] defaultWidthX = { 0 }, nominalWidthX = { 0 }, fdSelect; /** decoding table for Expert */ private static final int ExpertSubCharset[] = { // 87 // elements 0, 1, 231, 232, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 272, 300, 301, 302, 305, 314, 315, 158, 155, 163, 320, 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346 }; /** lookup table for names for type 1C glyphs */ public static final String type1CStdStrings[] = { // 391 // elements ".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "exclamdown", "cent", "sterling", "fraction", "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", "endash", "dagger", "daggerdbl", "periodcentered", "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", "ellipsis", "perthousand", "questiondown", "grave", "acute", "circumflex", "tilde", "macron", "breve", "dotaccent", "dieresis", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "emdash", "AE", "ordfeminine", "Lslash", "Oslash", "OE", "ordmasculine", "ae", "dotlessi", "lslash", "oslash", "oe", "germandbls", "onesuperior", "logicalnot", "mu", "trademark", "Eth", "onehalf", "plusminus", "Thorn", "onequarter", "divide", "brokenbar", "degree", "thorn", "threequarters", "twosuperior", "registered", "minus", "eth", "multiply", "threesuperior", "copyright", "Aacute", "Acircumflex", "Adieresis", "Agrave", "Aring", "Atilde", "Ccedilla", "Eacute", "Ecircumflex", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis", "Ograve", "Otilde", "Scaron", "Uacute", "Ucircumflex", "Udieresis", "Ugrave", "Yacute", "Ydieresis", "Zcaron", "aacute", "acircumflex", "adieresis", "agrave", "aring", "atilde", "ccedilla", "eacute", "ecircumflex", "edieresis", "egrave", "iacute", "icircumflex", "idieresis", "igrave", "ntilde", "oacute", "ocircumflex", "odieresis", "ograve", "otilde", "scaron", "uacute", "ucircumflex", "udieresis", "ugrave", "yacute", "ydieresis", "zcaron", "exclamsmall", "Hungarumlautsmall", "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "zerooldstyle", "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "commasuperior", "threequartersemdash", "periodsuperior", "questionsmall", "asuperior", "bsuperior", "centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior", "msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior", "tsuperior", "ff", "ffi", "ffl", "parenleftinferior", "parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall", "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", "Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall", "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", "colonmonetary", "onefitted", "rupiah", "Tildesmall", "exclamdownsmall", "centoldstyle", "Lslashsmall", "Scaronsmall", "Zcaronsmall", "Dieresissmall", "Brevesmall", "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash", "hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall", "questiondownsmall", "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "zerosuperior", "foursuperior", "fivesuperior", "sixsuperior", "sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", "threeinferior", "fourinferior", "fiveinferior", "sixinferior", "seveninferior", "eightinferior", "nineinferior", "centinferior", "dollarinferior", "periodinferior", "commainferior", "Agravesmall", "Aacutesmall", "Acircumflexsmall", "Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall", "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall", "Odieresissmall", "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall", "001.000", "001.001", "001.002", "001.003", "Black", "Bold", "Book", "Light", "Medium", "Regular", "Roman", "Semibold" }; /** Lookup table to map values */ private static final int ISOAdobeCharset[] = { // 229 // elements 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228 }; /** lookup data to convert Expert values */ private static final int ExpertCharset[] = { // 166 // elements 0, 1, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 158, 155, 163, 319, 320, 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378 }; // one byte operators public final static int VERSION = 0; public final static int NOTICE = 1; public final static int FULLNAME = 2; public final static int FAMILYNAME = 3; public final static int WEIGHT = 4; public final static int FONTBBOX = 5; public final static int BLUEVALUES = 6; public final static int OTHERBLUES = 7; public final static int FAMILYBLUES = 8; public final static int FAMILYOTHERBLUES = 9; public final static int STDHW = 10; public final static int STDVW = 11; public final static int ESCAPE = 12; public final static int UNIQUEID = 13; public final static int XUID = 14; public final static int CHARSET = 15; public final static int ENCODING = 16; public final static int CHARSTRINGS = 17; public final static int PRIVATE = 18; public final static int SUBRS = 19; public final static int DEFAULTWIDTHX = 20; public final static int NOMINALWIDTHX = 21; public final static int RESERVED = 22; public final static int SHORTINT = 28; public final static int LONGINT = 29; public final static int BCD = 30; // two byte operators public final static int COPYRIGHT = 3072; public final static int ISFIXEDPITCH = 3073; public final static int ITALICANGLE = 3074; public final static int UNDERLINEPOSITION = 3075; public final static int UNDERLINETHICKNESS = 3076; public final static int PAINTTYPE = 3077; public final static int CHARSTRINGTYPE = 3078; public final static int FONTMATRIX = 3079; public final static int STROKEWIDTH = 3080; public final static int BLUESCALE = 3081; public final static int BLUESHIFT = 3082; public final static int BLUEFUZZ = 3083; public final static int STEMSNAPH = 3084; public final static int STEMSNAPV = 3085; public final static int FORCEBOLD = 3086; public final static int LANGUAGEGROUP = 3089; public final static int EXPANSIONFACTOR = 3090; public final static int INITIALRANDOMSEED = 3091; public final static int SYNTHETICBASE = 3092; public final static int POSTSCRIPT = 3093; public final static int BASEFONTNAME = 3094; public final static int BASEFONTBLEND = 3095; public final static int ROS = 3102; public final static int CIDFONTVERSION = 3103; public final static int CIDFONTREVISION = 3104; public final static int CIDFONTTYPE = 3105; public final static int CIDCOUNT = 3106; public final static int UIDBASE = 3107; public final static int FDARRAY = 3108; public final static int FDSELECT = 3109; public final static int FONTNAME = 3110; private int weight = 388;// make it default private int[] blueValues = null; private int[] otherBlues = null; private int[] familyBlues = null; private int[] familyOtherBlues = null; private int stdHW = -1, stdVW = -1, subrs = -1; private byte[] encodingDataBytes = null; private String[] stringIndexData = null; private int[] charsetGlyphCodes = null; private int charsetGlyphFormat = 0; private int[] rosArray = new int[3]; /** needed so CIDFOnt0 can extend */ public Type1C() {} /** get handles onto Reader so we can access the file */ public Type1C(PdfObjectReader current_pdf_file, String substituteFont) { this.glyphs = new T1Glyphs(false); init(current_pdf_file); this.substituteFont = substituteFont; } /** read details of any embedded fontFile */ protected void readEmbeddedFont(PdfObject pdfFontDescriptor) throws Exception { if (this.substituteFont != null) { byte[] bytes; // read details BufferedInputStream from; // create streams ByteArrayOutputStream to = new ByteArrayOutputStream(); InputStream jarFile = null; try { if (this.substituteFont.startsWith("jar:") || this.substituteFont.startsWith("http:")) jarFile = this.loader .getResourceAsStream(this.substituteFont); else jarFile = this.loader.getResourceAsStream("file:///" + this.substituteFont); } catch (Exception e) { if (LogWriter.isOutput()) LogWriter.writeLog("3.Unable to open " + this.substituteFont); } catch (Error err) { if (LogWriter.isOutput()) LogWriter.writeLog("3.Unable to open " + this.substituteFont); } if (jarFile == null) { /** * from=new BufferedInputStream(new FileInputStream(substituteFont)); * * //write byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, * bytes_read); * * to.close(); from.close(); * * / **/ File file = new File(this.substituteFont); InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { System.out.println("Sorry! Your given file is too large."); return; } bytes = new byte[(int) length]; int offset = 0; int numRead; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } is.close(); // new BufferedReader // (new InputStreamReader(loader.getResourceAsStream("org/jpedal/res/cid/" + encodingName), "Cp1252")); /** * FileReader from2=null; try { from2 = new FileReader(substituteFont); //new BufferedReader); //outputStream = new * FileWriter("characteroutput.txt"); * * int c; while ((c = from2.read()) != -1) { to.write(c); } } finally { if (from2 != null) { from2.close(); } if (to != null) { * to.close(); } }/ **/ } else { from = new BufferedInputStream(jarFile); // write byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); to.close(); from.close(); bytes = to.toByteArray(); } /** load the font */ try { this.isFontSubstituted = true; // if (substituteFont.indexOf(".afm") != -1) readType1FontFile(bytes); // else // readType1CFontFile(to.toByteArray(),null); } catch (Exception e) { e.printStackTrace(System.out); if (LogWriter.isOutput()) LogWriter.writeLog("[PDF]Substitute font=" + this.substituteFont + "Type 1 exception=" + e); } // over-ride font remapping if substituted if (this.isFontSubstituted && this.glyphs.remapFont) this.glyphs.remapFont = false; } else if (pdfFontDescriptor != null) { PdfObject FontFile = pdfFontDescriptor.getDictionary(PdfDictionary.FontFile); /** try type 1 first then type 1c/0c */ if (FontFile != null) { try { byte[] stream = this.currentPdfFile.readStream(FontFile, true, true, false, false, false, FontFile.getCacheName(this.currentPdfFile.getObjectReader())); if (stream != null) readType1FontFile(stream); } catch (Exception e) { // tell user and log if (LogWriter.isOutput()) LogWriter.writeLog("Exception: " + e.getMessage()); } } else { PdfObject FontFile3 = pdfFontDescriptor.getDictionary(PdfDictionary.FontFile3); if (FontFile3 != null) { byte[] stream = this.currentPdfFile.readStream(FontFile3, true, true, false, false, false, FontFile3.getCacheName(this.currentPdfFile.getObjectReader())); if (stream != null) { // if it fails, null returned // check for type1c or ottf if (stream.length > 3 && stream[0] == 719 && stream[1] == 84 && stream[2] == 84 && stream[3] == 79) {} else // assume all standard cff for moment readType1CFontFile(stream, null); } } } } } /** read in a font and its details from the pdf file */ @Override public void createFont(PdfObject pdfObject, String fontID, boolean renderPage, ObjectStore objectStore, Map substitutedFonts) throws Exception { this.fontTypes = StandardFonts.TYPE1; // generic setup init(fontID, renderPage); /** * get FontDescriptor object - if present contains metrics on glyphs */ PdfObject pdfFontDescriptor = pdfObject.getDictionary(PdfDictionary.FontDescriptor); // FontBBox and FontMatix setBoundsAndMatrix(pdfFontDescriptor); setName(pdfObject, fontID); setEncoding(pdfObject, pdfFontDescriptor); try { readEmbeddedFont(pdfFontDescriptor); } catch (Exception e) { // tell user and log if (LogWriter.isOutput()) LogWriter.writeLog("Exception: " + e.getMessage()); } // setWidths(pdfObject); readWidths(pdfObject, true); // if(embeddedFontName!=null && is1C() && PdfStreamDecoder.runningStoryPad){ // embeddedFontName= cleanupFontName(embeddedFontName); // this.setBaseFontName(embeddedFontName); // this.setFontName(embeddedFontName); // } // make sure a font set if (renderPage) setFont(getBaseFontName(), 1); } /** Constructor for html fonts */ public Type1C(byte[] fontDataAsArray, PdfJavaGlyphs glyphs, boolean is1C) throws Exception { this.glyphs = glyphs; // generate reverse lookup so we can encode CMAP this.trackIndices = true; // flags we extract all details (used originally by rendering and now by PS2OTF) this.renderPage = true; if (is1C) readType1CFontFile(fontDataAsArray, null); else readType1FontFile(fontDataAsArray); } /** Constructor for OTF fonts */ public Type1C(byte[] fontDataAsArray, FontData fontData, PdfJavaGlyphs glyphs) throws Exception { this.glyphs = glyphs; readType1CFontFile(fontDataAsArray, fontData); } /** Handle encoding for type1C fonts. Also used for CIDFontType0C */ final private void readType1CFontFile(byte[] fontDataAsArray, FontData fontDataAsObject) throws Exception { if (LogWriter.isOutput()) LogWriter.writeLog("Embedded Type1C font used"); this.glyphs.setis1C(true); boolean isByteArray = (fontDataAsArray != null); // debugFont=getBaseFontName().indexOf("LC")!=-1; if (debugFont) System.err.println(getBaseFontName()); int start; // pointers within table int size = 2; /** * read Header */ int major, minor; if (isByteArray) { major = fontDataAsArray[0]; minor = fontDataAsArray[1]; } else { major = fontDataAsObject.getByte(0); minor = fontDataAsObject.getByte(1); } if ((major != 1 || minor != 0) && LogWriter.isOutput()) LogWriter.writeLog("1C format " + major + ':' + minor + " not fully supported"); if (debugFont) System.out.println("major=" + major + " minor=" + minor); // read header size to workout start of names index if (isByteArray) this.top = fontDataAsArray[2]; else this.top = fontDataAsObject.getByte(2); /** * read names index */ // read name index for the first font int count, offsize; if (isByteArray) { count = getWord(fontDataAsArray, this.top, size); offsize = fontDataAsArray[this.top + size]; } else { count = getWord(fontDataAsObject, this.top, size); offsize = fontDataAsObject.getByte(this.top + size); } /** * get last offset and use to move to top dict index */ this.top += (size + 1); // move pointer to start of font names start = this.top + (count + 1) * offsize - 1; // move pointer to end of offsets if (isByteArray) this.top = start + getWord(fontDataAsArray, this.top + count * offsize, offsize); else this.top = start + getWord(fontDataAsObject, this.top + count * offsize, offsize); /** * read the dict index */ if (isByteArray) { count = getWord(fontDataAsArray, this.top, size); offsize = fontDataAsArray[this.top + size]; } else { count = getWord(fontDataAsObject, this.top, size); offsize = fontDataAsObject.getByte(this.top + size); } this.top += (size + 1); // update pointer start = this.top + (count + 1) * offsize - 1; int dicStart, dicEnd; if (isByteArray) { dicStart = start + getWord(fontDataAsArray, this.top, offsize); dicEnd = start + getWord(fontDataAsArray, this.top + offsize, offsize); } else { dicStart = start + getWord(fontDataAsObject, this.top, offsize); dicEnd = start + getWord(fontDataAsObject, this.top + offsize, offsize); } /** * read string index */ String[] strings = readStringIndex(fontDataAsArray, fontDataAsObject, start, offsize, count); /** * read global subroutines (top set by Strings code) */ readGlobalSubRoutines(fontDataAsArray, fontDataAsObject); /** * decode the dictionary */ decodeDictionary(fontDataAsArray, fontDataAsObject, dicStart, dicEnd, strings); /** * allow for subdictionaries in CID font */ if (this.FDSelect != -1) { if (debugDictionary) System.out.println("=============FDSelect====================" + getBaseFontName()); // Read FDSelect int nextDic = this.FDSelect; int format; if (isByteArray) { format = getWord(fontDataAsArray, nextDic, 1); } else { format = getWord(fontDataAsObject, nextDic, 1); } int glyphCount; if (isByteArray) { glyphCount = getWord(fontDataAsArray, this.charstrings, 2); } else { glyphCount = getWord(fontDataAsObject, this.charstrings, 2); } this.fdSelect = new int[glyphCount]; if (format == 0) { // Format 0 is just an array of which to use for each glyph for (int i = 0; i < glyphCount; i++) { if (isByteArray) { this.fdSelect[i] = getWord(fontDataAsArray, nextDic + 1 + i, 1); } else { this.fdSelect[i] = getWord(fontDataAsObject, nextDic + 1 + i, 1); } } } else if (format == 3) { int nRanges; if (isByteArray) { nRanges = getWord(fontDataAsArray, nextDic + 1, 2); } else { nRanges = getWord(fontDataAsObject, nextDic + 1, 2); } int[] rangeStarts = new int[nRanges + 1], fDicts = new int[nRanges]; // Find ranges of glyphs with their DICT index for (int i = 0; i < nRanges; i++) { if (isByteArray) { rangeStarts[i] = getWord(fontDataAsArray, nextDic + 3 + (3 * i), 2); fDicts[i] = getWord(fontDataAsArray, nextDic + 5 + (3 * i), 1); } else { rangeStarts[i] = getWord(fontDataAsObject, nextDic + 3 + (3 * i), 2); fDicts[i] = getWord(fontDataAsObject, nextDic + 5 + (3 * i), 1); } } rangeStarts[rangeStarts.length - 1] = glyphCount; // Fill fdSelect array for (int i = 0; i < nRanges; i++) { for (int j = rangeStarts[i]; j < rangeStarts[i + 1]; j++) { this.fdSelect[j] = fDicts[i]; } } } ((T1Glyphs) this.glyphs).setFDSelect(this.fdSelect); // Read FDArray nextDic = this.FDArray; if (isByteArray) { count = getWord(fontDataAsArray, nextDic, size); offsize = fontDataAsArray[nextDic + size]; } else { count = getWord(fontDataAsObject, nextDic, size); offsize = fontDataAsObject.getByte(nextDic + size); } nextDic += (size + 1); // update pointer start = nextDic + (count + 1) * offsize - 1; this.privateDict = new int[count]; this.privateDictOffset = new int[count]; this.defaultWidthX = new int[count]; this.nominalWidthX = new int[count]; for (int i = 0; i < count; i++) { this.currentFD = i; this.privateDict[i] = -1; this.privateDictOffset[i] = -1; if (isByteArray) { dicStart = start + getWord(fontDataAsArray, nextDic + (i * offsize), offsize); dicEnd = start + getWord(fontDataAsArray, nextDic + ((i + 1) * offsize), offsize); } else { dicStart = start + getWord(fontDataAsObject, nextDic + (i * offsize), offsize); dicEnd = start + getWord(fontDataAsObject, nextDic + ((i + 1) * offsize), offsize); } decodeDictionary(fontDataAsArray, fontDataAsObject, dicStart, dicEnd, strings); } this.currentFD = -1; if (debugDictionary) System.out.println("=================================" + getBaseFontName()); } /** * get number of glyphs from charstrings index */ this.top = this.charstrings; int nGlyphs; if (isByteArray) nGlyphs = getWord(fontDataAsArray, this.top, size); // start of glyph index else nGlyphs = getWord(fontDataAsObject, this.top, size); // start of glyph index this.glyphs.setGlyphCount(nGlyphs); if (debugFont) System.out.println("nGlyphs=" + nGlyphs); int[] names = readCharset(this.charset, nGlyphs, fontDataAsObject, fontDataAsArray); if (debugFont) { System.out.println("=======charset==============="); int count2 = names.length; for (int jj = 0; jj < count2; jj++) { System.out.println(jj + " " + names[jj]); } System.out.println("=======Encoding==============="); } /** * set encoding if not set */ setEncoding(fontDataAsArray, fontDataAsObject, nGlyphs, names); /** * read glyph index */ this.top = this.charstrings; readGlyphs(fontDataAsArray, fontDataAsObject, nGlyphs, names); /**/ for (int i = 0; i < this.privateDict.length; i++) { this.currentFD = i; int dict = this.privateDict[i]; if (dict != -1) { int dictOffset = this.privateDictOffset[i]; decodeDictionary(fontDataAsArray, fontDataAsObject, dict, dictOffset + dict, strings); this.top = dict + dictOffset; int len, nSubrs; if (isByteArray) len = fontDataAsArray.length; else len = fontDataAsObject.length(); if (this.top + 2 < len) { if (isByteArray) nSubrs = getWord(fontDataAsArray, this.top, size); else nSubrs = getWord(fontDataAsObject, this.top, size); if (nSubrs > 0) readSubrs(fontDataAsArray, fontDataAsObject, nSubrs); } else if (debugFont || debugDictionary) { System.out.println("Private subroutine out of range"); } } } this.currentFD = -1; /**/ /** * set flags to tell software to use these descritpions */ this.isFontEmbedded = true; this.glyphs.setFontEmbedded(true); } /** pick up encoding from embedded font */ final private void setEncoding(byte[] fontDataAsArray, FontData fontDataAsObject, int nGlyphs, int[] names) { boolean isByteArray = fontDataAsArray != null; if (debugFont) System.out.println("Enc=" + this.enc); // read encoding (glyph -> code mapping) if (this.enc == 0) { this.embeddedEnc = StandardFonts.STD; if (this.fontEnc == -1) putFontEncoding(StandardFonts.STD); if (this.isCID) { // store values for lookup on text try { String name; for (int i = 1; i < nGlyphs; ++i) { if (names[i] < 391) { if (isByteArray) name = getString(fontDataAsArray, names[i], this.stringIdx, this.stringStart, this.stringOffSize); else name = getString(fontDataAsObject, names[i], this.stringIdx, this.stringStart, this.stringOffSize); putMappedChar(names[i], StandardFonts.getUnicodeName(name)); } } } catch (Exception e) { // tell user and log if (LogWriter.isOutput()) LogWriter.writeLog("Exception: " + e.getMessage()); } } } else if (this.enc == 1) { this.embeddedEnc = StandardFonts.MACEXPERT; if (this.fontEnc == -1) putFontEncoding(StandardFonts.MACEXPERT); } else { // custom mapping if (debugFont) System.out.println("custom mapping"); this.top = this.enc; int encFormat, c; if (isByteArray) encFormat = (fontDataAsArray[this.top++] & 0xff); else encFormat = (fontDataAsObject.getByte(this.top++) & 0xff); String name; if ((encFormat & 0x7f) == 0) { // format 0 int nCodes; if (isByteArray) nCodes = 1 + (fontDataAsArray[this.top++] & 0xff); else nCodes = 1 + (fontDataAsObject.getByte(this.top++) & 0xff); if (nCodes > nGlyphs) nCodes = nGlyphs; for (int i = 1; i < nCodes; ++i) { if (isByteArray) { c = fontDataAsArray[this.top++] & 0xff; name = getString(fontDataAsArray, names[i], this.stringIdx, this.stringStart, this.stringOffSize); } else { c = fontDataAsObject.getByte(this.top++) & 0xff; name = getString(fontDataAsObject, names[i], this.stringIdx, this.stringStart, this.stringOffSize); } putChar(c, name); } } else if ((encFormat & 0x7f) == 1) { // format 1 int nRanges; if (isByteArray) nRanges = (fontDataAsArray[this.top++] & 0xff); else nRanges = (fontDataAsObject.getByte(this.top++) & 0xff); int nCodes = 1; for (int i = 0; i < nRanges; ++i) { int nLeft; if (isByteArray) { c = (fontDataAsArray[this.top++] & 0xff); nLeft = (fontDataAsArray[this.top++] & 0xff); } else { c = (fontDataAsObject.getByte(this.top++) & 0xff); nLeft = (fontDataAsObject.getByte(this.top++) & 0xff); } for (int j = 0; j <= nLeft && nCodes < nGlyphs; ++j) { if (isByteArray) name = getString(fontDataAsArray, names[nCodes], this.stringIdx, this.stringStart, this.stringOffSize); else name = getString(fontDataAsObject, names[nCodes], this.stringIdx, this.stringStart, this.stringOffSize); putChar(c, name); nCodes++; c++; } } } if ((encFormat & 0x80) != 0) { // supplimentary encodings int nSups; if (isByteArray) nSups = (fontDataAsArray[this.top++] & 0xff); else nSups = (fontDataAsObject.getByte(this.top++) & 0xff); for (int i = 0; i < nSups; ++i) { if (isByteArray) c = (fontDataAsArray[this.top++] & 0xff); else c = (fontDataAsObject.getByte(this.top++) & 0xff); int sid; if (isByteArray) sid = getWord(fontDataAsArray, this.top, 2); else sid = getWord(fontDataAsObject, this.top, 2); this.top += 2; if (isByteArray) name = getString(fontDataAsArray, sid, this.stringIdx, this.stringStart, this.stringOffSize); else name = getString(fontDataAsObject, sid, this.stringIdx, this.stringStart, this.stringOffSize); putChar(c, name); } } } } // LILYPONDTOOL private final void readSubrs(byte[] fontDataAsArray, FontData fontDataAsObject, int nSubrs) throws Exception { boolean isByteArray = fontDataAsArray != null; int subrOffSize; if (isByteArray) subrOffSize = fontDataAsArray[this.top + 2]; else subrOffSize = fontDataAsObject.getByte(this.top + 2); this.top += 3; int subrIdx = this.top; int subrStart = this.top + (nSubrs + 1) * subrOffSize - 1; int nextTablePtr = this.top + nSubrs * subrOffSize; if (isByteArray) { if (nextTablePtr < fontDataAsArray.length) // allow for table at end of file this.top = subrStart + getWord(fontDataAsArray, nextTablePtr, subrOffSize); else this.top = fontDataAsArray.length - 1; } else { if (nextTablePtr < fontDataAsArray.length) // allow for table at end of file this.top = subrStart + getWord(fontDataAsObject, nextTablePtr, subrOffSize); else this.top = fontDataAsObject.length() - 1; } int[] subrOffset = new int[nSubrs + 2]; int ii = subrIdx; for (int jj = 0; jj < nSubrs + 1; jj++) { if (isByteArray) { if ((ii + subrOffSize) < fontDataAsArray.length) subrOffset[jj] = subrStart + getWord(fontDataAsArray, ii, subrOffSize); } else { if ((ii + subrOffSize) < fontDataAsObject.length()) subrOffset[jj] = subrStart + getWord(fontDataAsObject, ii, subrOffSize); } ii += subrOffSize; } subrOffset[nSubrs + 1] = this.top; this.glyphs.setLocalBias(calculateSubroutineBias(nSubrs)); // read the glyphs and store int current = subrOffset[0]; for (int jj = 1; jj < nSubrs + 1; jj++) { // skip if out of bounds if (current == 0 || subrOffset[jj] > fontDataAsArray.length || subrOffset[jj] < 0 || subrOffset[jj] == 0) continue; ByteArrayOutputStream nextSubr = new ByteArrayOutputStream(); for (int c = current; c < subrOffset[jj]; c++) { if (!isByteArray && c < fontDataAsObject.length()) nextSubr.write(fontDataAsObject.getByte(c)); } if (isByteArray) { int length = subrOffset[jj] - current; if (length > 0) { byte[] nextSub = new byte[length]; System.arraycopy(fontDataAsArray, current, nextSub, 0, length); this.glyphs.setCharString("subrs" + (jj - 1), nextSub, jj); } } else { nextSubr.close(); this.glyphs.setCharString("subrs" + (jj - 1), nextSubr.toByteArray(), jj); } current = subrOffset[jj]; } } private final void readGlyphs(byte[] fontDataAsArray, FontData fontDataAsObject, int nGlyphs, int[] names) throws Exception { boolean isByteArray = fontDataAsArray != null; int glyphOffSize; if (isByteArray) glyphOffSize = fontDataAsArray[this.top + 2]; else glyphOffSize = fontDataAsObject.getByte(this.top + 2); this.top += 3; int glyphIdx = this.top; int glyphStart = this.top + (nGlyphs + 1) * glyphOffSize - 1; if (isByteArray) this.top = glyphStart + getWord(fontDataAsArray, this.top + nGlyphs * glyphOffSize, glyphOffSize); else this.top = glyphStart + getWord(fontDataAsObject, this.top + nGlyphs * glyphOffSize, glyphOffSize); int[] glyphoffset = new int[nGlyphs + 2]; int ii = glyphIdx; // read the offsets for (int jj = 0; jj < nGlyphs + 1; jj++) { if (isByteArray) glyphoffset[jj] = glyphStart + getWord(fontDataAsArray, ii, glyphOffSize); else glyphoffset[jj] = glyphStart + getWord(fontDataAsObject, ii, glyphOffSize); ii = ii + glyphOffSize; } glyphoffset[nGlyphs + 1] = this.top; // read the glyphs and store int current = glyphoffset[0]; String glyphName; byte[] nextGlyph; for (int jj = 1; jj < nGlyphs + 1; jj++) { nextGlyph = new byte[glyphoffset[jj] - current]; // read name of glyph // get data for the glyph for (int c = current; c < glyphoffset[jj]; c++) { if (isByteArray) nextGlyph[c - current] = fontDataAsArray[c]; else nextGlyph[c - current] = fontDataAsObject.getByte(c); } if (this.isCID) { glyphName = String.valueOf(names[jj - 1]); } else { if (isByteArray) glyphName = getString(fontDataAsArray, names[jj - 1], this.stringIdx, this.stringStart, this.stringOffSize); else glyphName = getString(fontDataAsObject, names[jj - 1], this.stringIdx, this.stringStart, this.stringOffSize); } if (debugFont) System.out.println("glyph= " + glyphName + " start=" + current + " length=" + glyphoffset[jj] + " isCID=" + this.isCID); this.glyphs.setCharString(glyphName, nextGlyph, jj); current = glyphoffset[jj]; if (this.trackIndices) { this.glyphs.setIndexForCharString(jj, glyphName); } } } private static final int calculateSubroutineBias(int subroutineCount) { int bias; if (subroutineCount < 1240) { bias = 107; } else if (subroutineCount < 33900) { bias = 1131; } else { bias = 32768; } return bias; } private final void readGlobalSubRoutines(byte[] fontDataAsArray, FontData fontDataAsObject) throws Exception { boolean isByteArray = (fontDataAsArray != null); int subOffSize, count; if (isByteArray) { subOffSize = (fontDataAsArray[this.top + 2] & 0xff); count = getWord(fontDataAsArray, this.top, 2); } else { subOffSize = (fontDataAsObject.getByte(this.top + 2) & 0xff); count = getWord(fontDataAsObject, this.top, 2); } this.top += 3; if (count > 0) { int idx = this.top; int start = this.top + (count + 1) * subOffSize - 1; if (isByteArray) this.top = start + getWord(fontDataAsArray, this.top + count * subOffSize, subOffSize); else this.top = start + getWord(fontDataAsObject, this.top + count * subOffSize, subOffSize); int[] offset = new int[count + 2]; int ii = idx; // read the offsets for (int jj = 0; jj < count + 1; jj++) { if (isByteArray) offset[jj] = start + getWord(fontDataAsArray, ii, subOffSize); else offset[jj] = start + getWord(fontDataAsObject, ii, subOffSize); ii = ii + subOffSize; } offset[count + 1] = this.top; this.glyphs.setGlobalBias(calculateSubroutineBias(count)); // read the subroutines and store int current = offset[0]; for (int jj = 1; jj < count + 1; jj++) { ByteArrayOutputStream nextStream = new ByteArrayOutputStream(); for (int c = current; c < offset[jj]; c++) { if (isByteArray) nextStream.write(fontDataAsArray[c]); else nextStream.write(fontDataAsObject.getByte(c)); } nextStream.close(); // store this.glyphs.setCharString("global" + (jj - 1), nextStream.toByteArray(), jj); // setGlobalSubroutine(new Integer(jj-1+bias),nextStream.toByteArray()); current = offset[jj]; } } } private void decodeDictionary(byte[] fontDataAsArray, FontData fontDataAsObject, int dicStart, int dicEnd, String[] strings) { boolean fdReset = false; if (debugDictionary) System.out.println("=============Read dictionary====================" + getBaseFontName()); boolean isByteArray = fontDataAsArray != null; int p = dicStart, nextVal, key; int i = 0; double[] op = new double[48]; // current operand in dictionary while (p < dicEnd) { if (isByteArray) nextVal = fontDataAsArray[p] & 0xFF; else nextVal = fontDataAsObject.getByte(p) & 0xFF; if (nextVal <= 27 || nextVal == 31) { // operator key = nextVal; p++; if (debugDictionary && key != 12) System.out.println(key + " (1) " + OneByteCCFDict[key]); if (key == 0x0c) { // handle escaped keys if (isByteArray) key = fontDataAsArray[p] & 0xFF; else key = fontDataAsObject.getByte(p) & 0xFF; if (debugDictionary) System.out.println(key + " (2) " + TwoByteCCFDict[key]); p++; if (key != 36 && key != 37 && key != 7 && this.FDSelect != -1) { if (debugDictionary) { System.out.println("Ignored as part of FDArray "); for (int ii = 0; ii < 6; ii++) System.out.println(op[ii]); } } else if (key == 2) { // italic this.italicAngle = (int) op[0]; if (debugDictionary) System.out.println("Italic=" + op[0]); } else if (key == 7) { // fontMatrix if (!this.hasFontMatrix) System.arraycopy(op, 0, this.FontMatrix, 0, 6); if (debugDictionary) { for (int ii = 0; ii < 6; ii++) System.out.println(ii + "=" + op[ii] + ' ' + this); } this.hasFontMatrix = true; } else if (key == 6) { if (op[0] > 0) { this.blueValues = new int[6]; for (int z = 0; z < this.blueValues.length; z++) { this.blueValues[z] = (int) op[z]; } } } else if (key == 7) { if (op[0] > 0) { this.otherBlues = new int[6]; for (int z = 0; z < this.otherBlues.length; z++) { this.otherBlues[z] = (int) op[z]; } } } else if (key == 8) { this.familyBlues = new int[6]; for (int z = 0; z < this.familyBlues.length; z++) { this.familyBlues[z] = (int) op[z]; } } else if (key == 9) { if (op[0] > 0) { this.familyOtherBlues = new int[6]; for (int z = 0; z < this.familyOtherBlues.length; z++) { this.familyOtherBlues[z] = (int) op[z]; } } } else if (key == 10) { this.stdHW = (int) op[0]; } else if (key == 11) { this.stdVW = (int) op[0]; } else if (key == 30) { // ROS this.ros = (int) op[0]; this.isCID = true; if (debugDictionary) System.out.println(op[0]); } else if (key == 31) { // CIDFontVersion this.CIDFontVersion = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 32) { // CIDFontRevision this.CIDFontRevision = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 33) { // CIDFontType this.CIDFontType = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 34) { // CIDcount this.CIDcount = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 35) { // UIDBase this.UIDBase = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 36) { // FDArray this.FDArray = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 37) { // FDSelect this.FDSelect = (int) op[0]; fdReset = true; if (debugDictionary) System.out.println(op[0]); } else if (key == 0) { // copyright int id = (int) op[0]; if (id > 390) id = id - 390; this.copyright = strings[id]; if (debugDictionary) System.out.println("copyright= " + this.copyright); } else if (key == 21) { // Postscript // postscriptFontName=strings[id]; if (debugDictionary) { int id = (int) op[0]; if (id > 390) id = id - 390; System.out.println("Postscript= " + strings[id]); System.out.println(TwoByteCCFDict[key] + ' ' + op[0]); } } else if (key == 22) { // BaseFontname // baseFontName=strings[id]; if (debugDictionary) { int id = (int) op[0]; if (id > 390) id = id - 390; System.out.println("BaseFontname= " + this.embeddedFontName); System.out.println(TwoByteCCFDict[key] + ' ' + op[0]); } } else if (key == 38) { // fullname // fullname=strings[id]; if (debugDictionary) { int id = (int) op[0]; if (id > 390) id = id - 390; System.out.println("fullname= " + strings[id]); System.out.println(TwoByteCCFDict[key] + ' ' + op[0]); } } else if (debugDictionary) System.out .println(op[0]); } else { if (key == 2) { // fullname int id = (int) op[0]; if (id > 390) id = id - 390; this.embeddedFontName = strings[id]; if (debugDictionary) { System.out.println("name= " + this.embeddedFontName); System.out.println(OneByteCCFDict[key] + ' ' + op[0]); } } else if (key == 3) { // familyname // embeddedFamilyName=strings[id]; if (debugDictionary) { int id = (int) op[0]; if (id > 390) id = id - 390; System.out.println("FamilyName= " + this.embeddedFamilyName); System.out.println(OneByteCCFDict[key] + ' ' + op[0]); } } else if (key == 5) { // fontBBox if (debugDictionary) { for (int ii = 0; ii < 4; ii++) System.out.println(op[ii]); } for (int ii = 0; ii < 4; ii++) { // System.out.println(" "+ii+" "+op[ii]); this.FontBBox[ii] = (float) op[ii]; } // hasFontBBox=true; } else if (key == 0x0f) { // charset this.charset = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 0x10) { // encoding this.enc = (int) op[0]; if (debugDictionary) System.out.println(op[0]); } else if (key == 0x11) { // charstrings this.charstrings = (int) op[0]; if (debugDictionary) System.out.println(op[0]); // System.out.println("charStrings="+charstrings); } else if (key == 18 && this.glyphs.is1C()) { // readPrivate int dictNo = this.currentFD; if (dictNo == -1) { dictNo = 0; } this.privateDict[dictNo] = (int) op[1]; this.privateDictOffset[dictNo] = (int) op[0]; if (debugDictionary) System.out.println("privateDict=" + op[0] + " Offset=" + op[1]); } else if (key == 20) { // defaultWidthX int dictNo = this.currentFD; if (dictNo == -1) { dictNo = 0; } this.defaultWidthX[dictNo] = (int) op[0]; if (this.glyphs instanceof T1Glyphs) ((T1Glyphs) this.glyphs).setWidthValues(this.defaultWidthX, this.nominalWidthX); if (debugDictionary) System.out.println("defaultWidthX=" + op[0]); } else if (key == 21) { // nominalWidthX int dictNo = this.currentFD; if (dictNo == -1) { dictNo = 0; } this.nominalWidthX[dictNo] = (int) op[0]; if (this.glyphs instanceof T1Glyphs) ((T1Glyphs) this.glyphs).setWidthValues( this.defaultWidthX, this.nominalWidthX); if (debugDictionary) System.out.println("nominalWidthX=" + op[0]); } else if (debugDictionary) { // System.out.println(p+" "+key+" "+T1CcharCodes1Byte[key]+" <<<"+op); System.out.println("Other value " + key); /** * if(op <type1CStdStrings.length) System.out.println(type1CStdStrings[(int)op]); else * if((op-390) <strings.length) System.out.println("interesting key:"+key); */ } // System.out.println(p+" "+key+" "+raw1ByteValues[key]+" <<<"+op); } i = 0; } else { if (isByteArray) p = this.glyphs.getNumber(fontDataAsArray, p, op, i, false); else p = this.glyphs.getNumber(fontDataAsObject, p, op, i, false); i++; } } if (debugDictionary) System.out.println("=================================" + getBaseFontName()); // reset if (!fdReset) this.FDSelect = -1; } private String[] readStringIndex(byte[] fontDataAsArray, FontData fontDataAsObject, int start, int offsize, int count) { int nStrings; boolean isByteArray = (fontDataAsArray != null); if (isByteArray) { this.top = start + getWord(fontDataAsArray, this.top + count * offsize, offsize); // start of string index nStrings = getWord(fontDataAsArray, this.top, 2); this.stringOffSize = fontDataAsArray[this.top + 2]; } else { this.top = start + getWord(fontDataAsObject, this.top + count * offsize, offsize); // start of string index nStrings = getWord(fontDataAsObject, this.top, 2); this.stringOffSize = fontDataAsObject.getByte(this.top + 2); } this.top += 3; this.stringIdx = this.top; this.stringStart = this.top + (nStrings + 1) * this.stringOffSize - 1; if (isByteArray) this.top = this.stringStart + getWord(fontDataAsArray, this.top + nStrings * this.stringOffSize, this.stringOffSize); else this.top = this.stringStart + getWord(fontDataAsObject, this.top + nStrings * this.stringOffSize, this.stringOffSize); int[] offsets = new int[nStrings + 2]; String[] strings = new String[nStrings + 2]; int ii = this.stringIdx; // read the offsets for (int jj = 0; jj < nStrings + 1; jj++) { if (isByteArray) offsets[jj] = getWord(fontDataAsArray, ii, this.stringOffSize); // content[ii] & 0xff; else offsets[jj] = getWord(fontDataAsObject, ii, this.stringOffSize); // content[ii] & 0xff; // getWord(content,ii,stringOffSize); ii = ii + this.stringOffSize; } offsets[nStrings + 1] = this.top - this.stringStart; // read the strings int current = 0; StringBuilder nextString; for (int jj = 0; jj < nStrings + 1; jj++) { nextString = new StringBuilder(offsets[jj] - current); for (int c = current; c < offsets[jj]; c++) { if (isByteArray) nextString.append((char) fontDataAsArray[this.stringStart + c]); else nextString.append((char) fontDataAsObject.getByte(this.stringStart + c)); } if (debugFont) System.out.println("String " + jj + " =" + nextString); strings[jj] = nextString.toString(); current = offsets[jj]; } return strings; } /** Utility method used during processing of type1C files */ static final private String getString(FontData fontDataAsObject, int sid, int idx, int start, int offsize) { int len; String result; if (sid < 391) result = type1CStdStrings[sid]; else { sid -= 391; int idx0 = start + getWord(fontDataAsObject, idx + sid * offsize, offsize); int idxPtr1 = start + getWord(fontDataAsObject, idx + (sid + 1) * offsize, offsize); // System.out.println(sid+" "+idx0+" "+idxPtr1); if ((len = idxPtr1 - idx0) > 255) len = 255; result = new String(fontDataAsObject.getBytes(idx0, len)); } return result; } /** Utility method used during processing of type1C files */ static final private String getString(byte[] fontDataAsArray, int sid, int idx, int start, int offsize) { int len; String result; if (sid < 391) result = type1CStdStrings[sid]; else { sid -= 391; int idx0 = start + getWord(fontDataAsArray, idx + sid * offsize, offsize); int idxPtr1 = start + getWord(fontDataAsArray, idx + (sid + 1) * offsize, offsize); // System.out.println(sid+" "+idx0+" "+idxPtr1); if ((len = idxPtr1 - idx0) > 255) len = 255; result = new String(fontDataAsArray, idx0, len); } return result; } /** get standard charset or extract from type 1C font */ static final private int[] readCharset(int charset, int nGlyphs, FontData fontDataAsObject, byte[] fontDataAsArray) { boolean isByteArray = fontDataAsArray != null; int glyphNames[]; int i, j; if (debugFont) System.out.println("charset=" + charset); /** * //handle CIDS first if(isCID){ glyphNames = new int[nGlyphs]; glyphNames[0] = 0; * * for (i = 1; i < nGlyphs; ++i) { glyphNames[i] = i;//getWord(fontData, top, 2); //top += 2; } * * * // read appropriate non-CID charset }else */ if (charset == 0) glyphNames = ISOAdobeCharset; else if (charset == 1) glyphNames = ExpertCharset; else if (charset == 2) glyphNames = ExpertSubCharset; else { glyphNames = new int[nGlyphs + 1]; glyphNames[0] = 0; int top = charset; int charsetFormat; if (isByteArray) charsetFormat = fontDataAsArray[top++] & 0xff; else charsetFormat = fontDataAsObject.getByte(top++) & 0xff; if (debugFont) System.out.println("charsetFormat=" + charsetFormat); if (charsetFormat == 0) { for (i = 1; i < nGlyphs; ++i) { if (isByteArray) glyphNames[i] = getWord(fontDataAsArray, top, 2); else glyphNames[i] = getWord(fontDataAsObject, top, 2); top += 2; } } else if (charsetFormat == 1) { i = 1; int c, nLeft; while (i < nGlyphs) { if (isByteArray) c = getWord(fontDataAsArray, top, 2); else c = getWord(fontDataAsObject, top, 2); top += 2; if (isByteArray) nLeft = fontDataAsArray[top++] & 0xff; else nLeft = fontDataAsObject.getByte(top++) & 0xff; for (j = 0; j <= nLeft; ++j) glyphNames[i++] = c++; } } else if (charsetFormat == 2) { i = 1; int c, nLeft; while (i < nGlyphs) { if (isByteArray) c = getWord(fontDataAsArray, top, 2); else c = getWord(fontDataAsObject, top, 2); top += 2; if (isByteArray) nLeft = getWord(fontDataAsArray, top, 2); else nLeft = getWord(fontDataAsObject, top, 2); top += 2; for (j = 0; j <= nLeft; ++j) glyphNames[i++] = c++; } } } return glyphNames; } /** Utility method used during processing of type1C files */ static final private int getWord(FontData fontDataAsObject, int index, int size) { int result = 0; for (int i = 0; i < size; i++) { result = (result << 8) + (fontDataAsObject.getByte(index + i) & 0xff); } return result; } /** Utility method used during processing of type1C files */ static final private int getWord(byte[] fontDataAsArray, int index, int size) { int result = 0; for (int i = 0; i < size; i++) { result = (result << 8) + (fontDataAsArray[index + i] & 0xff); } return result; } /** * get bounding box to highlight * * @return */ @Override public Rectangle getBoundingBox() { if (this.BBox == null) { if (this.isFontEmbedded) this.BBox = new Rectangle((int) this.FontBBox[0], (int) this.FontBBox[1], (int) (this.FontBBox[2] - this.FontBBox[0]), (int) (this.FontBBox[3] - this.FontBBox[1])); // To change body of created methods // use File | Settings | File // Templates. else this.BBox = super.getBoundingBox(); } return this.BBox; } /** * @return The Font Dictionary select array */ public int[] getFDSelect() { return this.fdSelect; } public int[] getRosArray() { return this.rosArray; } public Object getKeyValue(int key) { switch (key) { case WEIGHT: return this.weight; case ITALICANGLE: return this.italicAngle; case FONTMATRIX: return this.FontMatrix; case FONTBBOX: return this.FontBBox; case ENCODING: return this.enc; case DEFAULTWIDTHX: return this.defaultWidthX[0]; case NOMINALWIDTHX: return this.nominalWidthX[0]; case BLUEVALUES: return this.blueValues; case OTHERBLUES: return this.otherBlues; case FAMILYBLUES: return this.familyBlues; case FAMILYOTHERBLUES: return this.familyOtherBlues; case STDHW: return this.stdHW; case STDVW: return this.stdVW; case SUBRS: return this.subrs; case ROS: return this.ros; case CIDCOUNT: return this.CIDcount; case CIDFONTREVISION: return this.CIDFontRevision; case CIDFONTVERSION: return this.CIDFontVersion; case CIDFONTTYPE: return this.CIDFontType; case FDARRAY: return this.FDArray; case FDSELECT: return this.FDSelect; default: throw new RuntimeException("Key is unknown or value is not yet assigned " + key); } } }
Skipper24/JPedal
src/org/jpedal/fonts/Type1C.java
249,372
import java.util.*; class Program { public static int[] twoNumberSum(int[] array, int targetSum) { // First put each number in a map for better lookup HashMap<Integer, Boolean> values = new HashMap<Integer, Boolean>(); for (int i : array) { values.put(i, true); } // Find the target sum for (int v : array) { int lookingFor = targetSum - v; if (lookingFor == v) { continue; } if (values.get(lookingFor) != null) { return new int[]{v, lookingFor}; } } return new int[0]; } }
masharp/algorithms-n-structures
algo-experts/TwoNumberSum.java
249,373
package server; import javax.swing.JButton; import javax.swing.JFrame; /** * Render a GUI for the server * * @author Group 4 * @version 0.6 * */ public class ServerGui extends JFrame{ private Server s; private JButton next; /** * GUI constructor * @param Fika experts */ public ServerGui(Server serv){ this.s = serv; this.makeFrame(); } /** * Initiate server GUI */ private void makeFrame() { next = new JButton("Next"); next.addActionListener(e->this.s.getGroup().nextFika()); this.add(next); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); this.setVisible(true); this.pack(); } }
larstomas/DAT055-ProjektFika
src/server/ServerGui.java
249,375
404: Not Found
trieuthanhdat/OnlineLearningG6
src/java/Temp/UsersDAO.java
249,376
import java.sql.PreparedStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; public class Choosine { public static void main(String[] args) throws java.lang.ClassNotFoundException { Connection con = null; PreparedStatement pst = null; ResultSet rs = null; if (args.length < 1) { System.err.println("ERROR: Usage: Choosine pollid"); return; } int pollid; try { pollid = Integer.parseInt(args[0]); } catch (Exception e) { System.err.println("ERROR: pollid must be an integer!"); return; } // To be initialized from mysql data int experts = 0; int size = 0; int length = 0; int[] choices = new int[0]; double[] rank = new double[0]; int[] id = new int[0]; Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/foodle"; // WHATEVER YOU WOULD WANT HERE String user = "foodle_admin"; // OUR USER-ID String password = "guru47*speck"; // USER PASSWORD try { con = DriverManager.getConnection(url, user, password); pst = con.prepareStatement("SELECT * FROM polls WHERE pollid = " + pollid); rs = pst.executeQuery(); rs.first(); size = rs.getInt(2); experts = rs.getInt(3); rs.close(); pst.close(); pst = con.prepareStatement("SELECT COUNT(*) FROM votes WHERE pollid = " + pollid); rs = pst.executeQuery(); rs.first(); length = rs.getInt(1); rs.close(); pst.close(); pst = con.prepareStatement("SELECT * FROM votes WHERE pollid = " + pollid); rs = pst.executeQuery(); int counter = 0; choices = new int[length]; rank = new double[length]; id = new int[length]; while (rs.next()) { id[counter] = rs.getInt(3); choices[counter]=rs.getInt(4); rank[counter] = rs.getDouble(5); // Check for errors in database data if (choices[counter] >= size || choices[counter] < 0) { System.err.println("ERROR: some vote has choiceid >= numchoices or < 0"); // This is the only "fatal" error if we let it run return; } else if (id[counter] > experts || id[counter] <= 0) { System.err.println("ERROR: some vote has voterid > numvoters or <= 0"); //return; } else if (rank[counter] > size || rank[counter] <= 0) { System.err.println("ERROR: some vote has voterid > numvoters or <= 0"); //return; } counter++; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Choosine.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { try { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Choosine.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } double[][] freq = new double[size][size]; for(int k=0;k<length;k++){ for(int l=k;l<length;l++){ if((id[k] == id[l]) && (rank[k] < rank [l])){ freq[choices[k]][choices[l]]= freq[choices[k]][choices[l]] + rank[l]-rank[k]; } if((id[k] == id[l]) && (rank[l] < rank [k])){ freq[choices[l]][choices[k]] = freq[choices[l]][choices[k]] + rank[k] - rank[l]; } } } // uncertainties for pairwise ranks (to add to DAG) Double[] toSort = new Double[size*size]; Double[] toSortOr = new Double[size*size]; int counter = 0; for(int i=0; i < size; i++){ for(int j=0; j < size; j++){ toSort[counter] = freq[j][i] - freq[i][j]; toSortOr[counter] = freq[j][i] - freq[i][j]; counter++; } } // sorting the uncertainty values mentioned above Insertion insertion = new Insertion(); insertion.sort(toSort); // the DAG Digraph digraph = new Digraph(size); int v1 = 0; int v2 = 0; for(int i = 0; i < toSort.length; i++){ for(int k = 0; k < toSort.length; k++){ v1 = 0; v2 = 0; if(Math.abs(toSort[i] - toSortOr[k]) < 0.001){ // Adding edges to DAG if(!digraph.contains(k/size,k%size)){ v1 = k/size; v2 = k%size; } digraph.addEdge(v1,v2); DirectedCycle finder = new DirectedCycle(digraph); if(finder.hasCycle()) {digraph.removeEdge(v1); } } } } //StdOut.println(digraph); // Getting an ordering, and saving it to the MySQL database Topological topological = new Topological(digraph); try { con = DriverManager.getConnection(url, user, password); // get the old table pst = con.prepareStatement("SELECT resultstable FROM polls WHERE pollid = ?"); pst.setInt(1, pollid); rs = pst.executeQuery(); rs.first(); String oldtablename = rs.getString(1); rs.close(); pst.close(); /* get a name for the new table (of the form results0.23, where 0 is the pollid, 23 is the update number */ int tableindex; if (oldtablename == null) { tableindex = 0; } else { try { String stringnum = oldtablename.substring(oldtablename.indexOf("_") + 1); //System.out.println("Number from old table: " + stringnum); tableindex = Integer.parseInt(stringnum); } catch (Exception e) { System.err.println("ERROR! Bad table name (bad int parsing): " + oldtablename); tableindex = 0; } } tableindex++; String tablename = "results" + pollid + "_" + tableindex++; // Don't reuse an existing table name pst = con.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'foodle' AND table_name = ?"); pst.setString(1, tablename); rs = pst.executeQuery(); rs.first(); while (rs.getInt(1) > 0) { rs.close(); pst.close(); tableindex++; tablename = "results" + pollid + "_" + tableindex++; pst = con.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'foodle' AND table_name = ?"); pst.setString(1, tablename); rs = pst.executeQuery(); rs.first(); } rs.close(); pst.close(); pst = con.prepareStatement("CREATE TABLE " + tablename + "(choiceid INT PRIMARY KEY, rank INT)"); pst.executeUpdate(); pst.close(); // construct the table int[] ordering = new int[size]; counter = 0; for(int v:topological.order()) { pst = con.prepareStatement("REPLACE INTO "+tablename+" VALUES (?, ?)"); pst.setInt(1, counter); pst.setInt(2, v); pst.executeUpdate(); pst.close(); ordering[counter] = v; counter++; } // replace the reference to the table from the polls table pst = con.prepareStatement("UPDATE polls SET resultstable = ? WHERE pollid = ?"); pst.setString(1, tablename); pst.setInt(2, pollid); pst.executeUpdate(); pst.close(); // drop the old table if (oldtablename != null && !oldtablename.equals(tablename)) { pst = con.prepareStatement("DROP TABLE "+oldtablename); pst.executeUpdate(); pst.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Choosine.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { try { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Choosine.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } } }
azzy/Foodle
voting-alg/Choosine.java
249,379
package graphs; import java.util.*; import java.util.Deque; // Problem Title => Two Clique Problem /* * Two Clique Problem (Check if Graph can be divided in two Cliques) Difficulty Level : Hard Last Updated : 20 Aug, 2021 A Clique is a subgraph of graph such that all vertices in subgraph are completely connected with each other. Given a Graph, find if it can be divided into two Cliques. Examples: Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course. In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students. Input : G[][] = {{0, 1, 1, 0, 0}, {1, 0, 1, 1, 0}, {1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {0, 0, 0, 1, 0}}; Output : Yes Recommended: Please try your approach on {IDE} first, before moving on to the solution. This problem looks tricky at first, but has a simple and interesting solution. A graph can be divided in two cliques if its complement graph is Bipartitie. So below are two steps to find if graph can be divided in two Cliques or not. Find the complement of Graph. Below is the complement graph is above shown graph. In complement, all original edges are removed. And the vertices which did not have an edge between them, now have an edge connecting them. twoclique2 Return true if complement is Bipartite, else false. The above shown graph is Bipartite. Checking whether a Graph is Biparitite or no is discussed here. How does this work? If complement is Bipartite, then graph can be divided into two sets U and V such that there is no edge connecting to vertices of same set. This means in original graph, these sets U and V are completely connected. Hence original graph could be divided in two Cliques. * */ public class Graph_Problem_44 { static int V = 5; // This function returns true if subgraph reachable from // src is Bipartite or not. static boolean isBipartiteUtil(int G[][], int src, int colorArr[]) { colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers and enqueue // source vertex for BFS traversal Deque <Integer> q = new ArrayDeque<>(); q.push(src); // Run while there are vertices in queue (Similar to BFS) while (!q.isEmpty()) { // Dequeue a vertex from queue int u = q.peek(); q.pop(); // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists and destination // v is not colored if (G[u][v] == -1 && colorArr[v] == -1) { // Assign alternate color to this adjacent // v of u colorArr[v] = 1 - colorArr[u]; q.push(v); } // An edge from u to v exists and destination // v is colored with same color as u else if (G[u][v] == colorArr[u] && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all adjacent vertices can // be colored with alternate color return true; } // Returns true if a Graph G[][] is Bipartite or not. Note // that G may not be connected. static boolean isBipartite(int G[][]) { // Create a color arrays.array to store colors assigned // to all vertices. Vertex number is used as index in // this arrays.array. The value '-1' of colorArr[i] // is used to indicate that no color is assigned to // vertex 'i'. The value 1 is used to indicate first // color is assigned and value 0 indicates // second color is assigned. int colorArr[]=new int[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // One by one check all not yet colored vertices. for (int i = 0; i < V; i++) if (colorArr[i] == -1) if (isBipartiteUtil(G, i, colorArr) == false) return false; return true; } // Returns true if G can be divided into // two Cliques, else false. static boolean canBeDividedinTwoCliques(int G[][]) { // Find complement of G[][] // All values are complemented except // diagonal ones int GC[][]=new int[V][V]; for (int i=0; i<V; i++) for (int j=0; j<V; j++) GC[i][j] = (i != j)? -GC[i][j] : 0; // Return true if complement is Bipartite // else false. return isBipartite(GC); } // Driver program to test above function public static void main(String[] args) { int[][] G = {{0, 1, 1, 1, 0}, {1, 0, 1, 0, 0}, {1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {0, 0, 0, 1, 0} }; if(canBeDividedinTwoCliques(G)) System.out.println("Yes"); else System.out.println("No"); } }
amangit1314/Java-Programs
graphs/Graph_Problem_44.java
249,380
package com.ubertob; import static com.ubertob.examples.MiniStringTrades.generatingTradesAndBrowing; public class Main { //reference: //http://cr.openjdk.java.net/~fparain/L-world/L-World-JVMS-4f.pdf //https://wiki.openjdk.java.net/display/valhalla/L-World+Value+Types //https://wiki.openjdk.java.net/display/valhalla/L-World+Value+Types+Command-line+Options //https://wiki.openjdk.java.net/display/valhalla/LW2 //https://mail.openjdk.java.net/pipermail/valhalla-spec-experts/2019-July/001091.html //You need to compile with javac -XDallowGenericsOverValues flag //Error:(3, 15) java: cannot access java.lang.invoke.ValueBootstrapMethods // class file for java.lang.invoke.ValueBootstrapMethods not found //you need source =14 public static void main(String[] args) { // BrowseTree.recursiveCalls(); // // System.out.println("\n\nNormal class Shark " + Metadata.extractClassMetadata(Shark.class)); // System.out.println("\n\nInline Type Cat " + Metadata.extractClassMetadata(Cat.class)); // //// Cat? maybeCat = null; //// System.out.println("\n\nInline Type Cat? " + Metadata.extractClassMetadata(maybeCat.class)); // // FlattenArrays.equalityAndToString(); // // FlattenArrays.boxesAndNullability(); // // FlattenArrays.flattenedArray(); // // Generics.wrappingInlined(); // // FlattenedStrings.userMemorySize(); generatingTradesAndBrowing(); } }
uberto/testValueTypes
src/main/java/com/ubertob/Main.java
249,382
package genesis; import java.awt.*; import java.util.Arrays; import javax.swing.*; //import adaTaylor.humor.HumorExpert; //import carolineAronoff.PsychologicallyPlausibleModel; import connections.ButtonSwitchBox; import consciousness.RecipeFinder; import constants.Radio; import constants.Switch; import dylanHolmes.MeansEndsProcessor; import expert.EscalationExpert; import expert.JessicasExpert; import gui.*; import gui.panels.BorderedParallelJPanel; import gui.panels.ParallelJPanel; //import olgaShestopalova.PredictionExpert; import subsystems.ExplanationBox; import subsystems.rashi.RashisExperts; import subsystems.rashi.SummarizeIntentions; import subsystems.recall.StoryRecallExpert; import subsystems.summarizer.Persuader; import subsystems.summarizer.Summarizer; import expert.StatisticsExpert; import utils.*; import zhutianYang.StoryAligner; /* * Created on May 8, 2010 * @author phw */ public class GenesisControls extends GenesisMenus { private SwitchPanel storyTellingControls; private SwitchPanel schizophreniaControls; private SwitchPanel conceptNetControls; private SwitchPanel rashiControls; private SwitchPanel expertControls; private SwitchPanel badGrammarControls; private SwitchColumns storyReadingControls; private SwitchPanel storySummaryControls; private SwitchColumns humorControls; private BorderedParallelJPanel storyPersuasionControls; protected static JButton nextButton; protected static JButton runButton; private ButtonSwitchBox syntaxToSemanticsSwitchBox; // protected JRadioButton left = new JRadioButton("P1"); // // protected JRadioButton right = new JRadioButton("P2"); // // protected JRadioButton both = new JRadioButton("Both"); public static JRadioButton leftButton; public static JRadioButton rightButton; public static JRadioButton bothButton; public static JComboBox teachingLevel; public static JCheckBoxMenuItem collaboration; public static JButton makeLargeVideoRecordingButton = new JButton("Set video recording dimensions to 1600 x 1200 (4:3)"); public static JButton makeSmallVideoRecordingButton = new JButton("Set video recording dimensions to 1024 x 768 (4:3, best for PowerPoint)"); public static JButton makeMediumVideoRecordingButton = new JButton("Set video recording dimensions to 1280 x 1024"); public static JButton makeCoUButton = new JButton("Set video recording dimensions to 1920 x 1080 (best for 10-250)"); protected JButton wordnetPurgeButton = new JButton("Purge WordNet cache"); protected JButton startPurgeButton = new JButton("Purge Start cache"); protected JButton conceptNetPurgeButton = new JButton("Purge ConceptNet cache"); protected JButton runAligner = new JButton("Run Aligner"); protected JButton clearMemoryButton = new JButton("Clear memory"); protected JButton eraseTextButton = new JButton("Erase text"); protected JButton disambiguationButton = new JButton("Load disambiguating events"); protected JButton experienceButton = new JButton("Load visual events"); protected JButton focusButton = new JButton("Select focus experience"); protected JButton clearSummaryTableButton = new JButton("Clear summary table"); protected ButtonGroup leftRightGroup; private JTabbedPane controls; private JTabbedPane tabbedSubsystems; private static TabbedMentalModelViewer mentalModelViewer; private ParallelJPanel conceptOptionsPanel; private ParallelJPanel behaviorOptionsPanel; private SwitchColumns summaryPersuaderPanel; private SwitchColumns consciousnessPanel; private ParallelJPanel subsystemsPanel; private ParallelJPanel storyTellingButtons = null; private ParallelJPanel debuggingPanel; private ParallelJPanel checkInPanel; private ParallelJPanel co57Panel; private ParallelJPanel videoPanel; private ParallelJPanel graveyardPanel; private ParallelJPanel actionButtons; protected JButton testSentencesButton = new JButton("Run test sentences"); protected JButton testStoriesButton = new JButton("Run test stories"); protected JButton testOperationsButton = new JButton("Run test operations"); protected JButton demonstrateConnectionsButton = new JButton("Demonstrate connection types"); protected JButton demonstrateConceptsButton = new JButton("Demonstrate concept options"); protected JButton rerunExperiment = new JButton("Run experiment again"); protected JButton rereadFile = new JButton("Read file again"); protected JButton demoSimulator = new JButton("Demo simulator"); protected JButton debugVideoFileButton = new JButton("Demo video story"); protected JButton loopButton = new JButton("Run loop"); protected JButton kjFileButton = new JButton("Korea/Japen"); protected JButton kjeFileButton = new JButton("Korea/Japan-Estonia/Russia"); protected JButton loadVideoPrecedents = new JButton("Load precedents"); protected JButton visionFileButton = new JButton("Vision commands"); protected JButton debugButton1 = new JButton("Debug text in debug1.txt"); protected JButton debugButton2 = new JButton("Debug text in debug2.txt"); protected JButton debugButton3 = new JButton("Debug text in debug3.txt"); protected JButton runWorkbenchTest = new JButton("Run Story Workbench test"); protected JButton simulateCo57Button = new JButton("Test/Simulate Co57"); protected JButton connectTestingBox = new JButton("Connect story testing box"); protected JButton disconnectTestingBox = new JButton("Disconnect story testing box"); protected JButton test1Button = new JButton("Check in test 1"); protected JButton test2Button = new JButton("Check in test 2"); public static JCheckBox useNewMatcherCheckBox = new JCheckBox("Use unified matcher", true); public static JCheckBox matchAllThreads = new JCheckBox("Match all threads", true); public static JCheckBox reportMatchingDifferencesCheckBox = new JCheckBox("Report Matcher Differences", false); public static JRadioButton co57LocalPassthrough = new JRadioButton("Use Local Passthrough Server", true); public static JRadioButton co57Passthrough = new JRadioButton("Use Co57 Passthrough Server"); public static JRadioButton co57SimulatorAndTranslator = new JRadioButton("Use Beryl Simulator Translator", true); public static JRadioButton co57JustTranslator = new JRadioButton("Only start Beryl Translator"); private EscalationExpert escalationExpert1; private EscalationExpert escalationExpert2; private StoryRecallExpert storyRecallExpert1; private StoryRecallExpert storyRecallExpert2; // private PredictionExpert predictionExpert1; private StatisticsExpert statisticsExpert; private JessicasExpert jessicasExpert; //private CarolinesExpert carolinesExpert; // private PsychologicallyPlausibleModel carolinesExpert; private MeansEndsProcessor dylansExpert; // private HumorExpert humorExpert; public static JLabel testStartConnection = new JLabel("Test"); class BorderedSwitchPanelWithExplanation extends JPanel { BorderedSwitchPanel bsp; public BorderedSwitchPanelWithExplanation(String name, String description) { setLayout(new BorderLayout()); bsp = new BorderedSwitchPanel(name); super.add(bsp, BorderLayout.CENTER); ExplanationBox box = new ExplanationBox(description); super.add(box, BorderLayout.SOUTH); } public void add(JToggleButton b) { bsp.addLeft(b); } public void add(JToggleButton b, String e) { add(b); bsp.addCenter(e); } } /** * Expects arguments in pairs: switch, explanation, but after title */ class BorderedSwitchPanel extends BorderedParallelJPanel { public BorderedSwitchPanel(Object... objects) { super((String) (objects[0])); setOpaque(true); setBackground(Color.WHITE); for (int i = 1; i < objects.length; i = i + 2) { JToggleButton s = (JToggleButton) (objects[i]); String e = (String) (objects[i + 1]); this.addLeft(s); this.addCenter(e); } } public void add(JToggleButton b) { addLeft(b); } public void add(JToggleButton b, String e) { add(b); addCenter(e); } } class SwitchPanelWithExplanation extends JPanel { SwitchPanel bsp; public SwitchPanelWithExplanation(String descriptions) { setLayout(new BorderLayout()); bsp = new SwitchPanel(); super.add(bsp, BorderLayout.CENTER); ExplanationBox box = new ExplanationBox(descriptions); super.add(box, BorderLayout.SOUTH); } public void add(JToggleButton b) { bsp.addLeft(b); } public void add(JToggleButton b, String e) { add(b); bsp.addCenter(e); } } /** * Expects arguments in pairs: switch, explanation */ class SwitchPanel extends ParallelJPanel { public SwitchPanel(Object... objects) { super(); setOpaque(true); setBackground(Color.WHITE); for (int i = 0; i < objects.length; i = i + 2) { JToggleButton s = (JToggleButton) (objects[i]); String e = (String) (objects[i + 1]); this.addLeft(s); this.addRight(e); } } public void add(JToggleButton b) { this.addLeft(b); } public void add(JToggleButton b, String e) { add(b); this.addCenter(e); } } class SwitchColumns extends JPanel { public SwitchColumns(JPanel... panels) { this.setLayout(new GridLayout(1, 0)); Arrays.asList(panels).stream().forEachOrdered(p -> this.add(p)); } } public JTabbedPane getControls() { if (controls == null) { controls = new JTabbedPane(); controls.setBackground(Color.WHITE); controls.setOpaque(true); controls.setName("Controls"); controls.addTab("Main", getMainMatrix()); // Do not add any subsystems // controls.addTab("Subsystems", getTabbedSubsystems()); // controls.addTab("Read/Tell", getReadTellMatrix()); setMinimumHeight(controls, 0); // controls.addTab("System options", getSystemSwitches()); controls.addTab("Miscellaneous", getMiscellaneousMatrix()); if (!Webstart.isWebStart()) { controls.addTab("Debugging", getDebuggingMatrix()); controls.addTab("Graveyard", getGraveyardMatrix()); } } return controls; } public JTabbedPane getTabbedSubsystems() { if (tabbedSubsystems == null) { tabbedSubsystems = new JTabbedPane(); tabbedSubsystems.setName("Subsystems"); tabbedSubsystems.setBackground(Color.WHITE); tabbedSubsystems.setOpaque(true); tabbedSubsystems.addTab("Reader", getStoryReadingControls()); tabbedSubsystems.addTab("Summarizer/persuader", getStorySummaryControls()); tabbedSubsystems.addTab("Self-aware responder", getConsciousnessPanel()); tabbedSubsystems.addTab("Basic responser", getExplanationPanel()); tabbedSubsystems.addTab("Story teller", getStoryTellingControls()); tabbedSubsystems.addTab("Surprise and Humor", getHumorControls()); tabbedSubsystems.addTab("Schizophrenia", getSchizophreniaControls()); tabbedSubsystems.addTab("BadGrammar sliders", getBadGrammarControls()); tabbedSubsystems.addTab("Expert advice link", getExpertControls()); tabbedSubsystems.addTab("Concept net link", getConceptNetControls()); } return tabbedSubsystems; } public SwitchColumns getStoryReadingControls() { if (storyReadingControls == null) { storyReadingControls = new SwitchColumns(); BorderedSwitchPanel bsp = new BorderedSwitchPanel("Minsky reasoning level"); bsp.add(Switch.level5UseMentalModels, "Minsky levels 5 & 6, actor-specific thinking"); bsp.add(Switch.level4ConceptPatterns, "Minsky level 4, reflective thinking"); bsp.add(Switch.level3ExplantionRules, "Minsky level 3, deliberative thinking"); bsp.add(Switch.Level2PredictionRules, "Minsky levels 1 & 2, reactive thinking"); storyReadingControls.add(bsp); bsp = new BorderedSwitchPanel("Concept management"); bsp.add(Switch.reportSubConceptsSwitch); bsp.add(Switch.findConceptOnsets); bsp.add(Switch.findConceptsContinuously); storyReadingControls.add(bsp); } return storyReadingControls; } BorderedSwitchPanel miscellaneousPanel; public BorderedSwitchPanel getMiscellaneousPanel() { if (miscellaneousPanel == null) { miscellaneousPanel = new BorderedSwitchPanel("Miscellaneous"); miscellaneousPanel.add(Switch.useInsertConceptConsequentsIntoStory, ""); miscellaneousPanel.add(Switch.useOnlyOneDeduction, ""); miscellaneousPanel.add(Switch.useOnlyOneExplanation, ""); miscellaneousPanel.add(Switch.levelLookForMentalModelEvidence, ""); miscellaneousPanel.add(Switch.pullNonEventsToLeft, ""); miscellaneousPanel.add(Switch.useColorInElaborationGraph, ""); miscellaneousPanel.add(Switch.showConnectionTypeInElaborationGraph, ""); getStoryReadingControls().add(miscellaneousPanel); } return miscellaneousPanel; } BorderedSwitchPanel matcherControlPanel; public BorderedSwitchPanel getMatcherControlPanel() { if (matcherControlPanel == null) { matcherControlPanel = new BorderedSwitchPanel("Matcher Control"); matcherControlPanel.add(Switch.useFeaturesWhenMatching, ""); matcherControlPanel.add(Switch.useMustWhenMatching, ""); matcherControlPanel.add(Switch.splitNamesWithUnderscores, ""); } return matcherControlPanel; } BorderedParallelJPanel simulatorControlPanel; public BorderedParallelJPanel getSimulatorControlPanel() { if (simulatorControlPanel == null) { simulatorControlPanel = new BorderedParallelJPanel("Simulator Control"); simulatorControlPanel.addCenter(Radio.blocksWorldSimulator); simulatorControlPanel.addCenter(Radio.robotSimulator); simulatorControlPanel.addCenter(Radio.realRobot); simulatorControlPanel.addCenter(Radio.justPlan); ButtonGroup group = new ButtonGroup(); group.add(Radio.blocksWorldSimulator); group.add(Radio.robotSimulator); group.add(Radio.realRobot); group.add(Radio.justPlan); } return simulatorControlPanel; } // ---------------------------------------------------------------------------------------- // added by Zhutian on 16 March 2019 for different modes of story aligner/ analogy making BorderedParallelJPanel alignerControlPanel; public BorderedParallelJPanel getAlignerControlPanel() { if (alignerControlPanel == null) { alignerControlPanel = new BorderedParallelJPanel("Story Aligner Control"); alignerControlPanel.addCenter(Radio.learnProcedure); alignerControlPanel.addCenter(Radio.learnConcept); alignerControlPanel.addCenter(Radio.learnDifference); ButtonGroup group = new ButtonGroup(); group.add(Radio.learnProcedure); group.add(Radio.learnConcept); group.add(Radio.learnDifference); } return alignerControlPanel; } // ---------------------------------------------------------------------------------------- public SwitchColumns getConsciousnessPanel() { if (consciousnessPanel == null) { consciousnessPanel = new SwitchColumns(); BorderedSwitchPanelWithExplanation bsp = new BorderedSwitchPanelWithExplanation("Inclusions", "Determines what is included in the elaboration graph."); bsp.add(Switch.useNegativesInExplanationsBox, ""); bsp.add(Switch.buildTree, ""); bsp.add(Switch.reportSteps, ""); bsp.add(Switch.reportComments, ""); consciousnessPanel.add(bsp); bsp = new BorderedSwitchPanelWithExplanation("Reporting level", "Determines how many levels of the goal tree are reported."); bsp.add(Radio.psLevel0, ""); bsp.add(Radio.psLevel1, ""); bsp.add(Radio.psLevel2, ""); bsp.add(Radio.psLevel3, ""); bsp.add(Radio.psLevelX, ""); bsp.add(Radio.psLevelP, ""); consciousnessPanel.add(bsp); bsp = new BorderedSwitchPanelWithExplanation("Miscellaneous", "Miscellaneous switches."); bsp.add(Switch.deplyNovice, ""); consciousnessPanel.add(bsp); ButtonGroup group = new ButtonGroup(); group.add(Radio.psLevel0); group.add(Radio.psLevel1); group.add(Radio.psLevel2); group.add(Radio.psLevel3); group.add(Radio.psLevelX); group.add(Radio.psLevelP); Radio.psLevelX.setSelected(true); } return consciousnessPanel; } public SwitchColumns getStorySummaryControls() { if (summaryPersuaderPanel == null) { summaryPersuaderPanel = new SwitchColumns(); BorderedSwitchPanel bsp = new BorderedSwitchPanel("Summarizer"); bsp.add(Switch.includeUnabriggedProcessing, ""); bsp.add(Switch.includeAgentRolesInSummary, ""); bsp.add(Switch.includeSurprises, ""); bsp.add(Switch.includeAbductions, ""); bsp.add(Switch.includePresumptions, ""); bsp.add(Switch.includeExplanations, ""); bsp.add(Switch.eliminateMeans, ""); bsp.add(Switch.eliminateIfFollowsFromPrevious, ""); bsp.add(Switch.showMarkup, ""); summaryPersuaderPanel.add(bsp); bsp = new BorderedSwitchPanel("Persuader"); bsp.add(Switch.showContrastInPersuasion); summaryPersuaderPanel.add(bsp); } return summaryPersuaderPanel; } public SwitchPanelWithExplanation getExplanationPanel() { if (explanationPanel == null) { explanationPanel = new SwitchPanelWithExplanation("Determines what is included in the answer to <i>why</i> questions. Used only when in basic question-answering mode."); explanationPanel.add(Switch.includePersonalityExplanationCheckBox, ""); explanationPanel.add(Switch.includeCauseExplanationCheckBox, ""); explanationPanel.add(Switch.includeConceptExplanationCheckBox, ""); } return explanationPanel; } public SwitchPanel getStoryTellingControls() { if (storyTellingControls == null) { storyTellingControls = new SwitchPanel(); storyTellingControls.add(Radio.tellStoryButton); storyTellingControls.add(Radio.spoonFeedButton); storyTellingControls.add(Radio.primingButton); storyTellingControls.add(Radio.primingWithIntrospectionButton); ButtonGroup group = new ButtonGroup(); group.add(Radio.spoonFeedButton); group.add(Radio.primingButton); group.add(Radio.primingWithIntrospectionButton); Radio.spoonFeedButton.setSelected(true); } return storyTellingControls; } public SwitchColumns getHumorControls() { if (humorControls == null) { humorControls = new SwitchColumns(); BorderedSwitchPanel surprise_panel = new BorderedSwitchPanel("Surprise Analysis"); surprise_panel.addLeft(Switch.humorCheckBox); surprise_panel.addLeft(Switch.humorContradictionCheckBox); surprise_panel.addLeft(Switch.humorParadoxCheckBox); //public static final CheckBoxWithMemory adaFlipCauseEffectCheckBox = new CheckBoxWithMemory("Err: Effect/Cause", false); surprise_panel.addLeft(Switch.humorLikelinessCheckBox); humorControls.add(surprise_panel); BorderedSwitchPanel resolution_panel = new BorderedSwitchPanel("Humor Resolution"); resolution_panel.addLeft(Switch.humorCharacter); resolution_panel.addLeft(Switch.humorMorbid); resolution_panel.addLeft(Switch.humorLanguage); resolution_panel.addLeft(Switch.humorTopic); resolution_panel.addLeft(Switch.humorMeaningAssignment); resolution_panel.addLeft(Switch.humorParseAmbiguity); humorControls.add(resolution_panel); } return humorControls; } public SwitchPanel getSchizophreniaControls() { if (schizophreniaControls == null) { schizophreniaControls = new SwitchPanel(); schizophreniaControls.add(Radio.sch_offButton); schizophreniaControls.add(Radio.sch_nonSchizophrenicButton); schizophreniaControls.add(Radio.sch_hyperpresumptionButton); schizophreniaControls.add(Radio.sch_failedInferringWantButton); ButtonGroup group = new ButtonGroup(); group.add(Radio.sch_offButton); Radio.sch_offButton.setSelected(true); group.add(Radio.sch_nonSchizophrenicButton); group.add(Radio.sch_hyperpresumptionButton); group.add(Radio.sch_failedInferringWantButton); } return schizophreniaControls; } public SwitchPanel getExpertControls() { if (expertControls == null) { expertControls = new SwitchPanel(); expertControls.addLeft(Switch.useExpertRules); } return expertControls; } public SwitchPanel getConceptNetControls() { if (conceptNetControls == null) { conceptNetControls = new SwitchPanel(); conceptNetControls.addLeft(Switch.performGoalAnalysis); conceptNetControls.addLeft(Switch.similarityMatchCheckBox); conceptNetControls.addLeft(Switch.useConceptNetCache); } return conceptNetControls; } public SwitchPanel getBadGrammarControls() { if (badGrammarControls == null) { badGrammarControls = new SwitchPanel(); badGrammarControls.addLeft(Switch.ECSlider1); badGrammarControls.addLeft(Switch.ECSlider2); badGrammarControls.addLeft(Switch.ECSlider3); badGrammarControls.addLeft(Switch.ECSlider4); badGrammarControls.addLeft(Switch.ECSlider5); badGrammarControls.addLeft(Switch.ECSlider6); badGrammarControls.addLeft(Switch.ECSlider7); } return badGrammarControls; } public JPanel getSubsystemsPanel() { if (subsystemsPanel == null) { subsystemsPanel = new BorderedParallelJPanel("Subsystems active"); subsystemsPanel.addLeft(getSummarizer().getGateKeeper()); subsystemsPanel.addLeft(getPersuader().getGateKeeper()); subsystemsPanel.addLeft(getEscalationExpert1().getGateKeeper()); subsystemsPanel.addLeft(getStoryRecallExpert1().getGateKeeper()); // subsystemsPanel.addLeft(getPredictionExpert1().getGateKeeper()); subsystemsPanel.addRight(getStatisticsExpert().getGateKeeper()); subsystemsPanel.addRight(getJessicasExpert().getGateKeeper()); // subsystemsPanel.addRight(getCarolinesExpert().getGateKeeper()); subsystemsPanel.addRight(getDylansExpert().getGateKeeper()); subsystemsPanel.addRight(Switch.storyAlignerCheckBox); subsystemsPanel.addRight(getRashiExperts().getGateKeeper()); // to add port Rashi // subsystemsPanel.addRight(Switch.uppCheckBox); // subsystemsPanel.addRight(getHumorExpert().getGateKeeper()); } return subsystemsPanel; } protected ButtonSwitchBox getSyntaxToSemanticsSwitchBox() { if (syntaxToSemanticsSwitchBox == null) { syntaxToSemanticsSwitchBox = new ButtonSwitchBox(Switch.useUnderstand); syntaxToSemanticsSwitchBox.setName("Switch"); } return syntaxToSemanticsSwitchBox; } public static JButton getNextButton() { if (nextButton == null) { nextButton = new JButton("Next"); nextButton.setName("Next button"); nextButton.setEnabled(false); } return nextButton; } public static JButton getRunButton() { if (runButton == null) { runButton = new JButton("Run"); runButton.setName("Run button"); runButton.setEnabled(false); } return runButton; } public static TabbedMentalModelViewer getMentalModelViewer() { if (mentalModelViewer == null) { mentalModelViewer = new TabbedMentalModelViewer(); mentalModelViewer.setBackground(Color.WHITE); mentalModelViewer.setOpaque(true); mentalModelViewer.setName("Mental Models"); setMinimumHeight(mentalModelViewer, 0); } return mentalModelViewer; } public JMatrixPanel getMainMatrix() { if (mainMatrix == null) { mainMatrix = new JMatrixPanel(); mainMatrix.setMinimumSize(new Dimension(460, 350)); mainMatrix.add(getActionButtons(), 0, 0, 20, 10); mainMatrix.add(getQuestionsPanel(), 20, 0, 10, 10); // mainMatrix.add(getModePanel(), 10, 0, 10, 6); // mainMatrix.add(getStorySummaryControls(), 10, 0, 10, 6); mainMatrix.add(getConnectionPanel(), 0, 10, 10, 10); // mainMatrix.add(getSubsystemsPanel(), 10, 10, 10, 10); // Do not all any subsystems mainMatrix.add(getPresentationPanel(), 20, 10, 10, 10); } return mainMatrix; } /** * All that is left here is for Fay's story generator, which is dormant * * @return */ // public JMatrixPanel getReadTellMatrix() { // if (readTellMatrix == null) { // readTellMatrix = new JMatrixPanel(); // // readTellMatrix.add(getStoryReadingControls(), 0, 0, 15, 6); // // readTellMatrix.add(getConsciousnessPanel(), 15, 0, 15, 6); // // // readTellMatrix.add(getSubsystemsPanel(), 30, 0, 10, 6); // // readTellMatrix.add(getSchizophreniaControls(), 40, 0, 10, 6); // // // readTellMatrix.add(getStorySummaryControls(), 0, 6, 20, 6); // // // // // readTellMatrix.add(getExplanationPanel(), 20, 6, 10, 4); // readTellMatrix.add(getModePanel(), 30, 6, 10, 4); // // readTellMatrix.add(getStoryTellingControls(), 40, 6, 10, 4); // // // readTellMatrix.add(getStoryPersuasionControls(), 20, 10, 30, 2); // // // readTellMatrix.add(getStorySummaryControls(), 30, 0, 10, 10); // // } // return readTellMatrix; // } public JMatrixPanel getMiscellaneousMatrix() { if (miscellaneousMatrix == null) { miscellaneousMatrix = new JMatrixPanel(); // miscellaneousMatrix.add(getElaborationOptionsPanel(), 0, 0, 3, 10); // ---------------------------------------------------------------------------------------- // added by Zhutian on 16 March 2019 for different modes of story aligner/ analogy making if(StoryAligner.showOptionsInControls) { miscellaneousMatrix.add(getMiscellaneousPanel(), 0, 0, 10, 5); miscellaneousMatrix.add(getAlignerControlPanel(), 0, 5, 10, 5); } else { miscellaneousMatrix.add(getMiscellaneousPanel(), 0, 0, 10, 10); } // miscellaneousMatrix.add(getMiscellaneousPanel(), 0, 0, 10, 10); // uncomment this if want to hide the options // ---------------------------------------------------------------------------------------- miscellaneousMatrix.add(getMatcherControlPanel(), 10, 0, 10, 5); miscellaneousMatrix.add(getSimulatorControlPanel(), 10, 5, 10, 5); miscellaneousMatrix.add(getVideoPanel(), 0, 10, 20, 5); // miscellaneousMatrix.add(getGraveyardPanel(), 0, 25, 10, 20); } return miscellaneousMatrix; } public JMatrixPanel getDebuggingMatrix() { if (debuggingMatrix == null) { debuggingMatrix = new JMatrixPanel(); debuggingMatrix.add(getDebuggingPanel(), 0, 0, 10, 5); debuggingMatrix.add(getCheckInPanel(), 0, 5, 2, 5); debuggingMatrix.add(getCo57Panel(), 5, 5, 5, 5); debuggingMatrix.add(getTestPanel(), 2, 5, 3, 5); } return debuggingMatrix; } public JMatrixPanel getGraveyardMatrix() { if (graveyardMatrix == null) { graveyardMatrix = new JMatrixPanel(); graveyardMatrix.add(getGraveyardPanel(), 0, 0, 10, 10); graveyardMatrix.add(getCorpsePanel(), 0, 10, 10, 10); } return graveyardMatrix; } public ParallelJPanel getCo57Panel() { if (co57Panel == null) { co57Panel = new BorderedParallelJPanel("Co57 communication"); ButtonGroup group = new ButtonGroup(); group.add(co57LocalPassthrough); group.add(co57Passthrough); co57Panel.addRight(co57LocalPassthrough); co57Panel.addRight(co57Passthrough); ButtonGroup group2 = new ButtonGroup(); group2.add(co57SimulatorAndTranslator); group2.add(co57JustTranslator); co57Panel.addRight(co57SimulatorAndTranslator); co57Panel.addRight(co57JustTranslator); } return co57Panel; } public ParallelJPanel getCheckInPanel() { if (checkInPanel == null) { checkInPanel = new BorderedParallelJPanel("Check in tests"); checkInPanel.addLeft(test1Button); checkInPanel.addLeft(test2Button); } return checkInPanel; } public ParallelJPanel getDebuggingPanel() { if (debuggingPanel == null) { debuggingPanel = new BorderedParallelJPanel("Miscellaneous"); debuggingPanel.setBackground(Color.WHITE); debuggingPanel.setOpaque(true); debuggingPanel.addLeft(Switch.showStartProcessingDetails); debuggingPanel.addLeft(Switch.countConceptNetWords); debuggingPanel.addCenter(Switch.showElaborationViewerDetails); debuggingPanel.addCenter(Switch.showTranslationDetails); // debuggingPanel.addCenter(Switch.useFestival); // mpfay 2013 debuggingPanel.addCenter(useNewMatcherCheckBox); debuggingPanel.addCenter(matchAllThreads); debuggingPanel.addCenter(reportMatchingDifferencesCheckBox); debuggingPanel.addRight(this.debugButton1); debuggingPanel.addRight(this.debugButton2); debuggingPanel.addRight(this.debugButton3); debuggingPanel.addRight(clearSummaryTableButton); debuggingPanel.addRight(simulateCo57Button); debuggingPanel.addRight(connectTestingBox); debuggingPanel.addRight(disconnectTestingBox); disconnectTestingBox.setEnabled(false); } return debuggingPanel; } public ParallelJPanel getVideoPanel() { if (videoPanel == null) { videoPanel = new BorderedParallelJPanel("Recording"); videoPanel.addLeft(makeSmallVideoRecordingButton); videoPanel.addLeft(makeLargeVideoRecordingButton); videoPanel.addLeft(makeMediumVideoRecordingButton); videoPanel.addLeft(makeCoUButton); } return videoPanel; } public BorderedParallelJPanel getPresentationPanel() { if (presentationPanel == null) { presentationPanel = new BorderedParallelJPanel("Presentation"); presentationPanel.addLeft(Switch.showTextEntryBox); presentationPanel.addLeft(Switch.showOnsetSwitch); presentationPanel.addLeft(Switch.showStatisticsBar); presentationPanel.addLeft(Switch.showDisconnectedSwitch); presentationPanel.addLeft(Switch.showCausationGraph); presentationPanel.addLeft(Switch.showCommonsenseCausationReasoning); presentationPanel.addLeft(Switch.slowMotionSwitch); presentationPanel.addLeft(Switch.stepThroughNextStory); presentationPanel.addLeft(Switch.useSpeechCheckBox); } return presentationPanel; } private JMatrixPanel mainMatrix; private JMatrixPanel readTellMatrix; private JMatrixPanel miscellaneousMatrix; private JMatrixPanel debuggingMatrix; private JMatrixPanel graveyardMatrix; private BorderedParallelJPanel presentationPanel; private BorderedParallelJPanel modePanel; private SwitchPanelWithExplanation explanationPanel; private BorderedParallelJPanel questionHandlerPanel; private BorderedParallelJPanel connectionPanel; private BorderedParallelJPanel testPanel; private BorderedParallelJPanel corpsePanel; // private BorderedParallelJPanel elaborationOptionsPanel; public BorderedParallelJPanel getModePanel() { if (modePanel == null) { modePanel = new BorderedParallelJPanel("Mode"); modePanel.addLeft(Radio.normalModeButton); modePanel.addLeft(Radio.tellStoryButton); modePanel.addLeft(Radio.calculateSimilarityButton); modePanel.addLeft(Radio.alignmentButton); } return modePanel; } public BorderedParallelJPanel getQuestionsPanel() { if (questionHandlerPanel == null) { questionHandlerPanel = new BorderedParallelJPanel("Question responder mode"); questionHandlerPanel.addCenter(Radio.qToLegacy); questionHandlerPanel.addCenter(Radio.qToPHW); questionHandlerPanel.addCenter(Radio.qToDXH); questionHandlerPanel.addCenter(Radio.qToJMN); questionHandlerPanel.addCenter(Radio.qToCA); questionHandlerPanel.addCenter(Radio.qToZTY); questionHandlerPanel.addCenter(Radio.qToZTY36); questionHandlerPanel.addCenter(Radio.qToZTYBTS); ButtonGroup group = new ButtonGroup(); group.add(Radio.qToLegacy); group.add(Radio.qToPHW); group.add(Radio.qToDXH); group.add(Radio.qToJMN); group.add(Radio.qToCA); group.add(Radio.qToZTY); group.add(Radio.qToZTY36); group.add(Radio.qToZTYBTS); } return questionHandlerPanel; } /* * public static final JRadioButton qToLegacy = new JRadioButton("Basic"); public static final JRadioButton qToPHW = * new JRadioButton("Self aware"); public static final JRadioButton qToJMN = new JRadioButton("Agent focused"); * public static final JRadioButton qToJMN = new JRadioButton("Development focused"); */ public JPanel getConnectionPanel() { if (connectionPanel == null) { connectionPanel = new BorderedParallelJPanel("Connections"); // connectionPanel.addLeft(NewTimer.startDirectTimer.getOnOffLabel()); // connectionPanel.addLeft(NewTimer.translationTimer.getOnOffLabel()); // connectionPanel.addLeft(NewTimer.generatorTimer.getOnOffLabel()); connectionPanel.addCenter(NewTimer.ruleProcessingTimer.getOnOffLabel()); connectionPanel.addCenter(NewTimer.conceptProcessingTimer.getOnOffLabel()); connectionPanel.addRight(NewTimer.startFailureTimer.getOnOffLabel()); connectionPanel.addRight(NewTimer.bundleGeneratorTimer.getOnOffLabel()); connectionPanel.addRight(Switch.useWordnetCache); connectionPanel.addRight(Switch.useStartCache); } return connectionPanel; } public JPanel getTestPanel() { if (testPanel == null) { testPanel = new BorderedParallelJPanel("Test"); testPanel.addLeft(NewTimer.startBetaTimer.getOnOffLabel()); testPanel.addLeft(NewTimer.generatorBetaTimer.getOnOffLabel()); testPanel.addLeft(Switch.useStartBeta); testPanel.addLeft(Switch.activateExperimentalParser); } return testPanel; } public JPanel getActionButtons() { if (actionButtons == null) { actionButtons = new BorderedParallelJPanel("Actions"); actionButtons.setBackground(Color.WHITE); actionButtons.setOpaque(true); actionButtons.addRight(this.rerunExperiment); actionButtons.addRight(this.rereadFile); actionButtons.addLeft(this.testSentencesButton); actionButtons.addLeft(this.testStoriesButton); actionButtons.addLeft(this.testOperationsButton); // actionButtons.addLeft(this.loopButton); actionButtons.addLeft(eraseTextButton); // actionButtons.addCenter(disambiguationButton); // actionButtons.addLeft(experienceButton); actionButtons.addRight(getNextButton()); actionButtons.addRight(getRunButton()); actionButtons.addLeft(startPurgeButton); actionButtons.addRight(wordnetPurgeButton); actionButtons.addLeft(this.demonstrateConnectionsButton); actionButtons.addRight(this.demonstrateConceptsButton); actionButtons.addLeft(conceptNetPurgeButton); actionButtons.addRight(runAligner); rereadFile.setEnabled(false); rerunExperiment.setEnabled(false); ButtonGroup group = new ButtonGroup(); group.add(Radio.normalModeButton); group.add(Radio.tellStoryButton); group.add(Radio.calculateSimilarityButton); group.add(Radio.alignmentButton); Radio.normalModeButton.setOpaque(false); Radio.tellStoryButton.setOpaque(false); Radio.calculateSimilarityButton.setOpaque(false); } return actionButtons; } public static final JRadioButton summarize = new RadioButtonWithDefaultValue("Summarize"); public BorderedParallelJPanel getCorpsePanel() { if (corpsePanel == null) { corpsePanel = new BorderedParallelJPanel("Obsoleted/Deprecated/Obscure/Rotted/Moribund---off by default"); corpsePanel.addLeft(Switch.disambiguatorSwitch); corpsePanel.addCenter(Switch.showBackgroundElements); corpsePanel.addLeft(memorySwitch); corpsePanel.addCenter(Switch.conceptSwitch); corpsePanel.addCenter(Switch.detectMultipleReflectionsSwitch); corpsePanel.addLeft(Switch.allowRepeatedCommands); } return corpsePanel; } // public JPanel getBehaviorOptionsPanel() { // if (behaviorOptionsPanel == null) { // behaviorOptionsPanel = new BorderedParallelJPanel("Behavior"); // // } // return behaviorOptionsPanel; // } // public BorderedParallelJPanel getElaborationOptionsPanel() { // if (elaborationOptionsPanel == null) { // elaborationOptionsPanel = new BorderedParallelJPanel("Elaboraton options"); // elaborationOptionsPanel.addLeft(Switch.showInferences); // elaborationOptionsPanel.addLeft(Switch.showWires); // // } // return elaborationOptionsPanel; // } public ParallelJPanel getGraveyardPanel() { if (graveyardPanel == null) { graveyardPanel = new BorderedParallelJPanel("Graveyard"); graveyardPanel.setBackground(Color.WHITE); graveyardPanel.setOpaque(true); deprecateLeft(Switch.workWithVision); deprecateLeft(Switch.useUnderstand); deprecateLeft(Switch.stepParser); deprecateCenter(debugVideoFileButton); deprecateCenter(demoSimulator); deprecateCenter(kjFileButton); deprecateCenter(kjeFileButton); deprecateRight(visionFileButton); deprecateRight(loadVideoPrecedents); deprecateRight(clearMemoryButton); deprecateRight(focusButton); } return graveyardPanel; } private void deprecateLeft(JComponent c) { getGraveyardPanel().addLeft(c); c.setEnabled(false); } private void deprecateCenter(JComponent c) { getGraveyardPanel().addCenter(c); c.setEnabled(false); } private void deprecateRight(JComponent c) { getGraveyardPanel().addRight(c); c.setEnabled(false); }; // These have to be here, instead of in GenesisGetters, because used in dsplay panels private Summarizer summarizer; private Persuader persuader; public Persuader getPersuader() { if (persuader == null) { persuader = Persuader.getPersuader(); } return persuader; } public Summarizer getSummarizer() { if (summarizer == null) { summarizer = Summarizer.getSummarizer(); } return summarizer; } // protected void setPreferredWidth(Component c, int w) { // int h = c.getPreferredSize().height; // c.setPreferredSize(new Dimension(w, h)); // } // // protected void setPreferredHeight(Component c, int h) { // int w = c.getPreferredSize().width; // c.setPreferredSize(new Dimension(w, h)); // } // // protected void setMinimumWidth(Component c, int w) { // int h = c.getMinimumSize().height; // c.setMinimumSize(new Dimension(w, h)); // } // // protected void setMinimumHeight(Component c, int h) { // int w = c.getMinimumSize().width; // c.setMinimumSize(new Dimension(w, h)); // } // Sample runtime switch // if (!Webstart.isWebStart()) public EscalationExpert getEscalationExpert1() { if (escalationExpert1 == null) { escalationExpert1 = new EscalationExpert(); escalationExpert1.setGateKeeper(Switch.escalationCheckBox); } return escalationExpert1; } public EscalationExpert getEscalationExpert2() { if (escalationExpert2 == null) { escalationExpert2 = new EscalationExpert(); escalationExpert2.setGateKeeper(Switch.escalationCheckBox); } return escalationExpert2; } public StoryRecallExpert getStoryRecallExpert1() { if (storyRecallExpert1 == null) { storyRecallExpert1 = new StoryRecallExpert(); storyRecallExpert1.setGateKeeper(Switch.storyRecallCheckBox); } return storyRecallExpert1; } public StoryRecallExpert getStoryRecallExpert2() { if (storyRecallExpert2 == null) { storyRecallExpert2 = new StoryRecallExpert(); storyRecallExpert2.setGateKeeper(Switch.storyRecallCheckBox); } return storyRecallExpert2; } // public PredictionExpert getPredictionExpert1() { // if (predictionExpert1 == null) { // predictionExpert1 = new PredictionExpert(); // predictionExpert1.setGateKeeper(Switch.predictionCheckBox); // } // return predictionExpert1; // } public StatisticsExpert getStatisticsExpert() { if (statisticsExpert == null) { statisticsExpert = new StatisticsExpert("Statistics", Switch.statisticsCheckBox); } return statisticsExpert; } public JessicasExpert getJessicasExpert() { if (jessicasExpert == null) { jessicasExpert = new JessicasExpert(); } return jessicasExpert; } /*public CarolinesExpert getCarolinesExpert() { if (carolinesExpert == null) { carolinesExpert = new CarolinesExpert(); } return carolinesExpert; }*/ // public PsychologicallyPlausibleModel getCarolinesExpert() { // if (carolinesExpert == null) { // carolinesExpert = new PsychologicallyPlausibleModel(); // } // return carolinesExpert; // } public MeansEndsProcessor getDylansExpert() { if (dylansExpert == null) { dylansExpert = new MeansEndsProcessor(); dylansExpert.setGateKeeper(Switch.meansToEndCheckBox); } return dylansExpert; } RecipeFinder recipeFinder = null; public RecipeFinder getRecipeFinder() { if (recipeFinder == null) { recipeFinder = new RecipeFinder("Recipe finder"); recipeFinder.setGateKeeper(Switch.storyAlignerCheckBox); } return recipeFinder; } // public HumorExpert getHumorExpert() { // if (humorExpert == null) { // humorExpert = new HumorExpert(); // } // return humorExpert; // } // RASHI 26 Jan 2019 RashisExperts rashiExperts; SummarizeIntentions summarizeIntentions; /* * Get an instance of LocalProcessor to do something with the output of a complete story object from a story * processor. */ public RashisExperts getRashiExperts() { if (rashiExperts == null) { rashiExperts = new RashisExperts(); } return rashiExperts; } /* * Get an instance of HighlightIntentions. HighlightIntentions analyzes a story about an author's decisions. */ public SummarizeIntentions getSummarizerOfIntentions() { if (summarizeIntentions == null) { summarizeIntentions = new SummarizeIntentions(); } return summarizeIntentions; } }
dollabs/rita-asi
Code/genesis-components/GenesisCore/source/genesis/GenesisControls.java
249,384
package com.example.mfusion.About; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.mfusion.R; public class AboutFragment extends Fragment { TextView Company,Function; Button more; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_about, container, false); Company = (TextView)rootView.findViewById(R.id.Company); Function= (TextView)rootView.findViewById(R.id.Function); more= (Button)rootView.findViewById(R.id.btnMore); more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Company.setText("Founded in 2001, M-Fusion develops proprietary digital signage software.\n" + "\n" + "Through the years, M-Fusion, went on to provide multimedia solutions on various digital medium. These solutions included kiosks, digital displaysand in-house tvs. Projects after projects we became domain experts in this field and streamlined some of our key solutions into digital signage products."); Function.setText("Our app can enable users to choose template, create Playback, assign a schedule, configure their own profiles..."); } }); return rootView; }//on click method for button more }
yangzifeiyu/AndroidPlayer
Src/About/AboutFragment.java
249,385
package domain; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import knowledge.KnowledgeSource; public abstract class Dependent { /** * Attribute collection of participating experts, thinkers, or general * consults. */ protected List<KnowledgeSource> references = new ArrayList<KnowledgeSource>(); /** * Public method to add a new knowledge source reference * * @param ref * the {@link knowledge.KnowledgeSource} reference * @return true if success */ public boolean addReference(KnowledgeSource ref) { return references.add(ref); } /** * Public method to return the number of knowledge source references * * @return integer number of references */ public int numberOfReferences() { return references.size(); } /** * Public method to remove a knowledge source reference * * @param ref * the {@link knowledge.KnowledgeSource} reference * @return true if success */ public boolean removeReference(KnowledgeSource ref) { return references.remove(ref); } public enum Direction { FORWARD, REVERSE } public void notify(Direction direction, Assumption statement) { ConcurrentLinkedQueue<Assumption> queue; Iterator<Assumption> iter; Assumption stmt; /** * Forward chaining Knowledge Sources */ if (direction == Direction.FORWARD) { for (KnowledgeSource knowledgeSource : references) { knowledgeSource.getPastAssumptions().add(statement); } } /** * Reverse chaining Knowledge Sources */ if (direction == Direction.REVERSE) { for (KnowledgeSource knowledgeSource : references) { queue = knowledgeSource.getPastAssumptions(); iter = queue.iterator(); while (iter.hasNext()) { stmt = (Assumption) iter.next(); if (stmt.equals(statement)) { iter.remove(); } } } } } }
adeboni/blackboard-cryptanalysis
src/domain/Dependent.java
249,386
/******************************************************************************* * Copyright (c) 2013, 2016 GK Software AG, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stephan Herrmann - initial API and implementation * IBM Corporation - Bug fixes *******************************************************************************/ package org.eclipse.jdt.internal.compiler.lookup; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FunctionalExpression; import org.eclipse.jdt.internal.compiler.ast.Invocation; import org.eclipse.jdt.internal.compiler.ast.LambdaExpression; import org.eclipse.jdt.internal.compiler.ast.ReferenceExpression; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.util.Sorting; /** * Main class for new type inference as per JLS8 sect 18. * Keeps contextual state and drives the algorithm. * * <h2>Inference Basics</h2> * <ul> * <li>18.1.1 Inference variables: {@link InferenceVariable}</li> * <li>18.1.2 Constraint Formulas: subclasses of {@link ConstraintFormula}</li> * <li>18.1.3 Bounds: {@link TypeBound}<br/> * Capture bounds are directly captured in {@link BoundSet#captures}, throws-bounds in {@link BoundSet#inThrows}.<br/> * Also: {@link BoundSet}: main state during inference.</li> * </ul> * Each instance of {@link InferenceContext18} manages instances of the above and coordinates the inference process. * <h3>Queries and utilities</h3> * <ul> * <li>{@link TypeBinding#isProperType(boolean)}: * used to exclude "types" that mention inference variables (18.1.1).</li> * <li>{@link TypeBinding#mentionsAny(TypeBinding[], int)}: * does the receiver type binding mention any of the given types?</li> * <li>{@link TypeBinding#substituteInferenceVariable(InferenceVariable, TypeBinding)}: * replace occurrences of an inference variable with a proper type.</li> * <li>{@link TypeBinding#collectInferenceVariables(Set)}: * collect all inference variables mentioned in the receiver type into the given set.</li> * <li>{@link TypeVariableBinding#getTypeBounds(InferenceVariable, InferenceSubstitution)}: * Compute the initial type bounds for one inference variable as per JLS8 sect 18.1.3.</li> * </ul> * <h2>Phases of Inference</h2> * <ul> * <li>18.2 <b>Reduction</b>: {@link #reduce()} with most work happening in implementations of * {@link ConstraintFormula#reduce(InferenceContext18)}: * <ul> * <li>18.2.1 Expression Compatibility Constraints: {@link ConstraintExpressionFormula#reduce(InferenceContext18)}.</li> * <li>18.2.2 Type Compatibility Constraints ff. {@link ConstraintTypeFormula#reduce(InferenceContext18)}.</li> * </ul></li> * <li>18.3 <b>Incorporation</b>: {@link BoundSet#incorporate(InferenceContext18)}; during inference new constraints * are accepted via {@link BoundSet#reduceOneConstraint(InferenceContext18, ConstraintFormula)} (combining 18.2 & 18.3)</li> * <li>18.4 <b>Resolution</b>: {@link #resolve(InferenceVariable[])}. * </ul> * Some of the above operations accumulate their results into {@link #currentBounds}, whereas * the last phase <em>returns</em> the resulting bound set while keeping the previous state in {@link #currentBounds}. * <h2>18.5. Uses of Inference</h2> * These are the main entries from the compiler into the inference engine: * <dl> * <dt>18.5.1 Invocation Applicability Inference</dt> * <dd>{@link #inferInvocationApplicability(MethodBinding, TypeBinding[], boolean)}. Prepare the initial state for * inference of a generic invocation - no target type used at this point. * Need to call {@link #solve(boolean)} with true afterwards to produce the intermediate result.<br/> * Called indirectly from {@link Scope#findMethod(ReferenceBinding, char[], TypeBinding[], InvocationSite, boolean)} et al * to select applicable methods into overload resolution.</dd> * <dt>18.5.2 Invocation Type Inference</dt> * <dd>{@link InferenceContext18#inferInvocationType(TypeBinding, InvocationSite, MethodBinding)}. After a * most specific method has been picked, and given a target type determine the final generic instantiation. * As long as a target type is still unavailable this phase keeps getting deferred.</br> * Different wrappers exist for the convenience of different callers.</dd> * <dt>18.5.3 Functional Interface Parameterization Inference</dt> * <dd>Controlled from {@link LambdaExpression#resolveType(BlockScope)}.</dd> * <dt>18.5.4 More Specific Method Inference</dt> * <dd><em>Not Yet Implemented</em></dd> * </dl> * For 18.5.1 and 18.5.2 high-level control is implemented in * {@link ParameterizedGenericMethodBinding#computeCompatibleMethod(MethodBinding, TypeBinding[], Scope, InvocationSite)}. * <h2>Inference Lifecycle</h2> * <li>Decision whether or not an invocation is a <b>variable-arity</b> invocation is made by first attempting * to solve 18.5.1 in mode {@link #CHECK_LOOSE}. Only if that fails, another attempt is made in mode {@link #CHECK_VARARG}. * Which of these two attempts was successful is stored in {@link #inferenceKind}. * This field must be consulted whenever arguments of an invocation should be further processed. * See also {@link #getParameter(TypeBinding[], int, boolean)} and its clients.</li> * </ul> */ public class InferenceContext18 { /** to conform with javac regarding https://bugs.openjdk.java.net/browse/JDK-8026527 */ static final boolean SIMULATE_BUG_JDK_8026527 = true; /** Temporary workaround until we know fully what to do with https://bugs.openjdk.java.net/browse/JDK-8054721 * It looks likely that we have a bug independent of this JLS bug in that we clear the capture bounds eagerly. */ // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=437444#c24 onwards static final boolean SHOULD_WORKAROUND_BUG_JDK_8054721 = true; /** * Detail flag to control the extent of {@link #SIMULATE_BUG_JDK_8026527}. * A setting of 'false' implements the advice from http://mail.openjdk.java.net/pipermail/lambda-spec-experts/2013-December/000447.html * i.e., raw types are not considered as compatible in constraints/bounds derived from invocation arguments, * but only for constraints derived from type variable bounds. */ static final boolean ARGUMENT_CONSTRAINTS_ARE_SOFT = false; // --- Main State of the Inference: --- /** the invocation being inferred (for 18.5.1 and 18.5.2) */ InvocationSite currentInvocation; /** arguments of #currentInvocation, if any */ Expression[] invocationArguments; /** The inference variables for which as solution is sought. */ InferenceVariable[] inferenceVariables; int nextVarId; /** Constraints that have not yet been reduced and incorporated. */ ConstraintFormula[] initialConstraints; // for final revalidation at a "macroscopic" level ConstraintExpressionFormula[] finalConstraints; /** The accumulated type bounds etc. */ BoundSet currentBounds; /** One of CHECK_STRICT, CHECK_LOOSE, or CHECK_VARARGS. */ int inferenceKind; /** Marks how much work has been done so far? Used to avoid performing any of these tasks more than once. */ public int stepCompleted = NOT_INFERRED; public static final int NOT_INFERRED = 0; /** Applicability Inference (18.5.1) has been completed. */ public static final int APPLICABILITY_INFERRED = 1; /** Invocation Type Inference (18.5.2) has been completed (for some target type). */ public static final int TYPE_INFERRED = 2; /** Signals whether any type compatibility makes use of unchecked conversion. */ public List<ConstraintFormula> constraintsWithUncheckedConversion; public boolean usesUncheckedConversion; public InferenceContext18 outerContext; Scope scope; LookupEnvironment environment; // java.lang.Object ReferenceBinding object; public BoundSet b2; // InferenceVariable interning: private InferenceVariable[] internedVariables; private InferenceVariable getInferenceVariable(TypeBinding typeParameter, int rank, InvocationSite site) { InferenceContext18 outermostContext = this.environment.currentInferenceContext; if (outermostContext == null) outermostContext = this; int i = 0; InferenceVariable[] interned = outermostContext.internedVariables; if (interned == null) { outermostContext.internedVariables = new InferenceVariable[10]; } else { int len = interned.length; for (i = 0; i < len; i++) { InferenceVariable var = interned[i]; if (var == null) break; if (//$IDENTITY-COMPARISON$ var.typeParameter == typeParameter && var.rank == rank && isSameSite(var.site, site)) return var; } if (i >= len) System.arraycopy(interned, 0, outermostContext.internedVariables = new InferenceVariable[len + 10], 0, len); } return outermostContext.internedVariables[i] = new InferenceVariable(typeParameter, rank, this.nextVarId++, site, this.environment, this.object); } boolean isSameSite(InvocationSite site1, InvocationSite site2) { if (site1 == site2) return true; if (site1 == null || site2 == null) return false; if (site1.sourceStart() == site2.sourceStart() && site1.sourceEnd() == site2.sourceEnd() && site1.toString().equals(site2.toString())) return true; return false; } public static final int CHECK_UNKNOWN = 0; public static final int CHECK_STRICT = 1; public static final int CHECK_LOOSE = 2; public static final int CHECK_VARARG = 3; static class SuspendedInferenceRecord { InvocationSite site; Expression[] invocationArguments; InferenceVariable[] inferenceVariables; int inferenceKind; boolean usesUncheckedConversion; SuspendedInferenceRecord(InvocationSite site, Expression[] invocationArguments, InferenceVariable[] inferenceVariables, int inferenceKind, boolean usesUncheckedConversion) { this.site = site; this.invocationArguments = invocationArguments; this.inferenceVariables = inferenceVariables; this.inferenceKind = inferenceKind; this.usesUncheckedConversion = usesUncheckedConversion; } } /** Construct an inference context for an invocation (method/constructor). */ public InferenceContext18(Scope scope, Expression[] arguments, InvocationSite site, InferenceContext18 outerContext) { this.scope = scope; this.environment = scope.environment(); this.object = scope.getJavaLangObject(); this.invocationArguments = arguments; this.currentInvocation = site; this.outerContext = outerContext; if (site instanceof Invocation) scope.compilationUnitScope().registerInferredInvocation((Invocation) site); } public InferenceContext18(Scope scope) { this.scope = scope; this.environment = scope.environment(); this.object = scope.getJavaLangObject(); } /** * JLS 18.1.3: Create initial bounds from a given set of type parameters declarations. * @return the set of inference variables created for the given typeParameters */ public InferenceVariable[] createInitialBoundSet(TypeVariableBinding[] typeParameters) { // if (this.currentBounds == null) { this.currentBounds = new BoundSet(); } if (typeParameters != null) { InferenceVariable[] newInferenceVariables = addInitialTypeVariableSubstitutions(typeParameters); this.currentBounds.addBoundsFromTypeParameters(this, typeParameters, newInferenceVariables); return newInferenceVariables; } return Binding.NO_INFERENCE_VARIABLES; } /** * Substitute any type variables mentioned in 'type' by the corresponding inference variable, if one exists. */ public TypeBinding substitute(TypeBinding type) { InferenceSubstitution inferenceSubstitution = new InferenceSubstitution(this); return inferenceSubstitution.substitute(inferenceSubstitution, type); } /** JLS 18.5.1: compute bounds from formal and actual parameters. */ public void createInitialConstraintsForParameters(TypeBinding[] parameters, boolean checkVararg, TypeBinding varArgsType, MethodBinding method) { if (this.invocationArguments == null) return; int len = checkVararg ? parameters.length - 1 : Math.min(parameters.length, this.invocationArguments.length); int maxConstraints = checkVararg ? this.invocationArguments.length : len; int numConstraints = 0; boolean ownConstraints; if (this.initialConstraints == null) { this.initialConstraints = new ConstraintFormula[maxConstraints]; ownConstraints = true; } else { numConstraints = this.initialConstraints.length; maxConstraints += numConstraints; System.arraycopy(this.initialConstraints, 0, this.initialConstraints = new ConstraintFormula[maxConstraints], 0, numConstraints); // these are lifted from a nested poly expression. ownConstraints = false; } for (int i = 0; i < len; i++) { TypeBinding thetaF = substitute(parameters[i]); if (this.invocationArguments[i].isPertinentToApplicability(parameters[i], method)) { this.initialConstraints[numConstraints++] = new ConstraintExpressionFormula(this.invocationArguments[i], thetaF, ReductionResult.COMPATIBLE, ARGUMENT_CONSTRAINTS_ARE_SOFT); } else if (!isTypeVariableOfCandidate(parameters[i], method)) { this.initialConstraints[numConstraints++] = new ConstraintExpressionFormula(this.invocationArguments[i], thetaF, ReductionResult.POTENTIALLY_COMPATIBLE); } // else we know it is potentially compatible, no need to assert. } if (checkVararg && varArgsType instanceof ArrayBinding) { varArgsType = ((ArrayBinding) varArgsType).elementsType(); TypeBinding thetaF = substitute(varArgsType); for (int i = len; i < this.invocationArguments.length; i++) { if (this.invocationArguments[i].isPertinentToApplicability(varArgsType, method)) { this.initialConstraints[numConstraints++] = new ConstraintExpressionFormula(this.invocationArguments[i], thetaF, ReductionResult.COMPATIBLE, ARGUMENT_CONSTRAINTS_ARE_SOFT); } else if (!isTypeVariableOfCandidate(varArgsType, method)) { this.initialConstraints[numConstraints++] = new ConstraintExpressionFormula(this.invocationArguments[i], thetaF, ReductionResult.POTENTIALLY_COMPATIBLE); } // else we know it is potentially compatible, no need to assert. } } if (numConstraints == 0) this.initialConstraints = ConstraintFormula.NO_CONSTRAINTS; else if (numConstraints < maxConstraints) System.arraycopy(this.initialConstraints, 0, this.initialConstraints = new ConstraintFormula[numConstraints], 0, numConstraints); if (// lifted constraints get validated at their own context. ownConstraints) { final int length = this.initialConstraints.length; System.arraycopy(this.initialConstraints, 0, this.finalConstraints = new ConstraintExpressionFormula[length], 0, length); } } private boolean isTypeVariableOfCandidate(TypeBinding type, MethodBinding candidate) { // cf. FunctionalExpression.isPertinentToApplicability() if (type instanceof TypeVariableBinding) { Binding declaringElement = ((TypeVariableBinding) type).declaringElement; if (declaringElement == candidate) return true; if (candidate.isConstructor() && declaringElement == candidate.declaringClass) return true; } return false; } private InferenceVariable[] addInitialTypeVariableSubstitutions(TypeBinding[] typeVariables) { int len = typeVariables.length; if (len == 0) { if (this.inferenceVariables == null) this.inferenceVariables = Binding.NO_INFERENCE_VARIABLES; return Binding.NO_INFERENCE_VARIABLES; } InferenceVariable[] newVariables = new InferenceVariable[len]; for (int i = 0; i < len; i++) newVariables[i] = getInferenceVariable(typeVariables[i], i, this.currentInvocation); if (this.inferenceVariables == null || this.inferenceVariables.length == 0) { this.inferenceVariables = newVariables; } else { // merge into this.inferenceVariables: int prev = this.inferenceVariables.length; System.arraycopy(this.inferenceVariables, 0, this.inferenceVariables = new InferenceVariable[len + prev], 0, prev); System.arraycopy(newVariables, 0, this.inferenceVariables, prev, len); } return newVariables; } /** Add new inference variables for the given type variables. */ public InferenceVariable[] addTypeVariableSubstitutions(TypeBinding[] typeVariables) { int len2 = typeVariables.length; InferenceVariable[] newVariables = new InferenceVariable[len2]; InferenceVariable[] toAdd = new InferenceVariable[len2]; int numToAdd = 0; for (int i = 0; i < typeVariables.length; i++) { if (typeVariables[i] instanceof InferenceVariable) // prevent double substitution of an already-substituted inferenceVariable newVariables[i] = (InferenceVariable) typeVariables[i]; else toAdd[numToAdd++] = newVariables[i] = getInferenceVariable(typeVariables[i], i, this.currentInvocation); } if (numToAdd > 0) { int start = 0; if (this.inferenceVariables != null) { int len1 = this.inferenceVariables.length; System.arraycopy(this.inferenceVariables, 0, this.inferenceVariables = new InferenceVariable[len1 + numToAdd], 0, len1); start = len1; } else { this.inferenceVariables = new InferenceVariable[numToAdd]; } System.arraycopy(toAdd, 0, this.inferenceVariables, start, numToAdd); } return newVariables; } /** JLS 18.1.3 Bounds: throws α: the inference variable α appears in a throws clause */ public void addThrowsContraints(TypeBinding[] parameters, InferenceVariable[] variables, ReferenceBinding[] thrownExceptions) { for (int i = 0; i < parameters.length; i++) { TypeBinding parameter = parameters[i]; for (int j = 0; j < thrownExceptions.length; j++) { if (TypeBinding.equalsEquals(parameter, thrownExceptions[j])) { this.currentBounds.inThrows.add(variables[i].prototype()); break; } } } } /** JLS 18.5.1 Invocation Applicability Inference. */ public void inferInvocationApplicability(MethodBinding method, TypeBinding[] arguments, boolean isDiamond) { ConstraintExpressionFormula.inferInvocationApplicability(this, method, arguments, isDiamond, this.inferenceKind); } /** JLS 18.5.2 Invocation Type Inference */ public BoundSet inferInvocationType(TypeBinding expectedType, InvocationSite invocationSite, MethodBinding method) throws InferenceFailureException { // not JLS: simply ensure that null hints from the return type have been seen even in standalone contexts: if (expectedType == null && method.returnType != null) // result is ignore, the only effect is on InferenceVariable.nullHints substitute(method.returnType); this.currentBounds = this.b2.copy(); try { // bullets 1&2: definitions only. if (expectedType != null && expectedType != TypeBinding.VOID && invocationSite instanceof Expression && ((Expression) invocationSite).isPolyExpression(method)) { // 3. bullet: special treatment for poly expressions if (!ConstraintExpressionFormula.inferPolyInvocationType(this, invocationSite, expectedType, method)) { return null; } } // 4. bullet: assemble C: Set<ConstraintFormula> c = new HashSet<ConstraintFormula>(); if (!addConstraintsToC(this.invocationArguments, c, method, this.inferenceKind, false, invocationSite)) return null; // not spec'd: BoundSet connectivityBoundSet = this.currentBounds.copy(); for (ConstraintFormula cf : c) connectivityBoundSet.reduceOneConstraint(this, cf); // 5. bullet: determine B4 from C List<Set<InferenceVariable>> components = connectivityBoundSet.computeConnectedComponents(this.inferenceVariables); while (!c.isEmpty()) { // * Set<ConstraintFormula> bottomSet = findBottomSet(c, allOutputVariables(c), components); if (bottomSet.isEmpty()) { bottomSet.add(pickFromCycle(c)); } // * c.removeAll(bottomSet); // * The union of the input variables of all the selected constraints, α1, ..., αm, ... Set<InferenceVariable> allInputs = new HashSet<InferenceVariable>(); Iterator<ConstraintFormula> bottomIt = bottomSet.iterator(); while (bottomIt.hasNext()) { allInputs.addAll(bottomIt.next().inputVariables(this)); } InferenceVariable[] variablesArray = allInputs.toArray(new InferenceVariable[allInputs.size()]); // ... is resolved if (!this.currentBounds.incorporate(this)) return null; BoundSet solution = resolve(variablesArray); // don't bother with finding the necessary superset, just resolve all: if (solution == null) solution = resolve(this.inferenceVariables); // * ~ apply substitutions to all constraints: bottomIt = bottomSet.iterator(); while (bottomIt.hasNext()) { ConstraintFormula constraint = bottomIt.next(); if (solution != null) if (!constraint.applySubstitution(solution, variablesArray)) return null; // * reduce and incorporate if (!this.currentBounds.reduceOneConstraint(this, constraint)) return null; } } // 6. bullet: solve BoundSet solution = solve(); if (solution == null || !isResolved(solution)) { // don't let bounds from unsuccessful attempt leak into subsequent attempts this.currentBounds = this.b2; return null; } // we're done, start reporting: reportUncheckedConversions(solution); // this is final, keep the result: return this.currentBounds = solution; } finally { this.stepCompleted = TYPE_INFERRED; } } private boolean addConstraintsToC(Expression[] exprs, Set<ConstraintFormula> c, MethodBinding method, int inferenceKindForMethod, boolean interleaved, InvocationSite site) throws InferenceFailureException { TypeBinding[] fs; if (exprs != null) { int k = exprs.length; int p = method.parameters.length; if (method.isVarargs()) { if (k < p - 1) return false; } else if (k != p) { return false; } switch(inferenceKindForMethod) { case CHECK_STRICT: case CHECK_LOOSE: fs = method.parameters; break; case CHECK_VARARG: fs = varArgTypes(method.parameters, k); break; default: throw new IllegalStateException("Unexpected checkKind " + //$NON-NLS-1$ this.inferenceKind); } for (int i = 0; i < k; i++) { TypeBinding fsi = fs[Math.min(i, p - 1)]; InferenceSubstitution inferenceSubstitution = new InferenceSubstitution(this.environment, this.inferenceVariables, site); TypeBinding substF = inferenceSubstitution.substitute(inferenceSubstitution, fsi); if (!addConstraintsToC_OneExpr(exprs[i], c, fsi, substF, method, interleaved)) return false; } } return true; } private boolean addConstraintsToC_OneExpr(Expression expri, Set<ConstraintFormula> c, TypeBinding fsi, TypeBinding substF, MethodBinding method, boolean interleaved) throws InferenceFailureException { // For all i (1 ≤ i ≤ k), if ei is not pertinent to applicability, the set contains ⟨ei → θ Fi⟩. if (!expri.isPertinentToApplicability(fsi, method)) { c.add(new ConstraintExpressionFormula(expri, substF, ReductionResult.COMPATIBLE, ARGUMENT_CONSTRAINTS_ARE_SOFT)); } if (expri instanceof FunctionalExpression) { c.add(new ConstraintExceptionFormula((FunctionalExpression) expri, substF)); if (expri instanceof LambdaExpression) { // https://bugs.openjdk.java.net/browse/JDK-8038747 LambdaExpression lambda = (LambdaExpression) expri; BlockScope skope = lambda.enclosingScope; if (// could be an inference variable. substF.isFunctionalInterface(skope)) { ReferenceBinding t = (ReferenceBinding) substF; ParameterizedTypeBinding withWildCards = InferenceContext18.parameterizedWithWildcard(t); if (withWildCards != null) { t = ConstraintExpressionFormula.findGroundTargetType(this, skope, lambda, withWildCards); } if (!t.isProperType(true) && t.isParameterizedType()) { // prevent already resolved inference variables from leaking into the lambda t = (ReferenceBinding) Scope.substitute(getResultSubstitution(this.currentBounds, false), t); } MethodBinding functionType; if (t != null && (functionType = t.getSingleAbstractMethod(skope, true)) != null && (lambda = lambda.resolveExpressionExpecting(t, this.scope, this)) != null) { TypeBinding r = functionType.returnType; Expression[] resultExpressions = lambda.resultExpressions(); for (int i = 0, length = resultExpressions == null ? 0 : resultExpressions.length; i < length; i++) { Expression resultExpression = resultExpressions[i]; if (!addConstraintsToC_OneExpr(resultExpression, c, r.original(), r, method, true)) return false; } } } } } else if (expri instanceof Invocation && expri.isPolyExpression()) { if (// https://bugs.openjdk.java.net/browse/JDK-8052325 substF.isProperType(true)) return true; Invocation invocation = (Invocation) expri; MethodBinding innerMethod = invocation.binding(); if (innerMethod == null) // -> proceed with no new C set elements. return true; Expression[] arguments = invocation.arguments(); TypeBinding[] argumentTypes = arguments == null ? Binding.NO_PARAMETERS : new TypeBinding[arguments.length]; for (int i = 0; i < argumentTypes.length; i++) argumentTypes[i] = arguments[i].resolvedType; InferenceContext18 innerContext = null; if (innerMethod instanceof ParameterizedGenericMethodBinding) innerContext = invocation.getInferenceContext((ParameterizedGenericMethodBinding) innerMethod); if (interleaved && innerContext != null) { MethodBinding shallowMethod = innerMethod.shallowOriginal(); innerContext.outerContext = this; if (// shouldn't happen, but let's play safe innerContext.stepCompleted < InferenceContext18.APPLICABILITY_INFERRED) innerContext.inferInvocationApplicability(shallowMethod, argumentTypes, shallowMethod.isConstructor()); if (!ConstraintExpressionFormula.inferPolyInvocationType(innerContext, invocation, substF, shallowMethod)) return false; return innerContext.addConstraintsToC(arguments, c, innerMethod.genericMethod(), innerContext.inferenceKind, interleaved, invocation); } else { int applicabilityKind = getInferenceKind(innerMethod, argumentTypes); return this.addConstraintsToC(arguments, c, innerMethod.genericMethod(), applicabilityKind, interleaved, invocation); } } else if (expri instanceof ConditionalExpression) { ConditionalExpression ce = (ConditionalExpression) expri; return addConstraintsToC_OneExpr(ce.valueIfTrue, c, fsi, substF, method, interleaved) && addConstraintsToC_OneExpr(ce.valueIfFalse, c, fsi, substF, method, interleaved); } return true; } protected int getInferenceKind(MethodBinding nonGenericMethod, TypeBinding[] argumentTypes) { switch(this.scope.parameterCompatibilityLevel(nonGenericMethod, argumentTypes)) { case Scope.AUTOBOX_COMPATIBLE: return CHECK_LOOSE; case Scope.VARARGS_COMPATIBLE: return CHECK_VARARG; default: return CHECK_STRICT; } } /** * 18.5.3 Functional Interface Parameterization Inference */ public ReferenceBinding inferFunctionalInterfaceParameterization(LambdaExpression lambda, BlockScope blockScope, ParameterizedTypeBinding targetTypeWithWildCards) { TypeBinding[] q = createBoundsForFunctionalInterfaceParameterizationInference(targetTypeWithWildCards); if (q == null || q.length != lambda.arguments().length) { // fail TODO: can this still happen here? } else { if (reduceWithEqualityConstraints(lambda.argumentTypes(), q)) { ReferenceBinding genericType = targetTypeWithWildCards.genericType(); // a is not-null by construction of parameterizedWithWildcard() TypeBinding[] a = targetTypeWithWildCards.arguments; TypeBinding[] aprime = getFunctionInterfaceArgumentSolutions(a); // TODO If F<A'1, ..., A'm> is a well-formed type, ... return blockScope.environment().createParameterizedType(genericType, aprime, targetTypeWithWildCards.enclosingType()); } } return targetTypeWithWildCards; } /** * Create initial bound set for 18.5.3 Functional Interface Parameterization Inference * @param functionalInterface the functional interface F<A1,..Am> * @return the parameter types Q1..Qk of the function type of the type F<α1, ..., αm>, or null */ TypeBinding[] createBoundsForFunctionalInterfaceParameterizationInference(ParameterizedTypeBinding functionalInterface) { if (this.currentBounds == null) this.currentBounds = new BoundSet(); TypeBinding[] a = functionalInterface.arguments; if (a == null) return null; InferenceVariable[] alpha = addInitialTypeVariableSubstitutions(a); for (int i = 0; i < a.length; i++) { TypeBound bound; if (a[i].kind() == Binding.WILDCARD_TYPE) { WildcardBinding wildcard = (WildcardBinding) a[i]; switch(wildcard.boundKind) { case Wildcard.EXTENDS: bound = new TypeBound(alpha[i], wildcard.allBounds(), ReductionResult.SUBTYPE); break; case Wildcard.SUPER: bound = new TypeBound(alpha[i], wildcard.bound, ReductionResult.SUPERTYPE); break; case Wildcard.UNBOUND: bound = new TypeBound(alpha[i], this.object, ReductionResult.SUBTYPE); break; default: // cannot continue; } } else { bound = new TypeBound(alpha[i], a[i], ReductionResult.SAME); } this.currentBounds.addBound(bound, this.environment); } TypeBinding falpha = substitute(functionalInterface); return falpha.getSingleAbstractMethod(this.scope, true).parameters; } public boolean reduceWithEqualityConstraints(TypeBinding[] p, TypeBinding[] q) { if (p != null) { for (int i = 0; i < p.length; i++) { try { if (!this.reduceAndIncorporate(ConstraintTypeFormula.create(p[i], q[i], ReductionResult.SAME))) return false; } catch (InferenceFailureException e) { return false; } } } return true; } /** * 18.5.4 More Specific Method Inference */ public boolean isMoreSpecificThan(MethodBinding m1, MethodBinding m2, boolean isVarArgs, boolean isVarArgs2) { // TODO: we don't yet distinguish vararg-with-passthrough from vararg-with-exactly-one-vararg-arg if (isVarArgs != isVarArgs2) { return isVarArgs2; } Expression[] arguments = this.invocationArguments; int numInvocArgs = arguments == null ? 0 : arguments.length; TypeVariableBinding[] p = m2.typeVariables(); TypeBinding[] s = m1.parameters; TypeBinding[] t = new TypeBinding[m2.parameters.length]; createInitialBoundSet(p); for (int i = 0; i < t.length; i++) t[i] = substitute(m2.parameters[i]); try { for (int i = 0; i < numInvocArgs; i++) { TypeBinding si = getParameter(s, i, isVarArgs); TypeBinding ti = getParameter(t, i, isVarArgs); Boolean result = moreSpecificMain(si, ti, this.invocationArguments[i]); if (result == Boolean.FALSE) return false; if (result == null) if (!reduceAndIncorporate(ConstraintTypeFormula.create(si, ti, ReductionResult.SUBTYPE))) return false; } if (t.length == numInvocArgs + 1) { TypeBinding skplus1 = getParameter(s, numInvocArgs, true); TypeBinding tkplus1 = getParameter(t, numInvocArgs, true); if (!reduceAndIncorporate(ConstraintTypeFormula.create(skplus1, tkplus1, ReductionResult.SUBTYPE))) return false; } return solve() != null; } catch (InferenceFailureException e) { return false; } } // FALSE: inference fails // TRUE: constraints have been incorporated // null: need to create the si <: ti constraint private Boolean moreSpecificMain(TypeBinding si, TypeBinding ti, Expression expri) throws InferenceFailureException { if (si.isProperType(true) && ti.isProperType(true)) { return expri.sIsMoreSpecific(si, ti, this.scope) ? Boolean.TRUE : Boolean.FALSE; } // "if Ti is not a functional interface type" specifically requests the si <: ti constraint created by our caller if (!ti.isFunctionalInterface(this.scope)) return null; TypeBinding funcI = ti.original(); // (we negate each condition for early exit): if (si.isFunctionalInterface(this.scope)) { // bullet 1 if (siSuperI(si, funcI) || siSubI(si, funcI)) // bullets 2 & 3 return null; if (si instanceof IntersectionTypeBinding18) { TypeBinding[] elements = ((IntersectionTypeBinding18) si).intersectingTypes; checkSuper: { for (int i = 0; i < elements.length; i++) if (!siSuperI(elements[i], funcI)) break checkSuper; // bullet 4 return null; // each element of the intersection is a superinterface of I, or a parameterization of a superinterface of I. } for (int i = 0; i < elements.length; i++) if (siSubI(elements[i], funcI)) // bullet 5 return null; // some element of the intersection is a subinterface of I, or a parameterization of a subinterface of I. } // all passed, time to do some work: TypeBinding siCapture = si.capture(this.scope, expri.sourceStart, expri.sourceEnd); // no wildcards should be left needing replacement MethodBinding sam = siCapture.getSingleAbstractMethod(this.scope, false); TypeBinding[] u = sam.parameters; TypeBinding r1 = sam.isConstructor() ? sam.declaringClass : sam.returnType; sam = // TODO ti.getSingleAbstractMethod(// TODO this.scope, // TODO true); TypeBinding[] v = sam.parameters; TypeBinding r2 = sam.isConstructor() ? sam.declaringClass : sam.returnType; return Boolean.valueOf(checkExpression(expri, u, r1, v, r2)); } return null; } private boolean checkExpression(Expression expri, TypeBinding[] u, TypeBinding r1, TypeBinding[] v, TypeBinding r2) throws InferenceFailureException { if (expri instanceof LambdaExpression && !((LambdaExpression) expri).argumentsTypeElided()) { for (int i = 0; i < u.length; i++) { if (!reduceAndIncorporate(ConstraintTypeFormula.create(u[i], v[i], ReductionResult.SAME))) return false; } if (r2.id == TypeIds.T_void) return true; LambdaExpression lambda = (LambdaExpression) expri; Expression[] results = lambda.resultExpressions(); if (results != Expression.NO_EXPRESSIONS) { if (r1.isFunctionalInterface(this.scope) && r2.isFunctionalInterface(this.scope) && !(r1.isCompatibleWith(r2) || r2.isCompatibleWith(r1))) { // (what does "applied .. to R1 and R2" mean? Why mention R1/R2 and not U/V?) for (int i = 0; i < results.length; i++) { if (!checkExpression(results[i], u, r1, v, r2)) return false; } return true; } checkPrimitive1: if (r1.isPrimitiveType() && !r2.isPrimitiveType()) { // check: each result expression is a standalone expression of a primitive type for (int i = 0; i < results.length; i++) { if (results[i].isPolyExpression() || (results[i].resolvedType != null && !results[i].resolvedType.isPrimitiveType())) break checkPrimitive1; } return true; } checkPrimitive2: if (r2.isPrimitiveType() && !r1.isPrimitiveType()) { for (int i = 0; i < results.length; i++) { // for all expressions (not for any expression not) if (!(// standalone of a referencetype (!results[i].isPolyExpression() && (results[i].resolvedType != null && !results[i].resolvedType.isPrimitiveType())) || // or a poly results[i].isPolyExpression())) break checkPrimitive2; } return true; } } return reduceAndIncorporate(ConstraintTypeFormula.create(r1, r2, ReductionResult.SUBTYPE)); } else if (expri instanceof ReferenceExpression && ((ReferenceExpression) expri).isExactMethodReference()) { ReferenceExpression reference = (ReferenceExpression) expri; for (int i = 0; i < u.length; i++) { if (!reduceAndIncorporate(ConstraintTypeFormula.create(u[i], v[i], ReductionResult.SAME))) return false; } if (r2.id == TypeIds.T_void) return true; MethodBinding method = reference.getExactMethod(); TypeBinding returnType = method.isConstructor() ? method.declaringClass : method.returnType; if (r1.isPrimitiveType() && !r2.isPrimitiveType() && returnType.isPrimitiveType()) return true; if (r2.isPrimitiveType() && !r1.isPrimitiveType() && !returnType.isPrimitiveType()) return true; return reduceAndIncorporate(ConstraintTypeFormula.create(r1, r2, ReductionResult.SUBTYPE)); } else if (expri instanceof ConditionalExpression) { ConditionalExpression cond = (ConditionalExpression) expri; return checkExpression(cond.valueIfTrue, u, r1, v, r2) && checkExpression(cond.valueIfFalse, u, r1, v, r2); } else { return false; } } private boolean siSuperI(TypeBinding si, TypeBinding funcI) { if (TypeBinding.equalsEquals(si, funcI) || TypeBinding.equalsEquals(si.original(), funcI)) return true; TypeBinding[] superIfcs = funcI.superInterfaces(); if (superIfcs == null) return false; for (int i = 0; i < superIfcs.length; i++) { if (siSuperI(si, superIfcs[i].original())) return true; } return false; } private boolean siSubI(TypeBinding si, TypeBinding funcI) { if (TypeBinding.equalsEquals(si, funcI) || TypeBinding.equalsEquals(si.original(), funcI)) return true; TypeBinding[] superIfcs = si.superInterfaces(); if (superIfcs == null) return false; for (int i = 0; i < superIfcs.length; i++) { if (siSubI(superIfcs[i], funcI)) return true; } return false; } // ========== Below this point: implementation of the generic algorithm: ========== /** * Try to solve the inference problem defined by constraints and bounds previously registered. * @return a bound set representing the solution, or null if inference failed * @throws InferenceFailureException a compile error has been detected during inference */ public /*@Nullable*/ BoundSet solve(boolean inferringApplicability) throws InferenceFailureException { if (!reduce()) return null; if (!this.currentBounds.incorporate(this)) return null; if (inferringApplicability) // Preserve the result after reduction, without effects of resolve() for later use in invocation type inference. this.b2 = this.currentBounds.copy(); BoundSet solution = resolve(this.inferenceVariables); /* If inferring applicability make a final pass over the initial constraints preserved as final constraints to make sure they hold true at a macroscopic level. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=426537#c55 onwards. */ if (inferringApplicability && solution != null && this.finalConstraints != null) { for (ConstraintExpressionFormula constraint : this.finalConstraints) { if (constraint.left.isPolyExpression()) // avoid redundant re-inference, inner poly's own constraints get validated in its own context & poly invocation type inference proved compatibility against target. continue; constraint.applySubstitution(solution, this.inferenceVariables); if (!this.currentBounds.reduceOneConstraint(this, constraint)) { return null; } } } return solution; } public /*@Nullable*/ BoundSet solve() throws InferenceFailureException { return solve(false); } public /*@Nullable*/ BoundSet solve(InferenceVariable[] toResolve) throws InferenceFailureException { if (!reduce()) return null; if (!this.currentBounds.incorporate(this)) return null; return resolve(toResolve); } /** * JLS 18.2. reduce all initial constraints * @throws InferenceFailureException */ private boolean reduce() throws InferenceFailureException { // Caution: This can be reentered recursively even as an earlier call is munching through the constraints ! for (int i = 0; this.initialConstraints != null && i < this.initialConstraints.length; i++) { final ConstraintFormula currentConstraint = this.initialConstraints[i]; if (currentConstraint == null) continue; this.initialConstraints[i] = null; if (!this.currentBounds.reduceOneConstraint(this, currentConstraint)) return false; } this.initialConstraints = null; return true; } /** * Have all inference variables been instantiated successfully? */ public boolean isResolved(BoundSet boundSet) { if (this.inferenceVariables != null) { for (int i = 0; i < this.inferenceVariables.length; i++) { if (!boundSet.isInstantiated(this.inferenceVariables[i])) return false; } } return true; } /** * Retrieve the resolved solutions for all given type variables. * @param typeParameters * @param boundSet where instantiations are to be found * @return array containing the substituted types or <code>null</code> elements for any type variable that could not be substituted. */ public TypeBinding[] getSolutions(TypeVariableBinding[] typeParameters, InvocationSite site, BoundSet boundSet) { int len = typeParameters.length; TypeBinding[] substitutions = new TypeBinding[len]; InferenceVariable[] outerVariables = null; if (this.outerContext != null && this.outerContext.stepCompleted < TYPE_INFERRED) outerVariables = this.outerContext.inferenceVariables; for (int i = 0; i < typeParameters.length; i++) { for (int j = 0; j < this.inferenceVariables.length; j++) { InferenceVariable variable = this.inferenceVariables[j]; if (isSameSite(variable.site, site) && TypeBinding.equalsEquals(variable.typeParameter, typeParameters[i])) { TypeBinding outerVar = null; if (outerVariables != null && (outerVar = boundSet.getEquivalentOuterVariable(variable, outerVariables)) != null) substitutions[i] = outerVar; else substitutions[i] = boundSet.getInstantiation(variable, this.environment); break; } } if (substitutions[i] == null) return null; } return substitutions; } /** When inference produces a new constraint, reduce it to a suitable type bound and add the latter to the bound set. */ public boolean reduceAndIncorporate(ConstraintFormula constraint) throws InferenceFailureException { // TODO(SH): should we immediately call a diat incorporate, or can we simply wait for the next round? return this.currentBounds.reduceOneConstraint(this, constraint); } /** * <b>JLS 18.4</b> Resolution * @return answer null if some constraint resolved to FALSE, otherwise the boundset representing the solution * @throws InferenceFailureException */ private /*@Nullable*/ BoundSet resolve(InferenceVariable[] toResolve) throws InferenceFailureException { this.captureId = 0; // NOTE: 18.5.2 ... // "(While it was necessary to demonstrate that the inference variables in B1 could be resolved // in order to establish applicability, the resulting instantiations are not considered part of B1.) // For this reason, resolve works on a temporary bound set, copied before any modification. BoundSet tmpBoundSet = this.currentBounds; if (this.inferenceVariables != null) { // find a minimal set of dependent variables: Set<InferenceVariable> variableSet; while ((variableSet = getSmallestVariableSet(tmpBoundSet, toResolve)) != null) { int oldNumUninstantiated = tmpBoundSet.numUninstantiatedVariables(this.inferenceVariables); final int numVars = variableSet.size(); if (numVars > 0) { final InferenceVariable[] variables = variableSet.toArray(new InferenceVariable[numVars]); variables: if (!tmpBoundSet.hasCaptureBound(variableSet)) { // try to instantiate this set of variables in a fresh copy of the bound set: BoundSet prevBoundSet = tmpBoundSet; tmpBoundSet = tmpBoundSet.copy(); for (int j = 0; j < variables.length; j++) { InferenceVariable variable = variables[j]; // try lower bounds: TypeBinding[] lowerBounds = tmpBoundSet.lowerBounds(/*onlyProper*/ variable, true); if (lowerBounds != Binding.NO_TYPES) { TypeBinding lub = this.scope.lowerUpperBound(lowerBounds); if (lub == TypeBinding.VOID || lub == null) return null; tmpBoundSet.addBound(new TypeBound(variable, lub, ReductionResult.SAME), this.environment); } else { TypeBinding[] upperBounds = tmpBoundSet.upperBounds(/*onlyProper*/ variable, true); // check exception bounds: if (tmpBoundSet.inThrows.contains(variable.prototype()) && tmpBoundSet.hasOnlyTrivialExceptionBounds(variable, upperBounds)) { TypeBinding runtimeException = this.scope.getType(TypeConstants.JAVA_LANG_RUNTIMEEXCEPTION, 3); tmpBoundSet.addBound(new TypeBound(variable, runtimeException, ReductionResult.SAME), this.environment); } else { // try upper bounds: TypeBinding glb = this.object; if (upperBounds != Binding.NO_TYPES) { if (upperBounds.length == 1) { glb = upperBounds[0]; } else { ReferenceBinding[] glbs = Scope.greaterLowerBound((ReferenceBinding[]) upperBounds); if (glbs == null) { throw new //$NON-NLS-1$ UnsupportedOperationException(//$NON-NLS-1$ "no glb for " + Arrays.asList(upperBounds)); } else if (glbs.length == 1) { glb = glbs[0]; } else { IntersectionTypeBinding18 intersection = (IntersectionTypeBinding18) this.environment.createIntersectionType18(glbs); if (!ReferenceBinding.isConsistentIntersection(intersection.intersectingTypes)) { // clean up tmpBoundSet = prevBoundSet; // and start over break variables; } glb = intersection; } } } tmpBoundSet.addBound(new TypeBound(variable, glb, ReductionResult.SAME), this.environment); } } } if (tmpBoundSet.incorporate(this)) continue; // clean-up for second attempt tmpBoundSet = prevBoundSet; } // Otherwise, a second attempt is made... // ensure stability of capture IDs Sorting.sortInferenceVariables(variables); final CaptureBinding18[] zs = new CaptureBinding18[numVars]; for (int j = 0; j < numVars; j++) zs[j] = freshCapture(variables[j]); final BoundSet kurrentBoundSet = tmpBoundSet; Substitution theta = new Substitution() { public LookupEnvironment environment() { return InferenceContext18.this.environment; } public boolean isRawSubstitution() { return false; } public TypeBinding substitute(TypeVariableBinding typeVariable) { for (int j = 0; j < numVars; j++) if (TypeBinding.equalsEquals(variables[j], typeVariable)) return zs[j]; /* If we have an instantiation, lower it to the instantiation. We don't want downstream abstractions to be confused about multiple versions of bounds without and with instantiations propagated by incorporation. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=430686. There is no value whatsoever in continuing to speak in two tongues. Also fixes https://bugs.eclipse.org/bugs/show_bug.cgi?id=425031. */ if (typeVariable instanceof InferenceVariable) { InferenceVariable inferenceVariable = (InferenceVariable) typeVariable; TypeBinding instantiation = kurrentBoundSet.getInstantiation(inferenceVariable, null); if (instantiation != null) return instantiation; } return typeVariable; } }; for (int j = 0; j < numVars; j++) { InferenceVariable variable = variables[j]; CaptureBinding18 zsj = zs[j]; // add lower bounds: TypeBinding[] lowerBounds = tmpBoundSet.lowerBounds(/*onlyProper*/ variable, true); if (lowerBounds != Binding.NO_TYPES) { TypeBinding lub = this.scope.lowerUpperBound(lowerBounds); if (lub != TypeBinding.VOID && lub != null) zsj.lowerBound = lub; } // add upper bounds: TypeBinding[] upperBounds = tmpBoundSet.upperBounds(/*onlyProper*/ variable, false); if (upperBounds != Binding.NO_TYPES) { for (int k = 0; k < upperBounds.length; k++) upperBounds[k] = Scope.substitute(theta, upperBounds[k]); if (!setUpperBounds(zsj, upperBounds)) // at violation of well-formedness skip this candidate and proceed continue; } if (tmpBoundSet == this.currentBounds) tmpBoundSet = tmpBoundSet.copy(); Iterator<ParameterizedTypeBinding> captureKeys = tmpBoundSet.captures.keySet().iterator(); Set<ParameterizedTypeBinding> toRemove = new HashSet<ParameterizedTypeBinding>(); while (captureKeys.hasNext()) { ParameterizedTypeBinding key = captureKeys.next(); int len = key.arguments.length; for (int i = 0; i < len; i++) { if (TypeBinding.equalsEquals(key.arguments[i], variable)) { toRemove.add(key); break; } } } captureKeys = toRemove.iterator(); while (captureKeys.hasNext()) tmpBoundSet.captures.remove(captureKeys.next()); tmpBoundSet.addBound(new TypeBound(variable, zsj, ReductionResult.SAME), this.environment); } if (tmpBoundSet.incorporate(this)) { if (tmpBoundSet.numUninstantiatedVariables(this.inferenceVariables) == oldNumUninstantiated) // abort because we made no progress return null; continue; } return null; } } } return tmpBoundSet; } int captureId = 0; /** For 18.4: "Let Z1, ..., Zn be fresh type variables" use capture bindings. */ private CaptureBinding18 freshCapture(InferenceVariable variable) { int id = this.captureId++; //$NON-NLS-1$ char[] sourceName = CharOperation.concat("Z".toCharArray(), '#', String.valueOf(id).toCharArray(), '-', variable.sourceName); int start = this.currentInvocation != null ? this.currentInvocation.sourceStart() : 0; int end = this.currentInvocation != null ? this.currentInvocation.sourceEnd() : 0; return new CaptureBinding18(this.scope.enclosingSourceType(), sourceName, variable.typeParameter.shortReadableName(), start, end, id, this.environment); } // === === private boolean setUpperBounds(CaptureBinding18 typeVariable, TypeBinding[] substitutedUpperBounds) { // 18.4: ... define the upper bound of Zi as glb(L1θ, ..., Lkθ) if (substitutedUpperBounds.length == 1) { // shortcut return typeVariable.setUpperBounds(substitutedUpperBounds, this.object); } else { TypeBinding[] glbs = Scope.greaterLowerBound(substitutedUpperBounds, this.scope, this.environment); if (glbs == null) return false; if (typeVariable.lowerBound != null) { for (int i = 0; i < glbs.length; i++) { if (!typeVariable.lowerBound.isCompatibleWith(glbs[i])) // not well-formed return false; } } // for deterministic results sort this array by id: sortTypes(glbs); if (!typeVariable.setUpperBounds(glbs, this.object)) return false; } return true; } static void sortTypes(TypeBinding[] types) { Arrays.sort(types, new Comparator<TypeBinding>() { public int compare(TypeBinding o1, TypeBinding o2) { int i1 = o1.id, i2 = o2.id; return (i1 < i2 ? -1 : (i1 == i2 ? 0 : 1)); } }); } /** * Find the smallest set of uninstantiated inference variables not depending * on any uninstantiated variable outside the set. */ private Set<InferenceVariable> getSmallestVariableSet(BoundSet bounds, InferenceVariable[] subSet) { // "Given a set of inference variables to resolve, let V be the union of this set and // all variables upon which the resolution of at least one variable in this set depends." Set<InferenceVariable> v = new HashSet<InferenceVariable>(); // compute only once, store for the final loop over 'v'. Map<InferenceVariable, Set<InferenceVariable>> dependencies = new HashMap(); for (InferenceVariable iv : subSet) { Set<InferenceVariable> tmp = new HashSet(); addDependencies(bounds, tmp, iv); dependencies.put(iv, tmp); v.addAll(tmp); } // "If every variable in V has an instantiation, then resolution succeeds and this procedure terminates." // -> (implicit if result remains unassigned) // "Otherwise, let { α1, ..., αn } be a non-empty subset of uninstantiated variables in V such that ... int min = Integer.MAX_VALUE; Set<InferenceVariable> result = null; // "i) for all i (1 ≤ i ≤ n), ..." for (InferenceVariable currentVariable : v) { if (!bounds.isInstantiated(currentVariable)) { // "... if αi depends on the resolution of a variable β, then either β has an instantiation or there is some j such that β = αj; ..." Set<InferenceVariable> set = dependencies.get(currentVariable); if (// not an element of the original subSet, still need to fetch this var's dependencies set == null) addDependencies(bounds, set = new HashSet(), currentVariable); // "... and ii) there exists no non-empty proper subset of { α1, ..., αn } with this property." int cur = set.size(); if (cur == 1) // won't get smaller return set; if (cur < min) { result = set; min = cur; } } } return result; } private void addDependencies(BoundSet boundSet, Set<InferenceVariable> variableSet, InferenceVariable currentVariable) { // not added if (boundSet.isInstantiated(currentVariable)) return; // already present if (!variableSet.add(currentVariable)) return; for (int j = 0; j < this.inferenceVariables.length; j++) { InferenceVariable nextVariable = this.inferenceVariables[j]; if (TypeBinding.equalsEquals(nextVariable, currentVariable)) continue; if (boundSet.dependsOnResolutionOf(currentVariable, nextVariable)) addDependencies(boundSet, variableSet, nextVariable); } } private ConstraintFormula pickFromCycle(Set<ConstraintFormula> c) { // Detail from 18.5.2 bullet 6.1 // Note on performance: this implementation could quite possibly be optimized a lot. // However, we only *very rarely* reach here, // so nobody should really be affected by the performance penalty paid here. // Note on spec conformance: the spec seems to require _all_ criteria (i)-(iv) to be fulfilled // with the sole exception of (iii), which should only be used, if _any_ constraints matching (i) & (ii) // also fulfill this condition. // Experiments, however, show that strict application of the above is prone to failing to pick any constraint, // causing non-termination of the algorithm. // Since that is not acceptable, I'm *interpreting* the spec to request a search for a constraint // that "best matches" the given conditions. // collect all constraints participating in a cycle HashMap<ConstraintFormula, Set<ConstraintFormula>> dependencies = new HashMap<ConstraintFormula, Set<ConstraintFormula>>(); Set<ConstraintFormula> cycles = new HashSet<ConstraintFormula>(); for (ConstraintFormula constraint : c) { Collection<InferenceVariable> infVars = constraint.inputVariables(this); for (ConstraintFormula other : c) { if (other == constraint) continue; if (dependsOn(infVars, other.outputVariables(this))) { // found a dependency, record it: Set<ConstraintFormula> targetSet = dependencies.get(constraint); if (targetSet == null) dependencies.put(constraint, targetSet = new HashSet<ConstraintFormula>()); targetSet.add(other); // look for a cycle: Set<ConstraintFormula> nodesInCycle = new HashSet<ConstraintFormula>(); if (isReachable(dependencies, other, constraint, new HashSet<ConstraintFormula>(), nodesInCycle)) { // found a cycle, record the involved nodes: cycles.addAll(nodesInCycle); } } } } Set<ConstraintFormula> outside = new HashSet<ConstraintFormula>(c); outside.removeAll(cycles); Set<ConstraintFormula> candidatesII = new HashSet<ConstraintFormula>(); // (i): participates in a cycle: candidates: for (ConstraintFormula candidate : cycles) { Collection<InferenceVariable> infVars = candidate.inputVariables(this); // (ii) does not depend on any constraints outside the cycle for (ConstraintFormula out : outside) { if (dependsOn(infVars, out.outputVariables(this))) continue candidates; } candidatesII.add(candidate); } if (candidatesII.isEmpty()) // not spec'ed but needed to avoid returning null below, witness: java.util.stream.Collectors candidatesII = c; // tentatively: (iii) has the form ⟨Expression → T⟩ Set<ConstraintFormula> candidatesIII = new HashSet<ConstraintFormula>(); for (ConstraintFormula candidate : candidatesII) { if (candidate instanceof ConstraintExpressionFormula) candidatesIII.add(candidate); } if (candidatesIII.isEmpty()) { // no constraint fulfills (iii) -> ignore this condition candidatesIII = candidatesII; } else // candidatesIII contains all relevant constraints ⟨Expression → T⟩ { // (iv) contains an expression that appears to the left of the expression // of every other constraint satisfying the previous three requirements // collect containment info regarding all expressions in candidate constraints: // (a) find minimal enclosing expressions: Map<ConstraintExpressionFormula, ConstraintExpressionFormula> expressionContainedBy = new HashMap<ConstraintExpressionFormula, ConstraintExpressionFormula>(); for (ConstraintFormula one : candidatesIII) { ConstraintExpressionFormula oneCEF = (ConstraintExpressionFormula) one; Expression exprOne = oneCEF.left; for (ConstraintFormula two : candidatesIII) { if (one == two) continue; ConstraintExpressionFormula twoCEF = (ConstraintExpressionFormula) two; Expression exprTwo = twoCEF.left; if (doesExpressionContain(exprOne, exprTwo)) { ConstraintExpressionFormula previous = expressionContainedBy.get(two); if (previous == null || doesExpressionContain(// only if improving previous.left, // only if improving exprOne)) expressionContainedBy.put(twoCEF, oneCEF); } } } // (b) build the tree from the above Map<ConstraintExpressionFormula, Set<ConstraintExpressionFormula>> containmentForest = new HashMap<ConstraintExpressionFormula, Set<ConstraintExpressionFormula>>(); for (Map.Entry<ConstraintExpressionFormula, ConstraintExpressionFormula> parentRelation : expressionContainedBy.entrySet()) { ConstraintExpressionFormula parent = parentRelation.getValue(); Set<ConstraintExpressionFormula> children = containmentForest.get(parent); if (children == null) containmentForest.put(parent, children = new HashSet<ConstraintExpressionFormula>()); children.add(parentRelation.getKey()); } // approximate the spec by searching the largest containment tree: int bestRank = -1; ConstraintExpressionFormula candidate = null; for (ConstraintExpressionFormula parent : containmentForest.keySet()) { int rank = rankNode(parent, expressionContainedBy, containmentForest); if (rank > bestRank) { bestRank = rank; candidate = parent; } } if (candidate != null) return candidate; } if (candidatesIII.isEmpty()) //$NON-NLS-1$ throw new IllegalStateException("cannot pick constraint from cyclic set"); return candidatesIII.iterator().next(); } /** * Does the first constraint depend on the other? * The first constraint is represented by its input variables and the other constraint by its output variables. */ private boolean dependsOn(Collection<InferenceVariable> inputsOfFirst, Collection<InferenceVariable> outputsOfOther) { for (InferenceVariable iv : inputsOfFirst) { for (InferenceVariable otherIV : outputsOfOther) if (this.currentBounds.dependsOnResolutionOf(iv, otherIV)) return true; } return false; } /** Does 'deps' contain a chain of dependencies leading from 'from' to 'to'? */ private boolean isReachable(Map<ConstraintFormula, Set<ConstraintFormula>> deps, ConstraintFormula from, ConstraintFormula to, Set<ConstraintFormula> nodesVisited, Set<ConstraintFormula> nodesInCycle) { if (from == to) { nodesInCycle.add(from); return true; } if (!nodesVisited.add(from)) return false; Set<ConstraintFormula> targetSet = deps.get(from); if (targetSet != null) { for (ConstraintFormula tgt : targetSet) { if (isReachable(deps, tgt, to, nodesVisited, nodesInCycle)) { nodesInCycle.add(from); return true; } } } return false; } /** Does exprOne lexically contain exprTwo? */ private boolean doesExpressionContain(Expression exprOne, Expression exprTwo) { if (exprTwo.sourceStart > exprOne.sourceStart) { return exprTwo.sourceEnd <= exprOne.sourceEnd; } else if (exprTwo.sourceStart == exprOne.sourceStart) { return exprTwo.sourceEnd < exprOne.sourceEnd; } return false; } /** non-roots answer -1, roots answer the size of the spanned tree */ private int rankNode(ConstraintExpressionFormula parent, Map<ConstraintExpressionFormula, ConstraintExpressionFormula> expressionContainedBy, Map<ConstraintExpressionFormula, Set<ConstraintExpressionFormula>> containmentForest) { if (expressionContainedBy.get(parent) != null) // not a root return -1; Set<ConstraintExpressionFormula> children = containmentForest.get(parent); if (children == null) // unconnected node or leaf return 1; int sum = 1; for (ConstraintExpressionFormula child : children) { int cRank = rankNode(child, expressionContainedBy, containmentForest); if (cRank > 0) sum += cRank; } return sum; } private Set<ConstraintFormula> findBottomSet(Set<ConstraintFormula> constraints, Set<InferenceVariable> allOutputVariables, List<Set<InferenceVariable>> components) { // 18.5.2 bullet 5.(1) // A subset of constraints is selected, satisfying the property that, // for each constraint, no input variable can influence an output variable of another constraint in C. ... // An inference variable α can influence an inference variable β if α depends on the resolution of β (§18.4), or vice versa; // or if there exists a third inference variable γ such that α can influence γ and γ can influence β. ... Set<ConstraintFormula> result = new HashSet<ConstraintFormula>(); constraintLoop: for (ConstraintFormula constraint : constraints) { for (InferenceVariable in : constraint.inputVariables(this)) { if (canInfluenceAnyOf(in, allOutputVariables, components)) continue constraintLoop; } result.add(constraint); } return result; } private boolean canInfluenceAnyOf(InferenceVariable in, Set<InferenceVariable> allOuts, List<Set<InferenceVariable>> components) { // can influence == lives in the same component for (Set<InferenceVariable> component : components) { if (component.contains(in)) { for (InferenceVariable out : allOuts) if (component.contains(out)) return true; return false; } } return false; } Set<InferenceVariable> allOutputVariables(Set<ConstraintFormula> constraints) { Set<InferenceVariable> result = new HashSet<InferenceVariable>(); Iterator<ConstraintFormula> it = constraints.iterator(); while (it.hasNext()) { result.addAll(it.next().outputVariables(this)); } return result; } private TypeBinding[] varArgTypes(TypeBinding[] parameters, int k) { TypeBinding[] types = new TypeBinding[k]; int declaredLength = parameters.length - 1; System.arraycopy(parameters, 0, types, 0, declaredLength); TypeBinding last = ((ArrayBinding) parameters[declaredLength]).elementsType(); for (int i = declaredLength; i < k; i++) types[i] = last; return types; } public SuspendedInferenceRecord enterPolyInvocation(InvocationSite invocation, Expression[] innerArguments) { SuspendedInferenceRecord record = new SuspendedInferenceRecord(this.currentInvocation, this.invocationArguments, this.inferenceVariables, this.inferenceKind, this.usesUncheckedConversion); this.inferenceVariables = null; this.invocationArguments = innerArguments; this.currentInvocation = invocation; this.usesUncheckedConversion = false; return record; } public SuspendedInferenceRecord enterLambda(LambdaExpression lambda) { SuspendedInferenceRecord record = new SuspendedInferenceRecord(this.currentInvocation, this.invocationArguments, this.inferenceVariables, this.inferenceKind, this.usesUncheckedConversion); this.inferenceVariables = null; this.invocationArguments = null; this.currentInvocation = null; this.usesUncheckedConversion = false; return record; } public void integrateInnerInferenceB2(InferenceContext18 innerCtx) { this.currentBounds.addBounds(innerCtx.b2, this.environment); this.inferenceVariables = innerCtx.inferenceVariables; this.inferenceKind = innerCtx.inferenceKind; innerCtx.outerContext = this; this.usesUncheckedConversion = innerCtx.usesUncheckedConversion; for (InferenceVariable variable : this.inferenceVariables) variable.updateSourceName(this.nextVarId++); } public void resumeSuspendedInference(SuspendedInferenceRecord record) { // merge inference variables: if (// no new ones, assume we aborted prematurely this.inferenceVariables == null) { this.inferenceVariables = record.inferenceVariables; } else { int l1 = this.inferenceVariables.length; int l2 = record.inferenceVariables.length; // move to back, add previous to front: System.arraycopy(this.inferenceVariables, 0, this.inferenceVariables = new InferenceVariable[l1 + l2], l2, l1); System.arraycopy(record.inferenceVariables, 0, this.inferenceVariables, 0, l2); } // replace invocation site & arguments: this.currentInvocation = record.site; this.invocationArguments = record.invocationArguments; this.inferenceKind = record.inferenceKind; this.usesUncheckedConversion = record.usesUncheckedConversion; } private Substitution getResultSubstitution(final BoundSet result, final boolean full) { return new Substitution() { public LookupEnvironment environment() { return InferenceContext18.this.environment; } public boolean isRawSubstitution() { return false; } public TypeBinding substitute(TypeVariableBinding typeVariable) { if (typeVariable instanceof InferenceVariable) { TypeBinding instantiation = result.getInstantiation((InferenceVariable) typeVariable, InferenceContext18.this.environment); if (instantiation != null || full) return instantiation; } return typeVariable; } }; } public boolean isVarArgs() { return this.inferenceKind == CHECK_VARARG; } /** * Retrieve the rank'th parameter, possibly respecting varargs invocation, see 15.12.2.4. * Returns null if out of bounds and CHECK_VARARG was not requested. * Precondition: isVarArgs implies method.isVarargs() */ public static TypeBinding getParameter(TypeBinding[] parameters, int rank, boolean isVarArgs) { if (isVarArgs) { if (rank >= parameters.length - 1) return ((ArrayBinding) parameters[parameters.length - 1]).elementsType(); } else if (rank >= parameters.length) { return null; } return parameters[rank]; } /** * Create a problem method signaling failure of invocation type inference, * unless the given candidate is tolerable to be compatible with buggy javac. */ public MethodBinding getReturnProblemMethodIfNeeded(TypeBinding expectedType, MethodBinding method) { if (InferenceContext18.SIMULATE_BUG_JDK_8026527 && expectedType != null && method.returnType instanceof ReferenceBinding) { if (method.returnType.erasure().isCompatibleWith(expectedType)) // don't count as problem. return method; } /* We used to check if expected type is null and if so return method, but that is wrong - it injects an incompatible method into overload resolution. if we get here with expected type set to null at all, the target context does not define a target type (vanilla context), so inference has done its best and nothing more to do than to signal error. */ ProblemMethodBinding problemMethod = new ProblemMethodBinding(method, method.selector, method.parameters, ProblemReasons.InvocationTypeInferenceFailure); problemMethod.returnType = expectedType != null ? expectedType : method.returnType; problemMethod.inferenceContext = this; return problemMethod; } // debugging: public String toString() { //$NON-NLS-1$ StringBuffer buf = new StringBuffer("Inference Context"); switch(this.stepCompleted) { //$NON-NLS-1$ case NOT_INFERRED: buf.append(" (initial)"); break; //$NON-NLS-1$ case APPLICABILITY_INFERRED: buf.append(" (applicability inferred)"); break; //$NON-NLS-1$ case TYPE_INFERRED: buf.append(" (type inferred)"); break; } switch(this.inferenceKind) { //$NON-NLS-1$ case CHECK_STRICT: buf.append(" (strict)"); break; //$NON-NLS-1$ case CHECK_LOOSE: buf.append(" (loose)"); break; //$NON-NLS-1$ case CHECK_VARARG: buf.append(" (vararg)"); break; } if (this.currentBounds != null && isResolved(this.currentBounds)) //$NON-NLS-1$ buf.append(" (resolved)"); buf.append('\n'); if (this.inferenceVariables != null) { //$NON-NLS-1$ buf.append("Inference Variables:\n"); for (int i = 0; i < this.inferenceVariables.length; i++) { //$NON-NLS-1$ buf.append('\t').append(this.inferenceVariables[i].sourceName).append(//$NON-NLS-1$ "\t:\t"); if (this.currentBounds != null && this.currentBounds.isInstantiated(this.inferenceVariables[i])) buf.append(this.currentBounds.getInstantiation(this.inferenceVariables[i], this.environment).readableName()); else buf.append("NOT INSTANTIATED"); buf.append('\n'); } } if (this.initialConstraints != null) { //$NON-NLS-1$ buf.append("Initial Constraints:\n"); for (int i = 0; i < this.initialConstraints.length; i++) if (this.initialConstraints[i] != null) buf.append('\t').append(this.initialConstraints[i].toString()).append('\n'); } if (this.currentBounds != null) buf.append(this.currentBounds.toString()); return buf.toString(); } /** * If 'type' is a parameterized type and one of its arguments is a wildcard answer the casted type, else null. * A nonnull answer is ensured to also have nonnull arguments. */ public static ParameterizedTypeBinding parameterizedWithWildcard(TypeBinding type) { if (type == null || type.kind() != Binding.PARAMETERIZED_TYPE) return null; ParameterizedTypeBinding parameterizedType = (ParameterizedTypeBinding) type; TypeBinding[] arguments = parameterizedType.arguments; if (arguments != null) { for (int i = 0; i < arguments.length; i++) if (arguments[i].isWildcard()) return parameterizedType; } return null; } public TypeBinding[] getFunctionInterfaceArgumentSolutions(TypeBinding[] a) { int m = a.length; TypeBinding[] aprime = new TypeBinding[m]; for (int i = 0; i < this.inferenceVariables.length; i++) { InferenceVariable alphai = this.inferenceVariables[i]; TypeBinding t = this.currentBounds.getInstantiation(alphai, this.environment); if (t != null) aprime[i] = t; else aprime[i] = a[i]; } return aprime; } /** Record the fact that the given constraint requires unchecked conversion. */ public void recordUncheckedConversion(ConstraintTypeFormula constraint) { if (this.constraintsWithUncheckedConversion == null) this.constraintsWithUncheckedConversion = new ArrayList<ConstraintFormula>(); this.constraintsWithUncheckedConversion.add(constraint); this.usesUncheckedConversion = true; } void reportUncheckedConversions(BoundSet solution) { if (this.constraintsWithUncheckedConversion != null) { int len = this.constraintsWithUncheckedConversion.size(); Substitution substitution = getResultSubstitution(solution, true); for (int i = 0; i < len; i++) { ConstraintTypeFormula constraint = (ConstraintTypeFormula) this.constraintsWithUncheckedConversion.get(i); TypeBinding expectedType = constraint.right; TypeBinding providedType = constraint.left; if (!expectedType.isProperType(true)) { expectedType = Scope.substitute(substitution, expectedType); } if (!providedType.isProperType(true)) { providedType = Scope.substitute(substitution, providedType); } /* FIXME(stephan): enable once we solved: (a) avoid duplication with traditional reporting (b) improve location to report against if (this.currentInvocation instanceof Expression) this.scope.problemReporter().unsafeTypeConversion((Expression) this.currentInvocation, providedType, expectedType); */ } } } /** For use by 15.12.2.6 Method Invocation Type */ public boolean usesUncheckedConversion() { return this.constraintsWithUncheckedConversion != null; } // INTERIM: infrastructure for detecting failures caused by specific known incompleteness: public static void missingImplementation(String msg) { throw new UnsupportedOperationException(msg); } public void forwardResults(BoundSet result, Invocation invocation, ParameterizedMethodBinding pmb, TypeBinding targetType) { if (targetType != null) invocation.registerResult(targetType, pmb); Expression[] arguments = invocation.arguments(); for (int i = 0, length = arguments == null ? 0 : arguments.length; i < length; i++) { Expression[] expressions = arguments[i].getPolyExpressions(); for (int j = 0, jLength = expressions.length; j < jLength; j++) { Expression expression = expressions[j]; if (!(expression instanceof Invocation)) continue; Invocation polyInvocation = (Invocation) expression; MethodBinding binding = polyInvocation.binding(); if (binding == null || !binding.isValidBinding()) continue; ParameterizedMethodBinding methodSubstitute = null; if (binding instanceof ParameterizedGenericMethodBinding) { MethodBinding shallowOriginal = binding.shallowOriginal(); TypeBinding[] solutions = getSolutions(shallowOriginal.typeVariables(), polyInvocation, result); if (// in CEF.reduce, we lift inner poly expressions into outer context only if their target type has inference variables. solutions == null) continue; methodSubstitute = this.environment.createParameterizedGenericMethod(shallowOriginal, solutions); } else { if (!binding.isConstructor() || !(binding instanceof ParameterizedMethodBinding)) // throw ISE ? continue; MethodBinding shallowOriginal = binding.shallowOriginal(); ReferenceBinding genericType = shallowOriginal.declaringClass; TypeBinding[] solutions = getSolutions(genericType.typeVariables(), polyInvocation, result); if (// in CEF.reduce, we lift inner poly expressions into outer context only if their target type has inference variables. solutions == null) continue; ParameterizedTypeBinding parameterizedType = this.environment.createParameterizedType(genericType, solutions, binding.declaringClass.enclosingType()); for (MethodBinding parameterizedMethod : parameterizedType.methods()) { if (parameterizedMethod.original() == shallowOriginal) { methodSubstitute = (ParameterizedMethodBinding) parameterizedMethod; break; } } } if (methodSubstitute == null || !methodSubstitute.isValidBinding()) continue; boolean variableArity = pmb.isVarargs(); final TypeBinding[] parameters = pmb.parameters; if (variableArity && parameters.length == arguments.length && i == length - 1) { TypeBinding returnType = methodSubstitute.returnType.capture(this.scope, expression.sourceStart, expression.sourceEnd); if (returnType.isCompatibleWith(parameters[parameters.length - 1], this.scope)) { variableArity = false; } } TypeBinding parameterType = InferenceContext18.getParameter(parameters, i, variableArity); forwardResults(result, polyInvocation, methodSubstitute, parameterType); } } } public void cleanUp() { this.b2 = null; this.currentBounds = null; } }
masud-technope/BLIZZARD-Replication-Package-ESEC-FSE2018
Corpus/eclipse.jdt.core/4456.java
249,387
/** * An implementation of the Symbol interface * * @author PCO Team */ public enum Signs implements Symbol { CROSS("C"), CIRCLE("I"), BALL("B"), BANGS("A"), CANNOT("N"), EMPTY("-"); private String rep; Signs(String s) { this.rep = s; } public String toString() { return this.rep; } public Signs[] symbols() { return this.values(); } }
dgvmiranda/columns-game
Signs.java
249,388
import java.util.Scanner; // import java.lang.*; class Main{ final static char signs[]={'/','*','+','-'}; private static String calculateReal(String s, int p, int q, int r) { int a=Integer.parseInt(s.substring(p,q)); int b=Integer.parseInt(s.substring(q+1,r)); int c=0; if(s.charAt(q)=='+') c=a+b; else if(s.charAt(q)=='-') c=a-b; else if(s.charAt(q)=='*') c=a*b; else if(s.charAt(q)=='/') c=a/b; return c+""; } private static String trimAllSpaces(String s) { String res=""; for(int a=0;a<s.length();a++) { if(s.charAt(a)!=32) res+=s.charAt(a); } return res; } private static String calculate(String s) { //for checking brackets////////////////////////////// int start=-1;//flag to check if starting bracket was found int end=s.length(); String ans=s; int count=0; for(int a=0;a<s.length();a++) { if(s.charAt(a)=='(') { if(start==-1) start=a; count++; } else if(start!=-1&&s.charAt(a)==')') { count--; end=a; } if(start!=-1&&count==0) { System.out.println("Values of start and end are:"+start+" "+a); ans=""; // count=0; if(start!=0) ans=s.substring(0,start); ans+=calculate(s.substring(start+1,a)); if(a!=s.length()-1) ans+=s.substring(a+1,s.length()); // //checking for more brackets // for(int c=a+1;c<s.length();c++) // if(s.charAt(c)=='(') // count++; s=ans; break; } } //////////////////////////////////////////////////////// int p,q,r; // String result=""; for(int a=0;a<signs.length;) { System.out.println("Checking for "+signs[a]); q=checkforSign(s,a); if(q!=-1) { p=getBefore(s,q); r=getAfter(s,q); String temp=calculateReal(s,p,q,r); if(p==0&&r==s.length()) s=temp; else if(p==0) s=temp +s.substring(r,s.length()); else if(r==s.length()) s=s.substring(0,p)+temp; else s=s.substring(0,p) +temp+s.substring(r,s.length()); } else { a++; } System.out.println("s so far: "+s); } return s; } private static int checkforSign(String s, int signIndex) { char c=signs[signIndex]; int index=-1; for(int a=1;a<s.length()-1;a++) { if(s.charAt(a)==c&&isNum(s.charAt(a-1))&&isNum(s.charAt(a+1))) { return a; } } return index; } private static boolean isNum(char c) { if(c>=48&&c<=57) return true; else return false; } private static int getBefore(String s,int signIndex) { int p=0; for(int a=signIndex-1;a>0;a++) { if(isNum(s.charAt(a))&&!isNum(s.charAt(a-1))) { p=a; break; } } return p; } private static int getAfter(String s,int signIndex) { int r=s.length(); for(int a=signIndex+1;a<s.length()-1;a++) { if(isNum(s.charAt(a))&&!isNum(s.charAt(a+1))) { r=a+1; break; } } return r; } public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Hey, this program calculates arithmetic operations you enter. For example, 2*3+7/13\ntype your input below_"); String s=""; // while(!input.toUpperCase().equals("stop")) // { int p,q,r; s=sc.next(); s=trimAllSpaces(s); q=checkforSign(s,0); p=getBefore(s,q); r=getAfter(s,q); System.out.println("\n Indices = "+p+" "+q+" "+r); System.out.println("\n Result = "+calculate(s)); // } sc.close(); } }
everythingshyam/windows-spotlight
Main.java
249,390
import java.io.*; import java.util.*; public class Main { private static int k; private static boolean[] isVisited = new boolean[10]; private static char[] signs; private static List<String> result = new ArrayList<>(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); k = sc.nextInt(); signs = new char[k]; for (int i = 0; i < k; i++) { signs[i] = sc.next().charAt(0); } dfs("", 0); Collections.sort(result); System.out.println(result.get(result.size() - 1)); System.out.println(result.get(0)); } public static boolean compare(int a, int b, char c) { if (c == '<') return a < b; else return a > b; } public static void dfs(String num, int depth) { if (depth == k + 1) { result.add(num); return; } for (int i = 0; i <= 9; i++) { if (depth == 0 || !isVisited[i] && compare(num.charAt(num.length() - 1) - '0', i, signs[depth - 1])) { isVisited[i] = true; dfs(num + i, depth + 1); isVisited[i] = false; } } } }
lecocococo/Algorithm-PS
2529.java
249,392
import java.util.Random; public class Deck{ Random rd = new Random(System.currentTimeMillis()); private Card[] deck = new Card[40]; private Card[] temp = new Card[40]; private Card[] randomCards = new Card[5]; private Card[] playerDeck = new Card[10]; private Card[] computerDeck = new Card[10]; Card[] boardDeck = new Card[30]; Card[] playerDeckRandom4 = new Card[4]; Card[] computerDeckRandom4 = new Card[4]; private String[] colors = {"R", "G", "Y", "B"}; // RED GREEN YELLOW BLUE //private String[] colors = {"B", "B", "B", "B"}; // Control BlueJack(sumValue=20) Win Game private String[] signs = {"+", "-", ""}; public Deck(){ int counter = 0; for(int i = 0; i<4; i++){ for(int n = 1; n<11; n++){ deck[counter] = new Card(signs[0],colors[i], n); counter++; } } } public void PrintBeforeShuffle(){ System.out.println("Game Is Started\n**************\nBefore Shuffle Card"); for(int i = 0; i<40; i++){ System.out.print(deck[i].getSign()+deck[i].getColor()+deck[i].getValue() + " "); } } public void Shuffle(){ int random = rd.nextInt(0,40); for(int i=0; i<40; i++){ while(temp[random]!=null) random = rd.nextInt(0,40); temp[random] = deck[i]; } System.out.print("\n**************\nThe first card of the game will be drawn from the end,\n" + " the first card will be given to the player,\n" + " the second card will be drawn from the beginning and\n" + " the second card will be given to the computer and this process will be repeated 5 times.\n**************\nAfter Shuffle Card"); System.out.println(); for(int i=0; i<40; i++){ deck[i] = temp[i]; System.out.print(deck[i].getSign()+deck[i].getColor()+deck[i].getValue() + " "); }System.out.println(); } public void DealCard(){ int idx = 39; for(int i=0; i<5; i++){ playerDeck[i]=deck[idx]; computerDeck[i]=deck[i]; idx--; } int counter =5; for(int i=0; i<30; i++){ boardDeck[i] = deck[counter]; counter++; } } public void randomCards(){ for(int attemp = 0; attemp<2; attemp++){ for(int i = 0; i<3; i++){ int x = 0; int color = rd.nextInt(0,4); int value = rd.nextInt(1,7); int sign = rd.nextInt(0,2); if(sign == 0){value*=-1; x =1;} randomCards[i] = new Card(signs[x],colors[color], value); } int counterCard = 3; for(int i = 0; i<2; i++){ int x = 0; int random = rd.nextInt(1,101); if(random <= 80){ int color = rd.nextInt(0,4); int value = rd.nextInt(1,7); int sign = rd.nextInt(0,2); if(sign == 0){value*=-1; x =1;} randomCards[counterCard] = new Card(signs[x],colors[color], value); counterCard++; }else{ int DorF = rd.nextInt(0,2); if(DorF==0) randomCards[counterCard] = new Card(signs[2],"DOUBLE(X)",2); else { randomCards[counterCard] = new Card(signs[2],"FLIP(X)", 1); randomCards[counterCard].setValue(randomCards[counterCard].getValue()*-1);; } counterCard++; } } if(attemp==0){ int counter = 0; for(int i = 5; i<10; i++){ playerDeck[i] = new Card(randomCards[counter].getSign(),randomCards[counter].getColor(),randomCards[counter].getValue()); counter++; } /*System.out.println(); for(int i = 0; i<5; i++){ System.out.print(randomCards[i].getColor()+randomCards[i].getValue() + ","); }*/ }else{ int counter = 0; for(int i = 5; i<10; i++){ computerDeck[i] = new Card(randomCards[counter].getSign(),randomCards[counter].getColor(),randomCards[counter].getValue()); counter++; } /*System.out.println(); for(int i = 0; i<5; i++){ System.out.print(randomCards[i].getColor()+randomCards[i].getValue() + ","); }*/ } } System.out.print("**************\nCards Were Dealt\nRandom Cards Are Created"); } public void SelectRandomCard(){ int[] controlArray = {0,1,2,3,4,5,6,7,8,9}; for(int attemp = 0; attemp<2; attemp++){ if(attemp==0){ for(int i = 0; i<4; i++){ int random = rd.nextInt(0,10); while(controlArray[random]==-1) random = rd.nextInt(0,10); playerDeckRandom4[i] = playerDeck[random]; controlArray[random]=-1; } }else{ int[] controlArray2 = {0,1,2,3,4,5,6,7,8,9}; for(int i = 0; i<4; i++){ int random = rd.nextInt(0,4); while(controlArray2[random]==-1) random = rd.nextInt(0,10); computerDeckRandom4[i] =computerDeck[random]; controlArray2[random]=-1; } } }System.out.println("Random cards were dealt 4 random cards were selected from 10 cards of each player."); /*System.out.println("\nPlayer Deck"); for(int i = 0; i<10; i++){ System.out.print(playerDeck[i].getColor()+playerDeck[i].getValue() + ","); }System.out.println("\nComputer Deck"); for(int i = 0; i<10; i++){ System.out.print(computerDeck[i].getColor()+computerDeck[i].getValue() + ","); }System.out.println(); */ }}
CanBthn/115Project
Deck.java
249,393
import java.util.*; import java.math.*; class rsigns { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); int laststart = 10; double counter2 = 1; BigInteger lint = new BigInteger("1000000007"); int oglimit = 0; for(int l=0;l<t;l++) { //double k = sc.nextDouble(); //int k = sc.nextInt(); String k = sc.next(); int consta =(int) Math.pow(10,9) + 7; int q = 1; if(q == 2) { BigInteger consta2 = new BigInteger("10000000007"); BigInteger start = BigInteger.TEN; BigInteger k3 = new BigInteger(k); BigInteger i = BigInteger.ONE; //k3 = k3.subtract(BigInteger.ONE); while(i.equals(k3) == false) { start = (start.add(start)).mod(consta2); System.out.println(i.add(BigInteger.ONE)+" "+start); i = i.add(BigInteger.ONE); } } else { //k = k-1; BigInteger ten = new BigInteger("10"); //double start = (Math.pow(2,k)*10)%consta; BigInteger start = new BigInteger("2"); int kl = k.length()-1; BigInteger two = new BigInteger("2"); BigInteger five = new BigInteger("5"); BigInteger k1 = new BigInteger(k); k1 = k1.subtract(BigInteger.ONE); //if(k1.equals(BigInteger.ONE)) //{ // System.out.println(10); //} //else //{ /*for(int i=3;i<=k;i++) { start = ((start.multiply(two))).mod(lint); //System.out.println(i+" "+start); }*/ //BigInteger k1 = new BigInteger(k); BigInteger result = start.modPow(k1,lint); /*BigInteger i = BigInteger.ONE; BigInteger result = two; while(i.equals(k1) == false) { result = result.multiply(two); i = i.add(BigInteger.ONE); System.out.println(i.add(BigInteger.ONE)+" "+result); } */ System.out.println(result.multiply(BigInteger.TEN).mod(lint)); //} } } } static double consta2 = Math.pow(10,9)+7; static double rec(double pos) { if(pos == 1) { return 10; } else { double someth = rec(pos-1); return (someth + someth) % consta2; } } }
tayadehritik/NightShift
rsigns.java
249,400
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package netdecoder; import java.io.Serializable; /** * * @author edroaldo */ public class Edge implements Serializable,Comparable<Edge>{ private Node from; private Node to; private Edge reverse; private double capacity; private double score; private double signScore; private double flow; private double cost; private int path; private double difference; public Edge(Node from, Node to){ this.from = from; this.to = to; this.flow = 0; signScore = 0; path = -1; difference = 0.0; } public Edge(Node from, Node to, double capacity){ this.from = from; this.to = to; this.capacity = capacity; this.flow = 0; signScore = 0; path = -1; difference = 0.0; } public Edge(Node from, Node to, double capacity, double cost){ this.from = from; this.to = to; this.capacity = capacity; this.flow = 0; signScore = 0; this.cost = cost; path = -1; difference = 0.0; } public String toString() { //return from.getName() + "->" + to.getName() + " " + capacity + "/" + flow ; String[] s1 = from.getName().split("\\/"); String[] s2 = to.getName().split("\\/"); return s1[0]+ "->" + s2[0];// + ":" + flow; //return from.getSymbol()+ "->" + to.getSymbol();// + " ";// + capacity + "/" + flow ; } public double residualCapacityTo(Node node){ if(node.getName().equals(from.getName())) return flow; else if(node.getName().equals(to.getName())) return capacity - flow; else throw new IllegalArgumentException("Illegal node"); } public void addResidualFlowTo(Node node, double delta){ if(node.getName().equals(from.getName())) flow -= delta; //backward edge else if (node.getName().equals(to.getName())) flow += delta; } public boolean isFrom(Node from){ if(this.from.equals(from.getName())) return true; else return false; } @Override public int hashCode() { return (from.getName() + to.getName()).hashCode(); } @Override public boolean equals(Object o){ if(o instanceof Edge){ Edge toCompare = (Edge)o; return this.from.equals(toCompare.from) && this.to.equals(toCompare.to); //return this.to.equals(toCompare.to); } return false; } /*@Override public boolean equals(Object o){ if(o instanceof Edge){ Edge toCompare = (Edge)o; return this.to.equals(toCompare.to); } return true; }*/ /*public boolean equals(Edge edge){ if(edge instanceof Edge){ if((from.getName().equals(edge.getFrom().getName()) && (to.getName().equals(edge.getTo().getName())))){ return true; } } return false; } */ public Node getOther(Node node){ if(node.getName().equals(this.from.getName())){ return this.to; }else if(node.getName().equals(this.to.getName())){ return this.from; }else{ throw new IllegalArgumentException("Illegal endpoint"); } } /** * @return the from */ public Node getFrom() { return from; } /** * @param from the from to set */ public void setFrom(Node from) { this.from = from; } /** * @return the to */ public Node getTo() { return to; } /** * @param to the to to set */ public void setTo(Node to) { this.to = to; } /** * @return the capacity */ public double getCapacity() { return capacity; } /** * @param capacity the capacity to set */ public void setCapacity(double capacity) { this.capacity = capacity; } /** * @return the score */ public double getMiscore() { return score; } /** * @param miscore the score to set */ public void setMiscore(double miscore) { this.score = miscore; } /** * @return the flow */ public double getFlow() { return flow; } /** * @param flow the flow to set */ public void setFlow(double flow) { this.flow = flow; } /** * @return the cost */ public double getCost() { return cost; } /** * @param cost the cost to set */ public void setCost(double cost) { this.cost = cost; } @Override public int compareTo(Edge edge) { if(this.cost < edge.getCost()) return -1; else if(this.cost > edge.getCost()) return +1; else return 0; } /** * @return the reverse */ public Edge getReverse() { return reverse; } /** * @param reverse the reverse to set */ public void setReverse(Edge reverse) { this.reverse = reverse; } /** * @return the path */ public int getPath() { return path; } /** * @param path the path to set */ public void setPath(int path) { this.path = path; } /*private void writeObject(final ObjectOutputStream out) throws IOException { out.writeDouble(this.capacity); out.writeDouble(this.flow); out.writeDouble(this.score); out.writeDouble(this.cost); } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { this.capacity = in.readDouble(); this.flow = in.readDouble(); this.score = in.readDouble(); this.cost = in.readDouble(); } */ /** * @return the difference */ public double getDifference() { return difference; } /** * @param difference the difference to set */ public void setDifference(double difference) { this.difference = difference; } /** * @return the signScore */ public double getSignScore() { return signScore; } /** * @param signScore the signScore to set */ public void setSignScore(double signScore) { this.signScore = signScore; } }
rubiruchi/NetDecoder
Edge.java
249,404
package Zodiac; // Create an Enum called "ZodiacSigns" which will contain all the signs by their name and in additions the following information. // Make sure to declare relevant fields & methods, Use Enum for Element as well. // Declare a program that will print the info of the sign represented by todays run date // (the relevant sign will be chosen according to the sysdate) /** * Created by yuriyf on 11/1/2016 */ public class Zodiac { public enum ZodiacSigns { ARIES("Ram", 21, 3, 20, 4, ZodiacElements.Elements.FIRE.getNameOfElement(), "Mars"), TAURUS("Bull", 21, 4, 20, 5, ZodiacElements.Elements.EARTH.getNameOfElement(), "Earth"), GEMINI("Twins", 21, 5, 20, 6, ZodiacElements.Elements.AIR.getNameOfElement(), "Mercury"), CANCER("Crab", 21, 6, 20, 7, ZodiacElements.Elements.WATER.getNameOfElement(), "Moon"), LEO("Lion", 21, 7, 20, 8, ZodiacElements.Elements.FIRE.getNameOfElement(), "Sun"), VIRGO("Maiden", 21, 8, 20, 9, ZodiacElements.Elements.EARTH.getNameOfElement(), "Mercury"), LIBRA("Scales", 21, 9, 20, 10, ZodiacElements.Elements.AIR.getNameOfElement(), "Venus"), SCOPRIO("Scorpion", 21, 10, 20, 11, ZodiacElements.Elements.WATER.getNameOfElement(), "Pluto"), SAGITTARIUS("Archer", 21, 11, 20, 12, ZodiacElements.Elements.FIRE.getNameOfElement(), "Jupiter"), CAPRICORN("Goat Horn", 21, 12, 20, 1, ZodiacElements.Elements.EARTH.getNameOfElement(), "Saturn"), AQUARIUS("Water Carrier", 21, 1, 20, 2, ZodiacElements.Elements.AIR.getNameOfElement(), "Uranus"), PISCES("Fish", 21, 2, 20, 3, ZodiacElements.Elements.WATER.getNameOfElement(), "Neptune"); private final String translation; private final int dayStart; private final int monthStart; private final int dayEnd; private final int monthEnd; private String element; private final String planet; ZodiacSigns(String translation, int dayStart, int monthStart, int dayEnd, int monthEnd, String element ,String planet) { this.translation = translation; this.dayStart = dayStart; this.monthStart = monthStart; this.dayEnd = dayEnd; this.monthEnd = monthEnd; this.element = element; this.planet = planet; } public String getTranslation() { return translation; } public int getDayStart() { return dayStart; } public int getMonthStart() { return monthStart; } public int getDayEnd() { return dayEnd; } public int getMonthEnd() { return monthEnd; } public String getPlanet() { return planet; } @Override public String toString() { return "ZodiacSigns{" + "translation='" + translation + '\'' + ", dayStart=" + dayStart + ", monthStart=" + monthStart + ", dayEnd=" + dayEnd + ", monthEnd=" + monthEnd + ", elements=" + element + ", planet='" + planet + '\'' + '}'; } } }
YuriyFedorov/Java_automation_local_YF
Zodiac.java
249,405
import java.io.*; import java.util.*; import java.util.stream.Collectors; public class Main { static int n; static List<Integer> signs; static Stack<Integer> stack; static boolean[] visited; static String min; static String max; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); n = Integer.parseInt(br.readLine()); signs = Arrays.stream(br.readLine().split(" ")) .map(it -> it.equals("<") ? 0 : 1) .collect(Collectors.toList()); visited = new boolean[10]; stack = new Stack<>(); backtracking(false); visited = new boolean[10]; stack = new Stack<>(); backtracking(true); System.out.println(max); System.out.println(min); } static boolean backtracking(boolean reverse) { if (stack.size() == n + 1) { List<Integer> sequence = new ArrayList<>(stack); if (check(sequence)) { if (reverse) { max = sequence.stream().map(Object::toString).collect(Collectors.joining("")); return true; } min = sequence.stream().map(Object::toString).collect(Collectors.joining("")); return true; } return false; } for (int j = 0; j <= 9; j++) { int i = reverse ? 9 - j : j; if (visited[i]) { continue; } stack.push(i); visited[i] = true; if (backtracking(reverse)) { return true; } visited[i] = false; stack.pop(); } return false; } static boolean check(List<Integer> sequence) { if (sequence.size() != n + 1) { return false; } Queue<Integer> queue = new LinkedList<>(sequence); int prev = queue.poll(); for (int i = 0; i < n; i++) { if (queue.isEmpty()) { return false; } int curr = queue.poll(); if (signs.get(i) == 0 && prev >= curr) { return false; } if (signs.get(i) == 1 && prev <= curr) { return false; } prev = curr; } return true; } }
pokycookie/BAEKJOON
2529.java
249,411
// 어떤 정수들이 있습니다. // 이 정수들의 절댓값을 차례대로 담은 정수 배열 absolutes와 이 정수들의 부호를 차례대로 담은 불리언 배열 signs가 매개변수로 주어집니다. // 실제 정수들의 합을 구하여 return 하도록 solution 함수를 완성해주세요. // 성공 class Solution { public int solution(int[] absolutes, boolean[] signs) { int answer = 0; for(int i = 0; i < signs.length; i++) { if(signs[i]) { answer += absolutes[i]; } else { answer += absolutes[i]*-1; } } return answer; } }
Minah7/Challenge
Q0332.java
249,417
public boolean isInSameQuadrantWith(Point p1) { if(isDifferentSigns(x,p1.x)) return false; if(isDifferentSigns(y,p1.y)) return false; return true; } public boolean isDifferentSigns(int a, int b) { return a > 0 && b < 0 || a < 0 && b > 0; }
zakupower/Java-Course-2018
Point.java
249,419
package report; import com.itextpdf.text.DocumentException; import java.sql.*; import java.util.ArrayList.*; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.Font; import com.itextpdf.text.Font.FontFamily; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.Paragraph; import java.io.*; public class Report7 { public static void main(String[] args) throws SQLException, DocumentException, FileNotFoundException { String connectionURL = "jdbc:mysql://127.0.0.1/servercis?user=root&password="; Connection myconn = DriverManager.getConnection(connectionURL); Document reportpdf = new Document(); PdfWriter.getInstance(reportpdf, new FileOutputStream("C:\\Users\\adam\\Desktop\\Report.pdf")); reportpdf.open(); reportpdf.add(new Paragraph("\b\b Report on the symptom of patient based on faculty:\n\n")); PreparedStatement myStmt = null; ResultSet myRs = null; String query0 = " Select distinct location_code from lhr_medication"; Statement st0 = myconn.createStatement(); ResultSet rs0 = st0.executeQuery(query0); while (rs0.next()) { String location_code = rs0.getString("Location_code"); String[] Faculty = {location_code}; { for (int i = 0; i < Faculty.length; i++) { { try { PdfPTable reportpdftable = new PdfPTable(3); PdfPCell reportpdf_cell; Font font = new Font(FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.WHITE); Font font1 = new Font(FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLACK); reportpdf_cell = new PdfPCell(new Phrase("Faculty:" + Faculty[i], font)); reportpdf_cell.setColspan(3); reportpdf_cell.setBackgroundColor(new BaseColor(0, 121, 182)); reportpdftable.addCell(reportpdf_cell); System.out.println("Faculty : " + Faculty[i]); System.out.println("==============\n"); System.out.println("----------------------------------------------------------------------------------"); System.out.println("||MEDICINE CODE||\b\b||DESCRIPTION||\b\b||TOTAL PATIENT||"); System.out.println("----------------------------------------------------------------------------------"); String Medication_code = ("MEDICINE CODE"); reportpdf_cell = new PdfPCell(new Phrase(Medication_code, font1)); reportpdf_cell.setBackgroundColor(BaseColor.LIGHT_GRAY); reportpdftable.addCell(reportpdf_cell); String description = ("DESCRIPTION"); reportpdf_cell = new PdfPCell(new Phrase(description, font1)); reportpdf_cell.setBackgroundColor(BaseColor.LIGHT_GRAY); reportpdftable.addCell(reportpdf_cell); String total_patient = ("TOTAL PATIENT"); reportpdf_cell = new PdfPCell(new Phrase(total_patient, font1)); reportpdf_cell.setBackgroundColor(BaseColor.LIGHT_GRAY); reportpdftable.addCell(reportpdf_cell); //myStmt = myconn.prepareStatement("select lhr_medication.Signs_code,Signs_desc,count(*) as Bilangan_pelajar from lhr_medication where LOCATION_CODE=? group by Signs_desc ORDER BY `Signs_desc` ASC "); myStmt = myconn.prepareStatement("SELECT LOCATION_CODE, Medication_code, Medication_desc, COUNT(Medication_code) as Bilangan_pelajar, COUNT(DISTINCT(Medication_code)) as MTotal FROM servercis.lhr_medication WHERE LOCATION_CODE=? group by Medication_code"); myStmt.setString(1, Faculty[i]); myRs = myStmt.executeQuery(); while (myRs.next()) { String signs_code = myRs.getString("Medication_code"); reportpdf_cell = new PdfPCell(new Phrase(signs_code)); reportpdftable.addCell(reportpdf_cell); String Medication_desc = myRs.getString("Medication_desc"); reportpdf_cell = new PdfPCell(new Phrase(Medication_desc)); reportpdftable.addCell(reportpdf_cell); String Bilangan_pelajar = myRs.getString("Bilangan_pelajar"); reportpdf_cell = new PdfPCell(new Phrase(Bilangan_pelajar)); reportpdftable.addCell(reportpdf_cell); System.out.println("||" + signs_code + "||\b\b||" + Medication_desc + "||\b\b||" + Bilangan_pelajar + "||"); System.out.println("----------------------------------------------------------------------------------"); } reportpdf.add(reportpdftable); try { myStmt = myconn.prepareStatement("select count(*) Medication_desc, COUNT(DISTINCT(Medication_code)) as MTotal from lhr_medication where location_code=? group by LOCATION_CODE"); myStmt.setString(1, Faculty[i]); myRs = myStmt.executeQuery(); while (myRs.next()) { String Total = myRs.getString("Medication_desc"); String MTotal = myRs.getString("MTotal"); System.out.println("Total medicine from " + Faculty[i] + " = " + MTotal + ""); reportpdf.add(new Paragraph("\n Total medicine from " + Faculty[i] + " = " + MTotal + " \n")); System.out.println("Total patient from " + Faculty[i] + " = " + Total + "\n\n"); reportpdf.add(new Paragraph(" Total patient from " + Faculty[i] + " = " + Total + " \n\n\n")); } } catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); } } catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); } } } } } reportpdf.close(); } }
umaqgeek/utem_eklinik
Report7.java
249,423
import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Files; import java.nio.file.Paths; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; public class Server { // initialize socket and input stream private Socket socket; private ServerSocket server; private DataInputStream in; private DataOutputStream out; public static int ports; public static String clientPath; public static String serverPath; static IvParameterSpec iv; static byte[] AESKey; // constructor with port public Server(int port, String clientPublicKeyPath, String serverPrivateKeyPath) { // starts server and waits for a connection try { server = new ServerSocket(port); System.out.println("Server started"); System.out.println("Waiting for a client ..."); socket = server.accept(); System.out.println("Client accepted"); // String[] AESKeyNsignature = new String[2]; String line = ""; // reads message from client until "Over" is sent while (!line.equals("over")) { try { // takes input from the client socket in = new DataInputStream(socket.getInputStream()); // output to the client socket out = new DataOutputStream(socket.getOutputStream()); // read AESKey from client String AESKey = in.readUTF(); System.out.println("GET AESKey from client: " + AESKey); // read AES Signature from client String AESSignature = in.readUTF(); System.out.println("GET AESSignature from client: " + AESSignature); // read serverPrivateKey from path byte[] serverPrivateKey = Files.readAllBytes(Paths.get(serverPrivateKeyPath)); // read clientPublicKey from path byte[] clientPublicKey = Files.readAllBytes(Paths.get(clientPublicKeyPath)); // decrypt AESKey receive from client using private key String decryptAESKey = decrypt(AESKey, serverPrivateKey); // verify signature boolean bool = verify(clientPublicKey, AESSignature.getBytes("UTF-8")); if (bool) { // output if match or not System.out.println("match"); // generate its own digital signature for the key; and send its digital // signature to the client. out.write(signSHA256RSA(decryptAESKey.getBytes("UTF-8"), serverPrivateKey)); System.out.println("sending digital signature"); out.flush(); } else { // print not match System.out.println("not match"); } // get size of a plain text string (in the unit of byte); int size = in.readInt(); System.out.println("GET size of a plaintext from client: " + size); // get an AES-encrypted version of the string String AESString = in.readUTF(); System.out.println("GET AESString from client: " + AESString); // get an digital signature for the plain text string String signatureText = in.readUTF(); System.out.println("GET signatureText from client: " + signatureText); // decrypt cipher text String plainText = decrypt(AESString, decryptAESKey.getBytes("UTF-8")); System.out.println("GET decrypt plainText: " + plainText); // verify signature boolean b = verify(clientPublicKey, signatureText.getBytes("UTF-8")); if (b) { System.out.println("match"); // generates its digital signature for the plain text and send to client out.write(signSHA256RSA(plainText.getBytes("UTF-8"), serverPrivateKey)); System.out.println("sending digital signature:"); out.flush(); } else { System.out.println("not match"); } } catch (IOException i) { System.out.println(i); } catch (Exception e) { e.printStackTrace(); } } System.out.println("Closing connection"); // close connection in.close(); out.close(); socket.close(); } catch (IOException i) { System.out.println(i); } } // Method for sign using SHA256RSA private static byte[] signSHA256RSA(byte[] input, byte[] bPk) throws Exception { // byte[] b1 = bPk; PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bPk); KeyFactory kf = KeyFactory.getInstance("RSA"); Signature privateSignature = Signature.getInstance("SHA256withRSA"); privateSignature.initSign(kf.generatePrivate(spec)); privateSignature.update(input); byte[] s = privateSignature.sign(); // return Base64.getEncoder().encodeToString(s); return s; } // Method for decrypt using AES/CBC public static String decrypt(String cipherText, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { SecretKeySpec aesKey = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC"); cipher.init(Cipher.DECRYPT_MODE, aesKey, iv); byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText)); return new String(plainText); } // method for verify signature with public key public static boolean verify(byte[] key, byte[] signature) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException { KeyFactory kf = KeyFactory.getInstance("AES/CBC"); // or "EC" or whatever PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(key)); Signature sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(publicKey); return sig.verify(signature); } public static void main(String args[]) { Server server = new Server(ports, clientPath, serverPath); } }
jasmineyliang/applying-basic-cryptographic-primitives-for-secure-communication
Server.java
249,424
import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.math.BigInteger; import java.net.Socket; import java.net.UnknownHostException; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Random; import java.util.Scanner; public class Client { static String IP; public static int ports; private Socket socket; private DataInputStream in; private DataOutputStream out; public static File serverPublicKey; public static File clientPrivateKey; // constructor to put IP address and port public Client(String address, int port, File serverPublicKey, File clientPrivateKey, String text) throws Exception { // randomly generate 256 bit numbers as shared-key BigInteger AESKey = new BigInteger(256, new Random()); // read serverPublicKey from file byte[] serverPublicKeyF = readContentIntoByteArray(serverPublicKey); // read clientPrivateKey from file byte[] clientPrivateKeyF = readContentIntoByteArray(clientPrivateKey); byte[] encryptAESKey = null; byte[] signature = null; try { // encrypt the keys using the public key encryptAESKey = encrypt(AESKey.toByteArray(), serverPublicKeyF); // generate signature of the key using private key signature = signSHA256RSA(AESKey.toByteArray(), clientPrivateKeyF); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } try { // create socket socket = new Socket(address, port); System.out.println("Connected"); // sends output to the socket out = new DataOutputStream(socket.getOutputStream()); // get input from the socket in = new DataInputStream(socket.getInputStream()); } catch (UnknownHostException u) { System.out.println(u); } catch (IOException i) { System.out.println(i); } // string to read message from input String line = ""; // keep reading until "Over" is input while (!line.equals("Over")) { try { // line = input.readLine(); // sent out (i) the encrypted AES key out.writeUTF(encryptAESKey.toString()); System.out.println("sending text size : " + encryptAESKey.toString()); out.flush(); // sent out (ii) its signature for the plain text AES key. out.writeUTF(signature.toString()); System.out.println("sending text size : " + signature.toString()); out.flush(); // get serverSignature from socket String serverSignature = in.readUTF(); System.out.println("get serverSignature : " + serverSignature); // verify signature using serverPublicKey ,check match or not Boolean bool = verify(serverPublicKeyF, serverSignature.getBytes("UTF-8")); if (bool) { // output the result (i.e., match or not). System.out.println("match"); // It converts the string received from its user to a byte array. byte[] byteText = text.getBytes("UTF-8"); // It generates a signature of the byte array, using “SHA512withRSA”. byte[] signatureText = signSHA256RSA(byteText, clientPrivateKeyF); // It encrypts the byte array with the shared AES key and CBC mode, to get // cipher-text. byte[] encryptbyteText = encrypt(byteText, AESKey.toByteArray()); // It sends to the server: (i) the size of the string (in the unit of byte) out.writeInt(byteText.length); System.out.println("sending text size : " + byteText.length); out.flush(); // It sends to the server: (ii) the cipher-text out.writeUTF(encryptbyteText.toString()); System.out.println("sending cipher-text text : " + encryptbyteText.toString()); out.flush(); // It sends to the server: (iii) its signature. out.writeUTF(signatureText.toString()); System.out.println("sending signature: " + encryptbyteText.toString()); out.flush(); } else { System.out.println("not match"); } } catch (IOException i) { System.out.println(i); } } // close the connection in.close(); out.close(); socket.close(); } // method read File Content Into Byte Array private static byte[] readContentIntoByteArray(File file) { FileInputStream fileInputStream = null; byte[] bFile = new byte[(int) file.length()]; try { // convert file into array of bytes fileInputStream = new FileInputStream(file); fileInputStream.read(bFile); fileInputStream.close(); for (int i = 0; i < bFile.length; i++) { System.out.print((char) bFile[i]); } } catch (Exception e) { e.printStackTrace(); } return bFile; } // Method for encrypt using AES/CBC public byte[] encrypt(byte[] key, byte[] plaintext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { SecretKeySpec aesKey = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC"); cipher.init(Cipher.ENCRYPT_MODE, aesKey); return cipher.doFinal(plaintext); } // Method for sign using SHA256RSA private static byte[] signSHA256RSA(byte[] input, byte[] bPk) throws Exception { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bPk); KeyFactory kf = KeyFactory.getInstance("RSA"); Signature privateSignature = Signature.getInstance("SHA256withRSA"); privateSignature.initSign(kf.generatePrivate(spec)); privateSignature.update(input); byte[] s = privateSignature.sign(); return s; } // Method for verify signature with public key public static boolean verify(byte[] key, byte[] signature) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException { KeyFactory kf = KeyFactory.getInstance("AES/CBC"); // or "EC" or whatever PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(key)); Signature sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(publicKey); return sig.verify(signature); } // main public static void main(String args[]) throws Exception { // user provide text message Scanner scan = new Scanner(System.in); System.out.println("Enter text: "); String text = scan.nextLine(); scan.close(); Client client = new Client(IP, ports, serverPublicKey, clientPrivateKey, text); } }
jasmineyliang/applying-basic-cryptographic-primitives-for-secure-communication
Client.java
249,432
import java.util.Scanner; public class postfix{ public static boolean isOperand(char c){ if( (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9')){ return true; }else{ return false; } } public static boolean isOperator(char c){ return c=='+' || c=='-' || c=='*' || c=='/'; } public static int precedenceOrder(char c){ if(c == '*' || c == '/' ){ return 2; }else { return 1; } } //main public static void main(String [] args){ String backStack = ""; int backLength = 0; CharStack opstack = new CharStack(); Scanner scan = new Scanner(System.in); System.out.println("Please enter your infix expression: "); String userIn = scan.nextLine(); int length = userIn.length(); for (int i = 0; i < length; i++){ char temp = userIn.charAt(i); if (isOperand(temp)) //operand System.out.print(temp); else if (isOperator(temp){ //operator if (opstack().isEmpty()) //if the stack is empty, push the operand to the stack opstack.push(temp); else{ //if the stack is not empty, pop the stack and write out signs with higher or equal precedence while (!opstack.isEmpty()){ if (precedenceOrder(temp) == 2) System.out.print(opstack.pop()); //higher precedence is written out else if (precedenceOrder(temp) == 1){ opstack.pop(); //lower precedence is popped but not written out backStack += opstack.pop(); //popped expressions added to string to be re-added to stack }//else if }//while backLength = backStack.length(); for (int j = (backLength - 1);j > -1; j--){ opstack.push(backStack[j]); //push all operators that are lower precedence back to the stack }//for opstack.push(temp); //push temp to stack }//else }//else if else if (temp == '(') //left parenthesis opstack.push(temp); else if (temp == ')'){//right parenthesis while (!opstack.isEmpty() && opstack.pop() != ')'){ System.out.print(opstack.pop()); } } }//for while (!opstack.isEmpty()) //write out the remaining operators in opstack System.out.print(opstack.pop()); }//main }//class
sbunivedu/cs2-program1-hjbahn
postfix.java
249,433
import java.util.Scanner; class Ten { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); // Accept the number of rows from the user System.out.print("Enter the number of rows for the half triangle: "); int numRows = scanner.nextInt(); // Print the triangle pattern printRow(1, numRows); scanner.close(); } // Recursive method to print rows private static void printRow(int currentRow, int numRows) { if (currentRow <= numRows) { printDollars(1, currentRow); System.out.println(); printRow(currentRow + 1, numRows); } } // Recursive method to print dollar signs in a row private static void printDollars(int currentCol, int maxCols) { if (currentCol <= maxCols) { System.out.print("$ "); printDollars(currentCol + 1, maxCols); } } }
Disha711/Core-Java
Ten.java
249,434
package dmeyers.engine.geom; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Path2D; import java.util.ArrayList; import cs195n.Vec2f; import dmeyers.engine.Entity; public class Ray { Vec2f source; Vec2f direction; float timeLeft = 0.2f; float destX; float destY; Vec2f perpendicular; public Ray(Vec2f src, Vec2f dir) { source = src; direction = dir.normalized(); destX = source.x + (direction.x * 500); destY = source.y + (direction.y * 500); perpendicular = new Vec2f(-direction.y,direction.x); } public void onDraw(Graphics2D g){ //System.out.println("draw ray"); g.setColor(Color.RED); Path2D.Float path = new Path2D.Float(); path.moveTo(source.minus(perpendicular.smult(3)).x, source.minus(perpendicular.smult(3)).y); path.lineTo(source.plus(perpendicular.smult(3)).x, source.plus(perpendicular.smult(3)).y); // path.lineTo(destX + 10, destY + 10); path.lineTo(destX, destY); g.fill(path); } public Vec2f raycastCircle(Circle c){ if (c.contains(source)){ Vec2f projection = c.getCenter().projectOntoLine(source, direction); float x = projection.dist(c.getCenter()); return source.plus(direction.smult(projection.dist(source) + (float) Math.sqrt((c.radius * c.radius) - (x * x)))); } else { Vec2f projection = c.getCenter().minus(source).projectOnto(direction).plus(source); // System.out.println(projection + ": " + c.getCenter()); if (c.contains(projection) && checkSigns(projection)){ float x = projection.dist(c.getCenter()); return source.plus(direction.smult(projection.dist(source) - (float) Math.sqrt((c.radius * c.radius) - (x * x)))); } } return null; } public Vec2f raycastPolygon(Polygon p) { float closestT = Float.POSITIVE_INFINITY; Vec2f closestTVec = null; int pSize = p.points.size(); for(int i = 0; i<pSize; i++){ // System.out.println(p + "-" + p.points.get(i)); Vec2f p1 = p.points.get(i); Vec2f p2 = p.points.get((i + 1) % pSize); Vec2f segment = p2.minus(p1).normalized(); Vec2f perpSeg = new Vec2f(-segment.y, segment.x); // System.out.println(p + " (" + p1 + ". " + p2 + "): " + p2.minus(source).cross(direction) * (p1.minus(source).cross(direction))); if (p2.minus(source).cross(direction) * (p1.minus(source).cross(direction)) < 0){ float t = p2.minus(source).dot(perpSeg) / direction.dot(perpSeg); if (t < closestT && t >= 0) { // System.out.println(t + ":" + p1 + ":" + p2); closestT = t; closestTVec = source.plus(direction.smult(t)); } } } // System.out.println(closestTVec); return closestTVec; } public Vec2f raycastAAB(AAB aab){ //System.out.println(aab.pos); return raycastPolygon(aab.toPolygon()); } public boolean checkSigns(Vec2f proj){ Vec2f dif = proj.minus(source); return ((dif.x >= 0 && direction.x >= 0) || (dif.x < 0 && direction.x <0)) && ((dif.y >= 0 && direction.y >= 0) || (dif.y < 0 && direction.y <0)); } public Entity collideRay(ArrayList<Entity> entities, ArrayList<Entity> es) { float minDistance = Float.POSITIVE_INFINITY; Entity minEntity = null; for (Entity e : entities){ if (e.shape != null && !es.contains(e)){ // System.out.println(e.shape); Vec2f intersect = e.shape.raycast(this); // if (intersect != null) System.out.println(intersect); if (intersect != null && intersect.dist2(source) < minDistance){ // System.out.println(e.shape + " !" + intersect.dist2(source)); minDistance = intersect.dist2(source); destX = intersect.x; destY = intersect.y; minEntity = e; // System.out.println(new Vec2f(destX,destY)); } } } return minEntity; } public Vec2f getDirection() { return direction; } public boolean remove(long nanos) { if (timeLeft <= 0) return true; else { timeLeft -= nanos /1000000000f; return false; } } }
danmeyers/engine
geom/Ray.java
249,439
import java.util.ArrayList; public class Road { //Attributes private String id; private int speedLimit; private int length; private int[] startLocation; private int[] endLocation; private ArrayList<Road> connectedRoads = new ArrayList<>(); private ArrayList<Car> carsOnRoad = new ArrayList<>(); private ArrayList<TrafficLight> ligthsOnRoad = new ArrayList<>(); private ArrayList<TrafficSign> signsOnRoad = new ArrayList<>(); private ArrayList<GasStation> gasStationList = new ArrayList<>(); //Constructors public Road(String id, int speedLimit, int length, int[] startLocation) { this.id = id; this.speedLimit = speedLimit; this.length = length; this.startLocation = startLocation; this.endLocation = new int[]{this.startLocation[0] + this.length, 0}; } public Road() { } //Get set methods public ArrayList<GasStation> getGasStationList() { return gasStationList; } public ArrayList<TrafficSign> getSignsOnRoad(){ return signsOnRoad; } public void setSignsOnRoad(ArrayList<TrafficSign> signsOnRoad){ this.signsOnRoad = signsOnRoad; } public void setGasStationList(ArrayList<GasStation> gasStationList) { this.gasStationList = gasStationList; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getSpeedLimit() { return speedLimit; } public void setSpeedLimit(int speedLimit) { this.speedLimit = speedLimit; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int[] getStartLocation() { return startLocation; } public void setStartLocation(int[] startLocation) { this.startLocation = startLocation; } public int[] getEndLocation() { return endLocation; } public void setEndLocation(int[] endLocation) { this.endLocation = endLocation; } public ArrayList<Road> getConnectedRoads() { return connectedRoads; } public void setConnectedRoads(ArrayList<Road> connectedRoads) { this.connectedRoads = connectedRoads; } public ArrayList<Car> getCarsOnRoad() { return carsOnRoad; } public void setCarsOnRoad(ArrayList<Car> carsOnRoad) { this.carsOnRoad = carsOnRoad; } public ArrayList<TrafficLight> getLigthsOnRoad() { return ligthsOnRoad; } public void setLigthsOnRoad(ArrayList<TrafficLight> ligthsOnRoad) { this.ligthsOnRoad = ligthsOnRoad; } //Input output methods public void showStartLocation() { System.out.println("Start Location is: " + startLocation[0] + "," + startLocation[1]); } public void showEndLocation() { System.out.println("End Location is: " + endLocation[0] + "," + endLocation[1]); } public void showRoadInfo() { System.out.printf("Road ID: %s - Speed limit: %dm/s - Length: %d%n" , this.id, this.speedLimit, this.length); showStartLocation(); showEndLocation(); } //Business methods }
peshin-ai/JCU_CP2406_Traffic_Simulator_1.0
src/Road.java
249,440
import java.util.ArrayDeque; import java.util.Iterator; public class Stacks { public static void main(String[] args) { String response = "2+3-12+2-4"; ArrayDeque<String> signs = new ArrayDeque<String>(); ArrayDeque<Integer> numbers = new ArrayDeque<Integer>(); String tempHolder = ""; for(int idx=0; idx < response.length(); idx++) { char x = response.charAt(idx); System.out.println(x); if(x == '+' || x == '-') { if(!tempHolder.equals("")) { numbers.push(Integer.parseInt(tempHolder)); tempHolder = ""; } signs.push(Character.toString(x)); } else { tempHolder += x; } } numbers.push(Integer.parseInt(tempHolder)); System.out.println(signs); System.out.println(numbers); Iterator<String> signIter = signs.iterator(); int running_total = 0; boolean firstTime = true; while(signIter.hasNext()) { String sign = (String)signIter.next(); if(firstTime) { Integer a1 = numbers.pop(); Integer a2 = numbers.pop(); if (sign.equals("+")) { running_total = a1 + a2; } else { running_total = a1 - a2; } firstTime = false; } else { Integer a1 = numbers.pop(); if (sign.equals("+")) { running_total = a1 + running_total; } else { running_total = a1 - running_total; } } } System.out.println("Expression: "+response); System.out.println("Total: "+running_total); } }
jigsheth57/Java101
Stacks.java
249,441
/** Purpose: finds 1 root of f(x) * * Date: 10/18 */ public class Solver{ public static void main ( String[] args){ double a ; double b; double epsilon; int count = 0; // default values for a, b, and epsilon if args.length == 0 if(args.length == 0 ){ a = 0; b = 20; epsilon = 0.5; }else{ a = Double.parseDouble(args[0]); b = Double.parseDouble(args[1]); epsilon = Double.parseDouble(args[2]); } if (Math.signum(f(a)) == Math.signum(f(b))){ System.out.println( " A and B have the same signs"); } else { System.out.println( " A and B have different signs"); } System.out.println( " Searching for roorts from " + a + " to " + b); System.out.println( " epsilon: " + epsilon); double min = a; double max = b; double x = (min + max) / 2; while ( Math.abs(f(x)) > epsilon ){ //System.out.println( " min: " + min + "max: " + max + "x= " + x); count++; if ((f(x)>0) == (f(min)>0)) { //checks if have same sign //if (Math.signum(f(x)) == Math.signum(f(min))) min = x; } else { max = x; } } System.out.println("found root: x=" +x); System.out.println("Count: " + count); } /** Returns x*sin(x) - 3. */ public static double f (double x) { //return x* Math.sin(x) -3; return Math.abs(x)/x; // return Math.pow(x,2) -2; } }
KalebGz/ComputerScienceA
Solver.java
249,442
import java.util.Scanner; class Eleven { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Accept the number of rows from the user System.out.print("Enter the number of rows for the triangle: "); int numRows = scanner.nextInt(); // Print the triangle pattern printTriangle(numRows, 1); scanner.close(); } // Recursive method to print the triangle private static void printTriangle(int numRows, int currentRow) { if (currentRow <= numRows) { printSpaces(numRows - currentRow); printDollars(2 * currentRow - 1); System.out.println(); printTriangle(numRows, currentRow + 1); } } // Recursive method to print spaces private static void printSpaces(int numSpaces) { if (numSpaces > 0) { System.out.print(" "); printSpaces(numSpaces - 1); } } // Recursive method to print dollar signs private static void printDollars(int numDollars) { if (numDollars > 0) { System.out.print("*"); printDollars(numDollars - 1); } } }
Disha711/Core-Java
Eleven.java
249,443
public class P76501 { class Solution { public int solution(int[] absolutes, boolean[] signs) { int answer = 0; for(int i=0; i<absolutes.length; i++) { if(signs[i]) answer += absolutes[i]; else answer -= absolutes[i]; } return answer; } } }
GoToGREAT/Algorithms_Programmers
P76501.java
249,444
import java.util.Scanner; class TriPatt { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Accept the number of rows from the user System.out.print("Enter the number of rows for the triangle: "); int numRows = scanner.nextInt(); // Print the triangle pattern printTriangle(numRows, 1); scanner.close(); } // Recursive method to print the triangle private static void printTriangle(int numRows, int currentRow) { if (currentRow <= numRows) { printSpaces(numRows - currentRow); printDollars(2 * currentRow - 1); System.out.println(); printTriangle(numRows, currentRow + 1); } } // Recursive method to print spaces private static void printSpaces(int numSpaces) { if (numSpaces > 0) { System.out.print(" "); printSpaces(numSpaces - 1); } } // Recursive method to print dollar signs private static void printDollars(int numDollars) { if (numDollars > 0) { System.out.print("*"); printDollars(numDollars - 1); } } }
Disha18021/Core-java
TriPatt.java
249,445
/** * A Bank can hold up to a fixed number of BankAccounts. * @author cs302 */ public class Bank { /** The array of BankAccount objects. */ private BankAccount[] accounts; /** The first available account index. */ private int firstAvailableAcc; /** * Creates a bank that can have up to numAccounts accounts. */ public Bank(int numAccounts) { this.accounts = new BankAccount[numAccounts]; this.firstAvailableAcc = 0; } /** * Adds the given BankAccount to the bank. If the bank is full * an error message is printed and the bank is unchanged. * @param account The account to add */ public void add(BankAccount account) { if (firstAvailableAcc == accounts.length) { System.out.println("Bank is full. No account added."); return; } this.accounts[firstAvailableAcc] = account; firstAvailableAcc++; } /** * Returns the bank account with the given account number. * If no such account exists, null is returned. * @param acctNumber The account number * @return The account */ public BankAccount find(int acctNumber) { for (int i = 0; i < firstAvailableAcc; i++) { if (accounts[i].getAccountNumber() == acctNumber) { return accounts[i]; } } return null; } /** * Returns a string representation of the bank. * The format is one account per line. */ public String toString() { if (firstAvailableAcc == 0) return "NONE"; String result = ""; for (int i = 0; i < firstAvailableAcc; i++) { result += accounts[i].getAccountNumber() + " "; result += accounts[i].getBalance() + "\n"; // Note that we don't make use of BankAccount's toString because // we don't want to have dollar signs ($) as part of the String // representation for the Bank. } return result; } }
abdulkk49/OOP-Labs
P8/Bank.java
249,446
class Solution { public int solution(int[] absolutes, boolean[] signs) { int answer = 0; for(int i=0;i<signs.length;i++){ if(signs[i]){ answer += absolutes[i]; } else{ answer -= absolutes[i]; } } return answer; } } //---------------------------------------------- //문제 분야 : 자바 연습 //https://school.programmers.co.kr/learn/courses/30/lessons/76501
Paper10/Algorism
20230714.java
249,449
import java.io.*; import java.util.*; import java.awt.geom.Point2D; public class Apl { // GLOBAL OUTPUT SETTINGS private String dir = "/home/daveg/Electronics/relay-clock/plots/"; private String project = "relay-clock"; private boolean process_F_Cu = false; private boolean process_B_Cu = true; private boolean process_NPTH = false; private int ppi = 1000; // pixels per inch private double border_mm = 1; // mm border around entire image // ============================== private double scale = 1; // 1 for mm private double step = 1; // subpixel stepping 0.5 private int border = (int)Math.round(border_mm/25.4*ppi); // pixel border around entire image private boolean single_quadrant = false; private MyGraphics myg = new MyGraphics(); private int linenumber = 0; private HashMap<Integer,Aperture> apertures = new HashMap<Integer,Aperture>(); private Aperture aperture = null; private HashMap<Integer,Aperture> tools = new HashMap<Integer,Aperture>(); private Aperture tool = null; private Point2D.Double lastPoint = new Point2D.Double(0,0); public void addAperture(String line) { // strip the %AD String s = line.substring(3); // get the aperture number int n = Integer.parseInt(s.substring(1, 3)); System.out.println("aperture number: "+n); // get the type String type = s.substring(3, 4); System.out.println("aperture type: #"+type+"#"); String modifiers = s.substring(s.indexOf(",")+1, s.indexOf("*")); System.out.println("modifiers: #"+modifiers+"#"); // extract modifiers float[] modarray = new float[4]; int modindex = 0; while (modifiers.length() > 0) { int xpos = modifiers.indexOf("X"); if (xpos != -1) { modarray[modindex] = Float.valueOf(modifiers.substring(0, xpos)); modifiers = modifiers.substring(xpos+1); } else { modarray[modindex] = Float.valueOf(modifiers); modifiers = ""; } modindex++; } System.out.println("modifier 0:"+modarray[0]); System.out.println("modifier 1:"+modarray[1]); System.out.println("modifier 2:"+modarray[2]); System.out.println("modifier 3:"+modarray[3]); Aperture a = new Aperture(this.ppi, type, modarray); this.apertures.put(new Integer(n), a); } public void addTool(String line) { // strip the T String s = line.substring(1); System.out.println("trimmed: "+s); // get the tool number int cpos = s.indexOf("C"); int n = Integer.parseInt(s.substring(0, cpos)); System.out.println("tool number: "+n); // extract modifiers float[] modarray = new float[4]; int modindex = 0; String modifiers = s.substring(cpos+1); while (modifiers.length() > 0) { int xpos = modifiers.indexOf("X"); if (xpos != -1) { modarray[modindex] = Float.valueOf(modifiers.substring(0, xpos)); modifiers = modifiers.substring(xpos+1); } else { modarray[modindex] = Float.valueOf(modifiers); modifiers = ""; } modindex++; } System.out.println("modifier 0:"+modarray[0]); System.out.println("modifier 1:"+modarray[1]); System.out.println("modifier 2:"+modarray[2]); System.out.println("modifier 3:"+modarray[3]); Aperture a = new Aperture(this.ppi, "C", modarray); this.tools.put(new Integer(n), a); } public void selectAperture(String line) { // strip the G54 String s = line.substring(3); // get the aperture number int n = Integer.parseInt(s.substring(1, 3)); System.out.println("selecting aperture number: "+n); this.aperture = this.apertures.get(new Integer(n)); } public void selectTool(String line) { // strip the T String s = line.substring(1); // get the tool number int n = Integer.parseInt(s); System.out.println("selecting tool number: "+n); this.tool = this.tools.get(new Integer(n)); } public void draw(String line) { int xpos = line.indexOf("X"); int ypos = line.indexOf("Y"); int dpos = line.indexOf("D"); String xstr = line.substring(xpos+1, ypos); String ystr = line.substring(ypos+1, dpos); // add leading zeroes while (xstr.length() < 7) { xstr = "0"+xstr; } while (ystr.length() < 7) { ystr = "0"+ystr; } // add decimal point xstr = xstr.substring(0, 3) + "." + xstr.substring(3); ystr = ystr.substring(0, 3) + "." + ystr.substring(3); int x = (int)Math.round(Double.valueOf(xstr)*(double)this.ppi); int y = (int)Math.round(Double.valueOf(ystr)*(double)this.ppi); if (line.endsWith("D01*")) { // move with shutter OPEN // make a path from lastPoint to x,y double distance = Functions.getDistance(lastPoint, x, y); while(distance > this.step) { Point2D.Double next = Functions.calcStep(lastPoint, x, y, this.step); int xx = (int)Math.round(next.x); int yy = (int)Math.round(next.y); this.aperture.draw(this.myg, xx, yy); this.lastPoint.x = next.x; this.lastPoint.y = next.y; distance = Functions.getDistance(lastPoint, x, y); //System.out.println("distance: "+distance); } } if (line.endsWith("D02*")) { // move with shutter CLOSED this.lastPoint.x = x; this.lastPoint.y = y; } if (line.endsWith("D03*")) { // flash this.aperture.draw(this.myg, x, y); this.lastPoint.x = x; this.lastPoint.y = y; } } private int parseValue(String s) { boolean negative = false; // strip minus signs if (s.startsWith("-")) { s = s.substring(1); negative = true; } s = addLeadingZeroes(s); s = addDecimalPoint(s); int i = (int)Math.round(Double.valueOf(s)*(double)this.ppi); if (negative) { i = i*-1; } return i; } private String addDecimalPoint(String s) { return s.substring(0, 3) + "." + s.substring(3); } private String addLeadingZeroes(String s) { while (s.length() < 7) { s = "0"+s; } return s; } public void drawArc(String line) { int xpos = line.indexOf("X"); int ypos = line.indexOf("Y"); int ipos = line.indexOf("I"); int jpos = line.indexOf("J"); int dpos = line.indexOf("D"); String xstr = line.substring(xpos+1, ypos); String ystr = line.substring(ypos+1, ipos); String istr = line.substring(ipos+1, jpos); String jstr = line.substring(jpos+1, dpos); int x = parseValue(xstr); int y = parseValue(ystr); int i = parseValue(istr); int j = parseValue(jstr); System.out.println("Arc: "+x+", "+y+", "+i+", "+j); int centerx = (int)this.lastPoint.x + i; int centery = (int)this.lastPoint.y + j; double radius = Functions.getDistance(lastPoint, centerx, centery); double arcResolution = 0.00175; System.out.println("Circle at: ["+centerx+", "+centery+"] Radius:"+radius); // The parametric equation for a circle is // x = cx + r * cos(a) // y = cy + r * sin(a) // Where r is the radius, cx,cy the origin, and a the angle from 0..2PI radians or 0..360 degrees. if (line.endsWith("D01*")) { // move with shutter OPEN // make a path from lastPoint to x,y double angle = 2 * Math.PI; while (angle > 0) { int xx = (int)Math.round(centerx + radius * Math.cos(angle)); int yy = (int)Math.round(centery + radius * Math.sin(angle)); this.aperture.draw(this.myg, xx, yy); this.lastPoint.x = xx; this.lastPoint.y = yy; angle = angle - arcResolution; } } } public void drill(String line) { int xpos = line.indexOf("X"); int ypos = line.indexOf("Y"); String xstr = line.substring(xpos+1, ypos); String ystr = line.substring(ypos+1); if (ystr.startsWith("-")) { ystr = ystr.substring(1); } // add leading zeroes while (xstr.length() < 6) { xstr = "0"+xstr; } while (ystr.length() < 6) { ystr = "0"+ystr; } // add decimal point xstr = xstr.substring(0, 2) + "." + xstr.substring(2); ystr = ystr.substring(0, 2) + "." + ystr.substring(2); //System.out.println("xstr:"+xstr); //System.out.println("ystr:"+xstr); int x = (int)Math.round(Double.valueOf(xstr)*(double)this.ppi); int y = (int)Math.round(Double.valueOf(ystr)*(double)this.ppi); y = Math.abs(y); // invert this.tool.draw(this.myg, x, y, true); this.lastPoint.x = x; this.lastPoint.y = y; } public boolean processGerber(String line) { this.linenumber++; line = line.trim().toUpperCase(); if (line.startsWith("%FS")) { System.out.println("got format definition! line "+this.linenumber); if (!line.equals("%FSLAX34Y34*%")) { System.out.println("wrong format definition! STOPPING..."); return true; } } if (line.startsWith("%AD")) { System.out.println("got aperture definition! line "+this.linenumber); addAperture(line); } if (line.startsWith("%MOIN*%")) { System.out.println("Dimensions are expressed in inches"); this.scale = 25.4; } if (line.startsWith("%MOMM*%")) { System.out.println("Dimensions are expressed in millimeters"); this.scale = 1; } if (line.startsWith("G04")) { System.out.println("ignoring comment on line "+this.linenumber); } if (line.startsWith("G70")) { System.out.println("Set unit to INCH"); } if (line.startsWith("G71")) { System.out.println("Set unit to MM"); } if (line.startsWith("G74")) { System.out.println("Selecting Single quadrant mode"); single_quadrant = true; } if (line.startsWith("G75")) { System.out.println("Selecting Multi quadrant mode"); single_quadrant = false; } if (line.startsWith("G90")) { System.out.println("Set Coordinate format to Absolute notation"); } if (line.startsWith("G91")) { System.out.println("Set the Coordinate format to Incremental notation"); } if (line.startsWith("G54")) { System.out.println("Select aperture"); selectAperture(line); } if (line.startsWith("M02")) { System.out.println("STOP"); return true; } if (line.startsWith("G02")) { drawArc(line); } if (line.startsWith("G03")) { drawArc(line); } if (line.startsWith("X")) { draw(line); } return false; } public boolean processDrill(String line) { this.linenumber++; line = line.trim().toUpperCase(); if (line.startsWith("T")) { if (line.indexOf("C") != -1) { System.out.println("got tool definition! line "+this.linenumber); addTool(line); } else { System.out.println("got tool change! line "+this.linenumber); if (!line.equals("T0")) { selectTool(line); } } } if (line.startsWith("M30")) { System.out.println("STOP"); return true; } if (line.startsWith("X")) { drill(line); } return false; } private void processGerberFile(String filename) { File file = new File(filename); FileReader fr = null; try { fr = new FileReader(file); } catch (Exception e) { System.out.println("Error (1): "+e); } BufferedReader br = new BufferedReader(fr); String line; try { boolean stop = false; this.linenumber = 0; while ((line = br.readLine()) != null && !stop) { stop = processGerber(line); } } catch (Exception e) { System.out.println("Error (2): "+e); e.printStackTrace(); } try { br.close(); } catch (Exception e) { System.out.println("Error (3): "+e); } } private void processDrillFile(String filename) { File file = new File(filename); FileReader fr = null; try { fr = new FileReader(file); } catch (Exception e) { System.out.println("Error (4): "+e); } BufferedReader br = new BufferedReader(fr); String line; try { boolean stop = false; this.linenumber = 0; while ((line = br.readLine()) != null && !stop) { stop = processDrill(line); } } catch (Exception e) { //System.out.println("Error (6): "+); e.printStackTrace(); } try { br.close(); } catch (Exception e) { System.out.println("Error (7): "+e); } } public Apl() { String prefix = dir+project; // process the largest image first, usually the outline. //then use the same image dimensions to make the traces image processGerberFile(prefix+"-Edge_Cuts.gbr"); if (process_NPTH) processDrillFile(prefix+"-NPTH.drl"); processDrillFile(prefix+".drl"); myg.drawAndWritePNG(prefix+"-mill-outline.png", this.ppi, border, true); if (process_B_Cu) processGerberFile(prefix+"-B_Cu.gbl"); if (process_F_Cu) processGerberFile(prefix+"-F_Cu.gtl"); if (process_NPTH) processDrillFile(prefix+"-NPTH.drl"); processDrillFile(prefix+".drl"); myg.drawAndWritePNG(prefix+"-mill-traces.png", this.ppi, border, false); } public static void main(String[] args) { Apl apl = new Apl(); } }
dgonner/gerber2png
src/Apl.java
249,450
import java.util.ArrayList; import java.util.List; /** * Represents a fraction (rational number) in lowest terms. * The numerator can be any integer, and the denominator * can be any non-negative integer. * * @author AP CS A (1 Mar 2018) */ public class Fraction extends Number implements Comparable<Fraction> { private final int num; private final int denom; /** Creates a new Fraction with given numerator and denominator. */ public Fraction(int num, int denom) { if (denom == 0) { throw new IllegalArgumentException("Denominator cannot be 0!"); } if (denom < 0) { // Flip both signs num = -num; denom = -denom; } int gcd = gcd(num, denom); this.num = num/gcd; this.denom = denom/gcd; } /** Creates a random Fraction. */ public Fraction() { this((int)(Math.random()*20-10), // Random num between -10 and 19 (int)(Math.random()*10+1)); // Random denom between 1 and 10 } /** Returns gcd of a and b. */ public static int gcd(int a, int b) { // Note: Very inefficient implementation! int gcd = 1; a = Math.abs(a); b = Math.abs(b); for (int i = 2; i <= a && i <= b; i++) { if (a % i == 0 && b % i == 0) { gcd = i; } } return gcd; } public String toString() { if (denom == 1) { return "" + num; } if (num == 0) { return "0"; } return num + "/" + denom; } public double doubleValue() { return ((double) num) / denom; } public float floatValue() { return ((float) num) / denom; } /** Truncates int division. */ public long longValue() { return num / denom; } /** Truncates int division. */ public int intValue() { return num / denom; } public int compareTo(Fraction f) { double thisD = this.doubleValue(); double thatD = f.doubleValue(); if (thisD > thatD) { return 1; } if (thisD == thatD) { return 0; } return -1; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (!(o instanceof Number)) { return false; } Number n = (Number) o; return this.doubleValue() == n.doubleValue(); } public static void main(String[] args) { Fraction f1 = new Fraction(1, 2); Fraction f2 = new Fraction(-2, -4); Fraction f3 = new Fraction(10, -15); System.out.println("Made " + f1 + " and " + f2 + " and " + f3); System.out.println(f1.compareTo(f2)); List<Fraction> nums = new ArrayList<>(); for (int i = 0; i < 10; i++) { nums.add(new Fraction()); } System.out.println(nums); java.util.Collections.sort(nums); System.out.println(nums); } }
xanderjakeq/simpleTanksClone
Fraction.java
249,453
//Import necessary classes import java.util.Scanner; /** * Student class: Holds 5 fields: First name, Last name, Grade, ID, and ID number. */ public class Student { private String studentFName; private String studentLName; private int studentGrade; private int studentID; private static int studentIDNum; /** * Student class object constructor takes three parameters, studentFName, studentLName, and studentGrade. * Assigning values to each instance of the class object by calling their respective "assign" methods. * @param studentFName * @param studentLName * @param studentGrade */ Student(String studentFName, String studentLName, int studentGrade) { this.studentFName = assignStudentFName(); this.studentLName = assignStudentLName(); this.studentGrade = assignStudentGrade(); this.studentID = studentIDNum; //independently increase the studentIDNum value each time a new "Student" object is made to ensure each student has a unique ID number. studentIDNum++; } /** * The "assignStudentFName" method is used to assign a new "Student" object's "studentFName" String value. * it does this by using a scanner and returning the String value input. * @return */ public String assignStudentFName(){ System.out.println("Student First Name:" ); Scanner scan = new Scanner(System.in); studentFName = scan.nextLine(); return studentFName; } /** * the "getStudentFName" simply retrieves the assigned studentFName value from a "Student" object. * (Getter method) * @return */ public String getStudentFName() { return studentFName; } public void setStudentFName(String studentFName) { this.studentFName = studentFName; } /** * Identical method to "assignStudentFName()" but for the student's assigned last name. * @return */ public String assignStudentLName(){ System.out.println("Student Last Name:"); Scanner scan = new Scanner(System.in); studentLName = scan.nextLine(); return studentLName; } /** * Identical getter method as "getStudentFName()" * @return */ public String getStudentLName() { return studentLName; } public void setStudentLName(String studentLName) { this.studentLName = studentLName; } /** * The "assignStudentGrade" method collects and assigns and integer value to a new "Student" object * by using a scanner. The method then checks to ensure that it is an integer value. If it is, it assigns the value, * otherwise it recursively calls itself until an integer is provided. * @return */ public int assignStudentGrade(){ System.out.println("Student Grade:" ); Scanner scan = new Scanner(System.in); if(scan.hasNextInt()){ studentGrade = scan.nextInt(); }else{ System.out.println("Please enter an integer value."); assignStudentGrade(); } return studentGrade; } /** * the "getStudentGrade" retrieves the assigned studentGrade value from a "Student" object. * @return */ public int getStudentGrade() { return studentGrade; } public void setStudentGrade(int studentGrade) { this.studentGrade = studentGrade; } /** * the "getStudentID" retrieves the assigned studentID value from a "Student" object. * @return */ public int getStudentID() { return studentID; } public int getStudentIDNum(){ return studentIDNum; } public void setStudentID(int studentID) { this.studentID = studentID; } }
FallingSn0w/Gabbie_VLNComPro11SchoolProj
Student.java
249,454
/** * Sign.java - Interface to signs * * @author James */ public class Sign implements ComplexBlock { private OTileEntitySign sign; /** * Creates a sign interface * * @param localSign */ public Sign(OTileEntitySign localSign) { sign = localSign; } /** * Sets the line of text at specified index * * @param index * line * @param text * text */ public void setText(int index, String text) { if (index >= 0 && sign.a.length > index) { sign.a[index] = text; } } /** * Returns the line of text * * @param index * line of text * @return text */ public String getText(int index) { if (index >= 0 && sign.a.length > index) { return sign.a[index]; } return ""; } @Override public int getX() { return sign.l; } @Override public int getY() { return sign.m; } @Override public int getZ() { return sign.n; } @Override public Block getBlock() { return getWorld().getBlockAt(getX(), getY(), getZ()); } @Override public World getWorld() { return this.sign.k.world; } @Override public void update() { getWorld().getWorld().j(getX(), getY(), getZ()); } /** * Returns a String value representing this Block * * @return String representation of this block */ @Override public String toString() { return String.format("Sign [x=%d, y=%d, z=%d]", getX(), getY(), getZ()); } /** * Tests the given object to see if it equals this object * * @param obj * the object to test * @return true if the two objects match */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Sign other = (Sign) obj; if (getX() != other.getX()) { return false; } if (getY() != other.getY()) { return false; } if (getZ() != other.getZ()) { return false; } return true; } /** * Returns a semi-unique hashcode for this block * * @return hashcode */ @Override public int hashCode() { int hash = 7; hash = 97 * hash + getX(); hash = 97 * hash + getY(); hash = 97 * hash + getZ(); return hash; } @Override public NBTTagCompound getMetaTag() { return sign.metadata; } @Override public void writeToTag(NBTTagCompound tag) { sign.b(tag.getBaseTag()); } @Override public void readFromTag(NBTTagCompound tag) { sign.a(tag.getBaseTag()); } }
sarahjean/CanaryClassic
src/Sign.java
249,455
/** * Sign.java - Interface to signs * * @author James */ public class Sign implements ComplexBlock { private jm sign; /** * Creates a sign interface * * @param localav */ public Sign(jm sign) { this.sign = sign; } /** * Sets the line of text at specified index * * @param index * line * @param text * text */ public void setText(int index, String text) { if (index >= 0 && sign.e.length > index) { sign.e[index] = text; } } /** * Returns the line of text * * @param index * line of text * @return text */ public String getText(int index) { if (index >= 0 && sign.e.length > index) { return sign.e[index]; } return ""; } public int getX() { return sign.b; } public int getY() { return sign.c; } public int getZ() { return sign.d; } public void update() { sign.c(); } /** * Returns a String value representing this Block * * @return String representation of this block */ @Override public String toString() { return String.format("Sign[x=%d, y=%d, z=%d, type=%d]", getX(), getY(), getZ()); } /** * Tests the given object to see if it equals this object * * @param obj the object to test * @return true if the two objects match */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Sign other = (Sign) obj; if (this.getX() != other.getX()) { return false; } if (this.getY() != other.getY()) { return false; } if (this.getZ() != other.getZ()) { return false; } return true; } /** * Returns a semi-unique hashcode for this block * * @return hashcode */ @Override public int hashCode() { int hash = 7; hash = 97 * hash + this.getX(); hash = 97 * hash + this.getY(); hash = 97 * hash + this.getZ(); return hash; } }
ScrewTSW/hMod
src/main/java/Sign.java
249,459
// $Id$ /* * CraftBook * Copyright (C) 2010 sk89q <http://www.sk89q.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import com.sk89q.craftbook.BlockType; import com.sk89q.craftbook.CraftBookWorld; import com.sk89q.craftbook.InsufficientArgumentsException; import com.sk89q.craftbook.Vector; import com.sk89q.craftbook.WorldBlockVector; import com.sk89q.craftbook.WorldLocation; /** * Library for Minecraft-related functions. * * @author sk89q */ public class Util { protected static void sendPacketToDimension(OPacket opacket, CraftBookWorld cbworld) { sendPacketToDimension(opacket, cbworld.name(), cbworld.dimension()); } protected static void sendPacketToDimension(OPacket opacket, String worldName, int dimension) { // Notchian: MinecraftServer.getConfigurationManager, func_71203_ab etc.getMCServer().af().sendPacketToDimension(opacket, worldName, dimension); } protected static void sendPacketToPlayersAroundPoint(CraftBookWorld cbworld, double x, double y, double z, double distance, OPacket opacket) { sendPacketToPlayersAroundPoint(cbworld.name(), cbworld.dimension(), x, y, z, distance, opacket); } protected static void sendPacketToPlayersAroundPoint(String worldName, int dimension, double x, double y, double z, double distance, OPacket opacket) { etc.getMCServer().af().a(x, y, z, distance, dimension, opacket, worldName); } protected static void sendPacketToAllPlayers(OPacket opacket) { etc.getMCServer().af().a(opacket); } /** * Gets the block behind a sign. * * @param x * @param y * @param z * @param multiplier * @return */ public static Vector getWallSignBack(CraftBookWorld cbworld, Vector pt, int multiplier) { return getWallSignBack(CraftBook.getWorld(cbworld), pt, multiplier); } public static Vector getWallSignBack(World world, Vector pt, int multiplier) { int x = pt.getBlockX(); int y = pt.getBlockY(); int z = pt.getBlockZ(); if (!world.isChunkLoaded(x, 0, z)) return null; int data = CraftBook.getBlockData(world, x, y, z); if (data == 0x2) { // East return new Vector(x, y, z + multiplier); } else if (data == 0x3) { // West return new Vector(x, y, z - multiplier); } else if (data == 0x4) { // North return new Vector(x + multiplier, y, z); } else { return new Vector(x - multiplier, y, z); } } public static Vector getWallSignBack(CraftBookWorld cbworld, Vector pt, double multiplier) { return getWallSignBack(CraftBook.getWorld(cbworld), pt, multiplier); } public static Vector getWallSignBack(World world, Vector pt, double multiplier) { int x = pt.getBlockX(); int y = pt.getBlockY(); int z = pt.getBlockZ(); if (!world.isChunkLoaded(x, 0, z)) return null; int data = CraftBook.getBlockData(world, x, y, z); if (data == 0x2) { // East return new Vector(x, y, z + multiplier); } else if (data == 0x3) { // West return new Vector(x, y, z - multiplier); } else if (data == 0x4) { // North return new Vector(x + multiplier, y, z); } else { return new Vector(x - multiplier, y, z); } } /** * Gets the block behind a sign. * * @param x * @param y * @param z * @param multiplier * @return */ public static Vector getSignPostOrthogonalBack(CraftBookWorld cbworld, Vector pt, int multiplier) { return getSignPostOrthogonalBack(CraftBook.getWorld(cbworld), pt, multiplier); } public static Vector getSignPostOrthogonalBack(World world, Vector pt, int multiplier) { int x = pt.getBlockX(); int y = pt.getBlockY(); int z = pt.getBlockZ(); int data = CraftBook.getBlockData(world, x, y, z); if (data == 0x8) { // East return new Vector(x, y, z + multiplier); } else if (data == 0x0) { // West return new Vector(x, y, z - multiplier); } else if (data == 0x4) { // North return new Vector(x + multiplier, y, z); } else if (data == 0xC) { // South return new Vector(x - multiplier, y, z); } else { return null; } } /** * Gets the block next to a sign. * * @param x * @param y * @param z * @param multiplier * @return */ public static Vector getWallSignSide(CraftBookWorld cbworld, Vector pt, int multiplier) { return getWallSignSide(CraftBook.getWorld(cbworld), pt, multiplier); } public static Vector getWallSignSide(World world, Vector pt, int multiplier) { int x = pt.getBlockX(); int y = pt.getBlockY(); int z = pt.getBlockZ(); if (!world.isChunkLoaded(x, y, z)) return null; int data = CraftBook.getBlockData(world, x, y, z); if (data == 0x2) { // East return new Vector(x + multiplier, y, z ); } else if (data == 0x3) { // West return new Vector(x - multiplier, y, z); } else if (data == 0x4) { // North return new Vector(x, y, z - multiplier); } else { return new Vector(x, y, z + multiplier); } } /** * Checks whether a sign at a location has a certain text on a * particular line, case in-sensitive. * * @param pt * @param lineNo * @param text * @return */ public static boolean doesSignSay(CraftBookWorld cbworld, Vector pt, int lineNo, String text) { return doesSignSay(CraftBook.getWorld(cbworld), pt, lineNo, text); } public static boolean doesSignSay(World world, Vector pt, int lineNo, String text) { ComplexBlock cBlock = world.getComplexBlock( pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()); if (cBlock instanceof Sign) { Sign sign = (Sign)cBlock; return text.equalsIgnoreCase(sign.getText(lineNo)); } return false; } /** * Checks if a wall sign is next to the input location point * Does not check if wall sign is attached to the point * * @param x * @param y * @param z * @return */ public static Sign getWallSignNextTo(CraftBookWorld cbworld, int x, int y, int z) { return getWallSignNextTo(CraftBook.getWorld(cbworld), x, y, z); } public static Sign getWallSignNextTo(World world, int x, int y, int z) { ComplexBlock cBlock = null; if (CraftBook.getBlockID(world, x+1, y, z) == BlockType.WALL_SIGN) cBlock = world.getComplexBlock(x+1, y, z); else if (CraftBook.getBlockID(world, x-1, y, z) == BlockType.WALL_SIGN) cBlock = world.getComplexBlock(x-1, y, z); else if (CraftBook.getBlockID(world, x, y, z+1) == BlockType.WALL_SIGN) cBlock = world.getComplexBlock(x, y, z+1); else if (CraftBook.getBlockID(world, x, y, z-1) == BlockType.WALL_SIGN) cBlock = world.getComplexBlock(x, y, z-1); if(cBlock != null && cBlock instanceof Sign) { return (Sign)cBlock; } return null; } /** * Gets the rotation of the wall sign * * @param worldType * @param pt * @return */ public static int getWallSignRotation(CraftBookWorld cbworld, Vector pt) { return getWallSignRotation(CraftBook.getWorld(cbworld), pt); } public static int getWallSignRotation(World world, Vector pt) { int x = pt.getBlockX(); int y = pt.getBlockY(); int z = pt.getBlockZ(); int data = CraftBook.getBlockData(world, x, y, z); if (data == 0x2) { // East return 90; } else if (data == 0x3) { // West return 270; } else if (data == 0x4) { // North return 0; } else { return 180; } } /** * Change a block ID to its name. * * @param id * @return */ public static String toBlockName(int id) { com.sk89q.worldedit.blocks.BlockType blockType = com.sk89q.worldedit.blocks.BlockType.fromID(id); if (blockType == null) { return "#" + id; } else { return blockType.getName(); } } /** * Joins a string from an array of strings. * * @param str * @param delimiter * @return */ public static String joinString(String[] str, String delimiter, int initialIndex) { if (str.length == 0) { return ""; } StringBuilder buffer = new StringBuilder(str[initialIndex]); for (int i = initialIndex + 1; i < str.length; i++) { buffer.append(delimiter).append(str[i]); } return buffer.toString(); } /** * Repeat a string. * * @param string * @param num * @return */ public static String repeatString(String str, int num) { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < num; i++) { buffer.append(str); } return buffer.toString(); } /** * Convert a comma-delimited list to a set of integers. * * @param str * @return */ public static Set<Integer> toBlockIDSet(String str) { if (str.trim().length() == 0) { return null; } String[] items = str.split(","); Set<Integer> result = new HashSet<Integer>(); for (String item : items) { try { result.add(Integer.parseInt(item.trim())); } catch (NumberFormatException e) { int id = etc.getDataSource().getItem(item.trim()); if (id != 0) { result.add(id); } else { CraftBookListener.logger.log(Level.WARNING, "CraftBook: Unknown block name: " + item); } } } return result; } /** * Checks to make sure that there are enough but not too many arguments. * * @param args * @param min * @param max -1 for no maximum * @param cmd command name * @throws InsufficientArgumentsException */ public static void checkArgs(String[] args, int min, int max, String cmd) throws InsufficientArgumentsException { if (args.length <= min) { throw new InsufficientArgumentsException("Minimum " + min + " arguments"); } else if (max != -1 && args.length - 1 > max) { throw new InsufficientArgumentsException("Maximum " + max + " arguments"); } } /** * Check if a player can use a command. * * @param player * @param command * @return */ public static boolean canUse(Player player, String command) { return player.canUseCommand(command); } /** * Gets the point in front of the direction * [Note]: It appears player rotations and a few or maybe all other entities * have different rotation values. Ex: player rotation seems to be 90 degrees * off from minecarts. * Hopefully this will change in more updates. * * This follows player rotation. * * @param rotation * @param x * @param y * @param z * @return */ public static Vector getFrontPoint(float rotation, int x, int y, int z) { rotation = rotation % 360; if(rotation < 0) rotation += 360; Vector point = null; if(rotation < 45 || rotation >= 315) { //west point = new Vector(x, y, z + 1); } else if(rotation >= 45 && rotation < 135) { //north point = new Vector(x - 1, y, z); } else if(rotation >= 135 && rotation < 225) { //east point = new Vector(x, y, z - 1); } else if(rotation >= 225 && rotation < 315) { //south point = new Vector(x + 1, y, z); } return point; } public static int getFrontBlockId(CraftBookWorld cbworld, float rotation, int x, int y, int z) { return getFrontBlockId(CraftBook.getWorld(cbworld), rotation, x, y, z); } public static int getFrontBlockId(World world, float rotation, int x, int y, int z) { Vector point = getFrontPoint(rotation, x, y, z); return CraftBook.getBlockID(world, point); } public static String locationToString(Location location) { return location.dimension +","+location.x +","+location.y +","+location.z +","+location.rotX +","+location.rotY ; } public static String worldLocationToString(WorldLocation wLocation) { return wLocation.getCBWorld().name() +","+locationToString(worldLocationToLocation(wLocation)) ; } public static Location stringToLocation(String data) { String[] locData = data.split(",",6); return stringsToLocation(locData); } public static WorldLocation stringToWorldLocation(String data) { String[] locData = data.split(",",7); if(locData.length < 6 || locData[0].isEmpty()) return null; String name = locData[0]; //old format support if(locData.length < 7) { if(locData.length != 6) return null; name = CraftBook.getMainWorldName(); } else { System.arraycopy(locData, 1, locData, 0, 6); } Location location = stringsToLocation(locData); return locationToWorldLocation(new CraftBookWorld(name, location.dimension), location); } public static Location stringsToLocation(String[] data) { if(data.length < 6) return null; Location location = null; try { int dimension = Integer.parseInt(data[0]); double x = Double.parseDouble(data[1]); double y = Double.parseDouble(data[2]); double z = Double.parseDouble(data[3]); float rotation = Float.parseFloat(data[4]); float pitch = Float.parseFloat(data[5]); location = new Location(x, y, z, rotation, pitch); location.dimension = dimension; } catch(NumberFormatException e) { return null; } return location; } public static WorldLocation locationToWorldLocation(CraftBookWorld cbworld, Location location) { if(cbworld == null || location == null) return null; return new WorldLocation(cbworld, location.x, location.y, location.z, location.rotX, location.rotY ); } public static Location worldLocationToLocation(WorldLocation wLocation) { if(wLocation == null) return null; Location location = new Location(wLocation.getX(), wLocation.getY(), wLocation.getZ(), wLocation.rotation(), wLocation.pitch() ); location.world = wLocation.getCBWorld().name(); location.dimension = wLocation.getCBWorld().dimension(); return location; } /** * * @param chunk * @return a copy of the values in the chunk's loadedTileEntityMap in array form */ public static Object[] getLoadedTileEntityList(Chunk chunk){ //Notchian: Chunk.chunkTileEntityMap, Searge: field_76648_i return chunk.chunk.i.values().toArray(); } /** * * @param wbv * @return true, if the block specified by the WorldBlockVector is currently loaded, false otherwise. */ public static boolean isBlockLoaded(WorldBlockVector wbv) { return ( etc.getServer().isWorldLoaded(wbv.getCBWorld().name()) && CraftBook.getWorld(wbv.getCBWorld()) .isChunkLoaded(wbv.getBlockX(), wbv.getBlockY(), wbv.getBlockZ()) ); } @SuppressWarnings("unchecked") public static List<Object>[] getEntityLists(Chunk chunk) { if (!chunk.isLoaded()) return null; //Notchian: List[] Chunk.entityLists, Searge: field_76645_j return chunk.getChunk().j; } public static boolean chunkHasEntities(Chunk chunk) { if (!chunk.isLoaded()) return false; //Notchian: Chunk.hasEntities, Searge: field_76644_m return chunk.getChunk().m; } /** get a spot that player can stand in up to 10 blocks above a given point * * @param cbworld * @param pos * @return Y-value of the safe location */ public static int getSafeYAbove(CraftBookWorld cbworld, Vector pos) { return getSafeYAbove(CraftBook.getWorld(cbworld), pos); } /** get a spot that player can stand in up to 10 blocks above a given point * * @param world * @param pos * @return Y-value of the safe location */ public static int getSafeYAbove(World world, Vector pos) { int maxY = Math.min(CraftBook.MAP_BLOCK_HEIGHT, pos.getBlockY() + 10); int x = pos.getBlockX(); int z = pos.getBlockZ(); for (int y = pos.getBlockY() + 1; y <= maxY; y++) { if (BlockType.canPassThrough(CraftBook.getBlockID(world, x, y, z)) && y < CraftBook.MAP_BLOCK_HEIGHT && BlockType.canPassThrough(CraftBook.getBlockID(world, x, y + 1, z))) { return y; } } return maxY; } }
CraftBook-Extra/craftbook
src/Util.java
249,460
// $Id$ /* * CraftBook * Copyright (C) 2010 sk89q <http://www.sk89q.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import com.sk89q.craftbook.InsufficientArgumentsException; import com.sk89q.craftbook.Vector; /** * Library for Minecraft-related functions. * * @author sk89q */ public class Util { /** * Gets the block behind a sign. * * @param x * @param y * @param z * @param multiplier * @return */ public static Vector getWallSignBack(Vector pt, int multiplier) { int x = pt.getBlockX(); int y = pt.getBlockY(); int z = pt.getBlockZ(); int data = CraftBook.getBlockData(x, y, z); if (data == 0x2) { // East return new Vector(x, y, z + multiplier); } else if (data == 0x3) { // West return new Vector(x, y, z - multiplier); } else if (data == 0x4) { // North return new Vector(x + multiplier, y, z); } else { return new Vector(x - multiplier, y, z); } } /** * Gets the block behind a sign. * * @param x * @param y * @param z * @param multiplier * @return */ public static Vector getSignPostOrthogonalBack(Vector pt, int multiplier) { int x = pt.getBlockX(); int y = pt.getBlockY(); int z = pt.getBlockZ(); int data = CraftBook.getBlockData(x, y, z); if (data == 0x0) { // West return new Vector(x, y, z - multiplier); } else if (data == 0x2) { return new Vector(x + multiplier, y, z - multiplier); } else if (data == 0x4) { // North return new Vector(x + multiplier, y, z); } else if (data == 0x5) { return new Vector(x + multiplier, y, z + multiplier); } else if (data == 0x8) { // East return new Vector(x, y, z + multiplier); } else if (data == 0xA) { return new Vector(x - multiplier, y, z + multiplier); } else if (data == 0xC) { // South return new Vector(x - multiplier, y, z); } else if (data == 0xE) { return new Vector(x - multiplier, y, z - multiplier); } else { return null; } } /** * Gets the block next to a sign. * * @param x * @param y * @param z * @param multiplier * @return */ public static Vector getWallSignSide(Vector pt, int multiplier) { int x = pt.getBlockX(); int y = pt.getBlockY(); int z = pt.getBlockZ(); int data = CraftBook.getBlockData(x, y, z); if (data == 0x2) { // East return new Vector(x + multiplier, y, z ); } else if (data == 0x3) { // West return new Vector(x - multiplier, y, z); } else if (data == 0x4) { // North return new Vector(x, y, z - multiplier); } else { return new Vector(x, y, z + multiplier); } } /** * Checks whether a sign at a location has a certain text on a * particular line, case in-sensitive. * * @param pt * @param lineNo * @param text * @return */ public static boolean doesSignSay(Vector pt, int lineNo, String text) { ComplexBlock cBlock = etc.getServer().getComplexBlock( pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()); if (cBlock instanceof Sign) { Sign sign = (Sign)cBlock; return text.equalsIgnoreCase(sign.getText(lineNo)); } return false; } /** * Change a block ID to its name. * * @param id * @return */ public static String toBlockName(int id) { com.sk89q.worldedit.blocks.BlockType blockType = com.sk89q.worldedit.blocks.BlockType.fromID(id); if (blockType == null) { return "#" + id; } else { return blockType.getName(); } } /** * Joins a string from an array of strings. * * @param str * @param delimiter * @return */ public static String joinString(String[] str, String delimiter, int initialIndex) { if (str.length == 0) { return ""; } StringBuilder buffer = new StringBuilder(str[initialIndex]); for (int i = initialIndex + 1; i < str.length; i++) { buffer.append(delimiter).append(str[i]); } return buffer.toString(); } /** * Repeat a string. * * @param string * @param num * @return */ public static String repeatString(String str, int num) { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < num; i++) { buffer.append(str); } return buffer.toString(); } /** * Convert a comma-delimited list to a set of integers. * * @param str * @return */ public static Set<Integer> toBlockIDSet(String str) { if (str.trim().length() == 0) { return null; } String[] items = str.split(","); Set<Integer> result = new HashSet<Integer>(); for (String item : items) { try { result.add(Integer.parseInt(item.trim())); } catch (NumberFormatException e) { int id = etc.getDataSource().getItem(item.trim()); if (id != 0) { result.add(id); } else { CraftBookListener.logger.log(Level.WARNING, "CraftBook: Unknown block name: " + item); } } } return result; } /** * Checks to make sure that there are enough but not too many arguments. * * @param args * @param min * @param max -1 for no maximum * @param cmd command name * @throws InsufficientArgumentsException */ public static void checkArgs(String[] args, int min, int max, String cmd) throws InsufficientArgumentsException { if (args.length <= min) { throw new InsufficientArgumentsException("Minimum " + min + " arguments"); } else if (max != -1 && args.length - 1 > max) { throw new InsufficientArgumentsException("Maximum " + max + " arguments"); } } /** * Check if a player can use a command. * * @param player * @param command * @return */ public static boolean canUse(Player player, String command) { return player.canUseCommand(command); } }
FeepingCreature/craftbook
src/Util.java
249,465
class Solution { public int solution(int[] absolutes, boolean[] signs) { int num = absolutes.length; int answer = 0; for(i=0;i<num;i++){ if(signs[i]=1){ answer =+ absolutes[i]; }else{ answer =- absolutes[i]; } } return answer; } }
HanaHww2/WWW
programmers/programmers_addYinAndYang/76501.java
249,466
public class Seat { String seatId; boolean assigned; public Seat(){} public Seat(String seatId,boolean assigned){ this.seatId=seatId; this.assigned=assigned; } public String getSeatID(){return seatId;} public boolean isAssigned(){return assigned;} public void unAssigned(){assigned=false;} public void AssignSeat(){assigned = true;} public void unAssignSeat(){ assigned = false;} }
Pratyum/CE2002-Assignment
src/Seat.java
249,467
/* String parsing */ /* Atoi */ c class Solution { public int atoi(final String A) { int result = 0; boolean neg = false; // iterate through the whole string for (int i=0; i<A.length(); i++) { // check for positive and negative signs if(i == 0 && A.charAt(i) == '+') { // skip to next charactr immediately to check for number continue; } else if (i == 0 && A.charAt(i) == '-') { // make whole result negative neg = true; } else if (Character.isDigit(A.charAt(i))) { int current = Character.getNumericValue(A.charAt(i)); // check for overflows before multiplying // negative if (neg) { if ((result * -1) >= (Integer.MIN_VALUE / 10)) { result = result * 10; } else { result = Integer.MIN_VALUE; break; } } // positive else { if (result <= Integer.MAX_VALUE / 10) { result = result * 10; } else { result = Integer.MAX_VALUE; break; } } // check for overflows before adding // negative if (neg) { if ( (result * -1) >= (Integer.MIN_VALUE + current) ) { result += current; } else { result = Integer.MIN_VALUE; break; } } // positive else { if (result <= Integer.MAX_VALUE - 10) { result += current; } else { result = Integer.MAX_VALUE; break; } } } else { break; } } if (neg && result != Integer.MIN_VALUE) { result = result * -1; } return result; } }
htoo97/codepath-interview-1_before_session
atoi.java
249,468
class Solution { public static int solution(int[] absolutes, boolean[] signs) { int sum=0; for(int i=0;i<absolutes.length;i++){ sum+= signs[i]==true ? absolutes[i] : -absolutes[i]; } return sum; } }
DragonSky2357/today-algorithm
26.java
249,471
/* * Copyright (C) 2012 by the Massachusetts Institute of Technology. * All rights reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * * Original source developed by yaSSL (http://www.yassl.com) * * Description: * * A simple client application which uses the MIT Kerberos Java GSS-API * SWIG wrapper. The following actions are taken by the client: * a) Establish a GSSAPI context with the example server * b) Signs and encrypts, and sends a message to the server using * gss_wrap. * c) Verifies the signature block returned by the server with * gss_verify_mic. * d) Repeat steps b) and c) but using gss_seal / gss_verify * e) Perform misc. GSSAPI function tests * */ import java.io.*; import java.net.*; import edu.mit.kerberos.*; public class client implements gsswrapperConstants { /* Global GSS-API context */ public static gss_ctx_id_t_desc context = new gss_ctx_id_t_desc(); public static void main(String argv[]) throws Exception { /* Return/OUTPUT variables */ long maj_status = 0; long[] min_status = {0}; long[] ret_flags = {0}; long[] time_rec = {0}; int ret = 0; int port = 11115; String server = "127.0.0.1"; String clientName = "myuser"; String serviceName = "[email protected]"; /* Customize this if a specific mechanisms should be negotiated, otherwise set neg_mech_set to GSS_C_NO_OID_SET */ gss_OID_set_desc neg_mech_set = new gss_OID_set_desc(); gss_OID_desc neg_mech = new gss_OID_desc("{ 1 2 840 113554 1 2 2 }"); maj_status = gsswrapper.gss_add_oid_set_member(min_status, neg_mech, neg_mech_set); if (maj_status != GSS_S_COMPLETE) { Util.displayError("adding oid to set", min_status, maj_status); System.exit(1); } Socket clientSocket = null; OutputStream serverOut = null; InputStream serverIn = null; String serverMsg; /* testing gss_oid_to_str */ gss_buffer_desc buffer = new gss_buffer_desc(); maj_status = gsswrapper.gss_oid_to_str(min_status, gsswrapper.getGSS_C_NT_EXPORT_NAME(), buffer); if (maj_status != GSS_S_COMPLETE) { Util.errorExit("Error calling gss_oid_to_str", min_status, maj_status); } gsswrapper.gss_release_buffer(min_status, buffer); /* create socket to connect to the server */ try { clientSocket = new Socket(server, port); System.out.println("Connected to " + server + " at port " + port); /* get input and output streams */ serverOut = clientSocket.getOutputStream(); serverIn = clientSocket.getInputStream(); } catch (UnknownHostException e) { System.err.println("Unknown host: " + server); e.printStackTrace(); } catch (IOException e) { System.err.println("I/O error for the connection to " + server); e.printStackTrace(); } /* Stores created context in global static "context" variable */ ret = Authenticate(clientSocket, serverIn, serverOut, clientName, serviceName, neg_mech_set); if (ret == 0) { System.out.println("Finished Authentication"); ret = PrintContextInfo(); if (ret == 0) { ret = Communicate(clientSocket, serverIn, serverOut); if (ret == 0) { System.out.println("Finished first communication with " + "server"); ret = AltCommunicate(clientSocket, serverIn, serverOut); if (ret == 0) { System.out.println("Finished second communication " + "with server"); ret = MiscFunctionTests(); } else { System.out.println("Failed during second " + "communication with server"); } } else { System.out.println("Failed during first communication " + "with server"); } } else { System.out.println("Failed during PrintContextInfo()"); } } else { System.out.println("Failed during Authentication"); } if (ret == 0) { System.out.println("SUCCESS!"); gss_buffer_desc output_token = GSS_C_NO_BUFFER; gss_OID_desc tmp = context.getMech_type(); maj_status = gsswrapper.gss_delete_sec_context(min_status, context, output_token); if (maj_status != GSS_S_COMPLETE) { Util.displayError("deleting security context", min_status, maj_status); } gsswrapper.gss_release_buffer(min_status, output_token); } else { System.out.println("FAILURE!"); } gsswrapper.gss_release_oid(min_status, neg_mech); gsswrapper.gss_release_oid_set(min_status, neg_mech_set); serverIn.close(); serverOut.close(); clientSocket.close(); } public static int Authenticate(Socket clientSocket, InputStream serverIn, OutputStream serverOut, String inClientName, String inServiceName, gss_OID_set_desc neg_mech_set) { long maj_status = 0; long[] min_status = {0}; gss_name_t_desc clientName = new gss_name_t_desc(); gss_name_t_desc serverName = new gss_name_t_desc(); gss_cred_id_t_desc clientCredentials = GSS_C_NO_CREDENTIAL; gss_ctx_id_t_desc context_tmp = GSS_C_NO_CONTEXT; long[] actualFlags = {0}; int err = 0; int ret[] = {0}; long[] time_rec = {0}; /* kerberos v5 */ gss_OID_desc gss_mech_krb5 = new gss_OID_desc("1.2.840.113554.1.2.2"); byte[] inputTokenBuffer = null; gss_buffer_desc inputToken = new gss_buffer_desc(); System.out.println("Authenticating [client]"); /* Testing gss_indicate_mechs */ gss_OID_set_desc mech_set = GSS_C_NO_OID_SET; maj_status = gsswrapper.gss_indicate_mechs(min_status, mech_set); if (maj_status != GSS_S_COMPLETE) { Util.displayError("gss_indicate_mechs(mech_set)", min_status, maj_status); return -1; } maj_status = gsswrapper.gss_release_oid_set(min_status, mech_set); if (maj_status != GSS_S_COMPLETE) { Util.displayError("gss_release_mechs(mech_set)", min_status, maj_status); return -1; } /* Client picks client principal it wants to use. Only done if we * know what client principal will get the service principal we need. */ if (inClientName != null) { gss_buffer_desc nameBuffer = new gss_buffer_desc(); nameBuffer.setLength(inClientName.length()); nameBuffer.setValue(inClientName); maj_status = gsswrapper.gss_import_name(min_status, nameBuffer, gsswrapper.getGSS_C_NT_USER_NAME(), clientName); if (maj_status != GSS_S_COMPLETE) { Util.displayError("gss_import_name(inClientName)", min_status, maj_status); return -1; } maj_status = gsswrapper.gss_acquire_cred(min_status, clientName, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, GSS_C_INITIATE, clientCredentials, null, time_rec); if (maj_status != GSS_S_COMPLETE) { Util.displayError("gss_acquire_cred", min_status, maj_status); gsswrapper.gss_release_cred(min_status, clientCredentials); return -1; } /* Did we want a specific mechanism to be used? */ if (neg_mech_set != GSS_C_NO_OID_SET) { maj_status = gsswrapper.gss_set_neg_mechs(min_status, clientCredentials, neg_mech_set); if (maj_status != GSS_S_COMPLETE) { Util.displayError("setting negotiation mechanism", min_status, maj_status); return -1; } else { System.out.println("Successfully set neg. mechanism"); } } } /* checking for valid import. Remember to run "kinit <clientName>" */ long[] lifetime = {0}; int[] cred_usage = {0}; gss_name_t_desc name = new gss_name_t_desc(); gss_OID_set_desc temp_mech_set = new gss_OID_set_desc(); maj_status = gsswrapper.gss_inquire_cred(min_status, clientCredentials, name, lifetime, cred_usage, temp_mech_set); if (maj_status != GSS_S_COMPLETE) { Util.displayError("gss_inquire_cred(temp_mech_set)", min_status, maj_status); return -1; } maj_status = gsswrapper.gss_release_oid_set(min_status, temp_mech_set); if (maj_status != GSS_S_COMPLETE) { Util.displayError("gss_release_oid_set(temp_mech_set)", min_status, maj_status); return -1; } /* Test gss_duplicate_name function */ gss_name_t_desc clientName_dup = new gss_name_t_desc(); maj_status = gsswrapper.gss_duplicate_name(min_status, clientName, clientName_dup); if (maj_status != GSS_S_COMPLETE) { Util.displayError("duplicating client name", min_status, maj_status); return -1; } gsswrapper.gss_release_name(min_status, clientName_dup); /* Test gss_canonicalize_name function */ gss_name_t_desc clientCanonicalized = new gss_name_t_desc(); maj_status = gsswrapper.gss_canonicalize_name(min_status, clientName, gss_mech_krb5, clientCanonicalized); if (maj_status != GSS_S_COMPLETE) { Util.displayError("canonicalizing client name", min_status, maj_status); return -1; } /* Test gss_export_name function */ gss_buffer_desc clientName_export = new gss_buffer_desc(); maj_status = gsswrapper.gss_export_name(min_status, clientCanonicalized, clientName_export); if (maj_status != GSS_S_COMPLETE) { Util.displayError("exporting client name", min_status, maj_status); return -1; } gsswrapper.gss_release_name(min_status, clientCanonicalized); gsswrapper.gss_release_buffer(min_status, clientName_export); /* Client picks the service principal it will try to use to connect * to the server. The server principal is given at the top of this * file.*/ gss_buffer_desc nameBuffer = new gss_buffer_desc(); nameBuffer.setLength(inServiceName.length()); nameBuffer.setValue(inServiceName); maj_status = gsswrapper.gss_import_name(min_status, nameBuffer, gsswrapper.getGSS_C_NT_HOSTBASED_SERVICE(), serverName); if (maj_status != GSS_S_COMPLETE) { Util.displayError("gss_import_name(inServiceName)", min_status, maj_status); return -1; } /* The main authentication loop. Because GSS is a multimechanism * API, we need to loop calling gss_init_sec_context - passing * in the "input tokens" received from the server and send the * resulting "output tokens" back until we get GSS_S_COMPLETE * or an error. */ maj_status = GSS_S_CONTINUE_NEEDED; while (maj_status != GSS_S_COMPLETE) { gss_buffer_desc outputToken = new gss_buffer_desc(); outputToken.setLength(0); outputToken.setValue(null); long requestedFlags = ( GSS_C_MUTUAL_FLAG ^ GSS_C_REPLAY_FLAG ^ GSS_C_SEQUENCE_FLAG ^ GSS_C_CONF_FLAG ^ GSS_C_INTEG_FLAG ); System.out.println("Calling gss_init_sec_context..."); gss_OID_desc actual_mech_type = new gss_OID_desc(); maj_status = gsswrapper.gss_init_sec_context(min_status, clientCredentials, context_tmp, serverName, GSS_C_NO_OID, requestedFlags, GSS_C_INDEFINITE, GSS_C_NO_CHANNEL_BINDINGS, inputToken, actual_mech_type, outputToken, actualFlags, time_rec); if (outputToken.getLength() > 0) { /* * Send the output token to the server (even on error), * using a Java byte[] */ byte[] temp_token = new byte[(int)outputToken.getLength()]; temp_token = gsswrapper.getDescArray(outputToken); System.out.println("Generated Token Length = " + temp_token.length); err = Util.WriteToken(serverOut, temp_token); /* free the output token */ gsswrapper.gss_release_buffer(min_status, outputToken); } if (err == 0) { if (maj_status == GSS_S_CONTINUE_NEEDED) { /* Protocol requires another packet exchange */ System.out.println("Protocol requires another " + "packet exchange"); /* Clean up old input buffer */ if (inputTokenBuffer != null) inputTokenBuffer = null; /* Read another input token from the server */ inputTokenBuffer = Util.ReadToken(serverIn); if (inputTokenBuffer != null) { gsswrapper.setDescArray(inputToken, inputTokenBuffer); inputToken.setLength(inputTokenBuffer.length); System.out.println("Received Token Length = " + inputToken.getLength()); } } else if (maj_status != GSS_S_COMPLETE) { Util.displayError("gss_init_sec_context", min_status, maj_status); return -1; } } } /* end while loop */ /* Test gss_compare_name - client and server names should differ */ maj_status = gsswrapper.gss_compare_name(min_status, clientName, serverName, ret); if (ret[0] == 1) { System.out.println("TEST: clientName == serverName"); } else { System.out.println("TEST: clientName != serverName"); } /* Save our context */ context = context_tmp; return 0; } /* end Authenticate() */ public static int Communicate(Socket clientSocket, InputStream serverIn, OutputStream serverOut) { long maj_status = 0; long[] min_status = {0}; long[] qop_state = {0}; int[] state = {0}; int err = 0; gss_buffer_desc in_buf = new gss_buffer_desc("Hello Server!"); gss_buffer_desc out_buf = new gss_buffer_desc(); byte[] sigBlockBuffer = null; System.out.println("Beginning communication with server"); /* Sign and encrypt plain message */ maj_status = gsswrapper.gss_wrap(min_status, context, 1, GSS_C_QOP_DEFAULT, in_buf, state, out_buf); if (maj_status != GSS_S_COMPLETE) { Util.displayError("wrapping message, gss_wrap", min_status, maj_status); return -1; } else if (state[0] == 0) { System.out.println("Warning! Message not encrypted."); } /* Send wrapped message to server */ byte[] temp_token = new byte[(int)out_buf.getLength()]; temp_token = gsswrapper.getDescArray(out_buf); err = Util.WriteToken(serverOut, temp_token); if (err != 0) { System.out.println("Error sending wrapped message to " + "server, WriteToken"); return -1; } /* Read signature block from the server */ sigBlockBuffer = Util.ReadToken(serverIn); if (sigBlockBuffer != null) { gsswrapper.setDescArray(out_buf, sigBlockBuffer); out_buf.setLength(sigBlockBuffer.length); } /* Verify signature block */ maj_status = gsswrapper.gss_verify_mic(min_status, context, in_buf, out_buf, qop_state); if (maj_status != GSS_S_COMPLETE) { Util.displayError("verifying signature, gss_verify_mic", min_status, maj_status); return -1; } else { System.out.println("Signature Verified"); } gsswrapper.gss_release_buffer(min_status, in_buf); gsswrapper.gss_release_buffer(min_status, out_buf); return 0; } /* end Communicate() */ public static int AltCommunicate(Socket clientSocket, InputStream serverIn, OutputStream serverOut) { long maj_status = 0; long[] min_status = {0}; int[] qop_state = {0}; int[] state = {0}; int err = 0; gss_buffer_desc in_buf = new gss_buffer_desc("Hello Server!"); gss_buffer_desc out_buf = new gss_buffer_desc(); byte[] sigBlockBuffer = null; gss_buffer_desc context_token = new gss_buffer_desc(); /* Test context export/import functions */ maj_status = gsswrapper.gss_export_sec_context(min_status, context, context_token); if (maj_status != GSS_S_COMPLETE) { Util.displayError("exporting security context", min_status, maj_status); return -1; } else { System.out.println("Successfully exported security context"); } maj_status = gsswrapper.gss_import_sec_context(min_status, context_token, context); if (maj_status != GSS_S_COMPLETE) { Util.displayError("importing security context", min_status, maj_status); return -1; } else { System.out.println("Successfully imported security context"); } gsswrapper.gss_release_buffer(min_status, context_token); /* Sign and encrypt plain message */ maj_status = gsswrapper.gss_seal(min_status, context, 1, GSS_C_QOP_DEFAULT, in_buf, state, out_buf); if (maj_status != GSS_S_COMPLETE) { Util.displayError("wrapping message, gss_seal", min_status, maj_status); return -1; } else if (state[0] == 0) { System.out.println("Warning! Message not encrypted."); } /* Send wrapped message to server */ byte[] temp_token = new byte[(int)out_buf.getLength()]; temp_token = gsswrapper.getDescArray(out_buf); err = Util.WriteToken(serverOut, temp_token); if (err != 0) { System.out.println("Error sending wrapped message to " + "server, WriteToken"); return -1; } /* Read signature block from the server */ sigBlockBuffer = Util.ReadToken(serverIn); if (sigBlockBuffer != null) { gsswrapper.setDescArray(out_buf, sigBlockBuffer); out_buf.setLength(sigBlockBuffer.length); } /* Verify signature block */ maj_status = gsswrapper.gss_verify(min_status, context, in_buf, out_buf, qop_state); if (maj_status != GSS_S_COMPLETE) { Util.displayError("verifying signature, gss_verify", min_status, maj_status); return -1; } else { System.out.println("Signature Verified"); } gsswrapper.gss_release_buffer(min_status, in_buf); gsswrapper.gss_release_buffer(min_status, out_buf); return 0; } /* end AltCommunicate() */ public static int PrintContextInfo() { long maj_status = 0; long[] min_status = {0}; gss_name_t_desc src_name = new gss_name_t_desc(); gss_name_t_desc targ_name = new gss_name_t_desc(); gss_buffer_desc sname = new gss_buffer_desc(); gss_buffer_desc tname = new gss_buffer_desc(); gss_buffer_desc oid_name = new gss_buffer_desc(); gss_buffer_desc sasl_mech_name = new gss_buffer_desc(); gss_buffer_desc mech_name = new gss_buffer_desc(); gss_buffer_desc mech_description = new gss_buffer_desc(); long lifetime[] = {0}; long[] time_rec = {0}; gss_OID_desc mechanism = new gss_OID_desc(); gss_OID_desc name_type = new gss_OID_desc(); gss_OID_desc oid = new gss_OID_desc(); long context_flags[] = {0}; int is_local[] = {0}; int is_open[] = {0}; gss_OID_set_desc mech_names = new gss_OID_set_desc(); gss_OID_set_desc mech_attrs = new gss_OID_set_desc(); gss_OID_set_desc known_attrs = new gss_OID_set_desc(); /* Get context information */ maj_status = gsswrapper.gss_inquire_context(min_status, context, src_name, targ_name, lifetime, mechanism, context_flags, is_local, is_open); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Inquiring context: gss_inquire_context", min_status, maj_status); return -1; } /* Check if our context is still valid */ maj_status = gsswrapper.gss_context_time(min_status, context, time_rec); if (maj_status != GSS_S_COMPLETE) { Util.displayError("checking for valid context", min_status, maj_status); return -1; } /* Get context source name */ maj_status = gsswrapper.gss_display_name(min_status, src_name, sname, name_type); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Displaying source name: gss_display_name", min_status, maj_status); return -1; } /* Get context target name */ maj_status = gsswrapper.gss_display_name(min_status, targ_name, tname, name_type); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Displaying target name: gss_display_name", min_status, maj_status); return -1; } System.out.println("------------- Context Information ---------------"); System.out.println("Context is Valid for another " + time_rec[0] + " seconds"); System.out.println(sname.getValue() + " to " + tname.getValue()); System.out.println("Lifetime: " + lifetime[0] + " seconds"); System.out.println("Flags: " + context_flags[0]); System.out.println("Initiated: " + ((is_local[0] == 1) ? "locally" : "remotely")); System.out.println("Status: " + ((is_open[0] == 1) ? "open" : "closed")); gsswrapper.gss_release_name(min_status, src_name); gsswrapper.gss_release_name(min_status, targ_name); gsswrapper.gss_release_buffer(min_status, sname); gsswrapper.gss_release_buffer(min_status, tname); maj_status = gsswrapper.gss_oid_to_str(min_status, name_type, oid_name); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Converting oid->string: gss_oid_to_str", min_status, maj_status); return -1; } System.out.println("Name type of source name: " + oid_name.getValue()); gsswrapper.gss_release_buffer(min_status, oid_name); /* Get mechanism attributes */ maj_status = gsswrapper.gss_inquire_attrs_for_mech(min_status, mechanism, mech_attrs, known_attrs); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Inquiring mechanism attributes", min_status, maj_status); return -1; } System.out.println(" Mechanism Attributes:"); for (int j = 0; j < mech_attrs.getCount(); j++) { gss_buffer_desc name = new gss_buffer_desc(); gss_buffer_desc short_desc = new gss_buffer_desc(); gss_buffer_desc long_desc = new gss_buffer_desc(); maj_status = gsswrapper.gss_display_mech_attr(min_status, mech_attrs.getElement(j), name, short_desc, long_desc); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Displaying mechanism attributes", min_status, maj_status); return -1; } System.out.println(" " + name.getValue()); gsswrapper.gss_release_buffer(min_status, name); gsswrapper.gss_release_buffer(min_status, short_desc); gsswrapper.gss_release_buffer(min_status, long_desc); } /* Get known attributes */ System.out.println(" Known Attributes:"); for (int k = 0; k < known_attrs.getCount(); k++) { gss_buffer_desc name = new gss_buffer_desc(); gss_buffer_desc short_desc = new gss_buffer_desc(); gss_buffer_desc long_desc = new gss_buffer_desc(); maj_status = gsswrapper.gss_display_mech_attr(min_status, known_attrs.getElement(k), name, short_desc, long_desc); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Displaying known attributes", min_status, maj_status); return -1; } System.out.println(" " + name.getValue()); gsswrapper.gss_release_buffer(min_status, name); gsswrapper.gss_release_buffer(min_status, short_desc); gsswrapper.gss_release_buffer(min_status, long_desc); } gsswrapper.gss_release_oid_set(min_status, mech_attrs); gsswrapper.gss_release_oid_set(min_status, known_attrs); /* Get names supported by the mechanism */ maj_status = gsswrapper.gss_inquire_names_for_mech(min_status, mechanism, mech_names); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Inquiring mech names", min_status, maj_status); return -1; } maj_status = gsswrapper.gss_oid_to_str(min_status, mechanism, oid_name); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Converting oid->string", min_status, maj_status); return -1; } System.out.println("Mechanism " + oid_name.getValue() + " supports " + mech_names.getCount() + " names"); for (int i = 0; i < mech_names.getCount(); i++) { maj_status = gsswrapper.gss_oid_to_str(min_status, mech_names.getElement(i), oid_name); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Converting oid->string", min_status, maj_status); return -1; } System.out.println(" " + i + ": " + oid_name.getValue()); gsswrapper.gss_release_buffer(min_status, oid_name); } gsswrapper.gss_release_oid_set(min_status, mech_names); /* Get SASL mech */ maj_status = gsswrapper.gss_inquire_saslname_for_mech(min_status, mechanism, sasl_mech_name, mech_name, mech_description); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Inquiring SASL name", min_status, maj_status); return -1; } System.out.println("SASL mech: " + sasl_mech_name.getValue()); System.out.println("Mech name: " + mech_name.getValue()); System.out.println("Mech desc: " + mech_description.getValue()); /* Inquire Mech for SASL name - to test */ maj_status = gsswrapper.gss_inquire_mech_for_saslname(min_status, sasl_mech_name, oid); if (maj_status != GSS_S_COMPLETE) { Util.displayError("Inquiring mechs for SASL name", min_status, maj_status); return -1; } if (oid == GSS_C_NO_OID) { System.out.println("Got different OID for mechanism"); } /* Determine largest message that can be wrapped, assuming max output token size of 100 (just for testing) */ long[] max_size = {0}; maj_status = gsswrapper.gss_wrap_size_limit(min_status, context, 1, GSS_C_QOP_DEFAULT, 100, max_size); if (maj_status != GSS_S_COMPLETE) { Util.displayError("determining largest wrapped message size", min_status, maj_status); return -1; } else { System.out.println("Largest message size able to be wrapped: " + max_size[0]); } gsswrapper.gss_release_buffer(min_status, sasl_mech_name); gsswrapper.gss_release_buffer(min_status, mech_name); gsswrapper.gss_release_buffer(min_status, mech_description); gsswrapper.gss_release_oid(min_status, oid); System.out.println("-------------------------------------------------"); return 0; } public static int MiscFunctionTests() { long maj_status = 0; long[] min_status = {0}; gss_cred_id_t_desc cred_handle = GSS_C_NO_CREDENTIAL; /* kerberos v5 */ gss_OID_desc mech_type = new gss_OID_desc("1.2.840.113554.1.2.2"); gss_name_t_desc name = new gss_name_t_desc(); long[] init_lifetime = {0}; long[] accept_lifetime = {0}; int[] cred_usage = {0}; System.out.println("------------------- MISC TESTS ------------------"); /* * FUNCTION: gss_inquire_cred_by_mech * Get info about default cred for default security mech. */ maj_status = gsswrapper.gss_inquire_cred_by_mech(min_status, cred_handle, mech_type, name, init_lifetime, accept_lifetime, cred_usage); if (maj_status != GSS_S_COMPLETE) { Util.displayError("inquiring credential info from mech", min_status, maj_status); return -1; } else { System.out.println("Credential Principal Name: " + name.getExternal_name().getValue()); System.out.println("Credential Valid for Initiating Contexts for " + init_lifetime[0] + " seconds"); System.out.println("Credential Valid for Accepting Contexts for " + accept_lifetime[0] + " seconds"); System.out.println("Credential Usage: " + cred_usage[0]); } /* FUNCTION: gss_pseudo_random */ gss_buffer_desc prf_out = new gss_buffer_desc(); gss_buffer_desc prf_in = new gss_buffer_desc("gss prf test"); maj_status = gsswrapper.gss_pseudo_random(min_status, context, 0, prf_in, 19, prf_out); if (maj_status != GSS_S_COMPLETE) { Util.displayError("testing gss_pseudo_random function", min_status, maj_status); return -1; } gsswrapper.gss_release_buffer(min_status, prf_out); gsswrapper.gss_release_buffer(min_status, prf_in); /* FUNCTION: gss_indicate_mechs_by_attrs */ gss_OID_set_desc desired_mech_attrs = GSS_C_NO_OID_SET; gss_OID_set_desc except_mech_attrs = GSS_C_NO_OID_SET; gss_OID_set_desc critical_mech_attrs = GSS_C_NO_OID_SET; gss_OID_set_desc mechs = new gss_OID_set_desc(); maj_status = gsswrapper.gss_indicate_mechs_by_attrs(min_status, desired_mech_attrs, except_mech_attrs, critical_mech_attrs, mechs); if (maj_status != GSS_S_COMPLETE) { Util.displayError("gss_indicate_mechs_by_attrs", min_status, maj_status); return -1; } System.out.println("-------------------------------------------------"); return 0; } }
kaduk/kerberos-java-gssapi
client.java
249,472
public class ATOI { public static int myAtoi(String s) { int i = 0; int n = s.length(); while (i < n && s.charAt(i) == ' ') { // skipping space characters at the beginning i++; } int positive = 0; int negative = 0; if (i < n && s.charAt(i) == '+') { positive++; // number of positive signs at the start in string i++; } if (i < n && s.charAt(i) == '-') { negative++; // number of negative signs at the start in string i++; } double ans = 0; while (i < n && s.charAt(i) >= '0' && s.charAt(i) <= '9') { ans = ans * 10 + (s.charAt(i) - '0'); // (s.charAt(i) - '0') is converting character to integer i++; } if (negative > 0) { // if negative sign exists ans = -ans; } if (positive > 0 && negative > 0) { // if both +ve and -ve sign exist, Example: +-12 return 0; } int INT_MAX = (int) Math.pow(2, 31) - 1; int INT_MIN = (int) Math.pow(-2, 31); if (ans > INT_MAX) { // if ans > 2^31 - 1 ans = INT_MAX; } if (ans < INT_MIN) { // if ans < -2^31 ans = INT_MIN; } return (int) ans; } public static void main(String[] args) { System.out.println(myAtoi("4193 with words")); } }
Mohak567/DSA
ATOI.java
249,474
import java.util.Scanner; public class Menu { private Scanner sc = new Scanner(System.in); private AdminMenu adminMenu = new AdminMenu(); private PassengerMenu passengerMenu = new PassengerMenu(); private Utils utils = new Utils(); // keeps track of the user's username when signing in public static String currentUsername; // executes the menu public void menuExecution() { utils.clearScreen(); mainMenu(); System.out.println(); System.out.println("> Enter your command: "); int command = utils.inputNum(); while (true) { switch (command) { case 1: utils.clearScreen(); signIn(); break; case 2: Signup signup = new Signup(); break; default: System.out.println("> Invalid input"); System.out.println("> Please try again"); } utils.clearScreen(); mainMenu(); System.out.println(); System.out.println("> Enter your command:"); command = utils.inputNum(); } } // signs in the admin and user private void signIn() { signInMenu(); System.out.println("> Enter your username: "); currentUsername = sc.next(); System.out.println("> Enter your password: "); String pass = sc.next(); boolean isValid = false; if (currentUsername.equals("Admin") && pass.equals("Admin")) { isValid = true; utils.clearScreen(); adminMenu.adminMenuExe(); } for (int i = 0; i < Database.users.size(); i++) { if (Database.users.get(i).getUsername().equals(currentUsername) && Database.users.get(i).getPassword().equals(pass)) { isValid = true; utils.clearScreen(); passengerMenu.passengerMenuExe(); } } if (!isValid) { System.out.println(); System.out.println(utils.RED_BOLD + "> Invalid username or password" + utils.RESET); System.out.println(utils.GREY_BOLD + "> If you don't hava an account, create one in sign up menu..." + utils.RESET); utils.pressEnterToContinue(); } } // prints menus private void mainMenu() { System.out.println(utils.CYAN_BOLD + """ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: WELCOME TO AIRLINE RESERVATION SYSTEM :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ..........................MENU OPTIONS........................ <1> Sign in <2> Sign up\s""" + utils.RESET); } private void signInMenu() { System.out.println(utils.CYAN_BOLD + """ :::::::::::::::::::::::::::::::::::::::: SIGN IN :::::::::::::::::::::::::::::::::::::::: """ + utils.RESET); } }
melodiw82/Java-Airline-Reservation
src/Menu.java
249,475
import java.util.Calendar; public class Person { // Variables private String name; private String city; private String mobileNumber; // Note: int or long cannot store leading zeros and country code signs (e.g. +63...) private String gender; private int birthYear; private Person friend; // Methods public void introduceSelf() { System.out.println("Hi, my name is " + getName() + ", I am " + (Calendar.getInstance().get(Calendar.YEAR) - getBirthYear()) + " years old and I live in " + getCity() + "."); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setCity(String city) { this.city = city; } public String getCity() { return city; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } public String getMobileNumber() { return mobileNumber; } public void setGender(String gender) { this.gender = gender; } public String getGender() { return gender; } public void setBirthYear(int birthYear) { this.birthYear = birthYear; } public int getBirthYear() { return birthYear; } public void setFriend(Person friend) { this.friend = friend; } public Person getFriend() { return friend; } }
jerichosy/CCPROG3
Person.java
249,476
/* 14. Write a Java program to print an American flag on the screen. Expected Output * * * * * * ================================== * * * * * ================================== * * * * * * ================================== * * * * * ================================== * * * * * * ================================== * * * * * ================================== * * * * * * ================================== * * * * * ================================== * * * * * * ================================== ============================================== ============================================== ============================================== ============================================== ============================================== ============================================== */ import java.lang.*; class Ques14 { public static void main(String[] args) { // Print a pattern of asterisks and equal signs to create a design System.out.println("* * * * * * =================================="); System.out.println(" * * * * * =================================="); System.out.println("* * * * * * =================================="); System.out.println(" * * * * * =================================="); System.out.println("* * * * * * =================================="); System.out.println(" * * * * * =================================="); System.out.println("* * * * * * =================================="); System.out.println(" * * * * * =================================="); System.out.println("* * * * * * =================================="); // Print a row of equal signs to complete the design System.out.println("=============================================="); System.out.println("=============================================="); System.out.println("=============================================="); System.out.println("=============================================="); System.out.println("=============================================="); System.out.println("=============================================="); } }
krishnajais001/Java-Prorgam-Pratice
Ques14.java
249,477
import java.util.*; class Solution { public int solution(int[] absolutes, boolean[] signs) { for(int i = 0; i < signs.length; ++i) { if (!signs[i]) absolutes[i] *= -1; } return Arrays.stream(absolutes).sum(); } }
KichanLee/Programmers
1204_01.java
249,478
// 어떤 정수들이 있습니다. 이 정수들의 절댓값을 차례대로 담은 정수 배열 absolutes와 이 정수들의 부호를 차례대로 담은 불리언 배열 signs가 매개변수로 주어집니다. 실제 정수들의 합을 구하여 return 하도록 solution 함수를 완성해주세요. class Solution { public int solution(int[] absolutes, boolean[] signs) { int answer = 0; for(int i = 0; i < absolutes.length; i++){ if(signs[i] == true){ answer += absolutes[i]; }else{ answer += (-1) * absolutes[i]; } } return answer; } }
HEEEUN9812/kata
Kata_26.java
249,479
public class t29 { public static void main(String[] args){ Solution29 solution=new Solution29(); System.out.println(solution.divide(88,12)); } } class Solution29 { public int divide(int dividend, int divisor) { //to minimize the condition dealt if(dividend==0)return 0; //the only exception if(dividend==Integer.MIN_VALUE && divisor==-1)return Integer.MAX_VALUE; int ans=0; //designed for ans's += int base=get_base(dividend,divisor); //get how many bit can be shifted (max) int lim=0; for(;lim<32;lim++){ //only when signs are exactly the same, it returns true if(!sign_not_changed(divisor,divisor<<lim))break; //lim is not reachable; } for(int i=lim-1;i>=0;i--){ //when a=-2147483648,1+2+4+8 could never reach that number, // there is a 1 missing! while (true){ int n=close_to_0(dividend , (divisor<<i)); if(n==0){ ans+=(base<<i);return ans; } if(sign_not_changed(dividend,n)){ dividend=n; ans+=(base<<i); } else break; } } return ans; } int get_base(int a,int b){ //different sign -> -1 if(a>0 && b<0 || a<0 && b>0)return -1; else return 1; } int close_to_0(int a,int b){ //make the abs close to zero if(a>0 && b<0 || a<0 && b>0)return a+b; else return a-b; } boolean sign_not_changed(int a, int b){ //a is not 0, //b is not 0, or it gets into a loop return a>0 &&b>0 ||a<0 && b<0; } }
fanyanpeng/leetcode
src/t29.java
249,481
import java.util.Scanner; public class y { public static int countCriticalReadings(String readings) { String[] readingsArray = readings.split(";"); int criticalCount = 0; for (String reading : readingsArray) { if (reading.trim().equalsIgnoreCase("critical")) { criticalCount++; } } return criticalCount; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the patient readings System.out.println("Enter the patient vital signs readings separated by ';':"); String patientReadings = scanner.nextLine(); int criticalCount = countCriticalReadings(patientReadings); System.out.println("Output:"); System.out.println(criticalCount); scanner.close(); } }
nithinkalyan41/DSA
Day-67/y.java
249,482
import java.util.Scanner; public class 8ballpt3 { public static void main (String[] args) { Scanner input = new Scanner(System.in); System.out.println("What is your question?"); String name = input.nextLine(); String[] wordList = {"Yes", "Maybe", "No", "As I see it, yes", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don’t count on it", "It is certain", "It is decidedly so", "Most likely", "My reply is no", "My sources say no", "Outlook good", "Outlook not so good", "Reply hazy try again", "Signs point to yes", "Very doubtful", "Without a doubt", "Yes, definitely", "You may rely on it", "You have to be kidding", "You didn't seriously just ask that", "I think its better I don't answer that"}; int oneLength = wordList.length; int rand1 = (int) (Math.random() * oneLength); String phrase = wordList[rand1]; System.out.println ("The answer to your question is: " + phrase); } }
emunro99/coding-challenge
8ballpt3.java
249,483
/* * This file is a part of solutions for the Java Basics course in the * Ventspils University of Applied Sciences. * There is an attempt to maintain Google Java code style declared at * https://google.github.io/styleguide/javaguide.html * * Author: Stanislavs Vjazovcevs * Email: [email protected], [email protected] * * Copyright Vjazovcevs Stanislavs, 2020 */ import java.util.Scanner; /** * This class is associated with the fifth task of the third seminar */ public class Task0305 { public static void main(String[] args) { Scanner is = new Scanner(System.in); int[] nums = new int[2]; byte idx = 0; System.out.println("This app will take in x, y, and calculate product of elements between\n"); while (idx < 2) { System.out.printf("Type in integer for #%d -> ", idx + 1); if (is.hasNextInt()) { nums[idx++] = is.nextInt(); } else { System.out.println("Invalid input. Try again...\n"); } is.nextLine(); } if (nums[0] > nums[1]) { int temp = nums[0]; nums[0] = nums[1]; nums[1] = temp; } long prod = nums[0]; for (int i = nums[0] + 1; i <= nums[1]; i++) { if (i == 0) { //in case x and y have opposing signs continue; } prod *= i; } System.out.printf("\nProduct of elements between [%d..%d] is %d\n", nums[0], nums[1], prod); is.close(); } }
Nazdorovye/Java_basics
Task0305.java
249,484
package Flappy; import javafx.geometry.Bounds; import javafx.geometry.Rectangle2D; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.transform.Rotate; import java.util.Objects; public class Pipe { private Rectangle bottomPipe; private Rectangle topPipe; private Pane flappyPane; private double gapMidpoint; public Pipe(Pane flappyPane, double x, double bottomPipeHeight) { this.flappyPane = flappyPane; // create the bottomPipe with the variables passed in this.bottomPipe = new Rectangle(x, bottomPipeHeight, FlapConstants.PIPE_WIDTH, FlapConstants.PIPE_LENGTH); this.bottomPipe.setFill(Color.GREEN); this.bottomPipe.setStroke(Color.BLACK); this.bottomPipe.setStrokeWidth(2.5); // create the top pipe based on the variables passed in to the bottom pipe double topPipeHeight = bottomPipeHeight - FlapConstants.PIPE_GAP_HEIGHT; this.topPipe = new Rectangle(x, topPipeHeight, FlapConstants.PIPE_WIDTH, FlapConstants.PIPE_LENGTH); this.topPipe.setFill(Color.GREEN); this.topPipe.setStroke(Color.BLACK); this.topPipe.setStrokeWidth(2.5); this.gapMidpoint = bottomPipeHeight - (FlapConstants.PIPE_GAP_HEIGHT / 2); // set the image for both pipes // this.weedPipe(x, bottomPipeHeight); // TODO fix :( // rotate the top pipe so that it is upside down this.rotateTopPipe(this.topPipe); this.flappyPane.getChildren().addAll(this.bottomPipe, this.topPipe); } /** * Method that rotates the top pipe so that it is aligned correctly * @param topPipe The top pipe that we want to rotate */ private void rotateTopPipe(Rectangle topPipe) { double rotationCenterX = (topPipe.getX() + (FlapConstants.PIPE_WIDTH / 2)); double rotationCenterY = topPipe.getY(); Rotate rotate = new Rotate(); rotate.setAngle(180); rotate.setPivotX(rotationCenterX); rotate.setPivotY(rotationCenterY); topPipe.getTransforms().addAll(rotate); } /** * Method that sets the weed pipe image for the pipes. */ private void weedPipe(double x, double bottomHeight) { Image image = new Image(Objects.requireNonNull(this.getClass().getResourceAsStream("weedPipe.png")), FlapConstants.PIPE_WIDTH, bottomHeight, true, true); ImageView imageView = new ImageView(image); imageView.setImage(image); imageView.setPreserveRatio(true); imageView.setSmooth(true); Rectangle2D viewportRect = new Rectangle2D(x - FlapConstants.PIPE_WIDTH, bottomHeight, FlapConstants.PIPE_WIDTH, FlapConstants.PIPE_LENGTH); imageView.setViewport(viewportRect); imageView.toFront(); this.flappyPane.getChildren().add(imageView); } public void scrollPipes() { // must have opposite signs because the top pipe is rotated this.topPipe.setX(this.topPipe.getX() + FlapConstants.SCROLLING_CONSTANT); this.bottomPipe.setX(this.bottomPipe.getX() - FlapConstants.SCROLLING_CONSTANT); } public void removeFromPane() { this.flappyPane.getChildren().removeAll(this.topPipe, this.bottomPipe); } /** * Method that sets the y locations of the pipes so that there is a constant gap between them. */ public Bounds getTopPipeBounds() { return this.topPipe.getBoundsInParent(); // this accounts for the rotation of the rectangle } public Bounds getBottomPipeBounds() { return this.bottomPipe.getBoundsInLocal(); // this does not account for rotation of the rectangle } public double getPipeX() { return this.bottomPipe.getX(); } public double getGapMidpoint() { return this.gapMidpoint; } }
Javierfg02/FlappyBird-With-Neuroevolution
Pipe.java
249,485
/* * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.lang; import java.io.ObjectStreamClass; import java.io.ObjectStreamField; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Formatter; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * The <code>String</code> class represents character strings. All * string literals in Java programs, such as <code>"abc"</code>, are * implemented as instances of this class. * <p> * Strings are constant; their values cannot be changed after they * are created. String buffers support mutable strings. * Because String objects are immutable they can be shared. For example: * <p><blockquote><pre> * String str = "abc"; * </pre></blockquote><p> * is equivalent to: * <p><blockquote><pre> * char data[] = {'a', 'b', 'c'}; * String str = new String(data); * </pre></blockquote><p> * Here are some more examples of how strings can be used: * <p><blockquote><pre> * System.out.println("abc"); * String cde = "cde"; * System.out.println("abc" + cde); * String c = "abc".substring(2,3); * String d = cde.substring(1, 2); * </pre></blockquote> * <p> * The class <code>String</code> includes methods for examining * individual characters of the sequence, for comparing strings, for * searching strings, for extracting substrings, and for creating a * copy of a string with all characters translated to uppercase or to * lowercase. Case mapping is based on the Unicode Standard version * specified by the {@link java.lang.Character Character} class. * <p> * The Java language provides special support for the string * concatenation operator (&nbsp;+&nbsp;), and for conversion of * other objects to strings. String concatenation is implemented * through the <code>StringBuilder</code>(or <code>StringBuffer</code>) * class and its <code>append</code> method. * String conversions are implemented through the method * <code>toString</code>, defined by <code>Object</code> and * inherited by all classes in Java. For additional information on * string concatenation and conversion, see Gosling, Joy, and Steele, * <i>The Java Language Specification</i>. * * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor * or method in this class will cause a {@link NullPointerException} to be * thrown. * * <p>A <code>String</code> represents a string in the UTF-16 format * in which <em>supplementary characters</em> are represented by <em>surrogate * pairs</em> (see the section <a href="Character.html#unicode">Unicode * Character Representations</a> in the <code>Character</code> class for * more information). * Index values refer to <code>char</code> code units, so a supplementary * character uses two positions in a <code>String</code>. * <p>The <code>String</code> class provides methods for dealing with * Unicode code points (i.e., characters), in addition to those for * dealing with Unicode code units (i.e., <code>char</code> values). * * @author Lee Boynton * @author Arthur van Hoff * @author Martin Buchholz * @author Ulf Zibis * @see java.lang.Object#toString() * @see java.lang.StringBuffer * @see java.lang.StringBuilder * @see java.nio.charset.Charset * @since JDK1.0 */ public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ private final char value[]; /** The offset is the first index of the storage that is used. */ private final int offset; /** The count is the number of characters in the String. */ private final int count; /** Cache the hash code for the string */ private int hash; // Default to 0 /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -6849794470754667710L; /** * Class String is special cased within the Serialization Stream Protocol. * * A String instance is written initially into an ObjectOutputStream in the * following format: * <pre> * <code>TC_STRING</code> (utf String) * </pre> * The String is written by method <code>DataOutput.writeUTF</code>. * A new handle is generated to refer to all future references to the * string instance within the stream. */ private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0]; /** * Initializes a newly created {@code String} object so that it represents * an empty character sequence. Note that use of this constructor is * unnecessary since Strings are immutable. */ public String() { this.offset = 0; this.count = 0; this.value = new char[0]; } /** * Initializes a newly created {@code String} object so that it represents * the same sequence of characters as the argument; in other words, the * newly created string is a copy of the argument string. Unless an * explicit copy of {@code original} is needed, use of this constructor is * unnecessary since Strings are immutable. * * @param original * A {@code String} */ public String(String original) { int size = original.count; char[] originalValue = original.value; char[] v; if (originalValue.length > size) { // The array representing the String is bigger than the new // String itself. Perhaps this constructor is being called // in order to trim the baggage, so make a copy of the array. int off = original.offset; v = Arrays.copyOfRange(originalValue, off, off+size); } else { // The array representing the String is the same // size as the String, so no point in making a copy. v = originalValue; } this.offset = 0; this.count = size; this.value = v; } /** * Allocates a new {@code String} so that it represents the sequence of * characters currently contained in the character array argument. The * contents of the character array are copied; subsequent modification of * the character array does not affect the newly created string. * * @param value * The initial value of the string */ public String(char value[]) { int size = value.length; this.offset = 0; this.count = size; this.value = Arrays.copyOf(value, size); } /** * Allocates a new {@code String} that contains characters from a subarray * of the character array argument. The {@code offset} argument is the * index of the first character of the subarray and the {@code count} * argument specifies the length of the subarray. The contents of the * subarray are copied; subsequent modification of the character array does * not affect the newly created string. * * @param value * Array that is the source of characters * * @param offset * The initial offset * * @param count * The length * * @throws IndexOutOfBoundsException * If the {@code offset} and {@code count} arguments index * characters outside the bounds of the {@code value} array */ public String(char value[], int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } // Note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } this.offset = 0; this.count = count; this.value = Arrays.copyOfRange(value, offset, offset+count); } /** * Allocates a new {@code String} that contains characters from a subarray * of the <a href="Character.html#unicode">Unicode code point</a> array * argument. The {@code offset} argument is the index of the first code * point of the subarray and the {@code count} argument specifies the * length of the subarray. The contents of the subarray are converted to * {@code char}s; subsequent modification of the {@code int} array does not * affect the newly created string. * * @param codePoints * Array that is the source of Unicode code points * * @param offset * The initial offset * * @param count * The length * * @throws IllegalArgumentException * If any invalid Unicode code point is found in {@code * codePoints} * * @throws IndexOutOfBoundsException * If the {@code offset} and {@code count} arguments index * characters outside the bounds of the {@code codePoints} array * * @since 1.5 */ public String(int[] codePoints, int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } // Note: offset or count might be near -1>>>1. if (offset > codePoints.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } final int end = offset + count; // Pass 1: Compute precise size of char[] int n = count; for (int i = offset; i < end; i++) { int c = codePoints[i]; if (Character.isBmpCodePoint(c)) continue; else if (Character.isValidCodePoint(c)) n++; else throw new IllegalArgumentException(Integer.toString(c)); } // Pass 2: Allocate and fill in char[] final char[] v = new char[n]; for (int i = offset, j = 0; i < end; i++, j++) { int c = codePoints[i]; if (Character.isBmpCodePoint(c)) v[j] = (char) c; else Character.toSurrogates(c, v, j++); } this.value = v; this.count = n; this.offset = 0; } /** * Allocates a new {@code String} constructed from a subarray of an array * of 8-bit integer values. * * <p> The {@code offset} argument is the index of the first byte of the * subarray, and the {@code count} argument specifies the length of the * subarray. * * <p> Each {@code byte} in the subarray is converted to a {@code char} as * specified in the method above. * * @deprecated This method does not properly convert bytes into characters. * As of JDK&nbsp;1.1, the preferred way to do this is via the * {@code String} constructors that take a {@link * java.nio.charset.Charset}, charset name, or that use the platform's * default charset. * * @param ascii * The bytes to be converted to characters * * @param hibyte * The top 8 bits of each 16-bit Unicode code unit * * @param offset * The initial offset * @param count * The length * * @throws IndexOutOfBoundsException * If the {@code offset} or {@code count} argument is invalid * * @see #String(byte[], int) * @see #String(byte[], int, int, java.lang.String) * @see #String(byte[], int, int, java.nio.charset.Charset) * @see #String(byte[], int, int) * @see #String(byte[], java.lang.String) * @see #String(byte[], java.nio.charset.Charset) * @see #String(byte[]) */ @Deprecated public String(byte ascii[], int hibyte, int offset, int count) { checkBounds(ascii, offset, count); char value[] = new char[count]; if (hibyte == 0) { for (int i = count ; i-- > 0 ;) { value[i] = (char) (ascii[i + offset] & 0xff); } } else { hibyte <<= 8; for (int i = count ; i-- > 0 ;) { value[i] = (char) (hibyte | (ascii[i + offset] & 0xff)); } } this.offset = 0; this.count = count; this.value = value; } /** * Allocates a new {@code String} containing characters constructed from * an array of 8-bit integer values. Each character <i>c</i>in the * resulting string is constructed from the corresponding component * <i>b</i> in the byte array such that: * * <blockquote><pre> * <b><i>c</i></b> == (char)(((hibyte &amp; 0xff) &lt;&lt; 8) * | (<b><i>b</i></b> &amp; 0xff)) * </pre></blockquote> * * @deprecated This method does not properly convert bytes into * characters. As of JDK&nbsp;1.1, the preferred way to do this is via the * {@code String} constructors that take a {@link * java.nio.charset.Charset}, charset name, or that use the platform's * default charset. * * @param ascii * The bytes to be converted to characters * * @param hibyte * The top 8 bits of each 16-bit Unicode code unit * * @see #String(byte[], int, int, java.lang.String) * @see #String(byte[], int, int, java.nio.charset.Charset) * @see #String(byte[], int, int) * @see #String(byte[], java.lang.String) * @see #String(byte[], java.nio.charset.Charset) * @see #String(byte[]) */ @Deprecated public String(byte ascii[], int hibyte) { this(ascii, hibyte, 0, ascii.length); } /* Common private utility method used to bounds check the byte array * and requested offset & length values used by the String(byte[],..) * constructors. */ private static void checkBounds(byte[] bytes, int offset, int length) { if (length < 0) throw new StringIndexOutOfBoundsException(length); if (offset < 0) throw new StringIndexOutOfBoundsException(offset); if (offset > bytes.length - length) throw new StringIndexOutOfBoundsException(offset + length); } /** * Constructs a new {@code String} by decoding the specified subarray of * bytes using the specified charset. The length of the new {@code String} * is a function of the charset, and hence may not be equal to the length * of the subarray. * * <p> The behavior of this constructor when the given bytes are not valid * in the given charset is unspecified. The {@link * java.nio.charset.CharsetDecoder} class should be used when more control * over the decoding process is required. * * @param bytes * The bytes to be decoded into characters * * @param offset * The index of the first byte to decode * * @param length * The number of bytes to decode * @param charsetName * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @throws UnsupportedEncodingException * If the named charset is not supported * * @throws IndexOutOfBoundsException * If the {@code offset} and {@code length} arguments index * characters outside the bounds of the {@code bytes} array * * @since JDK1.1 */ public String(byte bytes[], int offset, int length, String charsetName) throws UnsupportedEncodingException { if (charsetName == null) throw new NullPointerException("charsetName"); checkBounds(bytes, offset, length); char[] v = StringCoding.decode(charsetName, bytes, offset, length); this.offset = 0; this.count = v.length; this.value = v; } /** * Constructs a new {@code String} by decoding the specified subarray of * bytes using the specified {@linkplain java.nio.charset.Charset charset}. * The length of the new {@code String} is a function of the charset, and * hence may not be equal to the length of the subarray. * * <p> This method always replaces malformed-input and unmappable-character * sequences with this charset's default replacement string. The {@link * java.nio.charset.CharsetDecoder} class should be used when more control * over the decoding process is required. * * @param bytes * The bytes to be decoded into characters * * @param offset * The index of the first byte to decode * * @param length * The number of bytes to decode * * @param charset * The {@linkplain java.nio.charset.Charset charset} to be used to * decode the {@code bytes} * * @throws IndexOutOfBoundsException * If the {@code offset} and {@code length} arguments index * characters outside the bounds of the {@code bytes} array * * @since 1.6 */ public String(byte bytes[], int offset, int length, Charset charset) { if (charset == null) throw new NullPointerException("charset"); checkBounds(bytes, offset, length); char[] v = StringCoding.decode(charset, bytes, offset, length); this.offset = 0; this.count = v.length; this.value = v; } /** * Constructs a new {@code String} by decoding the specified array of bytes * using the specified {@linkplain java.nio.charset.Charset charset}. The * length of the new {@code String} is a function of the charset, and hence * may not be equal to the length of the byte array. * * <p> The behavior of this constructor when the given bytes are not valid * in the given charset is unspecified. The {@link * java.nio.charset.CharsetDecoder} class should be used when more control * over the decoding process is required. * * @param bytes * The bytes to be decoded into characters * * @param charsetName * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @throws UnsupportedEncodingException * If the named charset is not supported * * @since JDK1.1 */ public String(byte bytes[], String charsetName) throws UnsupportedEncodingException { this(bytes, 0, bytes.length, charsetName); } /** * Constructs a new {@code String} by decoding the specified array of * bytes using the specified {@linkplain java.nio.charset.Charset charset}. * The length of the new {@code String} is a function of the charset, and * hence may not be equal to the length of the byte array. * * <p> This method always replaces malformed-input and unmappable-character * sequences with this charset's default replacement string. The {@link * java.nio.charset.CharsetDecoder} class should be used when more control * over the decoding process is required. * * @param bytes * The bytes to be decoded into characters * * @param charset * The {@linkplain java.nio.charset.Charset charset} to be used to * decode the {@code bytes} * * @since 1.6 */ public String(byte bytes[], Charset charset) { this(bytes, 0, bytes.length, charset); } /** * Constructs a new {@code String} by decoding the specified subarray of * bytes using the platform's default charset. The length of the new * {@code String} is a function of the charset, and hence may not be equal * to the length of the subarray. * * <p> The behavior of this constructor when the given bytes are not valid * in the default charset is unspecified. The {@link * java.nio.charset.CharsetDecoder} class should be used when more control * over the decoding process is required. * * @param bytes * The bytes to be decoded into characters * * @param offset * The index of the first byte to decode * * @param length * The number of bytes to decode * * @throws IndexOutOfBoundsException * If the {@code offset} and the {@code length} arguments index * characters outside the bounds of the {@code bytes} array * * @since JDK1.1 */ public String(byte bytes[], int offset, int length) { checkBounds(bytes, offset, length); char[] v = StringCoding.decode(bytes, offset, length); this.offset = 0; this.count = v.length; this.value = v; } /** * Constructs a new {@code String} by decoding the specified array of bytes * using the platform's default charset. The length of the new {@code * String} is a function of the charset, and hence may not be equal to the * length of the byte array. * * <p> The behavior of this constructor when the given bytes are not valid * in the default charset is unspecified. The {@link * java.nio.charset.CharsetDecoder} class should be used when more control * over the decoding process is required. * * @param bytes * The bytes to be decoded into characters * * @since JDK1.1 */ public String(byte bytes[]) { this(bytes, 0, bytes.length); } /** * Allocates a new string that contains the sequence of characters * currently contained in the string buffer argument. The contents of the * string buffer are copied; subsequent modification of the string buffer * does not affect the newly created string. * * @param buffer * A {@code StringBuffer} */ public String(StringBuffer buffer) { String result = buffer.toString(); this.value = result.value; this.count = result.count; this.offset = result.offset; } /** * Allocates a new string that contains the sequence of characters * currently contained in the string builder argument. The contents of the * string builder are copied; subsequent modification of the string builder * does not affect the newly created string. * * <p> This constructor is provided to ease migration to {@code * StringBuilder}. Obtaining a string from a string builder via the {@code * toString} method is likely to run faster and is generally preferred. * * @param builder * A {@code StringBuilder} * * @since 1.5 */ public String(StringBuilder builder) { String result = builder.toString(); this.value = result.value; this.count = result.count; this.offset = result.offset; } // Package private constructor which shares value array for speed. String(int offset, int count, char value[]) { this.value = value; this.offset = offset; this.count = count; } /** * Returns the length of this string. * The length is equal to the number of <a href="Character.html#unicode">Unicode * code units</a> in the string. * * @return the length of the sequence of characters represented by this * object. */ public int length() { return count; } /** * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>. * * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise * <tt>false</tt> * * @since 1.6 */ public boolean isEmpty() { return count == 0; } /** * Returns the <code>char</code> value at the * specified index. An index ranges from <code>0</code> to * <code>length() - 1</code>. The first <code>char</code> value of the sequence * is at index <code>0</code>, the next at index <code>1</code>, * and so on, as for array indexing. * * <p>If the <code>char</code> value specified by the index is a * <a href="Character.html#unicode">surrogate</a>, the surrogate * value is returned. * * @param index the index of the <code>char</code> value. * @return the <code>char</code> value at the specified index of this string. * The first <code>char</code> value is at index <code>0</code>. * @exception IndexOutOfBoundsException if the <code>index</code> * argument is negative or not less than the length of this * string. */ public char charAt(int index) { if ((index < 0) || (index >= count)) { throw new StringIndexOutOfBoundsException(index); } return value[index + offset]; } /** * Returns the character (Unicode code point) at the specified * index. The index refers to <code>char</code> values * (Unicode code units) and ranges from <code>0</code> to * {@link #length()}<code> - 1</code>. * * <p> If the <code>char</code> value specified at the given index * is in the high-surrogate range, the following index is less * than the length of this <code>String</code>, and the * <code>char</code> value at the following index is in the * low-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, * the <code>char</code> value at the given index is returned. * * @param index the index to the <code>char</code> values * @return the code point value of the character at the * <code>index</code> * @exception IndexOutOfBoundsException if the <code>index</code> * argument is negative or not less than the length of this * string. * @since 1.5 */ public int codePointAt(int index) { if ((index < 0) || (index >= count)) { throw new StringIndexOutOfBoundsException(index); } return Character.codePointAtImpl(value, offset + index, offset + count); } /** * Returns the character (Unicode code point) before the specified * index. The index refers to <code>char</code> values * (Unicode code units) and ranges from <code>1</code> to {@link * CharSequence#length() length}. * * <p> If the <code>char</code> value at <code>(index - 1)</code> * is in the low-surrogate range, <code>(index - 2)</code> is not * negative, and the <code>char</code> value at <code>(index - * 2)</code> is in the high-surrogate range, then the * supplementary code point value of the surrogate pair is * returned. If the <code>char</code> value at <code>index - * 1</code> is an unpaired low-surrogate or a high-surrogate, the * surrogate value is returned. * * @param index the index following the code point that should be returned * @return the Unicode code point value before the given index. * @exception IndexOutOfBoundsException if the <code>index</code> * argument is less than 1 or greater than the length * of this string. * @since 1.5 */ public int codePointBefore(int index) { int i = index - 1; if ((i < 0) || (i >= count)) { throw new StringIndexOutOfBoundsException(index); } return Character.codePointBeforeImpl(value, offset + index, offset); } /** * Returns the number of Unicode code points in the specified text * range of this <code>String</code>. The text range begins at the * specified <code>beginIndex</code> and extends to the * <code>char</code> at index <code>endIndex - 1</code>. Thus the * length (in <code>char</code>s) of the text range is * <code>endIndex-beginIndex</code>. Unpaired surrogates within * the text range count as one code point each. * * @param beginIndex the index to the first <code>char</code> of * the text range. * @param endIndex the index after the last <code>char</code> of * the text range. * @return the number of Unicode code points in the specified text * range * @exception IndexOutOfBoundsException if the * <code>beginIndex</code> is negative, or <code>endIndex</code> * is larger than the length of this <code>String</code>, or * <code>beginIndex</code> is larger than <code>endIndex</code>. * @since 1.5 */ public int codePointCount(int beginIndex, int endIndex) { if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) { throw new IndexOutOfBoundsException(); } return Character.codePointCountImpl(value, offset+beginIndex, endIndex-beginIndex); } /** * Returns the index within this <code>String</code> that is * offset from the given <code>index</code> by * <code>codePointOffset</code> code points. Unpaired surrogates * within the text range given by <code>index</code> and * <code>codePointOffset</code> count as one code point each. * * @param index the index to be offset * @param codePointOffset the offset in code points * @return the index within this <code>String</code> * @exception IndexOutOfBoundsException if <code>index</code> * is negative or larger then the length of this * <code>String</code>, or if <code>codePointOffset</code> is positive * and the substring starting with <code>index</code> has fewer * than <code>codePointOffset</code> code points, * or if <code>codePointOffset</code> is negative and the substring * before <code>index</code> has fewer than the absolute value * of <code>codePointOffset</code> code points. * @since 1.5 */ public int offsetByCodePoints(int index, int codePointOffset) { if (index < 0 || index > count) { throw new IndexOutOfBoundsException(); } return Character.offsetByCodePointsImpl(value, offset, count, offset+index, codePointOffset) - offset; } /** * Copy characters from this string into dst starting at dstBegin. * This method doesn't perform any range checking. */ void getChars(char dst[], int dstBegin) { System.arraycopy(value, offset, dst, dstBegin, count); } /** * Copies characters from this string into the destination character * array. * <p> * The first character to be copied is at index <code>srcBegin</code>; * the last character to be copied is at index <code>srcEnd-1</code> * (thus the total number of characters to be copied is * <code>srcEnd-srcBegin</code>). The characters are copied into the * subarray of <code>dst</code> starting at index <code>dstBegin</code> * and ending at index: * <p><blockquote><pre> * dstbegin + (srcEnd-srcBegin) - 1 * </pre></blockquote> * * @param srcBegin index of the first character in the string * to copy. * @param srcEnd index after the last character in the string * to copy. * @param dst the destination array. * @param dstBegin the start offset in the destination array. * @exception IndexOutOfBoundsException If any of the following * is true: * <ul><li><code>srcBegin</code> is negative. * <li><code>srcBegin</code> is greater than <code>srcEnd</code> * <li><code>srcEnd</code> is greater than the length of this * string * <li><code>dstBegin</code> is negative * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than * <code>dst.length</code></ul> */ public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { if (srcBegin < 0) { throw new StringIndexOutOfBoundsException(srcBegin); } if (srcEnd > count) { throw new StringIndexOutOfBoundsException(srcEnd); } if (srcBegin > srcEnd) { throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); } System.arraycopy(value, offset + srcBegin, dst, dstBegin, srcEnd - srcBegin); } /** * Copies characters from this string into the destination byte array. Each * byte receives the 8 low-order bits of the corresponding character. The * eight high-order bits of each character are not copied and do not * participate in the transfer in any way. * * <p> The first character to be copied is at index {@code srcBegin}; the * last character to be copied is at index {@code srcEnd-1}. The total * number of characters to be copied is {@code srcEnd-srcBegin}. The * characters, converted to bytes, are copied into the subarray of {@code * dst} starting at index {@code dstBegin} and ending at index: * * <blockquote><pre> * dstbegin + (srcEnd-srcBegin) - 1 * </pre></blockquote> * * @deprecated This method does not properly convert characters into * bytes. As of JDK&nbsp;1.1, the preferred way to do this is via the * {@link #getBytes()} method, which uses the platform's default charset. * * @param srcBegin * Index of the first character in the string to copy * * @param srcEnd * Index after the last character in the string to copy * * @param dst * The destination array * * @param dstBegin * The start offset in the destination array * * @throws IndexOutOfBoundsException * If any of the following is true: * <ul> * <li> {@code srcBegin} is negative * <li> {@code srcBegin} is greater than {@code srcEnd} * <li> {@code srcEnd} is greater than the length of this String * <li> {@code dstBegin} is negative * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code * dst.length} * </ul> */ @Deprecated public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) { if (srcBegin < 0) { throw new StringIndexOutOfBoundsException(srcBegin); } if (srcEnd > count) { throw new StringIndexOutOfBoundsException(srcEnd); } if (srcBegin > srcEnd) { throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); } int j = dstBegin; int n = offset + srcEnd; int i = offset + srcBegin; char[] val = value; /* avoid getfield opcode */ while (i < n) { dst[j++] = (byte)val[i++]; } } /** * Encodes this {@code String} into a sequence of bytes using the named * charset, storing the result into a new byte array. * * <p> The behavior of this method when this string cannot be encoded in * the given charset is unspecified. The {@link * java.nio.charset.CharsetEncoder} class should be used when more control * over the encoding process is required. * * @param charsetName * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @return The resultant byte array * * @throws UnsupportedEncodingException * If the named charset is not supported * * @since JDK1.1 */ public byte[] getBytes(String charsetName) throws UnsupportedEncodingException { if (charsetName == null) throw new NullPointerException(); return StringCoding.encode(charsetName, value, offset, count); } /** * Encodes this {@code String} into a sequence of bytes using the given * {@linkplain java.nio.charset.Charset charset}, storing the result into a * new byte array. * * <p> This method always replaces malformed-input and unmappable-character * sequences with this charset's default replacement byte array. The * {@link java.nio.charset.CharsetEncoder} class should be used when more * control over the encoding process is required. * * @param charset * The {@linkplain java.nio.charset.Charset} to be used to encode * the {@code String} * * @return The resultant byte array * * @since 1.6 */ public byte[] getBytes(Charset charset) { if (charset == null) throw new NullPointerException(); return StringCoding.encode(charset, value, offset, count); } /** * Encodes this {@code String} into a sequence of bytes using the * platform's default charset, storing the result into a new byte array. * * <p> The behavior of this method when this string cannot be encoded in * the default charset is unspecified. The {@link * java.nio.charset.CharsetEncoder} class should be used when more control * over the encoding process is required. * * @return The resultant byte array * * @since JDK1.1 */ public byte[] getBytes() { return StringCoding.encode(value, offset, count); } /** * Compares this string to the specified object. The result is {@code * true} if and only if the argument is not {@code null} and is a {@code * String} object that represents the same sequence of characters as this * object. * * @param anObject * The object to compare this {@code String} against * * @return {@code true} if the given object represents a {@code String} * equivalent to this string, {@code false} otherwise * * @see #compareTo(String) * @see #equalsIgnoreCase(String) */ public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = count; if (n == anotherString.count) { char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } return true; } } return false; } /** * Compares this string to the specified {@code StringBuffer}. The result * is {@code true} if and only if this {@code String} represents the same * sequence of characters as the specified {@code StringBuffer}. * * @param sb * The {@code StringBuffer} to compare this {@code String} against * * @return {@code true} if this {@code String} represents the same * sequence of characters as the specified {@code StringBuffer}, * {@code false} otherwise * * @since 1.4 */ public boolean contentEquals(StringBuffer sb) { synchronized(sb) { return contentEquals((CharSequence)sb); } } /** * Compares this string to the specified {@code CharSequence}. The result * is {@code true} if and only if this {@code String} represents the same * sequence of char values as the specified sequence. * * @param cs * The sequence to compare this {@code String} against * * @return {@code true} if this {@code String} represents the same * sequence of char values as the specified sequence, {@code * false} otherwise * * @since 1.5 */ public boolean contentEquals(CharSequence cs) { if (count != cs.length()) return false; // Argument is a StringBuffer, StringBuilder if (cs instanceof AbstractStringBuilder) { char v1[] = value; char v2[] = ((AbstractStringBuilder)cs).getValue(); int i = offset; int j = 0; int n = count; while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } return true; } // Argument is a String if (cs.equals(this)) return true; // Argument is a generic CharSequence char v1[] = value; int i = offset; int j = 0; int n = count; while (n-- != 0) { if (v1[i++] != cs.charAt(j++)) return false; } return true; } /** * Compares this {@code String} to another {@code String}, ignoring case * considerations. Two strings are considered equal ignoring case if they * are of the same length and corresponding characters in the two strings * are equal ignoring case. * * <p> Two characters {@code c1} and {@code c2} are considered the same * ignoring case if at least one of the following is true: * <ul> * <li> The two characters are the same (as compared by the * {@code ==} operator) * <li> Applying the method {@link * java.lang.Character#toUpperCase(char)} to each character * produces the same result * <li> Applying the method {@link * java.lang.Character#toLowerCase(char)} to each character * produces the same result * </ul> * * @param anotherString * The {@code String} to compare this {@code String} against * * @return {@code true} if the argument is not {@code null} and it * represents an equivalent {@code String} ignoring case; {@code * false} otherwise * * @see #equals(Object) */ public boolean equalsIgnoreCase(String anotherString) { return (this == anotherString) ? true : (anotherString != null) && (anotherString.count == count) && regionMatches(true, 0, anotherString, 0, count); } /** * Compares two strings lexicographically. * The comparison is based on the Unicode value of each character in * the strings. The character sequence represented by this * <code>String</code> object is compared lexicographically to the * character sequence represented by the argument string. The result is * a negative integer if this <code>String</code> object * lexicographically precedes the argument string. The result is a * positive integer if this <code>String</code> object lexicographically * follows the argument string. The result is zero if the strings * are equal; <code>compareTo</code> returns <code>0</code> exactly when * the {@link #equals(Object)} method would return <code>true</code>. * <p> * This is the definition of lexicographic ordering. If two strings are * different, then either they have different characters at some index * that is a valid index for both strings, or their lengths are different, * or both. If they have different characters at one or more index * positions, let <i>k</i> be the smallest such index; then the string * whose character at position <i>k</i> has the smaller value, as * determined by using the &lt; operator, lexicographically precedes the * other string. In this case, <code>compareTo</code> returns the * difference of the two character values at position <code>k</code> in * the two string -- that is, the value: * <blockquote><pre> * this.charAt(k)-anotherString.charAt(k) * </pre></blockquote> * If there is no index position at which they differ, then the shorter * string lexicographically precedes the longer string. In this case, * <code>compareTo</code> returns the difference of the lengths of the * strings -- that is, the value: * <blockquote><pre> * this.length()-anotherString.length() * </pre></blockquote> * * @param anotherString the <code>String</code> to be compared. * @return the value <code>0</code> if the argument string is equal to * this string; a value less than <code>0</code> if this string * is lexicographically less than the string argument; and a * value greater than <code>0</code> if this string is * lexicographically greater than the string argument. */ public int compareTo(String anotherString) { int len1 = count; int len2 = anotherString.count; int n = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; if (i == j) { int k = i; int lim = n + i; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } } else { while (n-- != 0) { char c1 = v1[i++]; char c2 = v2[j++]; if (c1 != c2) { return c1 - c2; } } } return len1 - len2; } /** * A Comparator that orders <code>String</code> objects as by * <code>compareToIgnoreCase</code>. This comparator is serializable. * <p> * Note that this Comparator does <em>not</em> take locale into account, * and will result in an unsatisfactory ordering for certain locales. * The java.text package provides <em>Collators</em> to allow * locale-sensitive ordering. * * @see java.text.Collator#compare(String, String) * @since 1.2 */ public static final Comparator<String> CASE_INSENSITIVE_ORDER = new CaseInsensitiveComparator(); private static class CaseInsensitiveComparator implements Comparator<String>, java.io.Serializable { // use serialVersionUID from JDK 1.2.2 for interoperability private static final long serialVersionUID = 8575799808933029326L; public int compare(String s1, String s2) { int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) { // No overflow because of numeric promotion return c1 - c2; } } } } return n1 - n2; } } /** * Compares two strings lexicographically, ignoring case * differences. This method returns an integer whose sign is that of * calling <code>compareTo</code> with normalized versions of the strings * where case differences have been eliminated by calling * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on * each character. * <p> * Note that this method does <em>not</em> take locale into account, * and will result in an unsatisfactory ordering for certain locales. * The java.text package provides <em>collators</em> to allow * locale-sensitive ordering. * * @param str the <code>String</code> to be compared. * @return a negative integer, zero, or a positive integer as the * specified String is greater than, equal to, or less * than this String, ignoring case considerations. * @see java.text.Collator#compare(String, String) * @since 1.2 */ public int compareToIgnoreCase(String str) { return CASE_INSENSITIVE_ORDER.compare(this, str); } /** * Tests if two string regions are equal. * <p> * A substring of this <tt>String</tt> object is compared to a substring * of the argument other. The result is true if these substrings * represent identical character sequences. The substring of this * <tt>String</tt> object to be compared begins at index <tt>toffset</tt> * and has length <tt>len</tt>. The substring of other to be compared * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The * result is <tt>false</tt> if and only if at least one of the following * is true: * <ul><li><tt>toffset</tt> is negative. * <li><tt>ooffset</tt> is negative. * <li><tt>toffset+len</tt> is greater than the length of this * <tt>String</tt> object. * <li><tt>ooffset+len</tt> is greater than the length of the other * argument. * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt> * such that: * <tt>this.charAt(toffset+<i>k</i>)&nbsp;!=&nbsp;other.charAt(ooffset+<i>k</i>)</tt> * </ul> * * @param toffset the starting offset of the subregion in this string. * @param other the string argument. * @param ooffset the starting offset of the subregion in the string * argument. * @param len the number of characters to compare. * @return <code>true</code> if the specified subregion of this string * exactly matches the specified subregion of the string argument; * <code>false</code> otherwise. */ public boolean regionMatches(int toffset, String other, int ooffset, int len) { char ta[] = value; int to = offset + toffset; char pa[] = other.value; int po = other.offset + ooffset; // Note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) || (toffset > (long)count - len) || (ooffset > (long)other.count - len)) { return false; } while (len-- > 0) { if (ta[to++] != pa[po++]) { return false; } } return true; } /** * Tests if two string regions are equal. * <p> * A substring of this <tt>String</tt> object is compared to a substring * of the argument <tt>other</tt>. The result is <tt>true</tt> if these * substrings represent character sequences that are the same, ignoring * case if and only if <tt>ignoreCase</tt> is true. The substring of * this <tt>String</tt> object to be compared begins at index * <tt>toffset</tt> and has length <tt>len</tt>. The substring of * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and * has length <tt>len</tt>. The result is <tt>false</tt> if and only if * at least one of the following is true: * <ul><li><tt>toffset</tt> is negative. * <li><tt>ooffset</tt> is negative. * <li><tt>toffset+len</tt> is greater than the length of this * <tt>String</tt> object. * <li><tt>ooffset+len</tt> is greater than the length of the other * argument. * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative * integer <i>k</i> less than <tt>len</tt> such that: * <blockquote><pre> * this.charAt(toffset+k) != other.charAt(ooffset+k) * </pre></blockquote> * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative * integer <i>k</i> less than <tt>len</tt> such that: * <blockquote><pre> * Character.toLowerCase(this.charAt(toffset+k)) != Character.toLowerCase(other.charAt(ooffset+k)) * </pre></blockquote> * and: * <blockquote><pre> * Character.toUpperCase(this.charAt(toffset+k)) != * Character.toUpperCase(other.charAt(ooffset+k)) * </pre></blockquote> * </ul> * * @param ignoreCase if <code>true</code>, ignore case when comparing * characters. * @param toffset the starting offset of the subregion in this * string. * @param other the string argument. * @param ooffset the starting offset of the subregion in the string * argument. * @param len the number of characters to compare. * @return <code>true</code> if the specified subregion of this string * matches the specified subregion of the string argument; * <code>false</code> otherwise. Whether the matching is exact * or case insensitive depends on the <code>ignoreCase</code> * argument. */ public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) { char ta[] = value; int to = offset + toffset; char pa[] = other.value; int po = other.offset + ooffset; // Note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) || (toffset > (long)count - len) || (ooffset > (long)other.count - len)) { return false; } while (len-- > 0) { char c1 = ta[to++]; char c2 = pa[po++]; if (c1 == c2) { continue; } if (ignoreCase) { // If characters don't match but case may be ignored, // try converting both characters to uppercase. // If the results match, then the comparison scan should // continue. char u1 = Character.toUpperCase(c1); char u2 = Character.toUpperCase(c2); if (u1 == u2) { continue; } // Unfortunately, conversion to uppercase does not work properly // for the Georgian alphabet, which has strange rules about case // conversion. So we need to make one last check before // exiting. if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { continue; } } return false; } return true; } /** * Tests if the substring of this string beginning at the * specified index starts with the specified prefix. * * @param prefix the prefix. * @param toffset where to begin looking in this string. * @return <code>true</code> if the character sequence represented by the * argument is a prefix of the substring of this object starting * at index <code>toffset</code>; <code>false</code> otherwise. * The result is <code>false</code> if <code>toffset</code> is * negative or greater than the length of this * <code>String</code> object; otherwise the result is the same * as the result of the expression * <pre> * this.substring(toffset).startsWith(prefix) * </pre> */ public boolean startsWith(String prefix, int toffset) { char ta[] = value; int to = offset + toffset; char pa[] = prefix.value; int po = prefix.offset; int pc = prefix.count; // Note: toffset might be near -1>>>1. if ((toffset < 0) || (toffset > count - pc)) { return false; } while (--pc >= 0) { if (ta[to++] != pa[po++]) { return false; } } return true; } /** * Tests if this string starts with the specified prefix. * * @param prefix the prefix. * @return <code>true</code> if the character sequence represented by the * argument is a prefix of the character sequence represented by * this string; <code>false</code> otherwise. * Note also that <code>true</code> will be returned if the * argument is an empty string or is equal to this * <code>String</code> object as determined by the * {@link #equals(Object)} method. * @since 1. 0 */ public boolean startsWith(String prefix) { return startsWith(prefix, 0); } /** * Tests if this string ends with the specified suffix. * * @param suffix the suffix. * @return <code>true</code> if the character sequence represented by the * argument is a suffix of the character sequence represented by * this object; <code>false</code> otherwise. Note that the * result will be <code>true</code> if the argument is the * empty string or is equal to this <code>String</code> object * as determined by the {@link #equals(Object)} method. */ public boolean endsWith(String suffix) { return startsWith(suffix, count - suffix.count); } /** * Returns a hash code for this string. The hash code for a * <code>String</code> object is computed as * <blockquote><pre> * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] * </pre></blockquote> * using <code>int</code> arithmetic, where <code>s[i]</code> is the * <i>i</i>th character of the string, <code>n</code> is the length of * the string, and <code>^</code> indicates exponentiation. * (The hash value of the empty string is zero.) * * @return a hash code value for this object. */ public int hashCode() { int h = hash; if (h == 0 && count > 0) { int off = offset; char val[] = value; int len = count; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } hash = h; } return h; } /** * Returns the index within this string of the first occurrence of * the specified character. If a character with value * <code>ch</code> occurs in the character sequence represented by * this <code>String</code> object, then the index (in Unicode * code units) of the first such occurrence is returned. For * values of <code>ch</code> in the range from 0 to 0xFFFF * (inclusive), this is the smallest value <i>k</i> such that: * <blockquote><pre> * this.charAt(<i>k</i>) == ch * </pre></blockquote> * is true. For other values of <code>ch</code>, it is the * smallest value <i>k</i> such that: * <blockquote><pre> * this.codePointAt(<i>k</i>) == ch * </pre></blockquote> * is true. In either case, if no such character occurs in this * string, then <code>-1</code> is returned. * * @param ch a character (Unicode code point). * @return the index of the first occurrence of the character in the * character sequence represented by this object, or * <code>-1</code> if the character does not occur. */ public int indexOf(int ch) { return indexOf(ch, 0); } /** * Returns the index within this string of the first occurrence of the * specified character, starting the search at the specified index. * <p> * If a character with value <code>ch</code> occurs in the * character sequence represented by this <code>String</code> * object at an index no smaller than <code>fromIndex</code>, then * the index of the first such occurrence is returned. For values * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive), * this is the smallest value <i>k</i> such that: * <blockquote><pre> * (this.charAt(<i>k</i>) == ch) && (<i>k</i> &gt;= fromIndex) * </pre></blockquote> * is true. For other values of <code>ch</code>, it is the * smallest value <i>k</i> such that: * <blockquote><pre> * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> &gt;= fromIndex) * </pre></blockquote> * is true. In either case, if no such character occurs in this * string at or after position <code>fromIndex</code>, then * <code>-1</code> is returned. * * <p> * There is no restriction on the value of <code>fromIndex</code>. If it * is negative, it has the same effect as if it were zero: this entire * string may be searched. If it is greater than the length of this * string, it has the same effect as if it were equal to the length of * this string: <code>-1</code> is returned. * * <p>All indices are specified in <code>char</code> values * (Unicode code units). * * @param ch a character (Unicode code point). * @param fromIndex the index to start the search from. * @return the index of the first occurrence of the character in the * character sequence represented by this object that is greater * than or equal to <code>fromIndex</code>, or <code>-1</code> * if the character does not occur. */ public int indexOf(int ch, int fromIndex) { if (fromIndex < 0) { fromIndex = 0; } else if (fromIndex >= count) { // Note: fromIndex might be near -1>>>1. return -1; } if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { // handle most cases here (ch is a BMP code point or a // negative value (invalid code point)) final char[] value = this.value; final int offset = this.offset; final int max = offset + count; for (int i = offset + fromIndex; i < max ; i++) { if (value[i] == ch) { return i - offset; } } return -1; } else { return indexOfSupplementary(ch, fromIndex); } } /** * Handles (rare) calls of indexOf with a supplementary character. */ private int indexOfSupplementary(int ch, int fromIndex) { if (Character.isValidCodePoint(ch)) { final char[] value = this.value; final int offset = this.offset; final char hi = Character.highSurrogate(ch); final char lo = Character.lowSurrogate(ch); final int max = offset + count - 1; for (int i = offset + fromIndex; i < max; i++) { if (value[i] == hi && value[i+1] == lo) { return i - offset; } } } return -1; } /** * Returns the index within this string of the last occurrence of * the specified character. For values of <code>ch</code> in the * range from 0 to 0xFFFF (inclusive), the index (in Unicode code * units) returned is the largest value <i>k</i> such that: * <blockquote><pre> * this.charAt(<i>k</i>) == ch * </pre></blockquote> * is true. For other values of <code>ch</code>, it is the * largest value <i>k</i> such that: * <blockquote><pre> * this.codePointAt(<i>k</i>) == ch * </pre></blockquote> * is true. In either case, if no such character occurs in this * string, then <code>-1</code> is returned. The * <code>String</code> is searched backwards starting at the last * character. * * @param ch a character (Unicode code point). * @return the index of the last occurrence of the character in the * character sequence represented by this object, or * <code>-1</code> if the character does not occur. */ public int lastIndexOf(int ch) { return lastIndexOf(ch, count - 1); } /** * Returns the index within this string of the last occurrence of * the specified character, searching backward starting at the * specified index. For values of <code>ch</code> in the range * from 0 to 0xFFFF (inclusive), the index returned is the largest * value <i>k</i> such that: * <blockquote><pre> * (this.charAt(<i>k</i>) == ch) && (<i>k</i> &lt;= fromIndex) * </pre></blockquote> * is true. For other values of <code>ch</code>, it is the * largest value <i>k</i> such that: * <blockquote><pre> * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> &lt;= fromIndex) * </pre></blockquote> * is true. In either case, if no such character occurs in this * string at or before position <code>fromIndex</code>, then * <code>-1</code> is returned. * * <p>All indices are specified in <code>char</code> values * (Unicode code units). * * @param ch a character (Unicode code point). * @param fromIndex the index to start the search from. There is no * restriction on the value of <code>fromIndex</code>. If it is * greater than or equal to the length of this string, it has * the same effect as if it were equal to one less than the * length of this string: this entire string may be searched. * If it is negative, it has the same effect as if it were -1: * -1 is returned. * @return the index of the last occurrence of the character in the * character sequence represented by this object that is less * than or equal to <code>fromIndex</code>, or <code>-1</code> * if the character does not occur before that point. */ public int lastIndexOf(int ch, int fromIndex) { if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { // handle most cases here (ch is a BMP code point or a // negative value (invalid code point)) final char[] value = this.value; final int offset = this.offset; int i = offset + Math.min(fromIndex, count - 1); for (; i >= offset ; i--) { if (value[i] == ch) { return i - offset; } } return -1; } else { return lastIndexOfSupplementary(ch, fromIndex); } } /** * Handles (rare) calls of lastIndexOf with a supplementary character. */ private int lastIndexOfSupplementary(int ch, int fromIndex) { if (Character.isValidCodePoint(ch)) { final char[] value = this.value; final int offset = this.offset; char hi = Character.highSurrogate(ch); char lo = Character.lowSurrogate(ch); int i = offset + Math.min(fromIndex, count - 2); for (; i >= offset; i--) { if (value[i] == hi && value[i+1] == lo) { return i - offset; } } } return -1; } /** * Returns the index within this string of the first occurrence of the * specified substring. * * <p>The returned index is the smallest value <i>k</i> for which: * <blockquote><pre> * this.startsWith(str, <i>k</i>) * </pre></blockquote> * If no such value of <i>k</i> exists, then {@code -1} is returned. * * @param str the substring to search for. * @return the index of the first occurrence of the specified substring, * or {@code -1} if there is no such occurrence. */ public int indexOf(String str) { return indexOf(str, 0); } /** * Returns the index within this string of the first occurrence of the * specified substring, starting at the specified index. * * <p>The returned index is the smallest value <i>k</i> for which: * <blockquote><pre> * <i>k</i> &gt;= fromIndex && this.startsWith(str, <i>k</i>) * </pre></blockquote> * If no such value of <i>k</i> exists, then {@code -1} is returned. * * @param str the substring to search for. * @param fromIndex the index from which to start the search. * @return the index of the first occurrence of the specified substring, * starting at the specified index, * or {@code -1} if there is no such occurrence. */ public int indexOf(String str, int fromIndex) { return indexOf(value, offset, count, str.value, str.offset, str.count, fromIndex); } /** * Code shared by String and StringBuffer to do searches. The * source is the character array being searched, and the target * is the string being searched for. * * @param source the characters being searched. * @param sourceOffset offset of the source string. * @param sourceCount count of the source string. * @param target the characters being searched for. * @param targetOffset offset of the target string. * @param targetCount count of the target string. * @param fromIndex the index to begin searching from. */ static int indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) { if (fromIndex >= sourceCount) { return (targetCount == 0 ? sourceCount : -1); } if (fromIndex < 0) { fromIndex = 0; } if (targetCount == 0) { return fromIndex; } char first = target[targetOffset]; int max = sourceOffset + (sourceCount - targetCount); for (int i = sourceOffset + fromIndex; i <= max; i++) { /* Look for first character. */ if (source[i] != first) { while (++i <= max && source[i] != first); } /* Found first character, now look at the rest of v2 */ if (i <= max) { int j = i + 1; int end = j + targetCount - 1; for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* Found whole string. */ return i - sourceOffset; } } } return -1; } /** * Returns the index within this string of the last occurrence of the * specified substring. The last occurrence of the empty string "" * is considered to occur at the index value {@code this.length()}. * * <p>The returned index is the largest value <i>k</i> for which: * <blockquote><pre> * this.startsWith(str, <i>k</i>) * </pre></blockquote> * If no such value of <i>k</i> exists, then {@code -1} is returned. * * @param str the substring to search for. * @return the index of the last occurrence of the specified substring, * or {@code -1} if there is no such occurrence. */ public int lastIndexOf(String str) { return lastIndexOf(str, count); } /** * Returns the index within this string of the last occurrence of the * specified substring, searching backward starting at the specified index. * * <p>The returned index is the largest value <i>k</i> for which: * <blockquote><pre> * <i>k</i> &lt;= fromIndex && this.startsWith(str, <i>k</i>) * </pre></blockquote> * If no such value of <i>k</i> exists, then {@code -1} is returned. * * @param str the substring to search for. * @param fromIndex the index to start the search from. * @return the index of the last occurrence of the specified substring, * searching backward from the specified index, * or {@code -1} if there is no such occurrence. */ public int lastIndexOf(String str, int fromIndex) { return lastIndexOf(value, offset, count, str.value, str.offset, str.count, fromIndex); } /** * Code shared by String and StringBuffer to do searches. The * source is the character array being searched, and the target * is the string being searched for. * * @param source the characters being searched. * @param sourceOffset offset of the source string. * @param sourceCount count of the source string. * @param target the characters being searched for. * @param targetOffset offset of the target string. * @param targetCount count of the target string. * @param fromIndex the index to begin searching from. */ static int lastIndexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) { /* * Check arguments; return immediately where possible. For * consistency, don't check for null str. */ int rightIndex = sourceCount - targetCount; if (fromIndex < 0) { return -1; } if (fromIndex > rightIndex) { fromIndex = rightIndex; } /* Empty string always matches. */ if (targetCount == 0) { return fromIndex; } int strLastIndex = targetOffset + targetCount - 1; char strLastChar = target[strLastIndex]; int min = sourceOffset + targetCount - 1; int i = min + fromIndex; startSearchForLastChar: while (true) { while (i >= min && source[i] != strLastChar) { i--; } if (i < min) { return -1; } int j = i - 1; int start = j - (targetCount - 1); int k = strLastIndex - 1; while (j > start) { if (source[j--] != target[k--]) { i--; continue startSearchForLastChar; } } return start - sourceOffset + 1; } } /** * Returns a new string that is a substring of this string. The * substring begins with the character at the specified index and * extends to the end of this string. <p> * Examples: * <blockquote><pre> * "unhappy".substring(2) returns "happy" * "Harbison".substring(3) returns "bison" * "emptiness".substring(9) returns "" (an empty string) * </pre></blockquote> * * @param beginIndex the beginning index, inclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if * <code>beginIndex</code> is negative or larger than the * length of this <code>String</code> object. */ public String substring(int beginIndex) { return substring(beginIndex, count); } /** * Returns a new string that is a substring of this string. The * substring begins at the specified <code>beginIndex</code> and * extends to the character at index <code>endIndex - 1</code>. * Thus the length of the substring is <code>endIndex-beginIndex</code>. * <p> * Examples: * <blockquote><pre> * "hamburger".substring(4, 8) returns "urge" * "smiles".substring(1, 5) returns "mile" * </pre></blockquote> * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * <code>beginIndex</code> is negative, or * <code>endIndex</code> is larger than the length of * this <code>String</code> object, or * <code>beginIndex</code> is larger than * <code>endIndex</code>. */ public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > count) { throw new StringIndexOutOfBoundsException(endIndex); } if (beginIndex > endIndex) { throw new StringIndexOutOfBoundsException(endIndex - beginIndex); } return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex, endIndex - beginIndex, value); } /** * Returns a new character sequence that is a subsequence of this sequence. * * <p> An invocation of this method of the form * * <blockquote><pre> * str.subSequence(begin,&nbsp;end)</pre></blockquote> * * behaves in exactly the same way as the invocation * * <blockquote><pre> * str.substring(begin,&nbsp;end)</pre></blockquote> * * This method is defined so that the <tt>String</tt> class can implement * the {@link CharSequence} interface. </p> * * @param beginIndex the begin index, inclusive. * @param endIndex the end index, exclusive. * @return the specified subsequence. * * @throws IndexOutOfBoundsException * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative, * if <tt>endIndex</tt> is greater than <tt>length()</tt>, * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt> * * @since 1.4 * @spec JSR-51 */ public CharSequence subSequence(int beginIndex, int endIndex) { return this.substring(beginIndex, endIndex); } /** * Concatenates the specified string to the end of this string. * <p> * If the length of the argument string is <code>0</code>, then this * <code>String</code> object is returned. Otherwise, a new * <code>String</code> object is created, representing a character * sequence that is the concatenation of the character sequence * represented by this <code>String</code> object and the character * sequence represented by the argument string.<p> * Examples: * <blockquote><pre> * "cares".concat("s") returns "caress" * "to".concat("get").concat("her") returns "together" * </pre></blockquote> * * @param str the <code>String</code> that is concatenated to the end * of this <code>String</code>. * @return a string that represents the concatenation of this object's * characters followed by the string argument's characters. */ public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } char buf[] = new char[count + otherLen]; getChars(0, count, buf, 0); str.getChars(0, otherLen, buf, count); return new String(0, count + otherLen, buf); } /** * Returns a new string resulting from replacing all occurrences of * <code>oldChar</code> in this string with <code>newChar</code>. * <p> * If the character <code>oldChar</code> does not occur in the * character sequence represented by this <code>String</code> object, * then a reference to this <code>String</code> object is returned. * Otherwise, a new <code>String</code> object is created that * represents a character sequence identical to the character sequence * represented by this <code>String</code> object, except that every * occurrence of <code>oldChar</code> is replaced by an occurrence * of <code>newChar</code>. * <p> * Examples: * <blockquote><pre> * "mesquite in your cellar".replace('e', 'o') * returns "mosquito in your collar" * "the war of baronets".replace('r', 'y') * returns "the way of bayonets" * "sparring with a purple porpoise".replace('p', 't') * returns "starring with a turtle tortoise" * "JonL".replace('q', 'x') returns "JonL" (no change) * </pre></blockquote> * * @param oldChar the old character. * @param newChar the new character. * @return a string derived from this string by replacing every * occurrence of <code>oldChar</code> with <code>newChar</code>. */ public String replace(char oldChar, char newChar) { if (oldChar != newChar) { int len = count; int i = -1; char[] val = value; /* avoid getfield opcode */ int off = offset; /* avoid getfield opcode */ while (++i < len) { if (val[off + i] == oldChar) { break; } } if (i < len) { char buf[] = new char[len]; for (int j = 0 ; j < i ; j++) { buf[j] = val[off+j]; } while (i < len) { char c = val[off + i]; buf[i] = (c == oldChar) ? newChar : c; i++; } return new String(0, len, buf); } } return this; } /** * Tells whether or not this string matches the given <a * href="../util/regex/Pattern.html#sum">regular expression</a>. * * <p> An invocation of this method of the form * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the * same result as the expression * * <blockquote><tt> {@link java.util.regex.Pattern}.{@link * java.util.regex.Pattern#matches(String,CharSequence) * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote> * * @param regex * the regular expression to which this string is to be matched * * @return <tt>true</tt> if, and only if, this string matches the * given regular expression * * @throws PatternSyntaxException * if the regular expression's syntax is invalid * * @see java.util.regex.Pattern * * @since 1.4 * @spec JSR-51 */ public boolean matches(String regex) { return Pattern.matches(regex, this); } /** * Returns true if and only if this string contains the specified * sequence of char values. * * @param s the sequence to search for * @return true if this string contains <code>s</code>, false otherwise * @throws NullPointerException if <code>s</code> is <code>null</code> * @since 1.5 */ public boolean contains(CharSequence s) { return indexOf(s.toString()) > -1; } /** * Replaces the first substring of this string that matches the given <a * href="../util/regex/Pattern.html#sum">regular expression</a> with the * given replacement. * * <p> An invocation of this method of the form * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt> * yields exactly the same result as the expression * * <blockquote><tt> * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile * compile}(</tt><i>regex</i><tt>).{@link * java.util.regex.Pattern#matcher(java.lang.CharSequence) * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote> * *<p> * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the * replacement string may cause the results to be different than if it were * being treated as a literal replacement string; see * {@link java.util.regex.Matcher#replaceFirst}. * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special * meaning of these characters, if desired. * * @param regex * the regular expression to which this string is to be matched * @param replacement * the string to be substituted for the first match * * @return The resulting <tt>String</tt> * * @throws PatternSyntaxException * if the regular expression's syntax is invalid * * @see java.util.regex.Pattern * * @since 1.4 * @spec JSR-51 */ public String replaceFirst(String regex, String replacement) { return Pattern.compile(regex).matcher(this).replaceFirst(replacement); } /** * Replaces each substring of this string that matches the given <a * href="../util/regex/Pattern.html#sum">regular expression</a> with the * given replacement. * * <p> An invocation of this method of the form * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt> * yields exactly the same result as the expression * * <blockquote><tt> * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile * compile}(</tt><i>regex</i><tt>).{@link * java.util.regex.Pattern#matcher(java.lang.CharSequence) * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote> * *<p> * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the * replacement string may cause the results to be different than if it were * being treated as a literal replacement string; see * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}. * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special * meaning of these characters, if desired. * * @param regex * the regular expression to which this string is to be matched * @param replacement * the string to be substituted for each match * * @return The resulting <tt>String</tt> * * @throws PatternSyntaxException * if the regular expression's syntax is invalid * * @see java.util.regex.Pattern * * @since 1.4 * @spec JSR-51 */ public String replaceAll(String regex, String replacement) { return Pattern.compile(regex).matcher(this).replaceAll(replacement); } /** * Replaces each substring of this string that matches the literal target * sequence with the specified literal replacement sequence. The * replacement proceeds from the beginning of the string to the end, for * example, replacing "aa" with "b" in the string "aaa" will result in * "ba" rather than "ab". * * @param target The sequence of char values to be replaced * @param replacement The replacement sequence of char values * @return The resulting string * @throws NullPointerException if <code>target</code> or * <code>replacement</code> is <code>null</code>. * @since 1.5 */ public String replace(CharSequence target, CharSequence replacement) { return Pattern.compile(target.toString(), Pattern.LITERAL).matcher( this).replaceAll(Matcher.quoteReplacement(replacement.toString())); } /** * Splits this string around matches of the given * <a href="../util/regex/Pattern.html#sum">regular expression</a>. * * <p> The array returned by this method contains each substring of this * string that is terminated by another substring that matches the given * expression or is terminated by the end of the string. The substrings in * the array are in the order in which they occur in this string. If the * expression does not match any part of the input then the resulting array * has just one element, namely this string. * * <p> The <tt>limit</tt> parameter controls the number of times the * pattern is applied and therefore affects the length of the resulting * array. If the limit <i>n</i> is greater than zero then the pattern * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's * length will be no greater than <i>n</i>, and the array's last entry * will contain all input beyond the last matched delimiter. If <i>n</i> * is non-positive then the pattern will be applied as many times as * possible and the array can have any length. If <i>n</i> is zero then * the pattern will be applied as many times as possible, the array can * have any length, and trailing empty strings will be discarded. * * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the * following results with these parameters: * * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result"> * <tr> * <th>Regex</th> * <th>Limit</th> * <th>Result</th> * </tr> * <tr><td align=center>:</td> * <td align=center>2</td> * <td><tt>{ "boo", "and:foo" }</tt></td></tr> * <tr><td align=center>:</td> * <td align=center>5</td> * <td><tt>{ "boo", "and", "foo" }</tt></td></tr> * <tr><td align=center>:</td> * <td align=center>-2</td> * <td><tt>{ "boo", "and", "foo" }</tt></td></tr> * <tr><td align=center>o</td> * <td align=center>5</td> * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr> * <tr><td align=center>o</td> * <td align=center>-2</td> * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr> * <tr><td align=center>o</td> * <td align=center>0</td> * <td><tt>{ "b", "", ":and:f" }</tt></td></tr> * </table></blockquote> * * <p> An invocation of this method of the form * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt>&nbsp;<i>n</i><tt>)</tt> * yields the same result as the expression * * <blockquote> * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link * java.util.regex.Pattern#split(java.lang.CharSequence,int) * split}<tt>(</tt><i>str</i><tt>,</tt>&nbsp;<i>n</i><tt>)</tt> * </blockquote> * * * @param regex * the delimiting regular expression * * @param limit * the result threshold, as described above * * @return the array of strings computed by splitting this string * around matches of the given regular expression * * @throws PatternSyntaxException * if the regular expression's syntax is invalid * * @see java.util.regex.Pattern * * @since 1.4 * @spec JSR-51 */ public String[] split(String regex, int limit) { /* fastpath if the regex is a (1)one-char String and this character is not one of the RegEx's meta characters ".$|()[{^?*+\\", or (2)two-char String and the first char is the backslash and the second is not the ascii digit or ascii letter. */ char ch = 0; if (((regex.count == 1 && ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) || (regex.length() == 2 && regex.charAt(0) == '\\' && (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 && ((ch-'a')|('z'-ch)) < 0 && ((ch-'A')|('Z'-ch)) < 0)) && (ch < Character.MIN_HIGH_SURROGATE || ch > Character.MAX_LOW_SURROGATE)) { int off = 0; int next = 0; boolean limited = limit > 0; ArrayList<String> list = new ArrayList<>(); while ((next = indexOf(ch, off)) != -1) { if (!limited || list.size() < limit - 1) { list.add(substring(off, next)); off = next + 1; } else { // last one //assert (list.size() == limit - 1); list.add(substring(off, count)); off = count; break; } } // If no match was found, return this if (off == 0) return new String[] { this }; // Add remaining segment if (!limited || list.size() < limit) list.add(substring(off, count)); // Construct result int resultSize = list.size(); if (limit == 0) while (resultSize > 0 && list.get(resultSize-1).length() == 0) resultSize--; String[] result = new String[resultSize]; return list.subList(0, resultSize).toArray(result); } return Pattern.compile(regex).split(this, limit); } /** * Splits this string around matches of the given <a * href="../util/regex/Pattern.html#sum">regular expression</a>. * * <p> This method works as if by invoking the two-argument {@link * #split(String, int) split} method with the given expression and a limit * argument of zero. Trailing empty strings are therefore not included in * the resulting array. * * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following * results with these expressions: * * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result"> * <tr> * <th>Regex</th> * <th>Result</th> * </tr> * <tr><td align=center>:</td> * <td><tt>{ "boo", "and", "foo" }</tt></td></tr> * <tr><td align=center>o</td> * <td><tt>{ "b", "", ":and:f" }</tt></td></tr> * </table></blockquote> * * * @param regex * the delimiting regular expression * * @return the array of strings computed by splitting this string * around matches of the given regular expression * * @throws PatternSyntaxException * if the regular expression's syntax is invalid * * @see java.util.regex.Pattern * * @since 1.4 * @spec JSR-51 */ public String[] split(String regex) { return split(regex, 0); } /** * Converts all of the characters in this <code>String</code> to lower * case using the rules of the given <code>Locale</code>. Case mapping is based * on the Unicode Standard version specified by the {@link java.lang.Character Character} * class. Since case mappings are not always 1:1 char mappings, the resulting * <code>String</code> may be a different length than the original <code>String</code>. * <p> * Examples of lowercase mappings are in the following table: * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description"> * <tr> * <th>Language Code of Locale</th> * <th>Upper Case</th> * <th>Lower Case</th> * <th>Description</th> * </tr> * <tr> * <td>tr (Turkish)</td> * <td>&#92;u0130</td> * <td>&#92;u0069</td> * <td>capital letter I with dot above -&gt; small letter i</td> * </tr> * <tr> * <td>tr (Turkish)</td> * <td>&#92;u0049</td> * <td>&#92;u0131</td> * <td>capital letter I -&gt; small letter dotless i </td> * </tr> * <tr> * <td>(all)</td> * <td>French Fries</td> * <td>french fries</td> * <td>lowercased all chars in String</td> * </tr> * <tr> * <td>(all)</td> * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi"> * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil"> * <img src="doc-files/capsigma.gif" alt="capsigma"></td> * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi"> * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon"> * <img src="doc-files/sigma1.gif" alt="sigma"></td> * <td>lowercased all chars in String</td> * </tr> * </table> * * @param locale use the case transformation rules for this locale * @return the <code>String</code>, converted to lowercase. * @see java.lang.String#toLowerCase() * @see java.lang.String#toUpperCase() * @see java.lang.String#toUpperCase(Locale) * @since 1.1 */ public String toLowerCase(Locale locale) { if (locale == null) { throw new NullPointerException(); } int firstUpper; /* Now check if there are any characters that need to be changed. */ scan: { for (firstUpper = 0 ; firstUpper < count; ) { char c = value[offset+firstUpper]; if ((c >= Character.MIN_HIGH_SURROGATE) && (c <= Character.MAX_HIGH_SURROGATE)) { int supplChar = codePointAt(firstUpper); if (supplChar != Character.toLowerCase(supplChar)) { break scan; } firstUpper += Character.charCount(supplChar); } else { if (c != Character.toLowerCase(c)) { break scan; } firstUpper++; } } return this; } char[] result = new char[count]; int resultOffset = 0; /* result may grow, so i+resultOffset * is the write location in result */ /* Just copy the first few lowerCase characters. */ System.arraycopy(value, offset, result, 0, firstUpper); String lang = locale.getLanguage(); boolean localeDependent = (lang == "tr" || lang == "az" || lang == "lt"); char[] lowerCharArray; int lowerChar; int srcChar; int srcCount; for (int i = firstUpper; i < count; i += srcCount) { srcChar = (int)value[offset+i]; if ((char)srcChar >= Character.MIN_HIGH_SURROGATE && (char)srcChar <= Character.MAX_HIGH_SURROGATE) { srcChar = codePointAt(i); srcCount = Character.charCount(srcChar); } else { srcCount = 1; } if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale); } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT lowerChar = Character.ERROR; } else { lowerChar = Character.toLowerCase(srcChar); } if ((lowerChar == Character.ERROR) || (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) { if (lowerChar == Character.ERROR) { if (!localeDependent && srcChar == '\u0130') { lowerCharArray = ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH); } else { lowerCharArray = ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale); } } else if (srcCount == 2) { resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount; continue; } else { lowerCharArray = Character.toChars(lowerChar); } /* Grow result if needed */ int mapLen = lowerCharArray.length; if (mapLen > srcCount) { char[] result2 = new char[result.length + mapLen - srcCount]; System.arraycopy(result, 0, result2, 0, i + resultOffset); result = result2; } for (int x=0; x<mapLen; ++x) { result[i+resultOffset+x] = lowerCharArray[x]; } resultOffset += (mapLen - srcCount); } else { result[i+resultOffset] = (char)lowerChar; } } return new String(0, count+resultOffset, result); } /** * Converts all of the characters in this <code>String</code> to lower * case using the rules of the default locale. This is equivalent to calling * <code>toLowerCase(Locale.getDefault())</code>. * <p> * <b>Note:</b> This method is locale sensitive, and may produce unexpected * results if used for strings that are intended to be interpreted locale * independently. * Examples are programming language identifiers, protocol keys, and HTML * tags. * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the * LATIN SMALL LETTER DOTLESS I character. * To obtain correct results for locale insensitive strings, use * <code>toLowerCase(Locale.ENGLISH)</code>. * <p> * @return the <code>String</code>, converted to lowercase. * @see java.lang.String#toLowerCase(Locale) */ public String toLowerCase() { return toLowerCase(Locale.getDefault()); } /** * Converts all of the characters in this <code>String</code> to upper * case using the rules of the given <code>Locale</code>. Case mapping is based * on the Unicode Standard version specified by the {@link java.lang.Character Character} * class. Since case mappings are not always 1:1 char mappings, the resulting * <code>String</code> may be a different length than the original <code>String</code>. * <p> * Examples of locale-sensitive and 1:M case mappings are in the following table. * <p> * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description."> * <tr> * <th>Language Code of Locale</th> * <th>Lower Case</th> * <th>Upper Case</th> * <th>Description</th> * </tr> * <tr> * <td>tr (Turkish)</td> * <td>&#92;u0069</td> * <td>&#92;u0130</td> * <td>small letter i -&gt; capital letter I with dot above</td> * </tr> * <tr> * <td>tr (Turkish)</td> * <td>&#92;u0131</td> * <td>&#92;u0049</td> * <td>small letter dotless i -&gt; capital letter I</td> * </tr> * <tr> * <td>(all)</td> * <td>&#92;u00df</td> * <td>&#92;u0053 &#92;u0053</td> * <td>small letter sharp s -&gt; two letters: SS</td> * </tr> * <tr> * <td>(all)</td> * <td>Fahrvergn&uuml;gen</td> * <td>FAHRVERGN&Uuml;GEN</td> * <td></td> * </tr> * </table> * @param locale use the case transformation rules for this locale * @return the <code>String</code>, converted to uppercase. * @see java.lang.String#toUpperCase() * @see java.lang.String#toLowerCase() * @see java.lang.String#toLowerCase(Locale) * @since 1.1 */ public String toUpperCase(Locale locale) { if (locale == null) { throw new NullPointerException(); } int firstLower; /* Now check if there are any characters that need to be changed. */ scan: { for (firstLower = 0 ; firstLower < count; ) { int c = (int)value[offset+firstLower]; int srcCount; if ((c >= Character.MIN_HIGH_SURROGATE) && (c <= Character.MAX_HIGH_SURROGATE)) { c = codePointAt(firstLower); srcCount = Character.charCount(c); } else { srcCount = 1; } int upperCaseChar = Character.toUpperCaseEx(c); if ((upperCaseChar == Character.ERROR) || (c != upperCaseChar)) { break scan; } firstLower += srcCount; } return this; } char[] result = new char[count]; /* may grow */ int resultOffset = 0; /* result may grow, so i+resultOffset * is the write location in result */ /* Just copy the first few upperCase characters. */ System.arraycopy(value, offset, result, 0, firstLower); String lang = locale.getLanguage(); boolean localeDependent = (lang == "tr" || lang == "az" || lang == "lt"); char[] upperCharArray; int upperChar; int srcChar; int srcCount; for (int i = firstLower; i < count; i += srcCount) { srcChar = (int)value[offset+i]; if ((char)srcChar >= Character.MIN_HIGH_SURROGATE && (char)srcChar <= Character.MAX_HIGH_SURROGATE) { srcChar = codePointAt(i); srcCount = Character.charCount(srcChar); } else { srcCount = 1; } if (localeDependent) { upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale); } else { upperChar = Character.toUpperCaseEx(srcChar); } if ((upperChar == Character.ERROR) || (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) { if (upperChar == Character.ERROR) { if (localeDependent) { upperCharArray = ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale); } else { upperCharArray = Character.toUpperCaseCharArray(srcChar); } } else if (srcCount == 2) { resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount; continue; } else { upperCharArray = Character.toChars(upperChar); } /* Grow result if needed */ int mapLen = upperCharArray.length; if (mapLen > srcCount) { char[] result2 = new char[result.length + mapLen - srcCount]; System.arraycopy(result, 0, result2, 0, i + resultOffset); result = result2; } for (int x=0; x<mapLen; ++x) { result[i+resultOffset+x] = upperCharArray[x]; } resultOffset += (mapLen - srcCount); } else { result[i+resultOffset] = (char)upperChar; } } return new String(0, count+resultOffset, result); } /** * Converts all of the characters in this <code>String</code> to upper * case using the rules of the default locale. This method is equivalent to * <code>toUpperCase(Locale.getDefault())</code>. * <p> * <b>Note:</b> This method is locale sensitive, and may produce unexpected * results if used for strings that are intended to be interpreted locale * independently. * Examples are programming language identifiers, protocol keys, and HTML * tags. * For instance, <code>"title".toUpperCase()</code> in a Turkish locale * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the * LATIN CAPITAL LETTER I WITH DOT ABOVE character. * To obtain correct results for locale insensitive strings, use * <code>toUpperCase(Locale.ENGLISH)</code>. * <p> * @return the <code>String</code>, converted to uppercase. * @see java.lang.String#toUpperCase(Locale) */ public String toUpperCase() { return toUpperCase(Locale.getDefault()); } /** * Returns a copy of the string, with leading and trailing whitespace * omitted. * <p> * If this <code>String</code> object represents an empty character * sequence, or the first and last characters of character sequence * represented by this <code>String</code> object both have codes * greater than <code>'&#92;u0020'</code> (the space character), then a * reference to this <code>String</code> object is returned. * <p> * Otherwise, if there is no character with a code greater than * <code>'&#92;u0020'</code> in the string, then a new * <code>String</code> object representing an empty string is created * and returned. * <p> * Otherwise, let <i>k</i> be the index of the first character in the * string whose code is greater than <code>'&#92;u0020'</code>, and let * <i>m</i> be the index of the last character in the string whose code * is greater than <code>'&#92;u0020'</code>. A new <code>String</code> * object is created, representing the substring of this string that * begins with the character at index <i>k</i> and ends with the * character at index <i>m</i>-that is, the result of * <code>this.substring(<i>k</i>,&nbsp;<i>m</i>+1)</code>. * <p> * This method may be used to trim whitespace (as defined above) from * the beginning and end of a string. * * @return A copy of this string with leading and trailing white * space removed, or this string if it has no leading or * trailing white space. */ public String trim() { int len = count; int st = 0; int off = offset; /* avoid getfield opcode */ char[] val = value; /* avoid getfield opcode */ while ((st < len) && (val[off + st] <= ' ')) { st++; } while ((st < len) && (val[off + len - 1] <= ' ')) { len--; } return ((st > 0) || (len < count)) ? substring(st, len) : this; } /** * This object (which is already a string!) is itself returned. * * @return the string itself. */ public String toString() { return this; } /** * Converts this string to a new character array. * * @return a newly allocated character array whose length is the length * of this string and whose contents are initialized to contain * the character sequence represented by this string. */ public char[] toCharArray() { char result[] = new char[count]; getChars(0, count, result, 0); return result; } /** * Returns a formatted string using the specified format string and * arguments. * * <p> The locale always used is the one returned by {@link * java.util.Locale#getDefault() Locale.getDefault()}. * * @param format * A <a href="../util/Formatter.html#syntax">format string</a> * * @param args * Arguments referenced by the format specifiers in the format * string. If there are more arguments than format specifiers, the * extra arguments are ignored. The number of arguments is * variable and may be zero. The maximum number of arguments is * limited by the maximum dimension of a Java array as defined by * <cite>The Java&trade; Virtual Machine Specification</cite>. * The behaviour on a * <tt>null</tt> argument depends on the <a * href="../util/Formatter.html#syntax">conversion</a>. * * @throws IllegalFormatException * If a format string contains an illegal syntax, a format * specifier that is incompatible with the given arguments, * insufficient arguments given the format string, or other * illegal conditions. For specification of all possible * formatting errors, see the <a * href="../util/Formatter.html#detail">Details</a> section of the * formatter class specification. * * @throws NullPointerException * If the <tt>format</tt> is <tt>null</tt> * * @return A formatted string * * @see java.util.Formatter * @since 1.5 */ public static String format(String format, Object ... args) { return new Formatter().format(format, args).toString(); } /** * Returns a formatted string using the specified locale, format string, * and arguments. * * @param l * The {@linkplain java.util.Locale locale} to apply during * formatting. If <tt>l</tt> is <tt>null</tt> then no localization * is applied. * * @param format * A <a href="../util/Formatter.html#syntax">format string</a> * * @param args * Arguments referenced by the format specifiers in the format * string. If there are more arguments than format specifiers, the * extra arguments are ignored. The number of arguments is * variable and may be zero. The maximum number of arguments is * limited by the maximum dimension of a Java array as defined by * <cite>The Java&trade; Virtual Machine Specification</cite>. * The behaviour on a * <tt>null</tt> argument depends on the <a * href="../util/Formatter.html#syntax">conversion</a>. * * @throws IllegalFormatException * If a format string contains an illegal syntax, a format * specifier that is incompatible with the given arguments, * insufficient arguments given the format string, or other * illegal conditions. For specification of all possible * formatting errors, see the <a * href="../util/Formatter.html#detail">Details</a> section of the * formatter class specification * * @throws NullPointerException * If the <tt>format</tt> is <tt>null</tt> * * @return A formatted string * * @see java.util.Formatter * @since 1.5 */ public static String format(Locale l, String format, Object ... args) { return new Formatter(l).format(format, args).toString(); } /** * Returns the string representation of the <code>Object</code> argument. * * @param obj an <code>Object</code>. * @return if the argument is <code>null</code>, then a string equal to * <code>"null"</code>; otherwise, the value of * <code>obj.toString()</code> is returned. * @see java.lang.Object#toString() */ public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); } /** * Returns the string representation of the <code>char</code> array * argument. The contents of the character array are copied; subsequent * modification of the character array does not affect the newly * created string. * * @param data a <code>char</code> array. * @return a newly allocated string representing the same sequence of * characters contained in the character array argument. */ public static String valueOf(char data[]) { return new String(data); } /** * Returns the string representation of a specific subarray of the * <code>char</code> array argument. * <p> * The <code>offset</code> argument is the index of the first * character of the subarray. The <code>count</code> argument * specifies the length of the subarray. The contents of the subarray * are copied; subsequent modification of the character array does not * affect the newly created string. * * @param data the character array. * @param offset the initial offset into the value of the * <code>String</code>. * @param count the length of the value of the <code>String</code>. * @return a string representing the sequence of characters contained * in the subarray of the character array argument. * @exception IndexOutOfBoundsException if <code>offset</code> is * negative, or <code>count</code> is negative, or * <code>offset+count</code> is larger than * <code>data.length</code>. */ public static String valueOf(char data[], int offset, int count) { return new String(data, offset, count); } /** * Returns a String that represents the character sequence in the * array specified. * * @param data the character array. * @param offset initial offset of the subarray. * @param count length of the subarray. * @return a <code>String</code> that contains the characters of the * specified subarray of the character array. */ public static String copyValueOf(char data[], int offset, int count) { // All public String constructors now copy the data. return new String(data, offset, count); } /** * Returns a String that represents the character sequence in the * array specified. * * @param data the character array. * @return a <code>String</code> that contains the characters of the * character array. */ public static String copyValueOf(char data[]) { return copyValueOf(data, 0, data.length); } /** * Returns the string representation of the <code>boolean</code> argument. * * @param b a <code>boolean</code>. * @return if the argument is <code>true</code>, a string equal to * <code>"true"</code> is returned; otherwise, a string equal to * <code>"false"</code> is returned. */ public static String valueOf(boolean b) { return b ? "true" : "false"; } /** * Returns the string representation of the <code>char</code> * argument. * * @param c a <code>char</code>. * @return a string of length <code>1</code> containing * as its single character the argument <code>c</code>. */ public static String valueOf(char c) { char data[] = {c}; return new String(0, 1, data); } /** * Returns the string representation of the <code>int</code> argument. * <p> * The representation is exactly the one returned by the * <code>Integer.toString</code> method of one argument. * * @param i an <code>int</code>. * @return a string representation of the <code>int</code> argument. * @see java.lang.Integer#toString(int, int) */ public static String valueOf(int i) { return Integer.toString(i); } /** * Returns the string representation of the <code>long</code> argument. * <p> * The representation is exactly the one returned by the * <code>Long.toString</code> method of one argument. * * @param l a <code>long</code>. * @return a string representation of the <code>long</code> argument. * @see java.lang.Long#toString(long) */ public static String valueOf(long l) { return Long.toString(l); } /** * Returns the string representation of the <code>float</code> argument. * <p> * The representation is exactly the one returned by the * <code>Float.toString</code> method of one argument. * * @param f a <code>float</code>. * @return a string representation of the <code>float</code> argument. * @see java.lang.Float#toString(float) */ public static String valueOf(float f) { return Float.toString(f); } /** * Returns the string representation of the <code>double</code> argument. * <p> * The representation is exactly the one returned by the * <code>Double.toString</code> method of one argument. * * @param d a <code>double</code>. * @return a string representation of the <code>double</code> argument. * @see java.lang.Double#toString(double) */ public static String valueOf(double d) { return Double.toString(d); } /** * Returns a canonical representation for the string object. * <p> * A pool of strings, initially empty, is maintained privately by the * class <code>String</code>. * <p> * When the intern method is invoked, if the pool already contains a * string equal to this <code>String</code> object as determined by * the {@link #equals(Object)} method, then the string from the pool is * returned. Otherwise, this <code>String</code> object is added to the * pool and a reference to this <code>String</code> object is returned. * <p> * It follows that for any two strings <code>s</code> and <code>t</code>, * <code>s.intern()&nbsp;==&nbsp;t.intern()</code> is <code>true</code> * if and only if <code>s.equals(t)</code> is <code>true</code>. * <p> * All literal strings and string-valued constant expressions are * interned. String literals are defined in section 3.10.5 of the * <cite>The Java&trade; Language Specification</cite>. * * @return a string that has the same contents as this string, but is * guaranteed to be from a pool of unique strings. */ public native String intern(); }
THSJF/kuqAutoreply
String.java
249,563
public class User { public static String Name1, Name2; public static int Score1 = 0, Score2 = 0; public static int sw1 = 0; public static int sw2 = 1; public static String turn; public static int numberOfCard1 = 0; public static int numberOfCard2 = 0; public static String winPlayer; public static boolean prizeClaw1_1, prizeClaw1_2, prizeClaw2_1, prizeClaw2_2, prizeClaw3_1, prizeClaw3_2; public static int cardPanel11_1 = 0, cardPanel11_2 = 0; public static int cardPanel12_1 = 0, cardPanel12_2 = 0; public static int cardPanel13_1 = 0, cardPanel13_2 = 0; public static int cardPanel14_1 = 0, cardPanel14_2 = 0; public static int cardPanel15_1 = 0, cardPanel15_2 = 0; public static int cardPanel21_1 = 0, cardPanel21_2 = 0; public static int cardPanel22_1 = 0, cardPanel22_2 = 0; public static int cardPanel23_1 = 0, cardPanel23_2 = 0; public static int cardPanel24_1 = 0, cardPanel24_2 = 0; public static int cardPanel25_1 = 0, cardPanel25_2 = 0; public static int cardPanel31_1 = 0, cardPanel31_2 = 0; public static int cardPanel32_1 = 0, cardPanel32_2 = 0; public static int cardPanel33_1 = 0, cardPanel33_2 = 0; public static int cardPanel34_1 = 0, cardPanel34_2 = 0; public static int cardPanel35_1 = 0, cardPanel35_2 = 0; public static int numberRedCoin1 = 0, numberRedCoin2 = 0; public static int numberGreenCoin1 = 0, numberGreenCoin2 = 0; public static int numberBlueCoin1 = 0, numberBlueCoin2 = 0; public static int numberWhiteCoin1 = 0, numberWhiteCoin2 = 0; public static int numberBlackCoin1 = 0, numberBlackCoin2 = 0; public static int numberGoldCoin1 = 0, numberGoldCoin2 = 0; public static int numberSpecialRedCoin1 = 0, numberSpecialRedCoin2 = 0; public static int numberSpecialGreenCoin1 = 0, numberSpecialGreenCoin2 = 0; public static int numberSpecialBlueCoin1 = 0, numberSpecialBlueCoin2 = 0; public static int numberSpecialWhiteCoin1 = 0, numberSpecialWhiteCoin2 = 0; public static int numberSpecialBlackCoin1 = 0, numberSpecialBlackCoin2 = 0; public static String cardReserve1_1, cardReserve2_1, cardReserve3_1; public static String cardReserve1_2, cardReserve2_2, cardReserve3_2; public static int reserveNumber1 = 0, reserveNumber2 = 0; public static int numberUserGetRedCoin = 0; public static int numberUserGetGreenCoin = 0; public static int numberUserGetBlueCoin = 0; public static int numberUserGetWhiteCoin = 0; public static int numberUserGetBlackCoin = 0; }
alihidson/Amusement-Park
User.java
249,587
package Ai_main; import java.util.*; public class depth { private int V; private LinkedList<Integer>adj[]; depth(int v){ V=v; adj = new LinkedList[v]; for(int i=0;i<v;i++){ adj[i]=new LinkedList(); } } void addEdge(int v,int w){ adj[v].add(w); } void DFSUtil(int v,boolean visited[]){ visited[v]=true; System.out.println(v + " "); Iterator<Integer>i=adj[v].listIterator(); while(i.hasNext()){ int n =i.next(); if(!visited[n]){ DFSUtil(n, visited); } } } void dfs(int v){ boolean visited[]=new boolean[V]; DFSUtil(v, visited); } /*************/ void bfs(int s){ boolean visited[]=new boolean[V]; LinkedList<Integer>queue= new LinkedList<Integer>(); visited[s]=true; queue.add(s); while(queue.size()!=0){ s= queue.poll(); System.out.print(s +" "); Iterator<Integer>i = adj[s].listIterator(); while(i.hasNext()){ int n = i.next(); if(!visited[n]){ visited[n]=true; queue.add(n); } } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enterno of vertex"); int n = sc.nextInt(); System.out.println("enter no of edges"); int e= sc.nextInt(); depth g = new depth(n); System.out.println("enter the edges (S & D)"); for(int i=0;i<e;i++){ int a= sc.nextInt(); int b = sc.nextInt(); g.addEdge(a,b); } System.out.println("enter start vertex"); int s= sc.nextInt(); System.out.println("dfs traversal"); g.dfs(s); System.out.println("bfs traversal"); g.bfs(s); } }
vaishnavi6607/AI_LAB
depth.java
249,589
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; public class Tree { private Node root; public Tree() { root = null; } private Node insertAt(Node node, Content content) { if (node == null) node = new Node(content); else { if (content.id < node.getContent().id) node.left = insertAt(node.left, content); if (content.id > node.getContent().id) node.right = insertAt(node.right, content); if (content.id == node.getContent().id) System.out.println("mach ich nicht"); } return node; } private void printAscAt(Node node) { if (node == null) return; printAscAt(node.left); System.out.print(node.getContent().id + " "); printAscAt(node.right); } public void insert(Content content) { root = insertAt(root, content); } /** * Prints all elements of the tree in ascending order */ public void printAsc() { printAscAt(root); System.out.println(); } /** * @param id the id you want to search for * @return Content of the node if it was found */ public Content search(int id) { return searchAt(this.root, id); } /** * @param node the parent node from which the function will recurse * @param id the id to search for * @return Content if it was found */ private Content searchAt(Node node, int id) { if (node == null) return null; if (id > node.getContent().id) { return searchAt(node.right, id); } else if (id < node.getContent().id) { return searchAt(node.left, id); } else { return node.getContent(); } } private void printDescAt(Node node) { if (node == null) return; printDescAt(node.right); System.out.print(node.getContent().id + " "); printDescAt(node.left); } /** * Prints all elements of the tree in descending order */ public void printDesc() { printDescAt(root); System.out.println(); } public void printLevel(int level) { printLevelFrom(this.root, level - 1); System.out.println(); } private Node printLevelFrom(Node node, int level) { if (node == null) { System.out.print("❌ \t"); return null; } if (level != 0) { printLevelFrom(node.left, level - 1); printLevelFrom(node.right, level - 1); } else { System.out.print(node.getContent().id + " \t"); } return node; } // TODO: GetLevel(content) [root ist auf 1, Rückgabe "0", falls nicht vorhanden] public int getLevel(int id) { return getLevelFrom(this.root, id, 1); } private int getLevelFrom(Node node, int id, int level) { if (node == null) return -1; if (node.getContent().id == id) { return level; } if (node.left != null && node.getContent().id > id) { return getLevelFrom(node.left, id, level + 1); } return getLevelFrom(node.right, id, level + 1); } public void fromFile(String fileName) throws IOException { Reader reader = Files.newBufferedReader(Paths.get(fileName)); Gson gson = new GsonBuilder().setPrettyPrinting().create(); Content[] nodes = gson.fromJson(reader, Content[].class); for (Content node : nodes) { this.insert(node); } } public int depth() { return depthFrom(this.root, 1); } private int depthFrom(Node node, int depth) { if (node == null) return depth - 1; return Math.max(depthFrom(node.right, depth + 1), depthFrom(node.left, depth + 1)); } }
3nt3/cs-tree
Tree.java
249,591
public class BTree<T> { private TreeNode<T> head; public BTree(T head) { this.head = new TreeNode<T>(head); } public BTree(TreeNode<T> head) { this.head = head; } public void setLR(T headE, T leftE, T rightE) { TreeNode<T> h = head.get(headE); if (h == null) throw new NullPointerException("Parent node does not exist!"); TreeNode<T> lc = new TreeNode<T>(leftE); lc.setParent(h); h.setLeftChild(lc); TreeNode<T> rc = new TreeNode<T>(rightE); rc.setParent(h); h.setRightChild(rc); } public void setL(T headE, T leftE) { TreeNode<T> h = head.get(headE); if (h == null) throw new NullPointerException("Parent node does not exist!"); TreeNode<T> lc = new TreeNode<T>(leftE); lc.setParent(h); h.setLeftChild(lc); } public void setR(T headE, T rightE) { TreeNode<T> h = head.get(headE); if (h == null) throw new NullPointerException("Parent node does not exist!"); TreeNode<T> rc = new TreeNode<T>(rightE); rc.setParent(h); h.setRightChild(rc); } public void insertL(T headE, T leftE) { TreeNode<T> h = head.get(headE); if (h == null) throw new NullPointerException("Parent node does not exist!"); TreeNode<T> lc = new TreeNode<T>(leftE); TreeNode<T> plc = h.getLeftChild(); if(plc == null) throw new NullPointerException("Parent node does not have a left child!"); lc.setParent(h); lc.setLeftChild(plc); h.setLeftChild(lc); } public void insertR(T headE, T rightE) { TreeNode<T> h = head.get(headE); if (h == null) throw new NullPointerException("Parent node does not exist!"); TreeNode<T> rc = new TreeNode<T>(rightE); TreeNode<T> prc = h.getRightChild(); if(prc == null) throw new NullPointerException("Parent node does not have a left child!"); rc.setParent(h); rc.setRightChild(prc); h.setRightChild(rc); } public void deleteNode(T search) { head.deleteNode(search); } public TreeNode<T> get(T headE) { return head.get(headE); } public int size() { return head.size(); } public int depth() { return head.depth(); } public void prettyPrintTree() { BTreePrinter.printNode(head); } public void printPreOrder() { head.printPreOrder(); System.out.println(); } public void printPostOrder() { head.printPostOrder(); System.out.println(); } public void printInOrder() { head.printInOrder(); System.out.println(); } }
JoeAzar/Amorphous-Binary-Tree-Creator--Binary-Tree
BTree.java
249,593
public interface BT<T> { boolean empty(); boolean full(); boolean find(Relative rel); T retrieve(); void update(T val); boolean insert(T val, Relative rel); void deleteSub(); int depth(); }
abdulrahmanAlotaibi/assignment-3-csc212
src/BT.java
249,595
package tree; class TreeNode { int data; TreeNode leftChild; TreeNode rightChild; public TreeNode(int data) { this.data = data; } public String toString(){ return 'data'+ this.data; } } class BinarySearchTree { private TreeNode root; public BinarySearchTree() { this.root = null; } // recursive approach public TreeNode insert(TreeNode root, int value) { if (root == null) { return new TreeNode(value); } if (value <= root.data) { root.leftChild = insert(root.leftChild, value); } else { root.rightChild = insert(root.rightChild, value); } return root; } public void insert(int value) { // TreeNode node = new TreeNode(value); // if (root == null) { // root = node; // return; // } // TreeNode current = root; // while (true) { // if (value <= root.data) { // if (current.leftChild == null) { // current.leftChild = new TreeNode(value); // break; // } // current = current.leftChild; // } else { // if (current.rightChild == null) { // current.rightChild = new TreeNode(value); // break; // } // current = current.rightChild; // } // } insert(root, value); } private TreeNode find(TreeNode root, int value) { if (root == null) return null; if (root.data == value) return root; if (value < root.data) { return find(root.leftChild, value); } return find(root.rightChild, value); } public TreeNode find(int value) { return find(root, value); } private void preOrderTraversal(TreeNode root) { if (root == null) return; preOrderTraversal(root.leftChild); preOrderTraversal(root.rightChild); } public void preOrderTraversal() { preOrderTraversal(root); } private void inOrderTreaversal(TreeNode root) { if (root == null) return; inOrderTreaversal(root.leftChild, value); inOrderTreaversal(root.rightChild, value); } public void inOrderTreaversal() { inOrderTreaversal(root); } private int depth(TreeNode root, int value, int depth) { if (root == null) return -1; if (root.data == value) return depth; if (value <= root.data) { return depth(root.leftChild, value, depth + 1); } return depth(root.rightChild, value, depth + 1); } public int getHeightForNode(TreeNode root, int value) { if (root == null) return -1; if (root.data == value) return heightOfTree(root); if (value <= root.data) return getHeightForNode(root.leftChild, value); } public int heightOfTree(TreeNode root) { if (root == null) return -1; if (root.leftChild == null && root.rightChild == null) return 0; int myHeight = 1 + Math.max(height(root.leftChild), height(root.rightChild)); return myHeight; } public int getHeight() { return heightOfTree(root, 1); } private boolean isEqual(TreeNode r1, TreeNode r2) { if (r1 == null && r2 == null) return true; if (r1 == null) return false; if (r2 == null) return false; return r1.data == r2.data && isEqual(r1.leftChild, r2.leftChild) && isEqual(r1.rightChild, r2.rightChild); } }
saksham-tomer/tree
tree.java
249,596
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { boolean result; public boolean isBalanced(TreeNode root) { result = true; depth(root); return result; } public int depth(TreeNode root){ if(result == false) return -1; if(root==null) return 0; int left = depth(root.left); if(result == false) return -1; int right = depth(root.right); if(result == false) return -1; if(Math.abs(left-right)>1){result=false;return -1;} return Math.max(left,right)+1; } }
fztfztfztfzt/leetcode
110.java
249,597
class Solution { int diameter; public int diameterOfBinaryTree(TreeNode root) { diameter =0; depth(root); return diameter; } public int depth(TreeNode node){ if (node == null) return 0; int L = depth(node.left); int R = depth(node.right); diameter = Math.max(diameter , L + R); return 1 + Math.max(L , R); } }
swetaagarwal123/leetcode
543.java
249,598
public class Rope { private int leftChars; private int leftNewLines; private String value; private Rope left; private Rope right; private static final int KNOT_THRESHOLD = 10; public Rope(Rope left, Rope right) { this.leftChars = left.length(); this.leftNewLines = left.newLines(); this.left = left; this.right = right; } public Rope(String value) { if (value.length() <= KNOT_THRESHOLD) { this.leftChars = value.length(); this.leftNewLines = value.split("\n", -1).length - 1; this.value = value; } else { this.leftChars = value.length() / 2; this.left = new Rope(value.substring(0, this.leftChars)); this.right = new Rope(value.substring(this.leftChars)); this.leftNewLines = this.left.newLines(); } } public int length() { if (this.right == null) { return this.leftChars; } return this.leftChars + this.right.length(); } public int newLines() { if (this.right == null) { return this.leftNewLines; } return this.leftNewLines + this.right.newLines(); } public Rope concat(Rope other) { return new Rope(this, other); } public char get(int index) { if (this.value != null) { return this.value.charAt(index); } if (index >= this.leftChars) { return this.right.get(index - this.leftChars); } return this.left.get(index); } public int findNewLine(int lineIndex) { if (this.value != null) { int at = -1; while (lineIndex >= 0) { at = this.value.indexOf("\n", at + 1); lineIndex--; } return at; } if (lineIndex >= this.leftNewLines) { return this.leftChars + this.right.findNewLine(lineIndex - this.leftNewLines); } return this.left.findNewLine(lineIndex); } public int findLineStart(int lineIndex) { if (lineIndex == 0) { return 0; } return this.findNewLine(lineIndex - 1) + 1; } public int findLineEnd(int lineIndex) { if (lineIndex == newLines()) { return length(); } return this.findNewLine(lineIndex); } public int getLineAt(int index) { if (this.value != null) { return this.value.substring(0, index).split("\n", -1).length - 1; } if (index >= this.leftChars) { return this.leftNewLines + this.right.getLineAt(index - this.leftChars); } return this.left.getLineAt(index); } public Rope copy() { if (this.value != null) { return new Rope(this.value); } return new Rope(this.left.copy(), this.right.copy()); } public String sliceString(int start, int size) { char[] str = new char[size]; this.collateChars(str, -start); return new String(str); } public String sliceStringTo(int start, int end) { return this.sliceString(start, end - start); } public void collateChars(char[] str, int offset) { if (this.value != null) { for (int i = Math.max(0, -offset); i < Math.min(this.leftChars, str.length - offset); i++) { str[offset + i] = this.value.charAt(i); } return; } if (offset + this.leftChars > 0) { this.left.collateChars(str, offset); } if (str.length - offset > 0) { this.right.collateChars(str, offset + this.leftChars); } } public Rope sliceRope(int start, int size) { if (this.value != null) { return new Rope(this.value.substring(start, start + size)); } boolean includeLeft = start < this.leftChars; boolean includeRight = start + size > this.leftChars; if (includeLeft && includeRight) { return new Rope( this.left.sliceRope(start, this.leftChars - start), this.right.sliceRope(0, size - this.leftChars + start) ); } if (includeRight) { return this.right.sliceRope(start - this.leftChars, size); } // includeLeft return this.left.sliceRope(start, size); } public Rope sliceRopeTo(int start, int end) { return this.sliceRope(start, end - start); } public Rope insert(int index, Rope value) { return new Rope( new Rope( this.sliceRope(0, index), value ), this.sliceRope(index, this.length() - index) ); } public Rope insert(int index, String value) { return this.insert(index, new Rope(value)); } public Rope remove(int index, int size) { return new Rope( this.sliceRope(0, index), this.sliceRope(index + size, this.length() - index - size) ); } public Rope removeTo(int start, int end) { return this.remove(start, end - start); } public Rope reshape() { return new Rope(this.toString()); } public int depth() { if (this.value != null) { return 1; } if (this.right == null) { return this.left.depth() + 1; } return Math.max(this.left.depth(), this.right.depth()) + 1; } public int nodes() { if (this.value != null) { return 1; } if (this.right == null) { return this.left.nodes() + 1; } return this.left.nodes() + this.right.nodes() + 1; } public String stringRep() { if (this.value != null) { return "\"" + this.value.replace("\n", "\\n") + "\""; } return "(" + this.left.stringRep() + " <- " + this.leftChars + "," + this.leftNewLines + " -> " + this.right.stringRep() + ")"; } public String toString() { return this.sliceString(0, this.length()); } }
charliegregg/TextEditor
Rope.java